scanpy.tl.leiden#
- scanpy.tl.leiden(adata, resolution=1, *, restrict_to=None, rng=None, directed=None, use_weights=True, n_iterations=-1, partition_type=None, flavor='leidenalg' (sc.settings.preset='scanpy-v1' – changes in 2.0), use=None, out=False, adjacency=None, neighbors_key=None, obsp=None, key_added=None, copy=False, **clustering_args)[source]#
Cluster cells into subgroups [Traag et al., 2019].
Cluster cells using the Leiden algorithm [Traag et al., 2019], an improved version of the Louvain algorithm [Blondel et al., 2008]. It was proposed for single-cell analysis by Levine et al. [2015].
This requires having run
neighbors()orbbknn()first.Array type support# Array type
supported
… experimentally in dask
Array✅
❌
✅
❌
- Parameters:
- adata
AnnData The annotated data matrix.
- resolution
float(default:1) A parameter value controlling the coarseness of the clustering. Higher values lead to more clusters. Set to
Noneif overridingpartition_typeto one that doesn’t accept aresolution_parameter.- rng
int|integer|Sequence[int] |SeedSequence|Generator|BitGenerator|None(default:None) Random number generation to control stochasticity.
If a type:
SeedLikevalue, it’s used to seed a new random number generator; If anumpy.random.Generator,rng’s state will be directly advanced; IfNone, a non-reproducible random number generator is used. Seenumpy.random.default_rng()for more details.The default value matches legacy scanpy behavior and will change to
Nonein scanpy 2.0.- restrict_to
tuple[str,Sequence[str]] |None(default:None) Restrict the clustering to the categories within the key for sample annotation, tuple needs to contain
(obs_key, list_of_categories).- directed
bool|None(default:None) Whether to treat the graph as directed or undirected.
- use_weights
bool(default:True) If
True, edge weights from the graph are used in the computation (placing more emphasis on stronger edges).- n_iterations
int(default:-1) How many iterations of the Leiden clustering algorithm to perform. Positive values above 2 define the total number of iterations to perform, -1 has the algorithm run until it reaches its optimal clustering. 2 is faster and the default for underlying packages.
- partition_type
type[MutableVertexPartition] |None(default:None) Type of partition to use. Defaults to
RBConfigurationVertexPartition. For the available options, consult the documentation forfind_partition().- flavor
Literal['leidenalg','igraph'] |Default(default:'leidenalg' (sc.settings.preset='scanpy-v1' – changes in 2.0)) Which package’s implementation to use.
- use
GraphAcc|str|None(default:None) The neighborhood graph (connectivities) to use, e.g.
A.obsp['k']aftersc.pp.neighbors(adata, out=A.obsp['k']), or any other graph.strs areresolve()d, e.g.'obsp.k'. IfNone, the oneneighbors()wrote by default.- out
AdRef[Idx2D|int,AnnData] |str|bool(default:False) Where to write the cluster labels. Given by an accessor, e.g.
A.obs['clusters'].strs areanndata.acc.AdAcc.resolve()d. Accompanyingunsentries are stored under the same key. IfTrue, the cluster labels is returned instead of written. IfFalse, it is written to.obs['leiden']and.uns['leiden']('leiden_R'ifrestrict_tois passed).- key_added
str|None(default:None) Deprecated since version 1.13.0: Use
outinstead.key_added='k'isout=A.obs['k'].- adjacency
csr_array|csc_array|csr_matrix|csc_matrix|None(default:None) Deprecated since version 1.13.0: Store the graph in
.obspand passuse=A.obsp[...]instead.Sparse adjacency matrix of the graph, defaults to neighbors connectivities.
- neighbors_key
str|None(default:None) Deprecated since version 1.13.0: Use
useinstead, e.g.use=A.obsp['k_connectivities']forneighbors_key='k'.Use neighbors connectivities as adjacency. If not specified, leiden looks at .obsp[‘connectivities’] for connectivities (default storage place for pp.neighbors). If specified, leiden looks at .obsp[.uns[neighbors_key][‘connectivities_key’]] for connectivities.
- obsp
str|None(default:None) Deprecated since version 1.13.0: Use
use=A.obsp[...]instead.Use .obsp[obsp] as adjacency. You can’t specify both
obspandneighbors_keyat the same time.- copy
bool(default:False) Deprecated since version 1.13.0: Copy
adatabefore calling this function instead.Whether to copy
adataor modify it inplace.- **clustering_args
Any further arguments to pass to
find_partition()(which in turn passes arguments to thepartition_type) origraph.Graph.community_leiden()fromigraph.
- adata
- Return type:
AnnData|Categorical|None- Returns:
Returns the cluster labels if
out=True, elseNone. By default sets the following fields (seeoutfor others):adata.obs['leiden']pandas.Series(dtypecategory)Array of dim (number of samples) that stores the subgroup id (
'0','1', …) for each cell.adata.uns['leiden']['params']dictA dict with the values for the parameters
resolution,n_iterations, andrandom_state(if applicable).adata.uns['leiden']['modularity']floatThe modularity score of the final clustering, as calculated by the
flavor. Usescanpy.metrics.modularity()(adata, mode='calculate' | 'update')to calculate a score independent offlavor.