Skip to content

Commit 21e4358

Browse files
Max17190claude
authored andcommitted
perf(analyze): speed up suggest_questions betweenness, same scores
suggest_questions runs nx.betweenness_centrality to pick the top 3 bridge nodes. On a graph over 1000 nodes it samples 100 sources, but each search still reaches nearly the whole graph, with the search state in dicts keyed by node id. On Guava's 84k-node graph that was 18.2s of a 51.9s one-file update. _betweenness_centrality numbers the nodes once and keeps the same state in lists, resetting only the entries a source reached. It follows networkx's search order, summation order and rescale, so the scores match networkx 3.5 and later bit for bit. The step drops to 4.6s on Guava, and from 7.8s to 2.3s on Django. Co-Authored-By: Claude Opus 5.5 <[email protected]> (cherry picked from commit 6a7c6ae)
1 parent f51d46c commit 21e4358

2 files changed

Lines changed: 110 additions & 1 deletion

File tree

‎graphify/analyze.py‎

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
"""Graph analysis: god nodes (most connected), surprising connections (cross-community), suggested questions."""
22
from __future__ import annotations
3+
import math
4+
import random
35
from pathlib import Path
46
import networkx as nx
57

@@ -480,6 +482,71 @@ def _cross_community_surprises(
480482
return deduped[:top_n]
481483

482484

485+
def _betweenness_centrality(G: nx.Graph, k: int | None, seed: int) -> dict[str, float]:
486+
"""The scores of ``nx.betweenness_centrality(G, k=k, seed=seed)``, bit for bit.
487+
488+
Unweighted, normalized and without endpoints, the only form used here. networkx
489+
keeps the search state in dicts keyed by node id and rebuilds the path counts and
490+
predecessor lists over the whole graph for each source. This numbers the nodes
491+
once, keeps the same state in lists, and resets only the entries a source reached.
492+
The search order, the accumulation order and the rescale for sampled sources
493+
follow networkx 3.5 and later, so the scores do not depend on the installed networkx.
494+
"""
495+
nodes = list(G)
496+
n = len(nodes)
497+
if k == n:
498+
k = None
499+
index = {node: i for i, node in enumerate(nodes)}
500+
neighbors = [[index[w] for w in G[v]] for v in nodes]
501+
sources = range(n) if k is None else [index[v] for v in random.Random(seed).sample(nodes, k)]
502+
scores = [0.0] * n
503+
dist = [-1] * n
504+
sigma = [0.0] * n # number of shortest paths from the source
505+
delta = [0.0] * n
506+
preds: list[list[int]] = [[] for _ in range(n)]
507+
for s in sources:
508+
dist[s] = 0
509+
sigma[s] = 1.0
510+
order = [s] # the breadth-first queue, which is also the visit order
511+
i = 0
512+
while i < len(order):
513+
v = order[i]
514+
i += 1
515+
next_dist = dist[v] + 1
516+
sigma_v = sigma[v]
517+
for w in neighbors[v]:
518+
if dist[w] < 0:
519+
dist[w] = next_dist
520+
order.append(w)
521+
elif dist[w] != next_dist:
522+
continue
523+
sigma[w] += sigma_v
524+
preds[w].append(v)
525+
for w in reversed(order):
526+
coeff = (1 + delta[w]) / sigma[w]
527+
for v in preds[w]:
528+
delta[v] += sigma[v] * coeff
529+
if w != s:
530+
scores[w] += delta[w]
531+
for v in order:
532+
dist[v] = -1
533+
sigma[v] = delta[v] = 0.0
534+
preds[v] = []
535+
targets = n - 1 # a path through a node cannot end at that node
536+
if targets >= 2:
537+
if k is None:
538+
scale = 1 / (targets * (targets - 1))
539+
scores = [score * scale for score in scores]
540+
else:
541+
# A sampled source cannot lie on a path from itself.
542+
source_scale = 1 / ((k - 1) * (targets - 1)) if k > 1 else math.nan
543+
other_scale = 1 / (k * (targets - 1))
544+
sampled = set(sources)
545+
scores = [score * (source_scale if i in sampled else other_scale)
546+
for i, score in enumerate(scores)]
547+
return dict(zip(nodes, scores))
548+
549+
483550
def suggest_questions(
484551
G: nx.Graph,
485552
communities: dict[int, list[str]],
@@ -520,7 +587,7 @@ def suggest_questions(
520587
# 2. Bridge nodes (high betweenness) → cross-cutting concern questions
521588
if G.number_of_edges() > 0:
522589
k = min(100, G.number_of_nodes()) if G.number_of_nodes() > 1000 else None
523-
betweenness = nx.betweenness_centrality(G, k=k, seed=42)
590+
betweenness = _betweenness_centrality(G, k, seed=42)
524591
# Top bridge nodes that are NOT file-level hubs
525592
bridges = sorted(
526593
[(n, s) for n, s in betweenness.items()

‎tests/test_analyze.py‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Tests for analyze.py."""
22
import json
3+
import re
34
import networkx as nx
45
import pytest
56
from pathlib import Path
@@ -895,3 +896,44 @@ def test_surprise_score_normalizes_backslash_paths():
895896
def test_surprise_score_ignores_leading_dot_slash():
896897
assert _cross_reasons("./pkg/a.py", "b.py")
897898
assert not _cross_reasons("./a.py", "b.py")
899+
900+
901+
def _betweenness_case(n: int, m: int, *, directed: bool = False, extras: bool = False) -> nx.Graph:
902+
"""A random graph keyed by string ids, optionally with self-loops and isolated nodes."""
903+
G = nx.gnm_random_graph(n, m, seed=n + m, directed=directed)
904+
G = nx.relabel_nodes(G, {i: f"n{i:04d}" for i in G})
905+
if extras:
906+
G.add_edges_from([("n0003", "n0003"), ("n0010", "n0010")])
907+
G.add_nodes_from(["lone_a", "lone_b"])
908+
return G
909+
910+
911+
_NETWORKX_RESCALES_SAMPLES_BY_SOURCE = tuple(map(int, re.match(r"(\d+)\.(\d+)", nx.__version__).groups())) >= (3, 5)
912+
913+
914+
@pytest.mark.parametrize(
915+
("G", "k"),
916+
[
917+
(nx.Graph(), None),
918+
(nx.path_graph(["a"]), None),
919+
(nx.path_graph(["a", "b"]), None),
920+
(nx.path_graph(["a", "b", "c", "d"]), None),
921+
(nx.star_graph(6), None),
922+
(nx.cycle_graph(9), None),
923+
(nx.complete_graph(5), None),
924+
(_betweenness_case(60, 70, extras=True), None),
925+
(_betweenness_case(60, 140, directed=True, extras=True), None),
926+
pytest.param(_betweenness_case(300, 420, extras=True), 40, marks=pytest.mark.skipif(
927+
not _NETWORKX_RESCALES_SAMPLES_BY_SOURCE, reason="networkx < 3.5 rescales sampled scores differently")),
928+
pytest.param(_betweenness_case(200, 500, directed=True), 30, marks=pytest.mark.skipif(
929+
not _NETWORKX_RESCALES_SAMPLES_BY_SOURCE, reason="networkx < 3.5 rescales sampled scores differently")),
930+
# suggest_questions samples 100 sources once a graph has more than 1000 nodes.
931+
pytest.param(_betweenness_case(1500, 1900, extras=True), 100, marks=pytest.mark.skipif(
932+
not _NETWORKX_RESCALES_SAMPLES_BY_SOURCE, reason="networkx < 3.5 rescales sampled scores differently")),
933+
],
934+
)
935+
def test_betweenness_matches_networkx_bit_for_bit(G, k):
936+
from graphify.analyze import _betweenness_centrality
937+
938+
expected = nx.betweenness_centrality(G, k=k, seed=42)
939+
assert list(_betweenness_centrality(G, k, seed=42).items()) == list(expected.items())

0 commit comments

Comments
 (0)