Repository navigation
Adding the Tree Optimization in Floyd Warshall - #8361
Conversation
amcandio
left a comment
There was a problem hiding this comment.
Nice! Left some comments
dschult
left a comment
There was a problem hiding this comment.
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.
|
Hi @amcandio Thank you for the great review, I have worked upon your suggestion and pushed the new code, Now,
@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.
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 |
dschult
left a comment
There was a problem hiding this comment.
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...
Yes! It is what's being done.
@dschult , It is a great idea. Thank You, learnt a lot! @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! |
|
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
left a comment
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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! :}
cdc55f1 to
b89f213
Compare
Written the description of the algorithm
Nice!, will open a PR once these algorithms are merged (will be my first in technical writing :) ).
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. |
It was assigning dist[u][u]=0 instead of asserting, so fixed it
dschult
left a comment
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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!
|
What I changed in recent commits:
for w, pred_w in pred.items():
...since new keys might get inserted in the 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 aboveOr should I just chose the below version for w in G:
if w not in pred:
continue
for v, parent in pred_w.items(): # w to v path exist
if v == w:
continue
out_w[parent].append(v)
|
|
Hi, just a gentle ping in case this was missed. |
|
dschult
left a comment
There was a problem hiding this comment.
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.
:)
|
For sparse graph, it seems ~4x faster, for dense it seems ~3x faster. 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 graphthen and similar |
dschult
left a comment
There was a problem hiding this comment.
Looks good!
Ii approve this PR
|
Thank you @amcandio and @dschult for guiding throughout the PR some tasks I am planning to work on next:
Please give some feedback or suggestions to these :) |
|
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! |
|
Okay, Nice!, Trying on them... |
Sounds like good next steps! |
|
@amcandio, Yes you're right using your construction Thus, it is only slightly faster (~1.2x) for these graphs. |
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:
networkx/algorithms/shortest_paths/tests/test_dense.py(not added in new files in this PR)eg for the test:
I could not think of good name of the function, other than
..._tree, please suggest oneTODO: docs, adding more tests,
resolving empty dict, optimizations?