Skip to content

Optimizing Dijkstra's path construction for all targets case - #8218

Merged
dschult merged 5 commits into
networkx:mainfrom
amcandio:dijkstra_path_construction
Sep 15, 2025
Merged

dschult merged 5 commits into
networkx:mainfrom
amcandio:dijkstra_path_construction

Conversation

@amcandio

@amcandio amcandio commented Sep 1, 2025 •

Copy link
Copy Markdown
Contributor

Same approach of #8023, now for all target case, result from benchmark of #8059.

We can see noticeable improvements for adversarial graphs at the expense of extra overhead on small and "simple" graphs.

Results:

Change Before [069be4c] <weighted_benchmarks2~1> After [3438a8a2] <weighted_benchmarks> Ratio Benchmark (Parameter)
- 30.0±0.9μs 27.0±0.05μs 0.90 benchmark_algorithms.WeightedGraphBenchmark.time_shortest_path_source('dijkstra_relaxation_worst_case(10)')
- 3.93±0ms 3.37±0.04ms 0.86 benchmark_algorithms.WeightedGraphBenchmark.time_shortest_path_source('dijkstra_relaxation_worst_case(100)')
- 1.11±0.08s 758±20ms 0.69 benchmark_algorithms.WeightedGraphBenchmark.time_shortest_path_source('dijkstra_relaxation_worst_case(1000)')
6.97±0.02μs 7.43±0.08μs 1.07 benchmark_algorithms.WeightedGraphBenchmark.time_shortest_path_source('weighted_graph(42, gnp_random_graph, 10, 0.1, seed=42)')
12.0±0.03μs 12.2±0.2μs 1.02 benchmark_algorithms.WeightedGraphBenchmark.time_shortest_path_source('weighted_graph(42, gnp_random_graph, 10, 0.5, seed=42)')
17.9±0.02μs 17.6±0.4μs 0.98 benchmark_algorithms.WeightedGraphBenchmark.time_shortest_path_source('weighted_graph(42, gnp_random_graph, 10, 0.9, seed=42)')
200±0.5μs 193±0.8μs 0.96 benchmark_algorithms.WeightedGraphBenchmark.time_shortest_path_source('weighted_graph(42, gnp_random_graph, 100, 0.1, seed=42)')
- 740±20μs 672±10μs 0.91 benchmark_algorithms.WeightedGraphBenchmark.time_shortest_path_source('weighted_graph(42, gnp_random_graph, 100, 0.5, seed=42)')
1.18±0ms 1.12±0.02ms 0.95 benchmark_algorithms.WeightedGraphBenchmark.time_shortest_path_source('weighted_graph(42, gnp_random_graph, 100, 0.9, seed=42)')
16.5±0.3ms 16.2±2ms 0.98 benchmark_algorithms.WeightedGraphBenchmark.time_shortest_path_source('weighted_graph(42, gnp_random_graph, 1000, 0.1, seed=42)')
118±3ms 96.5±0.9ms ~0.82 benchmark_algorithms.WeightedGraphBenchmark.time_shortest_path_source('weighted_graph(42, gnp_random_graph, 1000, 0.5, seed=42)')
211±10ms 212±10ms 1.00 benchmark_algorithms.WeightedGraphBenchmark.time_shortest_path_source('weighted_graph(42, gnp_random_graph, 1000, 0.9, seed=42)')
62.7±0.7μs 66.7±1μs 1.06 benchmark_algorithms.WeightedGraphBenchmark.time_shortest_path_source('weighted_graph(42, path_graph, 100)')
1.22±0.02ms 1.26±0.01ms 1.03 benchmark_algorithms.WeightedGraphBenchmark.time_shortest_path_source('weighted_graph(42, path_graph, 1000)')
145±4ms 136±4ms 0.94 benchmark_algorithms.WeightedGraphBenchmark.time_shortest_path_source('weighted_graph(42, path_graph, 10000)')
603±80ms 528±5ms ~0.88 benchmark_algorithms.WeightedGraphBenchmark.time_shortest_path_source('weighted_graph(42, path_graph, 20000)')

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

Interesting! How common are these adversarial/worst-case graphs in practice?

Comment on lines +889 to +892
for v in dist:
pred_v = pred_dict.get(v)
if pred_v is not None:
paths[v] = paths[pred_v[0]] + [v]

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.

Untested, but would this be slower/faster?

Suggested change
for v in dist:
pred_v = pred_dict.get(v)
if pred_v is not None:
paths[v] = paths[pred_v[0]] + [v]
for v in dist.keys() & pred_dict.keys():
paths[v] = paths[pred_dict[v][0]] + [v]

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.

The problem is that & returns a set, which does not follow insertion order. Recursion depends on the insertion order of the dist dictionary.

I forgot to add a comment clarifying the use of the trick!

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.

@fei0319 iirc you gave me that idea for the implementation trick. Feel free to send the comment suggestion so you show up as co-author 🙂

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.

You can add the co-author text to any commit message. The format is a little tricky to get right (so github parses it correctly and gives credit), so suggestions are a good way too.

For this case, what about:

    for v in dist:
        if v not in pred_dict:
            continue
        paths[v] = paths[pred_dict[v][0]] + [v]

Or can we rely on the fact that v is in dist, so it is also in pred_dict. Then the last line is all that's needed in the loop?

@amcandio amcandio Sep 6, 2025 •

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.

The sources are not in pred dict (do we have a bug with 0 weights here?). I think the more robust approach would be to skip the sources here. I can skip the first len(sources) elements in dist.

