Algorithm Search⌘K

Algorithmcore

ComBat

Also called empirical Bayes batch correction.

Remove batch effects by fitting location and scale shifts per gene and batch, shrunk across genes by empirical Bayes.

Time
O(G (N p^2 + p^3) + G N T) worst
Space
O(G N) extra
Where
G = the number of genes; N = the number of samples; T = the number of iterations; p = the number of design columns
Properties
deterministicnot exactofflineiterative
Origin
W. Evan Johnson, Cheng Li, Ariel Rabinovic, 2007

ComBat removes batch effects from gene expression data: differences between groups of samples that come from processing them on different days, plates or machines. It models each gene in each batch with a shift of the mean and a change of scale, standardizes the data, and estimates the shifts and scales with empirical Bayes: the estimates of all genes in one batch give a prior, and each gene's estimate is pulled toward it. Then it removes the shifts and scales. Johnson, Li and Rabinovic (2007) built it for microarrays with small batches, where the plain estimates for each gene are too noisy. It solves the batch effect correction problem when the batches hold the same kinds of samples or when the biological differences are given as covariates.

In plain words

Each batch can make a gene read a bit high or a bit low, and a bit more or less spread out. With many samples per batch you could measure this for each gene and undo it. With three samples per batch, each such measurement is noisy. ComBat looks at all genes of a batch together: if most genes read about 1.4 units high in batch A, a gene that seems to read 1.8 units high probably reads less high than that. So it moves each gene's estimate part of the way toward the typical value of its batch, more when the batch is small or noisy. Then it subtracts the estimated shift and divides by the estimated spread. You must tell it which differences are biology, or it removes them too.

The problem

Input. A matrix YgjY_{gj} of expression values, such as log counts, for GG genes and NN samples, a batch label for each sample, with at least two samples per batch, and optional covariates xjx_j to keep.

Output. An adjusted matrix Y∗Y^\ast of the same shape.

Model. For sample jj in batch ii, Ygj=αg+xjβg+γig+δigεgjY_{gj} = \alpha_g + x_j\beta_g + \gamma_{ig} + \delta_{ig}\varepsilon_{gj}, where εgj\varepsilon_{gj} has mean 0 and variance σg2\sigma_g^2. The batch shifts γig\gamma_{ig} and scales δig\delta_{ig} are the effects to remove.

The algorithm

  1. COMBAT(Y, batch, x)
  2. 1for each gene g: fit Y[g] by least squares on batch indicators and x; α_g ← the size-weighted mean of the batch coefficients
  3. 2σ²_g ← the mean squared residual of gene g
  4. 3Z[g][j] ← (Y[g][j] - α_g - x_j β_g) / σ_g
  5. 4γ̂_ig, δ̂²_ig ← the mean and the sample variance of Z[g][j] over the samples j of batch i
  6. 5γ̄_i, τ²_i ← the mean and the sample variance of γ̂_ig over the genes
  7. 6D, S² ← the mean and the sample variance of δ̂²_ig over the genes; λ_i ← (D² + 2S²) / S²; θ_i ← (D³ + D S²) / S²
  8. 7repeat: γ*_ig ← (n_i τ²_i γ̂_ig + δ*²_ig γ̄_i) / (n_i τ²_i + δ*²_ig)
  9. 8δ*²_ig ← (θ_i + ½ Σ_j (Z[g][j] - γ*_ig)²) / (n_i/2 + λ_i - 1)
  10. 9until the relative change of γ* and δ*² is below 10^-4 ▷ start from δ*² = δ̂²
  11. 10Y*[g][j] ← σ_g / δ*_ig · (Z[g][j] - γ*_ig) + α_g + x_j β_g

Lines L1 to L3 put all genes on one scale. The fit uses one coefficient per batch, so after line L3 the mean of batch ii is the batch shift in units of σg\sigma_g. Line L4 gives the plain estimates of the shift and the scale of each gene and batch. Lines L5 and L6 fit the priors γig∼N(γˉi,τi2)\gamma_{ig} \sim N(\bar\gamma_i, \tau_i^2) and δig2∼InvGamma(λi,θi)\delta^2_{ig} \sim \text{InvGamma}(\lambda_i, \theta_i) by the method of moments, over all genes of batch ii. Line L7 is the posterior mean of the shift for a given scale, and line L8 the posterior mean of the scale for a given shift; both priors are conjugate. Lines L7 to L9 alternate the two until they agree. Line L10 removes the shrunk shift and scale and puts the gene back on its own scale.

Without lines L5 to L9, with γ∗=γ^\gamma^\ast = \hat\gamma and δ∗=δ^\delta^\ast = \hat\delta, this is the plain location and scale adjustment.

Example

Four genes in two batches of three samples:

gene A1 A2 A3 B1 B2 B3
1 1 2 3 4 5 6
2 2 4 6 5 6 7
3 3 3 4 7 9 11
4 5 6 7 6 8 10

For gene 1 the batch means are 2 and 5, so α1=3.5\alpha_1 = 3.5, the residuals are −1,0,1-1, 0, 1 in each batch, and σ12=4/6=2/3\sigma_1^2 = 4/6 = 2/3. Then Z=(Y−3.5)/0.8165Z = (Y - 3.5)/0.8165, and batch A has γ^A1=−1.837\hat\gamma_{A1} = -1.837 and δ^A12=1.5\hat\delta^2_{A1} = 1.5. Over the four genes, batch A has shifts −1.837,−0.775,−2.357,−0.775-1.837, -0.775, -2.357, -0.775 and scales 1.5,2.4,0.231,0.61.5, 2.4, 0.231, 0.6. So γˉA=−1.436\bar\gamma_A = -1.436, τA2=0.628\tau_A^2 = 0.628, λA=3.484\lambda_A = 3.484 and θA=2.938\theta_A = 2.938; the prior mean of the scale is θA/(λA−1)=1.183\theta_A/(\lambda_A - 1) = 1.183, the mean of the four scales. The iteration moves gene 1 to γA1∗=−1.687\gamma^\ast_{A1} = -1.687 and δA1∗2=1.122\delta^{\ast2}_{A1} = 1.122, toward the prior.

