Clustering, cell type annotation and reference mapping¶
Python port of the R vignette Clustering, cell type annotation and reference mapping. Original author: Gregor Lueg.
Intro¶
Getting from a corrected embedding to cell type labels involves more choices
than a single find_clusters() call suggests. Which graph do you cluster on?
Leiden or Louvain, and how many iterations? Do you cluster every cell, or
coarsen first because you have a million of them? Do you stamp one label per
cluster, or score each cell? And once you have a well annotated data set, how
do you avoid redoing all of it every time a new sample lands on your desk?
This vignette goes through these decisions in that order:
- Build a reference from two PBMC data sets (pbmc3k + pbmc4k), corrected with Harmony v2.
- Compare the three neighbour graphs bixverse can build (sNN, the UMAP fuzzy simplicial set and the plain kNN union) and what they do to the clustering.
- Leiden vs Louvain, and the fast clustering via k-means coarsening.
- Annotate with scType, per cluster and per cell.
- Compress the reference with Symphony (Kang, et al., 2021), map a third PBMC data set (pbmc8k) into it and transfer the labels.
If you have not read the batch correction vignette and the introductory vignette, please do so first; this vignette assumes familiarity with both.
import tempfile
from pathlib import Path
from typing import Literal
import matplotlib.pyplot as plt
import numpy as np
import polars as pl
import bixverse as bv
import bixverse.embed
from bixverse.params import FastClusterParams, HarmonyV2Params, NeighboursParams
Building the reference data¶
Loading the reference batches¶
We use the same pbmc3k + pbmc4k pair as in the batch correction vignette. Two batches with the same broad cell type composition and a clear technical difference between them is exactly the situation Symphony is designed for: the reference learns the batch correction once, and that correction can then be applied to future queries without rerunning Harmony.
dir_data = bv.io.download_pbmc_batches()
tempdir_ref = tempfile.TemporaryDirectory()
h5ad_paths = {
"pbmc3k": dir_data / "pbmc3k.h5ad",
"pbmc4k": dir_data / "pbmc4k.h5ad",
}
h5_tasks = bv.io.prescan_h5ad_files(h5ad_paths)
sc_ref = bv.io.load_multi_h5ad(
Path(tempdir_ref.name) / "symphony_ref",
h5_tasks,
verbose=True,
)
sc_ref
Scan 1/2: Counting gene expression across 2 files... Scanning genes in pbmc3k... Scanning genes in pbmc4k... Genes passing global QC: 13_925 / 31_232 Scan 2/2: Computing cell QC with final gene set... Scanning cells in pbmc3k... Scanning cells in pbmc4k... pbmc3k: 2_700 / 2_700 cells passing QC pbmc4k: 4_340 / 4_340 cells passing QC Total cells: 7_040 Writing cells to binary... Writing pbmc3k (2_700 cells)... Writing pbmc4k (4_340 cells)... Converting the cell-based data into the gene-based format. Multi-h5ad loading complete: 161.83ms
Counted 7_889_186 non-zeros over 13_925 genes in 3.20ms; converting in 1 phase(s). Phase 1/1: genes 0-13925, scatter 13.61ms, compress + write 10.81ms Conversion into gene-friendly format done: 28.77ms
SingleCells( dir='/var/folders/l0/d50zd8812jg94mhtl8t2swfc0000gn/T/tmpa_9vnu1x/symphony_ref', cells=7040 (kept 7040), genes=13925, hvg=False, pca=False, embeddings=none, knn=False, graph=False, magic=False, residuals=False, stale=none )
Quality control¶
Standard QC: mitochondrial gene proportions, library complexity, MAD-based outlier detection.
# the gene symbols come from one of the h5ad files: the multi file import
# keeps only gene_id in var
h5_metadata = bv.io.read_h5ad_metadata(h5ad_paths["pbmc3k"])
h5_var = h5_metadata["var"]
assert isinstance(h5_var, pl.DataFrame)
var_ref = sc_ref.var().join(
h5_var.select("gene_id", pl.col("symbol_tenx").alias("gene_symbol")),
on="gene_id",
)
gs_of_interest = {
"MT": var_ref.filter(pl.col("gene_symbol").str.contains("^MT-"))[
"gene_id"
].to_list(),
"Ribo": var_ref.filter(pl.col("gene_symbol").str.contains("^RP[SL]"))[
"gene_id"
].to_list(),
}
bv.qc.gene_set_proportions(sc_ref, gs_of_interest, streaming=False, verbose=True)
qc_df = sc_ref.obs(cols=["cell_id", "lib_size", "nnz", "MT", "exp_id"])
qc = bv.qc.run_cell_qc(
{
"log10_lib_size": np.log10(qc_df["lib_size"].to_numpy()),
"log10_nnz": np.log10(qc_df["nnz"].to_numpy()),
"MT": qc_df["MT"].to_numpy(),
},
sc_ref.cells_to_keep,
directions={
"log10_lib_size": "twosided",
"log10_nnz": "twosided",
"MT": "above",
},
threshold=3.0,
)
sc_ref.add_obs(pl.DataFrame({"cell_idx": qc.cell_idx, "outlier": qc.combined}))
sc_ref.set_cells_to_keep(qc.cell_idx[~qc.combined])
print(f"{qc.combined.sum()} of {qc.combined.size} cells flagged")
Load in data: 8.10ms Finished the gene set proportion calculations: 2.44ms 414 of 7040 cells flagged
HVGs, PCA, Harmony v2¶
This block is the Harmony v2 path of the batch correction vignette: pick HVGs,
run PCA, run Harmony v2, which is what bv.integrate.harmony() runs. Version
1 is still available via bv.integrate.harmony_v1() and HarmonyParams, but
v2 is preferable in most settings (see the batch correction vignette for the
reasoning).
bv.pp.find_hvg(sc_ref, hvg_no=2000, verbose=True)
bv.pp.calculate_pca(sc_ref, no_pcs=30)
bv.integrate.harmony(sc_ref, "exp_id", harmony_params=HarmonyV2Params())
HVG (VST): 13_925 genes, 1 batches, 1 disk block(s) HVG (VST): Calculated gene statistics in 10.78ms HVG (VST): Fitted Loess in 655.67µs HVG (VST): Standardised variance in 1.01ms (690 gene(s) re-read for the clip) HVG (VST): Total run time -> 12.50ms Using sparse SVD solving on scaled data on 2000 HVG.
Sparse PCA: Loaded in data in 12.03ms Sparse PCA: finished the data preparations in 2.12ms
Sparse PCA: finished calculations in 265.11ms Sparse PCA: total run time -> 279.38ms Auto-determined number of Harmony clusters: 100
Harmony v2: 6_626 cells, 30 dims, 1 variable(s), 100 clusters Variable 0: 2 levels Initial data preparation done in 520.88µs Running initial k-means... Initial objective: 318.7685 === Harmony v2 iteration 1 === Running k-means clustering... Applying ridge regression correction... Harmony objective: 299.8384 Finished iteration in 8.20ms / Total runtime 37.54ms === Harmony v2 iteration 2 === Running k-means clustering... Applying ridge regression correction... Harmony objective: 192.9918 Finished iteration in 8.29ms / Total runtime 45.84ms === Harmony v2 iteration 3 === Running k-means clustering... Applying ridge regression correction... Harmony objective: 120.4948 Finished iteration in 8.25ms / Total runtime 54.09ms === Harmony v2 iteration 4 === Running k-means clustering... Applying ridge regression correction... Harmony objective: 99.1038 Finished iteration in 8.78ms / Total runtime 62.88ms === Harmony v2 iteration 5 === Running k-means clustering... Applying ridge regression correction... Harmony objective: 94.8485 Finished iteration in 8.10ms / Total runtime 70.99ms === Harmony v2 iteration 6 === Running k-means clustering... Applying ridge regression correction... Harmony objective: 92.6682 Finished iteration in 7.74ms / Total runtime 78.74ms === Harmony v2 iteration 7 === Running k-means clustering... Applying ridge regression correction... Harmony objective: 91.7636 Finished iteration in 8.27ms / Total runtime 87.02ms Harmony v2 converged at iteration 7 Finished Harmony 87.03ms
Which graph to cluster on¶
find_neighbours() does two things: it finds the kNN on the embedding and it
symmetrises that kNN into the undirected, weighted graph the clustering runs
on. The second step is controlled by knn_sym in NeighboursParams. Three
options:
"snn"(default): the shared nearest neighbour graph of bluster/Seurat. Two cells are linked if their neighbourhoods overlap, weighted by Jaccard (or rank), and weak edges belowpruningare dropped."umap": the fuzzy simplicial set from UMAP, i.e. what ScanPy stores inobsp/connectivities. Use this if you want your Leiden clusters to line up with a ScanPy pipeline."knn": the plain union of the kNN, every edge weighted 1.
Let's build all three on the Harmony embedding and cluster each across a few resolutions. Every call recomputes the kNN as well, which at ~6k cells costs nothing.
graph_types: list[Literal["snn", "umap", "knn"]] = ["snn", "umap", "knn"]
resolutions = [0.5, 1.0, 1.5, 2.0]
rows = []
for graph_type in graph_types:
bv.graph.find_neighbours(
sc_ref,
embd_to_use="harmony",
neighbours_params=NeighboursParams(knn_sym=graph_type),
)
for res in resolutions:
col_name = f"leiden_{graph_type}_{res}"
bv.graph.find_clusters(sc_ref, res=res, name=col_name)
n = sc_ref.obs(cols=[col_name], filtered=True)[col_name].n_unique()
rows.append({"graph": graph_type, "resolution": res, "n_clusters": n})
n_clusters = pl.DataFrame(rows)
n_clusters.pivot("graph", index="resolution", values="n_clusters")
Generating kNN data with kmknn method.
Building kMkNN index ... ... built kMkNN index in 22.37ms Generated KmKnn index: 22.72ms Querying kMkNN index (self) ... ... queried kMkNN index (self) in 14.31ms Queried KmKnn index: 14.35ms Generating the snn graph.
Added 0 edges to reconnect components that pruning cut off.
Built the Snn { similarity: Jaccard, prune: 0.0625, rescue: true } graph: 14.65ms
Generating kNN data with kmknn method.
Building kMkNN index ... ... built kMkNN index in 21.13ms Generated KmKnn index: 21.48ms Querying kMkNN index (self) ... ... queried kMkNN index (self) in 13.79ms Queried KmKnn index: 13.84ms Generating the umap graph.
Built the Umap { local_connectivity: 1.0, mix_ratio: 1.0 } graph: 5.48ms
Generating kNN data with kmknn method.
Building kMkNN index ... ... built kMkNN index in 22.39ms Generated KmKnn index: 22.78ms Querying kMkNN index (self) ... ... queried kMkNN index (self) in 13.83ms Queried KmKnn index: 13.87ms Generating the knn graph.
Built the Knn { binary: false } graph: 1.66ms
| resolution | snn | umap | knn |
|---|---|---|---|
| f64 | i64 | i64 | i64 |
| 0.5 | 13 | 12 | 10 |
| 1.0 | 15 | 17 | 13 |
| 1.5 | 19 | 20 | 17 |
| 2.0 | 21 | 23 | 20 |
The point of this table: resolutions do not carry over between graphs. The
"umap" and "knn" graphs only hold the kNN pairs, while the sNN graph also
links cells that merely share neighbours and prunes weak edges. On this data
the differences are a handful of communities at a given resolution, and not
always in the same direction. On other data they can be larger. If you move a
ScanPy pipeline over and switch to knn_sym="umap", keep its resolution; if
you switch to sNN, retune it.
For the rest of the vignette we work on the sNN graph.
bv.graph.find_neighbours(
sc_ref,
embd_to_use="harmony",
neighbours_params=NeighboursParams(),
)
bv.embed.umap(sc_ref, embd_to_use="harmony", slot_name="umap_harm_v2")
Generating kNN data with kmknn method.
Building kMkNN index ... ... built kMkNN index in 20.51ms Generated KmKnn index: 20.87ms Querying kMkNN index (self) ... ... queried kMkNN index (self) in 11.97ms Queried KmKnn index: 12.01ms Generating the snn graph.
Added 0 edges to reconnect components that pruning cut off.
Built the Snn { similarity: Jaccard, prune: 0.0625, rescue: true } graph: 13.67ms
Clustering¶
Leiden vs Louvain¶
Both run in Rust, and the labels depend on seed only, not on the global RNG
or the number of threads. Leiden is the default; it guarantees connected
communities, which Louvain does not
(Traag, et al., 2019).
Labels are 0-based with 0 being the largest cluster.
bv.graph.find_clusters(sc_ref, res=1.0, name="leiden_clusters")
bv.graph.find_clusters(
sc_ref,
cluster_algorithm="louvain",
res=1.0,
name="louvain_clusters",
)
A few knobs on find_clusters():
n_iterations: defaults to2for both. A negative value iterates until the partition is stable.min_gain: with a negativen_iterations, also stop once an iteration gains no more than this in modularity.local_moving:"queue"is Traag's sequential queue,"coloured"moves the nodes of one colour class in parallel. The latter only kicks in on the larger levels of the graph, so on 6k cells don't expect much. Leiden defaults to the queue, Louvain to colour classes.node_order: the visit order of the queue,"bfs"(Leiden's default) or"shuffle"(Louvain's).
bv.graph.find_clusters(
sc_ref,
res=1.0,
name="leiden_stable",
n_iterations=-1,
min_gain=1e-4,
local_moving="coloured",
)
How much do the three labelings agree? A small helper that plots, for each cluster of one labeling, how its cells spread across the clusters of another:
def plot_overlap(a, b, name_a, name_b, title):
df = (
pl.DataFrame({"a": a, "b": b})
.group_by("a", "b")
.len()
.with_columns(frac=pl.col("len") / pl.col("len").sum().over("a"))
)
a_levels = np.sort(df["a"].unique().to_numpy())
b_levels = np.sort(df["b"].unique().to_numpy())
mat = np.full((a_levels.size, b_levels.size), np.nan)
ai = np.searchsorted(a_levels, df["a"].to_numpy())
bi = np.searchsorted(b_levels, df["b"].to_numpy())
mat[ai, bi] = df["frac"].to_numpy()
fig, ax = plt.subplots(figsize=(7, 5), layout="constrained")
im = ax.imshow(mat, cmap="viridis", vmin=0, vmax=1, origin="lower", aspect="auto")
# light text on the dark end of viridis, dark text on the yellow end
for i, j, f in zip(ai, bi, df["frac"].to_numpy(), strict=True):
ax.text(
float(j),
float(i),
f"{f:.2f}",
ha="center",
va="center",
fontsize=6,
color="white" if f < 0.5 else "black",
)
ax.set_xticks(range(b_levels.size), b_levels)
ax.set_yticks(range(a_levels.size), a_levels)
ax.set_xlabel(name_b)
ax.set_ylabel(name_a)
ax.set_title(title)
fig.colorbar(im, ax=ax, label="Fraction")
return ax
clusters_df = sc_ref.obs(
cols=["leiden_clusters", "louvain_clusters", "leiden_stable"], filtered=True
)
plot_overlap(
clusters_df["leiden_clusters"],
clusters_df["louvain_clusters"],
"Leiden",
"Louvain",
"Leiden vs Louvain (res = 1)",
)
plt.show()
plot_overlap(
clusters_df["leiden_clusters"],
clusters_df["leiden_stable"],
"Leiden (2 iterations)",
"Leiden (until stable)",
"Fixed iterations vs iterating until stable",
)
plt.show()
Fast clustering¶
On a few thousand cells the full graph clustering is instant. On a million it
isn't. fast_cluster() coarsens the cells with k-means first
(floor(4 * sqrt(N)) centroids by default, the faiss default for IVF), builds
a graph over the centroids and runs Louvain or Leiden on that. Each cell
inherits the community of its centroid. Two options for the centroid graph:
- the default, a symmetrised kNN between the centroids (
centroid_k,knn_sym); cell_mediated=True, the Secuer graph (Wei, et al., PLoS Comput Biol, 2022), where each cell links itsn_anchorsnearest centroids, so two centroids are connected if they share cells.
With n_seeds > 1 every resolution is run once per seed. The labels of the
seed with the lowest mean conductance are kept, and the ARI and conductance
across seeds come back as stability statistics.
fc_resolutions = (2.0, 1.5, 1.0, 0.5)
fc_knn = bv.graph.fast_cluster(
sc_ref,
embd_to_use="harmony",
resolutions=fc_resolutions,
n_seeds=10,
)
assert fc_knn is not None
fc_cell_med = bv.graph.fast_cluster(
sc_ref,
embd_to_use="harmony",
resolutions=fc_resolutions,
fc_params=FastClusterParams(cell_mediated=True),
n_seeds=10,
)
assert fc_cell_med is not None
k-means with 325 centroids: 26.61ms
Added 0 edges to reconnect components that pruning cut off.
Built the Snn { similarity: Jaccard, prune: 0.0625, rescue: true } graph: 569.92µs
Centroid graph: 1.43ms
Community detection: 26.30ms
k-means with 325 centroids: 26.34ms
Centroid graph: 4.46ms
Community detection: 22.49ms
The stats help to pick a resolution: high ARI means the partition barely changes between seeds, low conductance means the communities are well separated in the centroid graph.
assert fc_knn.stats is not None and fc_cell_med.stats is not None
fc_stats = pl.concat(
[
fc_knn.stats.with_columns(graph=pl.lit("centroid kNN")),
fc_cell_med.stats.with_columns(graph=pl.lit("cell-mediated")),
]
)
fc_stats
| resolution | mean_ari | median_ari | mean_conductance | median_conductance | mean_n_comms | graph |
|---|---|---|---|---|---|---|
| f64 | f64 | f64 | f64 | f64 | f64 | str |
| 2.0 | 0.948583 | 0.968529 | 0.197583 | 0.149728 | 8.8 | "centroid kNN" |
| 1.5 | 0.94605 | 0.937371 | 0.136998 | 0.140355 | 7.2 | "centroid kNN" |
| 1.0 | 1.0 | 1.0 | 0.052299 | 0.04312 | 5.0 | "centroid kNN" |
| 0.5 | 0.99732 | 1.0 | 0.050949 | 0.04312 | 5.0 | "centroid kNN" |
| 2.0 | 0.96134 | 0.965788 | 0.200439 | 0.169538 | 13.0 | "cell-mediated" |
| 1.5 | 0.964965 | 0.970662 | 0.116937 | 0.109002 | 9.0 | "cell-mediated" |
| 1.0 | 0.965596 | 0.965837 | 0.115929 | 0.107242 | 9.0 | "cell-mediated" |
| 0.5 | 0.95264 | 0.950164 | 0.084495 | 0.076132 | 6.9 | "cell-mediated" |
fig, axes = plt.subplots(1, 2, figsize=(7, 4), layout="constrained")
graphs = ["centroid kNN", "cell-mediated"]
colours = bv.pl.bx_colors("main", n=len(graphs))
for ax, metric in zip(axes, ["mean_ari", "mean_conductance"], strict=True):
for graph, colour in zip(graphs, colours, strict=True):
df = fc_stats.filter(pl.col("graph") == graph).sort("resolution")
ax.plot(df["resolution"], df[metric], marker="o", color=colour, label=graph)
ax.set_title(metric)
ax.set_xlabel("Resolution")
axes[1].legend(title="Centroid graph", loc="center left", bbox_to_anchor=(1, 0.5))
plt.show()
And how does the coarsened version compare against Leiden on the full graph?
sc_ref.add_obs(fc_cell_med.memberships)
fast_df = sc_ref.obs(cols=["leiden_clusters", "res_1"], filtered=True)
plot_overlap(
fast_df["leiden_clusters"],
fast_df["res_1"],
"Leiden (full graph)",
"Fast clustering (cell-mediated, res = 1)",
"Full vs fast clustering",
)
plt.show()
The numbers behind the plot:
n_cells_ref = sc_ref.n_cells
print(f"cells: {n_cells_ref}, centroids: {int(4 * np.sqrt(n_cells_ref))}")
print(f"Leiden (full graph), res = 1: {fast_df['leiden_clusters'].n_unique()}")
print(f"fast clustering (cell-mediated), res = 1: {fast_df['res_1'].n_unique()}")
cells: 6626, centroids: 325 Leiden (full graph), res = 1: 15 fast clustering (cell-mediated), res = 1: 9
With a few hundred centroids the partition comes out coarser than Leiden on
the full graph at the same resolution, and the centroid boundaries cut through
some of the full graph communities. For data sets of this size, stick with
find_clusters(). The fast path earns its keep once you are in the hundreds
of thousands of cells, see the
1 million cells vignette.
Cell type annotation¶
scType per cluster¶
We annotate with scType (Ianevski, et al., Nat Comm, 2022) using a PBMC marker set.
cell_markers = {
"CD3D": "T cells",
"CD3E": "T cells",
"CD3G": "T cells",
"IL7R": "CD4+ T",
"CD4": "CD4+ T",
"CD8A": "CD8+ T",
"CD8B": "CD8+ T",
"MS4A1": "B cells",
"CD79A": "B cells",
"CD19": "B cells",
"CD14": "CD14+ Mono",
"LYZ": "CD14+ Mono",
"S100A8": "CD14+ Mono",
"FCGR3A": "CD16+ Mono",
"CDKN1C": "CD16+ Mono",
"GNLY": "NK",
"NKG7": "NK",
"NCAM1": "NK",
"FCER1A": "mDC",
"CD1C": "mDC",
"LILRA4": "pDC",
"CLEC4C": "pDC",
"PPBP": "Platelet",
"PF4": "Platelet",
}
calc_sc_type_scores() scores every cell against every marker set,
score_clusters() sums the scores per cluster and assigns the winner.
cell_markers_df = pl.DataFrame(
{"gene_symbol": list(cell_markers), "cell_type": list(cell_markers.values())}
).join(var_ref.select("gene_symbol", "gene_id"), on="gene_symbol")
marker_list = bv.annotate.prepare_cell_markers(sc_ref, cell_markers_df)
sctype_scores = bv.annotate.calc_sc_type_scores(sc_ref, marker_list)
leiden = sc_ref.obs(cols=["leiden_clusters"], filtered=True)["leiden_clusters"]
cell_type_anno = bv.annotate.score_clusters(sctype_scores, leiden.to_numpy())
sc_ref.add_obs(
sc_ref.obs(cols=["cell_idx", "leiden_clusters"], filtered=True)
.join(
cell_type_anno.select(
pl.col("cluster_id").alias("leiden_clusters"),
pl.col("cell_type").alias("sc_type"),
),
on="leiden_clusters",
how="left",
)
.select("cell_idx", "sc_type")
)
cell_type_anno
ScType: 10 cell types, 24 marker genes, 6626 cells ScType: streamed scoring in 405.79µs ScType: total run time -> 692.38µs
| cluster_id | cell_type | scores | n_cells |
|---|---|---|---|
| i32 | str | f64 | i32 |
| 0 | "T cells" | 1208.782593 | 1369 |
| 1 | "CD14+ Mono" | 3427.712402 | 1110 |
| 2 | "T cells" | 914.480103 | 900 |
| 3 | "CD8+ T" | 1083.726318 | 868 |
| 4 | "B cells" | 1967.049805 | 607 |
| … | … | … | … |
| 10 | "pDC" | 607.270264 | 40 |
| 11 | "T cells" | 25.710888 | 30 |
| 12 | "T cells" | 23.948139 | 27 |
| 13 | "Platelet" | 392.051331 | 23 |
| 14 | "mDC" | 15.310444 | 23 |
scType per cell¶
The cluster level call stamps one label on every cell of a cluster. A small
population that shares a Leiden community with a bigger one gets absorbed and
nothing flags it. assign_sc_type() scores per cell instead: the score matrix
is smoothed over the neighbour graph via label spreading (Zhou, et al., NIPS,
2004), then each cell takes its own argmax. Cells whose best score falls below
score_floor come back as null. Pass cluster_col and you also get the
per-cluster composition and a hybrid call: clusters at or above
purity_threshold keep the cluster level label, mixed clusters fall back to
the per-cell calls.
sctype_cells = bv.annotate.assign_sc_type(
sc_ref,
sctype_scores,
cluster_col="leiden_clusters",
)
assert sctype_cells is not None
sc_ref.add_obs(
pl.DataFrame(
{
"cell_idx": sc_ref.cells_to_keep,
"sc_type_cell": sctype_cells.assignments,
"sc_type_hybrid": sctype_cells.hybrid,
"sc_type_margin": sctype_cells.margins,
}
)
)
sctype_cells
Assigning cell types per cell (smoothing: True).
ScTypeCellResults( n_cells=6626, n_cell_types=10, n_unknown=71, smoothed=True, n_mixed_clusters=7, n_clusters=15, )
The composition table is the place to look for clusters that hide more than one cell type. The mixed ones:
assert sctype_cells.composition is not None
sctype_cells.composition.filter(pl.col("cluster_mixed")).select(
"cluster_id", "n_cells", "dominant", "purity", "second", "second_fraction"
)
| cluster_id | n_cells | dominant | purity | second | second_fraction |
|---|---|---|---|---|---|
| i32 | i32 | str | f64 | str | f64 |
| 0 | 1369 | "T cells" | 0.726077 | "CD4+ T" | 0.149744 |
| 2 | 900 | "T cells" | 0.634444 | "CD4+ T" | 0.31 |
| 3 | 868 | "CD8+ T" | 0.425115 | "NK" | 0.282258 |
| 5 | 538 | "CD8+ T" | 0.86803 | "T cells" | 0.1171 |
| 11 | 30 | "T cells" | 0.666667 | "CD4+ T" | 0.266667 |
| 12 | 27 | "T cells" | 0.592593 | "CD8+ T" | 0.222222 |
| 14 | 23 | "mDC" | 0.347826 | "Platelet" | 0.304348 |
Most of the mixed clusters are T cell clusters split between "T cells" and
"CD4+ T" or "CD8+ T". That is the marker set, not the method: the generic
"T cells" set (CD3D/E/G) competes with the subtype sets on the same cells. A
hierarchical marker set, or dropping the generic T cell entry, cleans this up.
The margin (best minus second best score) flags ambiguous calls:
ax = bv.pl.embedding_plot(
sc_ref,
"umap_harm_v2",
"sc_type_margin",
discrete=False,
)
ax.set_title("Per-cell scType margin")
plt.show()
Sanity checks¶
Batches mixed, cell types separated:
ax = bv.pl.embedding_plot(
sc_ref,
"umap_harm_v2",
"exp_id",
label_by="exp_id",
discrete=True,
)
ax.set_title("Reference (Harmony v2 corrected)")
plt.show()
ax = bv.pl.embedding_plot(sc_ref, "umap_harm_v2", "sc_type", discrete=True)
ax.set_title("Reference cell types (scType, per cluster)")
plt.show()
ax = bv.pl.embedding_plot(sc_ref, "umap_harm_v2", "sc_type_hybrid", discrete=True)
ax.set_title("Reference cell types (scType, hybrid)")
plt.show()
And the canonical markers:
canonical_markers = {
"ENSG00000167286": "CD3D",
"ENSG00000153563": "CD8A",
"ENSG00000177455": "CD19",
"ENSG00000170458": "CD14",
}
bv.pl.feature_plot(
sc_ref,
list(canonical_markers),
"umap_harm_v2",
feature_labels=canonical_markers,
)
plt.show()
Reference mapping with Symphony¶
Once you have a well annotated reference, you don't want to redo QC, HVG selection, PCA, batch correction, clustering and manual annotation for every new sample. Symphony compresses the reference into a small set of cached terms that map new query cells into the same coordinate system in a single shot, with no need to keep the reference cells around at query time.
Compressing into a SymphonyReference¶
build_symphony_ref() re-runs PCA and Harmony internally using the supplied
HVGs, then caches the loadings, centroids and compression terms (nr,
c_cache) needed for query mapping. The Harmony version follows the type of
harmony_params. Pass label_columns to snapshot one or more obs columns,
here both scType annotations, into the reference for downstream label
transfer.
A note on the apparent duplication: yes, PCA + Harmony are run again inside
build_symphony_ref(), even though we just ran them on the same HVGs above.
This is deliberate. The standard pipeline keeps its embeddings on the
SingleCells object and streams from disk; the Symphony reference keeps a
self-contained, in-memory copy of everything it needs to project queries
without the reference cells. Sharing state across those two representations
would tie them together in unhelpful ways. The cost is one extra PCA + Harmony
run at build time.
# 0-based HVG indices, as stored on the experiment
hvg_indices = sc_ref.map.hvg
assert hvg_indices is not None
symphony_ref = bv.annotate.build_symphony_ref(
sc_ref,
"exp_id",
hvg_indices,
harmony_params=HarmonyV2Params(),
no_pcs=30,
label_columns=["sc_type", "sc_type_hybrid"],
verbose=True,
)
symphony_ref
Auto-determined number of Harmony clusters: 100
Symphony: building reference Sparse PCA: Loaded in data in 11.15ms Sparse PCA: finished the data preparations in 1.65ms
Sparse PCA: finished calculations in 255.06ms Sparse PCA: total run time -> 267.98ms Harmony v2: 6_626 cells, 30 dims, 1 variable(s), 100 clusters Variable 0: 2 levels Initial data preparation done in 483.04µs Running initial k-means... Initial objective: 318.7685 === Harmony v2 iteration 1 === Running k-means clustering... Applying ridge regression correction... Harmony objective: 299.8384 Finished iteration in 8.07ms / Total runtime 33.79ms === Harmony v2 iteration 2 === Running k-means clustering... Applying ridge regression correction... Harmony objective: 192.9918 Finished iteration in 7.91ms / Total runtime 41.71ms === Harmony v2 iteration 3 === Running k-means clustering... Applying ridge regression correction... Harmony objective: 120.4948 Finished iteration in 7.94ms / Total runtime 49.67ms === Harmony v2 iteration 4 === Running k-means clustering... Applying ridge regression correction... Harmony objective: 99.1038 Finished iteration in 8.03ms / Total runtime 57.71ms === Harmony v2 iteration 5 === Running k-means clustering... Applying ridge regression correction... Harmony objective: 94.8485 Finished iteration in 7.67ms / Total runtime 65.38ms === Harmony v2 iteration 6 === Running k-means clustering... Applying ridge regression correction... Harmony objective: 92.6682 Finished iteration in 7.78ms / Total runtime 73.17ms === Harmony v2 iteration 7 === Running k-means clustering... Applying ridge regression correction... Harmony objective: 91.7636 Finished iteration in 7.79ms / Total runtime 80.98ms Harmony v2 converged at iteration 7 Finished Harmony 81.00ms Symphony reference built in 350.53ms
SymphonyReference( n_hvgs=2000, n_pcs=30, n_clusters=100, n_cells=6626, harmony_backend='v2', batch_vars=['exp_id'], slim=False, labels=['sc_type', 'sc_type_hybrid'], )
The repr tells you the Harmony backend, the size of the loadings and centroid matrices, the batch variables and the stored label columns.
Loading the query¶
We use pbmc8k as the query. Same tissue, same broad biology, but a different 10x run: exactly the kind of "another sample arrives" scenario Symphony is built for.
pbmc8k_path = bv.io.download_pbmc8k()
tempdir_query = tempfile.TemporaryDirectory()
sc_query = bv.io.load_mtx(
Path(tempdir_query.name) / "symphony_query",
bv.io.get_cell_ranger_params(pbmc8k_path),
verbose=True,
)
sc_query
Text pass (integer): 2 buckets, ~4191 cells/bucket
Text pass done: 182.20ms (cell-major order) Genes passing QC: 15_446 / 33_694 Cells passing QC: 8_381 / 8_381 Writing pass: 2 buckets, no sort
Wrote bucket 1/2 (50%) Wrote bucket 2/2 (100%) Writing pass done: 59.77ms Converting the cell-based data into the gene-based format.
Counted 11_768_954 non-zeros over 15_446 genes in 6.12ms; converting in 1 phase(s). Phase 1/1: genes 0-15446, scatter 22.28ms, compress + write 16.84ms Conversion into gene-friendly format done: 46.71ms
SingleCells( dir='/var/folders/l0/d50zd8812jg94mhtl8t2swfc0000gn/T/tmpyp_msk0w/symphony_query', cells=8381 (kept 8381), genes=15446, hvg=False, pca=False, embeddings=none, knn=False, graph=False, magic=False, residuals=False, stale=none )
Quality control on the query¶
Same QC as the reference. We are not trying to match library sizes or anything fancy across data sets, just remove clearly bad cells.
var_q = sc_query.var()
gs_q = {
"MT": var_q.filter(pl.col("column1").str.contains("^MT-"))["gene_id"].to_list(),
"Ribo": var_q.filter(pl.col("column1").str.contains("^RP[SL]"))[
"gene_id"
].to_list(),
}
bv.qc.gene_set_proportions(sc_query, gs_q, streaming=False, verbose=True)
qc_df_q = sc_query.obs(cols=["cell_id", "lib_size", "nnz", "MT"])
qc_q = bv.qc.run_cell_qc(
{
"log10_lib_size": np.log10(qc_df_q["lib_size"].to_numpy()),
"log10_nnz": np.log10(qc_df_q["nnz"].to_numpy()),
"MT": qc_df_q["MT"].to_numpy(),
},
sc_query.cells_to_keep,
directions={
"log10_lib_size": "twosided",
"log10_nnz": "twosided",
"MT": "above",
},
threshold=3.0,
)
sc_query.add_obs(pl.DataFrame({"cell_idx": qc_q.cell_idx, "outlier": qc_q.combined}))
sc_query.set_cells_to_keep(qc_q.cell_idx[~qc_q.combined])
print(f"{qc_q.combined.sum()} of {qc_q.combined.size} cells flagged")
Load in data: 11.97ms Finished the gene set proportion calculations: 3.36ms 507 of 8381 cells flagged
Projecting the query¶
map_symphony_query() does the actual projection: query cells are
standardised against the reference's per-HVG means and SDs, projected through
the reference PCA loadings, and assigned soft cluster weights against the
reference centroids. Those weights then drive the cached MoE batch correction,
putting query cells into the same z_corr coordinate system as the reference.
Genes are matched by id. Missing HVGs are treated as zero columns; with
verbose=True the function reports how many were missing.
pbmc8k is a single batch, so we pass batch_column=None, which skips the
query-side correction (the resulting symphony embedding then equals
symphony_pca). With several query batches, pass the batch column and
Symphony corrects them against the reference.
bv.annotate.map_symphony_query(
symphony_ref,
sc_query,
batch_column=None,
verbose=True,
)
17 / 2000 reference HVGs not found in query; treated as zero columns.
Symphony query mapping: 7874 cells, 1983/2000 HVGs present in query Symphony query mapped in 14.30ms
The query now carries three embeddings: "symphony" (z_corr, the corrected
embedding), "symphony_pca" (z_pca, pre-correction), and "symphony_r"
(soft cluster assignments, one column per reference centroid).
{k: v.shape for k, v in sc_query.cache.embeddings.items()}
{'symphony': (7874, 30), 'symphony_pca': (7874, 30), 'symphony_r': (7874, 100)}
A neighbour graph and UMAP on the corrected embedding give us something to plot against:
bv.graph.find_neighbours(
sc_query,
embd_to_use="symphony",
neighbours_params=NeighboursParams(),
)
bv.embed.umap(sc_query, embd_to_use="symphony", slot_name="umap_symphony")
Generating kNN data with kmknn method.
Building kMkNN index ... ... built kMkNN index in 26.28ms Generated KmKnn index: 26.71ms Querying kMkNN index (self) ... ... queried kMkNN index (self) in 14.29ms Queried KmKnn index: 14.34ms Generating the snn graph.
Added 0 edges to reconnect components that pruning cut off.
Built the Snn { similarity: Jaccard, prune: 0.0625, rescue: true } graph: 14.07ms
Transferring labels¶
transfer_labels_symphony() does a kNN majority vote on the reference's
z_corr (the searchable index) using the query's "symphony" embedding. It
reads labels from the reference's stored labels, the ones we populated via
label_columns at build time. Distances on z_corr are Euclidean; the
default KnnParams matches.
predicted = bv.annotate.transfer_labels_symphony(
symphony_ref,
sc_query,
"sc_type_hybrid",
verbose=True,
)
predicted.head()
Building kMkNN index ... ... built kMkNN index in 22.66ms Generated KmKnn index: 23.00ms Querying kMkNN index ... ... queried kMkNN index in 15.06ms Queried KmKnn index: 15.51ms
| predicted_sc_type_hybrid | confidence_sc_type_hybrid |
|---|---|
| str | f64 |
| "B cells" | 1.0 |
| "CD14+ Mono" | 1.0 |
| "CD4+ T" | 0.6 |
| "T cells" | 0.933333 |
| "CD14+ Mono" | 1.0 |
The result is a polars DataFrame in cells_to_keep order with a predicted
label and a confidence score (fraction of neighbours agreeing on the winning
class). Both columns also land in the query obs straight away, as
predicted_sc_type_hybrid and confidence_sc_type_hybrid.
Visualising the result¶
Query UMAP coloured by transferred cell type:
ax = bv.pl.embedding_plot(
sc_query,
"umap_symphony",
"predicted_sc_type_hybrid",
label_by="predicted_sc_type_hybrid",
discrete=True,
)
ax.set_title("pbmc8k: transferred cell types")
plt.show()
Same UMAP, coloured by transfer confidence. Cells in the interior of their cell type sit at confidence 1; cells on cluster boundaries or in cell types poorly represented in the reference are the ones to scrutinise.
ax = bv.pl.embedding_plot(
sc_query,
"umap_symphony",
"confidence_sc_type_hybrid",
discrete=False,
)
ax.set_title("pbmc8k: kNN transfer confidence")
plt.show()
And a per-cell-type confidence distribution, useful for spotting cell types where the reference and query disagree systematically:
conf_df = (
sc_query.obs(
cols=["predicted_sc_type_hybrid", "confidence_sc_type_hybrid"], filtered=True
)
.drop_nulls("predicted_sc_type_hybrid")
.sort("predicted_sc_type_hybrid")
)
groups = conf_df.partition_by("predicted_sc_type_hybrid", maintain_order=True)
cell_types = [g["predicted_sc_type_hybrid"][0] for g in groups]
values = [g["confidence_sc_type_hybrid"].to_numpy() for g in groups]
rng = np.random.default_rng(42)
fig, ax = plt.subplots(figsize=(7, 4), layout="constrained")
parts = ax.violinplot(values, showextrema=False, widths=0.8)
for body in parts["bodies"]: # ty: ignore[not-iterable] # matplotlib stubs type the violin parts as bare Collection
body.set_facecolor("lightgrey")
body.set_alpha(1)
for i, v in enumerate(values, start=1):
ax.scatter(
i + rng.uniform(-0.15, 0.15, v.size),
v,
s=1,
alpha=0.2,
color=bv.pl.bx_colors("main", n=1)[0],
)
ax.set_xticks(range(1, len(cell_types) + 1), cell_types, rotation=30, ha="right")
ax.set_ylim(0, 1.025)
ax.set_ylabel("Transfer confidence")
ax.set_title("Per-cell-type kNN agreement on pbmc8k")
plt.show()
Sanity check of the transferred labels with the canonical markers:
bv.pl.feature_plot(
sc_query,
list(canonical_markers),
"umap_symphony",
feature_labels=canonical_markers,
)
plt.show()
Slim references and post-hoc labels¶
The reference above stores z_corr, z_orig, the soft cluster assignments
r and the labels. For large references that get checked into shared
storage, z_orig and r are dead weight; passing slim=True at build time
drops them. z_corr is always retained, since kNN label transfer searches
against it.
If you want to add or update labels after the reference is built (say, you
re-ran scType with a different marker set), use add_symphony_labels(). It
reads obs columns from a SingleCells object in cells_to_keep order and
snapshots them into a new reference (the input is left alone). The
cells_to_keep state must match the reference; the function errors if the
row count drifts.
slim_ref = bv.annotate.build_symphony_ref(
sc_ref,
"exp_id",
hvg_indices,
harmony_params=HarmonyV2Params(),
no_pcs=30,
slim=True,
)
slim_ref = bv.annotate.add_symphony_labels(slim_ref, sc_ref, ["sc_type"])
Multiple label columns can be attached at once, existing columns are
protected unless you pass overwrite=True, and
bv.annotate.get_symphony_labels(reference) returns the stored DataFrame (or
None if there is none). save_symphony_ref() and load_symphony_ref() write
the reference to a single .npz and back.
Clean up¶
tempdir_ref.cleanup()
tempdir_query.cleanup()