Skip to content

Fix group_betweenness_centrality on directed and size-3+ groups - #8666

Closed
Ijtihed wants to merge 2 commits into
networkx:mainfrom
Ijtihed:fix-group-betweenness-8559
Closed

Ijtihed wants to merge 2 commits into
networkx:mainfrom
Ijtihed:fix-group-betweenness-8559

Conversation

@Ijtihed

@Ijtihed Ijtihed commented May 29, 2026 •

Copy link
Copy Markdown

Fixes #8559.

Summary

group_betweenness_centrality could return negative values or raise KeyError on directed non-strongly-connected graphs. The endpoint correction and pairwise overlap terms assumed reachability that these graphs do not guarantee.

this replaces the Puzis matrix approach with a direct computation so for each source count shortest paths through the group as

(sigma - sigma_avoid) / sigma

where sigma_avoid is computed by a predecessor-DAG DP over shortest paths avoiding the group.

This also fixes wrong results that were silent for groups of size 3 or larger across directed, undirected, and weighted graphs.

Tests

Added two regression tests. Also checked against a brute-force reference, against betweenness_centrality for single-node groups, and against existing tests. Previously correct inputs keep the same output.

Notes

prominent_group has a separate deeper bug so it's left for future follow ups.

Compared old vs new against a brute-force nx.all_shortest_paths ground truth on 2000 random graphs covering directed/undirected, weighted/unweighted, n = 5–11 and group sizes 1–3:

new == brute force: 2000/2000
old: 1574 correct, 300 wrong, 126 crashed with KeyError
time: new 0.156s, old 0.324s, about 2.1x faster

So the new version matches the ground truth in all cases tested and is considerably faster.

comparison script
import random
import subprocess
import time

import networkx as nx

BASE = "96ad598c"  # commit just before the fix

src = subprocess.check_output(
    ["git", "show", f"{BASE}:networkx/algorithms/centrality/group.py"], text=True
)
src = "\n".join(ln for ln in src.splitlines() if "_dispatchable" not in ln)
ns = {}
exec(compile(src, "old_group", "exec"), ns)
old_gbc = ns["group_betweenness_centrality"]
new_gbc = nx.group_betweenness_centrality


def brute_force(G, group, weight=None):
    group = set(group)
    directed = G.is_directed()
    total = 0.0
    for s in G:
        if s in group:
            continue
        for t in G:
            if t == s or t in group:
                continue
            try:
                paths = list(nx.all_shortest_paths(G, s, t, weight=weight))
            except nx.NetworkXNoPath:
                continue
            total += sum(1 for p in paths if any(n in group for n in p)) / len(paths)
    return total if directed else total / 2


rng = random.Random(0)
trials = 2000
new_ok = old_ok = old_wrong = old_crash = 0
t_new = t_old = 0.0

for _ in range(trials):
    n = rng.randint(5, 11)
    G = nx.gnp_random_graph(n, rng.uniform(0.25, 0.6),
                            seed=rng.randint(0, 1 << 30), directed=rng.random() < 0.5)
    weight = None
    if rng.random() < 0.5:
        for _, _, d in G.edges(data=True):
            d["weight"] = rng.randint(1, 5)
        weight = "weight"
    group = rng.sample(list(G), rng.randint(1, 3))

    ref = brute_force(G, group, weight=weight)

    t0 = time.perf_counter()
    new_val = new_gbc(G, group, weight=weight, normalized=False, endpoints=False)
    t_new += time.perf_counter() - t0
    new_ok += abs(new_val - ref) <= 1e-6

    t0 = time.perf_counter()
    try:
        old_val = old_gbc(G, group, weight=weight, normalized=False, endpoints=False)
        t_old += time.perf_counter() - t0
        if abs(old_val - ref) <= 1e-6:
            old_ok += 1
        else:
            old_wrong += 1
    except Exception:
        t_old += time.perf_counter() - t0
        old_crash += 1

print(f"new == brute force: {new_ok}/{trials}")
print(f"old: {old_ok} correct, {old_wrong} wrong, {old_crash} crashed")
print(f"time: new {t_new:.3f}s, old {t_old:.3f}s, {t_old / t_new:.1f}x")

AI disclosure

I used an AI assistant to help double check the code + make sure I didn't miss anything stupid + run some local tests

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

Thanks for this!

