Skip to content

Fix BC scaling for source nodes with k and endpoints=False - #7949

Merged
rossbar merged 4 commits into
networkx:mainfrom
eriknw:fix_bc_source_and_nonsource
Apr 1, 2025
Merged

rossbar merged 4 commits into
networkx:mainfrom
eriknw:fix_bc_source_and_nonsource

Conversation

@eriknw

@eriknw eriknw commented Mar 31, 2025

Copy link
Copy Markdown
Contributor

This is a follow up to #7908 and specifically @dschult's question from #7908 (review):

The case with k < n and endpoints is False still confuses me. It seems like the number of valid (s, t) node pairs that could have a path through v where s != t should depend on whether node v was in the sample or not in the sample. The largest possible count for nodes in the sample (when endpoints is False) is (k-1)(n-2), but for nodes not in the sample the count can be k(n-2). Why are we using k*(n-2) for all the nodes?

After investigating this, I think source nodes and non-source nodes do indeed need to scale differently when k is given and endpoints=False.

I added a test that exercises this. I don't fully grok the test results, but I trust the scaling logic more than I did.

CC @ChuckHastings @rlratzel

Comment on lines 130 to +131
if k == len(G):
# This is for performance and correctness. When `endpoints` is False
# and k is given, k == n is a special case that would violate the
# assumption that node `v` is not one of the (s, t) node pairs.
# Should this warn or raise instead?
# This is done for performance; the result is the same regardless.

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.

It's nice that k == n is no longer a "special case", which otherwise is a red flag. Now, if we kept k = n, we would get the same result! This makes sense to me. This should be comforting and highly suggestive that scaling should be done as in this PR.

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.

Yes! I agree... And I was very much looking forward to having this comment about "correctness" removed. It does indeed make me feel more comfortable.

There is another part of this that I was wrestling with over the weekend. Instead of adjusting the scaling factor based on whether a node is in the sample or not, could we replace k with the expected value of the number of paths? That is, each node has chance k/n of being in the sample, so instead of k and k-1 for the different nodes, we could use k - k/n. That then is k*(n-1)/n which turns us around to scaling by n/k instead of (n-1)/k. This feels like it reverts some of the changes we made in the previous PR. But -- because we do have the set of nodes that are sampled, I prefer using that information for scaling. I guess I don't trust the "Law of large numbers " when we can use the more precise small numbers information.

I was working on this, but got distracted by our undirected graph adjustment when sampling.
I think there are troubles there too. Perhaps this is better for yet another PR though.
When k=1 we know that we have not double-counted any undirected paths. So we should NOT be dividing the count by 2. When k=2 we know that we considered at most 1 double-counted path. In general, we consider k(k-1)/2 paths twice, and the remaining k*(n-2) - k(k-1)/2 paths once. There must be a way to adjust our scaling of the undirected case to account for this bias when sampling.

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 think I understand your two points.

For your middle paragraph, I think you are suggesting an alternative that uses an expectation or an average value to use for the scale for all the nodes, but still prefer the exactness (and probably correctness) for scaling each node depending whether it was a source or not. Yeah, if we didn't have the source nodes available, I think this would be better than nothing, but we might as well use the source node information since we have it.

I'm not sure I completely follow your last paragraph, so let me paraphrase and correct me if I'm wrong. Basically, for undirected graphs when using k without normalizing, you are considering changing the "double counting" correction. The intuition is that for k=1, then no (s, t) and (t, s) pairs are double-counted, so we don't need to divide by two, and for k=len(G), then all (s, t) and (t, s) pairs were double-counted exactly, so we need to divide by two for all nodes. A linear scaling between these two boundaries could be correction = 1 + (k - 1) / (n - 1) (I almost certainly got this wrong), but maybe the more accurate way to count this would be to divide contributions of paths by two if (s, t) and (t, s) pairs were both sampled, but don't divide by two for paths if there is not a (s, t) and (t, s) pair. I don't think I buy this; or, rather, I don't think my current understanding of it is correct. I'm not able to articulate this yet, so I'm not confident, but I think we already do a good job of accounting for possible paths. I would be curious if there's an algorithm or implementation for undirected graphs with k samples that does not require the double-counting correction.

@dschult dschult Mar 31, 2025 •

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'll go read Blondel Brandes again... Or maybe they wrote another paper more recently about directed vs undirected.
:)

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

Thanks a lot for this @eriknw!!
Especially for the tests and making them readable! :)

I have some optional tweaks and suggestions below that I hope keep the flow clear.

I think the main issues I have left are:

  • when k=1 and endpoints=False should we raise? or assign to the sampled node 0 or 'nan'? See comment below.
  • how to handle undirected paths when sampling. I will try to explain why I think we are using the right formulas even though the appear to ignore double-counting in the sample. The key is assuming that the starting nodes are chosen randomly so chosen paths are not related to double-counting.

Undirected paths with k<n:
For undirected paths, I have convinced myself that what we are doing is the best we can do unless we start tracking which paths are double-counted. And I don't see an easy way to track that with the Brandes sigma/delta formulation. Here's my justification:

Let n=len(G) and N = n if endpoints else n-1 and K = k-1 if node in sample else k. Letbc_raw be the count of paths through a node, and bcf be the actual betweenness value normalized so it is the fraction of al possible paths that pass through a node. Let bc_count be the unnormalized value. I'll use "distinct paths" to refer to undirected paths that don't double-count both directions.

We currently use bc_count = bc_raw * N/(2*K) for undirected graphs. This works well for full bc computations, but it seems wrong for sampling.

The number of possible distinct paths through a node is N*(N-1)/2, but the number of distinct paths for a sample of k starting nodes is not as simple. Our sample has K*(K-1)/2 possible double-counted paths for each node. So the number of distinct paths in our sample is K(N-1) - K(K-1)/2. How then can we approximate the count of distinct paths through a node?

Let's assume that a path eventually double-counted is just as likely pass through this node as a single-counted path (which should be true for random sampling of starting nodes).

Then the expected number of double-counted paths should be bcf*K*(K-1)/2. Here bcf is the true value -- not an estimate. Our estimate of it comes from bc_raw in the relation bcf = (bc_raw - bcf*K*(K-1)/2) / (K*(N-1) - K*(K-1)/2). That is the ratio of counted distinct paths to possible distinct paths. This implicit equation for bcf can be rearranged to solve for bcf as

bcf = bc_raw/(K*(N-1))

But that is the same formula as for directed graphs!! So just as we currently do, we should compute the normalized bc values without regard to double-counting paths.

To get the non-normalized bc_count from bcf, multiply by the total possible distinct paths:
```bc_count = bcf * N*(N-1)/2 = bc_raw * N/(2*K)`.
This again is our current formula. The factor of 2 is the same.

I believe that to do better than this we need to track which paths through each node are double counted. And I think that would disturb our Brandes-based speed-up in counting the paths.

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

Niiccee!!!

Thanks @eriknw

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

Thanks all, again, for the detailed dive into the guts of betweenness centrality. I still can't claim to 100% follow all of the details, but the introduced tests really help me understand what's going on!

Once this work is completed and all follow-ups are in, I'm definitely in favor of a detailed release note to explain what all changed and why!

Finally - I have one nit comment: should we use math.nan or float("nan")? I don't really know whether there's a difference and am happy with whatever we decide, but figured I'd raise it for my own edification!

@eriknw

eriknw commented Apr 1, 2025

Copy link
Copy Markdown
Contributor Author

Thanks for the quick (and thorough, @dschult) reviews! I don't know of anything else that needs to be done before merging. I agree these changes are worth a detailed release note.

Finally - I have one nit comment: should we use math.nan or float("nan")? I don't really know whether there's a difference and am happy with whatever we decide, but figured I'd raise it for my own edification!

Fair question! I looked into this too. math.nan and float("nan") are equivalent, and math.nan is guaranteed to always be available as of Python 3.11: https://docs.python.org/3/library/math.html#math.nan, which says of math.nan "Equivalent to the output of float('nan')".

So, the main differences are math.nan is shorter to type and is about 5x faster for me:

In [2]: %timeit float("nan")
92.8 ns ± 5.64 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)

In [3]: %timeit math.nan
18.6 ns ± 2.66 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)

Undirected paths with k<n: [...]

@dschult, believe it or not what you laid out actually makes sense to me, and some quick sympy-fu verified the results. It also matches my intuition 👍.

@rossbar

rossbar commented Apr 1, 2025

Copy link
Copy Markdown
Contributor

Awesome - thanks again all!

@rossbar
rossbar merged commit b9df494 into networkx:main Apr 1, 2025
rapids-bot Bot pushed a commit to rapidsai/nx-cugraph that referenced this pull request Apr 1, 2025
Update note about `betweenness_centrality`, because libcugraph was updated to match  networkx/networkx#7908, but does not yet match networkx/networkx#7949.

Authors:
  - Erik Welch (https://github.com/eriknw)

Approvers:
  - Rick Ratzel (https://github.com/rlratzel)

URL: #107
@jarrodmillman jarrodmillman added this to the 3.5 milestone May 29, 2025
rapids-bot Bot pushed a commit to rapidsai/cugraph that referenced this pull request Jun 12, 2025
networkx/networkx#7949 implements an update to normalization that was originally described in #4941.  We pushed an update in #4974 that addressed the specific examples that the user identified in the original cugraph issue.  However, while @eriknw was exploring updates to networkx to address this, he identified a few more edge conditions that needed to be satisfied.  This PR addresses those remaining edge conditions.

Note that the python tests comparing results to networkx are still disabled.  These can't be re-enabled until networkx/networkx#7949 is included in a networkx release.

Closes #5006 
Closes #5107

Authors:
  - Chuck Hastings (https://github.com/ChuckHastings)
  - Rick Ratzel (https://github.com/rlratzel)

Approvers:
  - Seunghwa Kang (https://github.com/seunghwak)
  - Joseph Nke (https://github.com/jnke2016)
  - Rick Ratzel (https://github.com/rlratzel)

URL: #5105
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.

5 participants