Neighbours and clusters¶
kNN search, the neighbour graph and clustering.
Start with find_neighbours on a PCA (or any cached embedding), then
find_clusters for Leiden or Louvain on the resulting graph. The UMAP and the
other embeddings in bv.embed, and the integration metrics in bv.integrate,
read the same kNN.
What lands where. find_neighbours writes the kNN to sc.cache.knn and
its symmetrised graph to sc.cache.connectivities, both stamped, so sc prints
what has gone stale. find_clusters writes the labels to an obs column, 0-based
with 0 the largest community. generate_knn, fast_cluster, calc_knn_metrics
and get_connectivities return their result and leave the experiment alone.
SingleCells works everywhere. SingleCellsSubset is accepted by all but
generate_knn, and its labels go to the subset's obs. find_neighbours,
find_clusters and get_connectivities also take MetaCells, and on a
SingleCellsMultiModal they reach the ADT and WNN graphs through modality.
bv.graph.find_neighbours(sc, neighbours_params=bv.params.NeighboursParams(k=15))
bv.graph.find_clusters(sc, res=1.0, name="leiden_clustering")
Big data, or only want rough labels? fast_cluster coarsens with k-means,
clusters the centroids and hands each cell the label of its centroid. With
several seeds it also reports how stable the labels are. To check an
approximate index, build an exact generate_knn as the reference and compare
with calc_knn_metrics.
Gotchas. The embedding must exist and be fresh: find_neighbours raises on
a stale PCA and warns and returns if the embedding is absent. find_clusters
raises if the graph is stale or does not cover the kept cells, so rebuild the
neighbours after moving the cell filter. Resolutions don't carry over between
knn_sym choices ("snn", "umap", "knn"): retune res when you switch.
bv.integrate.bbknn overwrites the kNN and the graph. The graph is the
symmetric CSR in sc.cache.connectivities; get_connectivities(sc).scipy_csr()
takes it to scipy, igraph or networkx.
Worked through in KNN searches for single cell and Clustering, cell type annotation and reference mapping.
Neighbour graph¶
kNN search, the neighbour graph and clustering.
Start with find_neighbours on a PCA (or any cached embedding), then
find_clusters for Leiden or Louvain on the resulting graph. The UMAP and the
other embeddings in bv.embed, and the integration metrics in bv.integrate,
read the same kNN.
What lands where. find_neighbours writes the kNN to sc.cache.knn and
its symmetrised graph to sc.cache.connectivities, both stamped, so sc prints
what has gone stale. find_clusters writes the labels to an obs column, 0-based
with 0 the largest community. generate_knn, fast_cluster, calc_knn_metrics
and get_connectivities return their result and leave the experiment alone.
SingleCells works everywhere. SingleCellsSubset is accepted by all but
generate_knn, and its labels go to the subset's obs. find_neighbours,
find_clusters and get_connectivities also take MetaCells, and on a
SingleCellsMultiModal they reach the ADT and WNN graphs through modality.
bv.graph.find_neighbours(sc, neighbours_params=bv.params.NeighboursParams(k=15))
bv.graph.find_clusters(sc, res=1.0, name="leiden_clustering")
Big data, or only want rough labels? fast_cluster coarsens with k-means,
clusters the centroids and hands each cell the label of its centroid. With
several seeds it also reports how stable the labels are. To check an
approximate index, build an exact generate_knn as the reference and compare
with calc_knn_metrics.
Gotchas. The embedding must exist and be fresh: find_neighbours raises on
a stale PCA and warns and returns if the embedding is absent. find_clusters
raises if the graph is stale or does not cover the kept cells, so rebuild the
neighbours after moving the cell filter. Resolutions don't carry over between
knn_sym choices ("snn", "umap", "knn"): retune res when you switch.
bv.integrate.bbknn overwrites the kNN and the graph. The graph is the
symmetric CSR in sc.cache.connectivities; get_connectivities(sc).scipy_csr()
takes it to scipy, igraph or networkx.
find_neighbours
¶
find_neighbours(
sc: ScOrMc,
*,
embd_to_use: str = "pca",
no_embd_to_use: int | None = None,
modality: CacheModality = "rna",
neighbours_params: NeighboursParams | None = None,
seed: int = 42,
verbose: Verbose = True,
) -> None
The kNN and the neighbour graph over an embedding.
The kNN goes to the modality's cache (sc.cache for RNA), stamped as
derived from the embedding, and its symmetrisation (knn_sym: sNN, UMAP
fuzzy simplicial set or kNN union) to its connectivities, stamped as
derived from "knn".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrMc
|
The experiment. |
required |
embd_to_use
|
str
|
The embedding, |
'pca'
|
no_embd_to_use
|
int | None
|
Number of leading dimensions to use. |
None
|
modality
|
CacheModality
|
|
'rna'
|
neighbours_params
|
NeighboursParams | None
|
kNN and graph parameters. |
None
|
seed
|
int
|
Seed for the index build. |
42
|
verbose
|
Verbose
|
|
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the embedding is stale, or on |
Examples:
get_connectivities
¶
get_connectivities(
sc: ScOrMc, *, modality: Modality = "rna"
) -> CsrMatrix | None
The neighbour graph.
The undirected graph as its symmetric CSR, rows sorted, every edge
stored in both directions. No graph library is pulled in: hand
.scipy_csr() to scipy, or the three vectors to igraph / networkx.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrMc
|
The experiment. |
required |
modality
|
Modality
|
|
'rna'
|
Returns:
| Type | Description |
|---|---|
CsrMatrix | None
|
The graph, or |
Clustering¶
kNN search, the neighbour graph and clustering.
Start with find_neighbours on a PCA (or any cached embedding), then
find_clusters for Leiden or Louvain on the resulting graph. The UMAP and the
other embeddings in bv.embed, and the integration metrics in bv.integrate,
read the same kNN.
What lands where. find_neighbours writes the kNN to sc.cache.knn and
its symmetrised graph to sc.cache.connectivities, both stamped, so sc prints
what has gone stale. find_clusters writes the labels to an obs column, 0-based
with 0 the largest community. generate_knn, fast_cluster, calc_knn_metrics
and get_connectivities return their result and leave the experiment alone.
SingleCells works everywhere. SingleCellsSubset is accepted by all but
generate_knn, and its labels go to the subset's obs. find_neighbours,
find_clusters and get_connectivities also take MetaCells, and on a
SingleCellsMultiModal they reach the ADT and WNN graphs through modality.
bv.graph.find_neighbours(sc, neighbours_params=bv.params.NeighboursParams(k=15))
bv.graph.find_clusters(sc, res=1.0, name="leiden_clustering")
Big data, or only want rough labels? fast_cluster coarsens with k-means,
clusters the centroids and hands each cell the label of its centroid. With
several seeds it also reports how stable the labels are. To check an
approximate index, build an exact generate_knn as the reference and compare
with calc_knn_metrics.
Gotchas. The embedding must exist and be fresh: find_neighbours raises on
a stale PCA and warns and returns if the embedding is absent. find_clusters
raises if the graph is stale or does not cover the kept cells, so rebuild the
neighbours after moving the cell filter. Resolutions don't carry over between
knn_sym choices ("snn", "umap", "knn"): retune res when you switch.
bv.integrate.bbknn overwrites the kNN and the graph. The graph is the
symmetric CSR in sc.cache.connectivities; get_connectivities(sc).scipy_csr()
takes it to scipy, igraph or networkx.
FastClusters
dataclass
¶
FastClusters(
memberships: DataFrame,
stats: DataFrame | None,
k_means_cluster: ndarray | None,
centroids: ndarray | None,
resolutions: tuple[float, ...],
)
Fast clustering result.
Attributes:
| Name | Type | Description |
|---|---|---|
memberships |
DataFrame
|
|
stats |
DataFrame | None
|
|
k_means_cluster |
ndarray | None
|
k-means centroid per cell, if asked for. |
centroids |
ndarray | None
|
|
resolutions |
tuple[float, ...]
|
The resolutions, in column order. |
find_clusters
¶
find_clusters(
sc: ScOrMc,
*,
cluster_algorithm: ClusterAlgorithm = "leiden",
res: float = 1.0,
name: str = "leiden_clustering",
modality: Modality = "rna",
seed: int = 42,
beta: float = 0.01,
n_iterations: int | None = None,
min_gain: float = 0.0,
local_moving: LocalMoving | None = None,
node_order: NodeOrder | None = None,
) -> None
Leiden or Louvain on the neighbour graph.
The communities go to obs column name as 0-based integers, 0 the
largest. Depends on seed only, not on the thread count.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrMc
|
The experiment, with a neighbour graph over the kept cells. |
required |
cluster_algorithm
|
ClusterAlgorithm
|
|
'leiden'
|
res
|
float
|
Modularity resolution; higher gives more communities. |
1.0
|
name
|
str
|
The obs column to write. |
'leiden_clustering'
|
modality
|
Modality
|
The graph: |
'rna'
|
seed
|
int
|
Seed. |
42
|
beta
|
float
|
Randomness of the Leiden refinement. Ignored by Louvain. |
0.01
|
n_iterations
|
int | None
|
Full iterations, each starting from the previous
partition; negative iterates until stable. |
None
|
min_gain
|
float
|
With a negative |
0.0
|
local_moving
|
LocalMoving | None
|
|
None
|
node_order
|
NodeOrder | None
|
Visit order of the queue, |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the graph is stale or does not cover the kept cells. |
References
Traag, Waltman & van Eck, Sci Rep, 2019; Blondel, et al., J Stat Mech, 2008.
Examples:
fast_cluster
¶
fast_cluster(
sc: ScOrScSubset,
*,
embd_to_use: str = "pca",
no_embd_to_use: int | None = None,
resolutions: Sequence[float] = (2.0, 1.0, 0.5),
fc_params: FastClusterParams | None = None,
n_seeds: int = 1,
return_kmeans: bool = False,
seed: int = 42,
verbose: Verbose = True,
) -> FastClusters
k-means coarsening, a centroid graph and Louvain / Leiden on it.
Each cell inherits the community of its centroid. With n_seeds > 1
every resolution runs once per seed; the labels come from the seed with
the lowest mean conductance and the stability across seeds is returned.
Does not touch the experiment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
ScOrScSubset
|
The experiment. |
required |
embd_to_use
|
str
|
The embedding, |
'pca'
|
no_embd_to_use
|
int | None
|
Number of leading dimensions to use. |
None
|
resolutions
|
Sequence[float]
|
Modularity resolutions. |
(2.0, 1.0, 0.5)
|
fc_params
|
FastClusterParams | None
|
The parameters. |
None
|
n_seeds
|
int
|
Seeds per resolution; 1 skips the stability statistics. |
1
|
return_kmeans
|
bool
|
Return the k-means assignments and centroids. |
False
|
seed
|
int
|
Seed. |
42
|
verbose
|
Verbose
|
|
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the embedding is absent, or on an empty resolution
list or |
References
Wei, et al., PLoS Comput Biol, 2022.
Examples:
kNN searches and their quality¶
kNN search, the neighbour graph and clustering.
Start with find_neighbours on a PCA (or any cached embedding), then
find_clusters for Leiden or Louvain on the resulting graph. The UMAP and the
other embeddings in bv.embed, and the integration metrics in bv.integrate,
read the same kNN.
What lands where. find_neighbours writes the kNN to sc.cache.knn and
its symmetrised graph to sc.cache.connectivities, both stamped, so sc prints
what has gone stale. find_clusters writes the labels to an obs column, 0-based
with 0 the largest community. generate_knn, fast_cluster, calc_knn_metrics
and get_connectivities return their result and leave the experiment alone.
SingleCells works everywhere. SingleCellsSubset is accepted by all but
generate_knn, and its labels go to the subset's obs. find_neighbours,
find_clusters and get_connectivities also take MetaCells, and on a
SingleCellsMultiModal they reach the ADT and WNN graphs through modality.
bv.graph.find_neighbours(sc, neighbours_params=bv.params.NeighboursParams(k=15))
bv.graph.find_clusters(sc, res=1.0, name="leiden_clustering")
Big data, or only want rough labels? fast_cluster coarsens with k-means,
clusters the centroids and hands each cell the label of its centroid. With
several seeds it also reports how stable the labels are. To check an
approximate index, build an exact generate_knn as the reference and compare
with calc_knn_metrics.
Gotchas. The embedding must exist and be fresh: find_neighbours raises on
a stale PCA and warns and returns if the embedding is absent. find_clusters
raises if the graph is stale or does not cover the kept cells, so rebuild the
neighbours after moving the cell filter. Resolutions don't carry over between
knn_sym choices ("snn", "umap", "knn"): retune res when you switch.
bv.integrate.bbknn overwrites the kNN and the graph. The graph is the
symmetric CSR in sc.cache.connectivities; get_connectivities(sc).scipy_csr()
takes it to scipy, igraph or networkx.
KnnMetrics
dataclass
¶
A kNN compared against a reference.
Attributes:
| Name | Type | Description |
|---|---|---|
all_matches |
ndarray
|
Neighbours shared with the reference, per cell. |
all_ratios |
ndarray
|
Summed query over summed reference distance, per cell. Cells whose reference distances sum to about zero are skipped. |
final_recall |
float
|
Mean recall over all cells. |
final_ratio |
float
|
Mean of |
generate_knn
¶
generate_knn(
sc: SingleCells,
*,
embd_to_use: str = "pca",
cells_to_use: Sequence[str] | None = None,
no_embd_to_use: int | None = None,
neighbours_params: NeighboursParams
| KnnParams
| None = None,
seed: int = 42,
validate_index: bool = True,
verbose: Verbose = True,
) -> KnnGraph | None
A kNN over an embedding, without touching the experiment.
Exact methods: "kmknn" (the default) and "exhaustive". Approximate:
"hnsw", "nndescent" (the descent graph, handed back without a query
pass), "ivf" and "annoy".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sc
|
SingleCells
|
The experiment. |
required |
embd_to_use
|
str
|
The embedding, |
'pca'
|
cells_to_use
|
Sequence[str] | None
|
Cell ids to restrict the kNN to; they keep the
embedding's row order. |
None
|
no_embd_to_use
|
int | None
|
Number of leading dimensions to use. |
None
|
neighbours_params
|
NeighboursParams | KnnParams | None
|
The kNN parameters. |
None
|
seed
|
int
|
Seed for the index build. |
42
|
validate_index
|
bool
|
With |
True
|
verbose
|
Verbose
|
|
True
|
Returns:
| Type | Description |
|---|---|
KnnGraph | None
|
The kNN, indices into the rows used; |
KnnGraph | None
|
embedding is absent. |
Examples:
calc_knn_metrics
¶
calc_knn_metrics(
ref_knn: KnnGraph, query_knn: KnnGraph
) -> KnnMetrics