Repository navigation
ENH: Add Barber's bipartite modularity quality function - #8618
Conversation
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.
|
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 The bipartite delta has a simpler form than the unipartite case because the null-model term where The tests validate the invariant against the full A couple of notes on the design:
@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. |
|
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. :) |
|
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:
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 Another way of saying this, is it the case that barber modularity needs to be defined for a partition If this is the case then for barber modularity we would need to turn
into something like
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.
|
@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 I've pushed a refactor that addresses both comments together:
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 and the null-model term, using so Three things worth noting:
The tests have been rewritten around this. In particular there's a |
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.
|
Pushed a small performance follow-up to 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):
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
left a comment
There was a problem hiding this comment.
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. :)
| community_a, | ||
| community_b, |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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?
| *, | ||
| red_degree_attr="red_degree", | ||
| blue_degree_attr="blue_degree", | ||
| m, |
There was a problem hiding this comment.
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.
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
left a comment
There was a problem hiding this comment.
I approve this PR -- Thanks @jtorrents (and @dk-gh for review)
rossbar
left a comment
There was a problem hiding this comment.
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`.
|
Thanks @rossbar for the review! I've done the keyword-only change. Agreed that 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
left a comment
There was a problem hiding this comment.
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 !
|
Thanks @rossbar ! |
Add
bipartite.modularityimplementing Barber's Q_B (2007) as a quality function for bipartite community partitions. The implementation uses the community-sum formwhere 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.modularitybut with a bipartite null model: the product of two distinct degree sums rather than the square of a single one.References:
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.