Merge two single-cell RNA-seq count stores into one store and analyze their cells together. The data come from the Kang et al. experiment: human peripheral blood mononuclear cells (PBMCs) from eight lupus patients, cultured for 6 hours with or without interferon beta (IFN-beta). The cells of each condition were pooled and captured as one sample. The merged store holds 18,597 cells that passed quality control, measured on 35,635 genes, and each cell carries one of 13 annotated cell types stored with the data. Without batch correction, 14 of the 18 Leiden clusters draw at least 90% of their cells from one sample. In each of the 13 cell types, interferon-stimulated genes such as ISG15 are detected in a larger share of stimulated cells than of control cells and reach higher mean levels.
Download and open the source stores¶
Each source store holds one sample: its RNA counts, the annotated cell type of each cell in cluster_labels, and an I column that marks the active cells, those that passed quality control and that analyses use by default.
# Load the tools for merging, analyzing, plotting, and summarizing the stores.
from pathlib import Path
from tempfile import TemporaryDirectory
import matplotlib.pyplot as plt
import pandas as pd
import cytearc
from cytearc.plotting import CellField, NormalizationSpec
# Print errors only, without progress bars.
cytearc.configure_output(level="ERROR", progress=False)
# Download the control and stimulated stores from CyteArc's documentation repository.
repository = cytearc.datasets.connect("cytearc_docs")
ctrl_path = repository.download_dataset(
name="kang_15K_pbmc_rnaseq", destination="cytearc_datasets", zarr=True
)
stim_path = repository.download_dataset(
name="kang_14K_ifnb-pbmc_rnaseq", destination="cytearc_datasets", zarr=True
)
# Open both stores and count their cells, active cells, and RNA features.
ds_ctrl = cytearc.DataStore(f"{ctrl_path}/data.zarr", nthreads=4)
ds_stim = cytearc.DataStore(f"{stim_path}/data.zarr", nthreads=4)
pd.DataFrame(
[
{
"sample": name,
"cells": store.cells.N,
"active cells": int(store.cells.fetch_all("I").sum()),
"features": store.RNA.feats.N,
}
for name, store in (("ctrl", ds_ctrl), ("stim", ds_stim))
]
).set_index("sample")| cells | active cells | features | |
|---|---|---|---|
| sample | |||
| ctrl | 8487 | 8486 | 35635 |
| stim | 10111 | 10111 | 35635 |
Started: 2026-11-24T13:25:43.151545Z | Wall time: 18.845 s
All 10,111 stimulated cells and 8,486 of the 8,487 control cells are active, and both stores measure 35,635 RNA features.
Plan the merge¶
DataStoreMerge writes a new store that holds the cells of several source stores. It matches features across the sources by their IDs, and each merged assay must have the same assay type, such as RNA, in every source. The settings below name the sources ctrl and stim (names) and store each cell’s source name in a new sample_id column (source_column). prepend_text="orig" adds the prefix orig_ to each copied cell column, and reset_cell_filter=False keeps each source’s I values instead of activating every cell. Creating the merge writes nothing, and plan() reports the cells and features that the merge would write.
# Put the merged store in a new temporary folder on each run.
merge_directory = TemporaryDirectory()
merged_path = Path(merge_directory.name) / "kang_dataset_merging.zarr"
# Configure the merge, then resolve it without writing anything.
merge = cytearc.DataStoreMerge(
datasets=[ds_ctrl, ds_stim],
zarr_path=str(merged_path),
names=["ctrl", "stim"],
assays=["RNA"],
prepend_text="orig",
reset_cell_filter=False,
source_column="sample_id",
)
plan = merge.plan()
# Show the planned cells and the features of each merged assay.
pd.DataFrame(
[
{
"assay": assay.assayName,
"type": assay.assayType,
"cells": plan.nCells,
"features": assay.nFeatures,
"share of features in both samples": assay.featureOverlapFraction,
}
for assay in plan.assays
]
).set_index("assay")| type | cells | features | share of features in both samples | |
|---|---|---|---|---|
| assay | ||||
| RNA | RNA | 18598 | 35635 | 1.0 |
Started: 2026-11-24T13:26:01.997378Z | Wall time: 0.210 s
Every feature is found in both samples, so the share is 1.0, and the merged store will hold all 18,598 cells. When sources identify the same genes with different ID schemes, such as Ensembl IDs in one and gene symbols in the other, few features match and the share falls. Pass feature_key="names" to match features by name instead: the merged store then uses the names as feature IDs and sums the counts of features that share a name within one source.
Write the merged store¶
dump() writes the merged counts and cell metadata. A merge does not replace a store that has been opened as a DataStore, even with overwrite=True, so this page writes into a new temporary folder on each run. Use a permanent path for your own data.
# Write the merged counts and cell metadata.
merge.dump()
# Open the merged store and list its cells, assay, and cell columns.
merged = cytearc.DataStore(str(merged_path), nthreads=4)
mergedDataStore has 18597 (18598) cells with 1 assays: RNA
Cell metadata:
'I', 'ids', 'names', 'RNA_I', 'RNA_nCounts',
'RNA_nFeatures', 'RNA_percentMito', 'RNA_percentRibo', 'orig_RNA_UMAP1', 'orig_RNA_UMAP2',
'orig_RNA_clusters', 'orig_RNA_leiden_cluster', 'orig_cluster_labels', 'sample_id', 'sourceRow'
RNA assay has 35635 features and following metadata:
'I', 'ids', 'names', 'dropOuts', 'nCells'Started: 2026-11-24T13:26:02.208416Z | Wall time: 8.508 s
The merged store holds 18,598 cells, of which 18,597 are active: reset_cell_filter=False left the one control cell that failed quality control inactive. sample_id holds each cell’s source, and the copied columns carry the orig_ prefix, so orig_cluster_labels holds the annotated cell types. RNA_I marks the cells that the merged RNA assay measured, here every cell. When a source lacks an assay, the merge writes zeros for that source’s cells and leaves their <assay>_I value False. Analyses of that assay then refuse those cells, and merged.select_measured_cells("<assay>") returns a cell selection without them.
# Read the sample and annotated cell type of each active cell.
merged_labels = merged.cells.to_pandas_dataframe(
["sample_id", "orig_cluster_labels"], key="I"
)
# Count the active cells and annotated cell types in each sample.
merged_labels.groupby("sample_id")["orig_cluster_labels"].agg(
cells="count", cell_types="nunique"
)| cells | cell_types | |
|---|---|---|
| sample_id | ||
| ctrl | 8486 | 13 |
| stim | 10111 | 13 |
Started: 2026-11-24T13:26:10.717495Z | Wall time: 0.010 s
The merged store keeps each sample’s active cells, 8,486 control and 10,111 stimulated, and both samples contain all 13 annotated cell types.
Analyze the merged cells together¶
pipeline.rna runs CyteArc’s RNA recipe on the merged store and returns a PipelineRun, the durable record of each stage’s saved result. The settings below select 2,000 highly variable genes, reduce them to 25 principal components, connect each cell to its 21 nearest neighbors, embed the graph with UMAP, and cluster it with Leiden at resolution 1.0. No stage corrects for the sample, so the result shows how far the two samples differ.
The run analyzes the 18,597 active cells as they are (filtering=False), because each source’s I column already records which cells passed quality control. It skips cell-cycle scoring, doublet scoring, and marker ranking, which this comparison does not use. Doublets form within one capture, so when merged samples still need doublet scores, pass doublets={"sample_column": "sample_id"} to score each sample separately. snapshot_columns copies sample_id and orig_cluster_labels into run.cells, the run’s cell view, which keeps their values from the start of the run next to the run’s clusters and UMAP coordinates. The plots and the cluster table below read that view.
# Analyze the merged cells with the RNA recipe, without batch correction.
run = merged.pipeline.rna(
label="rna",
filtering=False,
cell_cycle=False,
hvg={"top_n": 2000},
pca={"dims": 25},
neighbors={"k": 21},
leiden={"partitions": [1.0]},
doublets=False,
markers=False,
snapshot_columns=("sample_id", "orig_cluster_labels"),
)Started: 2026-11-24T13:26:10.728512Z | Wall time: 39.881 s
Color the joint UMAP by sample, by annotated cell type, and by Leiden cluster.
# Draw the joint UMAP three times, side by side.
figure, axes = plt.subplots(1, 3, figsize=(14, 4.4), layout="constrained")
# Name the cell types in a side legend: a label drawn on the plot sits at the median
# of its cells, which falls between the two groups of a type that splits by sample.
panels = [
(CellField("sample_id", label="Sample"), "right"),
(CellField("orig_cluster_labels", label="Annotated cell type"), "right"),
(CellField("clusters", kind="categorical", label="Leiden cluster"), "on_data"),
]
for axis, (field, legend_loc) in zip(axes, panels, strict=True):
merged.plots.embedding(
run=run, color_by=field, legend_loc=legend_loc, target=axis, show=False
)
plt.show()
Started: 2026-11-24T13:26:50.610804Z | Wall time: 0.766 s
Control and stimulated cells occupy separate regions of the UMAP. Monocytes and dendritic cells form a stimulated group at the top right and a control group at the bottom right, and within each group the CD16 monocytes and the dendritic cells sit apart from the CD14 monocytes. The T-cell and B-cell regions each divide into a control side and a stimulated side. Count each cluster’s cells by sample and by annotated cell type to measure the split.
# Count each cluster's cells by sample and by annotated cell type.
cluster_cells = run.cells.to_pandas_dataframe(
["clusters", "sample_id", "orig_cluster_labels"]
)
by_sample = pd.crosstab(cluster_cells["clusters"], cluster_cells["sample_id"])
by_type = pd.crosstab(cluster_cells["clusters"], cluster_cells["orig_cluster_labels"])
# Count the clusters that draw at least 90% of their cells from one sample.
one_sample = by_sample.max(axis=1) / by_sample.sum(axis=1) >= 0.9
print(
f"{one_sample.sum()} of {len(one_sample)} clusters draw at least 90% "
"of their cells from one sample"
)
# Summarize each cluster by its stimulated share and its most common cell type.
pd.DataFrame(
{
"cells": by_sample.sum(axis=1),
"% stimulated": (100 * by_sample["stim"] / by_sample.sum(axis=1)).round(1),
"main cell type": by_type.idxmax(axis=1),
"% of cluster": (100 * by_type.max(axis=1) / by_type.sum(axis=1)).round().astype(int),
}
).rename_axis("cluster")14 of 18 clusters draw at least 90% of their cells from one sample
| cells | % stimulated | main cell type | % of cluster | |
|---|---|---|---|---|
| cluster | ||||
| 1 | 2924 | 99.7 | CD 14 Mono | 86 |
| 2 | 2759 | 0.3 | CD 14 Mono | 89 |
| 3 | 2179 | 99.8 | CD4 naive T | 91 |
| 4 | 1938 | 1.1 | CD4 naive T | 84 |
| 5 | 1402 | 99.4 | CD4 Memory T | 72 |
| 6 | 1219 | 3.0 | CD4 Memory T | 70 |
| 7 | 1197 | 99.2 | CD8 T | 52 |
| 8 | 889 | 9.2 | B | 67 |
| 9 | 889 | 99.7 | B | 82 |
| 10 | 700 | 98.9 | CD16 Mono | 100 |
| 11 | 602 | 0.2 | CD16 Mono | 97 |
| 12 | 560 | 2.9 | NK | 65 |
| 13 | 527 | 53.1 | T activated | 86 |
| 14 | 249 | 5.2 | DC | 86 |
| 15 | 205 | 59.5 | Mk | 96 |
| 16 | 170 | 99.4 | DC | 94 |
| 17 | 112 | 63.4 | pDC | 99 |
| 18 | 76 | 57.9 | Eryth | 97 |
Started: 2026-11-24T13:26:51.379585Z | Wall time: 0.028 s
Of the 18 clusters, 14 draw at least 90% of their cells from one sample. Six cell types each split into a control cluster and a stimulated cluster: the CD14 and CD16 monocytes, the dendritic cells, the CD4 naive and CD4 memory T cells, and the B cells. Stimulated cells fill a cluster in which 52% are CD8 T cells, and control cells one in which 65% are NK cells. The four clusters that mix the samples hold 53.1% to 63.4% stimulated cells, around the stimulated sample’s share of all cells (10,111 of 18,597). Their main types are activated T cells, megakaryocytes, plasmacytoid dendritic cells, and erythrocytes. Both samples contain every cell type, so the single-sample clusters reflect a change in expression rather than a cell type that only one sample has.
Compare interferon-stimulated genes and monocyte markers between samples¶
The dot plot below shows three interferon-stimulated genes and four monocyte markers in each annotated cell type of each sample. One of the markers, IFITM3, is itself an interferon-stimulated gene.
# Compare interferon-stimulated genes and monocyte markers by cell type and sample.
marker_plot = merged.plots.dotplot(
features={
"Interferon response": ["ISG15", "IFIT3", "MX1"],
"Monocyte markers": ["CD14", "S100A8", "FCGR3A", "IFITM3"],
},
group_by=("orig_cluster_labels", "sample_id"),
normalization=NormalizationSpec(transform="log1p"),
swap_axes=True,
figsize=(5.6, 9),
show=False,
)
# Name the rows in words rather than by their column names, then draw the plot.
marker_plot.axes["dotplot"].set_ylabel("Annotated cell type | sample")
marker_plot.show()
Started: 2026-11-24T13:26:51.408656Z | Wall time: 0.648 s
In each of the 13 cell types, ISG15, IFIT3, and MX1 are detected in a larger share of stimulated cells than of control cells and reach higher mean levels. ISG15 is highest in stimulated monocytes and dendritic cells. A response shared by every cell type is consistent with the split that most clusters follow, in which stimulated and control cells of the same type fall into different clusters. The monocyte markers differ between the samples as well. The dot plot returns the values it draws in marker_plot.tables["aggregate"], and the table below takes from it the percent of monocytes and dendritic cells in which each gene is detected.
# Read the percent of myeloid cells with each gene detected, from the dot plot's data.
detected = marker_plot.tables["aggregate"].pivot_table(
index=["group", "subgroup"], columns="feature", values="fraction"
)
myeloid_detected = detected.loc[
["CD 14 Mono", "CD16 Mono", "DC"], ["ISG15", "CD14", "S100A8", "FCGR3A", "IFITM3"]
]
(100 * myeloid_detected).round().astype(int).rename_axis(
index=["cell type", "sample"], columns=None
)| ISG15 | CD14 | S100A8 | FCGR3A | IFITM3 | ||
|---|---|---|---|---|---|---|
| cell type | sample | |||||
| CD 14 Mono | ctrl | 31 | 77 | 86 | 43 | 22 |
| stim | 100 | 23 | 53 | 29 | 100 | |
| CD16 Mono | ctrl | 55 | 68 | 38 | 88 | 66 |
| stim | 100 | 20 | 16 | 87 | 100 | |
| DC | ctrl | 34 | 21 | 26 | 15 | 15 |
| stim | 100 | 10 | 15 | 14 | 100 |
Started: 2026-11-24T13:26:52.057847Z | Wall time: 0.006 s
ISG15 is detected in 100% of stimulated monocytes and dendritic cells, against 31% to 55% of their control counterparts. In the control sample, S100A8 is detected in fewer CD16 monocytes than CD14 monocytes (38% against 86%), while FCGR3A (88% against 43%), IFITM3 (66% against 22%), and ISG15 (55% against 31%) are detected in more. After stimulation, CD14 monocytes shift toward that CD16 profile in three of these four genes: S100A8 falls to 53% of cells, and IFITM3 and ISG15 rise to 100%. FCGR3A, which encodes CD16, falls from 43% to 29% instead, and CD14 itself falls from 77% to 23%. Dendritic cells gain IFITM3 in the same way, from 15% to 100%.
These shifts matter when stimulated cells are labeled from control cells. The reference mapping and label transfer tutorial labels these stimulated cells from their nearest cells in the control sample, and nearly all stimulated CD14 monocytes and dendritic cells receive the CD16 monocyte label. The nearest control cells of the stimulated CD14 monocytes are the few monocytes with the strongest interferon response, and those cells carry the CD16 monocyte label.
Choose the next step¶
Each condition was captured separately, so the split between the samples combines the interferon response with any technical difference between the two captures, and this design cannot separate the two. Correcting the embedding for sample_id would pull the two samples together and hide the response in the embedding along with any technical difference; the counts, which the correction leaves unchanged, keep both. The Harmony batch correction tutorial corrects technical batches with Harmony and measures how well they mix, and the reference mapping and label transfer tutorial labels these stimulated cells from a reference built on the control cells. The donor-level comparisons tutorial tests differences between conditions across donors, which needs each cell’s donor; these stores pool the eight patients and carry no donor column.