Leiden Algorithm for Community Detection
leidenalg is a Python library that implements the Leiden algorithm for community detection in large networks. It is an extension of the Louvain algorithm, guaranteeing well-connected communities and often running faster. The library, currently at version 0.11.0, is actively maintained and provides Python bindings to a C++ core. It primarily relies on `python-igraph` for graph manipulation and can handle graphs with millions of nodes.
Warnings
- breaking Python 3.7 and 3.8 are no longer supported. Ensure you are using Python 3.9 or newer.
- gotcha The default `resolution_parameter` (γ = 1) in `leidenalg` might not be optimal for all networks, potentially leading to an inappropriate number of communities.
- gotcha Direct installation with `pip install leidenalg` usually works due to binary wheels. However, if building from source, `leidenalg` depends on the C++ core libraries `igraph` (>= 1.0.0) and `libleidenalg` (>= 0.12), which may require manual compilation and specific build tools (e.g., `build-essential`, `autoconf`, `automake`, `flex`, `bison` on Ubuntu) if pre-built binaries are not available or suitable.
- gotcha When integrating with other libraries like `Scanpy`, ensure the graph object is correctly prepared before calling the Leiden algorithm. Leiden operates on graph structures, not raw data matrices.
- deprecated The `Scanpy` library, which often uses `leidenalg`, is shifting its default backend for Leiden clustering towards `igraph`'s internal implementation instead of `leidenalg`'s. While `leidenalg` is still the default for now, direct reliance on `leidenalg` via `Scanpy`'s API might change in future `Scanpy` versions.
Install
-
pip install leidenalg
Imports
- leidenalg
import leidenalg as la
- igraph
import igraph as ig
- ModularityVertexPartition
from leidenalg import ModularityVertexPartition
Quickstart
import igraph as ig
import leidenalg as la
# Create a sample graph (e.g., Erdos-Renyi graph)
G = ig.Graph.Erdos_Renyi(100, 0.1)
# Find a partition using the Leiden algorithm with Modularity
partition = la.find_partition(G, la.ModularityVertexPartition)
print(f"Number of nodes: {G.vcount()}")
print(f"Number of edges: {G.ecount()}")
print(f"Number of communities: {len(partition)}")
print(f"Modularity: {partition.modularity}")
# To get community membership for each node:
# print(partition.membership)