gene 1 A1 A2 A3 B1 B2 B3
location and scale only 2.684 3.5 4.316 2.684 3.5 4.316
ComBat 2.441 3.385 4.329 2.834 3.619 4.404

Without shrinkage the two batches of gene 1 become the same. With shrinkage a small gap is left, because gene 1 has a larger shift than the typical gene and ComBat treats part of that as noise. With three samples per batch this is usually the better bet: in the tests, with 300 genes and batches of 3, the ComBat output was closer to the batch free data than the plain location and scale output (mean squared error 0.090 against 0.143, and 0.248 before correction). That is a measurement on data drawn from the model, not a theorem.

Correctness

The proof shows four things. Without shrinkage, the adjusted data of every gene have the same mean and sample variance in every batch. Line L7 is the posterior mean of the shift under a normal prior when the scale is known, and line L8 is the posterior mean of the scale under an inverse gamma prior when the shift is known. Line L6 is the only inverse gamma with the mean and variance of the plain scales. And the iteration converges, because the scale sequence is monotone and bounded. The answer is a fixed point of the two conditional means, not the joint posterior mean. Whether real batch effects follow the model is an assumption.

Proof: ComBat computes conditional posterior means under moment-fitted priors, its iteration converges, and without shrinkage it equalizes the batches exactlyfull

We prove what each step of ComBat computes. Without shrinkage, the adjusted data of every gene have the same mean and the same sample variance in every batch (Theorem 2). With shrinkage, line L7 is the posterior mean of the batch shift for a fixed scale (Lemma 3), line L8 is the posterior mean of the scale for a fixed shift (Lemma 4), line L6 fits the inverse gamma prior by the method of moments (Lemma 5), and the iteration of lines L7 to L9 converges to a point where both equations hold (Theorem 6). That the batch effects in real data follow the model, and that removing them keeps the biology, are assumptions; the tests measure them on simulated data. There is no theorem that the empirical Bayes estimates have lower error than the plain estimates for every parameter value, as there is for the James-Stein estimator.

Setting. Data YgjY_{gj} for genes g=1,…,Gg = 1, \dots, G and samples j=1,…,Nj = 1, \dots, N. Sample jj is in batch b(j)b(j), batch ii has ni≥2n_i \ge 2 samples, and xjx_j is a row of covariates. Line L1 fits, for each gene, Ygj≈cg,b(j)+xjβgY_{gj} \approx c_{g,b(j)} + x_j\beta_g by least squares, where cgic_{gi} is a coefficient for each batch, and sets αg=∑inicgi/N\alpha_g = \sum_i n_ic_{gi}/N. Let μgj=αg+xjβg\mu_{gj} = \alpha_g + x_j\beta_g and let rgjr_{gj} be the residuals of the fit. Line L2 sets σg2=1N∑jrgj2\sigma_g^2 = \frac1N\sum_j r_{gj}^2, and line L3 sets Zgj=(Ygj−μgj)/σgZ_{gj} = (Y_{gj} - \mu_{gj})/\sigma_g. Line L4 sets γ^ig\hat\gamma_{ig} and δ^ig2\hat\delta^2_{ig} to the mean and the sample variance (divisor ni−1n_i - 1) of ZgjZ_{gj} over the samples of batch ii. Line L10 returns

Ygj∗=σgδig∗(Zgj−γig∗)+μgj,i=b(j).Y^\ast_{gj} = \frac{\sigma_g}{\delta^\ast_{ig}}\big(Z_{gj} - \gamma^\ast_{ig}\big) + \mu_{gj}, \qquad i = b(j).

Lemma 1 (the standardized data). For each gene and batch, Zgj−γ^ig=rgj/σgZ_{gj} - \hat\gamma_{ig} = r_{gj}/\sigma_g for the samples of batch ii, and γ^ig=(cgi−αg)/σg\hat\gamma_{ig} = (c_{gi} - \alpha_g)/\sigma_g.

Proof. The design has an indicator column for each batch, so the normal equations make the residuals of each batch sum to 0. In batch ii, Ygj−μgj=(cgi−αg)+rgjY_{gj} - \mu_{gj} = (c_{gi} - \alpha_g) + r_{gj}, so the batch mean of ZgjZ_{gj} is (cgi−αg)/σg(c_{gi} - \alpha_g)/\sigma_g, and subtracting it leaves rgj/σgr_{gj}/\sigma_g. □\square

So γ^ig\hat\gamma_{ig} is the shift of batch ii in units of σg\sigma_g, and δ^ig2\hat\delta^2_{ig} is the variance of the residuals of batch ii in units of σg2\sigma_g^2. The covariates are fitted together with the batches, so a covariate effect is not counted as a batch effect, as long as the covariates are not collinear with the batches.

Theorem 2 (location and scale without shrinkage). With γ∗=γ^\gamma^\ast = \hat\gamma and δ∗=δ^\delta^\ast = \hat\delta, for every gene gg and batch ii, the values Ygj∗−μgjY^\ast_{gj} - \mu_{gj} over the samples of batch ii have mean 0 and sample variance σg2\sigma_g^2.

Proof. Ygj∗−μgj=σg(Zgj−γ^ig)/δ^igY^\ast_{gj} - \mu_{gj} = \sigma_g(Z_{gj} - \hat\gamma_{ig})/\hat\delta_{ig}. Over batch ii, the mean of Zgj−γ^igZ_{gj} - \hat\gamma_{ig} is 0 and its sample variance is δ^ig2\hat\delta^2_{ig}, so the mean is 0 and the sample variance is σg2δ^ig2/δ^ig2\sigma_g^2\hat\delta^2_{ig}/\hat\delta^2_{ig}. □\square

Lemma 3 (line L7). Let Z1,…,ZnZ_1, \dots, Z_n be independent N(γ,δ2)N(\gamma, \delta^2) given γ\gamma, with δ2\delta^2 known, and let γ∼N(γˉ,τ2)\gamma \sim N(\bar\gamma, \tau^2). Then the posterior mean of γ\gamma is

