Skip to content

ENH: Add Barber's bipartite modularity quality function - #8618

Merged
rossbar merged 9 commits into
networkx:mainfrom
jtorrents:bipartite-modularity
Apr 30, 2026
Merged

rossbar merged 9 commits into
networkx:mainfrom
jtorrents:bipartite-modularity

Conversation

@jtorrents

Copy link
Copy Markdown
Member

Add bipartite.modularity implementing Barber's Q_B (2007) as a quality function for bipartite community partitions. The implementation uses the community-sum form

Q_B = sum_c [ L_c/m - gamma * k_c * d_c / m^2 ]

where k_c and d_c are the degree sums of the red and blue nodes in community c. This mirrors the per-community form used by nx.community.modularity but with a bipartite null model: the product of two distinct degree sums rather than the square of a single one.

References:

  • Barber, M. J. (2007). Modularity and community detection in bipartite networks. Phys. Rev. E 76, 066102.

For context and roadmap see the discussion at #8610

AI disclaimer: I used claude to format and proof read (with minor edits, specially the math) the docstrings.

Add `bipartite.modularity` implementing Barber's Q_B (2007) as a
quality function for bipartite community partitions. The
implementation uses the community-sum form

    Q_B = sum_c [ L_c/m - gamma * k_c * d_c / m^2 ]

where k_c and d_c are the degree sums of the red and blue nodes in
community c. This mirrors the per-community form used by
`nx.community.modularity` but with a bipartite null model: the
product of two distinct degree sums rather than the square of a
single one.

References:
- Barber, M. J. (2007). Modularity and community detection in
  bipartite networks. Phys. Rev. E 76, 066102.
Simplify the internal edge sum by iterating over all community edges
rather than filtering by bipartite side. In a bipartite graph, edges
only exist between the two node sets, so G.edges(comm) with both
endpoints in comm counts each bipartite edge exactly once.

