Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
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 ogo_g of a sample and rgr_g of a reference sample for genes g=1,…,ng = 1, \dots, n, with library sizes No=∑gogN_o = \sum_g o_g and Nr=∑grgN_r = \sum_g r_g, and the trim fractions θM=0.3\theta_M = 0.3 and θA=0.05\theta_A = 0.05.

Output. A factor f>0f > 0 such that NofN_of and NrN_r are comparable library sizes: for an unchanged gene, og/(Nof)≈rg/Nro_g/(N_of) \approx r_g/N_r. For mm 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

  1. TMM(o, r, N_o, N_r, θ_M = 0.3, θ_A = 0.05) ▷ sample o against reference r
  2. 1keep the genes with o_g > 0 and r_g > 0, and let n be their number
  3. 2M_g ← log2((o_g / N_o) / (r_g / N_r)) ▷ log ratio of the shares
  4. 3A_g ← (log2(o_g / N_o) + log2(r_g / N_r)) / 2 ▷ mean log share
  5. 4v_g ← (N_o - o_g)/(N_o o_g) + (N_r - r_g)/(N_r r_g) ▷ approximate variance of M_g
  6. 5λ_M ← ⌊n θ_M⌋ + 1; λ_A ← ⌊n θ_A⌋ + 1
  7. 6rank the M_g and the A_g, with average ranks for ties
  8. 7K ← {g : λ_M ≤ rank(M_g) ≤ n + 1 - λ_M and λ_A ≤ rank(A_g) ≤ n + 1 - λ_A}
  9. 8f ← (Σ_{g ∈ K} M_g / v_g) / (Σ_{g ∈ K} 1 / v_g)
  10. 9return 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 (Ag,Mg)(A_g, M_g) of the MA plot. Line L4 is the delta method variance of MgM_g when each count is binomial given its library size: Var⁡(ln⁡p^)≈(1−p)/(Np)\operatorname{Var}(\ln\hat p) \approx (1-p)/(Np) for a share p^\hat p of NN reads, and the constant (ln⁡2)2(\ln 2)^2 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 [λM,n+1−λM][\lambda_M, n + 1 - \lambda_M] and whose A rank lies inside [λA,n+1−λA][\lambda_A, n + 1 - \lambda_A]. 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 ∣Mg∣<10−6|M_g| < 10^{-6}, as edgeR does.

For mm 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 NjfjN_jf_j is then the offset of the negative binomial model.

Example

Ten genes, a sample o with No=2503N_o = 2503 and a reference r with Nr=1260N_r = 1260. Genes 5 and 10 are much higher in o, and gene 7 is lower. With n=10n = 10, λM=⌊3⌋+1=4\lambda_M = \lfloor 3\rfloor + 1 = 4, so the M ranks 4 to 7 are kept, and λA=⌊0.5⌋+1=1\lambda_A = \lfloor 0.5\rfloor + 1 = 1, so no gene is trimmed by A.

gene ogo_g rgr_g MgM_g AgA_g vgv_g 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 6/56/5, so their M values tie and share the rank 6.5. The weighted mean of the four kept M values is f=−0.769f = -0.769, and the factor is 2−0.769=0.5872^{-0.769} = 0.587. The unweighted mean gives 0.591. The raw library sizes say that o is 1.99 times as deep as r. The effective sizes 2503⋅0.5872503 \cdot 0.587 and 12601260 say 1.17 times, which matches the count ratios og/rgo_g/r_g 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 ff into −f-f, because the average ranks of −M-M are n+1n + 1 minus those of MM and the kept interval is symmetric. It shows that genes with M values below m−m_- or above m+m_+ cannot be kept if there are at most λM−1\lambda_M - 1 of each, so the factor stays in [2m−,2m+][2^{m_-}, 2^{m_+}]. And it shows that if all other genes share exactly the same M value mm, the factor is exactly 2m2^m, 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 1/21/2 by this result. That the weights 1/vg1/v_g 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 mm, the factor is exactly 2m2^m (Theorem 4). The weights 1/vg1/v_g come from a delta-method approximation of the variance of MgM_g. 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 ogo_g and rgr_g and library sizes No,Nr>0N_o, N_r > 0. Line L1 keeps the genes with og>0o_g > 0 and rg>0r_g > 0; let nn be their number. For these genes,

Mg=log⁡2og/Norg/Nr,Ag=12(log⁡2ogNo+log⁡2rgNr),vg=No−ogNo og+Nr−rgNr rg.M_g = \log_2\frac{o_g/N_o}{r_g/N_r}, \quad A_g = \tfrac12\left(\log_2\frac{o_g}{N_o} + \log_2\frac{r_g}{N_r}\right), \quad v_g = \frac{N_o - o_g}{N_o\,o_g} + \frac{N_r - r_g}{N_r\,r_g}.

