UMAP and t-SNE¶
sb.tl.umap and sb.tl.tsne are the
manifolds-rs AnnData functions,
re-exported. They read and write the same slots as sc.tl.umap and
sc.tl.tsne, so plotting and everything downstream stays scanpy. Install
with uv add 'scbix[manifolds]'.
Data: the processed PBMC 3k from scanpy's datasets. It already has PCA and
Louvain labels; we rebuild the neighbour graph so it looks like what a
current sc.pp.neighbors writes.
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", message="IProgress not found")
import tarfile
from pathlib import Path
from urllib.request import urlretrieve
import anndata as ad
import manifolds_rs as mf
import matplotlib.pyplot as plt
import scanpy as sc
import scbix as sb
adata = sc.datasets.pbmc3k_processed()
sc.pp.neighbors(adata, n_neighbors=15, n_pcs=50)
adata
Downloading file 'pbmc3k_processed.h5ad' from 'https://exampledata.scverse.org/scanpy/pbmc3k.h5ad' to '/Users/gregorlueg/repos/shared/scbix/.claude/worktrees/expressive-riding-pike/docs/vignettes/data'.
0%| | 0.00/24.7M [00:00<?, ?B/s]
4%|█▌ | 1.05M/24.7M [00:00<00:02, 10.4MB/s]
9%|███▍ | 2.29M/24.7M [00:00<00:01, 11.5MB/s]
15%|█████▌ | 3.72M/24.7M [00:00<00:01, 12.8MB/s]
21%|███████▊ | 5.22M/24.7M [00:00<00:01, 13.6MB/s]
27%|█████████▉ | 6.59M/24.7M [00:00<00:01, 13.6MB/s]
33%|████████████▏ | 8.13M/24.7M [00:00<00:01, 14.2MB/s]
39%|██████████████▎ | 9.55M/24.7M [00:00<00:01, 14.2MB/s]
44%|████████████████▍ | 11.0M/24.7M [00:00<00:00, 14.1MB/s]
50%|██████████████████▌ | 12.4M/24.7M [00:00<00:00, 14.1MB/s]
56%|████████████████████▉ | 13.9M/24.7M [00:01<00:00, 14.5MB/s]
62%|███████████████████████ | 15.4M/24.7M [00:01<00:00, 13.9MB/s]
68%|█████████████████████████▏ | 16.8M/24.7M [00:01<00:00, 13.8MB/s]
74%|███████████████████████████▍ | 18.3M/24.7M [00:01<00:00, 14.1MB/s]
80%|█████████████████████████████▌ | 19.7M/24.7M [00:01<00:00, 13.9MB/s]
86%|███████████████████████████████▊ | 21.2M/24.7M [00:01<00:00, 14.2MB/s]
92%|█████████████████████████████████▉ | 22.6M/24.7M [00:01<00:00, 14.3MB/s]
98%|████████████████████████████████████▏| 24.1M/24.7M [00:01<00:00, 14.3MB/s]
0%| | 0.00/24.7M [00:00<?, ?B/s]
100%|█████████████████████████████████████| 24.7M/24.7M [00:00<00:00, 34.5GB/s]
AnnData object with n_obs × n_vars = 2638 × 1838
obs: 'n_genes', 'percent_mito', 'n_counts', 'louvain'
var: 'n_cells'
uns: 'draw_graph', 'louvain', 'louvain_colors', 'neighbors', 'pca', 'rank_genes_groups'
obsm: 'X_pca', 'X_tsne', 'X_umap', 'X_draw_graph_fr'
varm: 'PCs'
obsp: 'distances', 'connectivities'
layers: None (.X)
UMAP¶
sb.tl.umap takes the graph from sc.pp.neighbors rather than searching
again, the same as sc.tl.umap. Run both into one AnnData: key_added
keeps them apart.
sc.tl.umap(adata)
sb.tl.umap(adata, key_added="X_umap_scbix")
fig, axes = plt.subplots(1, 2, figsize=(10, 4.5))
sc.pl.embedding(
adata,
basis="X_umap",
color="louvain",
ax=axes[0],
show=False,
title="sc.tl.umap",
legend_loc=None,
)
sc.pl.embedding(
adata,
basis="X_umap_scbix",
color="louvain",
ax=axes[1],
show=False,
title="sb.tl.umap",
)
plt.tight_layout()
The parameters land in uns, as scanpy's do, so you can see later what
produced an embedding. Only scalars are kept, so it survives write_h5ad.
adata.uns["X_umap_scbix"]["params"]
{'init': 'spectral',
'learning_rate': 1.0,
'min_dist': 0.5,
'n_components': 2,
'n_neighbors': 14,
'optimiser': 'adam_parallel',
'randomised': False,
'seed': 42,
'spread': 1.0,
'verbose': 0,
'device': 'cpu',
'neighbors_key': 'neighbors'}
Anything else the manifolds_rs.UMAP estimator takes goes through as a
keyword argument. A tighter layout with more epochs, written to the default
obsm["X_umap"] so sc.pl.umap picks it up:
sb.tl.umap(adata, min_dist=0.1, n_epochs=1000)
sc.pl.umap(adata, color="louvain", title="sb.tl.umap, min_dist=0.1")
t-SNE¶
t-SNE searches its own 3 * perplexity neighbours on the representation, as
sc.tl.tsne does, so it ignores the neighbour graph. Barnes-Hut is the
default; approx="fft" switches to FFT-accelerated interpolation.
sb.tl.tsne(adata, n_pcs=50)
sb.tl.tsne(adata, n_pcs=50, approx="fft", key_added="X_tsne_fft")
fig, axes = plt.subplots(1, 2, figsize=(10, 4.5))
sc.pl.tsne(
adata,
color="louvain",
ax=axes[0],
show=False,
title="Barnes-Hut",
legend_loc=None,
)
sc.pl.embedding(
adata,
basis="X_tsne_fft",
color="louvain",
ax=axes[1],
show=False,
title="FFT",
)
plt.tight_layout()
Batch-corrected representation, custom neighbour graph¶
The usual integration workflow: correct the PCA, build a second neighbour
graph on it under its own key_added, and point sb.tl.umap at that graph
with neighbors_key. The representation comes along for free:
sc.pp.neighbors records use_rep in uns[key_added]["params"] and
sb.tl.umap reads it back from there.
Data: the two PBMC runs from the bixverse batch correction vignette, pbmc3k and pbmc4k. Same tissue, different 10x runs, sequencing depth and cell numbers, so a clear batch effect. Raw counts, all genes.
DATA_URL = (
"https://github.com/GregorLueg/bixverse-data/releases/download/v1.0.0/"
"pbmc_batches.tar.gz"
)
data_dir = Path("data")
if not (data_dir / "pbmc_batches").exists():
data_dir.mkdir(exist_ok=True)
archive, _ = urlretrieve(DATA_URL, data_dir / "pbmc_batches.tar.gz")
with tarfile.open(archive) as tar:
tar.extractall(data_dir, filter="data")
runs = {
name: ad.read_h5ad(data_dir / "pbmc_batches" / f"{name}.h5ad")
for name in ("pbmc3k", "pbmc4k")
}
# Ensembl IDs as the index: the two runs used different gene symbol releases.
for run in runs.values():
run.var_names = run.var["ENSEMBL_ID"].astype(str)
run.obs = run.obs[[]]
batches = ad.concat(runs, label="batch", index_unique="-", join="inner")
batches.var["symbol"] = (
runs["pbmc3k"].var["Symbol_TENx"].reindex(batches.var_names).astype(str).values
)
batches
AnnData object with n_obs × n_vars = 7040 × 31232
obs: 'batch'
var: 'symbol'
layers: None (.X)
Standard scanpy preprocessing, batch-aware HVGs, then Harmony on the PCA
with scanpy's own sc.pp.harmony_integrate (Harmony2 by default since 1.13).
It writes the corrected embedding to obsm["pca_harmony"].
sc.pp.filter_cells(batches, min_genes=200)
sc.pp.filter_genes(batches, min_cells=3)
batches.var["mt"] = batches.var["symbol"].str.startswith("MT-")
sc.pp.calculate_qc_metrics(batches, qc_vars=["mt"], inplace=True)
batches = batches[batches.obs["pct_counts_mt"] < 10].copy()
sc.pp.normalize_total(batches)
sc.pp.log1p(batches)
sc.pp.highly_variable_genes(batches, n_top_genes=2000, batch_key="batch")
sc.pp.pca(batches, mask_var="highly_variable")
sc.pp.harmony_integrate(batches, "obs.batch")
Two neighbour graphs: the default one on the uncorrected PCA, and one on the
Harmony embedding under key_added="harmony". Then a UMAP on each.
sc.pp.neighbors(batches)
sc.pp.neighbors(batches, use_rep="pca_harmony", key_added="harmony")
sb.tl.umap(batches)
sb.tl.umap(batches, neighbors_key="harmony", key_added="X_umap_harmony")
batches.uns["harmony"]["params"]
{'n_neighbors': 15,
'method': 'umap',
'metric': 'euclidean',
'random_state': 0,
'use_rep': 'pca_harmony'}
Cell type labels¶
Neither run comes annotated. As in the bixverse vignette: Leiden clusters on the uncorrected graph, each scored on a handful of canonical PBMC markers and named after the best-scoring set. Coarse on purpose, and the clusters carry whatever the batch effect did to them. Good enough to see whether the correction smears cell types together, not a ground truth. The "NK" set also picks up cytotoxic CD8 T cells (GNLY, NKG7), hence the size of that group.
MARKERS = {
"T cells": ["CD3D", "CD3E", "IL7R", "CD8A"],
"B cells": ["MS4A1", "CD79A"],
"Monocytes": ["CD14", "LYZ", "FCGR3A"],
"NK": ["GNLY", "NKG7"],
"DC": ["FCER1A", "CD1C"],
"Platelets": ["PPBP"],
}
symbol_to_id = dict(zip(batches.var["symbol"], batches.var_names, strict=True))
sc.tl.leiden(batches, resolution=1.0, key_added="leiden_uncorrected")
for cell_type, genes in MARKERS.items():
sc.tl.score_genes(batches, [symbol_to_id[g] for g in genes], score_name=cell_type)
cluster_scores = batches.obs.groupby("leiden_uncorrected", observed=True)[
list(MARKERS)
].mean()
batches.obs["cell_type"] = (
batches.obs["leiden_uncorrected"]
.map(cluster_scores.idxmax(axis=1))
.astype("category")
)
batches.obs["cell_type"].value_counts()
cell_type T cells 2942 Monocytes 1700 NK 1181 B cells 958 DC 196 Platelets 43 Name: count, dtype: int64
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
for row, basis, label in [
(0, "X_umap", "uncorrected"),
(1, "X_umap_harmony", "Harmony"),
]:
for col, colour in enumerate(["batch", "cell_type"]):
sc.pl.embedding(
batches,
basis=basis,
color=colour,
ax=axes[row, col],
show=False,
title=f"{label}, {colour}",
legend_loc="right margin" if row == 1 else None,
)
plt.tight_layout()
GPU¶
device="gpu" swaps in the GPU estimators, where the wheel was built with
them and an adapter is around. When it pays off is covered in the
manifolds-rs GPU vignette.
if mf.gpu_available():
sb.tl.umap(adata, device="gpu", key_added="X_umap_gpu")
sc.pl.embedding(adata, basis="X_umap_gpu", color="louvain", title="sb.tl.umap, GPU")
else:
print("No GPU adapter found, skipping.")
What next¶
PHATE, PaCMAP, diffusion maps and ForceAtlas2 exist in manifolds-rs as
estimators already. They get scanpy-style functions there first, then show
up here as sb.tl.*. Watch this space.