Skip to content

04 linalg shortest paths - #103

Open
eriknw wants to merge 7 commits into
python-graphblas:03-dispatchfrom
eriknw:04-linalg-shortest-paths
Open

eriknw wants to merge 7 commits into
python-graphblas:03-dispatchfrom
eriknw:04-linalg-shortest-paths

Conversation

@eriknw

@eriknw eriknw commented Dec 2, 2026

Copy link
Copy Markdown
Member

Return what NetworkX returns from the matrix-valued names, and match its answers on awkward graphs in the Floyd-Warshall, Bellman-Ford and Laplacian families. NetworkX's own algorithms do arithmetic on these results, so installing the backend used to break functions it does not implement.

  • adjacency_matrix, the Laplacians, bethe_hessian_matrix, tournament_matrix return scipy sparse arrays; modularity_matrix, directed_modularity_matrix, google_matrix, floyd_warshall_numpy return numpy arrays (floyd_warshall_numpy returns floats, with inf for unreachable pairs)
  • adjacency_matrix takes format; nodelist problems raise NetworkXError as in NetworkX
  • bethe_hessian_matrix and the Laplacians use NetworkX's degrees for self-loops, digraphs and zero-degree nodes
  • The floyd_warshall names raise NetworkXUnbounded on a negative cycle, fill inf for unreachable pairs, and give correct predecessors on undirected graphs
  • bellman_ford_path raises NetworkXNoPath/NodeNotFound as NetworkX does
  • lowest_common_ancestor refuses cyclic digraphs and the null graph; all_pairs_* names answer the empty graph
  • Integer path lengths raise OverflowError where they could pass 2**63 instead of wrapping

Stacked on #102.

Nine wrappers returned a graphblas.Matrix where NetworkX returns a
scipy sparse array (adjacency_matrix, laplacian_matrix,
normalized_laplacian_matrix, bethe_hessian_matrix, tournament_matrix)
or a numpy array (modularity_matrix, directed_modularity_matrix,
google_matrix, floyd_warshall_numpy). NetworkX's own algorithms do
arithmetic on these results (algebraic_connectivity, current-flow
betweenness, spanning-tree counts and more), so installing the backend
broke functions it does not implement. They now convert, and
floyd_warshall_numpy gives a float array with inf for unreachable
pairs, as NetworkX does.

adjacency_matrix takes NetworkX's format. The seven scipy sparse names
go through graphblas.io.to_scipy_sparse; anything else goes through
scipy's asformat as in NetworkX, since to_scipy_sparse would accept
"CSR", which NetworkX refuses, and refuse None, "dense" and "array",
which it accepts. format is newer than NetworkX 3.6, so the
backend-info generator does not count it as a parameter of ours.

