Skip to content

Multiple samples in one cytome

The multi-sample AnnData tutorial concatenates two PBMC libraries (SAN1 and SAN2) in memory. This tutorial runs the complete end-to-end multi-sample workflow — per-library QC, streaming doublet removal, INFOG normalization, SVD vs GDR embedding comparison, batch-aware COSG marker discovery, top-30 cluster marker dotplot, top-6 cluster marker UMAPs, canonical lineage marker UMAPs, and kamon cell-type annotation — with the samples merged into one cytome on disk.

Nothing about the mathematical methods changes; what changes is that every step streams chunks from disk so peak RAM stays bounded regardless of how many samples you merge.

import numpy as np
import pandas as pd
import cytome
import piaso
import cosg
piaso.settings.set_figure_params(style="cell")

1. Convert each library to a cytome and merge on disk

piaso.data.load_dataset (or cytome.from_10x_h5 for your own 10x .h5 files) writes a .cytome file directly on disk without holding an AnnData object in memory:

parts = []
for name in ("pbmc_multiome_san1", "pbmc_multiome_san2"):
piaso.data.load_dataset(
name,
return_type="cytome",
cytome_path=f"{name}.cytome",
).close()
parts.append(f"{name}.cytome")

Converting one sample at a time keeps peak memory proportional to a single library rather than the sum of all libraries. Next, cytome.merge streams the per-sample cytomes into a unified dataset, disambiguates colliding barcodes across libraries, and records sample provenance in ds.cells["sample"]:

ds = cytome.merge(
parts,
output="pbmc_merged.cytome",
batch_key="sample",
batch_labels=["SAN1", "SAN2"],
gene_strategy="inner",
)
ds.n_cells, ds.n_genes # (7905, 36601)
ds.cells["sample"].value_counts()
samplecells
SAN24,360
SAN13,545
Total7,905

Keep a single open connection. cytome.merge returns an open CytomeDataset handle (ds). Pass ds directly to every downstream piaso.pp, piaso.tl, cosg, and piaso.pl function rather than opening a second handle to the same path while ds is open.


2. Streaming quality control per sample

piaso.pp.calculateCellMetrics streams RNA_counts in chunks and writes n_counts, n_genes, pct_counts_mt, and pct_counts_ribo directly into ds.cells:

piaso.pp.calculateCellMetrics(
ds,
prefix_vars={"mt": "MT-", "ribo": ["RPS", "RPL"]},
)
ds.cells.groupby("sample", observed=True).agg(
n_cells=("n_genes", "count"),
median_genes=("n_genes", "median"),
median_counts=("n_counts", "median"),
median_pct_mt=("pct_counts_mt", "median"),
median_pct_ribo=("pct_counts_ribo", "median"),
)
samplen_cellsmedian_genesmedian_countsmedian_pct_mtmedian_pct_ribo
SAN13,5451,4222,53511.78%4.30%
SAN24,3601,3042,35612.14%4.35%
piaso.pl.plot_features_violin(
ds,
["n_genes", "n_counts", "pct_counts_mt", "pct_counts_ribo"],
groupby="sample",
)
QC metrics across samples in cytome

Per-library streaming Scrublet (library_key="sample")

Doublets can only form between cells encapsulated in the same microfluidic channel, so Scrublet must simulate artificial doublets within each sample separately (library_key="sample"):

piaso.pp.scrublet(
ds,
library_key="sample",
expected_doublet_rate=0.06,
random_state=0,
)
piaso.pl.plot_features_violin(ds, ["scrublet_score"], groupby="sample")
Scrublet doublet score per library in cytome

Filter out predicted doublets (is_doublet or scrublet_score >= 0.25) and low-quality droplets (n_genes < 200 or pct_counts_mt >= 25) in place on the cytome:

cells_df = ds.cells
keep_mask = (
(cells_df["n_genes"].values >= 200)
& (cells_df["pct_counts_mt"].values < 25.0)
& (~cells_df["is_doublet"].values.astype(bool))
& (cells_df["scrublet_score"].values < 0.25)
)
piaso.pp.filter_cells(ds, cell_mask=keep_mask)
ds.n_cells, ds.n_genes # (6529, 36601)

7,905 raw barcodes $\to$ 6,529 QC-passing cells (2,960 in SAN1, 3,569 in SAN2).


3. INFOG normalization and SVD vs GDR embeddings

piaso.tl.infog normalizes counts in streaming chunks and stores the variance-stabilized matrix in the infog layer on disk while leaving the raw counts untouched:

piaso.tl.infog(
ds,
modality="RNA",
layer="counts",
key_added="infog",
n_top_genes=3000,
save_layer=True,
inplace=True,
)

Baseline: Truncated SVD (runSVD)

First compute a standard 50-component truncated SVD on the infog-selected highly variable genes:

piaso.tl.runSVD(ds, layer="infog", use_highly_variable=True, n_components=50, key_added="X_svd")
piaso.tl.neighbors(ds, use_rep="X_svd", n_neighbors=15)
piaso.tl.leiden(ds, resolution=0.5, key_added="leiden_svd")
piaso.tl.umap(ds, use_rep="X_svd", key_added="X_umap_svd")
piaso.pl.embedding(ds, basis="X_umap_svd", color="sample", frameon=False)
SVD UMAP colored by sample

Batch-aware GDR (runGDR with batch_key="sample")

Now run piaso.tl.runGDR with batch_key="sample". GDR discovers cluster-specific marker programs independently within SAN1 and SAN2 and scores all 6,529 cells against the combined feature axes in streaming chunks:

piaso.tl.runGDR(
ds,
batch_key="sample",
groupby=None,
resolution=1.0,
n_gene=30,
layer="infog",
score_layer="infog",
key_added="X_gdr",
)
piaso.tl.neighbors(ds, use_rep="X_gdr", n_neighbors=15)
piaso.tl.leiden(ds, resolution=0.5, key_added="leiden_gdr")
piaso.tl.umap(ds, use_rep="X_gdr", key_added="X_umap_gdr")
piaso.pl.embedding(
ds,
basis="X_umap_gdr",
color=["sample", "leiden_gdr"],
legend_loc="on data",
ncols=2,
frameon=False,
)
GDR UMAP colored by sample and Leiden cluster

Both SAN1 and SAN2 interleave smoothly across all 17 Leiden clusters (0–16), while fine immune populations (such as CD14 vs CD16 monocytes, MAIT vs $\gamma\delta$ T cells, and pDC vs cDC) separate cleanly.


4. De novo marker gene discovery with COSG (cosg.cosg)

On a multi-sample cytome, cosg.cosg supports both standard COSG across all cells and batch-aware COSG (batch_key="sample"), which evaluates cosine-similarity specificity within each sample so sample-specific coverage differences cannot inflate marker scores:

# Standard COSG on the cytome
marker_std = cosg.cosg(
ds,
key_added="cosg",
groupby="leiden_gdr",
layer="infog",
mu=1,
n_genes_user=50,
)
# Batch-aware COSG across samples
marker_batch = cosg.cosg(
ds,
key_added="cosg_batch",
groupby="leiden_gdr",
batch_key="sample",
layer="infog",
mu=1,
n_genes_user=50,
)
pd.DataFrame(marker_batch["names"]).iloc[:5, :8]
rankCluster 0Cluster 1Cluster 2Cluster 3Cluster 4Cluster 5Cluster 6Cluster 7
0PID1PRF1LEF1INPP4BDYSFIGHDTCF7L2AC243829.2
1EPB41L3SPON2CCR7ANK3PLAURCOL19A1CDKN1CTRDC
2LRP1GNLYNDFIP1CDC14AACSL1FCRL1AC104809.2TRGC1
3CD14FGFBP2PDE3BFAAH2NAMPTAFF3SMIM25TRGC2
4YBX3KLRF1TRABD2AST8SIA1CXCL8LIX1-AS1LST1CCL5
pd.DataFrame(marker_batch["scores"]).iloc[:5, :8].round(3)
rankCluster 0Cluster 1Cluster 2Cluster 3Cluster 4Cluster 5Cluster 6Cluster 7
00.4590.7470.3900.3030.3870.7630.7190.341
10.3210.7390.3380.2880.3780.6970.6210.332
20.3010.7130.3010.2660.3600.6950.5750.309
30.2960.6790.2930.2310.3600.6890.5450.243
40.2960.6730.2880.2160.3520.6140.5390.234

Top-2 COSG markers across all 17 clusters

names_df = pd.DataFrame(marker_batch["names"])
top2_markers = list(dict.fromkeys(
g for col in names_df.columns for g in names_df[col].iloc[:2]
))
piaso.pl.dotplot(
ds,
var_names=top2_markers,
groupby="leiden_gdr",
layer="infog",
standard_scale="var",
)
Batch-aware COSG top-2 markers per cluster dotplot in cytome

Deep dive into a single cluster: Top 30 COSG markers dotplot & Top 6 marker UMAPs

To inspect the full transcriptional program of a single cluster in detail — for example Cluster 0 (CD14 monocyte) — plot its top 30 COSG marker genes across all clusters in a dotplot:

cluster_id = "0"
top30_cluster0 = list(names_df[cluster_id].iloc[:30])
piaso.pl.dotplot(
ds,
var_names=top30_cluster0,
groupby="leiden_gdr",
layer="infog",
standard_scale="var",
title=f"Cluster {cluster_id} — Top 30 Batch-Aware COSG Marker Genes",
)
Top 30 COSG marker genes for Cluster 0 in cytome

