Algorithmadvanced
Mutual nearest neighbors batch correction
Also called MNN correction.
Pair cells across batches that are mutual nearest neighbors, average their difference vectors, and shift one batch onto the other.
- Solves
- Batch effect correction
- Time
- O(q^2 n^2 (d + log n) + q k n^2 d) worst
- Space
- O(q n d + k n d) extra
- Where
- d = the number of genes; k = the number of neighbors; n = the number of cells per batch; q = the number of batches
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Laleh Haghverdi, Aaron T. L. Lun, Michael D. Morgan, John C. Marioni, 2018
Mutual nearest neighbors (MNN) batch correction removes batch effects from single-cell RNA-seq data by finding cells of the same type in two batches. A cell of one batch and a cell of the other are a pair when each is among the nearest neighbors of the other across the batches. The difference between the two cells of a pair estimates the batch effect at that place, and each cell of the second batch moves by a smoothed average of these differences. Haghverdi, Lun, Morgan and Marioni (2018) proposed it. Unlike ComBat, which removes one shift per gene and batch, it does not need the batches to hold the same mix of cell types, and the shift can change from one cell type to another. It solves the batch effect correction problem for single cells, under the assumption that the batches share at least one cell type.
In plain words
Two labs measured the same kinds of cells, but every cell from lab B looks a bit off in a certain direction. Find pairs of cells, one from each lab, that each pick the other as one of their closest matches in the other lab. Such pairs are most likely the same kind of cell, so the gap between them is the lab effect. Each cell of lab B then moves by the average gap of the pairs near it, with near pairs counting more. A kind of cell that only lab B has finds no partner, but it still moves with the pairs closest to it, so it is not pushed onto a different kind of cell.
The problem
Input. Batches of cells, each cell a vector of log expression values over the same genes, a number of neighbors and a kernel width . The first batch is the reference.
Output. The batches in one space, with the batch effect removed.
Assumptions (Haghverdi et al. 2018): at least one cell population is present in both batches, the batch effect is almost orthogonal to the biological subspace, and the batch effect varies much less than the biology between cell types.
The algorithm
MNN-CORRECT(batches, k, σ)- 1
divide every cell by its Euclidean norm ▷ cosine normalization - 2
for the reference R and the next batch B: N_R(b) ← the k nearest cells of R to b; N_B(r) ← the k nearest cells of B to r - 3
P ← all pairs (r, b) with r ∈ N_R(b) and b ∈ N_B(r) - 4
v_p ← r - b for each pair p = (r, b) - 5
for each cell x of B: c(x) ← Σ_p w_p v_p / Σ_p w_p, with w_p = exp(-‖x - b_p‖² / σ²) - 6
replace each cell x of B by x + c(x) - 7
add the corrected B to R and go to L2 with the next batch
Line L1 is the cosine normalization of the paper. After it, cells that differ only by a factor in all genes are the same point, and the distance between two cells depends only on the cosine similarity of their profiles. Lines L2 and L3 find the mutual pairs with two neighbor searches across the batches. Line L4 gives one batch vector per pair. Line L5 averages them with a Gaussian kernel on the distance from to the cell of in each pair, so the correction of a cell comes mostly from pairs in its own part of the data; this is a kernel smoother of the kind used in kernel density estimation. Line L7 merges the batches one at a time onto the reference.
Example
Five reference cells and five cells of a second batch in two dimensions, with and no cosine normalization. The reference has two cells of a type on the left and three of a type on the right. The second batch has three on the left, one on the right, and one cell of a type the reference does not have. The batch effect moved every cell of up by 3.
| reference | |||||
|---|---|---|---|---|---|
| batch |
The nearest cell of to is , but the nearest cell of to is , so has no pair. In the same way and pick , which picks . The mutual pairs are with , with , and with . All three pair vectors are , so every cell of moves by : the left and right cells land on the reference line, and the new type goes to , away from both. Moving by the difference of the batch means would use , which is wrong, because the two batches have different mixes of the two types.
Correctness
The proof shows that the correction of every cell is a weighted mean of the pair vectors with positive weights, so a batch effect that is the same for all pairs is removed exactly, and no cell moves further than the longest pair vector. It shows that with a translation shorter than half of the smallest distance between reference cells gives only true pairs, so the second batch lands exactly on the reference. It also shows that cosine normalization removes a scale factor of each cell. When the batch effect is not constant, or pairs join cells of different types, the result is an estimate, and its error is measured, not proved.
Proof: The MNN correction is a convex combination of the pair vectors, and it removes a small translation exactlyfull
We prove what the steps compute. Cosine normalization removes a scale factor of each cell and turns Euclidean distance into a function of the cosine (Lemma 1). The pairs are symmetric and there are at most of them (Lemma 2). The correction of every cell is a convex combination of the pair vectors, so it removes a batch effect exactly when all pair vectors equal it (Lemma 3). And a translation shorter than half of the smallest distance between reference cells is removed exactly with (Theorem 4). Haghverdi and co-authors state three assumptions: at least one cell population is present in both batches, the batch effect is almost orthogonal to the biological subspace, and the batch effect varies much less than the biology between cell types. When the batch effect is not constant, the result is a smoothed estimate; how good it is depends on the data, and the tests measure it.
Setting. A reference batch and a batch of points in . is the set of the nearest cells of to and the set of the nearest cells of to , with ties broken by index. Line L3 keeps the pairs . Line L4 sets for , and line L5 sets, for each ,
where is the cell of in pair . Line L6 returns .
Lemma 1 (cosine normalization). Line L1 maps to . Then for every , and .
Proof. . For unit vectors, .
So a cell whose counts are all larger by one factor, for example because its batch was sequenced more deeply, lands at the same point, and nearest neighbors after the normalization are nearest by angle.
Lemma 2 (pairs). if and only if is a pair when the roles of and are swapped, and .
Proof. The condition and is the same with the roles swapped. Each pair has , so for each there are at most pairs, and ; in the same way .
Lemma 3 (convex combination). If is not empty, then for every the weights are positive and sum to 1, so lies in the convex hull of the pair vectors. In particular, if for all , then for every .
Proof. Each exponential is positive and they are divided by their sum. The code subtracts the smallest squared distance from all of them before taking the exponential, which multiplies the numerator and the denominator by the same factor and keeps the largest term at 1, so the sum cannot underflow to 0. A weighted mean with positive weights that sum to 1 lies in the convex hull, and it equals when every term equals .
So the correction never moves a cell further than the longest pair vector, and a cell type that is found only in moves by the vectors of the nearest pairs, not onto some cell of . As all weights tend to and tends to the mean of the pair vectors, a single shift. As the weight goes to the pairs whose cell is nearest to , so a cell that is in exactly one pair gets that pair's vector.
Theorem 4 (translation). Let for a vector with , where , and let . Then for all , and line L6 returns for every .
Proof. For , , so the nearest cell of to is , with no tie. In the same way , so the nearest cell of to is . So is a pair for every , and no other pair exists because each has only one nearest cell. Every pair vector is , and by Lemma 3 every cell moves by .
The condition is the third assumption of the paper in its simplest form: the batch effect is smaller than the distances that separate cells. With a larger shift, cells of pair with the wrong cells of . With and noise, a pair can join cells of two different types; the tests count such pairs.
What the lines compute. Line L1 is Lemma 1. Lines L2 and L3 are the pairs of Lemma 2, found with two brute force neighbor searches. Line L4 gives the pair vectors and line L5 the weights of Lemma 3. Line L6 adds the correction. Line L7 adds the corrected batch to the reference, so the next batch is matched against all cells corrected so far; the result depends on the order of the batches.
Complexity. The two neighbor searches take time with sorting of , and there are at most pairs. Line L5 takes time. With batches of cells each, the batch is matched against cells, and line L5 takes for each batch, so the total time is by brute force. The space is for the cells and the pair vectors.
What the tests check. The test file checks the page example, the pairs against the definition with the bound and the symmetry of Lemma 2, Lemma 1, the convex hull of Lemma 3, Theorem 4 on random reference sets, the two limits of , and three batches in a row. Two simulations are measurements, not theorems. With two cell types in different proportions in the two batches, the MNN correction is much closer to the truth than moving the batch by the difference of its mean from the reference mean. A cell type found only in the second batch moves by about the true shift and stays far from the reference cells.
Complexity
With batches of cells and genes, the brute force neighbor searches for batch compare its cells with the cells corrected so far, which gives time in all. There are at most pairs per batch, so line L5 takes per batch. The space is for the cells and for the pair vectors. fastMNN works in a space of principal components, which makes small, and real tools use approximate neighbor search.
Properties
- Local correction. The shift can differ between cell types, because each cell uses the pairs near it.
- Robust to different cell type mixes. Cells without a partner do not change the pairs.
- Bounded. The correction is a convex combination of the pair vectors.
- Order dependent. With more than two batches the result depends on the order in which they are merged.
- Changes the expression values. The output is a corrected matrix, not a new embedding, so it can be used for clustering and display; using it for tests of differential expression is not advised.
Variants and improvements
- fastMNN. Finds the pairs and corrects in a space of principal components shared by the batches, which is much faster.
- Seurat anchors. Stuart and co-authors (2019) find mutual nearest neighbors in a shared space from canonical correlation analysis, score them, and use them as anchors for the correction.
- Harmony. Korsunsky and co-authors (2019) cluster the cells of all batches together and remove the batch effect cluster by cluster in principal component space, in rounds.
- Deep models. Variational autoencoders such as scVI learn a latent space that leaves out the batch.
- ComBat. ComBat is simpler and works when each batch holds the same cell types.
When to use it
Use it to put single-cell batches into one space before clustering, display on UMAP or t-SNE, or trajectory inference, when the batches share some cell types but not necessarily in the same proportions. Merge the largest or most diverse batch first, as the reference. The benchmark of Tran and co-authors (2020) recommends Harmony, LIGER and Seurat 3 over the other methods it compared, so try more than one method.
Pitfalls
- No shared types. If the batches share no cell type, every pair is wrong, and the method forces unrelated cells together.
- Too large a . In the tests, with two cell types and , 2 of 222 pairs joined different types; with , 80 of 560 did.
- Large batch effects break the nearest neighbor search: if the effect is larger than the distances between types, the pairs are wrong.
- Over-correction of real biological differences between conditions, for example between a treated and a control batch.
- Batch order. With many batches, merge in a fixed and sensible order, and check the result.
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/mnn-batch-correction/. The authors are listed in prov/MTE8PT.jsonl.
"""Batch correction by mutual nearest neighbors (Haghverdi, Lun, Morgan and Marioni 2018).
A batch is a list of cells and a cell is a list of expression values (for
example log counts of the highly variable genes). The first batch is the
reference. For each further batch B, against the reference R:
1. Cosine normalization: each cell is divided by its Euclidean norm.
2. A cell r of R and a cell b of B are a mutual nearest neighbor (MNN) pair
when r is among the k nearest cells of R to b and b is among the k nearest
cells of B to r.
3. Each pair gives the vector r - b.
4. Each cell x of B gets the average of the pair vectors, weighted by a
Gaussian kernel exp(-|x - b|^2 / sigma^2) of its distance to the cell b of
the pair, and moves by that average.
5. The corrected batch joins the reference, and the next batch is corrected
against the union.
Left out: the variance adjustment and the other options of the R function
mnnCorrect, approximate neighbor search, and the choice of the batch order.
Neighbor search is brute force with ties broken by index.
"""
from __future__ import annotations
import math
from typing import List, Sequence, Tuple
from rq3lin import knn, sqdist
Matrix = List[List[float]]
def cosine_normalize(X: Sequence[Sequence[float]]) -> Matrix:
out = []
for row in X:
norm = math.sqrt(sum(v * v for v in row))
if norm == 0:
raise ValueError("a cell with all values 0 has no direction")
out.append([v / norm for v in row]) # @line L1
return out
def mnn_pairs(R: Sequence[Sequence[float]], B: Sequence[Sequence[float]], k: int) -> List[Tuple[int, int]]:
"""All pairs (r, b) with r in the k nearest of b in R and b in the k nearest of r in B, sorted."""
near_r = knn(R, k, queries=B) # @line L2
near_b = [set(row) for row in knn(B, k, queries=R)]
return sorted((r, b) for b in range(len(B)) for r in near_r[b] if b in near_b[r]) # @line L3
def correction_vectors(R, B, pairs, sigma: float) -> Matrix:
"""The kernel-weighted average of the pair vectors r - b, for every cell of B."""
if not pairs:
raise ValueError("no mutual nearest neighbor pairs: the batches share no cell type")
vecs = [[x - y for x, y in zip(R[r], B[b])] for r, b in pairs] # @line L4
out = []
for x in B:
d = [sqdist(x, B[b]) for _, b in pairs]
m = min(d)
w = [math.exp(-(di - m) / (sigma * sigma)) for di in d] # the factor exp(-m / sigma^2) cancels
tot = sum(w)
out.append([sum(wi * v[a] for wi, v in zip(w, vecs)) / tot for a in range(len(x))]) # @line L5
return out
def correct_pair(R, B, k: int, sigma: float) -> Matrix:
pairs = mnn_pairs(R, B, k)
corr = correction_vectors(R, B, pairs, sigma)
return [[x + c for x, c in zip(row, cr)] for row, cr in zip(B, corr)] # @line L6
def mnn_correct(batches: Sequence[Sequence[Sequence[float]]], k: int = 20, sigma: float = 0.1,
cos_norm: bool = True) -> List[Matrix]:
"""The corrected batches, in the input order; the first batch is only normalized."""
data = [cosine_normalize(b) if cos_norm else [list(map(float, r)) for r in b] for b in batches]
out = [data[0]]
ref = list(data[0])
for B in data[1:]:
kk = min(k, len(ref), len(B))
C = correct_pair(ref, B, kk, sigma)
out.append(C)
ref = ref + C # @line L7
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_mnn_batch_correction.py 176 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mnn-batch-correction/. The authors are listed in prov/MTE8PT.jsonl.
import math
import random
import pytest
from mnn_batch_correction import correct_pair, correction_vectors, cosine_normalize, mnn_correct, mnn_pairs
from rq3lin import knn, sqdist
PAGE_R = [(0, 0), (1, 0), (6, 0), (7, 0), (8, 0)]
PAGE_B = [(0, 3), (1, 3), (2, 3), (7, 3), (3, 9)]
def close(a, b, tol=1e-9):
return all(math.isclose(x, y, abs_tol=tol) for x, y in zip(a, b))
def test_page_example():
pairs = mnn_pairs(PAGE_R, PAGE_B, 1)
assert pairs == [(0, 0), (1, 1), (3, 3)]
out = mnn_correct([PAGE_R, PAGE_B], k=1, sigma=1.0, cos_norm=False)[1]
want = [(0, 0), (1, 0), (2, 0), (7, 0), (3, 6)]
assert all(close(a, b) for a, b in zip(out, want))
# A global shift by the difference of the batch means would be wrong here.
mr = [sum(c) / 5 for c in zip(*PAGE_R)]
mb = [sum(c) / 5 for c in zip(*PAGE_B)]
assert close([a - b for a, b in zip(mr, mb)], [1.8, -4.2])
# With k = 2 the pairs include wrong matches, and the correction is no longer exact.
p2 = mnn_pairs(PAGE_R, PAGE_B, 2)
assert (2, 3) in p2
def brute_pairs(R, B, k):
def near(points, q):
return sorted(range(len(points)), key=lambda j: (sqdist(q, points[j]), j))[:k]
return sorted((r, b) for r in range(len(R)) for b in range(len(B))
if r in near(R, B[b]) and b in near(B, R[r]))
def test_pairs_match_the_definition_and_are_bounded():
rng = random.Random(1)
for _ in range(20):
R = [[rng.gauss(0, 1) for _ in range(3)] for _ in range(rng.randint(3, 15))]
B = [[rng.gauss(0.5, 1) for _ in range(3)] for _ in range(rng.randint(3, 15))]
k = rng.randint(1, 3)
p = mnn_pairs(R, B, k)
assert p == brute_pairs(R, B, k)
assert len(p) <= k * min(len(R), len(B))
assert sorted((r, b) for b, r in mnn_pairs(B, R, k)) == p
def test_cosine_normalization():
x = [3.0, 4.0, 0.0]
assert close(cosine_normalize([x])[0], [0.6, 0.8, 0.0])
assert close(cosine_normalize([[2.5 * v for v in x]])[0], [0.6, 0.8, 0.0])
rng = random.Random(2)
for _ in range(20):
a = [rng.uniform(0, 5) for _ in range(4)]
b = [rng.uniform(0, 5) for _ in range(4)]
na, nb = cosine_normalize([a, b])
cos = sum(p * q for p, q in zip(a, b)) / math.sqrt(sum(p * p for p in a) * sum(q * q for q in b))
assert math.isclose(sqdist(na, nb), 2 - 2 * cos, abs_tol=1e-12)
with pytest.raises(ValueError):
cosine_normalize([[0.0, 0.0]])
def test_correction_is_a_convex_combination_of_the_pair_vectors():
rng = random.Random(3)
R = [[rng.gauss(0, 1) for _ in range(2)] for _ in range(20)]
B = [[rng.gauss(1, 1) for _ in range(2)] for _ in range(20)]
pairs = mnn_pairs(R, B, 3)
vecs = [[x - y for x, y in zip(R[r], B[b])] for r, b in pairs]
for c in correction_vectors(R, B, pairs, 0.7):
for a in range(2):
assert min(v[a] for v in vecs) - 1e-12 <= c[a] <= max(v[a] for v in vecs) + 1e-12
def test_exact_translation_is_removed():
"""k = 1 and a shift shorter than half the closest distance in R: every pair is true, so B maps onto R."""
rng = random.Random(4)
for _ in range(10):
R = [[rng.uniform(0, 10) for _ in range(3)] for _ in range(25)]
dmin = min(math.sqrt(sqdist(p, q)) for i, p in enumerate(R) for q in R[i + 1:])
c = [rng.gauss(0, 1) for _ in range(3)]
n = math.sqrt(sum(v * v for v in c))
c = [v * 0.45 * dmin / n for v in c]
B = [[x + y for x, y in zip(p, c)] for p in R]
assert mnn_pairs(R, B, 1) == [(i, i) for i in range(25)]
out = correct_pair(R, B, 1, sigma=0.5)
assert all(close(a, b) for a, b in zip(out, R))
def test_bandwidth_limits():
rng = random.Random(5)
R = [[rng.gauss(0, 1) for _ in range(2)] for _ in range(15)]
B = [[rng.gauss(0.3, 1) for _ in range(2)] for _ in range(15)]
pairs = mnn_pairs(R, B, 2)
vecs = [[x - y for x, y in zip(R[r], B[b])] for r, b in pairs]
mean = [sum(v[a] for v in vecs) / len(vecs) for a in range(2)]
for c in correction_vectors(R, B, pairs, 1e4):
assert close(c, mean, 1e-6)
# A cell of B that is in exactly one pair gets that pair's vector when sigma is tiny.
tiny = correction_vectors(R, B, pairs, 1e-3)
for (r, b), v in zip(pairs, vecs):
if sum(1 for _, bb in pairs if bb == b) == 1:
assert close(tiny[b], v, 1e-9)
def two_batches(rng, frac1, frac2, n=60, dim=5):
"""Two cell types in two batches with different mixes; batch 2 is shifted by a constant vector."""
types = [[0.0] * dim, [4.0] + [0.0] * (dim - 1)]
shift = [0.0, 2.0, 1.0] + [0.0] * (dim - 3)
def cells(frac):
out, lab = [], []
for i in range(n):
t = 1 if i < frac * n else 0
out.append([m + rng.gauss(0, 0.5) for m in types[t]])
lab.append(t)
return out, lab
R, lr = cells(frac1)
T, lb = cells(frac2)
B = [[x + s for x, s in zip(p, shift)] for p in T]
return R, lr, B, lb, T
def test_different_cell_type_mix_measured():
"""A measurement: MNN finds the shift when the mixes differ; centering the batch means does not."""
rng = random.Random(2018)
R, lr, B, lb, truth = two_batches(rng, 0.2, 0.8)
out = mnn_correct([R, B], k=10, sigma=1.0, cos_norm=False)[1]
mr = [sum(c) / len(R) for c in zip(*R)]
mb = [sum(c) / len(B) for c in zip(*B)]
centered = [[x + a - b for x, a, b in zip(p, mr, mb)] for p in B]
def err(X):
return sum(math.sqrt(sqdist(p, q)) for p, q in zip(X, truth)) / len(X)
# Measured: 0.78 against 2.36. The error left is the noise of the paired cells.
assert err(out) < 0.4 * err(centered)
# After correction the nearest reference cell of each cell of B has its cell type.
nn = knn(R, 1, queries=out)
assert sum(lr[nn[i][0]] == lb[i] for i in range(len(B))) >= 0.95 * len(B)
def test_cell_type_missing_from_the_reference_measured():
"""A measurement: a type found only in batch 2 is moved, but not onto a type of batch 1."""
rng = random.Random(7)
R, lr, B, lb, truth = two_batches(rng, 0.5, 0.5)
extra = [[0.0, 0.0, 0.0, 5.0, 0.0] for _ in range(15)]
extra = [[m + rng.gauss(0, 0.5) for m in p] for p in extra]
shift = [0.0, 2.0, 1.0, 0.0, 0.0]
B2 = B + [[x + s for x, s in zip(p, shift)] for p in extra]
out = mnn_correct([R, B2], k=10, sigma=1.0, cos_norm=False)[1]
moved = out[len(B):]
gap = min(math.sqrt(sqdist(p, q)) for p in moved for q in R)
assert gap > 2.0
assert sum(math.sqrt(sqdist(p, q)) for p, q in zip(moved, extra)) / 15 < 1.5
def test_three_batches_in_order():
rng = random.Random(8)
R = [[rng.uniform(0, 10) for _ in range(2)] for _ in range(20)]
B = [[x + 0.01, y - 0.02] for x, y in R]
C = [[x - 0.015, y + 0.01] for x, y in R]
out = mnn_correct([R, B, C], k=1, sigma=0.5, cos_norm=False)
assert all(close(a, b, 1e-9) for a, b in zip(out[1], R))
assert all(close(a, b, 1e-9) for a, b in zip(out[2], R))
def test_no_pairs_is_an_error():
with pytest.raises(ValueError):
correction_vectors([[0.0]], [[1.0]], [], 1.0)
History
Before 2018, single-cell batches were often corrected with bulk methods such as ComBat or limma, which assume the same mix of cell types in each batch. Haghverdi, Lun, Morgan and Marioni (2018) proposed pairing mutual nearest neighbors across batches, which needs only one shared population. In 2019, the anchors of Seurat (Stuart et al.) built on mutual nearest neighbors, and Harmony (Korsunsky et al.) took another approach with clusters. The benchmark of Tran and co-authors (2020) compared 14 such methods.
References
- Laleh Haghverdi, Aaron T. L. Lun, Michael D. Morgan and John C. Marioni, Batch effects in single-cell RNA-sequencing data are corrected by matching mutual nearest neighbors, Nature Biotechnology 36(5), 421 to 427 (2018), the Results section on the MNN method and Figure 1, with the three assumptions, the cosine normalization, the pair vectors and the Gaussian kernel average
- Tim Stuart et al., Comprehensive integration of single-cell data, Cell 177(7), 1888 to 1902 (2019), the anchors between data sets, which are mutual nearest neighbors in a shared low dimensional space
- Hoa Thi Nhu Tran et al., A benchmark of batch-effect correction methods for single-cell RNA sequencing data, Genome Biology 21, article 12 (2020), the comparison of 14 correction methods on several data sets, and the recommendation of Harmony, LIGER and Seurat 3
- Ilya Korsunsky et al., Fast, sensitive and accurate integration of single-cell data with Harmony, Nature Methods 16(12), 1289 to 1296 (2019), the Harmony algorithm, which alternates soft clustering of all cells with a correction per cluster
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 MTE8PT Edit this page History Report an error Markdown