We assume og<Noo_g < N_o or rg<Nrr_g < N_r, so that vg>0v_g > 0. With trim fractions θM=0.3\theta_M = 0.3 and θA=0.05\theta_A = 0.05, let λM=⌊nθM⌋+1\lambda_M = \lfloor n\theta_M\rfloor + 1, ηM=n+1−λM\eta_M = n + 1 - \lambda_M, and λA,ηA\lambda_A, \eta_A the same with θA\theta_A. Ranks are average ranks: a block of tt tied values that follows uu smaller values gets rank u+(t+1)/2u + (t+1)/2. The kept set is K={g:λM≤rank⁡(Mg)≤ηM, λA≤rank⁡(Ag)≤ηA}\mathcal K = \{g : \lambda_M \le \operatorname{rank}(M_g) \le \eta_M,\ \lambda_A \le \operatorname{rank}(A_g) \le \eta_A\}, and

f=∑g∈KMg/vg∑g∈K1/vg,factor=2f.f = \frac{\sum_{g \in \mathcal K} M_g/v_g}{\sum_{g \in \mathcal K} 1/v_g}, \qquad \text{factor} = 2^f.

The code returns 1 when K\mathcal K is empty, when no gene is left after line L1, or when every ∣Mg∣<10−6|M_g| < 10^{-6}, as edgeR does.

Lemma 1 (what the lines compute). Lines L1 to L4 compute MgM_g, AgA_g and vgv_g for the genes with two positive counts. Line L5 computes the four rank bounds. Line L6 computes average ranks, line L7 forms K\mathcal K, and lines L8 and L9 return 2f2^f.

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, (i+j)/2+1(i + j)/2 + 1 for 0-based positions i,…,ji, \dots, j. This is u+(t+1)/2u + (t+1)/2 with u=iu = i and t=j−i+1t = j - i + 1. □\square

Lemma 2 (antisymmetry). Let f′f' be the value of ff with the roles of obs and ref swapped. Then f′=−ff' = -f, so the two factors multiply to 1.

Proof. The swap keeps the same genes at line L1 and the same nn, so the same bounds. It maps MgM_g to −Mg-M_g and keeps AgA_g and vgv_g. Negating all values reverses the sorted order. A block of tt tied values that had uu smaller values now has n−u−tn - u - t smaller values, so its new rank is n−u−t+(t+1)/2=n+1−(u+(t+1)/2)n - u - t + (t+1)/2 = n + 1 - (u + (t+1)/2). So rank⁡′(Mg)=n+1−rank⁡(Mg)\operatorname{rank}'(M_g) = n + 1 - \operatorname{rank}(M_g). The interval [λM,ηM][\lambda_M, \eta_M] is symmetric under x↦n+1−xx \mapsto n + 1 - x, because ηM=n+1−λM\eta_M = n + 1 - \lambda_M. Hence the kept set is the same, and f′=∑K(−Mg)/vg/∑K1/vg=−ff' = \sum_{\mathcal K}(-M_g)/v_g \big/ \sum_{\mathcal K}1/v_g = -f. □\square

In floating point, log⁡2(x/y)\log_2(x/y) and −log⁡2(y/x)-\log_2(y/x) 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 m−≤m+m_- \le m_+, and split the genes into L={g:Mg<m−}L = \{g : M_g < m_-\}, S={g:m−≤Mg≤m+}S = \{g : m_- \le M_g \le m_+\} and H={g:Mg>m+}H = \{g : M_g > m_+\}. If ∣L∣≤λM−1|L| \le \lambda_M - 1 and ∣H∣≤λM−1|H| \le \lambda_M - 1, then K⊆S\mathcal K \subseteq S. If moreover K\mathcal K is not empty, then m−≤f≤m+m_- \le f \le m_+.

Proof. Every value of LL is smaller than every value outside LL, so the genes of LL fill the first ∣L∣|L| sorted positions, and their average ranks lie between 1 and ∣L∣≤λM−1|L| \le \lambda_M - 1. In the same way the genes of HH fill the last ∣H∣|H| positions, and their ranks are at least n−∣H∣+1≥n+2−λM=ηM+1n - |H| + 1 \ge n + 2 - \lambda_M = \eta_M + 1. So no gene of LL or HH passes the rank test of line L7, and K⊆S\mathcal K \subseteq S. Then ff is a mean of values in [m−,m+][m_-, m_+] with positive weights 1/vg1/v_g, so it lies in [m−,m+][m_-, m_+]. □\square

