Integration
A batch effect is a systematic technical difference between groups of cells that biology does not explain. It appears when samples are processed at different times, on different 10x Chromium chips, by different operators or with different chemistries. Cells from two batches can then cluster apart on a UMAP even when they hold the same cell types, because the technical variation is larger than the biological variation between cell types.
This page builds that situation on purpose. PBMC 3k and PBMC 10k both hold blood mononuclear cells, but they differ in more than chemistry. PBMC 3k, published in 2016, used the v1 chemistry, the hg19 genome reference and Cell Ranger 1.1.0. PBMC 10k, published in 2018, used the v3 chemistry, GRCh38 and Cell Ranger 3.0.0. Each comes from its own donor sample. The batch on this page is the sum of these technical and donor differences, and the methods below cannot tell them apart.
Two datasets, one batch each
Section titled “Two datasets, one batch each”The source matrices are 10x Genomics’ PBMC 3k dataset, processed with Cell Ranger 1.1.0 in 2016, and PBMC 10k v3 dataset, processed with Cell Ranger 3.0.0 in 2018. Both provider records state CC BY 4.0. This lesson intersects genes, filters cells within each dataset, and derives the Harmony and scVI comparisons.
import numpy as npimport scanpy as scimport matplotlib.pyplot as plt
sc.settings.verbosity = 3np.random.seed(42)
pbmc3k = sc.read_10x_mtx("/opt/data/pbmc3k", var_names="gene_symbols", make_unique=True)pbmc3k.obs["sample"] = "pbmc3k"
pbmc10k = sc.read_10x_mtx("/opt/data/pbmc10k", var_names="gene_symbols", make_unique=True)pbmc10k.obs["sample"] = "pbmc10k"
# Concatenate the two matrices. join="inner" keeps the genes both# chemistries measured.adata = sc.concat([pbmc3k, pbmc10k], join="inner")adata.layers["counts"] = adata.X.copy()
print(adata)print(adata.obs["sample"].value_counts())AnnData object with n_obs × n_vars = 14469 × 20453 obs: 'sample' layers: None (.X), 'counts'samplepbmc10k 11769pbmc3k 2700Name: count, dtype: int64The inner join keeps the 20,453 genes that both references share. PBMC 10k holds 11,769 cells and PBMC 3k holds 2,700, so the larger dataset dominates every shared step.
Quality control per sample
Section titled “Quality control per sample”The MAD helper below adapts cells 18, 20 and 22 of the archived quality-control notebook. This version computes MAD with pandas and changes the filter combination. The source is copyright 2021 Theislab under Apache 2.0.
# sc-best-practices runs the QC metrics per batch, never on the# aggregated data.adata.var["mt"] = adata.var_names.str.startswith("MT-")sc.pp.calculate_qc_metrics(adata, qc_vars=["mt"], percent_top=None, log1p=False, inplace=True)adata.obs["log1p_total_counts"] = np.log1p(adata.obs["total_counts"])adata.obs["log1p_n_genes_by_counts"] = np.log1p( adata.obs["n_genes_by_counts"])
def is_outlier(adata, metric, nmads): """Flag cells whose metric sits more than nmads MADs from the median.
Args: adata: AnnData object holding the metric in .obs. metric: Column of adata.obs to test. nmads: Number of median absolute deviations for the cutoff.
Returns: Boolean Series, True where the cell is an outlier. """ values = adata.obs[metric] median = values.median() mad = (values - median).abs().median() return (values < median - nmads * mad) | (values > median + nmads * mad)
adata.obs["outlier"] = Falsefor sample in ("pbmc3k", "pbmc10k"): mask = adata.obs["sample"] == sample subset = adata[mask] outliers = ( is_outlier(subset, "log1p_total_counts", 5) | is_outlier(subset, "log1p_n_genes_by_counts", 5) | is_outlier(subset, "pct_counts_mt", 3) ) adata.obs.loc[mask, "outlier"] = outliers.values
print(adata.obs.groupby("sample")["outlier"].value_counts())adata = adata[~adata.obs["outlier"]].copy()sc.pp.filter_genes(adata, min_cells=3)print("after filtering:", adata.shape)sample outlierpbmc10k False 10271 True 1498pbmc3k False 2427 True 273Name: count, dtype: int64after filtering: (12698, 15244)The MAD rule removes 1,498 PBMC 10k cells, 12.7 percent, and 273 PBMC 3k cells, 10.1 percent. PBMC 3k loses one cell more here than on the Quality Control page, because the inner join drops genes and so changes the totals of each cell. 12,698 cells and 15,244 genes remain.
See the batch effect before correcting it
Section titled “See the batch effect before correcting it”sc.pp.normalize_total(adata, target_sum=1e4)sc.pp.log1p(adata)sc.pp.highly_variable_genes(adata, layer="counts", n_top_genes=2000, flavor="seurat_v3")adata.raw = adataadata = adata[:, adata.var["highly_variable"]]sc.pp.scale(adata, max_value=10)sc.tl.pca(adata, n_comps=50, random_state=42)sc.pp.neighbors(adata, n_neighbors=15, n_pcs=30, random_state=42)sc.tl.umap(adata, random_state=42)
def same_batch_neighbor_fraction(adata): """Return the mean fraction of each cell's graph weight on its own batch.
Args: adata: AnnData object with a neighbor graph and a batch column.
Returns: The mean over cells of the same-batch share of graph weights. """ connectivities = adata.obsp["connectivities"].toarray() batches = adata.obs["sample"].to_numpy() same = batches[:, None] == batches[None, :] own = (connectivities * same).sum(axis=1) total = connectivities.sum(axis=1) return float(np.mean(own / total))
share = (adata.obs["sample"] == "pbmc3k").mean()print(f"pbmc3k share of cells: {share:.3f}")print(f"uncorrected same-batch fraction: " f"{same_batch_neighbor_fraction(adata):.3f}")pbmc3k share of cells: 0.191uncorrected same-batch fraction: 0.997The fraction is the share of each cell’s neighbor graph weight that falls on cells of its own dataset, averaged over all cells. If both datasets held the same mix of cell types, a graph that ignored the batch completely would give about 0.69, 0.191 squared plus 0.809 squared. Two donor samples rarely hold identical mixes, and a cell type that is more common in one dataset keeps more of its neighbors there, so even a perfect correction of these data would sit somewhat above 0.69. The uncorrected graph gives 0.997, so the two datasets barely touch.
sc.pl.umap(adata, color="sample", show=False)plt.savefig("outputs/integration_uncorrected.png", dpi=150, bbox_inches="tight")plt.close()
Every PBMC 3k group sits apart from the PBMC 10k groups, although both datasets hold the same blood cell types.
Harmony
Section titled “Harmony”import harmonypy as hm
# Harmony adjusts the PCA embedding so the batches align, keeping the# neighbor graph structure.ho = hm.run_harmony(np.array(adata.obsm["X_pca"]), adata.obs, "sample", max_iter_harmony=20, verbose=False, random_state=42)adata.obsm["X_harmony"] = ho.Z_corr
sc.pp.neighbors(adata, use_rep="X_harmony", n_neighbors=15, random_state=42)sc.tl.umap(adata, random_state=42)print(f"harmony same-batch fraction: " f"{same_batch_neighbor_fraction(adata):.3f}")harmony same-batch fraction: 0.804sc.pl.umap(adata, color="sample", show=False)plt.savefig("outputs/integration_harmony.png", dpi=150, bbox_inches="tight")plt.close()
Harmony brings the fraction from 0.997 down to 0.804. Most PBMC 3k cells now sit inside PBMC 10k groups, but one small group stays separate. 0.804 is above the 0.69 of identical composition, and the fraction alone cannot say how much of that gap is batch left over and how much is a real difference in cell type mix.
import scvi
# scVI learns a latent embedding with a neural network that models the# counts directly and removes the batch effect it is told about. The# training runs on CPU here, so the epoch count stays small, and the# progress bar is off so the run prints its result and nothing else.scvi.settings.seed = 42scvi.model.SCVI.setup_anndata(adata, layer="counts", batch_key="sample")model = scvi.model.SCVI(adata, n_latent=10)model.train(max_epochs=50, enable_progress_bar=False)
adata.obsm["X_scVI"] = model.get_latent_representation()sc.pp.neighbors(adata, use_rep="X_scVI", n_neighbors=15, random_state=42)sc.tl.umap(adata, random_state=42)print(f"scVI same-batch fraction: " f"{same_batch_neighbor_fraction(adata):.3f}")scVI same-batch fraction: 0.875sc.pl.umap(adata, color="sample", show=False)plt.savefig("outputs/integration_scvi.png", dpi=150, bbox_inches="tight")plt.close()
scVI reaches 0.875, so on this measure it mixes the batches less than Harmony. The model trains for only 50 epochs on CPU here, and a band of PBMC 3k cells stays apart in the left group. The fraction measures mixing alone. It cannot tell whether a correction also merged cell types that should stay apart, which is the risk that the last section of this page describes.
Choosing a method
Section titled “Choosing a method”Several tools remove batch effects while they keep the biological signal.
| Method | Language | Approach | Speed |
|---|---|---|---|
| Harmony | R, Python | Iterative soft clustering on PCA embeddings | Fast |
| scVI | Python | Variational autoencoder on raw counts | Moderate |
| Seurat CCA/RPCA | R | Canonical correlation or reciprocal PCA to find anchors | Moderate |
| BBKNN | Python | Batch-balanced k-nearest neighbors graph | Fast |
Harmony is a good default starting point. It is fast and works well for most datasets. scVI suits complex experiments with many batches better but needs more computation.
When integration hides biology
Section titled “When integration hides biology”Integration is necessary to compare cell types across samples or conditions, because without it the batch effect dominates the clustering. It can also do harm. If two batches hold different cell types, integration may force them together. For example, if batch A is healthy tissue and batch B is tumor tissue, aggressive integration can merge tumor-specific populations with their healthy counterparts.
Scientific references
Section titled “Scientific references”Wolf, Angerer, and Theis, 2018 describe Scanpy, the Python toolkit for large-scale single-cell expression analysis.
Korsunsky and colleagues, 2019 describe Harmony, the single-cell integration method that harmonypy implements in Python.
Gayoso and colleagues, 2022 describe scvi-tools for the probabilistic analysis of single-cell omics data.
Further reading
Section titled “Further reading”The Scanpy Harmony integration reference explains correction of a PCA representation before neighbor-graph construction. It identifies the representation that Harmony changes.
The scvi-tools API tutorial explains count-layer registration, batch covariates, training, and latent representations. These steps differ from correction of an existing PCA matrix.