Skip to content

ENH: Add Beckett's LPAwb+ bipartite community detection - #8645

Open
jtorrents wants to merge 6 commits into
networkx:mainfrom
jtorrents:LAPwb_plus
Open

jtorrents wants to merge 6 commits into
networkx:mainfrom
jtorrents:LAPwb_plus

Conversation

@jtorrents

Copy link
Copy Markdown
Member

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.

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.

@jtorrents

jtorrents commented May 1, 2026 •

Copy link
Copy Markdown
Member Author

Adds bipartite.lpawb_plus_communities (Beckett 2016, RSOS 3:140536). Paper (not pay-walled) at https://royalsocietypublishing.org/rsos/article/3/1/140536/36438/Improved-community-detection-in-weighted-bipartite

Deviations from the paper

For review I'd like to highlight two deviations from the paper:

Tie-break in Eq. 2.5. _best_label favours the current label on tie and picks uniformly at random only among strictly-better non-current candidates. Pure random tie-breaking lets stage 1 oscillate over equally-scoring labels and breaks "repeat until no change" as a termination criterion; favour-current makes every label flip a strict local Q_B improvement and guarantees finite convergence.

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.

Correctness

The 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. test_southern_women_matches_barber_brim runs LPAwb+ over 20 seeds and asserts the best partition reaches at least Q_B − 1e-4, providing end-to-end evidence that the optimiser converges to the literature reference value on a network where the optimum is known.

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.

Performance

Dirty-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):

Network Nodes Edges Time (s) Q_B Communities
Davis Southern Women 32 89 <0.001 0.3455 4
bipartite.random_graph(50, 80, 0.3) 130 1 183 0.006 0.1684 7
bipartite.random_graph(200, 300, 0.05) 500 2_946 0.045 0.2721 10
Debian Lenny 5.0 12 921 20_072 1.10 0.9064 314
Nuclear Theory (2006-2011) 10_371 15_969 1.25 0.9484 564
High Energy Theory (2006-2011) 26_590 37_566 9.68 0.9412 1 614

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

  • DIRTLPAwb+ (Beckett section 2.2.3): wrapper that re-runs LPAwb+ with varying initial label counts. Maybe worth a follow-up dirtlpawb_plus_communities.
  • Resolution parameter gamma in the optimiser. bipartite.modularity accepts it; lpawb_plus_communities currently optimises gamma = 1 only.
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()

@jtorrents

Copy link
Copy Markdown
Member Author

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

Copy link
Copy Markdown
Member Author

I force-pushed because I forgot to check the formatting with ruff

Comment on lines +537 to +539
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)

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 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... :}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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.

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!!

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

jtorrents added 2 commits May 8, 2026 22:13
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 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 -- 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!

@jtorrents

Copy link
Copy Markdown
Member Author

Thanks @dschult for the careful read. Going point by point:

1. Scaling edge weights so M = 1

The algebra works; if we scale every edge weight by 1/M upfront, all strengths and inter values scale by 1/M, and both the Eq. 2.5 score and the stage-2 delta_Q_B end up scaled by a constant positive factor. And yes, M then drops out of every formula.

I'd rather not do it, to keep the code close to the paper. The implementation deliberately mirrors Beckett's Eq. 2.5 line-for-line:

score = n_xg - y_x * opposite_strength[g] / M

reads as the paper's N_xg - y_x · Z_g / M. Same for _stage2's delta = e / M - cross / (M * M) mapping to ΔQ_B = e_AB/m - (k_A·d_B + k_B·d_A)/m² (page 4 of the paper). Anyone reviewing this code with the paper open can verify each line by sight. Scaling breaks that correspondence. Also, label_strength_red[label] would no longer equal "sum of G.degree(v, weight=...) over red members of label", which is unfortunate and requires extra work.

2. Ground-truth and red/blue-swap tests

Thanks. The Davis Southern Women test is the strongest evidence that the optimiser converges to a known literature value, and the swap test was an easy way to assert that the internal "smaller side as red" relabel doesn't leak into the result.

3. What does LPAwb+ stand for?

You got it: Label Propagation Algorithm — weighted, bipartite — plus. The "plus" is Liu & Murata's [13 in Beckett] LPAb+ convention, the agglomeration step that LPAb adds on top of plain LPA. Beckett extends LPAb+ to weighted networks and calls the result LPAwb+.

4. Docs entry

Added doc/reference/algorithms/bipartite.rst, under the existing Communities section right below modularity.

5. Backticks in private-function docstrings

You're right that they don't render. I lean toward keeping them.

6. Out-of-PR: general bipartite docs

Agreed, this needs a follow-up. I'm also planning a follow up PR with the CONDOR algorithm (Platig et al, 2016. https://doi.org/10.1371/journal.pcbi.1005033) which is less good at maximizing Q_B but practical for bigger networks. We also have leiden work by @dk-gh which can be applied to bipartite networks. I'll put together a follow up PR with the documentation.

@jtorrents

Copy link
Copy Markdown
Member Author

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

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 think number_of_edges does a full iteration across the edges. So there are probably faster ways to do this check

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Member Author

Hi @dschult and @amcandio, a gentle ping on this one when you have time. I think all review comments are addressed:

  • The strength dicts are dense now, with a glossary of the bookkeeping objects at the top of lpawb_plus_communities (2f4b8d1, 6276e35).
  • lpawb_plus_communities is in doc/reference/algorithms/bipartite.rst (699f174).
  • The redundant edge-count check is gone (04f11d3).

If anything else stands out I'm happy to do another round.

This branch has not been deployed

No deployments
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