Remove batch effects from a feature matrix, cluster by cluster
Source:R/batch-correction.R
correct_feature_batch.RdRemoves batch shifts from a samples by features matrix before
fit_ebmf(), using Harmony's mixture-of-experts ridge correction. Each
sample is softly assigned to clusters of similar cell state. Within each
cluster, every feature is regressed on batch with a ridge penalty, weighted
by the assignments, and the fitted batch terms are subtracted. Batch shifts
may therefore differ between cell states, which a single per-batch centering
cannot model. The input is not clipped, so signed data such as shifted log
expression stay signed. Nonnegative input can gain negative values, and
zeros in sparse input become nonzero.
Usage
correct_feature_batch(
X,
sample_side,
metadata,
batch_col,
assignments,
protect = NULL,
id_col = "sample",
lambda = NULL,
alpha = 0.2,
batch_prop_cutoff = 1e-05
)Arguments
- X
Named numeric matrix or double sparse Matrix with no missing values, for example shifted log expression. The result is dense.
- sample_side
"rows"or"columns"ofX.- metadata
Data frame with one row per sample, keyed by
id_col. Extra rows are dropped and recorded.- batch_col
Metadata column holding the batch to remove; at least two levels. Factor level order is ignored beyond the order of the penalty columns.
- assignments
Either a samples by clusters matrix of soft assignments, with sample row names and cluster column names, nonnegative and each row summing to one within 1e-5 (as from
harmony_assignments()); or the name of a metadata column of hard cluster labels, such as cell types.- protect
Optional one-sided formula of metadata covariates to keep, such as
~ condition. They enter each cluster's regression without penalty and are not subtracted. A covariate fully determined by batch within a cluster (for example a condition applied to whole batches) keeps the batch shift aligned with it; the function warns in that case.- id_col
Metadata column holding sample IDs.
- lambda
Ridge penalty on the batch terms.
NULL(default) uses Harmony's automatic penalty,alphatimes the expected number of samples of each batch in each cluster. A positive number applies one penalty everywhere. A clusters by batches matrix, named likeassignmentscolumns and the batch levels, gives each its own penalty.- alpha
Positive scale of the automatic penalty (Harmony default 0.2). Used only when
lambdaisNULL. The ridge leaves part of each batch shift in place: aboutalpha * E / (O + alpha * E), whereOis the batch's weighted sample count in the cluster andEits expected count. In one test with a planted shift of 2 the default left a gap of 0.33. Batches with fewer samples than expected in a cluster are corrected less. Use a smalllambdasuch as 1e-6 for near-complete removal.- batch_prop_cutoff
A batch is corrected within a cluster only when its mean assignment to that cluster exceeds this value (Harmony default 1e-5). A cluster with fewer than two such batches is left unchanged.
Value
The corrected matrix, with the same orientation and IDs as X. Its
analysis_metadata attribute records the batch levels, the penalty matrix
used, skipped clusters, protected columns, dropped metadata rows and
SHA-256 hashes of the input and assignments.
Details
For cluster \(k\) with assignment weights \(r\), design
\(\Phi\) (intercept, protected covariates, batch indicators) and penalty
\(\Lambda_k\) (zero for the intercept and protected columns), the
coefficients are \(W_k = (\Phi^T \mathrm{diag}(r) \Phi + \Lambda_k)^{-1}
\Phi^T \mathrm{diag}(r) X\), always computed from the uncorrected X. The
batch rows of \(\mathrm{diag}(r) \Phi W_k\) are subtracted, and the
corrections add up over clusters. Without protect this reproduces
Harmony's own correction of its input embedding.
Batch here should be technical. If batch_col holds donors, and donors
are nested in a condition, the condition's effect within each cell state
is removed too unless protect names it. A protected covariate that is
constant within a cluster's corrected samples is an error.
The assignments are learned from the same data, so the correction is part
of the fit. For factor_stability() or factor_holdout(), run it inside
the fit_fn callback on each resample; correcting once beforehand
overstates stability. Memory: the result is a dense n by p double matrix,
and sample_side = "columns" holds one transposed copy as well.
The automatic penalty (alpha) and batch_prop_cutoff come from the Harmony
2.x software, not from the 2019 paper.
References
Korsunsky I, Millard N, Fan J, et al. (2019). Fast, sensitive and accurate integration of single-cell data with Harmony. Nature Methods 16, 1289-1296. doi:10.1038/s41592-019-0619-0
Kotliar D, Veres A, Nagy MA, et al. (2019). Identifying gene expression programs of cell-type identity and cellular activity with single-cell RNA-Seq. eLife 8, e43803. doi:10.7554/eLife.43803
See also
harmony_assignments() for soft assignments from an embedding.
Author
Mikhael Manurung (R implementation). Harmony algorithm: Ilya Korsunsky, Soumya Raychaudhuri and coauthors; gene-matrix adaptation: Dylan Kotliar (cNMF). No upstream code is copied.
Examples
set.seed(1)
state <- rep(c("alpha", "beta"), each = 20)
batch <- rep(c("b1", "b2"), times = 20)
X <- matrix(rnorm(40 * 6), 40, 6) + outer(batch == "b2" & state == "beta", rep(2, 6))
dimnames(X) <- list(paste0("s", 1:40), paste0("g", 1:6))
metadata <- data.frame(sample = rownames(X), batch = batch, state = state)
corrected <- correct_feature_batch(X, "rows", metadata, "batch", assignments = "state")
# batch b2 minus b1 within the beta state, before and after
beta <- state == "beta"
colMeans(X[beta & batch == "b2", ]) - colMeans(X[beta & batch == "b1", ])
#> g1 g2 g3 g4 g5 g6
#> 1.576167 2.171468 2.291981 2.319806 1.617298 2.019604
colMeans(corrected[beta & batch == "b2", ]) - colMeans(corrected[beta & batch == "b1", ])
#> g1 g2 g3 g4 g5 g6
#> 0.2626945 0.3619113 0.3819968 0.3866343 0.2695497 0.3366006