Skip to content

Adding the Tree Optimization in Floyd Warshall - #8361

Merged
amcandio merged 27 commits into
networkx:mainfrom
gulshan-123:feat/floyd-warshall-tree
Dec 14, 2025
Merged

amcandio merged 27 commits into
networkx:mainfrom
gulshan-123:feat/floyd-warshall-tree

Conversation

@gulshan-123

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

Copy link
Copy Markdown
Contributor

See Discussion: 8357

This pull request introduces an implementation of the "Tree" algorithm for all-pairs shortest paths as described in the paper.
The algorithm is designed to outperform classical Floyd–Warshall on sparse graphs by exploiting some properties in the tree structure made by the shortest path "tree".

Note:

  • I have implemented dfs array and skip array as discussed, also recursion is not needed.
  • I have tested locally with the same tests as original floyd warshall already present in networkx networkx/algorithms/shortest_paths/tests/test_dense.py (not added in new files in this PR)
    • The dist dict is generated the same and thus passes, but the pred dict also contains empty dictionaries:
      eg for the test:
        # dicts-of-defautdicts
        # make sure we don't get empty dictionary
        XG = nx.DiGraph()
        XG.add_weighted_edges_from(
            [("v", "x", 5.0), ("y", "x", 5.0), ("v", "y", 6.0), ("x", "u", 2.0)]
        )
        path, dist = nx.floyd_warshall_tree(XG)
        inf = float("inf")
        assert dist == {
            "v": {"v": 0, "x": 5.0, "y": 6.0, "u": 7.0},
            "x": {"x": 0, "u": 2.0, "v": inf, "y": inf},
            "y": {"y": 0, "x": 5.0, "v": inf, "u": 7.0},
            "u": {"u": 0, "v": inf, "x": inf, "y": inf},
        }
>       assert path == {
            "v": {"x": "v", "y": "v", "u": "x"},
            "x": {"u": "x"},
            "y": {"x": "y", "u": "x"},
        }
E         Left contains 1 more item:
E         {'u': defaultdict(<function floyd_warshall_tree.<locals>.<lambda> at 0x7eadeb267240>, {})}

I could not think of good name of the function, other than ..._tree, please suggest one


TODO: docs, adding more tests, resolving empty dict, optimizations?

@amcandio amcandio left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nice! Left some comments

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

Can you avoid all the index stuff by making the arrays be dicts keyed by node to whatever value you have in the list. Then you don't have to track indices -- you just look everything up using the node itself.

@gulshan-123

gulshan-123 commented Dec 3, 2025 •

Copy link
Copy Markdown
Contributor Author

Hi @amcandio Thank you for the great review, I have worked upon your suggestion and pushed the new code, Now,

  • I don't return defaultdict
  • empty dict test is passing (earlier default outer key was being generated just on read)
  • removed unused and redundant variable, and I hope the code is now cleaner

Can you avoid all the index stuff by making the arrays be dicts keyed by node to whatever value you have in the list. Then you don't have to track indices -- you just look everything up using the node itself.

@dschult, Thanks for the suggestion. I am not sure I fully understand how to remove the indices.

Right now I have two arrays in DFS order: dfs_array[i] is the ith node in the DFS, and skip_idx[v] is the index to jump to when I want to skip the subtree of v.
do you mean

  • construct dfs_array as a dict from the start, eg: dfs_array[node] = node_after_skipping_subtree?

I also need to be able to move forward in DFS order after a relaxation fails, jumping from a node to its “skip” node. With dicts keyed by node instead of indices, how would you recommend handling that traversal? Should I just move linearly without any operation until node_after_skipping_subtree is found? or you have some other idea?

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

Good points and questions --
I think that for this PR we should leave the parts of this function that were copied verbatim from the original function the same as they were. I left replies to that effect in some comments.

I made a couple of minor suggestions about varnames and comments/white-space.

I'd like to ramble on about the DFS part of this some more so I can understand it better and you can tell me where I'm missing something. It looks like we want to store a "dfs_node_preorder" so we can process the nodes in that order without having to recompute the children, etc. That is stored in dfs_array. Then we want some sort of "dfs_node_postorder" to tell which node to handle next whenever we skip a subtree. That is stored in skip_idx. The advantage of these extra arrays is to only do the DFS traversal once for each node "k" (formerly "w"). Then we process each "u" in G and each "v" in the order provided by the dfs preorder. This inner loop order allows us to skip many nodes when a subtree is deemed to be skipped. Is this approximately correct?

The paper says to store dfs as a list of nodes and skip as a list of indexes to jump to. The order of skip should match that of dfs in the sense that the ith element of dfs is the node from which you skip to the ith element of skip. Whenever I see the index of a list in graph algorithms I instinctively think of the list as a dict keyed by index to the associated node in the list. I do that because usually with graph algorithms the indices end up being replaceable by the nodes -- so instead of two lists each holding nodes you can use one dict keyed by node to the node corresponding to in in the other list.

