Doublets and metacells¶
sb.tl.scdblfinder and sb.tl.seacells are the bixverse Rust
implementations of scDblFinder and SEACells, in the base install. Both read
from and write to AnnData the way a scanpy tool would, so the steps in between
are plain scanpy.
Data: the raw PBMC 3k counts from scanpy's datasets. One capture, 2,700 cells.
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", message="IProgress not found")
import matplotlib.pyplot as plt
import numpy as np
import scanpy as sc
import scbix as sb
from scbix.tl import ScdblfinderParams, SeacellsParams
adata = sc.datasets.pbmc3k()
adata.var_names_make_unique()
adata.layers["counts"] = adata.X.copy()
adata
AnnData object with n_obs × n_vars = 2700 × 32738
var: 'gene_ids'
layers: None (.X), 'counts'
Doublets¶
scDblFinder wants raw counts and reads layers["counts"] by default. CSR or
CSC, any integer or float dtype, as long as the values are non-negative
integers. Canonical uint32 input is passed to Rust without a copy; this
float32 matrix is cast once.
sb.tl.scdblfinder(adata, verbose=False)
adata.obs.filter(like="scDblFinder").head()
| scDblFinder | scDblFinder_score | scDblFinder_cxds | scDblFinder_weighted | scDblFinder_cluster | |
|---|---|---|---|---|---|
| index | |||||
| AAACATACAACCAC-1 | False | 0.054603 | 0.191466 | 0.102714 | 1 |
| AAACATTGAGCTAC-1 | True | 0.702370 | 0.306965 | 0.623817 | 4 |
| AAACATTGATCAGC-1 | False | 0.318578 | 0.206205 | 0.509296 | 2 |
| AAACCGTGCTTCCG-1 | False | 0.032556 | 0.125182 | 0.110532 | 0 |
| AAACCGTGTATGCG-1 | False | 0.114092 | 0.076380 | 0.111799 | 3 |
The calls go to obs["scDblFinder"], the scores to the _score, _cxds
and _weighted columns. The threshold, the detected rate and the parameters
that produced them go to uns.
info = adata.uns["scDblFinder"]
info["threshold"], info["detected_doublet_rate"], adata.obs["scDblFinder"].sum()
(0.4731481969356537, 0.038148149847984314, np.int64(103))
Options go through ScdblfinderParams, whose fields and defaults match
bixverse.params.ScdblfinderParams. With several captures in one object,
group_by="sample" scores each one independently. PBMC 3k has a single
capture, so here it's just a fixed doublet rate:
sb.tl.scdblfinder(
adata,
scdblfinder_params=ScdblfinderParams(expected_doublet_rate=0.025),
key_added="scDblFinder_fixed",
verbose=False,
)
adata.obs[["scDblFinder", "scDblFinder_fixed"]].sum()
scDblFinder 103 scDblFinder_fixed 120 dtype: int64
The usual scanpy run to see where the doublets sit.
sc.pp.normalize_total(adata)
sc.pp.log1p(adata)
sc.pp.highly_variable_genes(adata, n_top_genes=2000)
sc.pp.pca(adata, n_comps=30)
sc.pp.neighbors(adata)
sc.tl.umap(adata)
sc.tl.leiden(adata, flavor="igraph", n_iterations=2)
adata.obs["doublet"] = adata.obs["scDblFinder"].map({True: "doublet", False: "singlet"})
sc.pl.umap(adata, color=["leiden", "scDblFinder_score", "doublet"], ncols=3)
Metacells¶
Drop the doublets, then fit SEACells on the PCA. SEACells only needs the
embedding in obsm. A C-contiguous float32 embedding is borrowed, anything
else is cast once. Roughly one metacell per 75 cells is the usual target.
singlets = adata[~adata.obs["scDblFinder"]].copy()
n_sea_cells = singlets.n_obs // 75
sb.tl.seacells(singlets, seacells_params=SeacellsParams(n_sea_cells=n_sea_cells))
singlets.obs["seacells"].value_counts().describe()
count 34.000000 mean 76.382353 std 56.082199 min 12.000000 25% 42.000000 50% 59.500000 75% 93.500000 max 215.000000 Name: count, dtype: float64
Assignments go to obs["seacells"] as a categorical. uns["seacells"]
holds every parameter, the archetype cell of each metacell, the RSS history
and whether the fit converged within max_iter.
fit = singlets.uns["seacells"]
fit["n_metacells_realized"], fit["n_iter"], fit["converged"]
(34, 10, True)
fig, axes = plt.subplots(1, 2, figsize=(10, 4.5))
sc.pl.umap(
singlets,
color="seacells",
ax=axes[0],
show=False,
legend_loc=None,
title="SEACells assignments",
)
archetypes = singlets[fit["archetype_obs_names"]].obsm["X_umap"]
axes[0].scatter(*archetypes.T, c="black", s=12)
axes[1].plot(np.arange(len(fit["rss"])), fit["rss"])
axes[1].set(xlabel="iteration", ylabel="RSS", title="Fit")
plt.tight_layout()
Summed raw counts per metacell are one scanpy call away, ready for whatever wants less sparse profiles.
metacells = sc.get.aggregate(singlets, by="seacells", func="sum", layer="counts")
metacells
AnnData object with n_obs × n_vars = 34 × 32738
obs: 'seacells', 'n_obs_aggregated'
var: 'gene_ids', 'highly_variable', 'means', 'dispersions', 'dispersions_norm'
layers: 'sum'
Elsewhere¶
The other tools in scbix.tl come from sibling packages, and their vignettes
live there:
- NEBULA on AnnData
(edge-rs) for
sb.tl.nebula. - The bonsai-rs guide for
sb.tl.sanityandsb.tl.bonsai. - The manifolds-rs vignettes for
the estimators behind
sb.tl.umapandsb.tl.tsne.