Skip to content

Networkx Implementation of Leiden Community Detection Algorithm - #8505

Closed
dk-gh wants to merge 15 commits into
networkx:mainfrom
dk-gh:implement_leiden
Closed

dk-gh wants to merge 15 commits into
networkx:mainfrom
dk-gh:implement_leiden

Conversation

@dk-gh

@dk-gh dk-gh commented Feb 7, 2026

Copy link
Copy Markdown
Contributor

I have implemented the leiden community detection algorithm within networkx. The original Leiden paper [1] gives pseudocode for the louvain and leiden algorithms side-by-side. My approach was to use the side-by-side pseudocode comparison as a guide to incrementally adapt the networkx implementation of louvain. This required changes in three broad areas:

i)   adapting louvain to allow use of a different quality function e.g. Constant-Potts model (CPM)

ii)  adapting the _one_level(...) function within networkx louvain to use the logic of the leiden MoveNodesFast function [1]

iii) introduce the RefinePartition step from leiden [1]

No AI/LLM tools have been used at any stage -- the main reason I undertook this project was to better understand the louvain and leiden algorithms.

Changes to Louvain:

In order to make these changes possible I started with refactoring parts of louvain. In order to implement i) I changed louvain to accept quality_function as parameter with modularity being the default. This allows the louvain algorithm to be run using quality functions other than modularity (e.g. CPM). In order to do this I also had to refactor modularity.

One of the challenges when abstracting modularity to more general quality function was that louvain implementation had parts of modularity hard-coded into _one_level(...). This was to calculate the modularity deltas from moving nodes between communities.

Quality Functions:

A quality function Q accepts a graph G and a partition P=[A, B, C, D], and returns a numerical value Q(G, P). However, quality functions like modularity and CPM are the sum of values calculated for each community within the partition, which means that computing the effect of moving a node to another can be calculated without computing Q(G, P) in full.

Let P = [A, B, C, D] be a partition, and suppose we move node u from community A to community B. This gives a new partition P' = [A', B', C, D]. To compute the change in quality from Q(G, P) to Q(G, P'), we only need to calculate the contribution of the terms A and B compared against that of A' and B' because of the property

Q(G, P) - Q(G, P') = Q(G, [A, B]) - Q(G, [A', B'])

However, the problem with the existing implementation of modularity is that we cannot run modularity(G, [A, B]) because the list of communities does not form a partition of G -- this would raise a NotAPartition exception. Therefore I included another parameter in modularity: allow_partial (set to False by default). If allow_partial=True then the quality function will compute the contribution of the lists of communities, even if these do not form a full partition. This keeps existing behaviour by default of modularity (original tests for louvain and modularity still passing).

I have implemented the quality function constant_potts_model(...) following [2], which has the same API as the refactored modularity(...), including the allow_partial parameter, and constant_potts_model can be used interchangeably with modularity in both louvain and leiden. Note that I used the formulation of CPM from [2] as it slightly more general than that described in [1]. The formula in [1] requires positive integer node sizes (node_weight). Following [2] the implementation allows for node_weight to be a float (set to 1.0 by default). The node_weight of the aggregated community is the sum of the node_weights of its members.

I haven't benchmarked performance for the new implementation of louvain against the existing version.

Adapting Louvain to Leiden:

The Leiden implementation is then an adaptation of the refactored louvain code. Like the updated louvain code, leiden can accept quality_function as a parameter, but uses constant_potts_model by default.

I have created tests for CPM, contant_potts_model(...) I have created a number of tests for Leiden by copying the Louvain tests. I have also included tests that resulting communities are connected.

Further tests for Leiden are probably useful. Because the algorithm is non-deterministic, it is difficult to test on known inputs and outputs. The randomness in leiden comes from two parts of the algorithm:

1) the order in which nodes are visited
2) the way communities are chosen from a probability distribution in the _refine_partition(...) stage

Both of these are controlled by the same seed, resulting in deterministic behaviour when using a set seed value.

From a quick test against the outputs of leidenalg, the community structures seem similar at the same resolution and theta values, however, more thorough testing may be required to ensure the correctness of this implementation. Overall the results seem to be less stable than leidenalg (greater variance in structure of resulting communities). I don't know why this is, and understanding the difference may come down to looking at implementation details of leidenalg (my initial guess would be it has something to do with the randomness in the order that nodes are visited, but this is not a well-informed view).

