Skip to content

Improve Performance of Tree Isomorphism and Center Calculation - #7946

Merged
rossbar merged 6 commits into
networkx:mainfrom
amcandio:tree-center-optimization
Apr 15, 2025
Merged

rossbar merged 6 commits into
networkx:mainfrom
amcandio:tree-center-optimization

Conversation

@amcandio

@amcandio amcandio commented Mar 30, 2025 •

Copy link
Copy Markdown
Contributor

Improve Performance of Tree Isomorphism and Center Calculation

When working with #7945 I tried running tree_isomorphism for big (over 1000 nodes) path graphs and realized method was pretty slow even though docs claimed time complexity of O(n*log(n)). After diving deep I realized center calculation was not leveraging the fact input graph was a tree, where we can use specialized algorithm with better time complexity.

Summary

This PR optimizes the time complexity of two key algorithms in NetworkX:

  1. Tree Center Calculation (_tree_center):

    • Replaces the previous approach (which involved all-pairs shortest path computations) with an iterative leaf-removal method.
    • Time complexity improvement: O(N² log N) → O(N).
    • Updates the center function to use _tree_center when applicable.
  2. Tree Isomorphism (tree_isomorphism):

    • Fixes an incorrect claim in the documentation. The current implementation previously stated:

      "This runs in O(n*log(n)) time for trees with n nodes."

    • However, the actual time complexity was higher due to the expensive center computation.
    • Now, with the optimized _tree_center, the overall complexity is reduced to O(N log N).

Performance Benchmark

We measured the performance improvement using nx.center(nx.path_graph(5000)):

  • Without optimization: Average execution time: 7.418421 seconds
  • With optimization: Average execution time: 0.007979 seconds
  • Speedup: ~1000× faster 🚀
import timeit
import networkx as nx

def run_center():
    return nx.center(nx.path_graph(5000))

execution_time = timeit.timeit(run_center, number=10) / 10  # Average over 10 runs
print(f"Average execution time: {execution_time:.6f} seconds")

Additional Changes

  • Updates the test suite to validate the correctness of the new _tree_center approach.
  • Fixes minor formatting inconsistencies in tree_isomorphism.py.

Impact

  • Performance boost for large tree graphs.
  • More accurate documentation regarding tree isomorphism complexity.