TL:DR; I think two lists is a fine way to proceed. Though two dicts could work too -- see below. I think the two lists is fine.

Either way -- we should probably remove the 2-tuple on the stack by making a processed set. And maybe keeping a "seen" that we check before putting elements onto the stack. Those should make the DFS faster.

=========== more on dfs_dict skip_dict approach ==============
The first list holds information beyond aligning with the second list. Its order is the DFS-preorder. If we try to make skip point to a node instead of an index, we will have to find that node's position in dfs anyway to figure out the right order. Perhaps we could instead store the order via a dict dfs_dict keyed by node to the next element in the DFS-preorder. While skip could be a dict keyed by node to the node to skip to when we want to skip a subtree. Then the loop would be something like:

    v = k
    while v in dfs_dict:
        if <relaxation condition>:
            <process>
            v = dfs_dict[v]
        else:
            v = skip_dict[v]

Setting up dfs_dict and skip_dict would involve a refactoring of the DFS. Maybe something like:

        # pre-process k
        stack = list(out_k[k])
        seen = {k}
        seen.update(stack)
        dfs_dict = {}
        skip_dict = {}
        node = k
        while stack:
            dfs_dict[node] = stack[-1]

            node = stack.pop()
            if stack:
                skip_dict[node] = stack[-1]
            new_nbrs = [nbr for nbr in out_k[node] if nbr not in seen]
            seen.update(new_nbrs)
            stack.extend(new_nbrs)

Is this easier to read/grok/come back to in 6 months? Perhaps... but it is not clear...

@gulshan-123

gulshan-123 commented Dec 4, 2025 •

Copy link
Copy Markdown
Contributor Author

I'd like to ramble on about the DFS part of this some more so I can understand it better and you can tell me where I'm missing something. It looks like we want to store a "dfs_node_preorder" so we can process the nodes in that order without having to recompute the children, etc. That is stored in dfs_array. Then we want some sort of "dfs_node_postorder" to tell which node to handle next whenever we skip a subtree. That is stored in skip_idx. The advantage of these extra arrays is to only do the DFS traversal once for each node "k" (formerly "w"). Then we process each "u" in G and each "v" in the order provided by the dfs preorder. This inner loop order allows us to skip many nodes when a subtree is deemed to be skipped. Is this approximately correct?

Yes! It is what's being done.

The first list holds information beyond aligning with the second list. Its order is the DFS-preorder. If we try to make skip point to a node instead of an index, we will have to find that node's position in dfs anyway to figure out the right order. Perhaps we could instead store the order via a dict dfs_dict keyed by node to the next element in the DFS-preorder. While skip could be a dict keyed by node to the node to skip to when we want to skip a subtree. Then the loop would be something like:

@dschult , It is a great idea. Thank You, learnt a lot!
I have updated the implementation by removing indexing to dicts, as recommended. I also refactored the code.

@amcandio , Thank you for reviewing the code and suggesting optimizations, I have also added them in my latest commit. Please review again if more optimization can be done.


If the implementation is approved, I will then add tests and docs. (tests will be same as original floyd warshall possibly with some addition). Locally, tests are passing!

@gulshan-123

Copy link
Copy Markdown
Contributor Author

Thanks @amcandio for the nice suggestions, I have added all of them in my latest commit. The code looks cleaner and readable now! Thanks again

@amcandio amcandio left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM. The next step should be adding docs referencing the paper and adding unit tests. We should parameterize pre-existing FW tests.

It would also be great to add unit tests that generate random graphs and compare output against reference FW implementation. You can see #7954 for an example.

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

Removing seen is better -- Thanks @amcandio and @gulshan-123 !!
I'm not sure how I missed the fact that we are doing a DFS on out_k which is a tree! :)

I think my current suggestions are all very minor! About comments and preloading inf and handling the first pass through the loop setting up dfs_dict.

Onward to docs and tests! :}

@gulshan-123
gulshan-123 force-pushed the feat/floyd-warshall-tree branch from cdc55f1 to b89f213 Compare December 5, 2025 05:40
Written the description of the algorithm
@gulshan-123

Copy link
Copy Markdown
Contributor Author

Hi @amcandio and @dschult , I have included the docs. Please review once.
Do I need to explain the algorithm in more detail?
I have written |V| instead of n (which is present in the classic floyd warshall docs).

@gulshan-123

gulshan-123 commented Dec 5, 2025 •

Copy link
Copy Markdown
Contributor Author

