Skip to content

feat(api): update non-tree check in _tree_center and move to tree subpackage - #8174

Merged
dschult merged 9 commits into
networkx:mainfrom
Peiffap:api/tree_center
Sep 2, 2025
Merged

dschult merged 9 commits into
networkx:mainfrom
Peiffap:api/tree_center

Conversation

@Peiffap

@Peiffap Peiffap commented Aug 1, 2025 •

Copy link
Copy Markdown
Member

Fixes #8098.

This PR moves the _tree_center function to the tree subpackage in a new tree.distance_measures module, allowing users to write nx.tree.center(G).

Other than changing the location and making this function more visible, there are several other changes:

  • Clean-ups to the docstring (backticks, grammar)
  • The error type for nontree inputs was changed from nx.NetworkXError to nx.NotATree---since this was previously not exposed, and the call in nx.center only happens after verifying the graph is a tree, this shouldn't be backward incompatible.
  • The check for nontree input is slightly more robust now by also checking if there are candidate centers left (are there still cases we don't catch?).
  • Additional tests.

This will also make an eventual migration of the tree centroid/barycenter function (after #8089 gets merged) easier.

Cc @amcandio who made the initial improvement, @rossbar who suggested moving to the tree subpackage.

EDIT: Comprehensive diff

Dan asked for a comprehensive overview of what changed. Here's the output of git diff --no-index old.py new.py where old.py and new.py are two files with the old version and new version respectively of the tree center function.

diff --git a/old.py b/new.py
index ff75b8c5..3acb8087 100644
--- a/old.py
+++ b/new.py
@@ -1,13 +1,13 @@
 @not_implemented_for("directed")
-def _tree_center(G):
+def center(G):
     """Returns the center of an undirected tree graph.
     The center of a tree consists of nodes that minimize the maximum eccentricity.
     That is, these nodes minimize the maximum distance to all other nodes.
     This implementation currently only works for unweighted edges.
     If the input graph is not a tree, results are not guaranteed to be correct and while
-    some non-trees will raise a ``NetworkXError`` not all non-trees will be discovered.
+    some non-trees will raise a `nx.NotATree` exception; not all non-trees will be discovered.
     Thus, this function should not be used if caller is unsure whether the input graph
-    is a tree. Use ``networkx.is_tree(G)`` to check.
+    is a tree. Use ``nx.is_tree(G)`` to check.
     Parameters
     ----------
     G : NetworkX graph
@@ -18,27 +18,27 @@ def _tree_center(G):
         A list of nodes in the center of the tree. This could be one or two nodes.
     Raises
     ------
-    NetworkXError
-        If algorithm detects input graph is not a tree. There is no guarantee
+    NotATree
+        If the algorithm detects input graph is not a tree. There is no guarantee
         this error will always raise if a non-tree is passed.
     Notes
     -----
     This algorithm iteratively removes leaves (nodes with degree 1) from the tree until
     there are only 1 or 2 nodes left. The remaining nodes form the center of the tree.
-    This algorithm's time complexity is O(N) where N is the number of nodes in the tree.
+    This algorithm's time complexity is ``O(N)`` where ``N`` is the number of nodes in the tree.
     Examples
     --------
     >>> G = nx.Graph([(1, 2), (1, 3), (2, 4), (2, 5)])
-    >>> _tree_center(G)
+    >>> nx.tree.center(G)
     [1, 2]
-    >>> G = nx.Graph([(1, 2), (2, 3), (3, 4), (4, 5)])
-    >>> _tree_center(G)
-    [3]
+    >>> G = nx.path_graph(5)
+    >>> nx.tree.center(G)
+    [2]
     """
     center_candidates_degree = dict(G.degree)
     leaves = {node for node, degree in center_candidates_degree.items() if degree == 1}
 
-    # It's better to fail than an infinite loop, so check leaves to ensure progress
+    # It's better to fail than an infinite loop, so check leaves to ensure progress.
     while len(center_candidates_degree) > 2 and leaves:
         new_leaves = set()
         for leaf in leaves:
@@ -47,14 +47,14 @@ def _tree_center(G):
                 if neighbor not in center_candidates_degree:
                     continue
                 center_candidates_degree[neighbor] -= 1
-                if center_candidates_degree[neighbor] == 1:
+                if (cddn := center_candidates_degree[neighbor]) == 1:
                     new_leaves.add(neighbor)
+                elif cddn == 0 and len(center_candidates_degree) != 1:
+                    raise nx.NotATree("input graph is not a tree")
         leaves = new_leaves
 
-    if not leaves and len(center_candidates_degree) >= 2:
-        # We detected graph is not a tree. This check does not cover all cases.
-        # For example, it does not cover the case where we have two islands (A-B) and (B-C)
-        # where we might eliminate (B-C) leaves and return [A, B] as centers.
-        raise nx.NetworkXError("Input graph is not a tree")
+    if (n := len(center_candidates_degree)) not in {1, 2} or n == 2 and not leaves:
+        # We detected graph is not a tree. This check does not necessarily cover all cases?
+        raise nx.NotATree("input graph is not a tree")
 
     return list(center_candidates_degree)

@dschult dschult changed the title feat(api): move _tree_center to tree subpackage feat(api): update non-tree check in _tree_center and move to tree subpackage Aug 4, 2025

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

This generally LGTM, thanks @Peiffap . +1 for getting tree distance measure algorithms publicly exposed.

@jbradberry

Copy link
Copy Markdown
Contributor

Hey @Peiffap , I just noticed this PR related to #8089. Is there anything that you all need me to do to finish up on my PR?

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

Nice -- and ready to merge. But I have two comments/suggestions/questions:

  • what's up with the benchmark? Have you thought about what kind of trees to time this with? Why are we adding the benchmark?
  • (see below) the condition for "not a tree" is cryptic, so best to make it as clear as possible. Are parens around and/or clauses good practice for readability? And simpler if we split out ideas into separate lines where possible, so avoid walrus operator unless it helps beyond reducing lines.

Not blockers -- and the benchmarks are a bigger conversation I suspect. :)

Co-authored-by: Dan Schult <[email protected]>
@Peiffap

Peiffap commented Sep 2, 2025

Copy link
Copy Markdown
Member Author

@dschult I originally added the benchmark when we were looking into making the nontree check more exhaustive, as I didn't want additional checks to negatively affect the algorithm's performance (as is the case when adding a check for self-loops, for example). Given that this is fundamentally a performance improvement, it makes sense IMO to have a benchmark for it somewhere in the repo.

As for why this specific benchmark... I don't have a good answer :(. My aim was to "measure performance across a variety of different trees," and that seemed like a general enough goal to make a separate benchmark class; it could be reused e.g. to measure performance improvements for other functions we add to the tree.distance_measures module (such as the algorithm in #8089).
There might be better ways to do that; it's an interesting discussion to have. I also agree with your final comment that this probably falls outside the scope of this particular PR. I think having a benchmark (the details of which we can iterate on in a follow-up discussion) is a net improvement over the current situation, though!

@dschult
dschult merged commit 6f5d4d2 into networkx:main Sep 2, 2025
@jarrodmillman jarrodmillman added this to the 3.6 milestone Sep 2, 2025
@Peiffap
Peiffap deleted the api/tree_center branch September 2, 2025 15:46
alfred-mikhael pushed a commit to alfred-mikhael/networkx that referenced this pull request Sep 3, 2025
… subpackage (networkx#8174)

* api: move `tree.center` to new `tree.distance_measures` subpackage

* clean up docstring

* Use `NotATree` exception and improve nontree check

* add tests for `nx.tree.center`

* add benchmarks for `nx(.tree).center`

* additional nontree check

Co-authored-by: Alejandro Candioti <[email protected]>

* fail on self-loops

* remove pointless benchmarking imports


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

* remove walrus operator

Co-authored-by: Dan Schult <[email protected]>

---------

Co-authored-by: Alejandro Candioti <[email protected]>
Co-authored-by: Ross Barnowski <[email protected]>
Co-authored-by: Dan Schult <[email protected]>
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.

Move _tree_center to a separate module

6 participants