Call each droplet’s donor in a pooled eight-donor experiment from hashtag oligonucleotide (HTO) counts, and check the calls against each droplet’s RNA content. In cell hashing, each sample is stained with its own HTO, attached through antibodies or lipids, so that several samples can share one droplet capture. A droplet with one positive tag is called a singlet, one with two or more a doublet, and one with none a negative.
The data come from the cell hashing experiment of Stoeckius et al. (2018), which stained the peripheral blood mononuclear cells (PBMCs) of eight human donors with one tag per donor, BatchA to BatchH, and pooled them with unstained HEK293T and mouse NIH3T3 cells as negative controls. Of 21,522 barcodes with at least 200 RNA UMIs, ds.qc.hto_demultiplexing calls 16,322 singlets (75.8%; 1,764 to 2,281 per donor), 3,203 doublets (14.9%) and 1,997 negatives (9.3%). The RNA counts, which the demultiplexing never reads, agree with the calls: doublets hold a median of 1,002 RNA UMIs against the singlets’ 561, and 81.9% of negatives hold more than 5,000 RNA UMIs, against 4.5% of singlets, so most negatives are the unstained cell lines.
Download the cell hashing example¶
The tag counts and the RNA counts come from GEO series GSE108313, as a 1.1 MB HTO file and a 33 MB RNA file. Only the eight tag counts go into a CyteArc store; from the RNA file the page keeps only each barcode’s total, to choose the barcodes that hold a cell and later to check the calls. The downloads and the store go to a temporary directory; to keep them, use a project directory instead.
# Download, verify and read the published count files.
import gzip
import hashlib
import shutil
import time
from http.client import HTTPException
from pathlib import Path
from tempfile import TemporaryDirectory
from urllib.request import urlopen
# Tabulate and plot the results, and write the tag counts to a CyteArc store.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.sparse import csr_matrix
import cytearc
# Keep routine logs and progress bars out of the results.
cytearc.configure_output(level="WARNING", progress=False)
# Keep this example's downloads and store together in a temporary directory.
work = TemporaryDirectory()
output_dir = Path(work.name)Started: 2026-11-18T00:15:59.086083Z | Wall time: 1.466 s
# Pin the two public GEO files, so that a changed download cannot alter the example silently.
sources = {
"hto": (
"https://ftp.ncbi.nlm.nih.gov/geo/samples/GSM2895nnn/GSM2895283/suppl/"
"GSM2895283_Hashtag-HTO-count.csv.gz",
"68ab6cd853964026a79f5c3da58a901808eab18c25684b3eecd41ebb71b9bce2",
),
"rna": (
"https://ftp.ncbi.nlm.nih.gov/geo/samples/GSM2895nnn/GSM2895282/suppl/"
"GSM2895282_Hashtag-RNA.umi.txt.gz",
"98a2be289ce79c2a2104eeaff3e39528ea25dfa0b3f3c1faf7246843f65ce3d9",
),
}
attempts = 3
paths = {}
for assay, (url, expected_digest) in sources.items():
path = output_dir / url.rsplit("/", 1)[1]
# Copy the response to disk in blocks, and try again after a pause when the connection fails.
for attempt in range(1, attempts + 1):
try:
with urlopen(url, timeout=60) as response, path.open("wb") as destination:
shutil.copyfileobj(response, destination)
break
except (OSError, HTTPException) as error:
if attempt == attempts:
raise RuntimeError(
f"Downloading {path.name} failed {attempts} times; check the connection to GEO"
) from error
time.sleep(30 * attempt)
# Reject a file whose contents differ from the verified source.
with path.open("rb") as source:
actual_digest = hashlib.file_digest(source, "sha256").hexdigest()
if actual_digest != expected_digest:
raise ValueError(f"Checksum mismatch for {path.name}")
paths[assay] = path
# Show the size of each download.
pd.Series(
{assay: path.stat().st_size / 1_000_000 for assay, path in paths.items()},
name="Downloaded MB",
).round(2)hto 1.07
rna 32.73
Name: Downloaded MB, dtype: float64Started: 2026-11-18T00:16:00.554935Z | Wall time: 1.428 s
Read the eight tag counts¶
The HTO table has tags in rows and barcodes in columns. Three of its rows, bad_struct, no_match and total_reads, summarize read processing rather than count a tag, so they are dropped before import. Each tag name is shortened to its BatchA to BatchH prefix; the suffix is the tag’s oligonucleotide sequence.
# Read the small tag table and drop the three read-processing rows.
hto_counts = pd.read_csv(paths["hto"], index_col=0).drop(
index=["bad_struct", "no_match", "total_reads"]
).T
# Put barcodes in rows and the short tag names in columns.
hto_counts.index.name = "barcode"
hto_counts.columns = hto_counts.columns.str.split("-").str[0]
hto_counts.head()| BatchA | BatchB | BatchC | BatchD | BatchE | BatchF | BatchG | BatchH | |
|---|---|---|---|---|---|---|---|---|
| barcode | ||||||||
| GGCGACTAGAGGACGG | 30 | 16 | 26 | 2698 | 8 | 15 | 55 | 32 |
| CATCAAGGTCTTGTCC | 4 | 39 | 0 | 22 | 24 | 47 | 21 | 17 |
| AAACCTGAGTGATCGG | 12 | 15 | 19 | 2 | 32 | 12 | 76 | 3 |
| TGAGGGAGTACTTAGC | 26 | 20 | 13 | 24 | 6 | 75 | 76 | 32 |
| CCTAAAGAGATGTGGC | 7 | 4 | 12 | 24 | 1755 | 19 | 82 | 5 |
Started: 2026-11-18T00:16:01.985679Z | Wall time: 2.156 s
Two of the first five barcodes carry one tag in the thousands, BatchD with 2,698 counts and BatchE with 1,755, while every other count in the table stays below 100.
Choose barcodes using RNA counts¶
HTO counts alone do not show that a droplet contains a cell. Keep the barcodes that both files hold and that have at least 200 RNA UMIs, the RNA threshold that Stoeckius et al. (2018) used to choose the barcodes to classify. The unstained cell lines stay in, so their barcodes should be called negative. The RNA table holds 40,899 genes for 50,000 barcodes, too large to load whole, so the next cell sums it one gene at a time, which takes about a minute.
# Sum the RNA UMIs of each barcode one gene at a time, without loading the whole matrix.
with gzip.open(paths["rna"], "rt") as source:
rna_barcodes = next(source).rstrip().split("\t")[1:]
rna_totals = np.zeros(len(rna_barcodes), dtype=np.int64)
n_genes = 0
for line in source:
gene, values = line.split("\t", 1)
gene_counts = np.fromstring(values, sep="\t", dtype=np.int64)
if gene_counts.size != rna_totals.size:
raise ValueError(f"Unexpected number of RNA counts for {gene}")
rna_totals += gene_counts
n_genes += 1
# Keep the barcodes that both files hold and that have at least 200 RNA UMIs.
rna_totals = pd.Series(rna_totals, index=rna_barcodes, name="RNA_nCounts")
shared_barcodes = rna_totals.index.intersection(hto_counts.index)
selected_barcodes = shared_barcodes[rna_totals.loc[shared_barcodes] >= 200]
selected_counts = hto_counts.loc[selected_barcodes]
# Report the size of each input and of the selection.
pd.Series({
"Genes in the RNA file": n_genes,
"Barcodes in the RNA file": len(rna_barcodes),
"Barcodes in the HTO file": len(hto_counts),
"Barcodes in both files": len(shared_barcodes),
"Shared barcodes with at least 200 RNA UMIs": len(selected_counts),
}, name="Count")Genes in the RNA file 40899
Barcodes in the RNA file 50000
Barcodes in the HTO file 65000
Barcodes in both files 39842
Shared barcodes with at least 200 RNA UMIs 21522
Name: Count, dtype: int64Started: 2026-11-18T00:16:04.144698Z | Wall time: 31.802 s
Import the HTO assay¶
Write the selected tag counts to a new store and declare the assay’s type as HTO, which ds.qc.hto_demultiplexing requires. The first writable open of a store removes from I, the column of active cells that analyses start from, every cell that detects 10 or fewer features of the default assay; a barcode here detects at most eight tags, so min_features_per_cell=-1 turns that floor off and I keeps every selected barcode. The RNA totals become a cell column, RNA_nCounts, without copying the RNA matrix.
# Write the selected raw tag counts to a new store, and declare the assay's type as HTO.
store_path = output_dir / "cell_hashing.zarr"
cytearc.SparseToZarr(
csr_matrix(selected_counts.to_numpy()),
str(store_path),
cell_ids=selected_counts.index.to_numpy(),
feature_ids=selected_counts.columns.to_numpy(),
assay_name="HTO",
assay_type="HTO",
nthreads=4,
mem_budget="1G",
).dump()
# Open the store without the feature-count floor, so that every selected barcode stays active.
ds = cytearc.DataStore(
str(store_path),
default_assay="HTO",
min_features_per_cell=-1,
nthreads=4,
mem_budget="1G",
)
# Add each barcode's RNA total as a cell column, keyed by barcode.
ds.cells.insert("RNA_nCounts", rna_totals.loc[ds.cells.fetch_all("ids")])
dsDataStore has 21522 (21522) cells with 1 assays: HTO
Cell metadata:
'I', 'ids', 'names', 'HTO_nCounts', 'HTO_nFeatures',
'RNA_nCounts', 'sourceRow'
HTO assay has 8 features and following metadata:
'I', 'ids', 'names', 'dropOuts', 'nCells'Started: 2026-11-18T00:16:35.948863Z | Wall time: 3.531 s
Assign singlets, doublets and negatives¶
ds.qc.hto_demultiplexing follows the method of Stoeckius et al. (2018), which Seurat implements as HTODemux. The method normalizes each tag’s counts across barcodes with the centered log-ratio (CLR) transform, clusters the barcodes with k-means into one more cluster than there are tags, and takes, for each tag, the cluster with the lowest mean count as the tag’s background. Each tag’s cutoff is the 0.99 quantile of a negative binomial distribution fitted to its background counts, and a count above the cutoff is positive; positive_quantile, Seurat’s positive.quantile, sets another quantile. The original method and Seurat’s default both cluster with k-medoids; with k-means, Seurat’s HTODemux makes the same calls as CyteArc in the comparison that the methods reference reports.
ds.qc.hto_demultiplexing reads a cell selection, a frozen record of which barcodes to analyze, and saves its calls as an artifact, an immutable stored result that records its inputs and settings; the cell table stays unchanged. Each singlet is labeled with its one positive tag, and every other barcode with Doublet, which includes higher-order multiplets, or Negative. Seurat instead names a singlet after the tag with its highest CLR value, which in unbalanced pools can be a tag that the cutoff called negative.
# Freeze the selected barcodes as a cell selection and demultiplex their raw tag counts.
cell_selection = ds.snapshot_cell_selection("I")
identities = ds.qc.hto_demultiplexing(cell_selection, random_seed=0)
# Load the calls indexed by barcode, so that no later step relies on row order.
labels = ds.artifacts.load_values(identities).to_pandas()
labels.name = "HTO call"
# Pool the eight tag calls into one singlet class and count the three classes.
class_type = pd.CategoricalDtype(["Singlet", "Doublet", "Negative"])
classes = (
labels.where(labels.isin(["Negative", "Doublet"]), "Singlet")
.astype(class_type)
.rename("Class")
)
class_counts = classes.value_counts(sort=False)
pd.DataFrame({
"Barcodes": class_counts,
"Percent": (100 * class_counts / len(labels)).round(1),
})| Barcodes | Percent | |
|---|---|---|
| Class | ||
| Singlet | 16322 | 75.8 |
| Doublet | 3203 | 14.9 |
| Negative | 1997 | 9.3 |
Started: 2026-11-18T00:16:39.482755Z | Wall time: 2.027 s
The next table splits the singlets by tag and gives each tag’s cutoff in raw counts.
# Count the singlets of each donor tag.
tag_names = ds.HTO.feats.fetch_all("ids").astype(str).tolist()
singlets_per_tag = labels.value_counts().reindex(tag_names)
# Read each tag's cutoff from the artifact, which lists one entry per pool; without sample_column, all barcodes form one pool.
cutoffs = pd.Series(ds.artifacts.load(identities).attrs["samples"][0]["cutoffs"])
pd.DataFrame({
"Singlets": singlets_per_tag,
"Cutoff (raw counts)": cutoffs.reindex(tag_names),
}).rename_axis("Tag")| Singlets | Cutoff (raw counts) | |
|---|---|---|
| Tag | ||
| BatchA | 2193 | 75 |
| BatchB | 2281 | 104 |
| BatchC | 2141 | 93 |
| BatchD | 1944 | 112 |
| BatchE | 1764 | 89 |
| BatchF | 1790 | 146 |
| BatchG | 2007 | 234 |
| BatchH | 2202 | 130 |
Started: 2026-11-18T00:16:41.511739Z | Wall time: 0.015 s
Every donor contributes between 1,764 (BatchE) and 2,281 (BatchB) singlets, as expected for samples pooled in equal proportion Stoeckius et al., 2018. The cutoffs range from 75 counts for BatchA to 234 for BatchG, because each tag has its own background level.
Inspect the tag signal¶
The heatmap shows the mean CLR value of each tag in each group of calls, and the table below it gives the range of those means.
# Compare the mean CLR value of all eight tags across the groups of calls.
identity_order = tag_names + ["Doublet", "Negative"]
heatmap = ds.plots.matrixplot(
features=tag_names,
groups=identities,
group_order=identity_order,
figsize=(9, 4),
show=False,
)
# Name the color scale, the groups and the tags.
heatmap.axes["matrixplot"].images[0].colorbar.set_label("Mean CLR value")
heatmap.axes["matrixplot"].set_xlabel("Assigned tag or class")
heatmap.axes["matrixplot"].set_ylabel("HTO tag")
plt.show()
# Summarize the plotted means: each singlet group's own tag against the other seven, and every tag in the doublets and negatives.
means = heatmap.tables["matrix"]
singlet_means = means.loc[tag_names, tag_names].to_numpy()
own_tag = np.eye(len(tag_names), dtype=bool)
ranges = {
"Singlets, own tag": singlet_means[own_tag],
"Singlets, other tags": singlet_means[~own_tag],
"Doublets, every tag": means["Doublet"].to_numpy(),
"Negatives, every tag": means["Negative"].to_numpy(),
}
pd.DataFrame(
{
"Lowest mean CLR": [values.min() for values in ranges.values()],
"Highest mean CLR": [values.max() for values in ranges.values()],
},
index=list(ranges),
).round(2)
| Lowest mean CLR | Highest mean CLR | |
|---|---|---|
| Singlets, own tag | 2.96 | 4.12 |
| Singlets, other tags | 0.44 | 0.53 |
| Doublets, every tag | 1.22 | 1.55 |
| Negatives, every tag | 0.50 | 0.58 |
Started: 2026-11-18T00:16:41.528401Z | Wall time: 0.399 s
Each singlet group averages 2.96 to 4.12 on its own tag and 0.44 to 0.53 on the other seven, close to the 0.50 to 0.58 that the negatives average on every tag. BatchG separates least: its singlets have the lowest own-tag mean, and its cutoff is the highest. Doublets average 1.22 to 1.55 on every tag, between the two levels.
The violins show the spread behind those means for BatchA and BatchB, one value per barcode.
# Plot each barcode's BatchA and BatchB values in every group of calls.
distributions = ds.plots.distribution(
["BatchA", "BatchB"],
grouping=identities,
groups=identity_order,
max_points=0,
italicize_features=False,
figsize=(10, 5),
show=False,
)
# Name the plotted values and the groups.
for ax in distributions.axes.values():
ax.set_xlabel("Assigned tag or class")
ax.set_ylabel("CLR value")
plt.show()
Started: 2026-11-18T00:16:41.929708Z | Wall time: 0.764 s
In both panels the tag’s own singlets sit far above the other singlet groups and the negatives. Their violin narrows to a thin tail toward the tag’s cutoff, where the other groups end, so few barcodes lie near the cutoff. The doublet violins have two modes: most doublets sit at background on a given tag, and the doublets that include a cell from that donor reach the singlets’ level, which puts the doublet means of the heatmap between the two.
Check the calls against RNA content¶
The demultiplexing reads only the tag counts, so the RNA content of each barcode gives an independent check: a droplet with two cells should hold about twice the RNA of a singlet. The plot shows, for each group of calls, the fraction of barcodes at or below each RNA total, with a dashed line at 5,000 RNA UMIs, and the table compares the classes’ medians and their share of barcodes above that line.
# Plot the cumulative distribution of RNA UMIs in each group of calls.
rna_ecdf = ds.plots.distribution(
"RNA_nCounts",
grouping=identities,
groups=identity_order,
kind="ecdf",
figsize=(8, 4.5),
show=False,
)
# Put the RNA totals on a log axis, mark the 5,000-UMI level that the table below uses, and name the axes.
ax = rna_ecdf.axes["RNA_nCounts"]
ax.set_xscale("log")
ax.axvline(5_000, color="0.4", linestyle="--", linewidth=1)
ax.set_xlabel("RNA UMIs per barcode")
ax.set_ylabel("Fraction of barcodes at or below")
ax.set_title("RNA content of each group of calls")
plt.show()
# Compare the classes' median RNA content and their share of barcodes above 5,000 RNA UMIs.
rna_umis = rna_totals.loc[labels.index]
pd.DataFrame({
"Median RNA UMIs": rna_umis.groupby(classes, observed=True).median().round().astype(int),
"Percent above 5,000 RNA UMIs": (100 * (rna_umis > 5_000).groupby(classes, observed=True).mean()).round(1),
})
| Median RNA UMIs | Percent above 5,000 RNA UMIs | |
|---|---|---|
| Class | ||
| Singlet | 561 | 4.5 |
| Doublet | 1002 | 5.4 |
| Negative | 19184 | 81.9 |
Started: 2026-11-18T00:16:42.696218Z | Wall time: 0.388 s
The eight singlet curves lie close together, so every donor contributes cells with similar RNA content. Doublets hold a median of 1,002 RNA UMIs, nearly twice the singlets’ 561. Negatives hold a median of 19,184 RNA UMIs, and 81.9% of them hold more than 5,000, a level that only 4.5% of singlets reach. Most negatives are therefore the unstained cell lines, as Stoeckius et al. (2018) also found; the authors attribute the remaining, lower-RNA negatives to failed reactions or droplets that hold only ambient RNA.
Hashing cannot see two kinds of multiplet, because each carries a single tag: two cells from the same donor, and a tagged PBMC paired with an untagged cell line. With eight donors in near-equal shares, about one PBMC doublet in eight pairs two cells of the same donor. The 4.5% of singlets above 5,000 RNA UMIs hold the RNA content of a cell line, as the second kind would. RNA quality control and RNA-based doublet scoring are the checks for such droplets.
Adjust the calls to your design¶
The default cutoff lets about one background count in a hundred through, so a singlet can gain a second positive tag by chance and be called a doublet. A stricter positive_quantile turns such false doublets back into singlets but can push weakly tagged singlets into the negatives. The next cell repeats the demultiplexing at 0.999 and follows the barcodes whose class changes, by their RNA content.
# Demultiplex again with a background tail ten times smaller, and pool the tag calls into classes as before.
strict = ds.qc.hto_demultiplexing(cell_selection, random_seed=0, positive_quantile=0.999)
strict_labels = ds.artifacts.load_values(strict).to_pandas()
strict_classes = strict_labels.where(strict_labels.isin(["Negative", "Doublet"]), "Singlet").astype(class_type)
# Count the barcodes of each pair of classes at the two quantiles, with their RNA content.
pairs = [classes.rename("Class at 0.99"), strict_classes.rename("Class at 0.999")]
pd.DataFrame({
"Barcodes": rna_umis.groupby(pairs, observed=True).size(),
"Median RNA UMIs": rna_umis.groupby(pairs, observed=True).median().round().astype(int),
"Percent above 5,000 RNA UMIs": (100 * (rna_umis > 5_000).groupby(pairs, observed=True).mean()).round(1),
})| Barcodes | Median RNA UMIs | Percent above 5,000 RNA UMIs | ||
|---|---|---|---|---|
| Class at 0.99 | Class at 0.999 | |||
| Singlet | Singlet | 16081 | 563 | 4.3 |
| Negative | 241 | 400 | 18.3 | |
| Doublet | Singlet | 262 | 622 | 7.3 |
| Doublet | 2935 | 1037 | 5.1 | |
| Negative | 6 | 492 | 33.3 | |
| Negative | Negative | 1997 | 19184 | 81.9 |
Started: 2026-11-18T00:16:43.086464Z | Wall time: 0.830 s
At 0.999, 262 doublets become singlets and 241 singlets become negatives, so the number of singlets barely changes. The new singlets hold a median of 622 RNA UMIs, close to the 563 of the singlets that stay and well below the 1,037 of the doublets that stay, so most of them are singlets whose second tag crossed the default cutoff by chance. The new negatives hold the lowest median in the table, 400 RNA UMIs, yet 18.3% of them hold more than 5,000, the range of the cell lines, against 4.3% of the singlets that stay, so the stricter cutoff also moves some cell-line barcodes out of the singlets. Try a stricter quantile when the doublet calls exceed the multiplet rate that the cell loading predicts and their second tags sit near background, and compare the classes in this way. Each quantile is saved as its own artifact, so both sets of calls stay in the store; the selection below keeps the default calls that the rest of this page describes.
Pools of cells that used different tags cannot be demultiplexed together: each tag’s background cluster falls in a pool that never used the tag, where its counts are all zero, so CyteArc refuses and names the tag. Pass the cell column of each cell’s pool as sample_column to demultiplex each pool with its own tags. A warning that a tag’s calls overlap its background means that fewer than half of its positive barcodes lie in the one-in-a-million tail of its background fit at the default quantile, as for an unused tag or a failed stain; inspect that tag’s count distribution before keeping its singlets. The API reference lists the other options of ds.qc.hto_demultiplexing, such as hashtags for a subset of tags, and the per-barcode diagnostics that the artifact stores: the two strongest CLR tags, max_id and second_id, and the difference of their values, margin.
Select the singlets¶
ds.select_cells turns the eight tag calls into a new cell selection and deletes no rows, so the negatives and doublets stay in the store. In a store that also holds the RNA counts, pass the selection as cell_selection= to an analysis or as cells= to a pipeline recipe. The RNA recipe can also demultiplex within its own run: with an assay of type HTO in the store, ds.pipeline.rna(hashing=True) keeps the cells of exactly one tag and sets the median absolute deviation (MAD) bounds of the recipe’s quality-control filter within each tag, so that each donor’s cells are filtered against their own distribution. hashing= also takes the keywords of ds.qc.hto_demultiplexing, such as {"positive_quantile": 0.999}.
# Select the barcodes called as one of the eight tags.
singlets = ds.select_cells(identities, include=tag_names)
singlet_mask = np.asarray(ds.artifacts.load(singlets)["values"][:], dtype=bool)
# Compare the selection with the barcodes that stay in the store.
pd.Series({
"Selected singlets": int(singlet_mask.sum()),
"Barcodes retained in the store": ds.cells.N,
}, name="Barcodes")Selected singlets 16322
Barcodes retained in the store 21522
Name: Barcodes, dtype: int64Started: 2026-11-18T00:16:43.919421Z | Wall time: 0.046 s
The selection keeps the 16,322 singlets, and all 21,522 barcodes stay in the store. Quality control and doublet detection covers the next step: filtering cells on their RNA quality metrics and scoring the doublets that hashing cannot see.
- Stoeckius, M., Zheng, S., Houck-Loomis, B., Hao, S., Yeung, B. Z., Mauck, W. M., Smibert, P., & Satija, R. (2018). Cell Hashing with barcoded antibodies enables multiplexing and doublet detection for single cell genomics. Genome Biology, 19(1). 10.1186/s13059-018-1603-1