Skip to content

ENH: Add Shen's overlapping modularity quality function - #8647

Merged
rossbar merged 2 commits into
networkx:mainfrom
jtorrents:overlapping-modularity
May 14, 2026
Merged

rossbar merged 2 commits into
networkx:mainfrom
jtorrents:overlapping-modularity

Conversation

@jtorrents

@jtorrents jtorrents commented May 2, 2026 •

Copy link
Copy Markdown
Member

Add nx.community.overlapping_modularity implementing Shen et al.'s extended modularity EQ (2009) as a quality function for overlapping community covers. The implementation uses the community-sum form

EQ = sum_i [ L_tilde_C / m - gamma * (k_tilde_C / 2m)^2 ]

where L_tilde_C is the overlap-discounted intra-community edge count (each edge weighted by 1/(O_v * O_w) with O_v the number of communities containing v) and k_tilde_C is the overlap-discounted degree sum. This mirrors the community-sum form used by nx.community.modularity with overlap-discounted quantities replacing the raw counterparts. When the cover is just a partition (O_v = 1 for all v), EQ reduces to Q exactly.

Also add nx.community.is_cover, the cover-equivalent of is_partition: a cover requires every node in G to belong to at least one community, but allows overlap. Used internally to validate input to overlapping_modularity, exposed publicly for users (e.g. to sanity-check the output of k_clique_communities before scoring).

The resolution parameter gamma is not in Shen's original definition; it is added for consistency with modularity(resolution=...). With gamma=1 the formula is exactly Shen's EQ.

Tests cover equivalence with standard modularity on partition inputs, hand-calculated EQ values for a triangle under several covers, weighted hand-calculation, k_clique_communities integration, resolution parameter monotonicity, and the usual edge cases (directed not implemented, empty graph, weight=None, invalid cover).

Add `nx.community.overlapping_modularity` implementing Shen et al.'s
extended modularity EQ (2009) as a quality function for overlapping
community covers. The implementation uses the community-sum form

    EQ = sum_i [ L_tilde_C / m - gamma * (k_tilde_C / 2m)^2 ]

where L_tilde_C is the overlap-discounted intra-community edge count
(each edge weighted by 1/(O_v * O_w) with O_v the number of
communities containing v) and k_tilde_C is the overlap-discounted
degree sum. This mirrors the community-sum form used by
`nx.community.modularity` with overlap-discounted quantities replacing
the raw counterparts. When the cover is just a partition
(O_v = 1 for all v), EQ reduces to Q exactly.

Also add `nx.community.is_cover`, the cover-equivalent of
`is_partition`: a cover requires every node in G to belong to at
least one community, but allows overlap. Used internally to validate
input to overlapping_modularity, exposed publicly for users (e.g. to
sanity-check the output of `k_clique_communities` before scoring).

The resolution parameter gamma is not in Shen's original definition;
it is added for consistency with `modularity(resolution=...)`. With
gamma=1 the formula is exactly Shen's EQ.

Tests cover equivalence with standard modularity on partition inputs,
hand-calculated EQ values for a triangle under several covers,
weighted hand-calculation, k_clique_communities integration, resolution
parameter monotonicity, and the usual edge cases (directed not
implemented, empty graph, weight=None, invalid cover).
@jtorrents

Copy link
Copy Markdown
Member Author

This is the third PR in the bipartite/overlapping community detection roadmap from #8610:

  1. ENH: Add Barber's bipartite modularity quality function #8618 : bipartite.modularity (Barber's Q_B). Merged.
  2. ENH: Add Beckett's LPAwb+ bipartite community detection #8645 : bipartite.lpawb_plus_communities (Beckett's LPAwb+). Open.
  3. This PR : overlapping_modularity (Shen et al. 2009 EQ). Independent of ENH: Add Barber's bipartite modularity quality function #8618 and ENH: Add Beckett's LPAwb+ bipartite community detection #8645.

overlapping_modularity is a general-graph quality function alongside nx.community.modularity, intended to score the output of overlapping community-detection algorithms. The only one currently in NetworkX is k_clique_communities; more (e.g. SLPA) are planned for follow-up PRs.

Algebra

Shen et al. (2009) write EQ in the all-pairs form (Eq. 2):

EQ = (1/2m) sum_i sum_{v in C_i, w in C_i} (1/(O_v * O_w)) [A_vw - k_v * k_w / 2m]

This is O(|C|^2) per community, that is, slow for real data, and dominated by the (much sparser) actual edge structure.

This implementation is refactored to the community-sum form, matching what nx.community.modularity already does following Clauset-Newman-Moore:

