Skip to content

Implement Constant-Potts Model (for use with Leiden community detection) - #8507

Merged
rossbar merged 28 commits into
networkx:mainfrom
dk-gh:implement_cpm
Feb 26, 2026
Merged

rossbar merged 28 commits into
networkx:mainfrom
dk-gh:implement_cpm

Conversation

@dk-gh

@dk-gh dk-gh commented Feb 9, 2026 •

Copy link
Copy Markdown
Contributor

This PR is a small component related to the larger PR gh-8505 which is being split into at least three smaller PRs.

This PR implements the Constant-Potts Model quality function for partitions constant_potts_model. This is the quality function typically used by default in the leiden community detection algorithm. This has been implemented along with the leiden algorithm, details can be found in #8505, and this will be submitted as a separate PR.

@dschult

dschult commented Feb 9, 2026

Copy link
Copy Markdown
Member

The circle CI tests were failing because this PR is started from an old version of the main branch that doesn't have our fix of the doc-creation troubles. So I merged this PR with main. (That's an easy button push on github.) BUT: this means you will need to pull from this branch on your fork back down to your local repo before making further changes. (!!)

Should be just (while at the implement_cpm branch locally):

git pull <fork-remote-nickname> implement_cpm

@dk-gh

dk-gh commented Feb 9, 2026

Copy link
Copy Markdown
Contributor Author

Thanks

@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! And its a size I can bite for review. :)

I have a few nit-picky comments -- most are suggestions to improve readability, which is a judgement call anyway. So think of them as suggestions and make changes or not accordingly. (the dict form of attribute assignment could be used in other places than I suggested)

@dk-gh

dk-gh commented Feb 10, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the comments and feedback.

Still welcome further comments on the doc string for constant_potts_model.

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

I have a high-level question: do you envision constant_potts_model to be used generally, or is it intended mostly for internal use w.r.t louvain/leiden?

The answer can help inform how best to integrate the functionality. For example, if this is really only intended for use within leiden and/or louvain, then it might make more sense to make this a private function (i.e prefixed with _) and perhaps simplify the API (i.e. get rid of the is_partition checks and/or the allow_partial).

If the goal is general use, then a follow-up questions becomes: how does this differ from partition_quality? And... should this be an independent function, or should it be an option to existing functions (e.g partition_quality(..., method="constant_potts"))?

@dk-gh

dk-gh commented Feb 11, 2026 •

Copy link
Copy Markdown
Contributor Author

In my most recent commit in PR #8509 I have changed the way the quality deltas are computed within leiden, which changes the role that quality_function e.g. constant_potts_model plays in the algorithm: now, at the beginning of leiden_partitions, the quality_function is used to set a pair of delta functions -- one measuring the quality cost of removing a node from a community, and another for measuring the quality cost of adding a node to a community. These delta functions then do the heavy lifting throughout the algorithm, with original quality_function only being invoked between iterations.

The idea is that for common quality functions like CPM or modularity, the pair of add/remove delta functions can be more highly optimised (i.e. using a more efficient formula, and without any assert overhead), however the leiden algorithm will still accept any suitable quality function for the quality_function parameter, with the associated delta functions being defined on the fly (using the basic quality_delta = quality_after - quality_before formulae) if a known optimised version doesn't exist. To define the pair of delta functions on the fly like this, the quality function API needs the allow_partial parameter, so I think this should be a requirement for any future quality functions to be compatible with leiden/louvain.

The allow_partial parameter is also useful when writing tests, particularly around optimising the delta functions.

The pre-defined and optimised delta functions are likely only ever to be used within leiden/louvain and would make sense to have as private functions, but to me it makes sense to expose constant_potts_model, modularity etc. as functions available in other contexts, and therefore worth keeping the is_partition guardrail.

Regarding your questions on partition_quality, I'm really not sure at this point.

@dschult

dschult commented Feb 12, 2026

Copy link
Copy Markdown
Member

Just FYI, I think it is worth thinking about removing the is_partition check inside all quality measures. We'd have to deprecate the old behavior and give people time to convert to calling is_partition themselves if they need/want that behavior. The two facts seem to be orthogonal 1) the quality of a stated community structure within a given graph (that could be larger than the specified community) and 2) whether the provided community structure is a partition of the graph.

The advantage of removing all such checks is that we don't need to introduce any allow_partial keyword cruft. And there doesn't seem to be a reason these concepts need to be combined.

I guess the key question here is "what happens if someone provides a communities input that has overlapping communities. That is, are quality measures dependent on the communities being disjoint? If so, let's change the is_partition test to making sure the community sets are disjoint. If not, I propose we remove the is_partition check from the quality measures.

@dk-gh do you know what happens to say modularity or cpm if the communities are overlapping sets?

@dk-gh

dk-gh commented Feb 12, 2026

Copy link
Copy Markdown
Contributor Author

I only included the is_partition check inside constant_potts_model because it was there in modularity and I wanted to keep the APIs as consistent as possible. I think it makes to either keep it as a requirement for all quality functions, or remove for all -- I think I would lean towards removing it, and doing away with allow_partial.

My understanding is that, by definition, a partition must consist of disjoint communities. It looks like is_partition would fail for non-disjoint communities as the sum(len(c) for c in communities) would exceed len(G) (the doc string also specifies disjoint communities).

From what I can see all/most partition quality functions Q(G, P) -- including CPM and modularity -- are of the form Q(G, P) = sum(q(G, C) for C in P) where q(G, C) is a community-level quality function.

If P has overlapping communities then Q(G, P) would still return a value for constant_potts_model (and for modularity if we remove the check) but I don't really know how to interpret the meaning of this value -- the final value would be effectively double-counting the contributions of the duplicated nodes, i.e. if u in C1 and u in C2 then we would have Q(G, P) = q(G, C1) + q (G, C2) + ...

…algorithm when computing cpm deltas as nodes are moved between communities.
@dk-gh

dk-gh commented Feb 12, 2026 •

Copy link
Copy Markdown
Contributor Author

I have added two new delta functions _constant_potts_model_add_cost and _constant_potts_model_remove_cost. Applying some basic algebra, these follow more efficient formulae to compute the cost of adding a single node to a community, and removing a node from a community respectively.

The leiden algorithm can be made to invoke these optimised add/remove cost functions -- this can be seen in #8509. If leiden receives a quality_function that doesn't have corresponding optimised add/remove cost functions, then it will simply use the quality_function to define these functions on the fly (using the same method that the tests use to check that the add/remove costs match the expected values based on using constant_potts_model directly)

Fundamentally, leiden no longer needs the allow_partial feature for the sake of efficiency, although being able to evaluate on communities that are not a full partition is still useful, so I still lean towards removing the is_partition check.

From some basic profiling, the majority of execution time for the leiden algorithm is spent in _constant_potts_model_add_cost (particularly during the _move_nodes_fast stage).

@dschult

dschult commented Feb 13, 2026

Copy link
Copy Markdown
Member

Niiiice!!!

It seems to me that the delta for adding a node to the community should just be the negative of the delta for removing it from the community. So maybe we only need one function. Can you check that?

Also, does Leiden (or Louvain) actually need the quality function itself? I guess it is called to look for improvement between levels. I'd prefer to the API to avoid prescribing both main function and the efficient delta function. Thoughts?

@dk-gh

dk-gh commented Feb 14, 2026

Copy link
Copy Markdown
Contributor Author

You're right that the cost of removing u from A is simply the negative of the cost of adding u to A-{u}, but it's not obvious to me that combining into one function will be more elegant, as there's some information implicit in the way these are called i.e. constant_potts_model_remove_cost(G, u, A) assumes that u in A. Whereas the add function assumes u not in B. I think to combine into one function we would have to either always add u to A, then calculate the cost of removing (or remove and calculate the cost of adding). Either way, I think this will incur some additional overhead.

Another reason I'd like to keep them separate is that the cost of adding nodes the most critical aspect for performance, so I would want to be able to optimise the add and remove functions separately (for example, there might be a way to pre-compute values for even faster add cost functions defined at each iteration of _move_nodes_fast).

The leiden algorithm will only use the quality_function to compute the value at the end of each iteration to measure the overall change (to determine whether it's time to stop). I think from the user perspective, the API should only reference quality_function -- the efficient delta functions are an implementation detail and not something passed explicitly by the user. The leiden_communities function will determine at runtime which delta functions to use, either invoking the efficient delta functions (if they exist), or defining the delta functions on the fly -- this is handled by the function _get_quality_add_cost(quality_function) in the latest commit in #8509.

This will be updated so that _get_quality_add_cost(constant_potts_model) returns the _constant_potts_model_add_cost function from this PR.

Using the _get_quality_add_cost method means the user can pass any quality function (as long as it has the same API as constant_potts_model).

@dschult

dschult commented Feb 16, 2026

Copy link
Copy Markdown
Member

Interesting perspective. I'm still wrapping my head around how an add_cost function could be optimized in a way that remove_cost would not. Hope that works.

I'm looking forward to your other ideas to improve this. I was envisioning that we make a function for add_cost(G, u, A). Then to find Q_delta we use:
add_cost(G, u, A) - add_cost(G, u, B-{u})
Aside: Why are we calling this "cost"? It's not a cost right?

The problem with looking up the add_cost function based on the quality function is that we can only use our known add_cost functions. The user can't specify an add_cost function. Only the quality function. Is there a way users could plug into the get_quality_add_cost lookup table? I'm not sure that is a good API. Probably better to have two keyword args. Or maybe:

  • make a big function with many options
  • make a function that calls the big function for modularity
  • make a function that calls the big function with cpm
    Then people who want to play with others would use the big function directly while other just use the one with the quality function already specified.

Still looking for best API...

@dk-gh

dk-gh commented Feb 16, 2026

Copy link
Copy Markdown
Contributor Author

@dschult I agree "cost" is not necessarily the best term for this -- I also used "contribution" thinking in terms of the overall contribution to the q_delta value.

In terms of the API, I would include the pair of "cost" functions (or whatever terminology we settle on) as kwargs, with default being None, in which case the leiden_communities will handle setting or creating on the fly as appropriate, while still giving the option to pass user-defined optimisations (I do wonder how much this feature would actually be used though).

dk-gh and others added 2 commits February 16, 2026 19:04
…es to tests to reflect this. Also removed the allow_partial parameter from cpm, as it will no longer be required for leiden
…nclude self-loops in tests to ensure cancellations of terms in partial evaluations are correct

@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'm still not convinced we should have separate functions for add and remove. But let's figure that out when we see how the Leiden algorithm interfaces with this. We can change it in that PR if needed.

I think these are my final comments on the CPM function PR.... but no promises. :} Anyway, we're close...