The nodelist is checked as NetworkX's matrix builders check it, by one
helper and in their order: the null graph, an empty nodelist, a node
the graph does not have, a repeated node. Each gave a matrix or a bare
KeyError where NetworkX raises NetworkXError. bethe_hessian_matrix
keeps NetworkX's ZeroDivisionError for the null graph. google_matrix
and floyd_warshall_numpy follow the rules of to_numpy_array, which
NetworkX builds them with: absent nodes, then a repeated one (after
floyd_warshall_numpy's own rule that the nodelist name every node).

Five answers differed on awkward graphs:
- laplacian_matrix and normalized_laplacian_matrix of an unweighted
  DiGraph raised KeyError: 'degrees+'; NetworkX uses the out-degrees.
- bethe_hessian_matrix of Graph([(0, 0), (0, 1)]) gave
  [[0.778, -0.667], [-0.667, 0.444]] where NetworkX gives
  [[1.75, -1.5], [-1.5, 2.25]]: r counts a self-loop at both ends.
- floyd_warshall_numpy with a nodelist scrambled an undirected result,
  whose upper triangle the permutation broke.
- modularity_matrix of a graph with no edges gave zeros; NetworkX's is
  all nan (it divides by twice the edge count), also when only the
  rows the nodelist selects have no edges.
- google_matrix with a nodelist that reorders every node took the
  dangling rows from the unpermuted graph: on DiGraph([(0, 1), (1, 2)])
  with [2, 1, 0] the uniform row came last where NetworkX puts it
  first.
The three floyd_warshall names returned distances for a graph with a
negative cycle, where shortest paths mean nothing and NetworkX raises
NetworkXUnbounded("Negative cycle detected."). They now raise too, on
every supported NetworkX; NetworkX itself raises from 3.7 on and
returns its meaningless distances before that.

NetworkX tests dist[u][u] < 0. The distance matrix here holds no
diagonal, so the same question is asked in two pieces: a cycle through
two or more nodes makes some D[u][v] + D[v][u] negative, and a
one-node cycle is a negative self-loop in the graph. A zero-weight
cycle is not negative, and an acyclic negative edge is not a cycle.

floyd_warshall left unreachable pairs out of its result, so indexing
one raised KeyError where NetworkX gives inf; on Graph([(0, 1), (2,
3)]) its first row was {0: 0, 1: 1}. Every pair is now present.

The predecessor map was wrong for every undirected graph. An undirected
graph is walked on its upper triangle and the result mirrored, which is
right for distances and wrong for predecessors: the node before v on
the way from u is not the node before u on the way from v. On
path_graph(3) pred[1] was {0: 0, 2: 1} where NetworkX gives
{0: 1, 2: 1}, and nx.reconstruct_path(1, 0, pred) never returned. The
triangle shortcut is now taken only when predecessors are not wanted.
The map also left out self-loops, which NetworkX records as a node's
own predecessor; a node whose only edge was a self-loop had no row.

A graph with no edges has integer distances, so its diagonal is 0, as
in NetworkX, rather than 0.0.
NetworkX checks the graph before it computes a lowest common ancestor:
a cyclic digraph raises NetworkXError("LCA only defined on directed
acyclic graphs.") and the null graph raises
NetworkXPointlessConcept("LCA meaningless on null graphs."). Neither
was checked here. On DiGraph([(0, 1), (1, 0)]) the call raised
IndexError from the kernel; on the null graph, KeyError. An absent
node also raised KeyError where NetworkX raises NodeNotFound naming the
node; the null graph is still reported first.

is_acyclic joins the DAG kernels: Kahn's algorithm a round at a time,
peeling every node with no surviving predecessor until none is left or
none can be peeled. A self-loop is never peeled, so it counts as a
cycle. Each round is one vector-matrix product and a deep graph takes
many rounds, so the answer, which cannot change for a graph, is cached
on it.
A chunk size given in bytes becomes a number of items by dividing the
budget by the size of one item, and every caller passes
len(G) * dtype.itemsize, which is zero for a graph with no nodes. So
all_pairs_shortest_path_length and all_pairs_bellman_ford_path_length
raised ZeroDivisionError on the empty graph, directed or not, where
NetworkX returns an empty result.

normalize_chunksize now answers "one chunk" when the item size is zero
or there are no items, so a chunked name added later is covered too.
square_clustering already returned early for the empty graph.
bellman_ford_path returned [] for a target it could not reach, where
NetworkX raises NetworkXNoPath, and an absent source or target raised
NodeNotFound with the bare node as its message. Each name now answers
an absent source, an absent or unreachable target and a source that is
its own target as NetworkX does, messages included: a path or length
from a node to itself is [node] or 0, before any walk, and an absent
target is reported after the walk, so a negative cycle on it wins.

bellman_ford_path_length returned an unevaluated expression on a graph
whose weights are all one value other than 1: it scaled the length
after reading it out. bellman_ford_path raised for every graph whose
weights are all one negative value, where only an undirected edge at
the source makes a cycle. Both names let their negative cycles reach
the caller as this package's internal exception rather than
NetworkXUnbounded.

With a target, both walks checked only whether the target's length
still improved, and a walk cut short at the target never saw a
negative self-loop beyond it. NetworkX raises for any negative cycle
the walk reaches, and so do these now.

A graph with no edge between two nodes has integer lengths, as in
NetworkX, rather than 0.0.
NetworkX adds integer weights as Python integers, which never overflow.
The bellman_ford names, negative_edge_cycle and the floyd_warshall
names added them as 64-bit integers, which wrap silently at 2**63. On a
path weighing 2**61 and 2**61 + 1, where every length fits,
Bellman-Ford's next candidate wrapped and it reported a negative cycle,
and Floyd-Warshall's sum of two lengths did the same.

A length is a walk of at most n edges, and Floyd-Warshall adds two, so
these names now raise OverflowError where n times the heaviest absolute
weight reaches 2**62. The bound reads the graph's least and greatest
values, which the graph caches; declining before conversion instead
would take a Python pass over every weight. ego_graph with a `distance`
walks the same way and raises too.

Floyd-Warshall on a graph with a negative cycle went on to the end and
only then added D[u][v] + D[v][u], though past such a cycle its lengths
can double at each node, past any bound: on the complete digraph of
weight -1 they reach about -2**60 at 60 nodes. It now stops at the
first negative closed walk through the node it is processing, the
earliest the cycle shows, and raises what NetworkX raises; until then
every length is a simple path's, within the bound. A negative self-loop
is read from the graph before the loop.

Below the bound, integer weights of any type are added in 64 bits. A
graph built from an INT8 Matrix wrapped at 127, and UINT64 weights met
the INT64 lengths in floating point. floyd_warshall_numpy, whose answer
is a float array in NetworkX, adds in floating point and never raises.

The backend info gains `additional_docs`, generated like the rest, to
say when each name raises.
A node whose weights sum to zero (zero-weight edges, or 1 and -1) has
degree 0, so its 1 / sqrt(degree) was inf, and its row and column came
back as inf and nan. NetworkX takes that factor as 0, which makes the
node's row and column zero, its diagonal included. The kernel now
leaves zero degrees out of the scaling, which gives the same.
@eriknw eriknw mentioned this pull request Dec 2, 2026
@codecov

codecov Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.38695% with 31 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.98%. Comparing base (7190d7f) to head (189d557).

Additional details and impacted files
@@               Coverage Diff               @@
##           03-dispatch     #103      +/-   ##
===============================================
+ Coverage        78.22%   82.98%   +4.76%     
===============================================
  Files              123      127       +4     
  Lines             5028     5777     +749     
  Branches           788      865      +77     
===============================================
+ Hits              3933     4794     +861     
+ Misses             826      737      -89     
+ Partials           269      246      -23     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@eriknw eriknw mentioned this pull request Dec 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant