Skip to content

Implement Leiden Community Detection Algorithm - #8509

Merged
dschult merged 135 commits into
networkx:mainfrom
dk-gh:implement_leiden_only
May 12, 2026
Merged

dschult merged 135 commits into
networkx:mainfrom
dk-gh:implement_leiden_only

Conversation

@dk-gh

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

Copy link
Copy Markdown
Contributor

This PR is related to the larger PR #8505 which has been split up into (at least three) smaller PRs.

This PR follows from PR #8507 which implemented the Constant Potts Model, which is a measure of the quality of a partition of a graph. The leiden algorithm uses Constant Potts Model by default. In principle another measure of quality could be used, for example, modularity, however the existing implementation of modularity will not work in its current form (see PR #8505 for further details).

This implementation of leiden is an adaptation of the existing louvain implementation, and closely follows the pseudocode from the original leiden paper [1]. One difference from the paper is this implementation allows arbitrary weights on nodes, and the weight of a node in the aggregated graphs is the sum of the weights of the nodes it contains (rather than just being a count of the number of nodes).

Because the leiden algorithm is probabilistic (randomness both in the order that nodes are visited,in _move_nodes_fast and also in how communities are chosen in the _refine_partition stage), it is not possible to verify the correctness simply using known inputs and expected outputs (some further discussion of this in PR #8505).

Therefore I think the main goal at this stage needs to be verifying the correctness of the algorithm. Once correctness is verified then further tests can be written for specific inputs and their expected outputs, and then improvements (e.g. performance) made without changing the behaviour.

I haven't done any serious profiling or benchmarking for performance -- this would be a subsequent step once the correctness of the algorithm has been verified.

Note on file changes

Changes to the following files have been merged in from PR #8507, which has already been reviewed:

quality.py
test_quality.py

This PR is specifically focused on the leiden algorithm and corresponding tests which are found it:

leiden.py
test_leiden.py

[1] "From Louvain to Leiden: guaranteeing well-connected communities" Vincent Traag, Ludo Waltman, Nees Jan van Eck https://arxiv.org/abs/1810.08473

Leiden based community detection algorithms are now supported via
`leiden_communities` and `leiden_partitions`. This provides an
alternative, often improved, community detection algorithm compared
to the Louvain functions.

dk-gh and others added 22 commits February 8, 2026 22:57
…ity_add_cost, rather than using quality_function directly. By default it still uses the underlying quality functions, but these can be easily swapped for optimised expressions for specific quality functions.
@dk-gh

dk-gh commented Feb 11, 2026 •

Copy link
Copy Markdown
Contributor Author

@dschult following the discussion around quality deltas in #8505, I have been thinking more about this and I have changed the approach here so that _move_nodes_fast and _refine_partition no longer use the quality_function, but rather use a pair of new functions: quality_remove_cost; and quality_add_cost.

If we move a node u from community A to community B then we can think of the overall quality delta as having two components: the cost of removing u from A denoted q_A, and the cost of adding u to B. denoted q_B.

The new functions compute these values and so we have:

q_A = quality_remove_cost(G, u, A)
q_B = quality_add_cost(G, u, B)
quality_delta = q_A + q_B

The quantity q_A needs to be computed far less often than q_B.

These functions will be specific to the quality function used, and the new method sets this up at the beginning of leiden_partitions.

_get_quality_add_cost(quality_function) returns the quality_remove_cost function specific to that quality function, e.g. _get_quality_add_cost(constant_potts_model) returns the function that computes q_B for CPM. Currently it does this by simply using the constant_potts_model quality function directly -- this is just a wrapper with no real performance benefit at this stage, however, it will be straightforward to make _get_quality_add_cost(constant_potts_model) instead return a highly optimised method based on a more efficient formula. For CPM I have this formula worked out, but it still needs to be implemented.

I think this method gives a good trade-off in terms of allowing leiden to accept any quality function, whilst also allowing for optimised delta functions.

dk-gh and others added 6 commits February 12, 2026 19:12
…algorithm when computing cpm deltas as nodes are moved between communities.
…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
@dk-gh

dk-gh commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor Author

@dk-gh , one thing I've noticed that I think is worth addressing: _move_nodes_fast evaluates the quality delta against every community for each candidate move, not just neighbor communities.

The current shape (approximately):

for new_com in set(node2com.values()):
    ...

For a node u, any community that contains no neighbor of u contributes a negative delta, that is, pure null-model penalty with zero internal-edge gain, so it cannot win. Iterating over all of them is wasted work. Cost per candidate move: O(|V|) here vs O(deg(u)) in Louvain's _one_level.

The fix is the same pattern as nx.community.louvain._one_level: collect neighbor communities from graph[u], plus the node's current community for the "stay" option, and evaluate delta only on those:

neighbor_coms = {node2com[v] for v in graph[u]}
neighbor_coms.add(node2com[u])  # keep current community as a candidate
for new_com in neighbor_coms:
    ...

A couple of notes:

  • This is cross-cutting: this applies to all four quality_delta. No per-quality-function changes needed.
  • _merge_node_subset is already neighbor-restricted via the T-set construction.

This has brought the test run-time from ~35 seconds down to ~11 seconds. @jtorrents I think combined with your other optimisation you've managed to get about x10 speedup (so far!)

@dk-gh

dk-gh commented Apr 21, 2026

Copy link
Copy Markdown
Contributor Author

@dk-gh thanks for wiring this in. Good to see the O(|A|+|B|) pattern generalize across CPM and modularity.

Two thoughts on the bipartite branch:

1. Red/blue identification: your attribute-based setup is the right direction.

Following our discussion, #8618 landed on per-node red_degree / blue_degree attributes, analogous to in_degree / out_degree for directed modularity. That's what makes the delta survive aggregation, your approach here follows this beautifully. No nodes container argument needed at the leiden API level.

One thing I'd drop is the nx.is_bipartite(G) check. It's a costly traversal on large graphs and it doesn't actually guarantee the bipartite=0/1 attributes are set (it only certifies a 2-coloring exists). The convention in nx.bipartite is to expect a valid bipartite graph form the user; bipartite.modularity itself explicitly documents this in its Notes section. Skipping the check matches that convention and avoids the cost.

2. Full-Q: inlining fits the pattern you've set.

CPM and unipartite modularity call the public quality functions because both work on aggregated graphs without a red/blue-style structural input. bipartite.modularity's nodes argument doesn't survive aggregation, so it can't be pinned at setup via functools.partial the same way. Since you're already inlining the delta (matching CPM/modularity), inlining the full-Q fits; and keeps bipartite.modularity in the public package with its standard bipartite signature as the standalone API + algebra reference, with leiden staying self-contained.

Thanks for this, I've removed the expensive bipartite check and I've put in a placeholder function for the barber modularity quality function to be defined inline.

@dk-gh

dk-gh commented Apr 22, 2026

Copy link
Copy Markdown
Contributor Author

@dschult thanks for the latest round of comments. I will work through refactoring the new tests to incorporate your suggestions e.g. using parameterisation.

Two things I want to highlight that I think require some further discussion:

First, how to handle the old tests -- in some cases there are simple tweaks to make these work (e.g. changing resolution value), but I haven't touched these at all as I don't know exactly what the knock-on effects will be for other backends.

Second, regarding the tests for expected partitions -- these are not based on any "ground truth" as the probabilistic nature of the algorithm (node visit order, and theta in refine partition) means we cannot check on a known input/output. The test here is useful for checking that the algorithm doesn't change when the code is modified (i.e. introducing unexpected behaviour changes), except of course when a minor change does affect the randomness in some way that alters the output, in which case the expected_partition needs to be updated.

I did some initial comparison with the leidenalg implementation, and it seems our nx version is far less stable and more varied in the partitions it output for different seeds. I can only think this is due to the fact we shuffle the nodes before visiting, rather than relying on theta alone to control the randomness, but I haven't looked into the implementation details of leidenalg on this. However, the outputs do seem to "look about right" in comparison i.e. similar community sizes and membership overlap.

One way to make this precise would be to compare the probability distributions of results i.e. for two implementations leiden_1(G) and leiden_2(G), each characterises a probability distribution on the space of partitions of G. We would say that leiden_1 and leiden_2 are the equivalent iff the resulting probability distributions are equal for all G. This would obviously exceed the scope of a unit test for a number of different reasons! It might still be worth doing some more systematic comparisons with leidenalg or some other implementation, even if it is just a heuristic check that things "look right".

@dschult

dschult commented Apr 23, 2026 •

Copy link
Copy Markdown
Member

First, how to handle the old tests -- in some cases there are simple tweaks to make these work (e.g. changing resolution value), but I haven't touched these at all as I don't know exactly what the knock-on effects will be for other backends.

For a general approach we should tweak the test to make it work. Then we will have to rely on the backends to verify that this works for their setup as well. I will try to get someone to help us with that. Can we come up with a good way to make this PR mergable while leaving the exploration of these tests for a follow-up PR? Adding the xfail will break the backend's tests anyway (they won't fail). Maybe for now we do what you did for test_modularity_increase by leaving the old test there with skipif(no backends) and (preferably immediately after) add the similar test that passes for the networkx version. That way, when the backend folks run the test their old tests still exist and the new ones will fail (or not -- tweaking might still allow their version to pass). And when we run the networkx version it will skip the old tests.

Second, regarding the tests for expected partitions ...

It's too bad that we don't have ground truths. It seems like there should be publications with reported communities for e.g. karate_club_graph and e.g. resolution=1. I'm not looking for what the leiden algorithm should produce -- I'm looking for an answer we can compare our "approximate value" to -- since Leiden is only expecting to approximate the optimal solution. This is also probably best left for a follow-up PR.

I think we want to stay away from analysis of probability distributions of produced solutions. That is well beyond the unit test approach. :}

So let's just focus on getting the PR mergable -- in a good state for us... and easy to parse for the backend folks. Specifically, let's put off consideration of the following:

  1. making every old test pass
  2. finding ground truth results for tests to compare against.

@dschult

dschult commented Apr 27, 2026

Copy link
Copy Markdown
Member

@dk-gh where do you stand on this now?
Anything left to do here before we break off further work to follow-up PRs?
No pressure -- just dont want you to be waiting for me.... :}

Thanks!

@dk-gh

dk-gh commented Apr 29, 2026

Copy link
Copy Markdown
Contributor Author

@dk-gh where do you stand on this now? Anything left to do here before we break off further work to follow-up PRs? No pressure -- just dont want you to be waiting for me.... :}

Thanks!

I think if we are happy the core algorithm is in a good place then I think it would be good to create separate issues for any other specific improvements/changes.