γ∗=nτ2γ^+δ2γˉnτ2+δ2,γ^=1n∑jZj.\gamma^\ast = \frac{n\tau^2\hat\gamma + \delta^2\bar\gamma}{n\tau^2 + \delta^2}, \qquad \hat\gamma = \tfrac1n\textstyle\sum_j Z_j.

Proof. The log of the posterior density is, up to a constant, −(γ−γˉ)2/2τ2−∑j(Zj−γ)2/2δ2-(\gamma - \bar\gamma)^2/2\tau^2 - \sum_j(Z_j - \gamma)^2/2\delta^2. This is a quadratic in γ\gamma with leading coefficient −12(1/τ2+n/δ2)-\frac12(1/\tau^2 + n/\delta^2) and linear coefficient γˉ/τ2+nγ^/δ2\bar\gamma/\tau^2 + n\hat\gamma/\delta^2, so the posterior is normal with mean (γˉ/τ2+nγ^/δ2)/(1/τ2+n/δ2)(\bar\gamma/\tau^2 + n\hat\gamma/\delta^2)/(1/\tau^2 + n/\delta^2). Multiply the numerator and the denominator by τ2δ2\tau^2\delta^2. □\square

The estimate moves γ^\hat\gamma toward γˉ\bar\gamma by the factor δ2/(nτ2+δ2)\delta^2/(n\tau^2 + \delta^2), which is large when the batch is small or noisy and small when the genes disagree a lot about the shift (τ2\tau^2 large).

Lemma 4 (line L8). Let Z1,…,ZnZ_1, \dots, Z_n be independent N(γ,δ2)N(\gamma, \delta^2) given δ2\delta^2, with γ\gamma known, and let δ2\delta^2 have the inverse gamma density proportional to (δ2)−λ−1e−θ/δ2(\delta^2)^{-\lambda - 1}e^{-\theta/\delta^2}. Then the posterior is inverse gamma with shape λ+n/2\lambda + n/2 and scale θ+12∑j(Zj−γ)2\theta + \frac12\sum_j(Z_j - \gamma)^2, and its mean is

δ∗2=θ+12∑j(Zj−γ)2n/2+λ−1.\delta^{\ast2} = \frac{\theta + \frac12\sum_j(Z_j - \gamma)^2}{n/2 + \lambda - 1}.

Proof. The likelihood is proportional to (δ2)−n/2e−∑j(Zj−γ)2/2δ2(\delta^2)^{-n/2}e^{-\sum_j(Z_j - \gamma)^2/2\delta^2}. Multiplying by the prior gives the stated shape and scale. An inverse gamma with shape a>1a > 1 and scale bb has mean b/(a−1)b/(a - 1). Here a=λ+n/2>1a = \lambda + n/2 > 1 because λ>2\lambda > 2 by Lemma 5. □\square

Lemma 5 (line L6). Let DD and S2>0S^2 > 0 be the mean and the sample variance of the values δ^ig2\hat\delta^2_{ig} over the genes. Then λ=(D2+2S2)/S2\lambda = (D^2 + 2S^2)/S^2 and θ=(D3+DS2)/S2\theta = (D^3 + DS^2)/S^2 are the only parameters with λ>2\lambda > 2 for which the inverse gamma has mean DD and variance S2S^2, and λ>2\lambda > 2, θ>0\theta > 0.

Proof. For λ>2\lambda > 2 the inverse gamma has mean θ/(λ−1)\theta/(\lambda - 1) and variance θ2/((λ−1)2(λ−2))\theta^2/((\lambda - 1)^2(\lambda - 2)). Setting the mean to DD gives θ=D(λ−1)\theta = D(\lambda - 1), and then the variance is D2/(λ−2)=S2D^2/(\lambda - 2) = S^2, so λ=2+D2/S2\lambda = 2 + D^2/S^2 and θ=D(1+D2/S2)\theta = D(1 + D^2/S^2), which are the formulas. D>0D > 0 and S2>0S^2 > 0 give λ>2\lambda > 2 and θ>0\theta > 0. □\square

In the same way line L5 sets the normal prior to the mean and the sample variance of the γ^ig\hat\gamma_{ig} over the genes. These are method of moments fits, so the prior is estimated from all genes at once, which is what makes the method empirical Bayes.

Theorem 6 (the iteration). For one gene and batch, let d0=δ^2d_0 = \hat\delta^2, and for t≥0t \ge 0 let gt+1=c(dt)g_{t+1} = c(d_t) and dt+1=h(dt)d_{t+1} = h(d_t), where c(x)=(nτ2γ^+xγˉ)/(nτ2+x)c(x) = (n\tau^2\hat\gamma + x\bar\gamma)/(n\tau^2 + x) and h(x)=(θ+12∑j(Zj−c(x))2)/(n/2+λ−1)h(x) = (\theta + \frac12\sum_j(Z_j - c(x))^2)/(n/2 + \lambda - 1). This is lines L7 and L8. The sequence dtd_t is monotone and converges to a limit d∗>0d^\ast > 0 with h(d∗)=d∗h(d^\ast) = d^\ast, and gtg_t converges to c(d∗)c(d^\ast). Every gtg_t lies between γ^\hat\gamma and γˉ\bar\gamma.

