Repository navigation
Floyd warshall: raises error if negative cycle is found - #8440
Conversation
|
I thought Bellman-Ford worked for negative edges, but not for negative cycles... |
We are raising the error in this PR (#8440 ). The previous PR (#8439 ) just has some minor changes which I found while working on this. EDIT: I have updated the description for readability and updated the docstring about raising error. |
b08d632 to
edfd221
Compare
|
This breaks backwards compatibility. Should we add a warning for a release? Edit: well given that previous reported values were wrong (we zero the diagonal), I think this is a big fix actually. I'm approving this one. I think that randomized test doesn't add much in this case so I'd just remove it. We could dedupe the diagonal check and exception raising that is done in many places. |
dschult
left a comment
There was a problem hiding this comment.
This looks good. Thanks!
I don't think we need a warning here about negative cycles now raising. They should have been raising before -- and we were ignoring them which is just wrong. So no deprecation. The raised error should hopefully be clear enough for users of old code that start getting this to realize that their previous results are suspect.
I think we should/can remove the random "consistency" tests for negative cycles. Unit-tests for the specific cases in question are better than random testing when they exist and they seem to exists here. I'm not actually sure whether random tests are appropriate for unit-testing systems like CI. But I guess in some cases we aren't as confident in the unit tests. Thats the justification for them I guess. Anyway, probably removing them here is good enough.
|
|
||
| def test_negative_cycle_consistency(): | ||
| unif = random.uniform | ||
| for random_seed in range(2): # range(20): | ||
| random.seed(random_seed) | ||
| for density in [0.1, 0.9]: # .3, .7, .9]: | ||
| for N in [1, 10, 20]: # range(1, 60 - int(30 * density)): | ||
| for max_cost in [1, 90]: # [1, 10, 40, 90]: | ||
| G = nx.binomial_graph(N, density, seed=4, directed=True) | ||
| edges = ((u, v, unif(-1, max_cost)) for u, v in G.edges) | ||
| G.add_weighted_edges_from(edges) | ||
|
|
||
| has_neg_cycle = nx.negative_edge_cycle(G) | ||
| for floyd_fn in floyd_fns: | ||
| if has_neg_cycle: | ||
| pytest.raises(nx.NetworkXUnbounded, floyd_fn, G) | ||
| else: | ||
| floyd_fn(G) # does not raise | ||
|
|
There was a problem hiding this comment.
Let's remove the randomized test here -- we've got the directly aimed tests above for negative cycles. That should be sufficient.
Same for the corresponding test in the numpy version test file.
There was a problem hiding this comment.
Thank you for the review.
I've removed the randomised tests from both test_dense.py and numpy version.
|
OK. This is ready. Any thoughts on whether this might raise an exception when it isn't actually a negative cycle but a zero-weight cycle that round-off turns negative? |
|
Another thing that I was thinking: I don't like that this API drops all the results when it raises the exception. In some cases the users might want to handle the negative cycle case themselves. For example, to handle rounding errors like the case you mentioned Dan. One easy way to fix this would be including the computed values as part of the exception. Or add a parameter that prevents the exception from being raised. |
Nice! I'm able to find a graph, where incorrect result is returned due to floating point roundoff error. Here in python: >>> 0.1 + 0.7 < 0.8
True
>>> G=nx.DiGraph()
>>> G.add_edge(0, 1, weight=0.1)
>>> G.add_edge(1, 2, weight=0.7)
>>> G.add_edge(2, 0, weight=-0.8)
>>> nx.negative_edge_cycle(G)
TrueCurrent PR: >>> nx.floyd_warshall(G)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
nx.floyd_warshall(G)
~~~~~~~~~~~~~~~~~^^^
File "/home/gulshan/Desktop/oss/networkx/networkx/utils/decorators.py", line 784, in func
return argmap._lazy_compile(__wrapper)(*args, **kwargs)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
File "<class 'networkx.utils.decorators.argmap'> compilation 16", line 3, in argmap_floyd_warshall_13
import gzip
^^^
File "/home/gulshan/Desktop/oss/networkx/networkx/utils/backends.py", line 551, in _call_if_no_backends_installed
return self.orig_func(*args, **kwargs)
~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
File "/home/gulshan/Desktop/oss/networkx/networkx/algorithms/shortest_paths/dense.py", line 466, in floyd_warshall
return floyd_warshall_predecessor_and_distance(G, weight=weight)[1]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^
File "/home/gulshan/Desktop/oss/networkx/networkx/utils/decorators.py", line 784, in func
return argmap._lazy_compile(__wrapper)(*args, **kwargs)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
File "<class 'networkx.utils.decorators.argmap'> compilation 20", line 3, in argmap_floyd_warshall_predecessor_and_distance_17
import gzip
^^^
File "/home/gulshan/Desktop/oss/networkx/networkx/utils/backends.py", line 551, in _call_if_no_backends_installed
return self.orig_func(*args, **kwargs)
~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
File "/home/gulshan/Desktop/oss/networkx/networkx/algorithms/shortest_paths/dense.py", line 352, in floyd_warshall_predecessor_and_distance
raise nx.NetworkXUnbounded("Negative cycle detected.")
networkx.exception.NetworkXUnbounded: Negative cycle detected.This graph G, even raises |
|
If we allow the user to use a weight function as one option, we could cover the floating point error case by putting instructions in the doc_string that point to our centralized doc on how to handle floating point edge weights. We can then use the example @gulshan-123 found to 1) check that it raises, and 2) check that using a weight function that does e.g. |
|
Just while using networkx/networkx/algorithms/shortest_paths/weighted.py Lines 2195 to 2201 in ebc6091 we are not adding any attribute which might be used in weight function. Thus it may throw a KeyError, if the weight function uses the attribute (which is generally the case), without any default value: >>> G = nx.DiGraph()
>>> G.add_edge(0, 1, weight=1)
>>> G.add_edge(1, 2, weight=2)
>>> def myweight(u, v, e_attr):
... return e_attr['weight']
...
>>> nx.bellman_ford_predecessor_and_distance(G, source=1, weight=myweight)
({1: [], 2: [1]}, {1: 0, 2: 2})bellman ford works but not negative_edge_cycle >>> nx.negative_edge_cycle(G, weight=myweight)
Traceback (most recent call last):
...
KeyError: 'weight'EDIT: SIDENOTE: G = nx.DiGraph()
G.add_edge(0, 1, weight=1)
G.add_edge(1, 2, weight=2)
def myweight(u, v, e_attr):
if u == 0 and v == 1:
return e_attr['weight']
else:
return None
nx.bellman_ford_predecessor_and_distance(G, source=0, weight=myweight)throws |
|
The weight function is provided by the user -- so they are responsible for errors occurring in the weight function, right? I guess you are saying that the weight function might not expect to get an edge with no edge attribute. But I think that would be clear enough to be easily fixed. Of course, we should make sure every function that uses a weight/capacity function also allows hiding the edge by having the function return It might be worth making an issue that lists what needs to be changed -- but if you can recall it all easily that is fine too if you plan to work on it. Thanks for identifying these bugs! |
Yes, agreed. Is there anything else left to be done in this PR?
I have created two issues: #8455 and #8456 to track the bugs noticed in this PR. |
dschult
left a comment
There was a problem hiding this comment.
This looks ready to go.
We've got some other issues that point out things we found here, and those will need their own PRs. But this PR implements raising an error for negative cycles found in floyd-warshall.
Thanks very much @gulshan-123 , and @amcandio for review.
In most of the shortest path algorithms, a error is raised if there is a
negative cycle. This is mostly done usingbellman fordalgorithm.But this can also be done in
floyd warshallwithout usingbellman ford.There is a negative cycle iff the output matrix contains negative diagonal (i.e distance to self is negative).
Our method:
distandpredmatrix in_init_pred_distfunction.Alternative:
We can also detect the negative cycle earlier during the relaxation (while checking
if dist_uwv >? dist_uw + dist_wv]) only: