Skip to content

Implement the algorithm to find the centroid(s) of a tree - #8089

Merged
dschult merged 11 commits into
networkx:mainfrom
jbradberry:tree-centroid
Sep 2, 2025
Merged

dschult merged 11 commits into
networkx:mainfrom
jbradberry:tree-centroid

Conversation

@jbradberry

Copy link
Copy Markdown
Contributor

This is a measure of centrality specific to trees that is based on balancing the number of nodes around the chosen node or nodes. I believe I have successfully implemented the algorithm with O(N) time complexity.

https://en.wikipedia.org/wiki/Tree_(graph_theory)#Properties

I waffled a bit whether to put it in the networkx/algorithms/tree/ directory, but there isn't much that it really fits with over there, and it feels like it belongs near the graph center algorithm.

I see that there had previously been a ticket #3525 opened, that was subsequently closed without a PR.

@amcandio

amcandio commented Jun 3, 2025

Copy link
Copy Markdown
Contributor

Does it make sense to have this method discoverable from the tree module too?

@jbradberry

Copy link
Copy Markdown
Contributor Author

Does it make sense to have this method discoverable from the tree module too?

Quite possibly.

@dschult

dschult commented Jun 3, 2025

Copy link
Copy Markdown
Member

This looks like the tree module should house this code. We can/should add "see also" links to it from the center-related code docstrings. But let's give it a new section heading in doc/reference/algorithms/tree.rst with a name related to distance measures or centers or centroids -- whatever you think fits the best.

The failed tests are not related to your PR. This afternoon they started failing due to a change in the drawing test software. So look to see if any of your stuff is causing an error -- but right now they are failures in the drawing tests. Just in time for your PR. :)

Thanks!

@jbradberry

Copy link
Copy Markdown
Contributor Author

Ok, I've moved the algorithm and the tests over to algorithms/tree, and have touched the tree.rst docs page.

I might want a bit more guidance on what any cross-reference from the center-related docs ought to look like, though.

@Peiffap

Peiffap commented Jun 3, 2025

Copy link
Copy Markdown
Member

I think Dan just means you should go through the docstrings for the functions related to the center, and add

:func:`~networkx.algorithms.tree.distance_measures.tree_centroid`

to the "See Also" section where appropriate. At least, if my link is correct...

The same thing we do in a few other places where functions in different parts of the code base are related; for example:

See Also
--------
eigenvector_centrality_numpy
:func:`~networkx.algorithms.link_analysis.pagerank_alg.pagerank`
:func:`~networkx.algorithms.link_analysis.hits_alg.hits`

@jbradberry

jbradberry commented Jun 3, 2025 •

Copy link
Copy Markdown
Contributor Author

Just as an aside, why doesn't networkx.algorithms.distance_measures.center and friends live with the centrality algorithms?

edit: Never mind, I see that the centrality functions mostly return dicts of measures instead of just a bare list of node labels.

@jbradberry

Copy link
Copy Markdown
Contributor Author

All right, I've updated the center docstring with the cross-ref. It felt less appropriate to do to any of the functions in centrality, so I'll stop there unless I get further feedback.

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

I could be wrong, but isn't this a duplicate of the functionality added in #7946 ? The proposal there was to expose that as nx.tree.center but we never submitted the follow-up PR to do so.

@jbradberry

jbradberry commented Jun 3, 2025 •

Copy link
Copy Markdown
Contributor Author

I could be wrong, but isn't this a duplicate of the functionality added in #7946 ? The proposal there was to expose that as nx.tree.center but we never submitted the follow-up PR to do so.

No. The center described there is maximizing the eccentricity. A tree centroid is the point or points that have minimum "weight" (not to be confused with edge weights -- this weight is just the number of nodes accessible down each branch).

Let me see if I can cook up an example where they legit have different results...

@rossbar

rossbar commented Jun 3, 2025

Copy link
Copy Markdown
Contributor

No. The center described there is maximizing the eccentricity. A tree centroid is the point or points that have minimum "weight" (not to be confused with edge weights -- this weight is just the number of nodes accessible down each branch).

In that case then I think we need to expand the test suite - the current tests give the same results for every case if you replace nx.tree_centroid with nx.center

@jbradberry

jbradberry commented Jun 3, 2025 •

Copy link
Copy Markdown
Contributor Author

A path graph with a star at one end:

