Repository navigation
Bug in floyd_warshall_tree in case of negative cycle + minor typo - #8439
gulshan-123 wants to merge 2 commits into
Conversation
|
Do we want to raise an error when the graph has a negative cycle? Doesn't that lead to shortest path being poorly defined? |
|
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 networkx/networkx/algorithms/shortest_paths/weighted.py Lines 1216 to 1226 in 7b9ce97 |
|
Making this raise for a negative cycle similar to bellman ford sounds like what we want to do. |
|
closing as this is a subpart of #8440 and discussion will be continued there. Thanks |
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):
This
KeyNotFounderror 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
networkx/networkx/algorithms/shortest_paths/dense.py
Lines 198 to 246 in 772c8dc
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.