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() or bbknn() first.

Array type support#

Array type

supported

… experimentally in dask Array

numpy.ndarray

✅

❌

scipy.sparse.{csr,csc}_{array,matrix}

✅

❌

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 None if overriding partition_type to one that doesn’t accept a resolution_parameter.

rng int | integer | Sequence[int] | SeedSequence | Generator | BitGenerator | None (default: None)

Random number generation to control stochasticity.

If a type:SeedLike value, it’s used to seed a new random number generator; If a numpy.random.Generator, rng’s state will be directly advanced; If None, a non-reproducible random number generator is used. See numpy.random.default_rng() for more details.

The default value matches legacy scanpy behavior and will change to None in 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 for find_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'] after sc.pp.neighbors(adata, out=A.obsp['k']), or any other graph. strs are resolve()d, e.g. 'obsp.k'. If None, the one neighbors() 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 are anndata.acc.AdAcc.resolve()d. Accompanying uns entries are stored under the same key. If True, the cluster labels is returned instead of written. If False, it is written to .obs['leiden'] and .uns['leiden'] ('leiden_R' if restrict_to is passed).

key_added str | None (default: None)

Deprecated since version 1.13.0: Use out instead.

key_added='k' is out=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 .obsp and pass use=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 use instead, e.g. use=A.obsp['k_connectivities'] for neighbors_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 obsp and neighbors_key at the same time.

copy bool (default: False)

Deprecated since version 1.13.0: Copy adata before calling this function instead.

Whether to copy adata or modify it inplace.

**clustering_args

Any further arguments to pass to find_partition() (which in turn passes arguments to the partition_type) or igraph.Graph.community_leiden() from igraph.

Return type:

AnnData | Categorical | None

Returns:

Returns the cluster labels if out=True, else None. By default sets the following fields (see out for others):

adata.obs['leiden']pandas.Series (dtype category)

Array of dim (number of samples) that stores the subgroup id ('0', '1', …) for each cell.

adata.uns['leiden']['params']dict

A dict with the values for the parameters resolution, n_iterations, and random_state (if applicable).

adata.uns['leiden']['modularity']float

The modularity score of the final clustering, as calculated by the flavor. Use scanpy.metrics.modularity()(adata, mode='calculate' | 'update') to calculate a score independent of flavor.