Skip to content

Bug in floyd_warshall_tree in case of negative cycle + minor typo - #8439

Closed
gulshan-123 wants to merge 2 commits into
networkx:mainfrom
gulshan-123:NoneAccess+typo
Closed

gulshan-123 wants to merge 2 commits into
networkx:mainfrom
gulshan-123:NoneAccess+typo

Conversation

@gulshan-123

@gulshan-123 gulshan-123 commented Dec 31, 2025 •

Copy link
Copy Markdown
Contributor

I was adding feature to raise warning if negative cycle is found in floyd warshall algorithm. (I have opened a draft PR #8440 ).

The current floyd_warshall_tree raises KeyNotFound error on some graphs. Thus I have cherry-picked those fixes and opened this PR earlier.

A simple graph to check the KeyError (added in the test of #8440):

        G = nx.cycle_graph(5)  # undirected Graph
        G.add_edge(1, 2, weight=-3)
        nx.floyd_warshall_tree(G)
                dist_u = dist[u]
                dist_uw = dist_u[w]
                if dist_uw == inf:  # small optimization
                    continue
    
                # note: we skip v=w as relaxation would always fail
>               v = dfs_dict[w]
                    ^^^^^^^^^^^
E               KeyError: 4

This KeyNotFound error can only happen in case of graphs having negative cycle, and thus was not detected earlier, (since we were working with positive weights).

proof:

Details

pred, dist = _init_pred_dist(G, weight)
# dont check for those w, `from` which `no` path exists
for w, pred_w in pred.items():
# out_w will store the adjacency list of the OUT_W tree of the paper,
# it is a tree, parent --> list of children
out_w = {parent: [] for parent in G}
for v, parent in pred_w.items(): # w to v path exist
if v == w:
continue
out_w[parent].append(v)
# dfs order dict and skip dict in practical improvements in the paper
stack = [w]
dfs_dict = {} # {node: next node in dfs order}
skip_dict = {} # {node: next node after subtree is skipped}
node = None
while stack:
next_node = stack.pop()
dfs_dict[node] = next_node
if stack:
skip_dict[next_node] = stack[-1]
stack.extend(out_w[next_node])
node = next_node
dist_w = dist[w] # for speed
# main inner loop starts here
for u in G:
if u == w: # small optimization
continue
dist_u = dist[u]
dist_uw = dist_u[w]
if dist_uw == inf: # small optimization
continue
# note: we skip v=w as relaxation would always fail
v = dfs_dict[w]
while v is not None:
dist_uwv = dist_uw + dist_w[v]
if dist_u[v] > dist_uwv:
dist_u[v] = dist_uwv
# update/new entries to be created in pred[u]
pred[u][v] = pred_w[v] # v must be in pred_w as checked above
v = dfs_dict.get(v, None)
else:
v = skip_dict.get(v, None)
return dict(pred), dict(dist)

Keyerror can only happen if w has no children in OUT_w. L235
Consider graph G with no neg cycle.
w must be a key in pred. This means w has at least one outgoing edge. L200-L201. Thus there exists at least one neighbor n reachable from w
Consider the shortest path from w to any reachable node u. This path must start with some edge (w, x)
If w-x - ... - u is a shortest path, then the sub path w-x must be a shortest path from w to x. (If there were a shorter way to reach x, the total path to u would be shorter via that way).

Therefore, there exists at least one neighbor x such that the direct edge (w, x) is the shortest path to x
For this neighbor x: pred[w][x] == w
Thus, w has atleast one child x in OUT_w.

This may be not true in negative cycle graph for the neighbour x, because the path from w can enter this cycle, making pred pointer not w, even if path starts from w-x.

w-x---negative cycle---x


I am thinking to add test in the PR implementing negative cycle Error.

@dschult

dschult commented Jan 1, 2026

Copy link
Copy Markdown
Member

Do we want to raise an error when the graph has a negative cycle? Doesn't that lead to shortest path being poorly defined?

@gulshan-123

gulshan-123 commented Jan 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Yes, that will make to have shortest path to be unbounded towards minus infinity, and thus poorly defined.

This is to make floyd warshall similar to bellman_ford algorithms, (which too cannot work in case of negative cycle).
Currently, we raise NetworkXUnbounded in bellman_ford if any negative cycle is found.

Raises
------
NodeNotFound
If `source` is not in `G`.
NetworkXUnbounded
If the (di)graph contains a negative (di)cycle, the
algorithm raises an exception to indicate the presence of the
negative (di)cycle. Note: any negative weight edge in an
undirected graph is a negative cycle.

@dschult

dschult commented Jan 2, 2026

Copy link
Copy Markdown
Member

Making this raise for a negative cycle similar to bellman ford sounds like what we want to do.
Thanks.
Are we doing that in this PR? There isn't any check or raising. But maybe it gets done implicitly.
Do we test for this case? If not, we should add such a test in this PR.

@gulshan-123

Copy link
Copy Markdown
Contributor Author

closing as this is a subpart of #8440 and discussion will be continued there. Thanks

@gulshan-123 gulshan-123 closed this Jan 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

2 participants