Suggested by @dk-gh in PR review.
Add _bipartite_modularity_delta_partial_eval_{remove,add}, the
bipartite modularity counterpart to the CPM delta helpers introduced
in networkx#8507. They compute the change in Barber's Q_B for moving a single
node between communities without recomputing Q_B over the whole
partition. The invariant

    q_rem + q_add == Q_B(P') - Q_B(P)

is validated against the full quality function over unweighted,
weighted, and random-graph moves. The composition property
q_rem == -add(u, A\{u}) is also tested, confirming compatibility
with the single quality_delta pattern used in networkx#8509.
@jtorrents

Copy link
Copy Markdown
Member Author

I've added a thired commit with the bipartite modularity delta helpers, following the approach @dk-gh suggested in the discussion: getting the delta working in isolation with tests validating the algebra, as was done for CPM in #8507.

The two private helpers are _bipartite_modularity_delta_partial_eval_remove and _bipartite_modularity_delta_partial_eval_add. They compute the change in Q_B when a single node moves between communities, without recomputing the full modularity. The contract is:

q_rem = remove(G, node, A, resolution, weight, nodes=nodes, m=m)
q_add = add(G, node, B, resolution, weight, nodes=nodes, m=m)
q_rem + q_add == Q_B(P') - Q_B(P)

The bipartite delta has a simpler form than the unipartite case because the null-model term k_c * d_c / m**2 is linear in the moving node's contribution (a red node only affects k_c, not d_c, and vice versa). The unified formula for both red and blue nodes is:

q_rem = resolution * deg(u) * opp_deg_sum(A) / m**2 - E_A(u) / m
q_add = E_B(u) / m - resolution * deg(u) * opp_deg_sum(B) / m**2

where opp_deg_sum(C) is the degree sum of the opposite-color nodes in C.

The tests validate the invariant against the full bipartite.modularity for: red and blue node moves, weighted edges, different resolution values, the composition property (remove(u, A) == -add(u, A\{u})), and a random-graph fuzz test over all possible single-node moves.

A couple of notes on the design:

  • The positional prefix (G, node, community, resolution, weight) matches the CPM helpers. The bipartite-specific context (nodes and m) is keyword-only, which I think is a reasonable pattern for quality-function-specific parameters. Note that passing m is necessary to avoid recomputing degree sums in the delta functions (that have to run in a tight loop).
  • Unlike CPM (which is unnormalized), these return m-normalized values matching the Q_B definition. This is a shape difference worth being aware if we end up going for a future unified interface.
  • The helpers follow the remove/add pair convention from Implement Constant-Potts Model (for use with Leiden community detection) #8507. I've also verified the composition property q_rem == -add(u, A\{u}), for compatibility with the single quality_delta pattern currently used in Implement Leiden Community Detection Algorithm #8509.

@dk-gh I'd appreciate your thoughts on the implementation in general, and on whether this shape works for what you're building in #8509, or if there are adjustments that would make integration easier.

As already discussed in #8610 , even if we decide in the end that it's not worth making leiden pluggable with arbitrary delta quality functions, the bipartite modularity deltas will be useful for developing dedicated bipartite_{louvaine,leiden} functions.

@dschult

dschult commented Apr 15, 2026 •

Copy link
Copy Markdown
Member

Can you change the quality functions to be a single function that return the quality difference after combining two disjoint communities? This will usually be 1 community and 1 single node. But Leiden needs to check delta for combining two disjoint communities too. With the admittedly slightly more complex version in place, it will be easy to see what the simpler case should be if performance becomes an issue.

If figuring out how this would work for two communities is tricky, don't worry about it. Just the version that adds a node to a community should be fine for now. :)

@dk-gh

dk-gh commented Apr 15, 2026

Copy link
Copy Markdown
Contributor

Thanks @jtorrents, I'll give my initial thoughts and questions I've had working through this, particularly as it relates to the leiden implementation in #8509. The way I see it, characterising a bipartite graph, there are (at least) two strategies one could follow:

  1. have a colour attribute (or a way of checking colour e.g. your node in nodes), and a degree attribute
  2. have red_degree and blue_degree attributes (which for a bipartite graph, one will be zero)

For a bipartite graph these choices of attribute both encode equivalent information, and your delta functions use a 1)-based approach.

Now the question that I have is: when applying leiden to a bipartite graph, do the aggregated graphs that are formed through each iteration remain bipartite? I think in general the aggregated graphs are no longer bipartite, as each node will represent a community which may be mixture of red and blue.

Therefore, strategy 1) will no longer work when computing barber modularity/delta as we cannot assign each node a single colour. However, strategy 2) does still work and the aggregated red_degree and blue_degree values still make sense as the sum of the constituent node values (and unlike a bipartite graph these can both be non-zero for a node in the aggregate graph). This would be essentially identical to the in_degree and out_degree case for directed unipartite modularity where we have track two degree attributes separately through the aggregation (@jtorrents as you laid out in #8610)

Another way of saying this, is it the case that barber modularity needs to be defined for a partition P of a graph G where the nodes of G have attributes red_degree and blue_degree? Where G is not necessarily a bipartite graph.

If this is the case then for barber modularity we would need to turn

k_c = sum(degree[u] for u in comm & red)

into something like

k_c = sum(red_deg for u, red_deg in G.nodes(data='red_degree') if u in comm)

and the deltas would also need to rely on the colour degree attributes at well.

Overall I really like the opposite colour optimisation for the delta, and my comments are centred around potential leiden integration which obviously isn't the only consideration.

Add a private helper `_bipartite_modularity_merge_delta` that computes
Q_B(P') - Q_B(P) when two disjoint communities A and B are merged:

    merge_delta(A, B) = E(A, B) / m
                     - gamma * (k_A d_B + k_B d_A) / m**2

where k_C and d_C are sums of per-node `red_degree` and `blue_degree`
attributes over the nodes of C, and E(A, B) is the cross-community
edge weight.

The helper reads red/blue degree contributions from node attributes
rather than inferring them from bipartite-set membership. On an
original bipartite graph each node carries its degree in one attribute
and zero in the other; on an aggregated super-node graph (as built by
multilevel optimizers such as Louvain/Leiden) both attributes can be
nonzero and represent the summed contributions of the super-node's
constituents.

Self-loops on aggregated super-nodes are possible: they encode
intra-community edges and are correctly excluded from E(A, B) by the
`v in community_b` filter. `m` is passed in as a graph-level invariant
preserved across aggregation.
@jtorrents

Copy link
Copy Markdown
Member Author

@dschult @dk-gh you're both right, and I missed the forest for the trees. Got absorbed in the algebra of the remove/add pair and overlooked the structural point: in any agglomerative community-detection algorithm on a bipartite graph, only the very first level actually sees a bipartite graph. As soon as Louvain/Leiden collapses communities into super-nodes, the aggregated graph contains nodes that mix red and blue, and the v in nodes check I was using just breaks. Node level red_degree / blue_degree attributes (exactly analogous to in_degree/out_degree for directed modularity) is the only approach that survives aggregation. So the remove/add helpers as originally written were a dead end for agglomeration.

I've pushed a refactor that addresses both comments together:

  1. The _add / _remove pair is gone.
  2. There's now a single _bipartite_modularity_merge_delta(G, A, B, resolution, weight, *, red_degree_attr, blue_degree_attr, m) that computes Q_B(P') - Q_B(P) when two disjoint communities A and B are merged.
  3. It reads red_degree / blue_degree from node attributes rather than checking set membership, so it works unchanged on the original bipartite graph (where each node has one attribute zero and the other equal to its degree) and on aggregated super-node graphs (where both can be nonzero).

The algebra is neat precisely because we're merging rather than moving a single node, and it never has to ask whether a node is red or blue. Starting from Q_B = sum_c [L_c/m - gamma * k_c * d_c / m**2], merging disjoint A and B into A∪B changes only the terms for those two communities. The internal-edge term gives

ΔL/m = (L_{A∪B} - L_A - L_B) / m = E(A, B) / m

and the null-model term, using k_{A∪B} = k_A + k_B and d_{A∪B} = d_A + d_B, gives

Δ(null) = gamma *  [(k_A + k_B)(d_A + d_B) - k_A * d_A - k_B * d_B] / m**2
        = gamma * (k_A * d_B + k_B * d_A) / m**2

so

merge_delta(A, B) = E(A, B) / m − gamma * (k_A * d_B + k_B * d_A) / m**2

Three things worth noting:

  • No color check anywhere. k_C and d_C are just attribute sums over the nodes of C. The function never needs to know which "side" a node belongs to, so it doesn't care whether the graph it's handed is still bipartite.
  • E(A, B) is computed by iterating edges incident to A and keeping those landing in B. Self-loops on aggregated super-nodes (which encode intra-community edges) have both endpoints in A and are correctly excluded.
  • m stays a graph-level invariant under aggregation (total weighted edge count is preserved when a community collapses to a self-loop), so it remains safe to pass in once and reuse.

The tests have been rewritten around this. In particular there's a test_aggregated_supernode_graph case that takes a small bipartite graph, partitions it, builds the 2-node aggregated graph by hand (super-nodes carrying summed red_degree / blue_degree, self-loops for intra-community weight, a cross-edge for inter-community weight), and asserts that _merge_delta returns the same value on the leaf graph and the aggregated graph.

Compute the red/blue degree sums for A and B by iterating over the
community members and looking up node attributes directly, rather than
scanning all of G.nodes and filtering with `v in community`. The
complexity of the degree-sum step drops from O(|V|) to O(|A| + |B|).

This matters because _bipartite_modularity_merge_delta is designed to
run in the inner loop of multilevel optimizers (Louvain/Leiden), where
candidate communities are typically much smaller than the graph and
the helper is invoked many times per node visit.
@jtorrents

Copy link
Copy Markdown
Member Author

Pushed a small performance follow-up to _bipartite_modularity_merge_delta. The four degree sums were iterating over all of G.nodes and filtering with v in community_a/b, making them O(|V|) per call. Since this helper is meant to run in the inner loop of Louvain/Leiden, where candidate communities are typically much smaller than the graph. I switched to iterating over the community members directly and looking up the attribute on each node. Complexity drops from O(|V|) to O(|A| + |B|) for the degree-sum step:

nodes = G.nodes
k_a = sum(nodes[v].get(red_degree_attr, 0) for v in community_a)
d_a = sum(nodes[v].get(blue_degree_attr, 0) for v in community_a)
k_b = sum(nodes[v].get(red_degree_attr, 0) for v in community_b)
d_b = sum(nodes[v].get(blue_degree_attr, 0) for v in community_b)

Benchmarked on random bipartite graphs across a spectrum of community sizes, simulating the Louvain/Leiden agglomeration from singletons to late-stage merges (|V|/4). Speedups (old / new):

|V| singletons size=3 sqrt|V| |V|/10 |V|/4
500 29x 25x 6x 3.1x 1.8x
1000 81x 50x 8x 3.2x 1.8x
2500 191x 115x 12x 3.1x 1.7x
5000 408x 227x 16x 3.0x 1.6x

The new version is never slower. Early iterations benefit the most, with speedups growing with |V| (the old version's O(|V|) cost dominates). Late stages still show a 1.6–1.8x win from avoiding the NodeDataView + full-graph scan overhead.

Benchmark script
"""Benchmark across community sizes to simulate agglomeration stages:
- early:  singletons / size-3 near-singletons
- mid:    communities ~ sqrt(|V|)
- late:   large communities, |A| ~ |V|/10, |V|/4
"""

import random
import time

import networkx as nx
from networkx.algorithms.bipartite.community import _bipartite_modularity_merge_delta


def set_bipartite_degree_attrs(G, red):
    for v in G:
        deg = G.degree(v)
        if v in red:
            G.nodes[v]["red_degree"] = deg
            G.nodes[v]["blue_degree"] = 0
        else:
            G.nodes[v]["red_degree"] = 0
            G.nodes[v]["blue_degree"] = deg


def merge_delta_old(
    G, A, B, resolution, weight="weight",
    *, red_degree_attr="red_degree", blue_degree_attr="blue_degree", m,
):
    rn = G.nodes(data=red_degree_attr, default=0)
    bn = G.nodes(data=blue_degree_attr, default=0)
    k_a = sum(rd for v, rd in rn if v in A)
    d_a = sum(bd for v, bd in bn if v in A)
    k_b = sum(rd for v, rd in rn if v in B)
    d_b = sum(bd for v, bd in bn if v in B)
    E = sum(wt for _, v, wt in G.edges(A, data=weight, default=1) if v in B)
    return E / m - resolution * (k_a * d_b + k_b * d_a) / m**2


def bench(G, m, comm_size, n_pairs, n_calls):
    all_nodes = list(G)
    rng = random.Random(42)
    pairs = []
    for _ in range(n_pairs):
        s = rng.sample(all_nodes, 2 * comm_size)
        pairs.append((set(s[:comm_size]), set(s[comm_size:])))

    for A, B in pairs[:5]:
        merge_delta_old(G, A, B, 1, weight=None, m=m)
        _bipartite_modularity_merge_delta(G, A, B, 1, weight=None, m=m)

    t0 = time.perf_counter()
    for _ in range(n_calls):
        for A, B in pairs:
            _bipartite_modularity_merge_delta(G, A, B, 1, weight=None, m=m)
    t_new = time.perf_counter() - t0

    t0 = time.perf_counter()
    for _ in range(n_calls):
        for A, B in pairs:
            merge_delta_old(G, A, B, 1, weight=None, m=m)
    t_old = time.perf_counter() - t0

    return t_old, t_new


def run(G, red, m, comm_size, n_pairs, n_calls, label):
    t_old, t_new = bench(G, m, comm_size=comm_size, n_pairs=n_pairs, n_calls=n_calls)
    total = n_pairs * n_calls
    print(
        f"  {label:12s}  |A|=|B|={comm_size:>5}  "
        f"calls={total:>6}  "
        f"old={t_old*1000:8.1f} ms  new={t_new*1000:8.1f} ms  "
        f"speedup={t_old/t_new:6.2f}x"
    )


def run_across_stages(n):
    n_red = n_blue = n // 2
    G = nx.bipartite.random_graph(n_red, n_blue, 10.0 / n, seed=0)
    red = {x for x, d in G.nodes(data=True) if d["bipartite"] == 0}
    set_bipartite_degree_attrs(G, red)
    m = sum(G.degree(v) for v in red)

    print(f"\n|V|={n}  |E|={G.number_of_edges()}")
    run(G, red, m, comm_size=1,        n_pairs=500, n_calls=20, label="singletons")
    run(G, red, m, comm_size=3,        n_pairs=500, n_calls=20, label="size=3")
    run(G, red, m, comm_size=max(4, int(n ** 0.5)),
        n_pairs=500, n_calls=20, label="size=sqrt|V|")
    run(G, red, m, comm_size=n // 10,  n_pairs=200, n_calls=10, label="size=|V|/10")
    run(G, red, m, comm_size=n // 4,   n_pairs=100, n_calls=5,  label="size=|V|/4")


if __name__ == "__main__":
    for n in (500, 1000, 2500, 5000):
        run_across_stages(n)

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

This looks good!! Thanks!

I've just a couple fo comments below. I've gone through tetss, docs and code so it should be close to ready for approval. :)

Comment on lines +167 to +168
community_a,
community_b,

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.

Sometimes uppercase, A, B are used to denote the communities and other times lowercase a and b are used. Is there reason we don't just use one choice?

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.

Well, community_{a,b} are parametres, and pep8 specifies that they should be lowercase. I'm now using monospaced/backticks for community_{a,b} to separate "math object" from "Python identifier". What do you think?

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.

sounds good!

*,
red_degree_attr="red_degree",
blue_degree_attr="blue_degree",
m,

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 haven't checked performance, and it definitely doesn't matter in this PR, but the modularity formula gives the same result if we scale all edge weights by m: G[u][v].get(weight, 1) / m. This might help performance in the inner loops where delta is computed. We'd have to do |E| divisions up front to avoid 3 divisions per call of q_delta. I think Leiden has so many calls to q_delta (it starts with a singleton partition and merges repeatedly) that saving the divisions in q_delta is worth the extra weight-scaling divisions. But I haven't checked that.

Let's leave this as is for this PR. We can change it later if that ends up being the right approach.

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.

Sounds good.

Address @dschult  review comments on PR networkx#8618:

- Correct "bipartite incidence matrix" -> "bipartite adjacency
  matrix" in the Q_B definition (nodes x nodes, not nodes x edges)
- Note that the default resolution=1 recovers Barber's original
  definition.
- Shorten the See Also reference from the full path to just
  `modularity`.
- Collapse the merge_delta closed-form onto a single line.
- Use backticked `community_a` / `community_b` for parameter
  references in prose and keep uppercase A/B/C for math notation,
  so the two no longer mix.
Address review feedback on PR networkx#8618. Neither `bipartite.modularity`
nor `_bipartite_modularity_merge_delta` excludes MultiGraph inputs,
and both use NetworkX idioms (`G.degree(weight=...)`,
`G.edges(nbunch, data=..., default=...)`) that already iterate
parallel edges correctly. Add hand-computed tests that pin this
behavior down:

- TestBipartiteModularity.test_multigraph: parallel edges contribute
  to both the degree sums and L_c.
- TestBipartiteModularityMergeDelta.test_multigraph: parallel edges
  contribute to E(A, B) and the result matches the full-Q reference.

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

I approve this PR -- Thanks @jtorrents (and @dk-gh for review)

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

Generally LGTM, though I'm relying heavily on @dschult and @dk-gh 's reviews for a deeper understanding of the computation itself!

The only thing I think should be resolved before merge is making some of the arguments for the public-facing function keyword-only. I think before weight is a natural place to put the *, but I leave it up to you if you prefer to be more aggressive!

One high-level comment: the rest of the bipartite module uses "top" and "bottom" to label partitions in the docs as opposed to "red" and "blue". The terminological issue doesn't block this PR, but it's worth considering whether we want to maintain wording consistency. Happy to merge as-is and create a follow-up issue!

Address review feedback on PR networkx#8618:
- Make `weight` and `resolution` keyword-only on the public `modularity()`.
- Use `nx.bipartite.modularity` in the doctest example instead of importing
  `bipartite` from `networkx.algorithms`.
@jtorrents

Copy link
Copy Markdown
Member Author

Thanks @rossbar for the review!

I've done the keyword-only change. Agreed that weight and resolution are a natural fit for keyword-only on the public API. I'll keep nodes positional since it's required and structurally part of the call (you can't meaningfully omit it for a bipartite quality function). I've also pushed the doctest tweak (nx.bipartite.modularity(...) instead of the import); it's cleaner.

On the terminology question (top/bottom vs red/blue), I think it's worth keeping "red/blue" here even at the cost of internal inconsistency with the rest of the bipartite subpackage. The "top/bottom" terminology comes from following Latapy et al.'s review paper on bipartite networks, which is the dominant reference for the clustering coefficients and projection methods in the subpackage; so "top/bottom" makes sense there.

The bipartite-modularity literature, however, has settled on "red/blue". The clearest example is the Beckett 2016 paper ("Improved community detection in weighted bipartite networks", which introduces LPAwb+ and DIRTLPAwb+ algorithms). I'm planning to follow up with an implementation of LPAwb+ (and maybe DIRTLPAwb+) from Beckett 2016. Beckett is foundational for this part of the field, and once we start working on those algorithms the choice of terminology will make a lot more sense: the red/blue language threads through the algorithm itself (the alternating red/blue label-propagation stages, the red/blue label matrices). Aligning with Barber/Beckett's terminology in the modularity-and-community part of the submodule, while keeping Latapy's top/bottom in the clustering/projection submodules, gives readers a 1-to-1 mapping with the paper they'd reach for in each case.

So my suggestion for the follow-up work on bipartite communities would be: document the deliberate split (top/bottom after Latapy for clustering/projections; red/blue after Barber/Beckett for modularity and community detection) rather than try to unify, since unifying in either direction makes one of the two halves of the package read further from its source literature.

Happy to discuss this further, and of course I'll defer if you and @dschult prefer the unified-terminology direction.

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

Great, thanks @jtorrents for the background! It's interesting backstory re: terminology - either way, not a blocker here!

I took the liberty of pushing up one final change: adding the new function to the reference guide (I missed this the last time through). Thanks again @jtorrents @dk-gh and @dschult !

@rossbar
rossbar merged commit 2486132 into networkx:main Apr 30, 2026
44 checks passed
@dschult dschult added this to the 3.7 milestone Apr 30, 2026
@jtorrents

Copy link
Copy Markdown
Member Author

Thanks @rossbar !

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.

4 participants