Looks good. Would be great to have some data around running time so we are sure we are not degrading on that front (it's probably already faster than previous version).

Regarding correctness, it would be great to have some randomized script that compares old and new versions over several graphs. We usually don't commit those but you can include it on the description.

Comment thread networkx/algorithms/centrality/group.py Resolved
@Ijtihed

Ijtihed commented May 31, 2026

Copy link
Copy Markdown
Author

Thanks for this!

Looks good. Would be great to have some data around running time so we are sure we are not degrading on that front (it's probably already faster than previous version).

Regarding correctness, it would be great to have some randomized script that compares old and new versions over several graphs. We usually don't commit those but you can include it on the description.

Just added into the PR body what I ran 🗡️ lmk if this is how it should be done, tbh I've never included code in a PR body so I hope this is okay!

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

Closing per agentic PR policy.

@rossbar rossbar closed this Jun 2, 2026
@Ijtihed

Ijtihed commented Jun 2, 2026 •

Copy link
Copy Markdown
Author

Closing per agentic PR policy.

Hey @rossbar could you please clarify whjch part violated the policy?

I've already checked the guidelines before today and tbh my understanding was that the policy allows AI assisted work if I manually review, understand the change, and ofc disclose AI use (which I did). I answered questions about the code as well..

Ik you guys reserve the right to close without explanation but if you could please lmk so I don't make the same mistake again, I really don't want to give off any wrong impressions. Thanks!

( @amcandio what are your thoughts on this? )

@amcandio

amcandio commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

I haven't had time to finish reviewing but not seeing red flags.

That 2x is great! If you have time, It would be great to add official benchmarks so we can track future improvements and ease reproducing. You can look at the other examples of benchmarks in the code base.

I'm not seeing "spammy" AI related behavior so happy to keep this one open and continue reviewing it as I find time.

@amcandio amcandio reopened this Jun 3, 2026
@Ijtihed

Ijtihed commented Jun 4, 2026

Copy link
Copy Markdown
Author

If you have time, It would be great to add official benchmarks so we can track future improvements and ease reproducing. You can look at the other examples of benchmarks in the code base.

cool! I added official ASV benchmarks for group_betweenness_centrality in benchmarks/benchmarks/benchmark_group_centrality.py.

I kept the randomized correctness script only in the PR description and committed only the benchmark source like you said

ASV built both commits and the report was that some benchmarks was that performance increased

some results were: weighted_path_graph(1000), node subset, 1.55s -> 1.09s. wheel_graph(1000), node subset, 1.10s -> 685ms. directed_wheel(1000), node subset, 1.14s -> 695ms.

@amcandio

Copy link
Copy Markdown
Contributor

I see that the behavior is different for this graph (your version returns 1). Is that the bug you mention? Can you elaborate more?

>>> import networkx as nx
... 
... G = nx.DiGraph()
... 
... G.add_weighted_edges_from([
...     (1, 0, 2),
...     (1, 5, 4),
...     (2, 0, 1),
...     (2, 3, 5),
...     (3, 2, 2),
...     (5, 3, 3),
... ])
... 
... G.add_node(4)
... 
... group = [3, 4, 2]
... 
... result = nx.group_betweenness_centrality(
...     G,
...     group,
...     weight="weight",
...     normalized=False,
...     endpoints=False,
... )
... 
... print("Group:", group)
... print("Group betweenness centrality:", result)
... 
Group: [3, 4, 2]
Group betweenness centrality: 3.0

@Ijtihed

Ijtihed commented Jun 14, 2026

Copy link
Copy Markdown
Author

I see that the behavior is different for this graph (your version returns 1). Is that the bug you mention? Can you elaborate more?

>>> import networkx as nx
... 
... G = nx.DiGraph()
... 
... G.add_weighted_edges_from([
...     (1, 0, 2),
...     (1, 5, 4),
...     (2, 0, 1),
...     (2, 3, 5),
...     (3, 2, 2),
...     (5, 3, 3),
... ])
... 
... G.add_node(4)
... 
... group = [3, 4, 2]
... 
... result = nx.group_betweenness_centrality(
...     G,
...     group,
...     weight="weight",
...     normalized=False,
...     endpoints=False,
... )
... 
... print("Group:", group)
... print("Group betweenness centrality:", result)
... 
Group: [3, 4, 2]
Group betweenness centrality: 3.0

yes this is the bug! the old implementation returns 3.0 on this graph but the correct answer is 1.0 from my understanding.

the non-group nodes are {0, 1, 5}. Of the 6 directed pairs among them, only (5, 0) matters -- the unique shortest path is 5->3->2->0 (cost 6), which goes through group nodes 3 and 2. the other two reachable pairs (1,0) and (1,5) go direct so GBC = 0 + 0 + 1 = 1.0.

the old code gets 3.0 because its endpoint correction is computed from forward reachability only (D[group_node]) which misses paths arriving at group nodes from non-group sources. node 5 can reach 3 and 2 but dneither can reach 5, so on a directed non-strongly-connected graph the subtraction undershoots and you get 9 - 6 = 3 instead of 1

@Ijtihed

Ijtihed commented Jul 12, 2026 •

Copy link
Copy Markdown
Author

@amcandio :)

@Ijtihed

Ijtihed commented Jul 24, 2026

Copy link
Copy Markdown
Author

pinging here again for visibility

@amcandio

Copy link
Copy Markdown
Contributor

I think it would be worth fixing the bugs in the original implementation as part of #8854 and then revisit this PR.

Full rewrites are tricky to review and especially if they also change behavior!

@rossbar

rossbar commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

I'm going to go ahead and re-close this to focus on #8854 - thanks @amcandio

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.

group_betweenness_centrality returns negative values on directed non-strongly-connected graphs

4 participants