I should probably avoid calling len in case any user is passing an iterable without len

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.

You could use something like number_of_sources = len(seen) before the while loop.

I think the zero-weight case needs to be updated on line 875 from pred[u] to pred_dict[u].
Probably good to add a test that triggers that as well, but could be a separate PR.

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.

Good idea, Dan! seen works perfectly because it drops duplicates. I sent a new revision with the number_of_sources skip using itertools.islice. I also unified the use of pred and pred_dict.

I don't think there was a bug with pred and pred_dict because if pred is not None, then pred is pred_dict. But code is simpler if we always access pred_dict when updating the dict. However, it is important that we keep the checks if pred is not None because they mean that caller wants all predecesors.

@amcandio

amcandio commented Sep 3, 2025 •

Copy link
Copy Markdown
Contributor Author

Interesting! How common are these adversarial/worst-case graphs in practice?

Really hard to answer, it really depends on the use case!

For a graph to benefit from this optimization it needs to have the shortest paths that are not the shortest in terms of hops. Computer networks can have this property due to routing policies, for example the direct link might have very little bandwidth so its metric is artificially increased to divert traffic from it.

For the graphs where that is not the case, we pay some extra overhead coming from having to re-iterate the distances dictionary. This seems to be in the order of microseconds.

The main advantage I see on the change is that it reduces algo complexity. Right now running time increases cubically as we increase n. This change makes it quadratical.

It is particularly noticeable as we increase n (I did some experiments with n=10_000 and it was 4x faster but I need to double check that).

@dschult

dschult commented Sep 3, 2025

Copy link
Copy Markdown
Member

Where does the cubic complexity come from, and how did we avoid it?

@amcandio

amcandio commented Sep 4, 2025 •

Copy link
Copy Markdown
Contributor Author

The current complexity comes from creating a new path on each relaxation. On this worst-case graph, each node is relaxed O(n) times, where each path is O(n), so that gives us n^3.

More especifically, each node k is relaxed k-1 times, which triggers the computation of a new path. That path starts gets one hop longer on each relaxation, so that node gets to construct paths of length 1, 2, ..., k. Since constructing a path of lenght k is O(k), constructing all those paths gives you O(k(k-1)/2) which is O(k^2).

This happens for each node k, going from k=1 to k=n. So this gives us a complexity of O(1+2^2+3^2+...+n^2) = O(n*(n+1)*(2*n+1)/6) ~= O(n^3).

(My numbers probably have some +-1 bugs, but it shouldn't change complexity results 😄)

This is clearer when adding a log line on each relaxation:

...
paths_dict[u] = paths_dict[v] + [u]
print(f"Best path to {u} is now {paths_dict[u]}")
...

Then if we run:

>>> def dijkstra_relaxation_worst_case(n):
        for i in range(n):
            for j in range(i + 1, n):
                G.add_edge(i, j, weight=2 * (j - 1 - i) + 1)
        return G

>>> G = dijkstra_relaxation_worst_case(5)
>>> nx.shortest_path(G, 0, weight='weight')
Best path to 1 is now [0, 1]
Best path to 2 is now [0, 2]
Best path to 3 is now [0, 3]
Best path to 4 is now [0, 4]
Best path to 2 is now [0, 1, 2]
Best path to 3 is now [0, 1, 3]
Best path to 4 is now [0, 1, 4]
Best path to 3 is now [0, 1, 2, 3]
Best path to 4 is now [0, 1, 2, 4]
Best path to 4 is now [0, 1, 2, 3, 4]

We can see there how we are computing and then dropping paths for each node. Node 1 constructs one path, node 2 constructs 2 and so on.

How did we avoid it? By updating predecesors on each relaxation (which is O(1)) and constructing the path only once (at the end).

With the current implementation, each path is constructed once per destination based on the path of the predecesor. This means that we pay O(k) for constructing the path with target k. That 1+2+...+k gives you the O(n^2) and path construction is not cubical anymore.

@amcandio amcandio changed the title Optimizing path construction for all targets case Optimizing Dijkstra's path construction for all targets case Sep 4, 2025
@amcandio

amcandio commented Sep 7, 2025

Copy link
Copy Markdown
Contributor Author

Implementation is pretty compact at this point. We can try moving the path construction after visiting each v (when we set dist). This would make algo work with only one pass through vertices.

@dschult

dschult commented Sep 7, 2025

Copy link
Copy Markdown
Member

If we try to move path construction inside the bigger loop, we'd need more to track the sources, check if paths is None and target is None in the big loop. Not clear its simpler -- but if you think it might be go ahead.

@amcandio

amcandio commented Sep 7, 2025

Copy link
Copy Markdown
Contributor Author

I can leave it for another PR. I'd only do it if faster. Code-wise I prefer current version!

@amcandio

Copy link
Copy Markdown
Contributor Author

@dschult what do you think of the current state? Are you good with implementation and timings?

@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 to me.
It delays computing paths until the search is complete to avoid intermediate path construction. It uses a pred_dict dict to hols the information for the delayed path construction. If pred is requested and paths is requested, then pred_dict uses the provided pred dict to store the predecessors -- conveniently providing the info needed to get paths and the pred dict itself.

Thanks @amcandio

@rossbar rossbar 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 @amcandio !

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

LGTM too, thanks Ale!

@dschult
dschult merged commit 0bad061 into networkx:main Sep 15, 2025
@dschult dschult added this to the 3.6 milestone Sep 15, 2025
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.

5 participants