Clustering with leidenalg
See original GitHub issueHello,
It would appear that louvain-igraph
has been obsoleted in favour of leidenalg
, and the author makes a persuasive case as to the superiority of the new approach. To my untrained eye, the algorithm is conceptually similar to the Louvain modification used by Seurat, but introduces an extra collapsed network refinement step.
it should be easy to support this in Scanpy - the syntax appears to be identical to the old louvain
innards, and I was able to construct a very minimal dummy function for testing by taking the key bits of sc.tl.louvain()
and replacing louvain.
with leidenalg.
:
import leidenalg
import numpy as np
import pandas as pd
from scanpy import utils
from natsort import natsorted
def leiden(adata, use_weights=False, resolution=1, iterations=-1):
g = utils.get_igraph_from_adjacency(adata.uns['neighbors']['connectivities'], directed=True)
weights = None
if use_weights:
weights = np.array(g.es["weight"]).astype(np.float64)
part = leidenalg.find_partition(
g, leidenalg.RBConfigurationVertexPartition,
resolution_parameter = resolution, weights = weights,
n_iterations = iterations,
)
groups = np.array(part.membership)
adata.obs['louvain'] = pd.Categorical(
values=groups.astype('U'),
categories=natsorted(np.unique(groups).astype('U')),
)
As such, replacing any louvain.
with leidenalg.
in sc.tl.louvain()
would do most of the work. Probably the only new thing that would need support would the the n_iterations
parameter in leidenalg.find_partition()
. The default value is 2, positive values control how many passes of the algorithm are performed. -1 just makes it run until it fails to improve the clustering.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:7
- Comments:28 (16 by maintainers)
Well, “implemented”… I’d say “wrapped”.
In that case, it’d probably be easiest to just add a
'leiden'
flavour tosc.tl.louvain()
. Due to the overlap of the syntax, you may even get away with explicitly recycling the existing Louvain code in the function and just swap the package behind the scenes: