Skip to content

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" or a name in the cache's embeddings.

'pca'
no_embd_to_use int | None

Number of leading dimensions to use. None for all.

None
modality CacheModality

"rna", or "adt" / "atac" on a SingleCellsMultiModal.

'rna'
neighbours_params NeighboursParams | None

kNN and graph parameters. None uses the defaults.

None
seed int

Seed for the index build.

42
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Raises:

Type Description
ValueError

If the embedding is stale, or on "adt" / "atac" without a multi-modal object.

Examples:

>>> bv.graph.find_neighbours(sc, no_embd_to_use=20)
>>> bv.graph.find_neighbours(
...     sc, neighbours_params=bv.params.NeighboursParams(k=30, knn_sym="umap")
... )

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", or "adt" / "atac" / "wnn" on a SingleCellsMultiModal.

'rna'

Returns:

Type Description
CsrMatrix | None

The graph, or None (with a warning) if none was built.

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

cell_idx (0-based) and one community column per resolution, res_<value>, 0 the largest.

stats DataFrame | None

resolution, mean_ari, median_ari, mean_conductance, median_conductance and mean_n_comms; None for one seed.

k_means_cluster ndarray | None

k-means centroid per cell, if asked for.

centroids ndarray | None

(n_centroids, n_dims) centroids, if asked for.

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" or "louvain".

'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", or "adt" / "atac" / "wnn" on a SingleCellsMultiModal.

'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 is 2.

None
min_gain float

With a negative n_iterations, also stop once an iteration gains no more than this.

0.0
local_moving LocalMoving | None

"queue" (Traag's sequential queue) or "coloured" (parallel colour classes on large levels). None is "queue" for Leiden and "coloured" for Louvain.

None
node_order NodeOrder | None

Visit order of the queue, "bfs" (sweep in BFS order from a random start, about half the work) or "shuffle" (as igraph). None is "bfs" for Leiden and "shuffle" for Louvain.

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:

>>> bv.graph.find_clusters(sc, res=0.5, name="leiden_05")
>>> bv.graph.find_clusters(sc, cluster_algorithm="louvain", name="louvain")

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" or a name in sc.cache.embeddings.

'pca'
no_embd_to_use int | None

Number of leading dimensions to use. None for all.

None
resolutions Sequence[float]

Modularity resolutions.

(2.0, 1.0, 0.5)
fc_params FastClusterParams | None

The parameters. None uses the defaults; a None n_centroids becomes floor(4 * sqrt(n_cells)) and a None n_iterations 2.

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

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Raises:

Type Description
ValueError

If the embedding is absent, or on an empty resolution list or n_seeds < 1.

References

Wei, et al., PLoS Comput Biol, 2022.

Examples:

>>> fast = bv.graph.fast_cluster(sc, resolutions=(1.0, 0.5))
>>> memberships = fast.memberships
>>> fast = bv.graph.fast_cluster(sc, n_seeds=3, return_kmeans=True)

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

KnnMetrics(
    all_matches: ndarray,
    all_ratios: ndarray,
    final_recall: float,
    final_ratio: float,
)

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 all_ratios.

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" or a name in sc.cache.embeddings.

'pca'
cells_to_use Sequence[str] | None

Cell ids to restrict the kNN to; they keep the embedding's row order. None for all kept cells.

None
no_embd_to_use int | None

Number of leading dimensions to use. None for all.

None
neighbours_params NeighboursParams | KnnParams | None

The kNN parameters. None uses the defaults.

None
seed int

Seed for the index build.

42
validate_index bool

With verbose, report the recall of an approximate index against an exhaustive search on a random subset.

True
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
KnnGraph | None

The kNN, indices into the rows used; None (with a warning) if the

KnnGraph | None

embedding is absent.

Examples:

>>> knn = bv.graph.generate_knn(sc)
>>> knn_hnsw = bv.graph.generate_knn(
...     sc, neighbours_params=bv.params.NeighboursParams(knn_method="hnsw")
... )

calc_knn_metrics

calc_knn_metrics(
    ref_knn: KnnGraph, query_knn: KnnGraph
) -> KnnMetrics

Recall at k and distance ratio of a kNN against a reference.

Parameters:

Name Type Description Default
ref_knn KnnGraph

The reference, e.g. an exhaustive search.

required
query_knn KnnGraph

The kNN to evaluate.

required

Raises:

Type Description
ValueError

If the two differ in cells or k.

Examples:

>>> ref_knn = bv.graph.generate_knn(sc, no_embd_to_use=20)
>>> query_knn = bv.graph.generate_knn(
...     sc,
...     no_embd_to_use=20,
...     neighbours_params=bv.params.NeighboursParams(knn_method="annoy"),
... )
>>> metrics = bv.graph.calc_knn_metrics(ref_knn, query_knn)