TODO:

  • One test in tests_leiden copied from tests_louvain is still not passing -- test_max_level
  • Need to write comprehensive doc strings for leiden_communities and leiden_partitions function

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

[2] "Narrow scope for resolution-limit-free community detection" V.A. Traag, P. Van Dooren, Y. Nesterov
https://arxiv.org/abs/1104.3083

@dschult

dschult commented Feb 8, 2026

Copy link
Copy Markdown
Member

Thanks for this -- there's a lot here and we may need to split it up to get it reviewed effectively. But first and foremost, thanks for this work. :)

My work with modularity and Louvain specifically shows that it is pretty crucial to compute the change in modularity instead of recomputing the full modularity and taking the difference. Publications hint at this need too. Removing this change (and the partial feature added to make it work) would simplify quite a lot. It would also be good to see whether CPM has a formula for the change in CPM after the change in one step... I suspect it will be too slow otherwise.

The rest is still quite large and I would suggest breaking it up to make review possible and timely. Some ideas along these lines:

  • use @pytest.mark.xfail("test_max_level isn't passing yet") on the test_max_level test. That let's it fail without stopping CI. And the xfail notice (along with your commets in the PR) will remind us to fix it.
  • constant_potts_model is self-contained and could make a reasonable PR all by itself with a few tests to ensure the values are correct (without any connection to louvain or leiden).
  • Leiden is the big new feature here, so a PR that adds Leiden is reasonable too. No reference or tests for CPM, but allowing a quality measure function is fine. Maybe even better would be a delta_quality function -- but let's take it one step at a time. You've already got the version here working. So put that together.
    • I'd really much rather have a brief summary of the algorithm in the doc_strings. No value-added to users if we just say: "go look at the paper". You did a lot of work figuring out how this works. Describe it so others can benefit from your work. At least leave the description that others created before you -- removing that in favor of a link to a paper is not helpful.
    • converting multigraph to graph in a helper routine might seem nice to users, but they may want to convert in a different way (something other than a sum of weights for example). Perhaps for ease of review you can keep extraneous features for a later PR and just have the initial PR be a barebones function that perhaps doesn't support multigraph (or do other things that I don't even know about yet).

Those two PRs can be submitted at the same time as long as you make them independent of each other. The next PR would presumably combine these two features with tests using Leiden and CPM. Another PR would involve rewriting Louvain -- but I'm not sure it will be worth doing. Maybe you can write some benchmarks of Louvain as a separate PR so it will be easy to test the timing across commits. I believe there already is one for Louvain in benchmarks/benchmarks/benchmark_algorithms.py. And that might be enough to see an order-of-magnitude first-pass for timing it. But if other cases, graph sizes, features, etc need to be tested for timing, a module of tests for Louvain would be reasonable.

I think the best things to spend time on first are the bullets above: get CI "passing" (with xfail), put CPM into its own PR, get Leiden as a separate PR. Push back if this doesn't seem like the right path. Ask questions if that will help. We can keep this PR as a conversation point to help organize the discussion. And it can point to other PRs that are better "bite-size" for the reviewers.

Thanks!

@dk-gh

dk-gh commented Feb 8, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the feedback, I appreciate it's a large PR and I agree it makes sense to split. I've been working on this incrementally, and found myself making changes back and forth between louvain.py, quality.py and leiden.py, and the order the code is written is not necessarily the logical order to submit as PRs -- I appreciate your thoughts on how to break it up into manageable pieces.

I think I agree that this naturally fits into three separate PRs (if refactoring louvain is to be included).

PR1 - Refactor Louvain (optional)

This PR would refactor louvain_communities and louvain_partitions to allow passing a quality_function parameter with default being quality_function=modularity.

This PR will change the way modularity is implemented (allowing partial evaluation for efficiently computing deltas).

Regarding the question as to whether refactoring louvain is worth it, I can see three benefits of this refactoring, and one potential drawback:

Benefits

  1. there will be the option to use different quality functions with louvain other than modularity (e.g. CPM)

  2. leiden and louvain will use the same underlying quality functions (the new constant_potts_model function cannot be used in the existing louvain implementation which has modularity hard-coded, and the leiden implementation will not be able to use the existing modularity function. If we want the option to use modularity with leiden, we would need two separate modularity functions.

  3. extending to add new quality functions for both leiden and louvain will be straightforward, as there is a clear abstraction for the properties and behaviour for a quality_function (see further comment below)

Drawbacks

  1. unknown impact on performance

  2. it will take time to review, and "if it ain't broke, don't fix it"

I will look at benchmarking, and maybe we can revisit the discussion on this later. I think in principle there are meaningful benefits. Am I missing anything else in terms of drawbacks?

PR2 - Implement CPM

This simple PR will introduce constant_potts_model as a quality function in quality.py, with tests in tests_quality.py. This implementation includes partial evaluation for efficiently calculating deltas (more comments on this below).

PR3 - Implement Leiden

This PR will introduce the full implementation of leiden_communities and leiden_partitions, which accept quality_function as a parameter with the default quality_function=constant_potts_model.

I think I will need to do PR2 then PR3 sequentially, as leiden requires constant_potts_model (or another quality function) to be implemented in order to run.

###Next Steps

I will go ahead with PR2 and PR3, and revisit PR1 once I have had a chance to look at performance benchmarking. I think this is in line with your comments above -- am I missing anything here?

Other Comments

Properties of a "Quality Function"

When thinking about abstracting to a more general quality function, the key property for the quality function $Q$ will be that it satisfies:

$Q(G, [A, B]) = Q(G, [A]) + Q(G, [B])$

This is a kind of "localness" condition; the changes of moving a node from one community to another can be determined locally (i.e. just in terms of the source and target communities), rather than relying on a "global" property of the graph and/or partition.

The functions modularity and constant_potts_model satisfy this property (I haven't explored any other quality functions). Keeping the NotAPartition exception and introducing the allow_partial parameter allows us to exploit this property while not breaking the existing tests. I should note that modularity does depend on a static piece of "global" information -- the sum of all edge weights of $G$. Therefore, in order to keep the API as consistent with the new constant_potts_model, the new modularity implementation uses functools.lru_cache so that the global information is not re-calculated for each local comparison.

Converting MultiGraph to Graph

This helper function was carried over from louvain.py -- not something I consciously chose to include, but rather opted to keep by default. I think it makes sense to use the not_implemented_for decorator, and require a user to convert the multigraph explicitly, rather than hiding the behaviour within a community detection algorithm, however I also think it would be confusing if leiden and louvain didn't handle this in the same way (I feel like one of the desirable behaviours of this implementation is that a user ought be able to exchange louvain_communities for leiden_communities in their code and nothing break).

@dschult

dschult commented Feb 8, 2026

Copy link
Copy Markdown
Member

Can you add the xfail pytest mark to the failing test of this PR and resubmit? That will allow us to see if there are any failures on the jobs that got canceled due to previous CI jobs failing.

Can't the leiden function use the modularity function instead of the CPM function? That would allow the CPM PR to be independent of the Leiden function.... (practically it may not matter because I suspect CPM will be easier to review than the Leiden anyway so it would be merged first.)

Can we have the Louvin and Leiden functions accept a delta-function instead? So instead of computing the full modulatity, they compute the change in the modularity on each step. We'd have to derive a formula for the change in CPM on one step, but I think that would be straightfoward. But I haven't tried it.

I haven't worked through what the allow_partial feature actually does. I get that it bypasses the check that the partition is actually a partition. But does it do anything else? I'm looking for a way to bypass calling the quality measure function. (of course benchmarking should back that up -- so I'm basing this on my ten years ago crude benchmarking that showed quite large differences. And that make sense because we are only swapping nodes from one community to another -- as you point out.)

:)

@dk-gh

dk-gh commented Feb 8, 2026

Copy link
Copy Markdown
Contributor Author

Can you add the xfail pytest mark to the failing test of this PR and resubmit? That will allow us to see if there are any failures on the jobs that got canceled due to previous CI jobs failing.

I have added the xfail decorator for the failing test now.

Can't the leiden function use the modularity function instead of the CPM function? That would allow the CPM PR to be independent of the Leiden function.... (practically it may not matter because I suspect CPM will be easier to review than the Leiden anyway so it would be merged first.)

Not without changes to modularity or to the current leiden_communities. Leiden cannot accept quality_function=modularity using the existing implementation of modularity because during _mode_nodes_fast, a node $u$ is moved from its community $A$ to a new community $B$, creating new communities $A'$ and $B'$. To measure the delta we call

q1=quality_function(G, [A, B], allow_partial=True)
q2=quality_function(G, [A', B'], allow_partial=True)
q_delta = q2 - q1

The only thing allow_partial=True is doing is preventing the exception being thrown. Otherwise the underlying logic of the quality function is the same -- it computes a sum of quality contributions for each community, we're just allowing it to return a value even if only a subset of communities are present.

Can we have the Louvin and Leiden functions accept a delta-function instead? So instead of computing the full modulatity, they compute the change in the modularity on each step. We'd have to derive a formula for the change in CPM on one step, but I think that would be straightfoward. But I haven't tried it.

Do you mean a function for the delta at the point of moving each node? This is basically how each q_delta is computed throughout the algorithm -- any quality function that satisfies the "local" property can be used to efficiently compute q_delta this way. This is basically the requirement of what kind of quality function leiden_communities will accept -- does it allow the q_delta trick to work.

Or do you mean tracking the incremental changes all the way through each iteration of aggregating nodes? I.e. to test whether the change meets the threshold to determine whether to continue or return the current partition.
In principle I think this could be done fairly easily, but it is complicated by the fact that nodes are moved in both _move_nodes_fast and _refine_partition phases. In practice I think the performance impact of this will minimal compared to the deltas computed for each node move.

I haven't worked through what the allow_partial feature actually does. I get that it bypasses the check that the partition is actually a partition. But does it do anything else? I'm looking for a way to bypass calling the quality measure function. (of course benchmarking should back that up -- so I'm basing this on my ten years ago crude benchmarking that showed quite large differences. And that make sense because we are only swapping nodes from one community to another -- as you point out.)

The allow_partial feature basically does nothing other than prevent the function from failing. This is easier to see in constant_potts_model which is actually far simpler than modularity. The issue with modularity is that it relies on some (unchanging) global data which would have to be recomputed at each comparison, so I have made other changes (entirely unrelated to the allow_partial behaviour) making use of the lru_cache -- these changes have nothing to do with the logic of the function as such and are purely an optimisation to prevent the same values being computed over and over again. This is probably still not as fast as the hard-coded formula in the original though.

@dschult

dschult commented Feb 9, 2026

Copy link
Copy Markdown
Member

Thanks for that -- the xfail makes it easier to see how these changes have affected the other tests. And the discussion of function input to both Louvain and Leiden is helpful.

What I'm envisioning is a function parameter that is used to compute q_delta. So instead of calling the quality function twice, these large scale function just call a single function qscale with inputs being the nodes that are moving and which communities that are moving from/to. The q_delta can just call the quality function twice as you have now in Louvain and Leiden. But it could also implement whatever shortcut or fast version of the q_delta computation as is desired. For example one option for q_delta could be the hardcoded code that is in Louvain in the main branch of NetworkX. And the q_delta for CPM could call it twice for now -- and could be replaced later once a fast way to do it is figured out.

I'd rather not have any constraints on how that change is computed inside the main functions. Let's move as much as possible to these helper fuctions that we can then provide, or a user can write themselves for new cases. Thoughts?

I do wonder at what point these functions are no longer Louvain or Leiden, but some new generalization of them. I'll take a look at the papers again...
:)

@dk-gh

dk-gh commented Feb 9, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks,

It will be easy to modify my implementation of leiden and louvain to use something like the qscale function you're talking about. It would just be a case of replacing the code

q1=quality_function(G, [A, B], allow_partial=True)
q2=quality_function(G, [A', B'], allow_partial=True)
q_delta = q2 - q1

with something like

q_delta = qscale(G, node=u, community_from=A, community_to=B)

in a few places.

For any given quality function, the delta function could either be based on a highly optimised formula, or for functions where this hasn't been developed yet, it could just be a wrapper that still applies the q_delta=q2-q1 logic.

I think looking into this further will fit naturally with benchmarking, the new louvain implementation (which uses exactly the same q_delta=q2-q1 method).

In the meantime I'll get the cpm and leiden PRs submitted. I do appreciate the comments and feedback.

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

@dk-gh it looks like there are two PRs open for Leiden - should we close this one?

@dk-gh

dk-gh commented Feb 19, 2026

Copy link
Copy Markdown
Contributor Author

@dk-gh it looks like there are two PRs open for Leiden - should we close this one?

Yes this one can be closed as PR #8509 supersedes it.

@dk-gh dk-gh closed this Feb 19, 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