Repository navigation
Conversation
|
Adds Deviations from the paperFor review I'd like to highlight two deviations from the paper: Tie-break in Eq. 2.5. Stage 1 dirty-set. Stage 1 visits only nodes whose inputs changed since their last visit. Pre-existing members of a stage-2-merge target are not dirtied even though the absorbing label's strength tables changed, so this is a heuristic, not a strict fixed-point equivalent of a full-sweep stage 1. Empirically, on the Debian package–developer bipartite graph (10 seeds): Q_B = 0.906430 (dirty-set) vs. 0.906435 (full-sweep), a ~5x10^-6 gap, well below typical seed-to-seed variance, this heuristic provides a ~50x speedup, which makes it practical for relatively large real world networks. CorrectnessThe Davis Southern Women network is small enough that Barber's original BRIM algorithm (Barber 2007, Table I) reports the best Q_B = 0.34554, used as the reference optimum in the bipartite community-detection literature. It's also worth noticing that this implementation has a single seed parameter. Beckett recommends running it with multiple seeds and keep the best Q_B. This is explained in the docstrings and is responsibility of the user to run it several times with different seeds and keep the best. PerformanceDirty-set stage 1, an incremental inter-module edge map, and stage-2 search restricted to label pairs present in that map together take the Debian network from ~140 s (literal pseudocode) to ~1.1 s. Benchmark (3 seeds per network, median wall time, best Q_B over the 3 seeds; heavy networks at 1 seed):
The three empirical networks come from Torrents & Ferraro 2015, SciPy Proceedings. Each has a Figshare DOI; I'll attach the GraphML files to the PR for convenience:
Not in this PR
Benchmark script"""Benchmark for `bipartite.lpawb_plus_communities`.
Run after each perf step to track regressions/wins.
Usage:
python benchmark_lpawb_plus.py # run all networks
python benchmark_lpawb_plus.py --profile # also cProfile the largest
"""
import argparse
import cProfile
import pstats
import statistics
import time
from pathlib import Path
import networkx as nx
from networkx.algorithms import bipartite
DEBIAN = Path.home() / "projects/structural_cohesion/data/debian_lenny_5.0.graphml"
NUCL_TH = Path.home() / "projects/structural_cohesion/data/nucl_th_2006_2011.graphml"
HEP_TH = Path.home() / "projects/structural_cohesion/data/hep_th_2006_2011.graphml"
def load_networks():
nets = []
G = nx.davis_southern_women_graph()
side = {n for n, d in G.nodes(data=True) if d["bipartite"] == 0}
nets.append(("davis_southern_women", G, side))
G = bipartite.random_graph(50, 80, 0.3, seed=42)
side = {n for n, d in G.nodes(data=True) if d["bipartite"] == 0}
nets.append(("random_50x80_p0.3", G, side))
G = bipartite.random_graph(200, 300, 0.05, seed=42)
side = {n for n, d in G.nodes(data=True) if d["bipartite"] == 0}
nets.append(("random_200x300_p0.05", G, side))
if DEBIAN.exists():
G = nx.read_graphml(DEBIAN)
side = {n for n, d in G.nodes(data=True) if d.get("bipartite") == 0}
nets.append(("debian_lenny_5.0", G, side))
if NUCL_TH.exists():
G = nx.read_graphml(NUCL_TH)
side = {n for n, d in G.nodes(data=True) if d.get("bipartite") == 0}
nets.append(("nuclear_theory", G, side))
if HEP_TH.exists():
G = nx.read_graphml(HEP_TH)
side = {n for n, d in G.nodes(data=True) if d.get("bipartite") == 0}
nets.append(("hep_theory", G, side))
return nets
def time_one(G, side, seed):
t0 = time.perf_counter()
comms = bipartite.lpawb_plus_communities(G, side, seed=seed)
elapsed = time.perf_counter() - t0
Q = bipartite.modularity(G, comms, side)
return elapsed, Q, len(comms)
def bench(name, G, side, seeds):
n = G.number_of_nodes()
e = G.number_of_edges()
s = len(side)
print(f"\n[{name}] nodes={n} edges={e} side(red?)={s}/{n - s}")
times, qs, ms = [], [], []
for seed in seeds:
t, Q, M = time_one(G, side, seed)
times.append(t)
qs.append(Q)
ms.append(M)
print(f" seed={seed:3d} t={t:7.3f}s Q={Q:.4f} communities={M}")
print(
f" -> median t={statistics.median(times):7.3f}s "
f"min t={min(times):7.3f}s "
f"best Q={max(qs):.4f}"
)
return times
def profile(G, side, seed):
print("\n--- cProfile (largest network, 1 run) ---")
pr = cProfile.Profile()
pr.enable()
bipartite.lpawb_plus_communities(G, side, seed=seed)
pr.disable()
ps = pstats.Stats(pr).sort_stats("cumulative")
ps.print_stats(15)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--profile", action="store_true")
ap.add_argument("--seeds", type=int, default=3, help="seeds per network")
args = ap.parse_args()
seeds = list(range(args.seeds))
nets = load_networks()
last = None
for name, G, side in nets:
# Heavy networks: fewer seeds.
s = seeds if G.number_of_edges() < 50_000 else seeds[:1]
bench(name, G, side, s)
last = (name, G, side)
if args.profile and last is not None:
name, G, side = last
print(f"\nProfiling {name} ...")
profile(G, side, 0)
if __name__ == "__main__":
main() |
Add `bipartite.lpawb_plus_communities` implementing Beckett's LPAwb+ algorithm (2016), a two-stage heuristic for maximizing Barber's weighted bipartite modularity Q_B. Stage 1 is asynchronous label propagation: blue-side then red-side labels are updated in random order, each node picking the label that maximizes its local Q_B contribution (Beckett Eq. 2.5). Ties including the node's current label keep the current label, which guarantees monotonic improvement and convergence. Stage 2 is agglomerative: each module looks for its best merge partner by Q_B delta; if two modules are mutually each other's best and the merge strictly increases Q_B, they are merged and Stage 1 is re-run. The outer loop repeats until no improving merge exists.
|
I force-pushed because I forgot to check the formatting with ruff |
| cross = label_strength_red.get(a, 0) * label_strength_blue.get( | ||
| b, 0 | ||
| ) + label_strength_red.get(b, 0) * label_strength_blue.get(a, 0) |
There was a problem hiding this comment.
This looks kinda awkward....
Would it be better to store the zeros in the label_strength dicts? You could then use dict lookups instead of get. Or maybe figure out which a or b is red and only do lookups in that direction? Probably this is fine -- but I thought I'd ask... :}
There was a problem hiding this comment.
Good question. Both options run into the same issue: labels aren't tied to a side.
A label starts on one side (each node begins in its own community), but stage 1 routinely produces mixed communities: a label a may have red members, blue members, or both. So we need to consult both label_strength_red[a] and label_strength_blue[a], and either may be missing.
For "store the zeros": we'd have to keep every active label present in both dicts. That means _apply_label_change and _merge_strength need extra branches to maintain the cross-side entry (create it when a label first acquires a node on that side, delete it when the last node leaves), and we lose the cheap if self_table[old] <= 0: del self_table[old] pattern that keeps the dicts sparse. We pay bookkeeping on every label move to save four .get calls in _stage2, which runs much less often than stage 1.
For "only look in the red direction": the (a, b) keys in inter aren't ordered by side: a < b is just an arbitrary integer ordering. Either endpoint can be a red-only, blue-only, or mixed community.
There was a problem hiding this comment.
Nice description -- that helps. And I'm not so worried about the time of 4 .get calls as I am about understanding the algorithm.
My follow-up question is: Do we need to keep the dicts sparse? If we give in to having full dicts we don't have to do the new-key and del-key parts of bookkeeping (nor the .get calls). Or am I missing something...
Also how big are the dicts? I'm thinking for N nodes in G we would start with two dicts of size N, instead of the current two dicts with N1 + N2 = N. So we are approximately doubling O(N) memory use. But that's at the start. As the merging progresses, it seems like the two dicts will likely have more and more similar keys because the merged community nodes will be mixed. But I haven't checked the bookkeeping to see what happens to the keys as we merge communities. Does the bookkeeping update to maintain one key for each community?
Can you also help me with the terms "src", "dst" in some places and "old", "new" in others and "a", "b". Are these all community labels? or are they nodes? That might make the bookkeeping easier for me to parse. Thanks!!
There was a problem hiding this comment.
You were right. I was about to reply that we need the strength dicts to be sparse for performance, but looked closely (and tested it by actually making the change) and keeping them sparse only adds bookkeeping work and makes the code difficult to read. I was conflating two things in my earlier reply: the sparse inter dict and the sparse strength dicts. The sparse inter is the real performance win: it's what lets _stage2 enumerate O(|inter|) candidate pairs instead of O(M²), and that one still stays sparse. Keeping label_strength_red / label_strength_blue sparse, by contrast, was never buying anything: I was paying readability cost (the four .get(., 0) you flagged, plus the if self_table[old] <= 0: del branch in _apply_label_change) to save trivial memory.
Going dense also gives a nice single invariant for the bookkeeping:
members.keys() == label_strength_red.keys() == label_strength_blue.keys()
Communities enter and leave all three dicts together. Wall-time is unchanged within run-to-run noise; no Q_B regression.
Regarding src/dst vs old/new vs a/b: all are community labels. I pushed a second commit that standardizes on a _label suffix, with a glossary block at the top of lpawb_plus_communities listing each bookkeeping object. _best_label keeps Beckett's x, g, current, best because those trace 1:1 to Eq. 2.5; its docstring now spells out which are nodes and which are labels. Let me know if it's easier to read and understand now.
While working on the renaming I spotted two easy improvements: inlined the mutual-best-partner check in _stage2 (the old back_partner intermediate only existed to give the comparison a name) and replaced inter.pop(..., None) with del inter[...] since the key is guaranteed to exist.
Maintain ``label_strength_red`` and ``label_strength_blue`` as dense
keyed-by-active-label dicts: every live community appears in both
dicts, with 0 on the side that has no members. The invariant
members.keys() == label_strength_red.keys() == label_strength_blue.keys()
is preserved jointly through stage 1 label moves and stage 2 merges,
so all reads are direct subscript access. The stage-2 cross term now
reads exactly like Beckett's ``k_A d_B + k_B d_A``.
The ``inter`` dict stays sparse on purpose: its sparsity is what makes
stage 2 enumerate O(|inter|) candidate pairs instead of O(M^2).
Suggested by @dschult in PR review. Memory cost at init is ~2x in the
strength tables (2 entries per node instead of 1), trivial in absolute
terms. Wall-time is unchanged within run-to-run noise (~5-10% on the
medium and large networks); no Q_B regression.
Address @dschult's PR review: the LPAwb+ bookkeeping helpers used three different conventions for referring to community labels, forcing a reader to re-derive the type of each variable in every helper. Standardize on ``_label`` suffixes for label parameters. Add a glossary comment at the top of ``lpawb_plus_communities`` listing the bookkeeping objects (``labels``, ``members``, ``label_strength_*``, ``inter``) and where each lives in the node/label type system. ``_best_label`` keeps Beckett's notation (``x``, ``g``, ``current``, ``best``, ``y_x``, ``n_xg``) -- those names trace 1:1 to Eq. 2.5 in the paper. Its docstring now spells out that ``x`` is a node and the rest are community labels. Drive-bys spotted while renaming: * Inline the mutual-best-partner check in ``_stage2``; the old intermediate ``back_partner`` only existed to give the comparison a name, and is unnecessary with ``keep_label`` / ``drop_label`` in scope. * Replace ``inter.pop(..., None)`` with ``del inter[...]``: the key is guaranteed to exist (it was scanned out of ``inter.items()`` to populate ``best_partner`` earlier in the same stage-2 call). No behavior change.
dschult
left a comment
There was a problem hiding this comment.
Thanks -- those were great changes. Between the changes and the comments it feels much easier to read.
Further comments:
- the edge weights get divided by M often. It seems like we could scale the edge weights at the very beginning (so that the sum of the edge weights is 1). That would get reflected in L_c, k_c and d_c, e_{ab}, in the strengths and maybe even in
inter. Is the only impact of that scaling that M becomes 1 everywhere? If so, is it worth it? - I like the test of "ground truth" e,.g. for Davis Southern Women Network; And the test that switching which bipartite set is "red" and "blue" leads to the same result.
- What does LPAwb stand for? I'm guessing wb is weighted bipartite... :)
- The new public function should connect to the docs by adding an entry in
doc/references/algorithms/bipartite.rst. - And FYI, the private function's doc_strings don't show in the docs, so if you find the many quotes to be bothersome you can leave them off the private function doc_strings. Though I do find it nice as a way of indicating code or variable names -- so my brain doesn't have to figure out whether it is being used as an english word, or as a variable name. :}
- Not for this PR, but we should update the general bipartite docs to include these new features along with some description of how to choose one method over another -- or at least if they are related (two ways of getting at the same idea).
Thanks for this -- it looks good!
|
Thanks @dschult for the careful read. Going point by point: 1. Scaling edge weights so
|
|
@dschult if you have time and energy to take another look at this, I think it is close to be ready to merge. |
| if len(red) > len(blue): | ||
| red, blue = blue, red | ||
|
|
||
| if G.number_of_edges() == 0 or not red or not blue: |
There was a problem hiding this comment.
I think number_of_edges does a full iteration across the edges. So there are probably faster ways to do this check
There was a problem hiding this comment.
Thanks for looking at this! You're right: number_of_edges() calls size(), which sums the degrees of all nodes. But it turns out the check isn't needed at all: the M == 0 guard a few lines below already covers graphs without edges (all strengths are zero) and returns the same singleton partition. Removed in 04f11d3, with a comment on the M == 0 line, and a test exercising the no-edges case.
Flagged in review: G.number_of_edges() sums all node degrees. The check is not needed at all, since the M == 0 guard below already covers graphs without edges (all strengths are zero) and returns the same singleton partition. Add a test pinning the no-edge behavior, which now goes through the M == 0 path.
|
Hi @dschult and @amcandio, a gentle ping on this one when you have time. I think all review comments are addressed:
If anything else stands out I'm happy to do another round. |
Add
bipartite.lpawb_plus_communitiesimplementing Beckett's LPAwb+ algorithm (2016), a two-stage heuristic for maximizing Barber's weighted bipartite modularity Q_B.Stage 1 is asynchronous label propagation: blue-side then red-side labels are updated in random order, each node picking the label that maximizes its local Q_B contribution (Beckett Eq. 2.5). Ties including the node's current label keep the current label, which guarantees monotonic improvement and convergence.
Stage 2 is agglomerative: each module looks for its best merge partner by Q_B delta; if two modules are mutually each other's best and the merge strictly increases Q_B, they are merged and Stage 1 is re-run. The outer loop repeats until no improving merge exists.
AI disclaimer: I used Claude to tidy up the wording of the docstring and the code comments, it was specially useful to correctly write the math so it renders nicely. Also made it review the implementation, and test extensively the heuristic applied to stage 1. Claude also wrote the benchmark script that I will attach in a follow up comment.