Proof. For x>0x > 0, γ^−c(x)=x(γ^−γˉ)/(nτ2+x)\hat\gamma - c(x) = x(\hat\gamma - \bar\gamma)/(n\tau^2 + x), so c(x)c(x) lies between γ^\hat\gamma and γˉ\bar\gamma, and ∣γ^−c(x)∣|\hat\gamma - c(x)| does not decrease as xx grows and is at most ∣γ^−γˉ∣|\hat\gamma - \bar\gamma|. Since γ^\hat\gamma is the mean of the ZjZ_j, ∑j(Zj−c)2=∑j(Zj−γ^)2+n(γ^−c)2\sum_j(Z_j - c)^2 = \sum_j(Z_j - \hat\gamma)^2 + n(\hat\gamma - c)^2. So hh is continuous and non-decreasing on (0,∞)(0, \infty), and its values lie in a bounded interval [h0,h1][h_0, h_1] with h0≥θ/(n/2+λ−1)>0h_0 \ge \theta/(n/2 + \lambda - 1) > 0. If d1≥d0d_1 \ge d_0, then d2=h(d1)≥h(d0)=d1d_2 = h(d_1) \ge h(d_0) = d_1, and by induction the sequence does not decrease; if d1≤d0d_1 \le d_0 it does not increase. A monotone bounded sequence converges, and its limit d∗≥h0>0d^\ast \ge h_0 > 0. By continuity, d∗=lim⁡h(dt)=h(d∗)d^\ast = \lim h(d_t) = h(d^\ast), and gt=c(dt−1)→c(d∗)g_t = c(d_{t-1}) \to c(d^\ast). □\square

The code stops when the relative change of both values is below 10−410^{-4}, as the sva package does, which happens after finitely many steps because both sequences converge. The fixed point is the pair of the two conditional posterior means of Lemmas 3 and 4. It is in general not the mean of the joint posterior of (γ,δ2)(\gamma, \delta^2); it is the estimate that Johnson, Li and Rabinovic define. The proof does not show that hh has only one fixed point.

What the lines compute. Lines L1 to L3 are Lemma 1, line L4 the batch estimates, lines L5 and L6 the priors of Lemma 5, lines L7 to L9 Theorem 6, and line L10 the adjustment, which is Theorem 2 when the shrinkage is off. A gene with Ygj+aY_{gj} + a in place of YgjY_{gj} gets μgj+a\mu_{gj} + a and the same ZZ, so its output moves by aa. If all data are multiplied by s>0s > 0, then ZZ and the priors do not change and the output is multiplied by ss.

Complexity. With pp columns in the design, the least squares fit of one gene takes O(Np2+p3)O(Np^2 + p^3) time, so lines L1 to L3 take O(G(Np2+p3))O(G(Np^2 + p^3)). Lines L4 to L6 take O(GN)O(GN). Each step of the iteration takes O(ni)O(n_i) time for one gene and batch, so TT steps take O(GNT)O(GNT) in all. The number of steps TT is finite by Theorem 6 but has no proved bound. The space is O(GN)O(GN).

What the tests check. The test file checks the page example. It checks Theorem 2 with and without a covariate, Lemma 5 against the inverse gamma moments, Theorem 6 (the fixed point equations, the monotone sequence and the position of γ∗\gamma^\ast) on random inputs, and Lemma 3 against numerical integration. It checks the shift and scale rules above. Two simulations are measurements, not theorems: with batches of 3 samples the empirical Bayes output is closer to the batch free data than the location and scale output; and with a biological group that is unbalanced across batches, leaving out the covariate removes much of the group difference.

Complexity

The least squares fit takes O(Np2+p3)O(Np^2 + p^3) time per gene for pp design columns, so O(G(Np2+p3))O(G(Np^2 + p^3)) in all. The priors take O(GN)O(GN). Each step of the iteration takes O(GN)O(GN) for all genes and batches, so TT steps take O(GNT)O(GNT). The proof shows that the iteration stops but gives no bound on TT. The space is O(GN)O(GN) for the standardized data.

Properties

  • Shrinkage across genes, like the James-Stein estimator. James-Stein shrinks all means by one common factor and has a theorem: for three or more normal means, it has lower total squared error than the sample means for every parameter value. ComBat shrinks each gene by its own factor δ2/(nτ2+δ2)\delta^2/(n\tau^2 + \delta^2), uses fitted priors for the shift and for the scale, and has no such theorem.
  • Empirical Bayes, by moments. The prior comes from the data of all genes, as in empirical Bayes, but by matching moments, not by maximizing the marginal likelihood.
  • Equivariant. Adding a constant to a gene adds it to the output, and scaling all data scales the output.
  • One batch at a time. The priors of each batch are separate.
  • Not a mixed model. A linear mixed model would treat the batch as a random effect in the analysis itself. ComBat cleans the data first and leaves the analysis to other tools.

Variants and improvements

  • Non-parametric prior. The paper also gives a version with the prior as the empirical distribution of the other genes' estimates, which is slower.
  • Mean only. Adjust only the shift, for batches whose spread is the same.
  • Reference batch. Leave one batch unchanged and move the others onto it.
  • Counts. ComBat-seq applies the same idea to RNA-seq counts with a negative binomial model.
  • Single cells. ComBat assumes that each batch holds the same mix of cell types. Methods such as MNN correction match cells across batches instead.

When to use it

Use it on bulk expression data with known batches, especially with small batches, and give the biological groups as covariates. It also works on log normalized single-cell data when every batch holds about the same cell types. When the batches hold different mixes of cell types, or for direct differential expression testing, it is better to put the batch in the model of the test, or to use a single-cell method.

Pitfalls

  • Confounded design. If the batch and a biological group are the same samples, no method can separate them, and ComBat removes the biology.
  • Leaving out covariates. In the tests, a group with an effect of 2, unbalanced across two batches, kept a difference of 1.92 with the covariate and only 1.03 without it.
  • Using the corrected data for tests. The correction uses the data, so tests on the corrected data are too confident, more so with an unbalanced design.
  • Batches with one sample have no variance and cannot be corrected.
  • Genes with no variance in a batch break the scale estimate; filter them first.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