Theorem 4 (a majority with one common ratio). Use the default trims θM=0.3\theta_M = 0.3 and θA=0.05\theta_A = 0.05. Suppose the genes of SS all have Mg=mM_g = m exactly, and ∣L∣,∣H∣≤λM−1|L|, |H| \le \lambda_M - 1 as in Lemma 3 with m−=m+=mm_- = m_+ = m. Then K\mathcal K is not empty and f=mf = m, so the factor is 2m2^m. (The early return of the code when every ∣Mg∣<10−6|M_g| < 10^{-6} gives 1 instead, which differs from 2m2^m by less than 10−610^{-6} in the exponent.)

Proof. By Lemma 3 it is enough to show that K\mathcal K is not empty. The genes of SS form one tie block after the ∣L∣|L| genes of LL, so they all have the rank ρ=∣L∣+(∣S∣+1)/2\rho = |L| + (|S| + 1)/2. With ∣S∣=n−∣L∣−∣H∣|S| = n - |L| - |H|, this is ρ=(n+1+∣L∣−∣H∣)/2\rho = (n + 1 + |L| - |H|)/2. Since ∣H∣≤λM−1|H| \le \lambda_M - 1, ρ≥(n+2−λM)/2\rho \ge (n + 2 - \lambda_M)/2, and this is at least λM\lambda_M when 3λM≤n+23\lambda_M \le n + 2. In the same way ρ≤ηM\rho \le \eta_M when 3λM≤n+23\lambda_M \le n + 2. For θM=0.3\theta_M = 0.3, 3λM≤0.9n+3≤n+23\lambda_M \le 0.9n + 3 \le n + 2 when n≥10n \ge 10, and for n=1,…,9n = 1, \dots, 9 the values λM=1,1,1,2,2,2,3,3,3\lambda_M = 1, 1, 1, 2, 2, 2, 3, 3, 3 satisfy 3λM≤n+23\lambda_M \le n + 2 one by one. So every gene of SS passes the M test.

The A test removes at most the λA−1\lambda_A - 1 lowest and the λA−1\lambda_A - 1 highest A ranks, so at most 2(λA−1)≤2nθA=0.1n2(\lambda_A - 1) \le 2n\theta_A = 0.1n genes. But ∣S∣≥n−2(λM−1)≥n−0.6n=0.4n>0.1n|S| \ge n - 2(\lambda_M - 1) \ge n - 0.6n = 0.4n > 0.1n (for n≥1n \ge 1, ∣S∣≥1|S| \ge 1 because 2(λM−1)≤0.6n<n2(\lambda_M - 1) \le 0.6n < n). So some gene of SS passes both tests, and K≠∅\mathcal K \ne \emptyset. □\square

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 NN. Then the TMM factor of A against B is 1/21/2.

Proof. The genes that B does not express have rg=0r_g = 0 and are dropped at line L1. For the shared genes, A has half of B's count share, og/N=12rg/No_g/N = \frac12 r_g/N, so Mg=−1M_g = -1 for every gene left. This is Theorem 4 with L=H=∅L = H = \emptyset and m=−1m = -1. □\square

The effective library size of A is then N/2N/2: 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 SS into two blocks of slightly different values. Each block gets its own average rank, and both can fall outside [λM,ηM][\lambda_M, \eta_M]. Then K\mathcal K is empty and the code, like edgeR, returns 1. The tests contain such a case. With a small spread in the M values of SS, no ties occur, and Lemma 3 applies.

Normalization over many samples. norm_factors computes fjf_j for every sample against one reference sample and divides by (∏jfj)1/m(\prod_j f_j)^{1/m}. 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 Θ(n)\Theta(n) time and the two rankings take Θ(nlog⁡n)\Theta(n\log n). With mm samples, norm_factors takes Θ(nmlog⁡n)\Theta(n m\log n) time, plus Θ(nmlog⁡n)\Theta(nm\log n) for the upper quartiles. The extra space is Θ(n)\Theta(n) per factor.

Complexity

On a real RAM, lines L1 to L4 take Θ(n)\Theta(n) time, and the two rankings at line L6 take Θ(nlog⁡n)\Theta(n\log n). So one factor costs Θ(nlog⁡n)\Theta(n\log n), and the factors of mm samples against one reference cost Θ(nmlog⁡n)\Theta(nm\log n), plus Θ(nmlog⁡n)\Theta(nm\log n) for the upper quartiles that choose the reference. The extra space is Θ(n)\Theta(n).

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 λM−1\lambda_M - 1 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 mm 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 vgv_g 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 θM\theta_M and θA\theta_A 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 θM\theta_M 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 log⁡2\log_2 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.

biostoch.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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.

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