Testing

  • Unit Tests:
    The updated implementation of _tree_center has been tested with various types of tree graphs, including simple trees, balanced trees, and path graphs. The tests validate that the center calculation is correct and efficient.

  • Test Cases:

    • Simple Tree:
      G = nx.Graph([(1, 2), (1, 3), (2, 4), (2, 5)])
      assert nx.center(G) == [1, 2]
    • Balanced Tree:
      For balanced trees, such as binary trees, the center should always be the root node:
      for r in range(2, 5):
          for h in range(1, 5):
              G = nx.balanced_tree(r, h)
              assert nx.center(G) == [0]
    • Path Graphs:
      For path graphs of various sizes, the center is expected to be at or near the middle of the graph:
      for n in range(1, 100):
          G = nx.path_graph(n)
          expected = {(n - 1) // 2, math.ceil((n - 1) / 2)}
          assert set(nx.center(G)) == expected

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

Another very nice find @amcandio ! I generally think this is a nice (and necessary) improvement.

Before diving into any specifics for review, I wanted to have a discussion on where this implementation should go. You made a sensible choice by putting this in the distance_measures module, but to me it feels like a shame to have this implementation be private. IMO this deserves to be publicly exposed and more discoverable!

What I would propose is that the definition gets moved to the networkx/algorithms/tree package, perhaps in a new, private module tree/_distance_measures.py1 with the name exported only to the tree namespace. Therefore users could in principle call the function like nx.tree.center. I'd definitely be in favor of keeping the condition in distance_measures.center as well as you've done here (L756 would just change from return _tree_center(G) to return nx.tree.center(G))

Anyways - I think this is a nice opportunity to make this ever-so-slightly more discoverable and fit neatly into the existing library structure. However I don't want to hold up the nice work with the organizational concerns, so if there's no feedback from other community members re: organization within a couple days I'll go ahead and push to get this in as-is and move the organizational-proposal to a follow-up PR!

Footnotes

  1. I suspect that center is not the only distance measure for which a more efficient algorithm exists specifically for trees! ↩

@amcandio

Copy link
Copy Markdown
Contributor Author

@rossbar I like that idea! Happy to take the refactoring in a follow up PR.

Question: tree.center would only be for unweighted graphs, should we clarify that in method name (i.e. unweighted_center) or should we just clarify it in the docs? Something like "for weighted center use nx.center)

@rossbar

rossbar commented Apr 1, 2025

Copy link
Copy Markdown
Contributor

Question: tree.center would only be for unweighted graphs, should we clarify that in method name

I'd vote to leave it out of the name - I think it's reasonable that someone would want to generalize to weighted graphs in the future, and that's much easier to implement if we don't have to modify function names. A simple note in the docstring that node/edge attributes are ignored should be sufficient IMO!

@amcandio

amcandio commented Apr 1, 2025

Copy link
Copy Markdown
Contributor Author

Ack. Will take that in a separate PR. Is this one okay to merge?

@dschult

dschult commented Apr 1, 2025

Copy link
Copy Markdown
Member

You can make that change in your branch locally, commit it and push it up to your fork on the same branch.
Github will add that commit to this PR nicely -- and you won't have to make a new PR.

@amcandio

amcandio commented Apr 2, 2025

Copy link
Copy Markdown
Contributor Author

@dschult I prefer to do it in a separate PR so I deliver small changes and I avoid having open PRs for a long time (I might need more days till I follow up on the tree.center change). Is that okay?

@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 some suggestions for wording -- see what you think.
I also made a couple minor suggestions for the code that arguably help readability. But that's often preference -- so see what you think.

@amcandio
amcandio force-pushed the tree-center-optimization branch from 25cd27f to b16a1fc Compare April 2, 2025 06:44

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

Generally LGTM, just one question about the nuts-and-bolts of leaf removal and a few minor suggestions!

Comment on lines +79 to +78
if degree is None:
continue

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.

Out of curiosity, in what situation does this arise? Is it only self-loops? If so, I'd advocate for handling slightly more explicitly, something like:

for neighbor in G.neighbors(leaf):
    # Ignore self-loops
    if neighbor == leaf:
        continue
    degree = center_candidates_degree[neighbor]

IMO this is more explicit and makes the procedure easier to understand!

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.

Maybe move it up one line (to before the degree lookup) and use if neighbor not in center_candidates_degree: instead of if degree is None:. That would make it arguably easier to read the code.

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.

@rossbar this is to defend against the case of a connected component with just two leaves (tree of size 2). Only for the case where we have multiple connected components (I'm assuming graph might not be a tree).

@dschult I made that change to make it clearer. I tend to optimize dict accesses, contains + [] is two dict accesses and doing '.get' is just one.

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.

I'm still a bit confused - isn't a graph with multiple components not a tree by definition? Shouldn't we raise in that case then?

One thing that would definitely help me understand would be if we could add an explicit test of a simple example which fails without this check but passes with it!

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.

Since this is a private method I didn't want to add an extra check if the graph is a tree (caller is already checking that). This way I avoid an extra graph traversal.

However, original implementation would loop for-ever in case somehow caller doesn't pass a connected graph. To be extra defensive against that case, I modified implementation a bit but there is no explicit tree check.

Makes sense? This will change once we migrate to a public method. In that PR we will have to think how to re-use code but also avoid validating input is a tree twice

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.

So how is it that we can get a neighbor which has already been removed?

Because I'm not actually modifying the graph, implementation is based on counters

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.

Okay that was the piece I was missing, thanks for your patience!

So in essence this is equivalent for n in set(G.neighbors(leaf)) & center_candidated_degree.keys():

I think this is clear as-is, my hangup was getting lost in multiple data structures.

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.

No worries. Just double checking: Do you want me to make that change?

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 think the newest version (with the check of node in center_candidate_degree) avoids this confusion. So we don't need to create the set of nbrs in the for statement. I think this concern has been addressed.

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.

I agree. What do you think @rossbar, do you think we can merge this?

@amcandio

amcandio commented Apr 9, 2025 •

Copy link
Copy Markdown
Contributor Author

@dschult @rossbar are we good to go to merge this one? Just let me know if you have more comments, happy to address them!

@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 would like to see the new function moved to a more public facing function in the tree subpackage. But that will be a separate PR.

I'm also slightly concerned at the justification of the complexity being O(N). "Each node is processed once" is not enough to show O(N). The processing time matters too. Here processing is O(1). Perhaps it is better to just state that it is O(1) without a partial justification. (And a complete justification of all complexity statements is beyond the scope of nx docs anyway.) But that's not a blocker for me.

@amcandio

Copy link
Copy Markdown
Contributor Author

I approve this PR I would like to see the new function moved to a more public facing function in the tree subpackage. But that will be a separate PR.

Yes, more PRs coming soon!

I'm also slightly concerned at the justification of the complexity being O(N). "Each node is processed once" is not enough to show O(N). The processing time matters too. Here processing is O(1). Perhaps it is better to just state that it is O(1) without a partial justification. (And a complete justification of all complexity statements is beyond the scope of nx docs anyway.) But that's not a blocker for me.

You are right, my justification is income. I removed the justification so I just state time complexity.

@amcandio
amcandio force-pushed the tree-center-optimization branch from 7fcfa60 to 3f40845 Compare April 13, 2025 04:06

@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 @amcandio , this LGTM! Sorry for holding things up when I got lost in the weeds :)

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