Skip to content

Adding optional sp arg to closeness_centrality - #8424

Merged
rossbar merged 8 commits into
networkx:mainfrom
Maninder-sd:closeness-centrality-precalculations
Mar 2, 2026
Merged

rossbar merged 8 commits into
networkx:mainfrom
Maninder-sd:closeness-centrality-precalculations

Conversation

@Maninder-sd

Copy link
Copy Markdown
Contributor

This code will add the sp argument to nx.centrality.closeness_centrality.
It is similar to how nx.eccentricity can use pre-computed shortest path lengths.
I added 8 unit tests to cover graphs, digraphs and weighted graphs. Here's an example

G = nx.complete_graph(5)
sp = dict(nx.all_pairs_shortest_path_length(G))
c = nx.closeness_centrality(G, sp=sp)

The idea comes from following the Facebook tutorial. The code snippet takes 30sec on my machine since its calculating shortest path lengths. We already calculate it early and it would be nice to be able to reuse the calculation

@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 the proposal @Maninder-sd - this is indeed an interesting idea for computation re-use with precedent in the distance_measures functions, which let you pass in the results of previous computation (either the shortest-paths or eccentricities, depending on the function).

I'm tentatively in favor of heading this direction, especially since this is motivated by a "real" use-case from nx-guides! One can see how users investigating various centrality measures on a large network could benefit from this mechanism. This same approach could be considered for other centrality measures that depend on shortest-paths (e.g. betweenness) but let's not try to pack that into this PR!

@Maninder-sd

Copy link
Copy Markdown
Contributor Author

Hi @rossbar thanks for the feedback! If all looks well feel free to merge this PR.
Yes I think it would be beneficial to have something similar for other centrality measures. I did a brief dig through the centrality measures documentation to find some places we can add a similar feature. Going to put what I found here for future contributions.

  1. betweenness_centrality/edge_betweenness_centrality (as you mentioned)
    Idea: c(v) = "what percent of all shortest paths pass through v"
    Corresponding function: all_pairs_all_shortest_paths
  2. group_betweenness_centrality/group_closeness_centrality
    Similar to betweenness and closeness
  3. harmonic_centrality
    Idea: c(v) = "reciprocal sum of shortest path lengths starting from v to all nodes "
    Corresponding function: all_pairs_shortest_path_length
  4. Current Flow Betweenness/ Current Flow Closeness
    Need to look into implementation
    Corresponding function: Not sure if we have a function to calculate the unique x[s][t] currents for a graph (Reference)

Comment on lines +133 to +138
if G.is_directed():
# code to "inverts" sp
sp_node = {}
for x in G.nodes():
if n in sp[x]:
sp_node[x] = sp[x][n]

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.

Doesn't this assume that G is strongly connected? What happens when the path from u -> v is shorter than the path from v -> u?

Either way, this added complexity strikes me as a net negative. I'd be more inclined to document the requirements for the input to sp (including additonal constraints for directed graphs)

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.

Hi @rossbar, I'm just following the convention of this implementation of closeness. There's no real complexity that's being added here.

The original logic is:
graph G is passed as arg, rev(G) if its directed(line 112) then calculate distances of rev(G) internally using nx.single_source_shortest_path_length.

This code does exactly that in a different order:
User passes G and distance calculation sp of G (by calling all_pairs_shortest_path_length beforehand) as args, then the function reverses G. Since internally sp must be calculated for rev(G) we "invert" the sp internally.

I'm not assuming strongly connected because line 137 only considers reachable nodes. This is what both nx.single_source_shortest_path_length and all_pairs_shortest_path_length do too.

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 not assuming strongly connected because line 137 only considers reachable nodes. This is what both nx.single_source_shortest_path_length and all_pairs_shortest_path_length do too.

My concern is that the code for "reversing" the path lengths is correct - I would expect there to be something like a {t: s: {... for s, t in sp type of pattern. Upon closer inspection maybe that's what's happening, but it's hard to tell with n and x as loop variables.

The reason I'm concerned is for cases where all the nodes are reachable, but the path lengths are different in different directions. In a case like this, if we are not handling the sp dict properly, we will be introducing bugs that are very hard to track down! For example, consider the directed cycle graph - when the edges are oriented "clockwise" (let's say), then the spl from node 0 to 3 is 3, but when the edges are "reversed" (i.e. "counterclockwise") then the spl from node 0 to 3 is 2.

From looking at this again, I'd say there are two things we could consider to improve:

  1. Let's add a test for the directed cycle
  2. In the case where the sp is passed in, we know we already have a fully-populated dict, so we can "reverse" it before entering the main loop (similar to how G itself is handled)

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.

Thanks for the feedback @rossbar . I think I understand your concern, the variables in the code are confusing. I've moved the reversing logic closer to the top of the function and added a test for directed cycle. This is in addition to another test with a directed path graph of length 3. Please look at my latest push. I'll leave it to you to resolve this comment

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

It looks like the tests are straightforward copies of the original tests only now with calling closeness_centrality with the sp argument. I'm guessing there is some way using fixture and/or parametrize to reduce the duplication. But that's for a follow-up PR I think. Can you verify that the values checked are the same for these new tests as for the original tests above? :}

Thanks for this!

@Maninder-sd

Copy link
Copy Markdown
Contributor Author

@dschult

It looks like the tests are straightforward copies of the original tests only now with calling closeness_centrality with the sp argument. I'm guessing there is some way using fixture and/or parametrize to reduce the duplication. But that's for a follow-up PR I think. Can you verify that the values checked are the same for these new tests as for the original tests above? :}

Thanks for this!

Yes exactly, the tests are a copy of the old tests with the new sp arg. I added one new test for a cyclic directed graph as recommended by rossbar.

@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.
There is likely refactoring/simplification we can do in the tests, but lets do that in a later PR.

I have one whitespace comment. ButI approve this PR.

@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 LGTM - I agree we can condense/parametrize tests in a follow-up. Thanks @Maninder-sd for sticking with this and @dschult for the review!

@rossbar
rossbar merged commit 3e6ed3b into networkx:main Mar 2, 2026
38 checks passed
@dschult dschult added this to the 3.7 milestone Mar 2, 2026
rossbar added a commit to rossbar/nx-guides that referenced this pull request Mar 5, 2026
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.

3 participants