Algorithmcore
Trimmed mean of M-values
Also called TMM normalization.
Scale samples by a weighted trimmed mean of log fold changes against a reference, assuming most genes are not differentially expressed.
- Time
- Θ(n m log n) worst · best
- Space
- Θ(n) extra
- Where
- m = the number of samples; n = the number of genes
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Mark D. Robinson, Alicia Oshlack, 2010
The trimmed mean of M-values (TMM) finds a normalization factor for each RNA-seq sample by comparing it with a reference sample. For each gene, M is the log ratio of the two samples' count shares and A is the mean log share. TMM removes the genes with the most extreme M values (30 percent at each end) and the most extreme A values (5 percent at each end), and takes a weighted mean of the M values that remain. The weights are the inverse of an approximate variance, so genes with more reads count more. If most genes do not change, the remaining M values all estimate the same log ratio, which is the composition effect between the samples. Robinson and Oshlack (2010) proposed it, and it is the default of edgeR. It solves the library size normalization problem, like median of ratios, but it compares each sample with one real sample, it trims instead of taking a median, and it weights the genes.
In plain words
Pick one sample as the yardstick. For every gene, ask how much bigger its share of reads is in your sample than in the yardstick, on a log scale. Most genes did not change, so most answers are about the same number. A few genes really changed and give extreme answers. Throw away the most extreme 30 percent at the top and at the bottom, and also the genes with the very highest and very lowest counts. Average what is left, and trust the genes with many reads more than the genes with few. The result tells you how much the shares differ for an ordinary gene, and so how to rescale the sample.
The problem
Input. The counts of a sample and of a reference sample for genes , with library sizes and , and the trim fractions and .
Output. A factor such that and are comparable library sizes: for an unchanged gene, . For samples, the factors of all samples against one reference, rescaled to have product 1.
Assumption. Most genes do not change, and the genes that change are few enough that their M values fall in the trimmed tails.
The algorithm
TMM(o, r, N_o, N_r, θ_M = 0.3, θ_A = 0.05) ▷ sample o against reference r- 1
keep the genes with o_g > 0 and r_g > 0, and let n be their number - 2
M_g ← log2((o_g / N_o) / (r_g / N_r)) ▷ log ratio of the shares - 3
A_g ← (log2(o_g / N_o) + log2(r_g / N_r)) / 2 ▷ mean log share - 4
v_g ← (N_o - o_g)/(N_o o_g) + (N_r - r_g)/(N_r r_g) ▷ approximate variance of M_g - 5
λ_M ← ⌊n θ_M⌋ + 1; λ_A ← ⌊n θ_A⌋ + 1 - 6
rank the M_g and the A_g, with average ranks for ties - 7
K ← {g : λ_M ≤ rank(M_g) ≤ n + 1 - λ_M and λ_A ≤ rank(A_g) ≤ n + 1 - λ_A} - 8
f ← (Σ_{g ∈ K} M_g / v_g) / (Σ_{g ∈ K} 1 / v_g) - 9
return 2^f
Line L1 drops genes with a zero in either sample, because their log ratio is not defined. Lines L2 and L3 put each gene at a point of the MA plot. Line L4 is the delta method variance of when each count is binomial given its library size: for a share of reads, and the constant is the same for all genes, so it drops out of the weights. Lines L5 to L7 keep the genes whose M rank lies inside and whose A rank lies inside . Both intervals are symmetric. Line L8 is the weighted mean of the kept M values. The code returns 1 when no gene is kept or when every , as edgeR does.
For samples, edgeR picks as the reference the sample whose upper quartile share (the 75th percentile of its counts divided by its library size) is closest to the mean of these shares. It computes the factor of every sample against that reference, the reference getting 1, and divides all factors by their geometric mean. The effective library size is then the offset of the negative binomial model.
Example
Ten genes, a sample o with and a reference r with . Genes 5 and 10 are much higher in o, and gene 7 is lower. With , , so the M ranks 4 to 7 are kept, and , so no gene is trimmed by A.
| gene | M rank | kept | |||||
|---|---|---|---|---|---|---|---|
| 1 | 120 | 100 | -0.727 | -4.019 | 0.01714 | 6.5 | yes |
| 2 | 300 | 260 | -0.784 | -2.669 | 0.00599 | 5 | yes |
| 3 | 45 | 40 | -0.820 | -5.387 | 0.04603 | 3 | no |
| 4 | 80 | 70 | -0.798 | -4.569 | 0.02559 | 4 | yes |
| 5 | 900 | 300 | 0.595 | -1.773 | 0.00325 | 9 | no |
| 6 | 60 | 50 | -0.727 | -5.019 | 0.03547 | 6.5 | yes |
| 7 | 15 | 60 | -2.990 | -5.887 | 0.08214 | 1 | no |
| 8 | 250 | 200 | -0.668 | -2.990 | 0.00781 | 8 | no |
| 9 | 33 | 30 | -0.853 | -5.819 | 0.06244 | 2 | no |
| 10 | 700 | 150 | 1.232 | -2.454 | 0.00690 | 10 | no |
Genes 1 and 6 both have the count ratio , so their M values tie and share the rank 6.5. The weighted mean of the four kept M values is , and the factor is . The unweighted mean gives 0.591. The raw library sizes say that o is 1.99 times as deep as r. The effective sizes and say 1.17 times, which matches the count ratios of the kept genes, 1.14 to 1.2. After the rescaling to product 1, the two factors are 0.766 and 1.305, and the effective library sizes are 1917.5 and 1644.8.
Correctness
The proof shows that swapping the two samples turns into , because the average ranks of are minus those of and the kept interval is symmetric. It shows that genes with M values below or above cannot be kept if there are at most of each, so the factor stays in . And it shows that if all other genes share exactly the same M value , the factor is exactly , because the tied block of the unchanged genes has a rank inside the kept interval and is too large to be removed by the A trim. The example of Robinson and Oshlack, a sample with as many extra genes as shared genes, gives the factor by this result. That the weights are good weights is a heuristic based on the delta method, and that real data have enough unchanged genes is an assumption.
Proof: TMM returns the common log ratio when the changed genes fit inside the trim, and it is antisymmetricfull
We prove three facts about the trimmed mean of M-values in exact arithmetic. Swapping the two samples inverts the factor (Lemma 2). Genes whose M values lie outside a band, and that are few enough to be trimmed, cannot move the factor out of that band (Lemma 3). If all the other genes share the same M value , the factor is exactly (Theorem 4). The weights come from a delta-method approximation of the variance of . That they are good weights is a heuristic and is not proved here. That real data have a majority of unchanged genes is a modelling assumption.
Setting. Two samples, obs and ref, with counts and and library sizes . Line L1 keeps the genes with and ; let be their number. For these genes,
We assume or , so that . With trim fractions and , let , , and the same with . Ranks are average ranks: a block of tied values that follows smaller values gets rank . The kept set is , and
The code returns 1 when is empty, when no gene is left after line L1, or when every , as edgeR does.
Lemma 1 (what the lines compute). Lines L1 to L4 compute , and for the genes with two positive counts. Line L5 computes the four rank bounds. Line L6 computes average ranks, line L7 forms , and lines L8 and L9 return .
Proof. This is a direct reading of the code. The function average_ranks sorts the values and gives each block of equal values the mean of its positions, for 0-based positions . This is with and .
Lemma 2 (antisymmetry). Let be the value of with the roles of obs and ref swapped. Then , so the two factors multiply to 1.
Proof. The swap keeps the same genes at line L1 and the same , so the same bounds. It maps to and keeps and . Negating all values reverses the sorted order. A block of tied values that had smaller values now has smaller values, so its new rank is . So . The interval is symmetric under , because . Hence the kept set is the same, and .
In floating point, and can differ in the last bit, so values that tie in one direction may not tie in the other. The tests check the lemma on real-valued counts, where no two M values tie.
Lemma 3 (outliers inside the trim). Let , and split the genes into , and . If and , then . If moreover is not empty, then .
Proof. Every value of is smaller than every value outside , so the genes of fill the first sorted positions, and their average ranks lie between 1 and . In the same way the genes of fill the last positions, and their ranks are at least . So no gene of or passes the rank test of line L7, and . Then is a mean of values in with positive weights , so it lies in .
Theorem 4 (a majority with one common ratio). Use the default trims and . Suppose the genes of all have exactly, and as in Lemma 3 with . Then is not empty and , so the factor is . (The early return of the code when every gives 1 instead, which differs from by less than in the exponent.)
Proof. By Lemma 3 it is enough to show that is not empty. The genes of form one tie block after the genes of , so they all have the rank . With , this is . Since , , and this is at least when . In the same way when . For , when , and for the values satisfy one by one. So every gene of passes the M test.
The A test removes at most the lowest and the highest A ranks, so at most genes. But (for , because ). So some gene of passes both tests, and .
Corollary 5 (the example of Robinson and Oshlack). Let sample A express the same genes as sample B at the same level, and as many genes again that B does not express, with the same library size . Then the TMM factor of A against B is .
Proof. The genes that B does not express have and are dropped at line L1. For the shared genes, A has half of B's count share, , so for every gene left. This is Theorem 4 with and .
The effective library size of A is then : half of A's reads go to the genes that B lacks. Dividing by the raw library size would make every shared gene look two times lower in A.
Rounding. Theorem 4 needs exact ties. When the common ratio is not a power of 2, rounding can split the block into two blocks of slightly different values. Each block gets its own average rank, and both can fall outside . Then is empty and the code, like edgeR, returns 1. The tests contain such a case. With a small spread in the M values of , no ties occur, and Lemma 3 applies.
Normalization over many samples. norm_factors computes for every sample against one reference sample and divides by . The product of the results is 1 by construction. The choice of the reference (the upper quartile rule of edgeR) is a heuristic.
Complexity. Lines L1 to L4 take time and the two rankings take . With samples, norm_factors takes time, plus for the upper quartiles. The extra space is per factor.
Complexity
On a real RAM, lines L1 to L4 take time, and the two rankings at line L6 take . So one factor costs , and the factors of samples against one reference cost , plus for the upper quartiles that choose the reference. The extra space is .
Properties
- Antisymmetric. The factor of r against o is the inverse of the factor of o against r, in exact arithmetic.
- Robust to changed genes in the tails. Up to genes at each end of the M ranking, about 30 percent, can change by any amount without moving the factor out of the range of the other M values.
- Exact for a common ratio. If the unchanged genes have exactly the same ratio, the factor is that ratio.
- Depends on the reference. The factors of samples are computed against one sample, so a poor reference sample, for example one with low depth, adds noise to all factors.
- Weighted. Genes with many reads have small and large weight.
Variants and improvements
- Unweighted TMM. Take the plain mean of the kept M values. It is less efficient when the counts differ much between genes.
- Other trims. The trims and are arguments. Larger trims are more robust and less efficient.
- Upper quartile and RLE. edgeR also offers the upper quartile factor and "RLE", which is median of ratios.
- Many zeros. edgeR has a version, TMMwsp, that pairs the genes with a zero in one sample to use more of them. For single-cell data, pooling size factors is the usual choice.
- Median instead of mean. With close to 0.5, the trimmed mean becomes the median of the M values against one reference sample, close in spirit to median of ratios.
When to use it
Use TMM for bulk RNA-seq counts in edgeR or limma-voom, when most genes do not change and the changes are not all in one direction. It handles samples with a few very highly expressed genes well, which is the case it was made for. With strongly unbalanced changes, or a global shift in expression, use spike-ins. With single cells, use pooling.
Pitfalls
- Rounding can split a tie and return 1. When the unchanged genes have exactly the same count ratio that is not a power of 2, rounding in can give two blocks of M values that differ in the last bit. Each block gets its own average rank, and with few genes both can fall outside the kept interval, so that no gene is kept and the factor is 1. The tests contain such a case. Real data rarely have exact ties among many genes, but small toy examples often do.
- The factor is not the size factor. In edgeR, the offset is the library size times the factor. Dividing counts by the factor alone leaves the depth in.
- Genes with a zero. Line L1 drops them. When the two samples express quite different sets of genes, this is right, as in the example of Robinson and Oshlack; but with low depth it can drop most genes.
- Assuming symmetry. If 40 percent of the genes go up and none go down, the trimmed mean is pulled toward the changed genes, because they are not all in the trimmed upper tail.
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
# Shared helper of the biology pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Random variates, exact probability mass functions and test helpers for
the stochastic pages of the biology area.
Every sampler takes a random.Random object as its first argument and never
uses the module-level random functions. Each sampler draws its random
numbers in the order that its docstring gives, so two runs with the same
seed give the same output.
Conventions:
- A reaction network with n species and m reactions is given by `stoich`, a
list of the m change vectors nu_1, ..., nu_m. So stoich[j][i] is the entry
S[i][j] of the n by m stoichiometric matrix S.
- `propensity(x)` takes the state as a tuple of n integer counts and returns
the m propensities a_1(x), ..., a_m(x) as a sequence of floats >= 0.
- nbinom_pmf uses the mean mu and the dispersion alpha, with
Var = mu + alpha mu^2. The size is r = 1 / alpha; alpha = 0 is Poisson.
- hypergeom_pmf(k, total, good, draws) is the probability of k good items
in `draws` draws without replacement from `total` items of which `good`
are good.
Requires Python 3.12 or later (random.Random.binomialvariate).
"""
from __future__ import annotations
import math
from statistics import NormalDist
from typing import Callable, List, Sequence, Tuple
State = Tuple[int, ...]
_POISSON_PART = 30.0
# Random variates
def poisson(rng, lam: float) -> int:
"""A Poisson(lam) variate.
For lam <= 30, inversion of the cumulative distribution with one
rng.random() draw. For lam > 30, the sum of p = ceil(lam / 30)
independent Poisson(lam / p) variates, drawn one after the other by
inversion (one rng.random() draw each).
"""
if lam < 0 or math.isnan(lam):
raise ValueError("lam must be >= 0")
if lam == 0:
return 0
if lam > _POISSON_PART:
parts = math.ceil(lam / _POISSON_PART)
part = lam / parts
return sum(_poisson_inversion(rng, part) for _ in range(parts))
return _poisson_inversion(rng, lam)
def _poisson_inversion(rng, lam: float) -> int:
u = rng.random()
k = 0
p = math.exp(-lam)
cdf = p
while u >= cdf:
k += 1
p *= lam / k
if p == 0.0:
# Rounding left u above the computed total mass; stop at the tail.
break
cdf += p
return k
def binomial(rng, n: int, p: float) -> int:
"""A Binomial(n, p) variate by rng.binomialvariate (one call)."""
if n < 0 or not 0.0 <= p <= 1.0:
raise ValueError("need n >= 0 and 0 <= p <= 1")
if n == 0 or p == 0.0:
return 0
if p == 1.0:
return n
return rng.binomialvariate(n, p)
def multinomial(rng, n: int, probs: Sequence[float]) -> List[int]:
"""A Multinomial(n, probs) vector by conditional binomials.
probs are weights >= 0 with a positive sum; they need not sum to 1. Cell
i gets Binomial(rest of n, probs[i] / rest of the weight), for i in
order; the last cell with positive weight gets the rest.
"""
if n < 0:
raise ValueError("n must be >= 0")
w = [float(q) for q in probs]
if any(q < 0 for q in w):
raise ValueError("weights must be >= 0")
total = sum(w)
if total <= 0:
raise ValueError("weights must have a positive sum")
last = max(i for i, q in enumerate(w) if q > 0)
out = [0] * len(w)
left = n
rest = total
for i in range(last):
if left == 0:
break
if w[i] == 0:
continue
x = binomial(rng, left, min(1.0, w[i] / rest))
out[i] = x
left -= x
rest -= w[i]
out[last] += left
return out
def categorical(rng, weights: Sequence[float]) -> int:
"""An index i with probability weights[i] / sum(weights).
One draw u = rng.random() * sum(weights), then a cumulative search from
index 0. Indices with weight 0 are never returned.
"""
total = 0.0
for w in weights:
if w < 0:
raise ValueError("weights must be >= 0")
total += w
if total <= 0:
raise ValueError("weights must have a positive sum")
u = rng.random() * total
acc = 0.0
last = -1
for i, w in enumerate(weights):
if w > 0:
acc += w
last = i
if u < acc:
return i
return last
def ssa_direct(rng, x0: Sequence[int], stoich: Sequence[Sequence[int]],
propensity: Callable[[State], Sequence[float]], t_end: float,
max_events: int = 10 ** 6):
"""Gillespie's direct method from state x0 at time 0 up to time t_end.
Each step computes a = propensity(x) and a0 = sum(a). If a0 = 0 the run
stops. Otherwise it draws tau = rng.expovariate(a0) first. If
t + tau > t_end the run stops, and no second number is drawn. Else it
draws u = rng.random() * a0 and fires the first reaction j with
a_1 + ... + a_j > u (a linear search), then adds stoich[j] to x.
Returns (times, states, complete). times[0] = 0.0 and states[0] =
tuple(x0); entry k > 0 is the time and the state just after event k.
The state at t_end is states[-1]. complete is False only when the run
stopped because max_events events had fired before t_end.
"""
x = tuple(int(v) for v in x0)
times = [0.0]
states = [x]
t = 0.0
m = len(stoich)
for _ in range(max_events):
a = propensity(x)
a0 = 0.0
for v in a:
if v < 0:
raise ValueError("propensities must be >= 0")
a0 += v
if a0 <= 0.0:
return times, states, True
t += rng.expovariate(a0)
if t > t_end:
return times, states, True
u = rng.random() * a0
acc = 0.0
j = -1
for i in range(m):
if a[i] > 0:
acc += a[i]
j = i
if u < acc:
break
nu = stoich[j]
x = tuple(x[i] + nu[i] for i in range(len(x)))
times.append(t)
states.append(x)
return times, states, False
# Sample statistics and test helpers
def mean_var(xs) -> Tuple[float, float]:
"""The mean and the unbiased sample variance (divisor n - 1) by the
Welford method. The variance is 0.0 for fewer than two values."""
n = 0
mean = 0.0
m2 = 0.0
for x in xs:
n += 1
d = x - mean
mean += d / n
m2 += d * (x - mean)
if n == 0:
raise ValueError("empty sample")
return mean, (m2 / (n - 1) if n > 1 else 0.0)
def check_mean(m: float, mu: float, var: float, n: int, z: float = 4.0) -> bool:
"""True when |m - mu| <= z sqrt(var / n): a sample mean m of n
independent values with exact mean mu and exact variance var."""
return abs(m - mu) <= z * math.sqrt(var / n)
# Exact probability mass functions
def log_choose(n: int, k: int) -> float:
"""ln C(n, k), or -inf when k < 0 or k > n."""
if k < 0 or k > n:
return -math.inf
return math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1)
def binom_pmf(k: int, n: int, p: float) -> float:
"""P(K = k) for K ~ Binomial(n, p)."""
if k < 0 or k > n:
return 0.0
if p == 0.0:
return 1.0 if k == 0 else 0.0
if p == 1.0:
return 1.0 if k == n else 0.0
return math.exp(log_choose(n, k) + k * math.log(p) + (n - k) * math.log1p(-p))
def poisson_pmf(k: int, lam: float) -> float:
"""P(K = k) for K ~ Poisson(lam)."""
if k < 0:
return 0.0
if lam == 0:
return 1.0 if k == 0 else 0.0
return math.exp(k * math.log(lam) - lam - math.lgamma(k + 1))
def nbinom_pmf(k: int, mu: float, alpha: float) -> float:
"""P(K = k) for the negative binomial with mean mu and Var = mu + alpha mu^2."""
if k < 0:
return 0.0
if alpha == 0:
return poisson_pmf(k, mu)
if mu == 0:
return 1.0 if k == 0 else 0.0
r = 1.0 / alpha
return math.exp(math.lgamma(k + r) - math.lgamma(r) - math.lgamma(k + 1)
+ r * math.log(r / (r + mu)) + k * math.log(mu / (r + mu)))
def hypergeom_pmf(k: int, total: int, good: int, draws: int) -> float:
"""P(K = k) for k good items in `draws` draws without replacement from
`total` items of which `good` are good."""
if k < 0 or k > good or draws - k < 0 or draws - k > total - good:
return 0.0
return math.exp(log_choose(good, k) + log_choose(total - good, draws - k)
- log_choose(total, draws))
def logsumexp(xs) -> float:
"""ln(sum of exp(x)) without overflow; -inf for an empty input."""
xs = list(xs)
if not xs:
return -math.inf
top = max(xs)
if top == -math.inf:
return -math.inf
if top == math.inf:
return math.inf
return top + math.log(sum(math.exp(x - top) for x in xs))
# Tail probabilities
def _gamma_q(a: float, x: float) -> float:
"""The regularized upper incomplete gamma function Q(a, x)."""
if a <= 0:
raise ValueError("a must be > 0")
if x <= 0:
return 1.0
log_front = -x + a * math.log(x) - math.lgamma(a)
if x < a + 1.0:
# Series for P(a, x).
ap = a
term = 1.0 / a
total = term
for _ in range(100000):
ap += 1.0
term *= x / ap
total += term
if abs(term) < abs(total) * 1e-16:
break
return max(0.0, 1.0 - total * math.exp(log_front))
# Continued fraction for Q(a, x), by the modified Lentz method.
tiny = 1e-300
b = x + 1.0 - a
c = 1.0 / tiny
d = 1.0 / b
h = d
for i in range(1, 100000):
an = -i * (i - a)
b += 2.0
d = an * d + b
if abs(d) < tiny:
d = tiny
c = b + an / c
if abs(c) < tiny:
c = tiny
d = 1.0 / d
delta = d * c
h *= delta
if abs(delta - 1.0) < 1e-16:
break
return math.exp(log_front) * h
def chi2_sf(x: float, df: float) -> float:
"""P(X > x) for X chi-squared with df degrees of freedom."""
if df <= 0:
raise ValueError("df must be > 0")
if x <= 0:
return 1.0
return _gamma_q(df / 2.0, x / 2.0)
_STD_NORMAL = NormalDist()
def normal_sf(x: float, mu: float = 0.0, sigma: float = 1.0) -> float:
"""P(X > x) for X ~ Normal(mu, sigma^2), by statistics.NormalDist."""
return _STD_NORMAL.cdf(-(x - mu) / sigma)
tmm_normalization.py 132 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tmm-normalization/. The authors are listed in prov/TKHD07.jsonl.
"""The trimmed mean of M-values (Robinson and Oshlack 2010).
tmm_factor follows .calcFactorTMM of edgeR: for each gene with a positive
count in both samples,
M = log2((obs / N_obs) / (ref / N_ref)),
A = (log2(obs / N_obs) + log2(ref / N_ref)) / 2,
v = (N_obs - obs) / (N_obs obs) + (N_ref - ref) / (N_ref ref).
Genes are kept when the rank of M (average ranks for ties) lies in
[floor(n m_trim) + 1, n - floor(n m_trim)] and the rank of A lies in
[floor(n a_trim) + 1, n - floor(n a_trim)]. The factor is 2^f with f the
mean of the kept M values weighted by 1 / v.
norm_factors follows calcNormFactors(method = "TMM"): drop genes that are 0
in every sample, take as reference the sample whose upper quartile of
count / library size is closest to the mean of these quartiles (or, when the
median of the quartiles is below 1e-20, the sample with the largest sum of
square roots of counts), compute each factor against it, and divide by the
geometric mean of the factors so that their product is 1.
"""
from __future__ import annotations
import math
from typing import List, Optional, Sequence
def average_ranks(xs: Sequence[float]) -> List[float]:
"""Ranks 1..n, with tied values given the mean of their ranks."""
order = sorted(range(len(xs)), key=lambda i: xs[i])
ranks = [0.0] * len(xs)
i = 0
while i < len(order):
j = i
while j + 1 < len(order) and xs[order[j + 1]] == xs[order[i]]:
j += 1
r = (i + j) / 2 + 1
for t in range(i, j + 1):
ranks[order[t]] = r
i = j + 1
return ranks
def tmm_factor(obs: Sequence[float], ref: Sequence[float],
lib_obs: Optional[float] = None, lib_ref: Optional[float] = None,
m_trim: float = 0.3, a_trim: float = 0.05,
weighted: bool = True, a_cutoff: float = -1e10) -> float:
"""The TMM factor of sample obs against sample ref."""
if len(obs) != len(ref):
raise ValueError("obs and ref need the same genes")
n_obs = float(sum(obs)) if lib_obs is None else float(lib_obs)
n_ref = float(sum(ref)) if lib_ref is None else float(lib_ref)
if n_obs <= 0 or n_ref <= 0:
raise ValueError("library sizes must be positive")
ms, avals, vs = [], [], []
for o, r in zip(obs, ref):
if o <= 0 or r <= 0: # @line L1
continue
po, pr = o / n_obs, r / n_ref
a = (math.log2(po) + math.log2(pr)) / 2
if not a > a_cutoff:
continue
ms.append(math.log2(po / pr)) # @line L2
avals.append(a) # @line L3
vs.append((n_obs - o) / n_obs / o + (n_ref - r) / n_ref / r) # @line L4
if not ms or max(abs(x) for x in ms) < 1e-6:
return 1.0
n = len(ms)
lo_m = math.floor(n * m_trim) + 1 # @line L5
hi_m = n + 1 - lo_m
lo_a = math.floor(n * a_trim) + 1
hi_a = n + 1 - lo_a
rm = average_ranks(ms) # @line L6
ra = average_ranks(avals)
keep = [g for g in range(n) if lo_m <= rm[g] <= hi_m and lo_a <= ra[g] <= hi_a] # @line L7
if not keep:
return 1.0
if weighted:
num = sum(ms[g] / vs[g] for g in keep) # @line L8
den = sum(1.0 / vs[g] for g in keep)
f = num / den if den > 0 and math.isfinite(num / den) else 0.0
else:
f = sum(ms[g] for g in keep) / len(keep)
return 2.0 ** f # @line L9
def quantile7(xs: Sequence[float], p: float) -> float:
"""The quantile of type 7 (the R default): linear between order statistics."""
s = sorted(xs)
h = (len(s) - 1) * p
lo = math.floor(h)
hi = min(lo + 1, len(s) - 1)
return s[lo] + (h - lo) * (s[hi] - s[lo])
def reference_column(counts: Sequence[Sequence[float]], lib: Sequence[float]) -> int:
"""The edgeR reference sample: upper quartile closest to the mean of the upper quartiles."""
m = len(lib)
f75 = [quantile7([row[j] for row in counts], 0.75) / lib[j] for j in range(m)]
s = sorted(f75)
med = s[m // 2] if m % 2 else (s[m // 2 - 1] + s[m // 2]) / 2
if med < 1e-20:
roots = [sum(math.sqrt(row[j]) for row in counts) for j in range(m)]
return max(range(m), key=lambda j: (roots[j], -j))
mean = sum(f75) / m
return min(range(m), key=lambda j: (abs(f75[j] - mean), j))
def norm_factors(counts: Sequence[Sequence[float]], ref_column: Optional[int] = None,
**kwargs) -> List[float]:
"""TMM factors of all samples (columns of counts), scaled to product 1."""
if not counts:
raise ValueError("need at least one gene")
m = len(counts[0])
lib = [float(sum(row[j] for row in counts)) for j in range(m)]
rows = [row for row in counts if any(k > 0 for k in row)]
if ref_column is None:
ref_column = reference_column(rows, lib)
ref = [row[ref_column] for row in rows]
f = [tmm_factor([row[j] for row in rows], ref, lib[j], lib[ref_column], **kwargs)
for j in range(m)]
g = math.exp(sum(math.log(x) for x in f) / m)
return [x / g for x in f]
def effective_library_sizes(counts: Sequence[Sequence[float]], factors: Sequence[float]) -> List[float]:
"""Library size times the normalization factor, the offset used by edgeR."""
m = len(factors)
return [sum(row[j] for row in counts) * factors[j] for j in range(m)]
test_tmm_normalization.py 184 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tmm-normalization/. The authors are listed in prov/TKHD07.jsonl.
import math
import random
import pytest
from biostoch import poisson
from tmm_normalization import (
average_ranks,
effective_library_sizes,
norm_factors,
quantile7,
reference_column,
tmm_factor,
)
def brute_force(obs, ref, m_trim=0.3, a_trim=0.05):
"""The same rule with ranks found by counting: rank = #smaller + (#equal + 1) / 2."""
no, nr = sum(obs), sum(ref)
genes = [(o, r) for o, r in zip(obs, ref) if o > 0 and r > 0]
if not genes:
return 1.0
ms = [math.log2((o / no) / (r / nr)) for o, r in genes]
av = [(math.log2(o / no) + math.log2(r / nr)) / 2 for o, r in genes]
vs = [(no - o) / no / o + (nr - r) / nr / r for o, r in genes]
if max(abs(x) for x in ms) < 1e-6:
return 1.0
n = len(ms)
def rank(xs, i):
return sum(x < xs[i] for x in xs) + (sum(x == xs[i] for x in xs) + 1) / 2
lo_m = int(n * m_trim) + 1
lo_a = int(n * a_trim) + 1
kept = [i for i in range(n)
if lo_m <= rank(ms, i) <= n + 1 - lo_m and lo_a <= rank(av, i) <= n + 1 - lo_a]
if not kept:
return 1.0
return 2 ** (sum(ms[i] / vs[i] for i in kept) / sum(1 / vs[i] for i in kept))
def test_average_ranks():
assert average_ranks([3.0, 1.0, 3.0, 2.0]) == [3.5, 1.0, 3.5, 2.0]
assert average_ranks([5, 5, 5]) == [2.0, 2.0, 2.0]
assert average_ranks([]) == []
def test_matches_brute_force_with_ties():
rng = random.Random(21)
for _ in range(200):
n = rng.randint(1, 60)
obs = [rng.randint(0, 12) for _ in range(n)]
ref = [rng.randint(0, 12) for _ in range(n)]
if sum(obs) == 0 or sum(ref) == 0:
continue
assert math.isclose(tmm_factor(obs, ref), brute_force(obs, ref), rel_tol=1e-12)
def test_swapping_the_samples_inverts_the_factor():
# Real-valued counts, so that no two M values tie; with ties, rounding can
# break them differently in the two directions.
rng = random.Random(22)
for _ in range(200):
n = rng.randint(1, 80)
obs = [rng.uniform(0.5, 40) for _ in range(n)]
ref = [rng.uniform(0.5, 40) for _ in range(n)]
assert math.isclose(tmm_factor(obs, ref) * tmm_factor(ref, obs), 1.0, rel_tol=1e-12)
def test_a_sample_against_itself_is_one():
assert tmm_factor([5, 0, 7, 9], [5, 0, 7, 9]) == 1.0
assert tmm_factor([0, 3], [4, 0]) == 1.0
def test_twice_as_many_genes_gives_one_half():
# The case in Robinson and Oshlack (2010): sample A expresses the genes of B
# at the same level and as many genes again, with the same depth.
rng = random.Random(23)
shared = [2 * rng.randint(5, 500) for _ in range(200)]
depth = sum(shared)
ref = shared + [0] * 200
own = [rng.randint(1, 100) for _ in range(200)]
own = [x * (depth // 2) / sum(own) for x in own]
obs = [x // 2 for x in shared] + own
assert tmm_factor(obs, ref, lib_obs=depth, lib_ref=depth) == 0.5
def outlier_case(rng, jitter):
"""Stable genes with obs = 3 r (1 + jitter), and u low and w high outliers, u, w <= floor(0.3 n)."""
stable = rng.randint(5, 40)
while True:
low = rng.randint(0, stable)
high = rng.randint(0, stable)
if max(low, high) <= math.floor(0.3 * (stable + low + high)):
break
ref, obs = [], []
for i in range(stable):
r = rng.randint(10, 1000)
ref.append(r)
obs.append(3 * r * (1 + jitter * i))
for _ in range(low):
r = rng.randint(10, 1000)
ref.append(r)
obs.append(r * 0.01)
for _ in range(high):
r = rng.randint(10, 1000)
ref.append(r)
obs.append(r * 100)
return obs, ref, stable
def test_outliers_within_the_trim_do_not_move_the_factor():
rng = random.Random(24)
for _ in range(200):
obs, ref, stable = outlier_case(rng, 1e-5)
no, nr = sum(obs), sum(ref)
band = [math.log2((o / no) / (r / nr)) for o, r in zip(obs[:stable], ref[:stable])]
f = math.log2(tmm_factor(obs, ref))
assert min(band) - 1e-12 <= f <= max(band) + 1e-12
def test_rounding_can_split_a_tie_and_empty_the_kept_set():
# With exact ratios 3 r / r, rounding gives two nearby M values; their average
# ranks can both fall outside the kept range, and the factor falls back to 1.
rng = random.Random(24)
fallbacks = 0
for _ in range(100):
obs, ref, stable = outlier_case(rng, 0.0)
if tmm_factor(obs, ref) == 1.0 and 3 * sum(ref) != sum(obs):
fallbacks += 1
assert fallbacks >= 1
def test_no_trimming_gives_the_weighted_mean_of_all_genes():
obs = [10, 20, 30, 40]
ref = [40, 30, 20, 10]
no = nr = 100
ms = [math.log2(o / r) for o, r in zip(obs, ref)]
vs = [(no - o) / no / o + (nr - r) / nr / r for o, r in zip(obs, ref)]
f = sum(m / v for m, v in zip(ms, vs)) / sum(1 / v for v in vs)
assert math.isclose(tmm_factor(obs, ref, m_trim=0.0, a_trim=0.0), 2 ** f, rel_tol=1e-12)
g = sum(ms) / 4
assert math.isclose(tmm_factor(obs, ref, m_trim=0.0, a_trim=0.0, weighted=False), 2 ** g, rel_tol=1e-12)
def test_quantile7_and_reference():
assert quantile7([1, 2, 3, 4], 0.75) == 3.25
assert quantile7([7], 0.75) == 7
counts = [[1, 2, 10], [2, 4, 0], [3, 6, 0], [4, 8, 10]]
lib = [10, 20, 20]
# upper quartiles over library size: 0.325, 0.325, 0.5; mean 0.383; ties go to the first
assert reference_column(counts, lib) == 0
zeros = [[0, 0, 0]] * 7 + [[1, 9, 4]]
assert reference_column(zeros, [1, 9, 4]) == 1
def test_norm_factors_multiply_to_one_and_offsets():
rng = random.Random(25)
counts = [[rng.randint(0, 50) for _ in range(5)] for _ in range(100)] + [[0] * 5]
f = norm_factors(counts)
assert math.isclose(math.prod(f), 1.0, rel_tol=1e-12)
eff = effective_library_sizes(counts, f)
for j in range(5):
assert math.isclose(eff[j], sum(row[j] for row in counts) * f[j])
with pytest.raises(ValueError):
norm_factors([])
def test_composition_measurement():
# A measurement, not a theorem: 10 percent of the genes are 4 times higher in
# sample 0. The true ratio of the factors is sum(q) / sum(q'), and TMM comes
# within 3 percent of it, while the library sizes alone are about 30 percent off.
rng = random.Random(26)
q = [math.exp(rng.uniform(math.log(20), math.log(400))) for _ in range(800)]
q2 = [x * 4 if g % 10 == 0 else x for g, x in enumerate(q)]
depth = 100000
a = [poisson(rng, x * depth / sum(q2)) for x in q2]
b = [poisson(rng, x * depth / sum(q)) for x in q]
f = norm_factors([[x, y] for x, y in zip(a, b)])
truth = sum(q) / sum(q2)
assert abs((f[0] / f[1]) / truth - 1) < 0.03
History
Robinson and Oshlack (2010) showed that RNA-seq counts are relative, so that a few very highly expressed genes in one sample lower the counts of all other genes. They proposed the weighted trimmed mean of M-values as the fix, with the trims of 30 and 5 percent. edgeR (Robinson, McCarthy and Smyth 2010) uses the factors to form the effective library sizes. In the same year, Anders and Huber (2010) proposed median of ratios for DESeq, which assumes the same thing in another way.
References
- Mark D. Robinson and Alicia Oshlack, A scaling normalization method for differential expression analysis of RNA-seq data, Genome Biology 11(3) (2010), article R25, the M and A values, the trim of 30 percent of the M values and 5 percent of the A values at each end, the weights from the delta method, and the example of a sample with extra genes
- Mark D. Robinson, Davis J. McCarthy and Gordon K. Smyth, edgeR, a Bioconductor package for differential expression analysis of digital gene expression data, Bioinformatics 26(1) (2010), pages 139 to 140, the effective library size, the library size times the normalization factor, as the offset of the negative binomial model
- Simon Anders and Wolfgang Huber, Differential expression analysis for sequence count data, Genome Biology 11(10) (2010), article R106, the median-of-ratios size factors, the other common answer to the same problem
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 TKHD07 Edit this page History Report an error Markdown