Skip to content

34 nan, infinite and negative weights - #132

Open
eriknw wants to merge 1 commit into
python-graphblas:32-float-path-lengthsfrom
eriknw:34-nan-weights
Open

eriknw wants to merge 1 commit into
python-graphblas:32-float-path-lengthsfrom
eriknw:34-nan-weights

Conversation

@eriknw

@eriknw eriknw commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

This makes the shortest-path names give NetworkX's answers when edge weights are NaN or infinite, or negative on the names NetworkX backs with Dijkstra, or leave the call to NetworkX. NetworkX's Bellman-Ford relaxes an edge only where the length through it is less than the length its head has, or less than inf for a head not yet reached. Through a NaN or +inf weight that is never true, so such an edge reaches nothing. On the directed path 0-1-2-3-4 with weights 1, NaN, 2 and 1.5, plus an edge 0-4 of weight 10, NetworkX's single_source_bellman_ford_path_length from 0 gives {0: 0, 1: 1.0, 4: 10.0}. The backend added the NaN like any other weight and also gave nodes 2 and 3 a NaN length.

  • The Bellman-Ford names now drop the edges whose weight is NaN or +inf before they walk: single_source_bellman_ford_path_length, bellman_ford_path_length, bellman_ford_path, all_pairs_bellman_ford_path_length and negative_edge_cycle. This is exact, because NetworkX never relaxes those edges, so the reached nodes, lengths and paths are now NetworkX's. The graph without them is cached on the conversion. A graph with no such weight is walked as before, and the check reads its values once per conversion.
  • With a NaN or a negative weight, the names NetworkX answers with Dijkstra go to NetworkX: eccentricity, diameter, radius, center, periphery, harmonic_diameter, closeness_centrality, harmonic_centrality, the Wiener, Schultz, Gutman and hyper-Wiener indices, average_shortest_path_length (method None or "dijkstra"), and ego_graph with a distance. There a NaN length compares false with every other length, so the answer follows the order NetworkX pops its heap. On the path 0-1-2-3 with weights 1, NaN and 1, plus an edge 0-3 of weight 10, NetworkX gives node 1 an eccentricity of 11.0. With the same edges added in another order it gives 1.0. The backend gave 11.0 to every node. A +inf weight is still served, since Dijkstra adds it like any other weight and the answers match.
  • A negative weight is left to NetworkX because its Dijkstra takes no weight to be negative: whether it raises "Contradictory paths found", and the lengths it gives when it does not, follow the order it pops its heap. The backend gave Bellman-Ford's lengths, so it answered calls that fail in NetworkX. On the directed edges 0-1 (2), 1-2 (-3), 0-2 (1), 2-3 (1) and 3-0 (5), NetworkX's wiener_index and eccentricity raise that error, where the backend answered 30 and {0: 2, 1: 3, 2: 8, 3: 7}. The check reads two facts cached on the conversion, so a repeated call costs nothing more. The Bellman-Ford names, and average_shortest_path_length with method="bellman-ford", still serve negative weights.
  • With a -inf weight, the Bellman-Ford names go to NetworkX too. No length can fall below -inf, so the backend's negative-cycle check, which looks for lengths still falling after n - 1 rounds, misses cycles that NetworkX finds.
  • So does a self-loop of an undirected graph that may weigh -inf. The conversion adds a loop's weight in twice and takes it out once, so a loop of weight -inf or +inf holds NaN, as a NaN loop does; such a NaN now counts as -inf. With a -inf loop NetworkX gives -inf lengths or raises for a negative cycle, by the order it walks (from the loop's node it gave -inf for every node of a graph with a negative undirected edge; from a neighbor it raised); here the loop was dropped as NaN, so the answer was the graph's without it. Undirected loops of NaN or +inf go to NetworkX with it, as the conversion cannot tell them apart; directed loops keep their weights and are served as before.
  • So do float weights so heavy that a sum of them may pass the largest float, which makes it inf or -inf. At -inf the lengths stop falling before the negative-cycle check runs. On an undirected graph with an edge of -1e308, negative_edge_cycle gave False where NetworkX gives True, and bellman_ford_path could run without end: the parents of two nodes pointed at each other, and the walk back from the target grew its list until memory ran out. At inf, NetworkX relaxes no edge and leaves the node unreached, where the backend gave it a length: on the directed path 0-1-2 with weights 1e308 and 1e308, NetworkX's bellman_ford_path(G, 0, 2) raises NetworkXNoPath and the backend returned [0, 1, 2]. These names, and average_shortest_path_length with method="bellman-ford", now go to NetworkX where n * n times the heaviest finite weight, doubled, reaches the largest float. (n - 1) times the heaviest weight bounds only a simple path. Where there is a negative cycle, NetworkX keeps walking around it until its heuristic or its count stops it, and it queues each node fewer than n times, so a length it adds has at most n * n - n + 1 edges, or n * n + n + 1 in negative_edge_cycle, which adds a node with an edge of weight 1 to every other. On 2254 random graphs of 3 to 12 nodes with a negative cycle, NetworkX added walks of up to 7.6 n edges (91 on 12 nodes) with the heuristic off and 4.5 n with it on, past n - 1 in 817 of 18786 single-source calls, and never past n * n. If such a sum reaches -inf before NetworkX finds the cycle, whether it then raises or gives -inf lengths follows the order it walks, so the bound has to hold for NetworkX's longest walk, not only for this backend's n edges. Doubling covers rounding, and the added node of negative_edge_cycle. The walk back along the parents now also stops, with RuntimeError, once it is longer than the nodes it can visit. The check reads the weights once per conversion.
  • So do float weights with a negative one that lie so far apart that a sum may lose one. A sum loses a weight under half a unit in its last place: 1e300 - 1 is 1e300. On the directed graph 0-1 of weight 1e300 with a loop of -1 at 1, NetworkX's single_source_bellman_ford_path_length from 0 never shortens the length of 1 by the loop and gives {0: 0, 1: 1e300}, where the backend read the loop as a negative cycle and raised NetworkXUnbounded. These names, average_shortest_path_length with method="bellman-ford" and the Floyd-Warshall names now go to NetworkX where the bound above, n * n times the heaviest finite weight, doubled, reaches 253 times the lightest nonzero one: no sum below the bound loses a weight that size. The ratio of the weights alone is not enough: after three edges of 252 a loop of -1 is lost too, as 3 * 252 - 1 rounds back to 3 * 252, though no weight is 253 times another. Without a negative weight a lost one moves a length only by rounding and makes no cycle negative, so such weights are still served: random weights spread from 1e-3 to 1e6 were never declined, on 10 to 10000 nodes; with a tenth of them negative they were declined from 3000 nodes (the bound passes 253 times 1e-3 at about 2100 nodes) and served up to 2000. A review found the same rule declines weights in [-1, 1] with some negative from about 1e5 nodes, and weights whose largest is 1e9 times the lightest from about 1e4. The lightest weight is read once per conversion, and only where a weight is negative. On 541 small graphs built to lose a weight (paths of 2**50 to 1e300 ending in a negative loop or cycle, and random mixes of such weights), the backend's answers differed from NetworkX's in 153 of 4869 calls before, all Bellman-Ford's, and in none after, in NetworkX dev and 3.7. In 3.6.1 the 111 left are Floyd-Warshall on a negative cycle, which 3.6.1 answers and 3.7 raises for, as the backend does.
  • A negative weight off the diagonal no longer counts as a negative self-loop. The cache took a missing off-diagonal minimum to be 0, so once a name had read the sign of the weights (the Dijkstra names' check does), the backend's negative_edge_cycle said True for a graph with a self-loop of 2.0, a -1.0 edge and no negative cycle, on NetworkX's cached conversion. This was so before this change too. This fix has been needed since 2023; it is in this change rather than a separate one so the stack carries one rule for the cached signs.
  • The Floyd-Warshall names (floyd_warshall, floyd_warshall_predecessor_and_distance, floyd_warshall_numpy) go to NetworkX for a NaN or infinite weight. NetworkX keeps NaN entries, and it gives a predecessor to an edge of weight inf but to no walk through one. Its NumPy version adds -inf to the inf of a missing edge and so fills NaN. They also go to NetworkX by the bound above for sums that may pass the largest float: on the path 0-1-2 with weights 1e308 and 1e308, NetworkX's floyd_warshall_predecessor_and_distance gives the pair (0, 2) no predecessor, as its sum is inf, where the backend gave one. On 208 graphs with such weights, that name differed from NetworkX's in 5 before and none after, in NetworkX dev and 3.7.
  • average_shortest_path_length with method="bellman-ford" goes to NetworkX for a NaN or infinite weight. NetworkX's sum skips the pairs those edges leave unconnected, but its check for a graph in pieces still counts the edges.
  • all_pairs_bellman_ford_path_length now checks its weights when it is called, not at the first item, so a declined call goes to NetworkX while NetworkX's dispatcher is still handling the call.
  • Each rule is documented in the backend notes that NetworkX shows for these names.
  • all_pairs_dijkstra_path_length (30 dijkstra #133) leaves NaN and negative weights to NetworkX in the same way.
  • Other names whose answers still differ from NetworkX with NaN or infinite weights are left for a separate change: clustering, average_clustering, modularity_matrix, directed_modularity_matrix, google_matrix, normalized_laplacian_matrix, and pagerank with an infinite weight.

Stacked on #129.

NetworkX's Bellman-Ford relaxes an edge only where the length through
it is less than the length its head has, which through a NaN or +inf
weight it never is, so such an edge reaches nothing. Here it was summed,
and every node past it got a NaN or inf length. The Bellman-Ford names
now drop those edges. They, and the average length by Bellman-Ford,
still serve negative weights.

NetworkX's Dijkstra, behind eccentricity and its kin, closeness,
harmonic, the Wiener indices, ego_graph with a distance and the average
length by Dijkstra, meets a NaN in the order it pops its heap, and it
takes no weight to be negative: given one, whether it raises
"Contradictory paths found", and the lengths it gives when it does not,
follow that order too. Those names gave Bellman-Ford's lengths for a
negative weight, so a call that fails in NetworkX was answered. They
now leave NaN and negative weights to NetworkX, by facts cached on the
conversion, and the handlers that gave a negative cycle NetworkX's
Dijkstra error are removed, as nothing reaches them. Floyd-Warshall
keeps NaN entries, so its calls with a NaN go to NetworkX too, as does
any call here with a -inf weight, where the check for a negative cycle
misses cycles NetworkX finds.

On an undirected graph the conversion adds a self-loop's weight in
twice and takes it out once, so a loop of -inf or +inf holds NaN, as a
NaN loop does. Such a NaN on the diagonal counts as -inf there, and
the call goes to NetworkX.

Float weights so heavy that a sum may pass the largest float go to
NetworkX too: at -inf the lengths stop falling before the check for a
negative cycle, and the walk back along the parents could run without
end; at inf a node NetworkX leaves unreached got a length. The walk
now stops after as many steps as there are nodes.

A negative weight off the diagonal no longer counts as a negative
self-loop, as it did once the sign of the weights was cached.

The Floyd-Warshall names take the same bound, and where a weight is
negative, the Bellman-Ford and Floyd-Warshall names also go to
NetworkX when that bound reaches 2**53 times the lightest nonzero
weight, as a sum that large can lose a weight and with it a negative
cycle that NetworkX's rounding hides.
@codecov

codecov Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.26027% with 16 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.28%. Comparing base (28445c9) to head (f9c1c17).

Additional details and impacted files
@@                    Coverage Diff                    @@
##           32-float-path-lengths     #132      +/-   ##
=========================================================
+ Coverage                  92.93%   93.28%   +0.35%     
=========================================================
  Files                        182      183       +1     
  Lines                      11276    11795     +519     
  Branches                    1275     1339      +64     
=========================================================
+ Hits                       10479    11003     +524     
+ Misses                       545      544       -1     
+ Partials                     252      248       -4     
🚀 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
@eriknw
eriknw force-pushed the 32-float-path-lengths branch from faf0d71 to 28445c9 Compare December 2, 2026 20:40
@eriknw eriknw mentioned this pull request Dec 2, 2026
@eriknw eriknw changed the title 34 nan weights 34 nan, infinite and negative weights Dec 2, 2026
This was referenced Dec 3, 2026
@eriknw
eriknw force-pushed the 34-nan-weights branch 3 times, most recently from f4faf1b to f9c1c17 Compare December 3, 2026 08:59
@eriknw eriknw mentioned this pull request Dec 4, 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