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.
- Solves
- Batch effect correction
- 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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 of expression values, such as log counts, for genes and samples, a batch label for each sample, with at least two samples per batch, and optional covariates to keep.
Output. An adjusted matrix of the same shape.
Model. For sample in batch , , where has mean 0 and variance . The batch shifts and scales are the effects to remove.
The algorithm
COMBAT(Y, batch, x)- 1
for each gene g: fit Y[g] by least squares on batch indicators and x; α_g ← the size-weighted mean of the batch coefficients - 2
σ²_g ← the mean squared residual of gene g - 3
Z[g][j] ← (Y[g][j] - α_g - x_j β_g) / σ_g - 4
γ̂_ig, δ̂²_ig ← the mean and the sample variance of Z[g][j] over the samples j of batch i - 5
γ̄_i, τ²_i ← the mean and the sample variance of γ̂_ig over the genes - 6
D, S² ← the mean and the sample variance of δ̂²_ig over the genes; λ_i ← (D² + 2S²) / S²; θ_i ← (D³ + D S²) / S² - 7
repeat: γ*_ig ← (n_i τ²_i γ̂_ig + δ*²_ig γ̄_i) / (n_i τ²_i + δ*²_ig) - 8
δ*²_ig ← (θ_i + ½ Σ_j (Z[g][j] - γ*_ig)²) / (n_i/2 + λ_i - 1) - 9
until the relative change of γ* and δ*² is below 10^-4 ▷ start from δ*² = δ̂² - 10
Y*[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 is the batch shift in units of . Line L4 gives the plain estimates of the shift and the scale of each gene and batch. Lines L5 and L6 fit the priors and by the method of moments, over all genes of batch . 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 and , 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 , the residuals are in each batch, and . Then , and batch A has and . Over the four genes, batch A has shifts and scales . So , , and ; the prior mean of the scale is , the mean of the four scales. The iteration moves gene 1 to and , 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 for genes and samples . Sample is in batch , batch has samples, and is a row of covariates. Line L1 fits, for each gene, by least squares, where is a coefficient for each batch, and sets . Let and let be the residuals of the fit. Line L2 sets , and line L3 sets . Line L4 sets and to the mean and the sample variance (divisor ) of over the samples of batch . Line L10 returns
Lemma 1 (the standardized data). For each gene and batch, for the samples of batch , and .
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 , , so the batch mean of is , and subtracting it leaves .
So is the shift of batch in units of , and is the variance of the residuals of batch in units of . 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 and , for every gene and batch , the values over the samples of batch have mean 0 and sample variance .
Proof. . Over batch , the mean of is 0 and its sample variance is , so the mean is 0 and the sample variance is .
Lemma 3 (line L7). Let be independent given , with known, and let . Then the posterior mean of is
Proof. The log of the posterior density is, up to a constant, . This is a quadratic in with leading coefficient and linear coefficient , so the posterior is normal with mean . Multiply the numerator and the denominator by .
The estimate moves toward by the factor , which is large when the batch is small or noisy and small when the genes disagree a lot about the shift ( large).
Lemma 4 (line L8). Let be independent given , with known, and let have the inverse gamma density proportional to . Then the posterior is inverse gamma with shape and scale , and its mean is
Proof. The likelihood is proportional to . Multiplying by the prior gives the stated shape and scale. An inverse gamma with shape and scale has mean . Here because by Lemma 5.
Lemma 5 (line L6). Let and be the mean and the sample variance of the values over the genes. Then and are the only parameters with for which the inverse gamma has mean and variance , and , .
Proof. For the inverse gamma has mean and variance . Setting the mean to gives , and then the variance is , so and , which are the formulas. and give and .
In the same way line L5 sets the normal prior to the mean and the sample variance of the 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 , and for let and , where and . This is lines L7 and L8. The sequence is monotone and converges to a limit with , and converges to . Every lies between and .
Proof. For , , so lies between and , and does not decrease as grows and is at most . Since is the mean of the , . So is continuous and non-decreasing on , and its values lie in a bounded interval with . If , then , and by induction the sequence does not decrease; if it does not increase. A monotone bounded sequence converges, and its limit . By continuity, , and .
The code stops when the relative change of both values is below , 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 ; it is the estimate that Johnson, Li and Rabinovic define. The proof does not show that 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 in place of gets and the same , so its output moves by . If all data are multiplied by , then and the priors do not change and the output is multiplied by .
Complexity. With columns in the design, the least squares fit of one gene takes time, so lines L1 to L3 take . Lines L4 to L6 take . Each step of the iteration takes time for one gene and batch, so steps take in all. The number of steps is finite by Theorem 6 but has no proved bound. The space is .
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 ) 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 time per gene for design columns, so in all. The priors take . Each step of the iteration takes for all genes and batches, so steps take . The proof shows that the iteration stops but gives no bound on . The space is 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 , 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.
# 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag PBAHAY Edit this page History Report an error Markdown