EQ = sum_i [ L_tilde_C / m - gamma * (k_tilde_C / 2m)^2 ]

where L_tilde_C = sum_{(v,w) in edges of C} 1/(O_v * O_w) is the overlap-discounted intra-community edge count, and k_tilde_C = sum_{v in C} k_v / O_v is the overlap-discounted degree sum.

The derivation is in two steps:

  1. Null-model factoring: 1/(O_v * O_w) = (1/O_v) * (1/O_w), and the inner double sum is over an independent product of v and w over the same set, so sum_{v,w} k_v * k_w / (O_v * O_w) = (sum_v k_v / O_v)^2 = k_tilde_C^2.
  2. Edge-term collapsing: the inner sum over A_vw selects only the |edges in C| nonzero entries, with each undirected edge counted twice (as A_vw and A_wv). Hence sum A_vw / (O_v * O_w) = 2 * L_tilde_C, and the 1/(2m) outer factor leaves L_tilde_C / m.

Result: O(|edges in C| + |C|) per community, same approach as nx.community.modularity. The "EQ on a partition equals Q" tests are the sanity checks that show that this refactoring is correct.

Things worth looking closely

  • Math derivation: docstring "Implementation uses the equivalent community-sum form" section, plus the comment in community_contribution.
  • Single-count edge iteration: G.edges(comm, data=weight, default=1) yields each undirected edge once; the 2 * factor in 2 * L_c_tilde / deg_sum comes from the math (inner double sum), not from double-counting in code. Same idiom as nx.community.modularity.
  • Resolution parameter gamma: not in Shen; added for consistency with modularity(resolution=...). With gamma=1 the formula is exactly Shen's EQ.
  • Multigraphs: supported via NetworkX's standard edge-summation convention. Test test_multigraph round-trips a simple graph through nx.MultiGraph(G) and verifies a parallel edge changes the value (same pattern as test_louvain.test_multigraph).
  • is_cover: cover-equivalent of is_partition. Used internally for input validation; exposed publicly so users can sanity-check k_clique_communities output before scoring the quality of the cover with overlapping_modularity.

Out of scope (deferred to follow-up PRs)

  • Directed overlapping modularity (EQ_D, Nicosia et al. 2009): drop @not_implemented_for("directed") and branch on G.is_directed() like nx.community.modularity does. Math derived in my own working notes, can be planned as the next PR if there is interest. Right now k_clique_communities only supports undirected graphs.

References

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

Very nice! Good topic -- fills a hole we've been neglecting in our community measures. Overlapping communities makes the questions more complicated. But its often a better description of the community structure.

Well written and understandable relative to existing stuff in the networkx community suite. Thanks @jtorrents

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

LGTM, thanks @jtorrents !

The only thing to get in before merging is the keyword-only arguments comment; everything else is just a nit or high-level question!


@not_implemented_for("directed")
@nx._dispatchable(edge_attrs="weight")
def overlapping_modularity(G, communities, weight="weight", resolution=1):

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.

Let's make these keyword-only!

Suggested change
def overlapping_modularity(G, communities, weight="weight", resolution=1):
def overlapping_modularity(G, communities, *, weight="weight", resolution=1):

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.

Done!

Comment on lines +309 to +311
set, but sets may overlap. Accepts the output of
:func:`~networkx.algorithms.community.kclique.k_clique_communities`
directly.

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.

Not a blocker or anything, just satisfying my own curiosity... why is k_clique_communities called out specifically here?

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.

I called it out originally because k_clique_communities is currently the only overlapping community-detection algorithm in NetworkX, so it's the natural producer of input for overlapping_modularity. Future-proofing seemed wise though, so I've generalized the wording to "any NetworkX overlapping community-detection algorithm such as ...".

A bit of context on why future-proofing matters here: I have follow-up PRs planned to add more overlapping community detection algorithms. The most direct one is EAGLE (Shen et al. 2009), the companion algorithm in the same paper that introduced EQ. EAGLE is an agglomerative hierarchical clustering on the set of maximal cliques, and it uses EQ as the cut criterion for its dendrogram. SLPA (Xie et al. 2011) is also on the roadmap as a label-propagation-class overlapping community detection algorithm, complementing EAGLE's agglomerative-hierarchical approach. Both are described in the broader discussion at #8610.

Comment on lines +317 to +320
resolution : float, optional (default=1)
Resolution parameter $\gamma$. Values smaller than 1 favor larger
communities; values greater than 1 favor smaller communities.

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.

It might be worth mentioning (if possible) what impact this has on the number of nodes in multiple communities. The meaning of resolution in modularity is described as a parameter controlling the tradeoff between inter/intra community edges. Is that the same here? Does the degree of overlap between communities vary with this parameter?