combat.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/combat/. The authors are listed in prov/PBAHAY.jsonl.
"""ComBat batch correction with parametric empirical Bayes priors (Johnson, Li and Rabinovic 2007).

data[g][j] is the expression of gene g in sample j (for example log counts),
batch[j] is the batch of sample j, and covariates[j] is an optional list of
biological covariates of sample j that the correction must keep.

The model of the paper is Y_ijg = alpha_g + x_j beta_g + gamma_ig + delta_ig e_ijg
for sample j of batch i, with e_ijg of mean 0 and variance sigma_g^2. The steps
follow the R function ComBat of the sva package:

1. Least squares fit on the design [batch indicators | covariates]; alpha_g is
   the mean of the batch coefficients weighted by the batch sizes, and
   sigma_g^2 is the mean squared residual (divisor N).
2. Standardize: Z = (Y - alpha_g - x_j beta_g) / sigma_g.
3. gamma_hat_ig is the mean and delta_hat_ig^2 the variance (divisor n_i - 1)
   of Z over batch i.
4. Priors by the method of moments: gamma_ig ~ N(gamma_bar_i, tau_i^2) and
   delta_ig^2 ~ InvGamma(lambda_i, theta_i), from the values over all genes.
5. Iterate the two conditional posterior means until the relative change is
   below conv.
6. Y* = sigma_g / delta*_ig (Z - gamma*_ig) + alpha_g + x_j beta_g.

Left out: the non-parametric prior, the mean-only option, the reference batch
option and the handling of genes with zero variance inside a batch.
"""

from __future__ import annotations

from typing import Dict, List, Optional, Sequence, Tuple

from rq3lin import solve

Matrix = List[List[float]]


def mean(v: Sequence[float]) -> float:
    return sum(v) / len(v)


def var(v: Sequence[float]) -> float:
    """Sample variance with divisor len(v) - 1."""
    m = mean(v)
    return sum((x - m) ** 2 for x in v) / (len(v) - 1)


def design_matrix(batch: Sequence, covariates: Optional[Sequence[Sequence[float]]]) -> Tuple[Matrix, List]:
    levels = sorted(set(batch), key=lambda b: list(batch).index(b))
    rows = []
    for j, b in enumerate(batch):
        row = [1.0 if b == lv else 0.0 for lv in levels]
        if covariates is not None:
            row += [float(c) for c in covariates[j]]
        rows.append(row)
    return rows, levels


def least_squares(X: Matrix, y: Sequence[float]) -> List[float]:
    p = len(X[0])
    XtX = [[sum(r[a] * r[b] for r in X) for b in range(p)] for a in range(p)]
    Xty = [sum(r[a] * v for r, v in zip(X, y)) for a in range(p)]
    return solve(XtX, Xty)


def standardize(data: Sequence[Sequence[float]], batch: Sequence,
                covariates: Optional[Sequence[Sequence[float]]] = None):
    """(Z, stand_mean, sigma, levels): the standardized data and what is needed to undo it."""
    X, levels = design_matrix(batch, covariates)
    N, nb = len(batch), len(levels)
    sizes = [sum(1 for b in batch if b == lv) for lv in levels]
    Z, stand, sigma = [], [], []
    for y in data:
        coef = least_squares(X, y)  # @line L1
        alpha = sum(sizes[i] * coef[i] for i in range(nb)) / N
        cov_part = [sum(r[nb + a] * coef[nb + a] for a in range(len(coef) - nb)) for r in X]
        fit = [sum(r[a] * coef[a] for a in range(len(coef))) for r in X]
        s2 = sum((v - f) ** 2 for v, f in zip(y, fit)) / N  # @line L2
        if s2 <= 0:
            raise ValueError("a gene has no residual variance")
        s = s2 ** 0.5
        sm = [alpha + c for c in cov_part]
        Z.append([(v - m) / s for v, m in zip(y, sm)])  # @line L3
        stand.append(sm)
        sigma.append(s)
    return Z, stand, sigma, levels


def inverse_gamma_moments(d: Sequence[float]) -> Tuple[float, float]:
    """(lambda, theta) of the inverse gamma with the mean and variance of d."""
    D, S2 = mean(d), var(d)
    if S2 <= 0:
        raise ValueError("the batch variances do not vary over genes")
    return (D * D + 2 * S2) / S2, (D ** 3 + D * S2) / S2  # @line L6


def posterior(z: Sequence[float], g_hat: float, d_hat: float, g_bar: float, t2: float,
              lam: float, theta: float, conv: float = 1e-4, max_iter: int = 1000,
              history: Optional[list] = None) -> Tuple[float, float]:
    """The fixed point (gamma*, delta*^2) of the two conditional posterior means, for one gene and batch."""
    n = len(z)
    g_old, d_old = g_hat, d_hat
    for _ in range(max_iter):
        g_new = (t2 * n * g_hat + d_old * g_bar) / (t2 * n + d_old)  # @line L7
        ss = sum((x - g_new) ** 2 for x in z)
        d_new = (theta + 0.5 * ss) / (n / 2.0 + lam - 1.0)  # @line L8
        if history is not None:
            history.append((g_new, d_new))
        change = max(abs(g_new - g_old) / abs(g_old) if g_old != 0 else abs(g_new - g_old),
                     abs(d_new - d_old) / d_old)
        g_old, d_old = g_new, d_new
        if change < conv:  # @line L9
            break
    return g_old, d_old


def combat(data: Sequence[Sequence[float]], batch: Sequence,
           covariates: Optional[Sequence[Sequence[float]]] = None,
           shrink: bool = True, conv: float = 1e-4) -> Matrix:
    """The batch corrected data, genes by samples. With shrink=False the batch estimates are used as they are."""
    G = len(data)
    if G < 2:
        raise ValueError("ComBat needs at least two genes to estimate the priors")
    Z, stand, sigma, levels = standardize(data, batch, covariates)
    cols: Dict = {lv: [j for j, b in enumerate(batch) if b == lv] for lv in levels}
    if any(len(c) < 2 for c in cols.values()):
        raise ValueError("every batch needs at least two samples")
    out = [[0.0] * len(batch) for _ in range(G)]
    for lv in levels:
        idx = cols[lv]
        zs = [[Z[g][j] for j in idx] for g in range(G)]
        g_hat = [mean(z) for z in zs]  # @line L4
        d_hat = [var(z) for z in zs]
        if shrink:
            g_bar, t2 = mean(g_hat), var(g_hat)  # @line L5
            lam, theta = inverse_gamma_moments(d_hat)
            est = [posterior(zs[g], g_hat[g], d_hat[g], g_bar, t2, lam, theta, conv) for g in range(G)]
        else:
            est = list(zip(g_hat, d_hat))
        for g in range(G):
            gs, ds = est[g]
            for j in idx:
                out[g][j] = sigma[g] / ds ** 0.5 * (Z[g][j] - gs) + stand[g][j]  # @line L10
    return out