And visualize the spatial specificity of the top 6 COSG markers for Cluster 0 (PID1, EPB41L3, LRP1, YBX3, CD14, CPVL) on the GDR UMAP using cmap=piaso.pl.color.c_color1:

top6_cluster0 = list(names_df[cluster_id].iloc[:6])
piaso.pl.embedding(
ds,
basis="X_umap_gdr",
color=top6_cluster0,
layer="infog",
cmap=piaso.pl.color.c_color1,
ncols=3,
frameon=False,
)
Top 6 COSG marker genes for Cluster 0 on GDR UMAP in cytome

Canonical PBMC lineage markers on the GDR UMAP

Alongside unsupervised COSG markers, plotting canonical lineage markers (CD14, FCGR3A, MS4A1, IL7R, GNLY, TCF4) confirms the major immune compartments directly on the cytome:

canonical_markers = ["CD14", "FCGR3A", "MS4A1", "IL7R", "GNLY", "TCF4"]
piaso.pl.embedding(
ds,
basis="X_umap_gdr",
color=canonical_markers,
layer="infog",
cmap=piaso.pl.color.c_color1,
ncols=3,
frameon=False,
)
Canonical PBMC lineage markers on GDR UMAP in cytome

5. Reference-based annotation with KAMON (piaso.tl.kamon)

Retrieve the curated human PBMC marker database (PBMC_Granulocyte_Bridge2026_RNA) from PIASOmarkerDB and run piaso.tl.kamon (or piaso.tl.predictCellTypeByMarker) directly on the open cytome:

marker_db = piaso.tl.getMarkers(
study="PBMC_Granulocyte_Bridge2026_RNA",
as_dict=True,
)
piaso.tl.kamon(
ds,
marker_gene_set=marker_db,
score_layer="infog",
use_rep="X_gdr",
smooth_prediction=True,
key_added="CellTypes",
)
ds.cells["CellTypes"].value_counts().head(8)
CellTypescells
CD14 monocyte1,650
Naive CD4 T cell982
CD56dim NK cell756
Memory CD4 T cell663
Naive B cell482
CD16 monocyte344
MAIT339
Memory B cell249
piaso.pl.embedding(
ds,
basis="X_umap_gdr",
color="CellTypes",
legend_loc="right margin",
frameon=False,
)
Predicted cell types on GDR UMAP in cytome

Split UMAP and sample composition across cell types

Splitting the UMAP by sample (piaso.pl.plot_embeddings_split) shows that every immune population is recovered in both SAN1 and SAN2 at consistent coordinates:

piaso.pl.plot_embeddings_split(
ds,
basis="X_umap_gdr",
color="CellTypes",
splitby="sample",
)
Cell types split by sample in cytome

A Sankey diagram (piaso.pl.sankey) confirms the correspondence between unsupervised leiden_gdr clusters and CellTypes, while piaso.pl.stackedBarplot quantifies the SAN1 vs SAN2 proportion within each cell type:

piaso.pl.sankey(
ds,
groupby1="leiden_gdr",
groupby2="CellTypes",
title="Leiden clusters (GDR) vs KAMON CellTypes",
)
Sankey diagram between Leiden clusters and CellTypes in cytome
piaso.pl.stackedBarplot(
ds,
groupby="CellTypes",
color_by="sample",
normalize=True,
)
Sample proportions across cell types in cytome

6. Post-annotation group QC audit (calculateGroupMetrics)

Finally, run piaso.pp.calculateGroupMetrics and piaso.pl.plotGroupMetrics on the cytome to verify that every annotated population reflects genuine biological complexity rather than low-coverage debris or doublets:

piaso.pp.calculateGroupMetrics(ds, groupby="CellTypes")
piaso.pl.plotGroupMetrics(ds, groupby="CellTypes")
Group-level QC metrics across cell types in cytome
ds.close()

Summary: AnnData vs cytome for multi-sample workflows

CapabilityMulti-sample AnnDataMulti-sample cytome (this tutorial)
Storage & RAMConcatenated in memory (anndata.concat)Streamed on disk (cytome.merge)
Sample provenanceadata.obs["sample"]Written at merge (batch_key="sample")
Per-library Scrubletpiaso.pp.scrublet(..., library_key="sample")piaso.pp.scrublet(..., library_key="sample") (streaming)
Batch-aware GDRpiaso.tl.runGDR(..., batch_key="sample")piaso.tl.runGDR(..., batch_key="sample") (streaming)
Batch-aware COSGcosg.cosg(..., batch_key="sample")cosg.cosg(..., batch_key="sample") (streaming)
KAMON annotationpiaso.tl.kamon(adata, ...)piaso.tl.kamon(ds, ...) (streaming)