We could add a FW, similar to what we did for Dijkstra's (https://networkx.org/documentation/stable/reference/algorithms/shortest_paths/dijkstra.html)

Nice!, will open a PR once these algorithms are merged (will be my first in technical writing :) ).

Docs look good to me.

Moving forward to add tests!, will look the reference you provided earlier for comparing classical FW and this algo outputs. And as suggested, will look how I can add parameters in existing tests.

@gulshan-123

Copy link
Copy Markdown
Contributor Author

Hi @amcandio and @dschult, I have added the tests.

  • Included pytest parametrize for tests which were already present
  • Added tests to check consistencies of both FW variants, by comparing the dist dict produced by both variants on small random graphs

All the tests are passing!

@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. I have one minor comment. And one question which is about helping me understand the algorithm better.

Thanks!

This variant implements the Tree algorithm of Brodnik, Grgurovic and Pozar.
It differs from the classical Floyd Warshall algorithm by using a shortest
path tree rooted at each intermediate vertex w. For every w, the algorithm
builds a tree OUT_w of current shortest paths and scans it in depth first

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.

side question: what does "current" refer to in "builds a tree OUT_w of current shortest paths".

I'm guessing that it means pred is still being updated. So we are building the tree using the most recent updates of shortest path predecessors. But it is more than that because every node in G, v, is appended as a child or w if v does not have an entry in pred yet. I guess I should look at the paper again. :) Is there a simple description of what "current" means here?

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.

Is there a simple description of what "current" means here?

Since FW maintains a distance matrix which gets refined at each iteration wrt w. The OUT_w tree is formed from this currently known matrix.

every node in G, v, is appended as a child of w if v does not have an entry in pred yet

Nice point, we do not need to check for relaxations for those v, added this optimization in my latest commit. Thank you!

@gulshan-123

gulshan-123 commented Dec 7, 2025 •

Copy link
Copy Markdown
Contributor Author

What I changed in recent commits:

  1. In the floyd_warshall_tree function:
    NOTE: These parts are also valid for already present floyd_warshall_predecessor_and_distance, we may handle these parts in a separate PR (in both functions at the same time), in which case, I will revert the change
  • in the outermost loop, iterate for only those w, from which some outgoing path exists, else, no relaxations can be made
    • Here I need suggestion:
      Is this safe to call?
for w, pred_w in pred.items():
    ...

since new keys might get inserted in the pred dict, when new paths are found (EDIT: actually, no new keys can be inserted in pred, as for below if condition to succeed, dist_uw must be finite, thus u must already be in pred; still need suggestion):

            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

Or should I just chose the below version

for w in G:
    if w not in pred:
        continue
  • Also, OUT_w will contain edges only if some path w to v exists, this is done by adding the below portion of code:
        for v, parent in pred_w.items():  # w to v path exist
            if v == w:
                continue
            out_w[parent].append(v)
  1. In the test file:
  • removed redundant floyd_warshall test call as it just internally calls floyd_warshall_predecessor_and_distance and return the dist dictionary
  • As @amcandio pointed we should not return defaultdict even in case of dist, a future PR may be created to do this. Currently, I noticed that assert dist1 == dist2 may be bad for defaultdicts due to missing keys, thus replaced with for u in G: for v in G: ...

@gulshan-123

Copy link
Copy Markdown
Contributor Author

Hi, just a gentle ping in case this was missed.

@amcandio amcandio left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM, thanks!

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

Just a couple of doc suggestions.

Also the file doc/reference/algorithms/shortest_paths.rst
now has a conflict with main. You can merge it or rebase it to resolve that conflict. If you want one of us to do that let us know.

@gulshan-123

Copy link
Copy Markdown
Contributor Author
  • Resolved the merge conflict by following contributing guide, Thank You!

  • Updated the docs as suggested.

  • Modified reference to Chicago Style (saw from guide)

  • Added the dispatchable decorator @nx.dispatchable.

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

Those changes look good -- one line in the reference is now over the 88 char limit (which is not enforced in doc_strings, but we like to follow it anyway). See suggestion below).

The next step I'd like to see (I think the final thing) is a very basic timing comparison between the new tree version and the original. I don't think a full benchmark in our benchmarking system is needed. Just the results from an ipython session (or jupyter) where a reasonable size graph is created, problem set up, then rune %timeit nx.floyd_warshall_tree(...) and then %timeit nx.floyd_warshall(..). It should be faster, but let's see how much. I guess you could see whether the size of the graph matters. But don't go crazy with it -- just doubling the size once or twice is usually sufficient to get an idea of how timing changes.

:)

@gulshan-123

gulshan-123 commented Dec 14, 2025 •

Copy link
Copy Markdown
Contributor Author

For sparse graph, it seems ~4x faster, for dense it seems ~3x faster.

