Skip to content

ENH: leiden test and doc_string improvements - #8656

Merged
rossbar merged 8 commits into
networkx:mainfrom
dschult:leiden_followup
May 22, 2026
Merged

rossbar merged 8 commits into
networkx:mainfrom
dschult:leiden_followup

Conversation

@dschult

@dschult dschult commented May 17, 2026

Copy link
Copy Markdown
Member

This PR is a follow-up to #8509

The tests are reorganized using fixtures, and parametrization across "cpm" and "modularity" metrics. Doc-strings are reworded and rewrapped with example added to leiden_communities(). Hopefully they are improved, but that is often subjective.

Perhaps the most controversial change is to rename the kwarg quality_function to metric. The value is not a function. It is the name of the objective function to use: either "cpm" for Constant Potts Model, or "modularity" for Modularity. I tried the kwarg method like we use elsewhere. But the algorithm is the same, just the objective function has changed. So "method" isn't quite right. I also tried quality_metric, but the term "quality", while historically relevant as the measure of "partition quality", is not descriptive with the adjective "partition". And the length of the kwarg is annoying for code wrapping. So I am proposing metric. I'm open to suggestions.

I tried to replace the name "resolution", but could not find a better word. I tried to describe it better in the doc-string using "low resolution" and "high resolution" to make the analogy that low res sees big stuff, while high res sees little stuff.

All original tests should still be there but now covering both metrics. New tests include trying to get at ground_truth examples. The LFR_benchmark_graph example has the constructed communities indicated as node attributes. So one test checks that those are the communities found by louvain(), leiden with "cpm" and leiden with "modularity". Results vary by seed value and resolution value, so I picked resolutions for each metric that usually gave about the right number of communities. The resulting 3 communities vary a little by seed, but its easy to find seeds that match except for leiden "modularity" for which seeds 0-10_000 do not produce the communities used to construct the graph. I will look at that more as I do the next follow-up PR focused on core code and comments.

I also added a test with a barbell graph that has obvious communities in each weight(cliques) and the bar(path) between them.

Futher follow-up planned:

  • optimization & readability
  • revisit Louvain code/docs to use ideas that came up during the implementation of leiden.

Removed an unused helper function (it was commented as for debugging and named _is_valid_refinement)

Overall leiden seems to have quite variable results from run to run. We may want to explore whether to reduce variation by removing randomness in node order, or by choosing a different default theta value. Louvain is comparatively stable from run to run. Once resolution is chosen to produce about 3 communities, it always selects the correct communities.

Another oddity I've noticed is that varying resolution produces a smoother profile with "cpm" than with "modularity". By profile I mean as resolution is changed, "cpm" gives many smaller changes in number of communities. "moudularity" leads to fewer and larger changes in the number of communities.

@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 @dschult - overall I'm very +1 on the updates.

I took the liberty of pushing up a change in how leiden_partitions is called under-the-hood to get rid of all the keyword-only test failures. Interestingly there's still one test that fails - I've left it in for now so you can take a look. It could be just a seed that needs updating, but let's double-check!

Once the failing docstring example is looked at I'm +1 on this going in!

Perhaps the most controversial change is to rename the kwarg quality_function to metric

I'm +1. metric is shorter, more accurate, and less overloaded (unlike e.g. meth) - all of which are pointed out in the motivation for the change.

The resulting 3 communities vary a little by seed, but its easy to find seeds that match except for leiden "modularity" for which seeds 0-10_000 do not produce the communities used to construct the graph. I will look at that more as I do the next follow-up PR focused on core code and comments.

Very interesting - thanks for doing the deep dive! This along with the observation on "stability" of Leiden vs. Louvain are very interesting. There are a lot of potential contributing factors (algorithm itself, various metrics, how the various metrics behave in different algorithms, many other combinations) that will be very interesting to explore - it's good to get this on the radar now!

weight : string or None, optional (default="weight")
The name of an edge attribute that holds the numerical value
used as a weight. If None then each edge has weight 1.
metric : str (default="cpm")

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.

Worth clarifying what cpm means at the end of the docs maybe?

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.

More than at the end of the docs! :) It should be the first time the abbreviation is used.
Thanks!

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 see now that you probably meant more than just "cpm" refers to constant_potts_model. We should probably point to the docs for the two functions constant_potts_model and modularity so people can follow up with more info in those docs. :\

@dschult

dschult commented May 19, 2026

Copy link
Copy Markdown
Member Author

Thanks Ross!

Very helpful! and thanks for getting the PR past ruff. The examples and keyword-only changes were near the end of my day, so I guess I'm not surprised that they caused failures. No excuse for my not checking it though.

And even more thanks for input on these changes. The name and

But mostly: Thanks for the comments on the metric name and the comparison between algorithms and metrics.

As for the failing example:
I originally had that example running with barbell_graph(10, 3) instead of barbell(3, 4). I recall changing it because the output was just too long. But I guess I didn't check after that to make sure the test passed! I also added the next line which sorts the communities to show what they are. And I didn't test that either apparently. Anyway, after being sorted they are lists of lists -- not the sets I originally put in there.

I think the latest commit will turn the checks green! But that sentence jinxed me, so who knows. :)

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

Nice cleanup overall. I left a few small things, mostly around making the new parametrization/tests a bit tighter and polishing the public-facing metric bits.

assert nx.community.is_partition(G, partition)
def _quality():
def cpm(G, P):
return comm.constant_potts_model(G, P, resolution=0.2)

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 think this accidentally weakens the gamma parametrization below. The algorithm call uses resolution=gamma, but the quality functions here always evaluate at resolution=0.2, so the 0.5 and 0.9 cases are not checking improvement in the same objective Leiden just optimized. Could make these callbacks take gamma, or yield partials already bound to each gamma.

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.

Yes -- you are right...
This is an oversight on my part. And it not only weakens the test.
Even worse, correcting it leads to failure for the resolution=0.2 case.
I will fix and explore this case in a followup PR.

Thanks!!!

Comment thread networkx/algorithms/community/leiden.py Resolved
Comment thread networkx/algorithms/community/leiden.py Resolved
Comment thread networkx/algorithms/community/leiden.py Resolved

@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 @dschult - this all LGTM.

I'm happy to merge as-is or incorporate some/all of @Peiffap 's comments - I'll leave it up to you since we have more follow-up PRs inbound!

@dschult

dschult commented May 22, 2026

Copy link
Copy Markdown
Member Author

Thanks @amcandio @rossbar and @Peiffap for the reviews.
I left one item @Peiffap pointed out for a follow-up as it brings into question the leiden_communities implementation. I'll explore that as I work through the code for follow-ups.
The question is "why would any changes be accepted if they reduce the metric value?". The answer might be that the search allows decreases to avoid getting stuck in local minimums. But it might also be that it isn't supposed to happen. The papers and code should reveal the intent. :)

I believe this is ready for merging!

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

4 participants