rq3lin.py 203 lines
# SPDX-License-Identifier: MIT
# Group module of the single-cell pages of https://algorithm.tamnd.com/ (group rq3). The authors are listed in prov/.
"""Small dense linear algebra and neighbor search for the single-cell pages.

The reference copy is in biology/transcriptomics/doublet-detection/impl/python/.
The other rq3 pages hold identical copies. The module holds no algorithm of a
page: no doublet score, no clustering, no batch correction and no pseudotime.

Conventions:
- A vector is a list of floats and a matrix is a list of rows.
- Ties between equal distances are broken by the smaller index, so that every
  result is deterministic.
- Random draws use a random.Random object that the caller passes in.
"""

from __future__ import annotations

import math
import random
from typing import List, Optional, Sequence, Tuple

Vector = List[float]
Matrix = List[List[float]]


def dot(a: Sequence[float], b: Sequence[float]) -> float:
    return sum(x * y for x, y in zip(a, b))


def sqdist(a: Sequence[float], b: Sequence[float]) -> float:
    return sum((x - y) * (x - y) for x, y in zip(a, b))


def transpose(A: Sequence[Sequence[float]]) -> Matrix:
    return [list(col) for col in zip(*A)]


def matmul(A: Sequence[Sequence[float]], B: Sequence[Sequence[float]]) -> Matrix:
    Bt = transpose(B)
    return [[dot(row, col) for col in Bt] for row in A]


def matvec(A: Sequence[Sequence[float]], x: Sequence[float]) -> Vector:
    return [dot(row, x) for row in A]


def identity(n: int) -> Matrix:
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def column_means(X: Sequence[Sequence[float]]) -> Vector:
    n = len(X)
    return [sum(col) / n for col in zip(*X)]


def knn(points: Sequence[Sequence[float]], k: int,
        queries: Optional[Sequence[Sequence[float]]] = None) -> List[List[int]]:
    """The k nearest points (Euclidean) of each query, by brute force.

    With queries=None the queries are the points themselves and each point is
    left out of its own list. Each list is sorted by (distance, index).
    """
    self_query = queries is None
    qs = points if self_query else queries
    limit = len(points) - (1 if self_query else 0)
    if not 0 <= k <= limit:
        raise ValueError("k must be between 0 and the number of candidate points")
    out = []
    for i, q in enumerate(qs):
        cand = [(sqdist(q, p), j) for j, p in enumerate(points) if not (self_query and j == i)]
        cand.sort()
        out.append([j for _, j in cand[:k]])
    return out


def solve(A: Sequence[Sequence[float]], b: Sequence[float]) -> Vector:
    """Solve A x = b by Gaussian elimination with partial pivoting.

    Raises ValueError when a pivot is zero, that is when A is singular in
    floating point.
    """
    n = len(A)
    M = [list(map(float, A[i])) + [float(b[i])] for i in range(n)]
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(M[r][c]))
        if M[p][c] == 0.0:
            raise ValueError("singular matrix")
        M[c], M[p] = M[p], M[c]
        piv = M[c][c]
        for r in range(c + 1, n):
            f = M[r][c] / piv
            if f != 0.0:
                row, top = M[r], M[c]
                for j in range(c, n + 1):
                    row[j] -= f * top[j]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        s = M[i][n] - sum(M[i][j] * x[j] for j in range(i + 1, n))
        x[i] = s / M[i][i]
    return x


def inverse(A: Sequence[Sequence[float]]) -> Matrix:
    """The inverse of A, one column at a time with solve."""
    n = len(A)
    cols = [solve(A, [1.0 if i == j else 0.0 for i in range(n)]) for j in range(n)]
    return transpose(cols)


def jacobi_eigh(S: Sequence[Sequence[float]], tol: float = 1e-12,
                max_sweeps: int = 100) -> Tuple[Vector, Matrix]:
    """All eigenvalues and eigenvectors of a symmetric matrix by the cyclic Jacobi method.

    Returns (values, vectors): values in decreasing order, and vectors[i] the
    unit eigenvector of values[i]. Each eigenvector is given the sign that
    makes its entry of largest absolute value positive.
    """
    n = len(S)
    A = [list(map(float, row)) for row in S]
    V = identity(n)
    for _ in range(max_sweeps):
        off = sum(A[i][j] * A[i][j] for i in range(n) for j in range(n) if i != j)
        scale = sum(A[i][i] * A[i][i] for i in range(n)) + off
        if off <= tol * tol * max(scale, 1e-300):
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                apq = A[p][q]
                if apq == 0.0:
                    continue
                theta = (A[q][q] - A[p][p]) / (2.0 * apq)
                t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                s = t * c
                for k in range(n):
                    akp, akq = A[k][p], A[k][q]
                    A[k][p] = c * akp - s * akq
                    A[k][q] = s * akp + c * akq
                for k in range(n):
                    apk, aqk = A[p][k], A[q][k]
                    A[p][k] = c * apk - s * aqk
                    A[q][k] = s * apk + c * aqk
                for k in range(n):
                    vkp, vkq = V[k][p], V[k][q]
                    V[k][p] = c * vkp - s * vkq
                    V[k][q] = s * vkp + c * vkq
    order = sorted(range(n), key=lambda i: -A[i][i])
    values = [A[i][i] for i in order]
    vectors = []
    for i in order:
        v = [V[k][i] for k in range(n)]
        big = max(range(n), key=lambda k: abs(v[k]))
        if v[big] < 0:
            v = [-x for x in v]
        vectors.append(v)
    return values, vectors