weight range: [1.0, 10.0] uniformly distributed
n	p	original		tree			ratio
100	0.1	59.8 ms ± 10.7 ms	15.4 ms ± 218 μs	3.88
100	0.8	64.6 ms ± 16 ms		28.4 ms ± 97.4 μs	2.27
200	0.1	483 ms ± 54.4 ms	101 ms ± 1.37 ms	4.78
200	0.8	502 ms ± 56.4 ms	177 ms ± 1.4 ms		2.84
400	0.1	4.36 s ± 126 ms		1.18 s ± 139 ms		3.70
400	0.8	4.87 s ± 190 ms		1.78 s ± 89.8 ms	2.74

Code:

def make_graph(n, p, weights):
    graph = nx.erdos_renyi_graph(n, p)

    for u, v in graph.edges():
        graph[u][v]["weight"] = random.uniform(*weights)
    return graph

then G1 = make_graph(100, 0.1, [1.,10.])
then %timeit nx.floyd_warshall_predecessor_and_distance(G1)
then %timeit nx.floyd_warshall_tree(G1)

and similar

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

Looks good!
Ii approve this PR

@gulshan-123

Copy link
Copy Markdown
Contributor Author

Thank you @amcandio and @dschult for guiding throughout the PR

some tasks I am planning to work on next:

  1. Currently the Floyd warshall (FW) does not raise any warning or error when a negative cycle is present in the graph. In this case dist matrix is incorrect. we may raise a NetworkXUnbounded, similar to bellman_ford_predecessor_and_distance when a negative cycle is detected {small PR}

  2. Some small optimizations in original FW, like instead of for w in G:, we could write for w, pred_w in pred.items() as in this PR {small}

  3. Most other shortest path distance functions in NetworkX support specifying the edge weight as a callable. We may extend FW to support weight functions as well {small}

  4. As pointed in discussion, we should/may sort out the API for different versions of FW. There are already three (fw_numpy, fw_original, fw_tree, and one upcoming fw_hourglass)

  5. shortest_path_length(G, source=None, target=None, weight=None, method="dijkstra") etc do not currently support method="floyd_warshall". We may add support for this too {may be large}

  6. Implement the second algo from same paper: Hourglass algorithm {large}

  7. Adding reference documentation for FW, similar to existing dijkstra ref.

Please give some feedback or suggestions to these :)
Thanks again!

@amcandio

Copy link
Copy Markdown
Contributor

Nice! Be careful with those random graphs though. They tend to be disconnected and their shortest paths be of only a few hops (exactly taylored for the skip infinity optimization).

I recently added a Dijkstra worst case graph that requires a bunch of relaxations. You might want to try using that one too!

@gulshan-123

Copy link
Copy Markdown
Contributor Author

Okay, Nice!, Trying on them...

@amcandio

Copy link
Copy Markdown
Contributor

Thank you @amcandio and @dschult for guiding throughout the PR

some tasks I am planning to work on next:

  1. Currently the Floyd warshall (FW) does not raise any warning or error when a negative cycle is present in the graph. In this case dist matrix is incorrect. we may raise a NetworkXUnbounded, similar to bellman_ford_predecessor_and_distance when a negative cycle is detected {small PR}

  2. Some small optimizations in original FW, like instead of for w in G:, we could write for w, pred_w in pred.items() as in this PR {small}

  3. Most other shortest path distance functions in NetworkX support specifying the edge weight as a callable. We may extend FW to support weight functions as well {small}

  4. As pointed in discussion, we should/may sort out the API for different versions of FW. There are already three (fw_numpy, fw_original, fw_tree, and one upcoming fw_hourglass)

  5. shortest_path_length(G, source=None, target=None, weight=None, method="dijkstra") etc do not currently support method="floyd_warshall". We may add support for this too {may be large}

  6. Implement the second algo from same paper: Hourglass algorithm {large}

  7. Adding reference documentation for FW, similar to existing dijkstra ref.

Please give some feedback or suggestions to these :)
Thanks again!

Sounds like good next steps!

@amcandio
amcandio merged commit 0d3fe6a into networkx:main Dec 14, 2025
@dschult dschult added this to the 3.6 milestone Dec 14, 2025
@gulshan-123

Copy link
Copy Markdown
Contributor Author

@amcandio, Yes you're right

using your construction dijkstra_relaxation_worst_case(n),

n          original                         tree                            ratio (original/tree)
100      66.6 ms ± 1.93           54.8 ms ± 359 μs      1.22
200      515 ms ± 3.26 ms     436 ms ± 2.53 ms      1.18
400      5.62 s ± 147 ms         4.55 s ± 19.4 ms        1.24

Thus, it is only slightly faster (~1.2x) for these graphs.

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