Mapping finds each new cell’s nearest cells in a fixed reference analysis and labels the new cell from them, without rebuilding the reference. This page maps 10,111 human peripheral blood mononuclear cells (PBMCs) stimulated with interferon beta onto a reference of 8,486 control PBMCs from the same experiment (Kang et al. 2018), transfers the reference cells’ annotated cell types, stored in cluster_labels, and checks the transferred labels against the annotated cell types of the stimulated cells.
Of the stimulated cells, 9,499 receive a label and 612 receive none because their nearest reference cells disagree, and 55% of the labeled cells agree with their annotated label. Most CD4 naive T cells (86%), CD8 T cells (91%) and NK cells (87%) keep their labels, against 36% of CD4 memory T cells and 56% of B cells. The CD14 monocytes and dendritic cells almost never do: 99.7% of the 2,532 CD14 monocytes and 96.7% of the 214 dendritic cells are labeled CD16 monocytes, most of them by a unanimous vote of their three nearest reference cells. Interferon beta induces interferon-stimulated genes such as ISG15 in every stimulated cell type, and in the control reference ISG15 is highest in a small group of monocytes labeled CD16 monocytes. The stimulated CD14 monocytes take those few cells as their nearest neighbors.
The dataset merging tutorial takes the other route with the same two samples: it merges them into one store and analyzes their cells together.
Mapping supports RNA data only. The reference and the query stay in separate stores, and the query store must be writable, because the mapping and the transferred labels are saved there.
Open the reference and the query¶
# Load the libraries for arrays, tables and figures, and CyteArc with its plot options.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import cytearc
from cytearc.plotting import (
CellField,
ColorScale,
FeatureRef,
Highlight,
NamedCellArtifact,
NormalizationSpec,
)
# Print warnings and errors only, without progress bars.
cytearc.configure_output(level="WARNING", progress=False)
# Download the control reference cells from CyteArc's example-data repository.
repository = cytearc.datasets.connect("cytearc_docs")
ctrl_path = repository.download_dataset(
name="kang_15K_pbmc_rnaseq",
destination="cytearc_datasets",
zarr=True,
)
# Open the reference store.
ds_ctrl = cytearc.DataStore(
f"{ctrl_path}/data.zarr",
default_assay="RNA",
nthreads=4,
)
ds_ctrlDataStore has 8486 (8487) cells with 1 assays: RNA
Cell metadata:
'I', 'ids', 'names', 'RNA_UMAP1', 'RNA_UMAP2',
'RNA_clusters', 'RNA_leiden_cluster', 'RNA_nCounts', 'RNA_nFeatures', 'RNA_percentMito',
'RNA_percentRibo', 'cluster_labels'
RNA assay has 35635 features and following metadata:
'I', 'ids', 'names', 'dropOuts', 'nCells'Started: 2026-11-19T08:31:03.340458Z | Wall time: 9.548 s
# Download the interferon-beta stimulated query cells.
stim_path = repository.download_dataset(
name="kang_14K_ifnb-pbmc_rnaseq",
destination="cytearc_datasets",
zarr=True,
)
# Open the query store, which will hold the mapping and the transferred labels.
ds_stim = cytearc.DataStore(
f"{stim_path}/data.zarr",
default_assay="RNA",
nthreads=4,
)
ds_stimDataStore has 10111 (10111) cells with 1 assays: RNA
Cell metadata:
'I', 'ids', 'names', 'RNA_UMAP1', 'RNA_UMAP2',
'RNA_clusters', 'RNA_leiden_cluster', 'RNA_nCounts', 'RNA_nFeatures', 'RNA_percentMito',
'RNA_percentRibo', 'cluster_labels'
RNA assay has 35635 features and following metadata:
'I', 'ids', 'names', 'dropOuts', 'nCells'Started: 2026-11-19T08:31:12.889956Z | Wall time: 8.876 s
Both stores hold an annotated cell type for each cell in cluster_labels, 13 types in all, and a saved RNA analysis of their cells. Each figure shows one sample on its own UMAP.
# Draw the annotated labels of each sample on its own UMAP.
ds_ctrl.plots.embedding(
layout_key="RNA_UMAP",
color_by=CellField("cluster_labels", label="Control reference"),
)
ds_stim.plots.embedding(
layout_key="RNA_UMAP",
color_by=CellField("cluster_labels", label="Stimulated query"),
)

Started: 2026-11-19T08:31:21.767271Z | Wall time: 0.309 s
The two UMAPs were computed separately, so the same cell type sits in different places: the B cells are at the top left of the control map and at the bottom of the stimulated map. Mapping leaves both layouts as they are: it finds each stimulated cell’s nearest control cells in the PCA space of the control analysis, and the control UMAP then shows which control cells the stimulated cells reached.
Prepare a reusable reference¶
The control store holds a saved RNA analysis labeled rna, with its selected genes, normalization, PCA, neighbors and UMAP. pipeline.open(label="rna") reopens that analysis as a PipelineRun, and indexing the run by a step’s output name, as in run["neighbors"], returns an ArtifactRef, the handle of that step’s saved result. mapping.build_reference saves what mapping needs from the analysis as one artifact: the gene panel, which holds the analysis’s highly variable genes, the scaling of each gene and the PCA model, with a link to the analysis’s neighbor index. mapping.load_reference loads the artifact as a MappingReference. The UMAP is not part of the reference; the code keeps it to draw the reference cells.
# Open the saved RNA analysis of the control cells and keep its UMAP for plotting.
run = ds_ctrl.pipeline.open(label="rna")
reference_layout = run["umap"]
# Save the gene panel, scaling and PCA model as a reference linked to the neighbor index.
reference_ref = ds_ctrl.mapping.build_reference(run["neighbors"])
reference = ds_ctrl.mapping.load_reference(reference_ref)
# Summarize the reference.
{
"reference": reference_ref,
"reference cells": reference.selected_cell_count,
"panel genes": reference.model.n_features,
"PCA dimensions": reference.model.n_dims,
}{'reference': ArtifactRef(assay='RNA', kind='mapping_reference', artifact_id='95bc3b206085...'),
'reference cells': 8486,
'panel genes': 2000,
'PCA dimensions': 25}Started: 2026-11-19T08:31:22.077889Z | Wall time: 0.577 s
The reference covers all 8,486 control cells, with a panel of 2,000 genes and 25 principal components. A MappingReference is immutable: its genes, scaling, PCA model and neighbor index stay fixed, so every query maps onto the same reference. The reference holds no cell labels; label transfer reads them when it runs. reference_ref is the ArtifactRef of the new artifact, and later calls take such handles to find their inputs.
Map the query¶
ds_stim.mapping.run matches the query’s genes to the reference panel by gene ID, normalizes and scales the query counts with the reference’s parameters, projects them into the reference PCA space, and saves the three nearest reference cells of each query cell (save_k=3, the default) in the query store. The call maps the cells in query_run["analysis_cell_selection"], the frozen selection of cells that the stimulated sample’s own analysis used, so every mapped cell also has a position on the query UMAP.
# Open the saved RNA analysis of the stimulated cells and keep its UMAP for plotting.
query_run = ds_stim.pipeline.open(label="rna")
query_layout = query_run["umap"]
# Project the cells of that analysis onto the fixed reference.
mapping_ref = ds_stim.mapping.run(reference, query_run["analysis_cell_selection"])
mapping_refArtifactRef(assay='RNA', kind='projection', artifact_id='27074d927074...')Started: 2026-11-19T08:31:22.656032Z | Wall time: 2.130 s
The saved projection reports how closely the query matches the reference:
# Load the saved projection and read its diagnostics.
mapping = ds_stim.mapping.load_result(mapping_ref, reference=reference)
mapping.diagnostics{'featureCoverage': 1.0,
'queryBatchCount': 1,
'algorithmVariant': 'scaled_pca',
'uninformativeCellCount': 0,
'queryScaledDispersion': 1.329895474385472}Started: 2026-11-19T08:31:24.787536Z | Wall time: 0.034 s
featureCoverageis the share of panel genes that the query measured, 1.0 here.uninformativeCellCountcounts the query cells without counts in any panel gene that the query measured, none here. Such cells receive no label.queryScaledDispersionis the query’s mean squared deviation from the reference gene means, with each gene scaled by its reference standard deviation, so the reference cells themselves score exactly 1. The stimulated cells score 1.33: they lie farther from the reference’s average expression than the reference cells do. With afeatureCoveragebelow 1 the value is not comparable with 1, because each query cell is then normalized over fewer genes than the reference cells were.algorithmVariantandqueryBatchCountrecord the projection method, here a scaled PCA without batch correction, and the number of query batches, here one.
Where did the query land?¶
Each query cell gives a weight to each of its three nearest reference cells, more to nearer ones. A reference cell’s mapping score adds up the weight that the cell receives from one group of query cells, scaled by the size of the group and shown on a log scale. Scored as one group, the whole query would spread its weight over many reference cells, so the code splits the query into four populations by their annotated labels and pools the remaining cells as other. The annotated labels spell CD14 monocytes CD 14 Mono, with a space.
# Read the annotated labels of the mapped cells, in the order of the query analysis.
mapped_rows = np.flatnonzero(query_run.cells.fetch_all("I"))
query_labels = np.asarray(ds_stim.cells.fetch_all("cluster_labels"))[mapped_rows].astype(str)
# Key the labels by cell ID, as the mapping plots take them.
labels_by_cell = pd.Series(query_labels, index=ds_stim.cells.fetch_all("ids")[mapped_rows])
# Give four populations a panel each and pool the remaining cells as other.
focus = {"CD 14 Mono", "CD4 Memory T", "CD4 naive T", "NK"}
score_groups = labels_by_cell.where(labels_by_cell.isin(focus), "other")
score_groups.rename("query population").value_counts().to_frame("cells")| cells | |
|---|---|
| query population | |
| other | 3462 |
| CD 14 Mono | 2532 |
| CD4 naive T | 2390 |
| CD4 Memory T | 1297 |
| NK | 430 |
Started: 2026-11-19T08:31:24.822074Z | Wall time: 0.032 s
Each panel draws one group’s mapping score on the reference UMAP; reference cells that received no weight from the group are gray.
# Draw, for each group, the reference cells that received its neighbor weight.
ds_stim.plots.mapping_score(
mapping_ref,
reference=reference,
layout=reference_layout,
target_groups=score_groups,
size_by_score=True,
figsize=(12, 7),
)
Started: 2026-11-19T08:31:24.854868Z | Wall time: 0.343 s
The query’s CD4 naive T, CD4 memory T and NK cells send their weight to the matching regions of the reference. Almost none of the weight of the 2,532 CD14 monocytes reaches the reference CD14 monocytes: it falls on a narrow band that runs along the lower edge of the CD16 monocytes to the CD14 monocytes. A whole population that crowds onto a small part of another reference population points to a query state that the reference lacks.
Transfer labels¶
mapping.transfer_labels gives each query cell the label with the largest share of its neighbors’ weight, where nearer neighbors weigh more. By default the winning label needs at least half of the weight (threshold_fraction=0.5); otherwise the cell abstains and gets no label. The result is saved in the query store as a label_transfer artifact, together with a frozen copy of the reference labels it read, so a later change to the reference annotation cannot change the result.
# Transfer the reference labels; by default a label needs half of the neighbor weight.
transfer_ref = ds_stim.mapping.transfer_labels(
mapping_ref,
reference=reference,
reference_labels="cluster_labels",
)
# Load the labels with their evidence and count the labeled and abstained cells.
transfer = ds_stim.mapping.load_label_transfer(transfer_ref)
transfer.labels.notna().value_counts().rename(
index={True: "labeled", False: "abstained"}
).rename("query cells")label
labeled 9499
abstained 612
Name: query cells, dtype: int64Started: 2026-11-19T08:31:25.199306Z | Wall time: 0.171 s
An abstained cell has a missing label, and the abstentionReason column of transfer.evidence gives the reason, such as below_threshold when the winning label holds less than threshold_fraction of the neighbor weight. The mapping API reference lists the other four reasons.
# Count the abstained cells by reason.
transfer.evidence["abstentionReason"].value_counts()abstentionReason
below_threshold 612
Name: count, dtype: int64Started: 2026-11-19T08:31:25.371384Z | Wall time: 0.003 s
All 612 abstentions fall below the threshold. The figure compares the annotated and the transferred labels on the query UMAP, with abstained cells in gray. Passing transfer_ref to color_by colors the embedding from the saved transfer, without writing a column into the query’s cell metadata.
# Draw the annotated and the transferred labels side by side on the query UMAP.
ds_stim.plots.embedding(
layout=query_layout,
color_by=[
CellField("cluster_labels", label="Annotated labels"),
NamedCellArtifact("Transferred labels", transfer_ref),
],
figsize=(10, 4),
)
Started: 2026-11-19T08:31:25.375230Z | Wall time: 0.279 s
The lymphocytes keep most of their annotated labels, though CD8 T labels and gray abstentions appear among the CD4 memory T cells and B cells. The whole monocyte island, CD14 monocytes and dendritic cells included, is labeled CD16 Mono.
Inspect the evidence behind each label¶
transfer.evidence holds the evidence for every transferred label, and mapping_evidence plots it for the query cells of each annotated label:
voteFraction: the share of neighbor weight behind the winning label.topTwoMargin: the winning share minus the share of the runner-up.referenceDistancePercentile: the percentile of the distance to the nearest reference cell among the reference cells’ own nearest-neighbor distances. At 0.95, a query cell is farther from its nearest reference cell than 95% of reference cells are from theirs.
Here only voteFraction decides whether a cell receives a label; the margin and the distance percentile change no label.
# Plot the saved vote evidence of the query cells of each annotated label.
ds_stim.plots.mapping_evidence(
transfer_ref,
target_groups=labels_by_cell,
metrics=("voteFraction", "topTwoMargin", "referenceDistancePercentile"),
kind="box",
figsize=(14, 4),
)
Started: 2026-11-19T08:31:25.655005Z | Wall time: 0.234 s
Nine of the 13 populations have a median voteFraction of 1, the monocytes, dendritic cells, CD4 naive T, CD8 T and NK cells among them: the typical cell’s three neighbors agree. The B cells, CD4 memory T cells and activated B and T cells have medians near 0.67, the share when two of three neighbors at similar distances carry the winning label. In every population the median distance percentile is about 0.9 or higher, so the typical stimulated cell lies farther from its nearest reference cell than about 90% of reference cells lie from theirs: the whole stimulated sample sits away from the reference, not only the monocytes.
Check the transferred labels against the annotated labels¶
The stimulated cells carry their own cluster_labels, so the transferred labels can be scored against them. mapping_confusion cross-tabulates the annotated labels (rows, Known label) against the transferred labels (columns, Predicted label), with abstentions in the first column.
# Cross-tabulate the labels as fractions of the cells of each annotated label.
ds_stim.plots.mapping_confusion(
transfer_ref,
known_labels=labels_by_cell,
normalize="true",
)
Started: 2026-11-19T08:31:25.889864Z | Wall time: 0.225 s
The table gives, for each annotated label of the stimulated cells, the share of cells that keep their label, that are labeled CD16 Mono or that abstain, with the population’s median vote fraction and distance percentile.
# Compare transferred with annotated labels; an abstained cell counts as no match.
transferred = transfer.labels.to_numpy(dtype=object)
evidence = transfer.evidence.assign(
agrees=transferred == query_labels,
labeled_cd16_mono=transferred == "CD16 Mono",
)
evidence["annotated label"] = query_labels
# Summarize agreement, abstention and vote evidence within each annotated label.
by_population = evidence.groupby("annotated label")
pd.DataFrame(
{
"cells": by_population.size(),
"agreement": by_population["agrees"].mean(),
"labeled CD16 Mono": by_population["labeled_cd16_mono"].mean(),
"abstained": by_population["abstained"].mean(),
"median vote fraction": by_population["voteFraction"].median(),
"median distance percentile": by_population[
"referenceDistancePercentile"
].median(),
}
).sort_values("cells", ascending=False).round(3)| cells | agreement | labeled CD16 Mono | abstained | median vote fraction | median distance percentile | |
|---|---|---|---|---|---|---|
| annotated label | ||||||
| CD 14 Mono | 2532 | 0.001 | 0.997 | 0.000 | 1.000 | 0.950 |
| CD4 naive T | 2390 | 0.856 | 0.001 | 0.030 | 1.000 | 0.953 |
| CD4 Memory T | 1297 | 0.362 | 0.001 | 0.180 | 0.671 | 0.947 |
| CD16 Mono | 956 | 1.000 | 1.000 | 0.000 | 1.000 | 0.896 |
| B | 746 | 0.559 | 0.042 | 0.197 | 0.669 | 0.995 |
| CD8 T | 655 | 0.907 | 0.002 | 0.024 | 1.000 | 0.970 |
| NK | 430 | 0.867 | 0.000 | 0.028 | 1.000 | 0.988 |
| T activated | 282 | 0.301 | 0.000 | 0.199 | 0.687 | 0.987 |
| Mk | 247 | 0.304 | 0.296 | 0.113 | 1.000 | 0.986 |
| DC | 214 | 0.019 | 0.967 | 0.000 | 1.000 | 0.990 |
| B activated | 205 | 0.580 | 0.000 | 0.200 | 0.678 | 0.995 |
| Eryth | 83 | 0.470 | 0.157 | 0.024 | 1.000 | 0.974 |
| pDC | 74 | 0.757 | 0.122 | 0.068 | 1.000 | 0.999 |
Started: 2026-11-19T08:31:26.115820Z | Wall time: 0.010 s
All 956 CD16 monocytes keep their label, and 99.7% of the CD14 monocytes and 96.7% of the dendritic cells take the same label, CD16 Mono, at a median vote fraction of 1: their wrong labels rest on unanimous votes. Smaller shares of the megakaryocytes (Mk, 29.6%), erythrocytes (Eryth, 15.7%) and pDCs (12.2%) are labeled CD16 Mono as well. Abstentions concentrate where votes split: about a fifth of the B cells, activated B cells, CD4 memory T cells and activated T cells abstain.
mapping_calibration shows what a stricter vote threshold would change. It applies each threshold to the candidate labels saved with the transfer, without recomputing them, and plots the accuracy of the cells that the threshold keeps against their share of all query cells, with a 95% confidence band. Accuracy counts only the kept cells, unlike the agreement column above, which counts an abstained cell as a mismatch. The red point marks the transfer’s own threshold_fraction, and the lowest threshold, 0.333, keeps every cell: with three neighbors, the winning label always holds at least a third of the weight.
# Compare label accuracy with retained coverage across vote thresholds.
calibration = ds_stim.plots.mapping_calibration(transfer_ref, known_labels=labels_by_cell)
# Show the lowest threshold, the transfer's own threshold and the highest one.
curve = calibration.tables["calibration"]
shown = [
curve["threshold"].min(), transfer.threshold_fraction, curve["threshold"].max()
]
curve[curve["threshold"].isin(shown)].round(3).set_index("threshold")[
["nAccepted", "coverage", "accuracy"]
]
| nAccepted | coverage | accuracy | |
|---|---|---|---|
| threshold | |||
| 1.000 | 6644 | 0.657 | 0.531 |
| 0.500 | 9499 | 0.939 | 0.551 |
| 0.333 | 10111 | 1.000 | 0.530 |
Started: 2026-11-19T08:31:26.126656Z | Wall time: 0.091 s
Accuracy barely changes with the threshold: 0.530 when every cell keeps its candidate label, 0.551 at the transfer’s threshold of 0.5, and 0.531 when only unanimous votes count, which keeps 66% of the cells. A threshold stricter than 0.5 removes cells with split votes, which are right more often than the unanimous cells, and keeps the unanimous monocyte errors.
Why stimulated monocytes take the CD16 monocyte label¶
Each transferred label comes from a cell’s three nearest reference cells. Loading the projection with load_arrays=True adds those neighbors as positions among the reference cells, and reference.fetch_cell_column reads the reference labels in the same order. The table counts, for five populations of the query, how many distinct reference cells their neighbors include, and how those neighbors are labeled.
# Load the projection again, now with each mapped cell's saved reference neighbors.
mapping = ds_stim.mapping.load_result(
mapping_ref, reference=reference, load_arrays=True
)
# Read the reference labels in the order that the neighbor indices use.
reference_labels = reference.fetch_cell_column("cluster_labels").astype(str)
# Count the reference cells that each population reached, and their commonest label.
neighbor_summary = {}
for population in ["CD 14 Mono", "DC", "CD16 Mono", "CD4 naive T", "NK"]:
neighbors = mapping.indices[query_labels == population]
neighbor_labels = pd.Series(reference_labels[neighbors.ravel()]).value_counts(
normalize=True
)
neighbor_summary[population] = {
"query cells": len(neighbors),
"reference cells reached": len(np.unique(neighbors)),
"most common neighbor label": neighbor_labels.index[0],
"share of neighbors": round(neighbor_labels.iloc[0], 3),
}
pd.DataFrame(neighbor_summary).T| query cells | reference cells reached | most common neighbor label | share of neighbors | |
|---|---|---|---|---|
| CD 14 Mono | 2532 | 61 | CD16 Mono | 0.997 |
| DC | 214 | 31 | CD16 Mono | 0.961 |
| CD16 Mono | 956 | 30 | CD16 Mono | 1.0 |
| CD4 naive T | 2390 | 153 | CD4 naive T | 0.772 |
| NK | 430 | 79 | NK | 0.829 |
Started: 2026-11-19T08:31:26.218372Z | Wall time: 0.054 s
The 2,532 stimulated CD14 monocytes draw all their neighbors from 61 of the 8,486 reference cells, and 99.7% of those neighbors are labeled CD16 Mono. The neighbors of the 214 dendritic cells come from 31 reference cells and are 96.1% CD16 Mono, and those of the 956 CD16 monocytes come from 30 reference cells, all labeled CD16 Mono. The stimulated CD4 naive T cells and NK cells also crowd onto few reference cells, 153 and 79, but 77.2% and 82.9% of their neighbors carry the matching label.
The figure colors ISG15, an interferon-stimulated gene, on the reference UMAP (left) and the query UMAP (middle) on one color scale, and marks the 61 neighbors of the stimulated CD14 monocytes in black on the faded reference labels (right).
# Find the reference cells that the stimulated CD14 monocytes chose as neighbors.
monocyte_neighbors = np.unique(mapping.indices[query_labels == "CD 14 Mono"])
# Draw ISG15 on both UMAPs on one color scale.
isg15_scale = ColorScale(vmin=0.0, vmax=4.5)
log_expression = NormalizationSpec(transform="log1p")
figure, axes = plt.subplots(1, 3, figsize=(14, 4.6), layout="constrained")
ds_ctrl.plots.embedding(
layout=reference_layout,
color_by=FeatureRef("ISG15", label="Control ISG15, log(1 + counts per 1,000)"),
normalization=log_expression,
color_scale=isg15_scale,
target=axes[0],
show=False,
)
ds_stim.plots.embedding(
layout=query_layout,
color_by=FeatureRef("ISG15", label="Stimulated ISG15, log(1 + counts per 1,000)"),
normalization=log_expression,
color_scale=isg15_scale,
target=axes[1],
show=False,
)
# Mark the chosen cells on the reference, with its labels in a side legend.
ds_ctrl.plots.embedding(
layout=reference_layout,
color_by=CellField("cluster_labels", label="Annotated label"),
highlight=Highlight(indices=tuple(monocyte_neighbors.tolist()), color="black"),
legend_loc="right",
target=axes[2],
show=False,
)
axes[2].set_title("Neighbors of stimulated CD14 monocytes")
plt.show()
Started: 2026-11-19T08:31:26.273287Z | Wall time: 0.847 s
In the control cells, ISG15 is low in most cells and highest in a narrow band that runs along the lower edge of the CD16 monocytes to the CD14 monocytes. In the stimulated cells, ISG15 is high in every population and highest in the monocytes. The neighbors of the stimulated CD14 monocytes sit on the band. The table averages four interferon-stimulated genes as log(1 + counts per 1,000) in the control CD14 and CD16 monocytes, in the 61 control cells that the stimulated CD14 monocytes chose, and in the stimulated CD14 monocytes, and checks that the reference panel holds each gene.
# Read which genes the reference panel holds.
panel_genes = set(
ds_ctrl.RNA.feats.fetch_all("names")[
run.features.fetch_all("highly_variable_features")
]
)
# Define the groups; match the chosen reference cells to control cells by cell ID.
chosen_ids = reference.fetch_cell_column("ids")[monocyte_neighbors]
control_labels = ds_ctrl.cells.fetch("cluster_labels")
monocyte_groups = {
"control CD14 Mono": (ds_ctrl, control_labels == "CD 14 Mono"),
"control CD16 Mono": (ds_ctrl, control_labels == "CD16 Mono"),
"control neighbors of stimulated CD14 Mono": (
ds_ctrl,
np.isin(ds_ctrl.cells.fetch("ids"), chosen_ids),
),
"stimulated CD14 Mono": (
ds_stim,
ds_stim.cells.fetch("cluster_labels") == "CD 14 Mono",
),
}
# Average four interferon-stimulated genes as log(1 + counts per 1,000) in each group.
interferon_genes = {}
for gene in ["ISG15", "IFIT3", "MX1", "CXCL10"]:
row = {"in reference panel": gene in panel_genes}
for name, (store, cells) in monocyte_groups.items():
values = np.log1p(store.get_cell_vals(from_assay="RNA", cell_key="I", k=gene))
row[name] = values[cells].mean()
interferon_genes[gene] = row
pd.DataFrame.from_dict(interferon_genes, orient="index").round(2)| in reference panel | control CD14 Mono | control CD16 Mono | control neighbors of stimulated CD14 Mono | stimulated CD14 Mono | |
|---|---|---|---|---|---|
| ISG15 | True | 0.17 | 0.50 | 1.95 | 3.76 |
| IFIT3 | True | 0.02 | 0.15 | 0.50 | 1.47 |
| MX1 | True | 0.03 | 0.11 | 0.46 | 0.93 |
| CXCL10 | True | 0.01 | 0.28 | 0.70 | 2.79 |
Started: 2026-11-19T08:31:27.121581Z | Wall time: 2.550 s
All four genes belong to the reference panel, so the projection carries the interferon response into the reference PCA space. Control CD16 monocytes express each gene more than control CD14 monocytes do (ISG15 at 0.50 against 0.17), and stimulated CD14 monocytes express them far more (ISG15 at 3.76). The 61 control cells that the stimulated CD14 monocytes chose average ISG15 at 1.95, against 0.50 across all control CD16 monocytes, and the other three genes rank the four groups in the same order. The stimulated CD14 monocytes therefore land nearest to the control cells with the strongest interferon response, which mostly carry the CD16 Mono label. The dataset merging tutorial shows how stimulation changes the monocyte markers in a joint analysis of both samples. A reference labels only the states it contains: to label stimulated monocytes, it needs stimulated monocytes.
Adjust the threshold, the neighbors and the gene matching¶
Each of these settings saves a new result next to the existing one, so the two can be compared:
threshold_fractioninmapping.transfer_labelssets the share of neighbor weight that a label needs. A higher value labels fewer cells; the calibration curve shows what that gains in accuracy, here nothing.max_distanceinmapping.transfer_labelsmakes a cell abstain when its nearest reference cell is farther than this distance. On this query a distance limit cannot single out the monocytes: their median distance percentile, 0.950, is no higher than that of the CD4 naive T cells, 0.953.save_kinmapping.runkeeps more neighbors per query cell, which changes the votes and the mapping scores.missing_feature_policyinmapping.runsets what happens to panel genes that the query lacks:"reference_mean", the default, fills them with the reference mean, which is zero after scaling,"zero"fills them with a normalized zero, and"error"refuses the query.feature_key="names"inmapping.runmatches query genes to the panel by name instead of by ID, for a query that uses another ID scheme, such as gene symbols against Ensembl IDs. Query genes that share a name then add their counts, and a reference whose genes share a name is refused.
This reference is a plain PCA reference. A Symphony reference Kang et al., 2021, built from an analysis corrected with Harmony, also corrects the query: it estimates how the query, or each query batch given in query_batches, is offset from the reference and removes that offset. Use one only when the reference and the query differ by technical batch; on this query it would treat the interferon response as a batch offset and remove it.
Reuse the reference and saved labels¶
A later session reopens both stores and reloads the reference, the projection and the transfer from their artifact references without recomputing them. The code below reuses reference_ref, mapping_ref and transfer_ref from this session; a new session finds them again with ds_ctrl.artifacts.list(kind="mapping_reference", complete_only=True), and with the same call on ds_stim for kind="projection" and kind="label_transfer". A saved transfer loads from the query store alone.
# Reload the reference, projection and transfer from their saved references.
reference = ds_ctrl.mapping.load_reference(reference_ref)
reloaded_mapping = ds_stim.mapping.load_result(mapping_ref, reference=reference)
reloaded_transfer = ds_stim.mapping.load_label_transfer(transfer_ref)
# Check the reloaded results.
{
"query cells": reloaded_mapping.n_cells,
"batch correction": reloaded_mapping.correction_method,
"reference labels": reloaded_transfer.reference_label_source,
"threshold_fraction": reloaded_transfer.threshold_fraction,
}{'query cells': 10111,
'batch correction': 'none',
'reference labels': 'cluster_labels',
'threshold_fraction': 0.5}Started: 2026-11-19T08:31:29.672750Z | Wall time: 0.166 s
For repeated use, open the reference store with zarr_mode="r", so that no query can change it. When the query counts come from a read-only source, or from the store that holds the reference, mount_datastore creates a writable query store that reads its counts from that source.
Transferring again with unchanged reference labels and settings reuses the saved transfer. After the reference annotation changes, the same call freezes the new labels as another reference_labels artifact and saves a new transfer next to the old one, which keeps its labels. The reference labels can also come from a cell-label artifact of the reference store, such as a clustering.
The lineage of the transfer follows its inputs into the reference store: from the transfer through the frozen labels, the projection and the query cell selection, to the mapping reference and the reference analysis it was built from.
# Draw the transfer's lineage, which follows its inputs into the reference store.
ds_stim.artifacts.lineage(transfer_ref, references=reference)Started: 2026-11-19T08:31:29.839989Z | Wall time: 0.432 s
Artifacts marked external belong to the reference store: the mapping reference and the reference analysis that it was built from. The others belong to the query store, and every artifact is complete; the provenance guide explains how results record their inputs.
Before trusting labels from a reused reference, read featureCoverage and queryScaledDispersion, and look for a query population that crowds onto a few cells of another reference population; without known labels, group the query by its own clusters for that check. On this query, the dispersion of 1.33 and the 2,532 CD14 monocytes crowding onto 61 reference cells point to the problem, while the vote fractions and distance percentiles do not: the wrong labels rest on unanimous votes at distances typical of the whole query. When some query cells carry known labels, the confusion matrix and the calibration curve measure the result directly. The mapping API reference documents the methods and results used here, and the plotting API reference the diagnostic plots.
- Kang, J. B., Nathan, A., Weinand, K., Zhang, F., Millard, N., Rumker, L., Moody, D. B., Korsunsky, I., & Raychaudhuri, S. (2021). Efficient and precise single-cell reference atlas mapping with Symphony. Nature Communications, 12(1). 10.1038/s41467-021-25957-x