def pca_fit(X: Sequence[Sequence[float]], r: int) -> Tuple[Vector, Matrix, Vector]:
    """Principal axes of the rows of X: (means, axes, variances), r axes of unit length.

    The covariance uses the divisor n - 1. The axes come from jacobi_eigh, so they
    are deterministic up to the sign rule of that function.
    """
    n, d = len(X), len(X[0])
    if not 1 <= r <= d:
        raise ValueError("r must be between 1 and the number of columns")
    mu = column_means(X)
    C = [[0.0] * d for _ in range(d)]
    for row in X:
        z = [x - m for x, m in zip(row, mu)]
        for a in range(d):
            za = z[a]
            if za != 0.0:
                Ca = C[a]
                for b in range(a, d):
                    Ca[b] += za * z[b]
    for a in range(d):
        for b in range(a, d):
            C[a][b] /= max(n - 1, 1)
            C[b][a] = C[a][b]
    values, vectors = jacobi_eigh(C)
    return mu, vectors[:r], values[:r]


def pca_project(X: Sequence[Sequence[float]], mu: Sequence[float], axes: Sequence[Sequence[float]]) -> Matrix:
    """The coordinates of the rows of X on the axes, after subtracting mu."""
    return [[dot([x - m for x, m in zip(row, mu)], a) for a in axes] for row in X]


def poisson_knuth(rng: random.Random, lam: float) -> int:
    """A Poisson draw by multiplying uniforms (Knuth); for test data with lam up to about 50.

    Draw order: rng.random() until the product falls below exp(-lam).
    """
    if lam < 0:
        raise ValueError("lam must be non-negative")
    limit, k, p = math.exp(-lam), 0, 1.0
    while True:
        p *= rng.random()
        if p <= limit:
            return k
        k += 1
test_combat.py 188 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/combat/. The authors are listed in prov/PBAHAY.jsonl.

import math
import random

import pytest

from combat import combat, inverse_gamma_moments, mean, posterior, standardize, var

PAGE = [[1, 2, 3, 4, 5, 6], [2, 4, 6, 5, 6, 7], [3, 3, 4, 7, 9, 11], [5, 6, 7, 6, 8, 10]]
PAGE_BATCH = ["A"] * 3 + ["B"] * 3


def close(a, b, tol=5e-4):
    return all(math.isclose(x, y, abs_tol=tol) for x, y in zip(a, b))


def test_page_example():
    Z, stand, sigma, _ = standardize(PAGE, PAGE_BATCH)
    assert math.isclose(sigma[0] ** 2, 2 / 3) and stand[0] == [3.5] * 6
    zA = Z[0][:3]
    assert math.isclose(mean(zA), -1.5 / math.sqrt(2 / 3)) and math.isclose(var(zA), 1.5)
    # The priors of batch A over the four genes.
    zs = [z[:3] for z in Z]
    g_hat, d_hat = [mean(z) for z in zs], [var(z) for z in zs]
    lam, theta = inverse_gamma_moments(d_hat)
    assert close([mean(g_hat), var(g_hat), lam, theta], [-1.4359, 0.6283, 3.4837, 2.9375])
    gs, ds = posterior(zs[0], g_hat[0], d_hat[0], mean(g_hat), var(g_hat), lam, theta)
    assert close([gs, ds], [-1.6874, 1.1223])
    # Without shrinkage both batches of gene 1 become 2.684, 3.5, 4.316; with it they keep a small gap.
    ls = combat(PAGE, PAGE_BATCH, shrink=False)
    assert close(ls[0], [2.684, 3.5, 4.316] * 2, 1e-3)
    eb = combat(PAGE, PAGE_BATCH)
    assert close(eb[0], [2.441, 3.385, 4.329, 2.834, 3.619, 4.404], 1e-3)


def random_data(rng, G, sizes, covariate=False):
    batch, cov = [], []
    for i, n in enumerate(sizes):
        batch += [i] * n
        cov += [[float(rng.random() < 0.5)] for _ in range(n)]
    data = []
    for g in range(G):
        shift = [rng.gauss(0, 1) for _ in sizes]
        scale = [math.exp(rng.gauss(0, 0.4)) for _ in sizes]
        data.append([5 + 2 * cov[j][0] + shift[b] + scale[b] * rng.gauss(0, 1) for j, b in enumerate(batch)])
    return data, batch, (cov if covariate else None)


def test_location_scale_without_shrinkage_equalizes_batches_exactly():
    rng = random.Random(1)
    for covariate in (False, True):
        data, batch, cov = random_data(rng, 6, (4, 5, 6), covariate)
        out = combat(data, batch, cov, shrink=False)
        _, stand, sigma, _ = standardize(data, batch, cov)
        for g in range(6):
            for b in range(3):
                idx = [j for j in range(len(batch)) if batch[j] == b]
                resid = [out[g][j] - stand[g][j] for j in idx]
                assert abs(mean(resid)) < 1e-9
                assert math.isclose(var(resid), sigma[g] ** 2, rel_tol=1e-9)


def test_inverse_gamma_moments_match():
    rng = random.Random(2)
    for _ in range(20):
        d = [rng.uniform(0.2, 3.0) for _ in range(10)]
        lam, theta = inverse_gamma_moments(d)
        assert lam > 2
        assert math.isclose(theta / (lam - 1), mean(d))
        assert math.isclose(theta ** 2 / ((lam - 1) ** 2 * (lam - 2)), var(d))


def test_posterior_is_a_fixed_point_and_converges_monotonically():
    rng = random.Random(3)
    for _ in range(50):
        n = rng.randint(2, 6)
        z = [rng.gauss(1, 1.5) for _ in range(n)]
        g_hat, d_hat = mean(z), var(z)
        g_bar, t2 = rng.gauss(0, 1), rng.uniform(0.05, 2)
        lam, theta = rng.uniform(2.1, 8), rng.uniform(0.5, 8)
        hist = []
        gs, ds = posterior(z, g_hat, d_hat, g_bar, t2, lam, theta, conv=1e-13, history=hist)
        assert math.isclose(gs, (t2 * n * g_hat + ds * g_bar) / (t2 * n + ds), rel_tol=1e-9, abs_tol=1e-12)
        assert math.isclose(ds, (theta + 0.5 * sum((x - gs) ** 2 for x in z)) / (n / 2 + lam - 1), rel_tol=1e-9)
        assert min(g_hat, g_bar) - 1e-12 <= gs <= max(g_hat, g_bar) + 1e-12
        ds_seq = [d_hat] + [d for _, d in hist]
        steps = [b - a for a, b in zip(ds_seq[1:], ds_seq[2:])]
        assert all(s >= -1e-12 for s in steps) or all(s <= 1e-12 for s in steps)