Very much welcome your thoughts on what the concrete next steps should be i.e. what is still to do in this PR, and what are the followup PRs (e.g. backend compatibility, optimisation, support for additional quality functions, ground truth examples, improved tests, revisiting louvain)

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

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

The basics are good and we should get this merged so others can work with it:

  • nx-cugraph backend will need to adapt to it.
  • bipartitie and overlapping community tools can use ideas and code from this.
  • Other items that follow-ups can improve:
    • optimization
    • parametrizing tests and unifying approach so other versions/quality measures can reuse tests
    • develop some "ground truth" results that community detection can use generally
    • revisit Louvain with respect to the more general approach taken here.

@jtorrents

Copy link
Copy Markdown
Member

For what it's worth, I'm also +1 on merging this. Very good work @dk-gh !

@dk-gh

dk-gh commented May 7, 2026

Copy link
Copy Markdown
Contributor Author

Thanks all, and particular thanks to @dschult for all the effort in review.

@dschult

dschult commented May 12, 2026

Copy link
Copy Markdown
Member

I am going to go ahead and merge this. We can get feedback from the backend maintainers and adjust what is here if needed in further PRs.

Thanks everyone!

@dschult
dschult merged commit 708ebfa into networkx:main May 12, 2026
74 of 77 checks passed
@dschult dschult added this to the 3.7 milestone May 12, 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.

6 participants