Skip to content

optimise is_reachable() - #8112

Merged
dschult merged 23 commits into
networkx:mainfrom
akshitasure12:numpy_is_reachable
Jul 17, 2025
Merged

dschult merged 23 commits into
networkx:mainfrom
akshitasure12:numpy_is_reachable

Conversation

@akshitasure12

@akshitasure12 akshitasure12 commented Jun 13, 2025 •

Copy link
Copy Markdown
Contributor

As per the discussion in the recent networkx community meeting, these are the major changes introduced in this PR:

  • converted the networkx graph object to a numpy-based matrix with the help of nx.to_numpy_array().
  • replaced the use of is_path() with direct matrix-based checks to identify two-hop neighbors.
  • mapped node labels to integer indices and used index-based access throughout the function.

[edit] : Heatmap for reference
image

@dschult

dschult commented Jun 14, 2025 •

Copy link
Copy Markdown
Member

Looks like this needs:

  • using "import or skip" to skip tests when numpy is not available: np = pytest.importorskip("numpy") inside each test function/class/module that you want to skip. I think here it might be each test function.
  • add the module to the "needs_numpy" list in networkx/conftest.py.

And we should figure out how to handle backward compatibility for people who don't have numpy. It looks like this affects both is_reachable and is_strongly_connected. I don't think that has to be in this PR, but it might be easy/nice to have it here if we decide we need it.

@rossbar Do you think we need a fallback option in the code to allow it to work for folks that don't have numpy available?
I'm +0 for providing that. I don't think is_reachable is used much. But I suspect is_strongly_connected could be.

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

Do you think we need a fallback option in the code to allow it to work for folks that don't have numpy available?

My preference is to err on the side of caution, so I'd vote for a fallback. I agree this probably isn't used a ton, but adding a new dependency to an existing function could be taking away functionality from a subset of users. If it's not difficult to do (and it doesn't seem to be in this case) I'd vote to keep the dependency-free implementation as well.

There is precedent for this as well - see e.g. #7716 and #7718 for the approach taken with random_k_out_graph to implement such a fallback mechanism.

@akshitasure12 akshitasure12 changed the title modified is_reachable() with an adjacency matrix implementation optimise is_reachable() Jun 20, 2025
@akshitasure12

akshitasure12 commented Jun 24, 2025 •

Copy link
Copy Markdown
Contributor Author

The current test failure seems unrelated to me.

dschult
dschult previously approved these changes Jun 30, 2025

@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!
Thanks @akshitasure12

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

This looks nice :)!
Some comments below.

Comment thread networkx/conftest.py Resolved
Comment thread networkx/algorithms/tournament.py Resolved
Comment thread networkx/algorithms/tournament.py Resolved
Comment thread networkx/algorithms/tournament.py Resolved
@akshitasure12

Copy link
Copy Markdown
Contributor Author

Thank you so much @Peiffap for your suggestions! I've incorporated them in the recent commits :)

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

That's exactly what I had in mind! If you have the time, maybe some benchmarks would make sense too (since this is primarily a performance improvement). Either way, LGTM! :)

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

Honestly looking at the two different implementations I'm surprised that the numpy-based one is significantly faster... if anything dictionary lookups should be faster than array lookups (or at least not significantly slower.

I think it's worth looking at the Python implementation again to see if we can't improve the two_neighborhood implementation there. For example, that loops over all nodes in G, but can't we instead exploit the neighbor relationships to avoid looking at everything?

Anyways - IMO it's worth having a complete handle on it before introducing a numpy dependency. In other words, if we can improve performance without changing the dependency footprint, that is definitely a win!

Given the nature of these changes I agree with @Peiffap that some explicit benchmarks for this functionality would be extremely helpful!

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

A speed-up for the python version (to eliminate possible cubic dependence on len(G) and also eliminate all the checking in is_path that we know is true for these cases) might be something like (near line 406 in this PR... line 332 of the main branch):

            return {
                x for x in G if x == v or x in G[v] or any(z in G[v] for z in G.pred[x])
            }

Note that the set comprehension should cache G[v] automatically. So that lookup is only done once -- the lookup G.pred[x] gets done for each x. So another step in speedup might be to start with for x, xpred in G.pred.items() .... But either way, the inner loop is already reduced from is_simple_path(...) over all triples (v,z,x) with each node z in G, to calling z in G[v] for each node z that is a predecessor of x.

This should make a large improvement! :)

@akshitasure12

Copy link
Copy Markdown
Contributor Author

Thanks @dschult!
Here, T1: run time of Numpy implementation, and T2: run time of pure Python implementation

Number of nodes: 200
T1: 0.01871013641357422
T2: 0.03364920616149902
Finished <function is_reachable at 0x101504ae0>

Number of nodes: 400
T1: 0.07384085655212402
T2: 0.1333141326904297
Finished <function is_reachable at 0x101504ae0>

