Skip to content

Floyd warshall: raises error if negative cycle is found - #8440

Merged
dschult merged 11 commits into
networkx:mainfrom
gulshan-123:fw/warn-neg-cycle
Jan 17, 2026
Merged

dschult merged 11 commits into
networkx:mainfrom
gulshan-123:fw/warn-neg-cycle

Conversation

@gulshan-123

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

Copy link
Copy Markdown
Contributor

In most of the shortest path algorithms, a error is raised if there is a negative cycle. This is mostly done using bellman ford algorithm.
But this can also be done in floyd warshall without using bellman ford.

There is a negative cycle iff the output matrix contains negative diagonal (i.e distance to self is negative).

Our method:

  • I have added a check for negative self loop during initialization of dist and pred matrix in _init_pred_dist function.
  • We will check in the resultant output matrix, if there is a negative diagonal, then negative cycle is present

Alternative:
We can also detect the negative cycle earlier during the relaxation (while checking if dist_uwv >? dist_uw + dist_wv]) only:

  • if some of the relaxation makes diagonal negative. Then there is a negative cycle.
  • It is generally preferred when numerical overflow can happen
  • In this paper, section 2, it is shown that absolute edge weight can grow exponentially in each iteration, thus there is a chance of numerical overflow
  • but I think this is not an issue in python

@dschult

dschult commented Jan 1, 2026

Copy link
Copy Markdown
Member

I thought Bellman-Ford worked for negative edges, but not for negative cycles...
The whole idea of shortest_path kind of blows up when there are negative cycles. Right?

@gulshan-123

gulshan-123 commented Jan 3, 2026 •

Copy link
Copy Markdown
Contributor Author

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.

Originally posted by @dschult in #8439 (comment)

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.
Since, Changes from that PR are already present in this PR, we should close the previous PR. Sorry for any confusion.

EDIT: I have updated the description for readability and updated the docstring about raising error.

@gulshan-123
gulshan-123 marked this pull request as ready for review January 3, 2026 07:02
@amcandio

amcandio commented Jan 3, 2026 •

Copy link
Copy Markdown
Contributor

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 dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +281 to +299

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the review.
I've removed the randomised tests from both test_dense.py and numpy version.

@dschult

dschult commented Jan 4, 2026

Copy link
Copy Markdown
Member

OK. This is ready.
But I had a late night worry about whether it would trigger an exception due to floating point round-off error.

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?

@amcandio

amcandio commented Jan 4, 2026 •

Copy link
Copy Markdown
Contributor

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.

@gulshan-123

gulshan-123 commented Jan 6, 2026 •

Copy link
Copy Markdown
Contributor Author

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?

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.79.. < 0.8

>>> 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)
True

Current 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 NetworkXUnbounded in case of other algorithms including:
nx.goldberg_radzik(G,source=0)
nx.bellman_ford_predecessor_and_distance(G, source=0)

@dschult

dschult commented Jan 6, 2026

Copy link
Copy Markdown
Member

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. round(wt * 1e6) gives a correct result.

@gulshan-123

gulshan-123 commented Jan 7, 2026 •

Copy link
Copy Markdown
Contributor Author

Just while using weight as function in negative_edge_cycle, I came to find that weight function is not supported in negative_edge_cycle as the user may want.
it is because, since we are adding a new node and edges from the new node to all existing nodes L-2201,

# find unused node to use temporarily
newnode = -1
while newnode in G:
newnode -= 1
# connect it to all nodes
G.add_edges_from([(newnode, n) for n in G])

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:
This is mentioned in docstring about the new node:

    This algorithm uses bellman_ford_predecessor_and_distance() but finds
    negative cycles on any component by first adding a new node connected to
    every node, and starting bellman_ford_predecessor_and_distance on that
    node.  It then removes that extra node.

SIDENOTE:
Hiding an edge by returning None is not supported in bellman_ford algorithms (although there is nothing written about returning None to hide edge in bellman ford docstring, user might use it, as supported in most of the algorithms like dijkstra):

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 TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

@dschult

dschult commented Jan 8, 2026

Copy link
Copy Markdown
Member

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 None.

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!

@gulshan-123

Copy link
Copy Markdown
Contributor Author

But I think that would be clear enough to be easily fixed.

Yes, agreed.

Is there anything else left to be done in this PR?

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!

I have created two issues: #8455 and #8456 to track the bugs noticed in this PR.
Thank You

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@dschult
dschult merged commit d46d572 into networkx:main Jan 17, 2026
@dschult dschult added this to the 3.7 milestone Jan 17, 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.

3 participants