In [5]: G = nx.Graph([(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (6, 7), (7
      ⋮ , 8), (8, 9), (9, 10)])

In [6]: nx.center(G)
Out[6]: [7]

In [7]: nx.tree_centroid(G)
Out[7]: [0]

The long branch doesn't contribute enough weight to throw off the centroid from the middle of the star. But the graph center wants to be close to the middle of the long path.

@jbradberry

Copy link
Copy Markdown
Contributor Author

Test added.

@jbradberry
jbradberry requested a review from rossbar June 3, 2025 23:29

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

All of these are nits, except maybe for the exception docstring. Feel free to disregard what you don't like.

And let's maybe add a paragraph to the notes to quickly mention the difference between center and centroid, and maybe an example too!

@dschult

dschult commented Jun 4, 2025

Copy link
Copy Markdown
Member

Centrality creates measures of how central each node is. Distance measures are typically trying to find single number measures of networks -- like diameter or center. Centrality tries to find the key/important nodes. Center is trying to find the geographic middle (of a non-positioned object :)

@jbradberry

Copy link
Copy Markdown
Contributor Author

All right, I think I got all of the comments. I even made a stab at explaining the difference between centroid and center, but my writing always feels a bit clumsy.

@jbradberry
jbradberry requested a review from Peiffap June 4, 2025 14:47

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

I might be getting lost in the sauce a little here, but some more comments.

  • Perhaps most importantly: isn't the tree centroid the same thing as the tree barycenter? If I understand correctly, the centroid is (roughly) $\arg\min_{u \in T} \max_{C \in T \setminus \{u\}} |C|$, i.e. the node that minimizes the size of the largest component upon being removed from $T$. The barycenter is $\arg \min_{u \in T} \sum_{v \in T} d_T(u, v)$, the node that minimizes the sum of its distances to all nodes. I don't have time to look for a proof right now, but empirically replacing the body of nx.tree_centroid by nx.barycenter(T) seems to work (except for the exception tests, which are really only for internal consistency. If so, maybe something similar to what was done in #7946 can be done here?
  • Can this easily be extended to work with weighted graphs? If not, we should probably mention that somewhere.

@jbradberry

Copy link
Copy Markdown
Contributor Author

I might be getting lost in the sauce a little here, but some more comments.

* Perhaps most importantly: isn't the tree centroid the same thing as the tree barycenter?

I strongly suspect that this is not the case, though it isn't as easy for me to think up a counter-example as it was for center vs centroid.

* Can this easily be extended to work with weighted graphs? If not, we should probably mention that somewhere.

I don't think so given the definitions I've read, though I admit I'm not conversant with the mathematical literature on the subject.

@jbradberry

jbradberry commented Jun 4, 2025 •

Copy link
Copy Markdown
Contributor Author

Hm.

In [42]: for g in nx.graph_atlas_g():
    ...:     if len(g.nodes) == 0:
    ...:         continue
    ...:     if not nx.is_tree(g):
    ...:         continue
    ...:     b = nx.barycenter(g)
    ...:     c = nx.tree_centroid(g)
    ...:     if b != c:
    ...:         print(g, b, c)
    ...: 
Graph named 'G81' with 6 nodes and 5 edges [3, 4] [4, 3]
Graph named 'G83' with 6 nodes and 5 edges [4, 5] [5, 4]

In [43]: for g in nx.graph_atlas_g():
    ...:     if len(g.nodes) == 0:
    ...:         continue
    ...:     if not nx.is_tree(g):
    ...:         continue
    ...:     b = set(nx.barycenter(g))
    ...:     c = set(nx.tree_centroid(g))
    ...:     if b != c:
    ...:         print(g, b, c)
    ...: 

In [44]: 

Time to break out the Knuth.

@jbradberry

Copy link
Copy Markdown
Contributor Author

A bit of ambiguous argument:

I've been trying systematically generated small trees (I think I got up to 9 nodes before it was taking too long for my taste) and a variety of larger randomly generated trees. I have yet to find any that have a divergent result between these two functions. But! This is mathematics -- I'm not comfortable just saying that they are equivalent without a formal proof.

I looked up the source material mentioned in the docs as the source of the barycenter definition (D. B. West, “Introduction to Graph Theory”, Prentice Hall, 2nd ed., 2001). The tree centroid is defined (although not given a name) in 2.1.56, immediately after the section defining the barycenter (2.1.55). The centroid section does not make use of the barycenter definition, and I can find no further mention elsewhere in the book.

@jbradberry
jbradberry requested a review from Peiffap June 4, 2025 17:39
@jbradberry

Copy link
Copy Markdown
Contributor Author

What the heck is going on with test/dispatch (3.11)? It's throwing a bunch of KeyError: 'G' for my tests.

@jbradberry

Copy link
Copy Markdown
Contributor Author

All right, I just did the simplest thing -- left tree_centroid as a discoverable function, and call out to it from barycenter when invoked with an undirected tree graph (and none of the optional parameters for barycenter are used).

@dschult @rossbar , what do you think?

@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 - the only real decisions left in my book are big-picture questions (which don't necessarily have to be addressed in this PR).

Namely - how do we expose the functionality to users. My inclination, based on the patterns we discussed for center in #7946 is that we confine the export of this functionality to the tree namespace and rename it to barycenter to match the existing distance measure.

The main motivation for doing so in my view is that we can then remove the is_tree check from tree_centroid instead relying on the fact that it is part of the tree namespace as an indication to users that it's only relevant for trees. This pattern is used in other namespaces in the library (e.g. bipartite) and has additional advantages:

  • It prevents is_tree from being called twice (once in barycenter, once implicitly) when users call nx.barycenter on a tree
  • It unifies the naming scheme for distance measures (i.e. those that apply to all graphs and those that are implementations specific to trees)

Anyways - that's the API I gravitate towards but it's not a blocker for me. If others strongly prefer the API proposed herein that's okay with me. It also doesn't necessarily have to be hammered out in this PR, we can always tweak the API in follow-ups (we're several months away from the next release).

In any case, with the addition of the asymetrical test case and the confirmation that centroid == barycenter semantically this LGTM. I approve the addition and am happy to push API munging to future PRs!

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

Sorry, just back to this one! No further comments from me

@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'm going to merge this centroid of a tree PR.
Thanks @jbradberry for your patience.

We've got 4 approvals and another PR working on comments and ideas stemming from this one. We can work out details of the API -- hopefully before the next release. :)

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

Happy to leave these points to a follow-up PR (either myself, or leave it to @jbradberry), but this makes for a simple place to organize my comments. Let's make sure this gets hammered out pre-3.6 though :).

Comment thread networkx/algorithms/__init__.py Outdated
from networkx.algorithms.tree.branchings import ArborescenceIterator
from networkx.algorithms.tree.coding import *
from networkx.algorithms.tree.decomposition import *
from networkx.algorithms.tree.distance_measures import *

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.

Do we additionally want to expose this in the main namespace? I'd vote no, especially if we rename from nx.tree.tree_centroid to just nx.tree.centroid or nx.tree.barycenter. Note that #8174 already exposed specialized distance measure algorithms to the nx.tree namespace.

:func:`~networkx.algorithms.tree.distance_measures.tree_centroid`
"""
if weight is None and attr is None and sp is None:
if nx.is_tree(G) and not G.is_directed():

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.

Do we need to check if G is undirected here? Does it change the result? If directed graphs that "correspond" to trees can also use the fast path I say we should do so.

"""
if weight is None and attr is None and sp is None:
if nx.is_tree(G) and not G.is_directed():
return nx.tree_centroid(G)

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.

In case it doesn't get exposed in the main namespace.

Suggested change
return nx.tree_centroid(G)
return nx.tree.tree_centroid(G)

Comment on lines +119 to +202
if not nx.is_tree(G):
raise nx.NotATree("provided graph is not a tree")

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 check can be removed if we don't expose this outside the nx.tree namespace.

Comment on lines +31 to +34
def test_tree_centroid_not_a_tree(self):
G = nx.cycle_graph(3)
with pytest.raises(nx.NotATree, match=r"not a tree"):
nx.tree_centroid(G)

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.

And this test will then no longer be accurate :).

@jbradberry

Copy link
Copy Markdown
Contributor Author

Oh, uh oh, I see that there are some conflicts. I'll hit this up after work today and get it sorted out.

@dschult

dschult commented Sep 2, 2025 •

Copy link
Copy Markdown
Member

No need to merge the conflicts. I'm on it. (and I'm handling the recent comments too)
I knew this would happen when I merged the "tree.center" PR so I'll fix it.

@dschult
dschult merged commit 6fad2d3 into networkx:main Sep 2, 2025
@jarrodmillman jarrodmillman added this to the 3.6 milestone Sep 2, 2025
alfred-mikhael pushed a commit to alfred-mikhael/networkx that referenced this pull request Sep 3, 2025
)

* Implement the algorithm to find the centroid(s) of a tree

* Move the new tree_centroid to networkx/algorithms/tree/

* Add a cross-reference to tree_centroid() from center()

* Add a tree_centroid test that diverges from the results of center()

* Addressing the review comments for tree_centroid()

* Move the center vs tree_centroid example description

down to the Examples section

* Rename the graph parameter for tree_centroid

* Addressing further review comments on tree_centroid()

* Expand on the meaning of the algorithm in _subtree_sizes

* Call out to tree_centroid from barycenter()

but only if barycenter isn't being invoked with optional parameters,
and only if the graph is an undirected tree.

* fix see also links

---------

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.

6 participants