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 npimport pandas as pdimport cytomeimport piasoimport 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()| sample | cells |
|---|---|
SAN2 | 4,360 |
SAN1 | 3,545 |
| Total | 7,905 |
Keep a single open connection.
cytome.mergereturns an openCytomeDatasethandle (ds). Passdsdirectly to every downstreampiaso.pp,piaso.tl,cosg, andpiaso.plfunction rather than opening a second handle to the same path whiledsis 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"),)| sample | n_cells | median_genes | median_counts | median_pct_mt | median_pct_ribo |
|---|---|---|---|---|---|
SAN1 | 3,545 | 1,422 | 2,535 | 11.78% | 4.30% |
SAN2 | 4,360 | 1,304 | 2,356 | 12.14% | 4.35% |
piaso.pl.plot_features_violin( ds, ["n_genes", "n_counts", "pct_counts_mt", "pct_counts_ribo"], groupby="sample",)
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")
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.cellskeep_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)
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,)
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 cytomemarker_std = cosg.cosg( ds, key_added="cosg", groupby="leiden_gdr", layer="infog", mu=1, n_genes_user=50,)
# Batch-aware COSG across samplesmarker_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]| rank | Cluster 0 | Cluster 1 | Cluster 2 | Cluster 3 | Cluster 4 | Cluster 5 | Cluster 6 | Cluster 7 |
|---|---|---|---|---|---|---|---|---|
| 0 | PID1 | PRF1 | LEF1 | INPP4B | DYSF | IGHD | TCF7L2 | AC243829.2 |
| 1 | EPB41L3 | SPON2 | CCR7 | ANK3 | PLAUR | COL19A1 | CDKN1C | TRDC |
| 2 | LRP1 | GNLY | NDFIP1 | CDC14A | ACSL1 | FCRL1 | AC104809.2 | TRGC1 |
| 3 | CD14 | FGFBP2 | PDE3B | FAAH2 | NAMPT | AFF3 | SMIM25 | TRGC2 |
| 4 | YBX3 | KLRF1 | TRABD2A | ST8SIA1 | CXCL8 | LIX1-AS1 | LST1 | CCL5 |
pd.DataFrame(marker_batch["scores"]).iloc[:5, :8].round(3)| rank | Cluster 0 | Cluster 1 | Cluster 2 | Cluster 3 | Cluster 4 | Cluster 5 | Cluster 6 | Cluster 7 |
|---|---|---|---|---|---|---|---|---|
| 0 | 0.459 | 0.747 | 0.390 | 0.303 | 0.387 | 0.763 | 0.719 | 0.341 |
| 1 | 0.321 | 0.739 | 0.338 | 0.288 | 0.378 | 0.697 | 0.621 | 0.332 |
| 2 | 0.301 | 0.713 | 0.301 | 0.266 | 0.360 | 0.695 | 0.575 | 0.309 |
| 3 | 0.296 | 0.679 | 0.293 | 0.231 | 0.360 | 0.689 | 0.545 | 0.243 |
| 4 | 0.296 | 0.673 | 0.288 | 0.216 | 0.352 | 0.614 | 0.539 | 0.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",)
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",)
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,)
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,)
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)| CellTypes | cells |
|---|---|
CD14 monocyte | 1,650 |
Naive CD4 T cell | 982 |
CD56dim NK cell | 756 |
Memory CD4 T cell | 663 |
Naive B cell | 482 |
CD16 monocyte | 344 |
MAIT | 339 |
Memory B cell | 249 |
piaso.pl.embedding( ds, basis="X_umap_gdr", color="CellTypes", legend_loc="right margin", frameon=False,)
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",)
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",)
piaso.pl.stackedBarplot( ds, groupby="CellTypes", color_by="sample", normalize=True,)
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")
ds.close()Summary: AnnData vs cytome for multi-sample workflows
| Capability | Multi-sample AnnData | Multi-sample cytome (this tutorial) |
|---|---|---|
| Storage & RAM | Concatenated in memory (anndata.concat) | Streamed on disk (cytome.merge) |
| Sample provenance | adata.obs["sample"] | Written at merge (batch_key="sample") |
| Per-library Scrublet | piaso.pp.scrublet(..., library_key="sample") | piaso.pp.scrublet(..., library_key="sample") (streaming) |
| Batch-aware GDR | piaso.tl.runGDR(..., batch_key="sample") | piaso.tl.runGDR(..., batch_key="sample") (streaming) |
| Batch-aware COSG | cosg.cosg(..., batch_key="sample") | cosg.cosg(..., batch_key="sample") (streaming) |
| KAMON annotation | piaso.tl.kamon(adata, ...) | piaso.tl.kamon(ds, ...) (streaming) |