def test_posterior_mean_matches_numerical_integration():
    """gamma* with delta^2 fixed is the posterior mean under a normal prior and a normal likelihood."""
    z, d2, g_bar, t2 = [0.8, 2.1, 1.4], 1.3, -0.5, 0.6
    n = len(z)
    want = (t2 * n * mean(z) + d2 * g_bar) / (t2 * n + d2)
    h = 1e-3
    grid = [-8 + h * i for i in range(16001)]

    def dens(g):
        return math.exp(-(g - g_bar) ** 2 / (2 * t2) - sum((x - g) ** 2 for x in z) / (2 * d2))

    w = [dens(g) for g in grid]
    got = sum(g * v for g, v in zip(grid, w)) / sum(w)
    assert math.isclose(got, want, abs_tol=1e-6)


def test_shift_and_scale_of_a_gene_carry_through():
    rng = random.Random(4)
    data, batch, cov = random_data(rng, 5, (3, 4), True)
    base = combat(data, batch, cov)
    shifted = [row[:] for row in data]
    shifted[2] = [v + 7.0 for v in data[2]]
    assert close(combat(shifted, batch, cov)[2], [v + 7.0 for v in base[2]], 1e-9)
    # Scaling all genes by one factor scales the output, because the priors use standardized data.
    scaled = [[3.0 * v for v in row] for row in data]
    out = combat(scaled, batch, cov)
    for g in range(5):
        assert close(out[g], [3.0 * v for v in base[g]], 1e-9)


def simulate(rng, G, sizes, group=None):
    """Data from the ComBat model with a known batch free signal."""
    batch = [i for i, n in enumerate(sizes) for _ in range(n)]
    group = group or [0] * len(batch)
    prior = [(rng.gauss(0, 1), 0.4, 4.0, 3.0) for _ in sizes]
    clean, obs = [], []
    for g in range(G):
        a = rng.gauss(6, 1)
        s = math.exp(rng.gauss(-0.5, 0.3))
        beta = rng.gauss(0, 1)
        gam = [rng.gauss(m, math.sqrt(t2)) for m, t2, _, _ in prior]
        dl = [math.sqrt(th / rng.gammavariate(lam, 1.0)) for _, _, lam, th in prior]
        c_row, o_row = [], []
        for j, b in enumerate(batch):
            e = rng.gauss(0, 1) * s
            base = a + beta * group[j]
            c_row.append(base + e)
            o_row.append(base + gam[b] * s + dl[b] * e)
        clean.append(c_row)
        obs.append(o_row)
    return clean, obs, batch


def test_shrinkage_lowers_the_error_with_small_batches_measured():
    """A measurement: 300 genes, 3 batches of 3 samples. EB beats the plain location and scale fix."""
    rng = random.Random(2007)
    clean, obs, batch = simulate(rng, 300, (3, 3, 3))

    def err(out):
        return sum((o - c - (mean(oo) - mean(cc))) ** 2 for oo, cc in zip(out, clean)
                   for o, c in zip(oo, cc)) / (300 * 9)

    eb = combat(obs, batch)
    ls = combat(obs, batch, shrink=False)
    raw = err(obs)
    assert err(eb) < err(ls) < raw


def test_covariate_keeps_an_unbalanced_group_difference_measured():
    """A measurement: group 1 sits mostly in batch 1. Without the covariate ComBat removes much of its effect."""
    rng = random.Random(11)
    group = [0, 0, 0, 0, 0, 1] + [0, 1, 1, 1, 1, 1]
    batch = [0] * 6 + [1] * 6
    data = []
    for g in range(60):
        eff = 2.0 if g < 20 else 0.0
        shift = rng.gauss(1.0, 0.3)
        data.append([5 + eff * group[j] + shift * batch[j] + rng.gauss(0, 0.5) for j in range(12)])

    def group_diff(out):
        d = [mean([r[j] for j in range(12) if group[j]]) - mean([r[j] for j in range(12) if not group[j]]) for r in out[:20]]
        return mean(d)

    with_cov = combat(data, batch, [[float(x)] for x in group])
    without = combat(data, batch)
    assert abs(group_diff(with_cov) - 2.0) < 0.3
    assert group_diff(without) < 1.5


def test_errors():
    with pytest.raises(ValueError):
        combat([[1, 2, 3]], [0, 0, 1])
    with pytest.raises(ValueError):
        combat([[1, 2, 3], [2, 3, 5]], [0, 0, 1])
    with pytest.raises(ValueError):
        inverse_gamma_moments([1.0, 1.0, 1.0])

History

Batch effects in microarray data were known from the early 2000s. Johnson, Li and Rabinovic (2007) proposed the location and scale model with empirical Bayes priors, aimed at batches too small for the gene by gene estimates of earlier methods. Leek and co-authors (2010) showed how common and how large batch effects are in high-throughput data. ComBat became the most used batch correction for bulk data, and later versions added counts and single-cell data.

References

  1. W. Evan Johnson, Cheng Li and Ariel Rabinovic, Adjusting batch effects in microarray expression data using empirical Bayes methods, Biostatistics 8(1), 118 to 127 (2007), the section on the empirical Bayes method, with the location and scale model, the standardization, the priors, the conditional posterior means and the adjustment
  2. Jeffrey T. Leek et al., Tackling the widespread and critical impact of batch effects in high-throughput data, Nature Reviews Genetics 11(10), 733 to 739 (2010), the discussion of batch effects, of their confounding with biology, and of correction methods

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example