Select the highly variable genes (HVGs) of 3,948 human peripheral blood mononuclear cells (PBMCs) from a healthy donor. PCA, the neighbor graph, and the clusters and layouts built on them use only these genes. A gene’s variance rises with its mean expression, so a ranking by raw variance favors abundant transcripts, such as housekeeping and ribosomal protein genes, whose variance follows sequencing depth more than cell type. features.hvgs instead compares each gene’s variance with the variance of genes of similar mean and keeps the genes that rise furthest above that background.
The page changes one choice at a time: the gene families excluded by name, the variability score, and the number of genes. The highest-scoring genes each peak in one population, led by PPBP in the 12 platelets. The default name exclusions keep 8 MHC class II genes and 3 histone genes out of the top 500, although these genes mark the antigen-presenting cells and the platelets. Each pair of the three variability scores shares 362 to 414 of its 500 genes, and only seurat_v3 leaves out the T-cell marker CD3D. Doubling the selection to 1,000 genes redraws the T-cell clusters: the larger selection separates CD8 effector cells and a 52-cell regulatory T-cell cluster, and splits the naive T cells by the immediate early gene EGR1, a split that may come from sample handling. Every cluster outside the T cells keeps at least 92.9% of its cells together.
Open the saved PBMC analysis¶
The example store holds the counts of the 10x Genomics dataset “5k Peripheral blood mononuclear cells (PBMCs) from a healthy donor (v3 chemistry)”, released under CC BY 4.0, and the saved RNA analysis whose clusters the PBMC analysis names.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from IPython.display import display
import cytearc
from cytearc.features.gene_families import GENE_FAMILY_PATTERNS
from cytearc.features.variability import DEFAULT_HVG_BLACKLIST
from cytearc.plotting import CellField, FeatureRef, NormalizationSpec
# Keep routine logs and progress bars out of the results.
cytearc.configure_output(level="WARNING", progress=False)
# Download the prepared PBMC store, which holds the saved RNA analysis.
dataset = cytearc.datasets.connect("cytearc_docs").download_dataset(
"tenx_5K_pbmc_rnaseq", destination="cytearc_datasets", zarr=True
)Started: 2026-11-23T23:00:44.256258Z | Wall time: 6.620 s
ds.pipeline.open(label="rna") returns the saved analysis as a pipeline run, and indexing the run by an output name, such as run["analysis_cell_selection"] below, returns that saved result as an ArtifactRef, a reference to a result that never changes. analysis_cell_selection is the run’s frozen cell selection: a saved record of the cells that passed quality control, which later edits of the cell table cannot alter, so every gene selection on this page scores the same 3,948 cells. The run selected 500 genes to keep the example small; the RNA recipe, ds.pipeline.rna, selects 1,000 by default. The comparisons below read clusters through the broad cell types that the PBMC analysis assigns from marker genes, so the next cell also saves those names as the cell column pbmc_cell_type.
# Open the store, its saved RNA run, and the run's frozen selection of analyzed cells.
ds = cytearc.DataStore(f"{dataset}/data.zarr", nthreads=4)
run = ds.pipeline.open(label="rna")
cell_selection = run["analysis_cell_selection"]
analyzed = run.cells.fetch_all("I").astype(bool)
feature_names = ds.RNA.feats.fetch_all("names").astype(str)
print(
f"{analyzed.sum():,} of {ds.cells.N:,} cells analyzed; {len(feature_names):,} genes"
)
# Name the run's clusters with the broad cell types of the PBMC analysis.
cell_type_by_cluster = {
"1": "T cells",
"2": "CD14 monocytes",
"3": "T cells",
"4": "T cells",
"5": "NK cells",
"6": "B cells",
"7": "B cells",
"8": "T cells",
"9": "NK cells",
"10": "CD16 monocytes",
"11": "pDC-like cells",
"12": "platelets",
}
# Save the names as a cell column, keyed by cell ID, labeling the cells outside the analysis.
cell_types = np.full(ds.cells.N, "Not analyzed", dtype=object)
cell_types[analyzed] = [
cell_type_by_cluster[cluster] for cluster in run.cells.fetch("clusters").astype(str)
]
ds.cells.insert(
"pbmc_cell_type", pd.Series(cell_types, index=ds.cells.fetch_all("ids")), overwrite=True
)
analyzed_types = cell_types[analyzed]
# Read genes' normalized expression in the active cells, which are the analyzed cells.
def expression_of(genes):
return pd.DataFrame(
{
gene: ds.get_cell_vals(from_assay="RNA", cell_key="I", k=gene)
for gene in genes
}
)
# Count the analyzed cells of each broad cell type.
type_counts = pd.Series(analyzed_types).value_counts().rename_axis("broad cell type")
type_counts.rename("cells")3,948 of 5,025 cells analyzed; 33,538 genes
broad cell type
T cells 2385
CD14 monocytes 704
B cells 495
NK cells 312
CD16 monocytes 25
pDC-like cells 15
platelets 12
Name: cells, dtype: int64Started: 2026-11-23T23:00:50.877851Z | Wall time: 0.889 s
The 3,948 analyzed cells are mostly T cells (2,385), CD14 monocytes (704), B cells (495), and NK cells (312), with three small populations: 25 CD16 monocytes, 15 pDC-like cells, and 12 platelets.
Fit the mean-variance model¶
features.hvgs takes a cell selection and returns the selected genes as a feature-selection artifact. It scales each cell’s counts to a total of 1,000, computes each gene’s variance over the selected cells, and divides that variance by the lower quartile of the variances of genes with a similar mean. This corrected variance is 1 for a gene whose variance equals that background and grows as the gene varies more than its peers. The call keeps the top_n genes with the highest corrected variance, after the exclusions covered below, and draws its diagnostic: one point per gene, placed by its mean expression in the cells that detect it and by its corrected variance, both on log2 scales. Outlined points are the selected genes, and color shows how many cells detect each gene, from blue to green for the other genes and from pale yellow to black for the selected ones:
# Select 500 genes on the analyzed cells; the call draws its mean-variance diagnostic.
hvg_500 = ds.features.hvgs(cell_selection, top_n=500)
# Compare the selected genes with those of the saved run.
saved_values = ds.artifacts.load(run["highly_variable_features"])["values"][:]
print(
"Same genes as the saved run:",
bool((ds.artifacts.load(hvg_500)["values"][:] == saved_values).all()),
)
Same genes as the saved run: True
Started: 2026-11-23T23:00:51.768201Z | Wall time: 1.044 s
The selected genes lie above the unselected cloud across most of the range of mean expression, while most genes that nearly every cell detects, the green band at the lower right, sit near a corrected variance of 1 (0 on the log2 axis). A few unselected points score higher than the lowest selected genes: blue ones, and green ones such as FTL and MALAT1, the point at the far right. The blacklist or the detection bounds exclude these genes, as the next section shows. The call selects the same 500 genes as the saved run, which selected its genes on the same cells with the same settings.
The selection records its input, the feature summary: the per-gene statistics it was computed from, such as each gene’s variance and the number of cells that detect it. Read the statistics, then rank all genes by raw variance and the selected genes by corrected variance:
# Read each gene's statistics from the feature summary, the selection's recorded input.
inputs = ds.artifacts.inspect(hvg_500).inputs
summary = ds.artifacts.load(cytearc.ArtifactRef.from_dict(inputs["feature_summary"]))
selection = ds.artifacts.load(hvg_500)
gene_stats = pd.DataFrame(
{
"mean": summary["normed_tot"][:] / analyzed.sum(),
"variance": summary["sigmas"][:],
"corrected variance": selection["corrected_variance"][:],
"cells detecting": summary["normed_n"][:].astype(int),
"selected": selection["values"][:],
},
index=pd.Index(feature_names, name="gene"),
)
# Measure how closely variance follows the mean over the genes that any cell detects.
detected_genes = gene_stats[gene_stats["mean"] > 0]
correlation = detected_genes["variance"].corr(detected_genes["mean"], method="spearman")
print(f"Genes detected in any analyzed cell: {len(detected_genes):,}")
print(f"Spearman correlation of their variance and mean: {correlation:.3f}")
# Rank every gene by raw variance, then the selected genes by corrected variance.
display(gene_stats.drop(columns="mean").nlargest(10, "variance").round(1))
top_genes = gene_stats[gene_stats["selected"]].nlargest(10, "corrected variance")
top_genes = top_genes[["corrected variance", "cells detecting"]].round(1)
top_genes["highest mean in"] = (
expression_of(top_genes.index).groupby(analyzed_types).mean().idxmax()
)
top_genesGenes detected in any analyzed cell: 21,148
Spearman correlation of their variance and mean: 0.995
| variance | corrected variance | cells detecting | selected | |
|---|---|---|---|---|
| gene | ||||
| MALAT1 | 492.4 | 3.1 | 3945 | False |
| LYZ | 65.6 | 32.7 | 1857 | True |
| S100A9 | 60.9 | 44.6 | 1288 | True |
| S100A8 | 32.9 | 48.3 | 952 | True |
| MT-CO1 | 25.8 | 1.1 | 3945 | False |
| FTL | 22.9 | 11.6 | 3929 | False |
| EEF1A1 | 20.7 | 1.2 | 3944 | False |
| B2M | 19.5 | 1.4 | 3948 | False |
| RPS27 | 18.1 | 1.6 | 3945 | False |
| RPS12 | 17.5 | 1.6 | 3941 | False |
| corrected variance | cells detecting | highest mean in | |
|---|---|---|---|
| gene | |||
| PPBP | 243.2 | 36 | platelets |
| NRGN | 132.3 | 534 | platelets |
| PF4 | 90.9 | 21 | platelets |
| TUBB1 | 76.3 | 21 | platelets |
| CAVIN2 | 68.2 | 24 | platelets |
| GNG11 | 65.5 | 57 | platelets |
| IGLC3 | 51.0 | 223 | B cells |
| S100A8 | 48.3 | 952 | CD14 monocytes |
| IGLC2 | 48.2 | 269 | B cells |
| IGKC | 45.4 | 671 | B cells |
Started: 2026-11-23T23:00:52.813085Z | Wall time: 0.980 s
Variance follows the mean closely: over the 21,148 genes that any analyzed cell detects, the Spearman correlation between the two is 0.995. The 10 genes with the highest raw variance are therefore mostly abundant transcripts that nearly every cell detects: MALAT1, EEF1A1, B2M, FTL, the mitochondrial MT-CO1, and the ribosomal RPS27 and RPS12. Five of these seven score near the background of 1, with corrected variances of 1.1 to 1.6, while MALAT1 scores 3.1 and FTL 11.6. None of the seven is selected, because each is detected in at least 3,929 of the 3,948 cells, more than the upper detection bound described below allows; MT-CO1, RPS27, and RPS12 also match the name blacklist. The other three, the monocyte genes LYZ, S100A9, and S100A8, rank high on both scales and are selected.
Ranked by corrected variance, the top 10 selected genes each peak in one population: six in the platelets, three immunoglobulin light chains in the B cells, and S100A8 in the CD14 monocytes. The platelet gene PPBP leads with a variance 243 times the background of genes with a similar mean. A population of 12 cells can lead the ranking because its genes are highly expressed in those cells and nearly absent elsewhere: only 36 of the 3,948 cells detect PPBP.
Check what the default exclusions remove¶
Before ranking, features.hvgs removes genes by name and by how many cells detect them. The default blacklist, DEFAULT_HVG_BLACKLIST, is a case-insensitive regular expression matched from the start of each gene name. It combines the seven gene families of cytearc.features.gene_families: mitochondrial genes (MT-), cytosolic and mitochondrial ribosomal protein genes (RPS, RPL, MRPS, MRPL), cyclins (CCN followed by a letter), the MHC genes of human (HLA-) and mouse (H2-), the replication-dependent histones under their old and current symbols, and ten sex-linked genes such as XIST. Count the genes of each family in this dataset, and read the detection bounds that the selection applied to these cells:
# Count the genes that the default blacklist and each of its families match.
print(
"Genes matched by the default blacklist:",
len(ds.RNA.feats.grep(DEFAULT_HVG_BLACKLIST)),
)
family_counts = pd.Series(
{
family: len(ds.RNA.feats.grep(pattern))
for family, pattern in GENE_FAMILY_PATTERNS.items()
},
name="genes matched",
).rename_axis("family")
# Read the detection bounds that the selection applied to these cells.
bounds = ds.artifacts.inspect(hvg_500).parameters
print("Detection bounds:", {name: bounds[name] for name in ("min_cells", "max_cells")})
family_countsGenes matched by the default blacklist: 329
Detection bounds: {'min_cells': 20, 'max_cells': 3929}
family
mitochondrial 13
ribosomal 184
cellCycleCcn 31
hla 20
h2 0
histone 71
sexLinked 10
Name: genes matched, dtype: int64Started: 2026-11-23T23:00:53.794319Z | Wall time: 0.115 s
The blacklist matches 329 genes here, most of them ribosomal protein genes (184) and histones (71). These families vary with sequencing depth, cell quality, the cell cycle, or sex, and the measured expression of the polymorphic HLA genes can differ between donors. In many datasets they shape PCA without separating the cell types of interest. The patterns match names, not functions: ^CCN[A-Z] removes the cyclin CCND1 but not the matricellular protein CCN1, and the histone family leaves out replacement histones such as H3-3A. blacklist= replaces the whole default pattern, and blacklist="" excludes no names.
The detection bounds scale with the number of selected cells. min_cells keeps genes detected in at least the cube root of the number of selected cells, rounded up and never fewer than 20, so that from 8,000 cells on, genes seen in only a handful of cells of a large selection do not crowd out genes that mark cell types; a selection of fewer than 381 cells uses 5% of its cells instead, and at least 5. max_cells drops genes detected in more than 99.5% of the selected cells. For these 3,948 cells, a gene must be detected in at least 20 cells and in fewer than 3,929. Pass min_cells= or max_cells= to move the detection bounds; max_cells=np.inf removes the upper one.
Select 500 genes again with blacklist="" to see which genes the exclusions keep out. The table ranks each entering gene within the new selection and gives the percentage of each broad cell type’s cells that detect it:
# Select 500 genes again without name exclusions; find the genes that enter and leave.
hvg_no_blacklist = ds.features.hvgs(
cell_selection, top_n=500, blacklist="", show_plot=False
)
unblocked = ds.artifacts.load(hvg_no_blacklist)
unblocked_values = unblocked["values"][:]
default_values = gene_stats["selected"].to_numpy()
entering = feature_names[unblocked_values & ~default_values]
leaving = feature_names[default_values & ~unblocked_values]
# Rank the genes that leave within the default selection.
default_rank = gene_stats.loc[default_values, "corrected variance"].rank(
ascending=False
)
print(
"Genes that leave, by rank in the default selection:",
", ".join(
f"{gene} ({rank})"
for gene, rank in default_rank[leaving].astype(int).sort_values().items()
),
)
# Rank the entering genes, and give the share of each cell type that detects them.
unblocked_scores = pd.Series(unblocked["corrected_variance"][:], index=feature_names)
unblocked_rank = unblocked_scores[unblocked_values].rank(ascending=False)
detection = expression_of(entering).gt(0).groupby(analyzed_types).mean()
detection = (
detection.mul(100).round().astype(int).T[type_counts.index].add_suffix(" (%)")
)
detection.insert(0, "rank without blacklist", unblocked_rank[entering].astype(int))
detection.sort_values("rank without blacklist").rename_axis("gene")Genes that leave, by rank in the default selection: HMOX1 (490), GADD45G (491), NUP214 (492), MARCH1 (493), CYTOR (494), WARS (495), LYN (496), LMO2 (497), PCLAF (498), BST1 (499), CD83 (500)
| rank without blacklist | T cells (%) | CD14 monocytes (%) | B cells (%) | NK cells (%) | CD16 monocytes (%) | pDC-like cells (%) | platelets (%) | |
|---|---|---|---|---|---|---|---|---|
| gene | ||||||||
| HIST1H2AC | 19 | 12 | 10 | 14 | 12 | 20 | 27 | 100 |
| HLA-DRA | 42 | 19 | 99 | 100 | 27 | 100 | 100 | 0 |
| HLA-DRB1 | 55 | 20 | 98 | 100 | 46 | 100 | 100 | 0 |
| HLA-DQA1 | 60 | 2 | 9 | 99 | 3 | 36 | 27 | 0 |
| HLA-DPA1 | 68 | 36 | 94 | 100 | 71 | 100 | 100 | 0 |
| HLA-DPB1 | 78 | 38 | 92 | 100 | 74 | 100 | 100 | 8 |
| HIST1H2BJ | 114 | 4 | 0 | 1 | 4 | 4 | 7 | 75 |
| HLA-DQB1 | 120 | 3 | 53 | 98 | 2 | 64 | 73 | 0 |
| HIST1H3H | 201 | 2 | 1 | 1 | 3 | 0 | 7 | 92 |
| HLA-DMB | 339 | 5 | 86 | 92 | 6 | 56 | 93 | 0 |
| HLA-DMA | 348 | 11 | 81 | 92 | 10 | 68 | 100 | 8 |
Started: 2026-11-23T23:00:53.910394Z | Wall time: 1.677 s
Clearing the blacklist moves 8 MHC class II genes and 3 histone genes into the top 500 and pushes out the 11 lowest-ranked genes of the default selection, ranks 490 to 500. Two of the entering genes rank near the top of the new selection: HIST1H2AC 19th and HLA-DRA 42nd. The MHC class II genes mark the antigen-presenting cells: HLA-DRA is detected in 100% of B cells, 99% of CD14 monocytes, and all 25 CD16 monocytes and 15 pDC-like cells, against 19% of T cells and 27% of NK cells. The histone genes are detected in 75 to 100% of the 12 platelets and in at most 27% of the cells of any other population.
Color the saved UMAP by HLA-DRA, the highest-ranked MHC class II gene, beside the broad cell types:
# Show where the highest-ranked excluded MHC class II gene is expressed.
ds.plots.embedding(
layout=run["umap"],
color_by=[
FeatureRef("HLA-DRA", label="HLA-DRA, log(1 + counts per 1,000)"),
CellField("pbmc_cell_type", label="Broad cell type"),
],
normalization=NormalizationSpec(transform="log1p"),
)
Started: 2026-11-23T23:00:55.589033Z | Wall time: 0.282 s
HLA-DRA expression is high in the B-cell, monocyte, and pDC-like clusters and low or absent in most T and NK cells and in the platelets. The default selection separates these populations with other genes, but an analysis of antigen presentation, or of activated T cells, which express MHC class II, can keep the HLA genes and exclude the other families:
# Exclude every default gene family except the HLA genes.
blacklist = "|".join(
pattern for family, pattern in GENE_FAMILY_PATTERNS.items() if family != "hla"
)
ds.features.hvgs(cell_selection, top_n=500, blacklist=blacklist)Choose a variability score¶
features.hvgs scores variability with one of three flavors:
"cytearc", the default, divides the variance of library-size normalized values by the background of genes with a similar mean, as above."seurat_v3"fits the trend of raw-count variance against the mean by local regression, standardizes each gene’s counts with that trend, clips them, and scores the variance of the result, as Seurat’svstmethod and Scanpy’sflavor="seurat_v3"do Stuart et al., 2019."pearson_residuals"scores the variance of analytic Pearson residuals of the counts under a negative binomial model Lause et al., 2021, as Scanpy’s experimental flavor of that name does.
The two count-based flavors apply no detection bounds unless you pass them, but they keep the blacklist; pass blacklist="" to reproduce Scanpy’s selection. Select 500 genes with each flavor and count the genes that each pair shares:
# Select 500 genes with each flavor on the same cells.
flavor_refs = {
flavor: ds.features.hvgs(cell_selection, flavor=flavor, top_n=500, show_plot=False)
for flavor in ("cytearc", "seurat_v3", "pearson_residuals")
}
flavor_values = {
flavor: ds.artifacts.load(ref)["values"][:] for flavor, ref in flavor_refs.items()
}
# Count the genes that each pair of flavors selects together.
pd.DataFrame(
{
first: {
second: int((flavor_values[first] & flavor_values[second]).sum())
for second in flavor_values
}
for first in flavor_values
}
)| cytearc | seurat_v3 | pearson_residuals | |
|---|---|---|---|
| cytearc | 500 | 362 | 414 |
| seurat_v3 | 362 | 500 | 374 |
| pearson_residuals | 414 | 374 | 500 |
Started: 2026-11-23T23:00:55.871889Z | Wall time: 1.843 s
# Compare the flavors on lineage markers and on how many cells detect their genes.
lineage_markers = ["CD3D", "MS4A1", "CD14", "LYZ", "NKG7", "GNLY", "PPBP"]
cells_detecting = gene_stats["cells detecting"]
pd.DataFrame(
{
flavor: {
"lineage markers left out": ", ".join(
gene
for gene in lineage_markers
if not values[feature_names == gene].any()
)
or "none",
f"genes detected in fewer than {bounds['min_cells']} cells": int(
(cells_detecting[values] < bounds["min_cells"]).sum()
),
"median cells detecting a gene": int(cells_detecting[values].median()),
}
for flavor, values in flavor_values.items()
}
).T.rename_axis("flavor")| lineage markers left out | genes detected in fewer than 20 cells | median cells detecting a gene | |
|---|---|---|---|
| flavor | |||
| cytearc | none | 0 | 614 |
| seurat_v3 | CD3D | 56 | 494 |
| pearson_residuals | none | 53 | 611 |
Started: 2026-11-23T23:00:57.715622Z | Wall time: 0.006 s
Each pair of flavors shares 362 to 414 of its 500 genes. Without a detection bound, the count-based flavors also select genes that few cells detect: 56 seurat_v3 genes and 53 Pearson residual genes are detected in fewer than 20 cells, which the default flavor’s lower bound excludes. Only seurat_v3 shifts its whole selection toward rarely detected genes: its median gene is detected in 494 cells, against 614 for the default flavor and 611 for Pearson residuals. seurat_v3 also leaves out the T-cell marker CD3D, while the other two flavors keep all seven lineage markers.
Pearson residuals also serve as a normalization. Setting ds.RNA.normMethod to a PearsonResidualNormalizer makes every normalized read of the assay return residuals, including the reads of marker search. theta sets the negative binomial overdispersion, 100 by default, and clip the largest absolute residual, by default the square root of the number of normalized cells; the example clips at 10. cytearc.assay.norm_pearson_residuals is the normalizer with both defaults. Run PCA on the residuals of the residual flavor’s genes without rescaling each gene, since residuals are already standardized, then restore library-size normalization for the rest of the page:
# Reduce Pearson residuals of the residual flavor's genes without rescaling each gene.
ds.RNA.normMethod = cytearc.assay.PearsonResidualNormalizer(theta=100, clip=10)
residuals = ds.features.normalize(cell_selection, flavor_refs["pearson_residuals"])
residual_pca = ds.reduction.pca(residuals, dims=15, feat_scaling=False)
# Restore library-size normalization for the rest of the page.
ds.RNA.normMethod = cytearc.assay.norm_lib_size
ds.artifacts.load(residual_pca)["data"].shape(3948, 15)Started: 2026-11-23T23:00:57.722547Z | Wall time: 0.843 s
Select genes across samples¶
When samples differ technically, a pooled selection can favor genes that separate the samples rather than cell states. With batch, features.hvgs scores every sample on its own, counts the samples in which each gene ranks among the top_n, and selects the genes variable in the most samples, ties broken by their median rank. That is the order of Seurat’s SelectIntegrationFeatures and of Scanpy’s flavor="seurat_v3_paper"; Scanpy’s flavor="seurat_v3" sorts by median rank first. batch takes a cell metadata column or a label artifact such as HTO identities; every selected cell needs a label, and every sample at least two selected cells. This dataset holds one sample, so the call is shown without running it, and the Harmony batch correction tutorial compares pooled and batch-aware selections before Harmony:
# Score each sample on its own and keep the genes variable in the most samples.
by_sample = ds.features.hvgs(cell_selection, flavor="seurat_v3", batch="sample", top_n=2000)
# Count, for each gene, the samples that rank it among their top 2,000.
batch_count = ds.artifacts.load(by_sample)["batch_count"][:]Compare 500 and 1,000 genes¶
The number of selected genes sets the basis of PCA, and through it the neighbor graph and the clusters. Select 1,000 genes on the same cells:
# Select 1,000 genes on the same cells.
hvg_1000 = ds.features.hvgs(cell_selection, top_n=1000, show_plot=False)
hvg_1000_values = ds.artifacts.load(hvg_1000)["values"][:]
print(
"Genes of the 500-gene selection among the 1,000:",
int((hvg_1000_values & default_values).sum()),
)Genes of the 500-gene selection among the 1,000: 500
Started: 2026-11-23T23:00:58.566678Z | Wall time: 0.677 s
The 1,000 genes include all 500 of the smaller selection, so the larger set adds the next 500 genes of the ranking. Build a branch from each selection: its own normalization, PCA, neighbor graph, UMAP, and Leiden clusters. Both branches use the saved run’s settings of 15 PCs, 11 neighbors, and Leiden resolution 0.5, so that only the number of genes differs:
# Build each branch with the saved run's PCA, neighbor, and Leiden settings.
branches = {}
for top_n, features in {500: hvg_500, 1000: hvg_1000}.items():
pca = ds.reduction.pca(ds.features.normalize(cell_selection, features), dims=15)
graph = ds.graph.connectivity(ds.graph.neighbors(ds.graph.ann_index(pca), k=11))
branches[top_n] = (
ds.embeddings.umap(graph, ds.embeddings.initialization(pca)),
ds.clusters.leiden(graph, resolution=0.5),
)
# Read each branch's cluster label for every analyzed cell.
cluster_labels = {
top_n: ds.artifacts.load_values(clusters, cell_ids=False).values
for top_n, (_, clusters) in branches.items()
}
# Compare the 500-gene branch's clusters with those of the saved run.
saved_labels = ds.artifacts.load_values(run["clusters"], cell_ids=False).values
print(
"The 500-gene branch reproduces the saved run's clusters:",
bool(np.array_equal(cluster_labels[500], saved_labels)),
)
pd.Series(
{top_n: len(np.unique(labels)) for top_n, labels in cluster_labels.items()},
name="Leiden clusters",
).rename_axis("selected genes")The 500-gene branch reproduces the saved run's clusters: True
selected genes
500 12
1000 14
Name: Leiden clusters, dtype: int64Started: 2026-11-23T23:00:59.244626Z | Wall time: 8.631 s
The 500-gene branch reproduces the saved run’s clusters, and the 1,000-gene branch finds 14 clusters against 12. Color each branch’s UMAP by its own clusters, and both by the broad cell types:
# Draw each branch's UMAP twice: by its own clusters, and by the broad cell types.
figure, axes = plt.subplots(2, 2, figsize=(10, 9), layout="constrained")
for column, (top_n, (umap, clusters)) in enumerate(branches.items()):
ds.plots.embedding(
layout=umap,
color_by=clusters,
legend_loc="on_data",
target=axes[0, column],
show_titles=False,
show=False,
)
axes[0, column].set_title(f"{top_n:,} genes: Leiden clusters")
ds.plots.embedding(
layout=umap,
color_by=CellField("pbmc_cell_type", label="Broad cell type"),
legend_loc="right" if column == 1 else "none",
target=axes[1, column],
show_titles=False,
show=False,
)
axes[1, column].set_title(f"{top_n:,} genes: broad cell types")
plt.show()
Started: 2026-11-23T23:01:07.876752Z | Wall time: 0.557 s
In both layouts the broad cell types stay apart: the B cells, the monocytes, and the small pDC-like and platelet clusters lie away from the T and NK cells. The partitions differ inside the T cells, which form clusters 1, 3, 4, and 8 with 500 genes and six clusters with 1,000. Each partition numbers its clusters by size, so the same number can name different cells in the two. Cross-tabulate the partitions cell by cell, with the broad cell type of each 500-gene cluster, and measure their agreement with the adjusted Rand index (ARI), which is 1 for identical partitions and near 0 for unrelated ones:
# Count how the cells of each 500-gene cluster spread over the 1,000-gene clusters.
counts = pd.crosstab(
pd.Series(cluster_labels[500], name="500 genes"),
pd.Series(cluster_labels[1000], name="1,000 genes"),
)
crossing = counts.copy()
crossing["cells"] = counts.sum(axis=1)
crossing["largest share (%)"] = (100 * counts.max(axis=1) / crossing["cells"]).round(1)
# Label each 500-gene cluster with its broad cell type.
crossing = crossing.rename(
index=lambda cluster: f"{cluster} ({cell_type_by_cluster[str(cluster)]})"
)
# Measure the agreement of the two partitions, whatever their cluster numbers.
ari = ds.clusters.compute_concordance(branches[500][1], branches[1000][1])
print(f"Adjusted Rand index: {ari:.3f}")
crossingAdjusted Rand index: 0.704
| 1,000 genes | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | cells | largest share (%) |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 500 genes | ||||||||||||||||
| 1 (T cells) | 921 | 0 | 7 | 282 | 0 | 0 | 0 | 0 | 5 | 2 | 0 | 0 | 0 | 0 | 1217 | 75.7 |
| 2 (CD14 monocytes) | 0 | 701 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 0 | 704 | 99.6 |
| 3 (T cells) | 2 | 0 | 236 | 0 | 9 | 279 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 528 | 52.8 |
| 4 (T cells) | 60 | 0 | 309 | 55 | 0 | 0 | 0 | 0 | 0 | 50 | 0 | 0 | 0 | 0 | 474 | 65.2 |
| 5 (NK cells) | 0 | 0 | 0 | 0 | 276 | 4 | 0 | 0 | 0 | 0 | 3 | 0 | 0 | 0 | 283 | 97.5 |
| 6 (B cells) | 0 | 0 | 0 | 0 | 0 | 0 | 247 | 9 | 0 | 0 | 0 | 0 | 0 | 0 | 256 | 96.5 |
| 7 (B cells) | 0 | 0 | 0 | 0 | 0 | 0 | 17 | 222 | 0 | 0 | 0 | 0 | 0 | 0 | 239 | 92.9 |
| 8 (T cells) | 11 | 0 | 0 | 58 | 0 | 0 | 0 | 0 | 97 | 0 | 0 | 0 | 0 | 0 | 166 | 58.4 |
| 9 (NK cells) | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 29 | 0 | 0 | 0 | 29 | 100.0 |
| 10 (CD16 monocytes) | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 0 | 0 | 25 | 100.0 |
| 11 (pDC-like cells) | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 0 | 15 | 100.0 |
| 12 (platelets) | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 12 | 12 | 100.0 |
Started: 2026-11-23T23:01:08.435670Z | Wall time: 0.016 s
The partitions agree with an ARI of 0.704. Outside the T cells, every 500-gene cluster keeps at least 92.9% of its cells in one 1,000-gene cluster. The four T-cell clusters keep 52.8 to 75.7% of their cells together and become six. Read the new T-cell clusters with markers of T-cell states: the table gives whether each selection includes a marker and the percentage of each cluster’s cells that detect it.
# Find the 1,000-gene clusters that consist mostly of T cells.
majority_type = pd.crosstab(analyzed_types, cluster_labels[1000]).idxmax()
t_cell_clusters = majority_type.index[majority_type == "T cells"]
# Name the T-cell state that each marker reports.
t_cell_markers = {
"CCR7": "naive and central memory",
"LEF1": "naive",
"CD8B": "CD8 T cells",
"GZMK": "effector memory",
"GZMH": "cytotoxic effector",
"IL7R": "naive and memory, low in regulatory",
"FOXP3": "regulatory",
"CTLA4": "regulatory",
"IKZF2": "regulatory",
"EGR1": "immediate early response",
}
# Give the share of each T-cell cluster's cells that detect each marker.
genes = list(t_cell_markers)
detection = expression_of(genes).gt(0).groupby(cluster_labels[1000]).mean()
detection = detection.mul(100).round().astype(int).T[t_cell_clusters]
sizes = pd.Series(cluster_labels[1000]).value_counts()
detection.columns = [
f"{cluster} ({sizes[cluster]} cells)" for cluster in t_cell_clusters
]
in_1000 = pd.Series(hvg_1000_values, index=feature_names)
detection.insert(0, "among the 1,000 genes", in_1000[genes])
detection.insert(0, "among the 500 genes", gene_stats.loc[genes, "selected"])
detection.insert(0, "marks", pd.Series(t_cell_markers))
detection.rename_axis("marker")| marks | among the 500 genes | among the 1,000 genes | 1 (994 cells) | 3 (552 cells) | 4 (395 cells) | 6 (283 cells) | 9 (102 cells) | 10 (52 cells) | |
|---|---|---|---|---|---|---|---|---|---|
| marker | |||||||||
| CCR7 | naive and central memory | False | True | 84 | 28 | 85 | 7 | 87 | 33 |
| LEF1 | naive | False | True | 77 | 35 | 78 | 10 | 82 | 50 |
| CD8B | CD8 T cells | True | True | 5 | 8 | 14 | 64 | 96 | 0 |
| GZMK | effector memory | True | True | 2 | 47 | 3 | 57 | 1 | 2 |
| GZMH | cytotoxic effector | True | True | 1 | 7 | 1 | 70 | 1 | 2 |
| IL7R | naive and memory, low in regulatory | True | True | 88 | 98 | 91 | 54 | 93 | 42 |
| FOXP3 | regulatory | True | True | 1 | 1 | 1 | 1 | 0 | 46 |
| CTLA4 | regulatory | False | True | 2 | 4 | 1 | 0 | 0 | 27 |
| IKZF2 | regulatory | False | True | 2 | 4 | 7 | 17 | 4 | 46 |
| EGR1 | immediate early response | True | True | 76 | 72 | 27 | 49 | 73 | 44 |
Started: 2026-11-23T23:01:08.453103Z | Wall time: 1.158 s
The markers name the six T-cell clusters of the 1,000-gene partition:
CD8 effector cells separate from the other memory T cells. Of the 528 cells of 500-gene cluster 3, 279 form most of 1,000-gene cluster 6, where 64% of cells detect CD8B and 70% GZMH. Another 236 join 309 cells of 500-gene cluster 4 in 1,000-gene cluster 3, where 8% detect CD8B and 47% GZMK.
Regulatory T cells form a cluster of their own. Cluster 10 of the 1,000-gene partition holds 52 cells, 50 of them from 500-gene cluster 4: 46% of its cells detect FOXP3, 46% IKZF2, and 27% CTLA4, and fewer detect IL7R (42%) than in any other T-cell cluster.
The naive T cells split by detection of the immediate early gene EGR1. Of the 1,217 cells of 500-gene cluster 1, 921 form most of 1,000-gene cluster 1 and 282 join 1,000-gene cluster 4. Both clusters detect CCR7 in most cells (84% and 85%), but EGR1 in 76% and 27% of cells.
Naive CD8 T cells make up 1,000-gene cluster 9: 96% of its 102 cells detect CD8B, 87% CCR7, and 82% LEF1. The cluster takes 97 of the 166 cells of 500-gene cluster 8, and 58 others join 1,000-gene cluster 4.
Only the larger selection holds the naive T-cell markers CCR7 and LEF1 and the regulatory T-cell genes CTLA4 and IKZF2. With 1,000 genes, the clusters resolve regulatory T cells and CD8 effector cells. The naive split needs checking before it is read as a cell state, because immediate early genes such as EGR1 respond within minutes to stimulation, including the handling of cells before capture.
Supply your own gene set¶
A study can call for a specific gene program or a gene set chosen elsewhere. features.snapshot saves such a set as a feature selection, from a Boolean mask over the complete gene axis or from integer indexes into the gene table, and rejects duplicate or out-of-range indexes, misaligned masks, and empty sets. A graph built from a small marker panel separates the identities that the panel was chosen for, so it cannot test those identities. Save a six-gene panel:
# Match a small marker panel to the complete gene axis.
panel_genes = ["CD3D", "MS4A1", "CD14", "LYZ", "NKG7", "GNLY"]
panel_mask = np.isin(feature_names, panel_genes)
print("mask length:", len(panel_mask), "selected:", int(panel_mask.sum()))
# Save the panel as a feature selection.
custom_features = ds.features.snapshot(mask=panel_mask)
custom_featuresmask length: 33538 selected: 6
ArtifactRef(assay='RNA', kind='feature_selection', artifact_id='5de8a22e6ccf...')Started: 2026-11-23T23:01:09.612686Z | Wall time: 0.026 s
The returned ArtifactRef takes the place of an HVG selection in every later step, such as ds.features.normalize(cell_selection, custom_features). ds.RNA.feats.sift and multi_sift build Boolean masks from feature metadata columns, and get_index_by returns feature indexes for feature_indexes=. features.detected(cell_selection, min_cells=...) selects genes by detection alone, and features.universe() selects every gene.
Set the gene selection of the RNA recipe¶
The RNA recipe selects 1,000 genes with the default flavor and blacklist, and its hvg keyword takes the settings of features.hvgs:
# Select 2,000 genes and keep the HLA genes, with the blacklist built above.
ds.pipeline.rna(hvg={"top_n": 2000, "blacklist": blacklist})Compare feature sets on the same frozen cells with features.hvgs, as this page does, before fixing the recipe’s settings. For scATAC-seq, features.prevalent_peaks plays the same role: it keeps the most prevalent peaks, and the ATAC recipe takes prevalent_peaks={"top_n": ...}, as the scATAC-seq tutorial shows.
- Stuart, T., Butler, A., Hoffman, P., Hafemeister, C., Papalexi, E., Mauck, W. M., Hao, Y., Stoeckius, M., Smibert, P., & Satija, R. (2019). Comprehensive Integration of Single-Cell Data. Cell, 177(7), 1888-1902.e21. 10.1016/j.cell.2019.05.031
- Lause, J., Berens, P., & Kobak, D. (2021). Analytic Pearson residuals for normalization of single-cell RNA-seq UMI data. Genome Biology, 22(1). 10.1186/s13059-021-02451-7