Skip to content

ENH: Speed up connectivity checks in random_reference and lattice_reference - #8893

Merged
amcandio merged 1 commit into
networkx:mainfrom
floppy73:optimize-reference-graph-connectivity-checks
Sep 2, 2026
Merged

amcandio merged 1 commit into
networkx:mainfrom
floppy73:optimize-reference-graph-connectivity-checks

Conversation

@floppy73

@floppy73 floppy73 commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

The motivation for this change is to speed up nx.random_reference and nx.lattice_reference.

Currently, connectivity after an edge swap is checked using nx.local_edge_connectivity(G, a, b)==0, where (a, b) is one of the edges selected for the swap. However, only reachability between nodes a and b needs to be checked here; therefore nx.has_path is sufficient for this purpose.

In a simple local benchmark (benchmark.py), replacing nx.local_edge_connectivity with nx.has_path made nx.random_reference about 548× faster and nx.lattice_reference about 45× faster on average.

  • random_reference: 12.6030 s -> 0.0230 s
  • lattice_reference: 4.1919 s -> 0.0929 s

I also confirmed that the current implementation and this modification generate identical graphs for five different random seeds by comparing hashes of their edge lists.

The code after this change passes the tests in test_smallworld.py.

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

Thanks for this! The change is correct and I think should go in: local_edge_connectivity(G, a, b) == 0 and not nx.has_path(G, a, b) are testing exactly the same thing. Worth noting that connected_double_edge_swap already uses nx.has_path for exactly this post-swap check.

I'd like to point out that the original code called local_edge_connectivity without auxiliary and residual params, so every call (inside a tight loop no less) rebuilt the auxiliary digraph and the residual network from scratch. That's two full graph constructions per swap attempt. The flow computation itself is a small part of the cost. But even that is not needed, a simple BFS does the trick.

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

Thanks for this!

@amcandio
amcandio merged commit 6820645 into networkx:main Sep 2, 2026
41 checks passed
@dschult dschult added this to the 3.7 milestone Sep 2, 2026
@floppy73
floppy73 deleted the optimize-reference-graph-connectivity-checks branch September 3, 2026 02:03
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.

4 participants