We need to turn on the documentation for constant_potts_model. Add it to the file doc/reference/algorithms/community.rst in the section for measuring partitions. You can check if it looks good after the CI is completed using the "view details" link for the test named "documentation artifact".

Why are we constructing the set community - {node} twice inside the remove function? Maybe just call the add function with community- {node} and negate the answer? At least store the new set and use it twice instead of constructing it twice. :)

@dk-gh

dk-gh commented Feb 18, 2026

Copy link
Copy Markdown
Contributor Author

I'm still not convinced we should have separate functions for add and remove. But let's figure that out when we see how the Leiden algorithm interfaces with this. We can change it in that PR if needed.

I agree with this approach. I feel like you probably are right about reusing the add function for remove, but these functions only exist to support leiden, so makes sense to think about these as part of that PR.

We need to turn on the documentation for constant_potts_model. Add it to the file doc/reference/algorithms/community.rst in the section for measuring partitions. You can check if it looks good after the CI is completed using the "view details" link for the test named "documentation artifact".

I have added this.

Why are we constructing the set community - {node} twice inside the remove function? Maybe just call the add function with community- {node} and negate the answer? At least store the new set and use it twice instead of constructing it twice. :)

Fixed the duplicate construction within the remove function.

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

The quote in the doc_string is being formatted strangely with the first line bigger and Boldface. I think the quotation mark is not aligned with the rest of the paragraph, so the text->html machinery (Sphinx) is interpreting is differently.

Since the indentation makes it a "quotation" you can probably leave off the double quotes around it. At least in a textbook that's how they would do it. If you prefer to leave the double quotes that is fine, but add a space before the 1st one so it treats the whole thing as one quotation.

I approve this PR

@dk-gh

dk-gh commented Feb 18, 2026

Copy link
Copy Markdown
Contributor Author

The quote in the doc_string is being formatted strangely with the first line bigger and Boldface. I think the quotation mark is not aligned with the rest of the paragraph, so the text->html machinery (Sphinx) is interpreting is differently.

Since the indentation makes it a "quotation" you can probably leave off the double quotes around it. At least in a textbook that's how they would do it. If you prefer to leave the double quotes that is fine, but add a space before the 1st one so it treats the whole thing as one quotation.

Thanks, I've removed the quote marks from the indented quotation -- hopefully this looks OK now

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

This LGTM, thanks again @dk-gh and @dschult for the review!

@rossbar
rossbar merged commit fa30c16 into networkx:main Feb 26, 2026
38 checks passed
@dschult dschult added this to the 3.7 milestone Feb 26, 2026
jtorrents added a commit to jtorrents/networkx that referenced this pull request Apr 15, 2026
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.
rossbar added a commit that referenced this pull request Apr 30, 2026
* ENH: Add Barber's bipartite modularity quality function

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.

Suggested by @dk-gh in PR review.

* ENH: Add partial-evaluation delta helpers for bipartite modularity

Add _bipartite_modularity_delta_partial_eval_{remove,add}, the
bipartite modularity counterpart to the CPM delta helpers introduced
in #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 #8509.

* ENH: Add bipartite modularity merge-delta helper

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.

* Speed up bipartite modularity merge-delta inner loop

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.

* DOC: Add new module/fn to ref guide.

---------

Co-authored-by: Ross Barnowski <[email protected]>
Co-authored-by: Dan Schult <[email protected]>
Co-authored-by: evk <[email protected]>
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