Repository navigation
Improve Performance of Tree Isomorphism and Center Calculation - #7946
Conversation
rossbar
left a comment
There was a problem hiding this comment.
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
-
I suspect that
centeris not the only distance measure for which a more efficient algorithm exists specifically for trees! ↩
|
@rossbar I like that idea! Happy to take the refactoring in a follow up PR. Question: |
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! |
|
Ack. Will take that in a separate PR. Is this one okay to merge? |
|
You can make that change in your branch locally, commit it and push it up to your fork on the same branch. |
|
@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 |
dschult
left a comment
There was a problem hiding this comment.
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.
25cd27f to
b16a1fc
Compare
rossbar
left a comment
There was a problem hiding this comment.
Generally LGTM, just one question about the nuts-and-bolts of leaf removal and a few minor suggestions!
| if degree is None: | ||
| continue |
There was a problem hiding this comment.
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!
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
@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.
There was a problem hiding this comment.
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!
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
No worries. Just double checking: Do you want me to make that change?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
I agree. What do you think @rossbar, do you think we can merge this?
dschult
left a comment
There was a problem hiding this comment.
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.
Yes, more PRs coming soon!
You are right, my justification is income. I removed the justification so I just state time complexity. |
Removing incomplete time complexity explanation
Adapting algorithms to detect non-trees in a single pass
Reverting previous changes
7fcfa60 to
3f40845
Compare
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:
Tree Center Calculation (
_tree_center):centerfunction to use_tree_centerwhen applicable.Tree Isomorphism (
tree_isomorphism):_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)):Average execution time: 7.418421 secondsAverage execution time: 0.007979 secondsAdditional Changes
_tree_centerapproach.tree_isomorphism.py.Impact
Testing
Unit Tests:
The updated implementation of
_tree_centerhas 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:
For balanced trees, such as binary trees, the center should always be the root node:
For path graphs of various sizes, the center is expected to be at or near the middle of the graph: