Tools
valency-anndata methods¶
valency_anndata.tools.recipe_polis ¶
recipe_polis(
adata: AnnData,
*,
participant_vote_threshold: int = 7,
key_added_pca: str = "X_pca_polis",
key_added_kmeans: str = "kmeans_polis",
mask_var: str | None = None,
inplace: bool = True,
)
Projects and clusters participants as of [Small et al., 2021].
Expects sparse vote matrix .X with {+1, 0, -1}
and NaN values.
Recipe Steps
- Masks out meta and moderated-out statements with zeros.
- Imputes missing matrix votes with statement-wise means.
- Runs standard PCA on the imputed matrix.
- Runs sparsity-aware scaling on PCA projections.
- Calculates a participant mask using 7-vote threshold.
- On unmasked rows, calculates k-means clustering for 2 ≤ k ≤ 5, selecting the optimal k via silhouette scores.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
participant_vote_threshold
|
int
|
Vote threshold at which each participant will be included in clustering. |
7
|
key_added_pca
|
str
|
'X_pca_polis'
|
|
key_added_kmeans
|
str
|
|
'kmeans_polis'
|
mask_var
|
str | None
|
Column name in |
None
|
inplace
|
bool
|
Perform computation inplace or return result. |
True
|
Returns:
| Type | Description |
|---|---|
.obsm['X_pca_polis' | key_added]
|
PCA representation of data. |
.varm['X_pca_polis' | key_added]
|
The principal components containing the loadings. |
.uns['X_pca_polis' | key_added]['variance_ratio']
|
Ratio of explained variance. |
.uns['X_pca_polis' | key_added]['variance']
|
Explained variance, equivalent to the eigenvalues of the covariance matrix. |
.obs['kmeans_polis' | key_added]
|
Array of dim (number of samples) that stores the subgroup id ('0', '1', …) for each cell. |
.uns['kmeans_polis' | key_added]['params']
|
A dict with the values for the k-means parameters. |
Examples:
Basic usage:
import valency_anndata as val
adata = val.datasets.aufstehen()
val.tools.recipe_polis(adata)
val.viz.embedding(adata, basis="pca_polis", color="kmeans_polis")
Use with highly variable statement filtering:
import valency_anndata as val
adata = val.datasets.aufstehen()
# First identify highly variable statements
val.preprocessing.highly_variable_statements(adata, n_top_statements=100)
# Run Polis recipe using only highly variable statements for PCA
val.tools.recipe_polis(adata, mask_var="highly_variable")
# Visualize the results
val.viz.embedding(adata, basis="pca_polis", color="kmeans_polis")
Source code in src/valency_anndata/tools/_polis.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | |
valency_anndata.tools.recipe_polis2_statements ¶
recipe_polis2_statements(
adata: AnnData,
*,
show_progress: bool = False,
inplace: bool = True,
) -> AnnData | None
Embed and cluster statements (the var axis) using the Polis v2 pipeline.
Reads free-text statement content from .var["content"], produces
dense embeddings, projects them to 2-D with UMAP, and attaches a
hierarchy of cluster labels — all stored on the var axis so that
the results live alongside the statements that produced them.
Requires the optional polis2 dependency group::
pip install valency-anndata[polis2]
Recipe Steps
- Embeds each statement's text into a high-dimensional vector space
and stores the result in
.varm["content_embedding"]. - Projects the embeddings to 2-D with UMAP and stores the coordinates
in
.varm["content_umap"]. - Builds a hierarchy of clustering layers (finest → coarsest) and
stores them in
.varm["evoc_polis2"](shapen_var × num_layers) with the coarsest layer also surfaced as the categorical column.var["evoc_polis2_top"].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adata
|
AnnData
|
AnnData object whose |
required |
show_progress
|
bool
|
Show embedding progress bar. When |
False
|
inplace
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
Depending on *inplace*, returns ``None`` or the modified ``AnnData``.
|
|
.varm['content_embedding']
|
Dense text embeddings, shape |
.varm['content_umap']
|
2-D UMAP projection of the embeddings, shape |
.varm['evoc_polis2']
|
Stacked layers of clustering labels, shape |
.var['evoc_polis2_top']
|
Categorical column taken from the coarsest clustering layer
(i.e. |
Examples:
adata = val.datasets.polis.chile_protests(translate_to="en")
with val.viz.schematic_diagram(diff_from=adata):
val.tools.recipe_polis2_statements(adata)

val.viz.embedding(
# Transpose .var and .obs axes for plotting
adata.transpose(),
basis="content_umap",
color=["evoc_polis2_top", "moderation_state"],
)

Source code in src/valency_anndata/tools/_polis2.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 | |
valency_anndata.tools.kmeans ¶
kmeans(
adata: AnnData,
use_rep: Optional[str] = None,
n_pcs: Optional[int] = None,
k_bounds: Optional[Tuple[int, int]] = None,
init: Literal[
"k-means++", "random", "polis"
] = "k-means++",
init_centers: Optional[ndarray] = None,
random_state: Optional[int] = None,
mask_obs: NDArray[bool_] | str | None = None,
key_added: str = "kmeans",
inplace: bool = True,
) -> AnnData | None
Apply BestPolisKMeans clustering to an AnnData object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adata
|
AnnData
|
Input data. Must have |
required |
use_rep
|
Optional[str]
|
Representation to use for clustering. If |
None
|
n_pcs
|
Optional[int]
|
Number of dimensions to use from the selected representation. If given,
only the first |
None
|
k_bounds
|
Optional[Tuple[int, int]]
|
Minimum and maximum number of clusters to try. Defaults to [2, 5]. |
None
|
init
|
Literal['k-means++', 'random', 'polis']
|
Initialization method for KMeans. Defaults to 'k-means++'. |
'k-means++'
|
init_centers
|
Optional[ndarray]
|
Initial cluster centers to use. |
None
|
random_state
|
Optional[int]
|
Random seed for reproducibility. |
None
|
mask_obs
|
NDArray[bool_] | str | None
|
Restrict clustering to a certain set of observations. The mask is specified as a boolean array or a string referring to an array in anndata.AnnData.obs. |
None
|
key_added
|
str
|
Name of the column to store cluster labels in |
'kmeans'
|
inplace
|
bool
|
If True, modify |
True
|
Returns:
| Type | Description |
|---|---|
AnnData or None
|
Returns a copy if |
Source code in src/valency_anndata/tools/_kmeans.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | |
valency_anndata.tools.pacmap ¶
pacmap(
adata: AnnData,
*,
layer: str = "X_imputed",
n_neighbors: Optional[int] = None,
n_components: int = 2,
mask_var: str | None = None,
key_added: str | None = None,
copy: bool = False,
) -> AnnData | None
Compute PaCMAP dimensionality reduction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adata
|
AnnData
|
AnnData object. |
required |
layer
|
str
|
Layer to use for computation. Default is "X_imputed". |
'X_imputed'
|
n_neighbors
|
Optional[int]
|
Number of neighbors for PaCMAP. |
None
|
n_components
|
int
|
Number of dimensions for the embedding. Default is 2. |
2
|
mask_var
|
str | None
|
Column name in |
None
|
key_added
|
str | None
|
Key under which to store the embedding in |
None
|
copy
|
bool
|
Return a copy instead of modifying adata in place. |
False
|
Returns:
| Type | Description |
|---|---|
AnnData | None
|
Returns AnnData if |
Source code in src/valency_anndata/tools/_pacmap.py
valency_anndata.tools.localmap ¶
localmap(
adata: AnnData,
*,
layer: str = "X_imputed",
n_neighbors: Optional[int] = None,
n_components: int = 2,
mask_var: str | None = None,
key_added: str | None = None,
copy: bool = False,
) -> AnnData | None
Compute LocalMAP dimensionality reduction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adata
|
AnnData
|
AnnData object. |
required |
layer
|
str
|
Layer to use for computation. Default is "X_imputed". |
'X_imputed'
|
n_neighbors
|
Optional[int]
|
Number of neighbors for LocalMAP. |
None
|
n_components
|
int
|
Number of dimensions for the embedding. Default is 2. |
2
|
mask_var
|
str | None
|
Column name in |
None
|
key_added
|
str | None
|
Key under which to store the embedding in |
None
|
copy
|
bool
|
Return a copy instead of modifying adata in place. |
False
|
Returns:
| Type | Description |
|---|---|
AnnData | None
|
Returns AnnData if |
Source code in src/valency_anndata/tools/_pacmap.py
scanpy methods (inherited)¶
Note
These methods are simply quick convenience wrappers around methods in scanpy, a tool for single-cell gene expression. They will use terms like "cells", "genes" and "counts", but you can think of these as "participants", "statements" and "votes".
See scanpy.tl for more methods you can experiment with via the val.scanpy.tl namespace.
valency_anndata.tools.pca ¶
pca(
data: AnnData | ndarray | CSBase,
n_comps: int | None = None,
*,
layer: str | None = None,
zero_center: bool = True,
svd_solver: SvdSolver | None = None,
chunked: bool = False,
chunk_size: int | None = None,
random_state: _LegacyRandom = 0,
return_info: bool = False,
mask_var: NDArray[bool_] | str | None | Empty = _empty,
use_highly_variable: bool | None = None,
dtype: DTypeLike = "float32",
key_added: str | None = None,
copy: bool = False,
) -> AnnData | ndarray | CSBase | None
Principal component analysis :cite:p:Pedregosa2011.
Computes PCA coordinates, loadings and variance decomposition.
Uses the following implementations (and defaults for svd_solver):
.. list-table:: :header-rows: 1 :stub-columns: 1
- -
- :class:
~numpy.ndarray, :class:~scipy.sparse.spmatrix, or :class:~scipy.sparse.sparray - :class:
dask.array.Array
- :class:
-
chunked=False,zero_center=True- sklearn :class:
~sklearn.decomposition.PCA('arpack') -
- dense: dask-ml :class:
~dask_ml.decomposition.PCA\ [#high-mem]_ ('auto')
- dense: dask-ml :class:
- sparse or
svd_solver='covariance_eigh': custom implementation ('covariance_eigh')
-
chunked=False,zero_center=False- sklearn :class:
~sklearn.decomposition.TruncatedSVD('randomized') - dask-ml :class:
~dask_ml.decomposition.TruncatedSVD\ [#dense-only]_ ('tsqr')
-
chunked=True(zero_centerignored)- sklearn :class:
~sklearn.decomposition.IncrementalPCA('auto') - dask-ml :class:
~dask_ml.decomposition.IncrementalPCA\ [#densifies]_ ('auto')
.. [#high-mem] Consider svd_solver='covariance_eigh' to reduce memory usage (see :issue:dask/dask-ml#985).
.. [#dense-only] This implementation can not handle sparse chunks, try manually densifying them.
.. [#densifies] This implementation densifies sparse chunks and therefore has increased memory usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
AnnData | ndarray | CSBase
|
The (annotated) data matrix of shape |
required |
n_comps
|
int | None
|
Number of principal components to compute. Defaults to 50, or 1 - minimum dimension size of selected representation. |
None
|
layer
|
str | None
|
If provided, which element of layers to use for PCA. |
None
|
zero_center
|
bool
|
If Our default PCA algorithms (see |
True
|
svd_solver
|
SvdSolver | None
|
SVD solver to use.
See table above to see which solver class is used based on Efficient computation of the principal components of a sparse matrix
currently only works with the
.. versionchanged:: 1.9.3
Default value changed from |
None
|
chunked
|
bool
|
If |
False
|
chunk_size
|
int | None
|
Number of observations to include in each chunk.
Required if |
None
|
random_state
|
_LegacyRandom
|
Change to use different initial states for the optimization. |
0
|
return_info
|
bool
|
Only relevant when not passing an :class: |
False
|
layer
|
str | None
|
Layer of |
None
|
dtype
|
DTypeLike
|
Numpy data type string to which to convert the result. |
'float32'
|
key_added
|
str | None
|
If not specified, the embedding is stored as
:attr: |
None
|
copy
|
bool
|
If an :class: |
False
|
Returns:
| Type | Description |
|---|---|
If `data` is array-like and `return_info=False` was passed,
|
|
this function returns the PCA representation of `data` as an
|
|
array of the same type as the input array.
|
|
Otherwise, it returns `None` if `copy=False`, else an updated `AnnData` object.
|
|
Sets the following fields:
|
|
`.obsm['X_pca' | key_added]` : :class:`~scipy.sparse.csr_matrix` | :class:`~scipy.sparse.csc_matrix` | :class:`~numpy.ndarray` (shape `(adata.n_obs, n_comps)`)
|
PCA representation of data. |
`.varm['PCs' | key_added]` : :class:`~numpy.ndarray` (shape `(adata.n_vars, n_comps)`)
|
The principal components containing the loadings. |
`.uns['pca' | key_added]['variance_ratio']` : :class:`~numpy.ndarray` (shape `(n_comps,)`)
|
Ratio of explained variance. |
`.uns['pca' | key_added]['variance']` : :class:`~numpy.ndarray` (shape `(n_comps,)`)
|
Explained variance, equivalent to the eigenvalues of the covariance matrix. |
Source code in .venv/lib/python3.10/site-packages/scanpy/preprocessing/_pca/__init__.py
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 | |
valency_anndata.tools.tsne ¶
tsne(
adata: AnnData,
n_pcs: int | None = None,
*,
use_rep: str | None = None,
perplexity: float = 30,
metric: str = "euclidean",
early_exaggeration: float = 12,
learning_rate: float = 1000,
random_state: _LegacyRandom = 0,
use_fast_tsne: bool = False,
n_jobs: int | None = None,
key_added: str | None = None,
copy: bool = False,
) -> AnnData | None
t-SNE :cite:p:vanDerMaaten2008,Amir2013,Pedregosa2011.
t-distributed stochastic neighborhood embedding (tSNE, :cite:t:vanDerMaaten2008) was
proposed for visualizating single-cell data by :cite:t:Amir2013. Here, by default,
we use the implementation of scikit-learn :cite:p:Pedregosa2011. You can achieve
a huge speedup and better convergence if you install Multicore-tSNE_
by :cite:t:Ulyanov2016, which will be automatically detected by Scanpy.
.. _multicore-tsne: https://github.com/DmitryUlyanov/Multicore-TSNE
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adata
|
AnnData
|
Annotated data matrix. |
required |
perplexity
|
float
|
The perplexity is related to the number of nearest neighbors that is used in other manifold learning algorithms. Larger datasets usually require a larger perplexity. Consider selecting a value between 5 and 50. The choice is not extremely critical since t-SNE is quite insensitive to this parameter. |
30
|
metric
|
str
|
Distance metric calculate neighbors on. |
'euclidean'
|
early_exaggeration
|
float
|
Controls how tight natural clusters in the original space are in the embedded space and how much space will be between them. For larger values, the space between natural clusters will be larger in the embedded space. Again, the choice of this parameter is not very critical. If the cost function increases during initial optimization, the early exaggeration factor or the learning rate might be too high. |
12
|
learning_rate
|
float
|
Note that the R-package "Rtsne" uses a default of 200. The learning rate can be a critical parameter. It should be between 100 and 1000. If the cost function increases during initial optimization, the early exaggeration factor or the learning rate might be too high. If the cost function gets stuck in a bad local minimum increasing the learning rate helps sometimes. |
1000
|
random_state
|
_LegacyRandom
|
Change this to use different intial states for the optimization.
If |
0
|
n_jobs
|
int | None
|
Number of jobs for parallel computation.
|
None
|
key_added
|
str | None
|
If not specified, the embedding is stored as
:attr: |
None
|
copy
|
bool
|
Return a copy instead of writing to |
False
|
Returns:
| Type | Description |
|---|---|
Returns `None` if `copy=False`, else returns an `AnnData` object. Sets the following fields:
|
|
`adata.obsm['X_tsne' | key_added]` : :class:`numpy.ndarray` (dtype `float`)
|
tSNE coordinates of data. |
`adata.uns['tsne' | key_added]` : :class:`dict`
|
tSNE parameters. |
Source code in .venv/lib/python3.10/site-packages/scanpy/tools/_tsne.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 | |
valency_anndata.tools.umap ¶
umap(
adata: AnnData,
*,
min_dist: float = 0.5,
spread: float = 1.0,
n_components: int = 2,
maxiter: int | None = None,
alpha: float = 1.0,
gamma: float = 1.0,
negative_sample_rate: int = 5,
init_pos: _InitPos | ndarray | None = "spectral",
random_state: _LegacyRandom = 0,
a: float | None = None,
b: float | None = None,
method: Literal["umap", "rapids"] = "umap",
key_added: str | None = None,
neighbors_key: str = "neighbors",
copy: bool = False,
) -> AnnData | None
Embed the neighborhood graph using UMAP :cite:p:McInnes2018.
UMAP (Uniform Manifold Approximation and Projection) is a manifold learning
technique suitable for visualizing high-dimensional data. Besides tending to
be faster than tSNE, it optimizes the embedding such that it best reflects
the topology of the data, which we represent throughout Scanpy using a
neighborhood graph. tSNE, by contrast, optimizes the distribution of
nearest-neighbor distances in the embedding such that these best match the
distribution of distances in the high-dimensional space.
We use the implementation of umap-learn_ :cite:p:McInnes2018.
For a few comparisons of UMAP with tSNE, see :cite:t:Becht2018.
.. _umap-learn: https://github.com/lmcinnes/umap
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adata
|
AnnData
|
Annotated data matrix. |
required |
min_dist
|
float
|
The effective minimum distance between embedded points. Smaller values
will result in a more clustered/clumped embedding where nearby points on
the manifold are drawn closer together, while larger values will result
on a more even dispersal of points. The value should be set relative to
the |
0.5
|
spread
|
float
|
The effective scale of embedded points. In combination with |
1.0
|
n_components
|
int
|
The number of dimensions of the embedding. |
2
|
maxiter
|
int | None
|
The number of iterations (epochs) of the optimization. Called |
None
|
alpha
|
float
|
The initial learning rate for the embedding optimization. |
1.0
|
gamma
|
float
|
Weighting applied to negative samples in low dimensional embedding optimization. Values higher than one will result in greater weight being given to negative samples. |
1.0
|
negative_sample_rate
|
int
|
The number of negative edge/1-simplex samples to use per positive edge/1-simplex sample in optimizing the low dimensional embedding. |
5
|
init_pos
|
_InitPos | ndarray | None
|
How to initialize the low dimensional embedding. Called
|
'spectral'
|
random_state
|
_LegacyRandom
|
If |
0
|
a
|
float | None
|
More specific parameters controlling the embedding. If |
None
|
b
|
float | None
|
More specific parameters controlling the embedding. If |
None
|
method
|
Literal['umap', 'rapids']
|
Chosen implementation.
|
'umap'
|
key_added
|
str | None
|
If not specified, the embedding is stored as
:attr: |
None
|
neighbors_key
|
str
|
Umap looks in
:attr: |
'neighbors'
|
copy
|
bool
|
Return a copy instead of writing to adata. |
False
|
Returns:
| Type | Description |
|---|---|
Returns `None` if `copy=False`, else returns an `AnnData` object. Sets the following fields:
|
|
`adata.obsm['X_umap' | key_added]` : :class:`numpy.ndarray` (dtype `float`)
|
UMAP coordinates of data. |
`adata.uns['umap' | key_added]` : :class:`dict`
|
UMAP parameters. |
Source code in .venv/lib/python3.10/site-packages/scanpy/tools/_umap.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 | |
valency_anndata.tools.leiden ¶
leiden(
adata: AnnData,
resolution: float = 1,
*,
restrict_to: tuple[str, Sequence[str]] | None = None,
random_state: _LegacyRandom = 0,
key_added: str = "leiden",
adjacency: CSBase | None = None,
directed: bool | None = None,
use_weights: bool = True,
n_iterations: int = -1,
partition_type: type[MutableVertexPartition]
| None = None,
neighbors_key: str | None = None,
obsp: str | None = None,
copy: bool = False,
flavor: Literal["leidenalg", "igraph"] = "leidenalg",
**clustering_args,
) -> AnnData | None
Cluster cells into subgroups :cite:p:Traag2019.
Cluster cells using the Leiden algorithm :cite:p:Traag2019,
an improved version of the Louvain algorithm :cite:p:Blondel2008.
It was proposed for single-cell analysis by :cite:t:Levine2015.
This requires having run :func:~scanpy.pp.neighbors or
:func:~scanpy.external.pp.bbknn first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adata
|
AnnData
|
The annotated data matrix. |
required |
resolution
|
float
|
A parameter value controlling the coarseness of the clustering.
Higher values lead to more clusters.
Set to |
1
|
random_state
|
_LegacyRandom
|
Change the initialization of the optimization. |
0
|
restrict_to
|
tuple[str, Sequence[str]] | None
|
Restrict the clustering to the categories within the key for sample
annotation, tuple needs to contain |
None
|
key_added
|
str
|
|
'leiden'
|
adjacency
|
CSBase | None
|
Sparse adjacency matrix of the graph, defaults to neighbors connectivities. |
None
|
directed
|
bool | None
|
Whether to treat the graph as directed or undirected. |
None
|
use_weights
|
bool
|
If |
True
|
n_iterations
|
int
|
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. |
-1
|
partition_type
|
type[MutableVertexPartition] | None
|
Type of partition to use.
Defaults to :class: |
None
|
neighbors_key
|
str | None
|
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. |
None
|
obsp
|
str | None
|
Use .obsp[obsp] as adjacency. You can't specify both
|
None
|
copy
|
bool
|
Whether to copy |
False
|
flavor
|
Literal['leidenalg', 'igraph']
|
Which package's implementation to use. |
'leidenalg'
|
**clustering_args
|
Any further arguments to pass to :func: |
{}
|
Returns:
| Type | Description |
|---|---|
Returns `None` if `copy=False`, else returns an `AnnData` object. Sets the following fields:
|
|
`adata.obs['leiden' | key_added]` : :class:`pandas.Series` (dtype ``category``)
|
Array of dim (number of samples) that stores the subgroup id
( |
`adata.uns['leiden' | key_added]['params']` : :class:`dict`
|
A dict with the values for the parameters |
Source code in .venv/lib/python3.10/site-packages/scanpy/tools/_leiden.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 | |