Not a blocker, just curious!

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. I've expanded the docstring in the last commit to address this:

  • On community size: resolution behaves exactly like in standard modularity. It scales only the null-model term gamma * (k_tilde_C / 2m)^2, so smaller gamma shrinks the expected-edges penalty and favors larger communities; larger gamma does the opposite.

  • On degree of overlap: independent of resolution in this function: the cover is supplied by the caller, not optimized internally. The overlap-discount factor 1/(O_v O_w) sits outside gamma in the formula, so it isn't rescaled either.

Actually, thinking about this made me realize one interesting thing about the resolution parameter, though it is not relevant to the current API: if someone were optimizing EQ (no such optimizer exists in NetworkX yet), resolution would change which cover scores best. Because resolution rescales k_v k_w / 2m but the 1/(O_v O_w) discount is not scaled, higher resolution penalizes the null-model contribution of high-degree (hub) nodes the most, making it less attractive to place them in multiple communities. Conversely, lower resolution would let hubs spread across communities more cheaply. This is a property of resolution's interaction with the EQ formula, not a property of the current scoring function, so I've left it out of the docstring.

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.

Correction to my previous comment ;) I had the sign of the hub effect reversed. Higher resolution makes hub-spreading more attractive under optimization, not less.

Sketch: a node v's contribution to sum_C (k_tilde_C / 2m)^2, summed over the O_v communities containing it, is

sum_{C ∋ v}  γ * (k_v / O_v)^2 / (2m)^2  =  γ * k_v^2 / (O_v * (2m)^2)

which decreases in O_v. So increasing O_v saves null-model penalty, and resolution scales the size of those savings.

Quick check on a star (hub h, 4 leaves, m = 4):

  • One community {h, l1, l2, l3, l4}: EQ = 1 - γ
  • Two communities {h, l1, l2}, {h, l3, l4}, O_h = 2: EQ = 1/2 - γ/2

Difference (1 - γ)/2: at resolution < 1 the non-overlapping cover wins, at resolution > 1 the spread cover wins.

Intuition: higher resolution -> bigger absolute null-model penalty -> bigger savings from anything that shrinks k_tilde_C, and spreading high-degree nodes does exactly that. None of this affects the current API or docstring (the cover is input, not optimized). Just flagging the corrected direction for the record.

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 initially struggled understanding resolution's relationship to community size (in modularity itself) and could only convince myself after trying it out with examples. The fact that modularity goes negative relatively quickly with increasing resolution also surprised me :). There's clearly lots to learn about for me on the community detection front!

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.

The "goes negative quickly" thing tripped me up too the first time. The intuition that finally stuck for me:

For any community C, the edge-term contribution L_C/m is bounded above by 1 (when C is the whole graph), but the null-term γ * (k_C/2m)^2 is also bounded above by γ (same case). So the trivial single-community cover gives Q = 1 - γ, that is, already negative for any γ > 1, regardless of how clustered the graph actually is. And for non-trivial covers the edge term is smaller while the null term is still quadratic in the per-community degree sum, so the crossover into negative territory happens even faster.

The deeper reason this matters is Fortunato & Barthélemy's (2007) resolution limit (https://doi.org/10.1073/pnas.0605965104): at γ=1, modularity can't resolve communities smaller than ~sqrt(2m) edges, no matter how well-separated they are. Tuning resolution up shrinks that floor (lets you detect smaller communities) at the cost of fragmenting larger ones; tuning it down does the opposite. Reichardt & Bornholdt's (2006) statistical-mechanics derivation (https://arxiv.org/abs/cond-mat/0603718) frames it as picking the scale at which you're looking for structure, which I find a better way to think about it than "tradeoff parameter."

Comment on lines +377 to +381
membership = {}
for community in communities:
for node in community:
if node in G:
membership[node] = membership.get(node, 0) + 1

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.

Using a defaultdict here makes the updating a little clearer:

Suggested change
membership = {}
for community in communities:
for node in community:
if node in G:
membership[node] = membership.get(node, 0) + 1
membership = defaultdict(int)
for community in communities:
for node in community:
if node in G:
membership[node] += 1

Also not a blocker :)

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.

Done!

Make weight and resolution keyword-only, switch to defaultdict
for membership counting, generalize the k_clique_communities
reference, and clarify the effect of the resolution parameter.

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

Thanks for taking the time to address my questions - interesting stuff! LGTM!

@rossbar
rossbar merged commit a860184 into networkx:main May 14, 2026
44 checks passed
@dschult dschult added this to the 3.7 milestone May 14, 2026
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