Number of nodes: 800
T1: 0.29588794708251953
T2: 0.5328099727630615
Finished <function is_reachable at 0x101504ae0>

Number of nodes: 1600
T1: 1.215939998626709
T2: 2.3156769275665283
Finished <function is_reachable at 0x101504ae0>

Number of nodes: 3200
T1: 4.9940502643585205
T2: 9.749640941619873
Finished <function is_reachable at 0x101504ae0>
is_reachable

The NumPy version is still consistently faster than the pure Python implementation, although the Python version’s runtime has improved a lot. So it seems that, for this graph (a tournament), the cost of Python dict lookups and iteration is still higher than scanning a NumPy matrix?

@Peiffap

Peiffap commented Jul 13, 2025

Copy link
Copy Markdown
Member

@akshitasure12 When you say Python code, is that just by replacing two_neighborhood function with Dan's explicit suggestion? Or did you also add his second optimization?

@akshitasure12

akshitasure12 commented Jul 13, 2025 •

Copy link
Copy Markdown
Contributor Author

@akshitasure12 When you say Python code, is that just by replacing two_neighborhood function with Dan's explicit suggestion? Or did you also add his second optimization?

I added the second optimisation as well!

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

Some more performance-focused comments.

Comment thread networkx/algorithms/tournament.py Resolved
Comment thread networkx/algorithms/tournament.py Resolved
Comment thread networkx/algorithms/tournament.py Resolved
Comment thread networkx/algorithms/tournament.py Resolved
Co-authored-by: Gilles Peiffer <[email protected]>
@akshitasure12

akshitasure12 commented Jul 13, 2025 •

Copy link
Copy Markdown
Contributor Author

I used %prun to inspect the pure Python implementation

    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    1.781    1.781    3.283    3.283 digraph.py:737(add_edges_from)
  1905729    0.664    0.000    0.808    0.000 coreviews.py:81(__getitem__)
      800    0.635    0.001    3.130    0.004 test_isreachable.py:40(two_neighborhood)
   946129    0.382    0.000    1.056    0.000 test_isreachable.py:44(<genexpr>)
   639201    0.378    0.000    0.378    0.000 {method 'update' of 'dict' objects}
  1265729    0.362    0.000    0.690    0.000 <frozen _collections_abc>:811(__contains__)
   319601    0.328    0.000    0.780    0.000 tournament.py:185(<genexpr>)

From this, it looks like the two_neighborhood logic is relatively efficient in pure Python, but the __getitem__ calls (coreviews.py:81) make the overall implementation more expensive.

Note: test_isreachable.py is just a script to run the _is_reachable_python implementation.

@dschult

dschult commented Jul 13, 2025

Copy link
Copy Markdown
Member

To speed up the __getitem__ parts you should replace G.pred[u] with G._pred[u] and G[u] with G._adj[u]. That bypasses the read-only Adjacency class G.pred which is slower than the read-write dict class G._pred.
:)
These are definitely into the weeds of optimization -- but that is what profiling is all about.

@akshitasure12

Copy link
Copy Markdown
Contributor Author

With these micro-optimizations, the pure Python version now runs in about half the time of the NumPy-based implementation. This means we no longer need to rely on NumPy for this function :)

200
0.008026838302612305
0.018900156021118164
Finished <function is_reachable at 0x101fe8ae0>
400
0.03205585479736328
0.07407689094543457
Finished <function is_reachable at 0x101fe8ae0>
800
0.12898588180541992
0.29385805130004883
Finished <function is_reachable at 0x101fe8ae0>
1600
0.5705702304840088
1.226412057876587
Finished <function is_reachable at 0x101fe8ae0>
3200
2.345529079437256
4.898989200592041
Finished <function is_reachable at 0x101fe8ae0>
is_reachable

@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 that the pure Python implementation ends up faster than the numpy one!

Could you add some benchmarks to the benchmarking suite to validate the performance improvements? #8059 is a recent PR that added benchmarks if you want an example (the "benchmarking" section of the contributor's guide isn't very complete...).

Comment thread networkx/algorithms/tournament.py Resolved
Comment thread networkx/algorithms/tournament.py Resolved
@akshitasure12

Copy link
Copy Markdown
Contributor Author

Added a ReachabilityBenchmark Class:

  • supports graphs of size 400, 800, 1600.
  • utilises a random number generator for a consistent choice of source and target.

Benchmarks comparing the previous pure Python implementation vs the new version:

All benchmarks:

| Change   | Before [22314eec] <main>   | After [b01a4c68] <numpy_is_reachable>   |   Ratio | Benchmark (Parameter)                                                                                                                                      |
|----------|----------------------------|-----------------------------------------|---------|------------------------------------------------------------------------------------------------------------------------------------------------------------|
| -        | 9.01±0.06s                 | 487±40ms                                |    0.05 | benchmark_algorithms.ReachabilityBenchmark.time_is_reachable('Tournament(1600, seed=42)') [Akshita-MacBook-Pro.local/virtualenv-py3.11-numpy-pandas-scipy] |
| -        | 10.6±0.07s                 | 557±30ms                                |    0.05 | benchmark_algorithms.ReachabilityBenchmark.time_is_reachable('Tournament(1600, seed=42)') [Akshita-MacBook-Pro.local/virtualenv-py3.12-numpy-pandas-scipy] |
| -        | 10.0±0.02s                 | 415±2ms                                 |    0.04 | benchmark_algorithms.ReachabilityBenchmark.time_is_reachable('Tournament(1600, seed=42)') [Akshita-MacBook-Pro.local/virtualenv-py3.13-numpy-pandas-scipy] |
| -        | 542±3ms                    | 25.7±1ms                                |    0.05 | benchmark_algorithms.ReachabilityBenchmark.time_is_reachable('Tournament(400, seed=42)') [Akshita-MacBook-Pro.local/virtualenv-py3.11-numpy-pandas-scipy]  |
| -        | 645±2ms                    | 31.2±0.1ms                              |    0.05 | benchmark_algorithms.ReachabilityBenchmark.time_is_reachable('Tournament(400, seed=42)') [Akshita-MacBook-Pro.local/virtualenv-py3.12-numpy-pandas-scipy]  |
| -        | 614±2ms                    | 23.8±0.01ms                             |    0.04 | benchmark_algorithms.ReachabilityBenchmark.time_is_reachable('Tournament(400, seed=42)') [Akshita-MacBook-Pro.local/virtualenv-py3.13-numpy-pandas-scipy]  |
| -        | 2.16±0s                    | 108±3ms                                 |    0.05 | benchmark_algorithms.ReachabilityBenchmark.time_is_reachable('Tournament(800, seed=42)') [Akshita-MacBook-Pro.local/virtualenv-py3.11-numpy-pandas-scipy]  |
| -        | 2.56±0.01s                 | 126±0.04ms                              |    0.05 | benchmark_algorithms.ReachabilityBenchmark.time_is_reachable('Tournament(800, seed=42)') [Akshita-MacBook-Pro.local/virtualenv-py3.12-numpy-pandas-scipy]  |
| -        | 2.45±0s                    | 94.3±0.2ms                              |    0.04 | benchmark_algorithms.ReachabilityBenchmark.time_is_reachable('Tournament(800, seed=42)') [Akshita-MacBook-Pro.local/virtualenv-py3.13-numpy-pandas-scipy]  |

This is my first time working with ASV benchmarks, so pls let me know if I'm missing something :)

Comment thread networkx/algorithms/__init__.py Resolved

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

Thanks for sticking with this through all the back-and-forth @akshitasure12 !

This LGTM, any additional comments of mine are not blockers.

@rossbar
rossbar requested a review from dschult July 16, 2025 10:16
@rossbar

rossbar commented Jul 16, 2025

Copy link
Copy Markdown
Contributor

This PR technically has multiple approvals but there were a lot of changes between the different approvals so I will hold off from pushing the green button until others have had a chance to look at latest!

Co-authored-by: Ross Barnowski <[email protected]>
Co-authored-by: Gilles Peiffer <[email protected]>

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

Very impressive performance improvement from what ended up being a relatively minor change! Nice work everybody, and thanks for being patient with the many comments, Akshita! :)

I have one more comment about the benchmarks, but given the change in performance we can already measure, it's definitely not a blocker.

Comment on lines +83 to +89
def _make_tournament_benchmark_graphs(seed):
number_of_nodes = [10, 100, 1000]
graphs = {}
for nodes in number_of_nodes:
G = nx.tournament.random_tournament(nodes, seed=seed)
graphs[f"Tournament ({nodes}, seed={seed})"] = G
return graphs

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.

It would be nice to split this up into two test functions—one where the nodes are known to be reachable, and one where they aren't reachable! You can compute SCCs to enforce this condition I believe.
In line with Ross' comment, I believe that should better showcase the usefulness and importance of short-circuiting—or, if the short-circuits are already being hit, whether the speed-up is equally impressive without short-circuiting. In this case, I believe both cases will be significantly faster than before, but it doesn't hurt to make sure!

@dschult
dschult dismissed their stale review July 17, 2025 13:40

Just tracking that I'm re-reviewing this due to many changes since my first approval.

@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 more tweak that I'd like you to test @akshitasure12. It probably doesn't make a difference in timing (based on the other timings you have done this isn't a critical pathway) so I think of it as a readability issue.
Thanks!

Comment thread networkx/algorithms/tournament.py Resolved

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

I approve this PR.

I'm going to merge as well -- we can tweak the benchmark by figuring out a way to pick source-targets that are reachable or not reachable in a separate PR.

@dschult
dschult merged commit f750ce5 into networkx:main Jul 17, 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.

4 participants