Algorithm Search⌘K

Algorithmcore

Median-of-ratios normalization

Also called DESeq size factors.

Take as the size factor of a sample the median over genes of its count divided by the geometric mean count of that gene across samples.

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
Simon Anders, Wolfgang Huber, 2010

Median-of-ratios normalization finds the size factors of RNA-seq samples, the numbers by which the counts of each sample are divided to make samples comparable. For each gene, it computes the geometric mean of its counts over all samples, a pseudo-reference sample. The size factor of a sample is then the median, over genes, of the ratio of its count to this pseudo-reference. If more than half of the genes do not change between samples, their ratios all point to the true factor, and the median ignores the rest. Anders and Huber (2010) introduced it in DESeq, and it is the default of DESeq2. It is one solution of the library size normalization problem; TMM solves the same problem with a weighted trimmed mean against one real sample in place of the median against a pseudo-reference.

In plain words

Make an average sample by taking, for each gene, the typical count of that gene across all your samples. Now compare each real sample with this average, one gene at a time. If a sample was sequenced twice as deeply, most of its genes will show about twice the average. A few genes will show something else, because they really changed. Take the middle value of all these per-gene comparisons. The genes that changed sit at the ends of the list, so the middle value tells you the depth. Genes that are missing from any sample are left out, because the comparison makes no sense for them.

The problem

Input. A matrix of counts Kgj≥0K_{gj} \ge 0, genes g=1,…,ng = 1, \dots, n in rows and samples j=1,…,mj = 1, \dots, m in columns.

Output. Size factors s^1,…,s^m>0\hat s_1, \dots, \hat s_m > 0, such that Kgj/s^jK_{gj}/\hat s_j is comparable across samples.

Assumption. E[Kgj]=sjqgjE[K_{gj}] = s_jq_{gj}, and qgj=qgq_{gj} = q_g for more than half of the genes that have a positive count in every sample. The factors are defined only up to a common constant. The estimator fixes it so that the factors have geometric mean 1 when the counts are exactly proportional.

The algorithm

  1. MEDIAN-OF-RATIOS(K) ▷ K: n genes by m samples, counts ≥ 0
  2. 1for each gene g do ▷ the log of the pseudo-reference
  3. 2if K[g][j] > 0 for every sample j then
  4. 3ℓ_g ← (1/m) Σ_j ln K[g][j] else ℓ_g ← -∞
  5. 4G ← {g : ℓ_g is finite} ▷ genes with no zero count
  6. 5if G is empty then fail
  7. 6for j ← 1 to m do
  8. 7r ← [ln K[g][j] - ℓ_g for g in G with K[g][j] > 0]
  9. 8ŝ_j ← exp(median(r)) ▷ median of the log ratios
  10. 9return ŝ_1, …, ŝ_m

Lines L1 to L3 compute the log of the geometric mean of each gene, ℓg=1m∑jln⁡Kgj\ell_g = \frac1m\sum_j\ln K_{gj}. A gene with a zero in any sample gets −∞-\infty, since its geometric mean is 0 and no ratio to it is defined. Line L4 keeps the other genes. Line L7 forms the log ratios ln⁡(Kgj/eℓg)\ln(K_{gj}/e^{\ell_g}) of sample jj. The test Kgj>0K_{gj} > 0 there matters only when the reference ℓ\ell comes from other samples, as in the fixed-reference variant below. Line L8 takes the median on the log scale. For an odd number of genes this is the log of the median ratio. For an even number it is the mean of the two middle log ratios, so s^j\hat s_j is the geometric mean of the two middle ratios. DESeq2 does the same.

The factors enter the analysis in two ways. For plots and clustering, the normalized counts are Kgj/s^jK_{gj}/\hat s_j. In the negative binomial model of DESeq2, the raw counts stay as they are and ln⁡s^j\ln\hat s_j is an offset in the log-linear model of the mean.

Example

Five genes in three samples. Samples 1 and 3 have the same depth, and sample 2 is twice as deep. Gene 4 is 10 times higher in sample 3, and gene 5 has a zero.

gene Kg1K_{g1} Kg2K_{g2} Kg3K_{g3} geometric mean ratio 1 ratio 2 ratio 3
1 100 200 100 125.99 0.7937 1.5874 0.7937
2 50 100 50 63.00 0.7937 1.5874 0.7937
3 20 40 20 25.20 0.7937 1.5874 0.7937
4 300 600 3000 814.33 0.3684 0.7368 3.684
5 0 10 5 0

Gene 5 is dropped at line L4. Each sample has four ratios, and three of them are equal, so the median is that value: s^=(0.7937,1.5874,0.7937)\hat s = (0.7937, 1.5874, 0.7937), which is (2−1/3,22/3,2−1/3)(2^{-1/3}, 2^{2/3}, 2^{-1/3}). The product is 1. The ratio s^2/s^1=2\hat s_2/\hat s_1 = 2 is the true depth ratio, and s^3/s^1=1\hat s_3/\hat s_1 = 1.

gene normalized 1 normalized 2 normalized 3
1 126.0 126.0 126.0
4 378.0 378.0 3779.8

The library sizes are 470, 950 and 3175. Dividing by them would make sample 3 look 6.8 times as deep as sample 1, and gene 1 would look 6.8 times lower in sample 3. Gene 4 alone holds 94 percent of the reads of sample 3. This is the composition effect.

Correctness

The proof shows three facts in exact arithmetic. If Kgj=sjqgK_{gj} = s_jq_g for every usable gene, the estimator returns sj/sˉs_j/\bar s, where sˉ\bar s is the geometric mean of the true factors, because every log ratio of sample jj equals ln⁡(sj/sˉ)\ln(s_j/\bar s). If this holds only for a set SS of genes with ∣S∣>∣G∣/2|S| > |G|/2, the answer is the same, because more than half of the log ratios of each sample are equal, and then both middle positions of the sorted list hold that value. The bound ∣S∣>∣G∣/2|S| > |G|/2 cannot be improved. Last, multiplying one sample by cc multiplies its factor relative to every other sample by cc. That real data have a majority of unchanged genes is an assumption, and with Poisson or negative binomial counts the estimate has an error that the tests measure but the proof does not bound.

Proof: Median-of-ratios size factors recover the true factors when more than half of the genes do not changefull

We prove what the median-of-ratios estimator gets right in exact arithmetic. If the counts are exactly proportional, it returns the true size factors divided by their geometric mean (Lemma 1). It keeps this answer when fewer than half of the usable genes change in any way (Theorem 2). It also scales correctly: multiplying one sample by cc multiplies its factor relative to every other sample by cc (Lemma 3). The claim that real data satisfy the assumption of Theorem 2 is a modelling assumption. It is not proved here, and the page labels it as such.

Setting. Counts Kgj≥0K_{gj} \ge 0 for genes g=1,…,ng = 1, \dots, n and samples j=1,…,mj = 1, \dots, m. Let G={g:Kgj>0 for all j}G = \{g : K_{gj} > 0 \text{ for all } j\} be the usable genes, and assume GG is not empty. For g∈Gg \in G, let ℓg=1m∑k=1mln⁡Kgk\ell_g = \frac1m\sum_{k=1}^m \ln K_{gk} be the log of the geometric mean, and let ρgj=ln⁡Kgj−ℓg\rho_{gj} = \ln K_{gj} - \ell_g be the log ratio. The algorithm returns s^j=exp⁡(median⁡g∈Gρgj)\hat s_j = \exp(\operatorname{median}_{g \in G}\rho_{gj}), where the median of an even number of values is the mean of the two middle ones.

Lemma 1 (exact proportional counts). Suppose Kgj=sjqgK_{gj} = s_j q_g with sj>0s_j > 0 and qg>0q_g > 0 for every g∈Gg \in G and every jj. Then s^j=sj/sˉ\hat s_j = s_j / \bar s, where sˉ=(∏ksk)1/m\bar s = (\prod_k s_k)^{1/m} is the geometric mean of the true factors.

Proof. For g∈Gg \in G, ℓg=ln⁡qg+1m∑kln⁡sk=ln⁡qg+ln⁡sˉ\ell_g = \ln q_g + \frac1m\sum_k \ln s_k = \ln q_g + \ln\bar s. So ρgj=ln⁡sj+ln⁡qg−ln⁡qg−ln⁡sˉ=ln⁡(sj/sˉ)\rho_{gj} = \ln s_j + \ln q_g - \ln q_g - \ln\bar s = \ln(s_j/\bar s). This does not depend on gg, so every value in the median at line L8 equals ln⁡(sj/sˉ)\ln(s_j/\bar s), and so does the median. □\square

The factors are identified only up to one common constant. This is unavoidable, because the counts Kgj=sjqgK_{gj} = s_j q_g do not change when every sjs_j is multiplied by cc and every qgq_g is divided by cc. The estimator fixes the constant by making the factors have geometric mean 1 in the exact case.

Theorem 2 (robustness to a minority of changed genes). Let S⊆GS \subseteq G be a set of genes with Kgj=sjqgK_{gj} = s_j q_g for g∈Sg \in S and all jj, and suppose ∣S∣>∣G∣/2|S| > |G|/2. The other genes of GG may have any positive counts. Then s^j=sj/sˉ\hat s_j = s_j/\bar s for every jj.

Proof. For g∈Sg \in S the computation of Lemma 1 holds gene by gene, because it uses only the counts of gg: ρgj=ln⁡(sj/sˉ)\rho_{gj} = \ln(s_j/\bar s). So for each sample jj, more than half of the values ρgj\rho_{gj}, g∈Gg \in G, are equal to the same number cj=ln⁡(sj/sˉ)c_j = \ln(s_j/\bar s).

Now use a fact about medians. Let x(1)≤⋯≤x(N)x_{(1)} \le \dots \le x_{(N)} be sorted values, and suppose more than N/2N/2 of them equal cc. The values equal to cc fill one block of consecutive positions a,…,ba, \dots, b with b−a+1>N/2b - a + 1 > N/2. Fewer than N/2N/2 positions lie before the block and fewer than N/2N/2 lie after it, so a−1<N/2a - 1 < N/2 and N−b<N/2N - b < N/2. If NN is odd, these give a≤(N+1)/2≤ba \le (N+1)/2 \le b, so the middle position is in the block. If NN is even, they give a≤N/2a \le N/2 and b≥N/2+1b \ge N/2 + 1, so both middle positions are in the block. In both cases the median is cc.

Hence median⁡g∈Gρgj=cj\operatorname{median}_{g \in G}\rho_{gj} = c_j and s^j=sj/sˉ\hat s_j = s_j/\bar s for every jj. □\square

So the constant is the same as in Lemma 1: the changed genes change neither the relative factors s^j/s^k=sj/sk\hat s_j/\hat s_k = s_j/s_k nor their common scale. The bound ∣S∣>∣G∣/2|S| > |G|/2 is the breakdown point of the median, and it cannot be improved in general: if exactly half of the genes are changed, they can all have ρgj\rho_{gj} equal to a value cj′≠cjc_j' \ne c_j, and the median of an even number of values is then (cj+cj′)/2(c_j + c_j')/2.

Lemma 3 (scale equivariance). Let K′K' be KK with sample j0j_0 multiplied by c>0c > 0, and let s^′\hat s' be the factors of K′K'. Then s^j0′/s^k′=c s^j0/s^k\hat s'_{j_0}/\hat s'_k = c\,\hat s_{j_0}/\hat s_k for every k≠j0k \ne j_0.

Proof. The set GG does not change, because c>0c > 0. For g∈Gg \in G, ℓg′=ℓg+1mln⁡c\ell'_g = \ell_g + \frac1m\ln c. So ρgj′=ρgj−1mln⁡c\rho'_{gj} = \rho_{gj} - \frac1m\ln c for j≠j0j \ne j_0, and ρgj0′=ρgj0+ln⁡c−1mln⁡c\rho'_{gj_0} = \rho_{gj_0} + \ln c - \frac1m\ln c. Subtracting a constant from every value subtracts it from the median, so ln⁡s^k′=ln⁡s^k−1mln⁡c\ln\hat s'_k = \ln\hat s_k - \frac1m\ln c and ln⁡s^j0′=ln⁡s^j0+(1−1m)ln⁡c\ln\hat s'_{j_0} = \ln\hat s_{j_0} + (1 - \frac1m)\ln c. The difference is ln⁡s^j0′−ln⁡s^k′=ln⁡s^j0−ln⁡s^k+ln⁡c\ln\hat s'_{j_0} - \ln\hat s'_k = \ln\hat s_{j_0} - \ln\hat s_k + \ln c. □\square

So sequencing a sample twice as deeply doubles its factor relative to the others, which is what a size factor must do.

What the lines compute. Lines L1 to L3 compute ℓg\ell_g for g∈Gg \in G, and the code marks the other genes with −∞-\infty. Line L4 forms GG, and line L5 fails when GG is empty, since then no ratio is defined. Lines L6 to L8 compute s^j\hat s_j. The median at line L8 is the median of the log ratios, so for an even ∣G∣|G| it is the log of the geometric mean of the two middle ratios. This is the definition used in the proofs above, and it equals the median of the ratios themselves when ∣G∣|G| is odd, because exp⁡\exp is increasing.

Complexity. Lines L1 to L4 read each count once, which is Θ(nm)\Theta(nm) time. Line L8 uses a sort, so the medians take O(m ∣G∣log⁡∣G∣)O(m\,|G|\log|G|) time; a linear-time selection such as quickselect makes this O(m ∣G∣)O(m\,|G|) expected. The extra space is Θ(n)\Theta(n).

What the tests check. The test file checks Lemma 1 on random factors, Theorem 2 with up to ∣S∣−1|S| - 1 changed genes of random size, Lemma 3 with four scale constants, and the page example. It also compares the code with a brute force that works on the plain ratio scale and sorts, and it measures the error on Poisson counts. That last check is a measurement, not a theorem.

Complexity

On a real RAM, lines L1 to L4 read each count once, which takes Θ(nm)\Theta(nm) time. The medians at line L8 take O(∣G∣log⁡∣G∣)O(|G|\log|G|) time per sample with sorting, so the total is Θ(nmlog⁡n)\Theta(nm\log n) in the worst case. A linear-time selection such as quickselect or median of medians lowers this to O(nm)O(nm). The extra space is Θ(n)\Theta(n) for the ℓg\ell_g and one list of ratios.

Properties

  • Robust to a minority of changed genes. Up to half of the usable genes, less one, can change by any amount without moving the factors. This is the breakdown point of the median.
  • Scale equivariant. Doubling all counts of one sample doubles its factor relative to the others.
  • Symmetric in the samples. The pseudo-reference uses all samples equally, so the result does not depend on the order of the samples or on the choice of a reference sample.
  • Normalized to geometric mean 1. In the exact case the factors multiply to 1. With real counts they are close to that.
  • Uses only genes seen in every sample. This makes it unusable when most counts are 0, as in single-cell data.

Variants and improvements

  • Fixed reference. Compute ℓg\ell_g once from a reference set of samples and pass it in, so that new samples get factors on the same scale without changing the old ones. The code accepts this as an argument.
  • Control genes. Compute the medians only over genes known not to change, such as spike-ins or housekeeping genes. DESeq2 has an argument for this.
  • Positive counts. For data with many zeros, DESeq2 has a type "poscounts", which takes the geometric mean over the positive counts only, so that fewer genes are dropped.
  • Pooling. For single cells, pooling size factors sums cells into pools, applies median of ratios to the pools, and solves for the cell factors.
  • Gene-specific factors. When length or GC bias differs between samples, DESeq2 takes a matrix of normalization factors sgjs_{gj} in place of the vector.
  • Trimmed mean. TMM replaces the median by a weighted trimmed mean of the log ratios, and the pseudo-reference by one real sample.

When to use it

Use it on bulk RNA-seq counts when you expect most genes not to change, and when most genes have positive counts in every sample. It is the default of DESeq2, and the factors are meant for its model. For single-cell data use pooling. When you expect a global shift, such as a general loss of transcription in one condition, no method of this kind can see it; use spike-ins. When you need the whole distribution to match, as for microarrays, use quantile normalization, which makes a stronger assumption.

Pitfalls

  • Dropping too many genes. One zero in one sample removes a gene. With many samples, or with low depth, few genes may be left, and the factors become noisy.
  • Many changes in one direction. If 40 percent of the genes go up in one condition, the median is still right in exact arithmetic, but with noise it moves toward the changed genes. Check the plot of log ratios against the mean: the unchanged genes should form a band at the line of the factor.
  • Normalized counts as input. DESeq2 and edgeR need raw counts. Passing them Kgj/s^jK_{gj}/\hat s_j breaks the variance model, because the variance of a count depends on its size.
  • Size factor is not library size. The factors are relative and have geometric mean about 1. They are not the number of reads. Mixing them with the total counts of another method gives wrong offsets.
  • Low-count genes. Genes with counts of 1 or 2 have very noisy ratios. They rarely move the median, but filtering them first does no harm.

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)
median_of_ratios_normalization.py 72 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/median-of-ratios-normalization/. The authors are listed in prov/NF2283.jsonl.
"""Median-of-ratios size factors (Anders and Huber 2010, DESeq and DESeq2).

counts is a list of rows, one row per gene and one column per sample. The
size factor of sample j is

    s_j = median over genes g in G of K[g][j] / geomean_k K[g][k],

where G is the set of genes with a positive count in every sample. The
median is taken on the log scale, so for an even number of genes it is the
geometric mean of the two middle ratios. This is what DESeq2 does in
estimateSizeFactorsForMatrix with its default settings.

A fixed reference can be given as log_geo_means (one value per gene, with
-inf or None for a gene that must not be used); then only the samples to be
scaled need to be in counts.
"""

from __future__ import annotations

import math
from statistics import median
from typing import List, Optional, Sequence


def log_geometric_means(counts: Sequence[Sequence[float]]) -> List[float]:
    """The mean of log K[g][j] over the samples j, or -inf when a count is 0."""
    out = []
    for row in counts:
        if len(row) == 0:
            raise ValueError("every gene needs at least one sample")
        if any(k < 0 for k in row):
            raise ValueError("counts must be >= 0")
        if all(k > 0 for k in row):  # @line L2
            out.append(sum(math.log(k) for k in row) / len(row))  # @line L3
        else:
            out.append(-math.inf)
    return out


def size_factors(counts: Sequence[Sequence[float]],
                 log_geo_means: Optional[Sequence[Optional[float]]] = None) -> List[float]:
    """The median-of-ratios size factors, one per sample (column)."""
    if not counts:
        raise ValueError("need at least one gene")
    m = len(counts[0])
    if any(len(row) != m for row in counts):
        raise ValueError("every gene needs the same number of samples")
    if log_geo_means is None:
        lg = log_geometric_means(counts)  # @line L1
    else:
        if len(log_geo_means) != len(counts):
            raise ValueError("need one reference value per gene")
        lg = [-math.inf if v is None else float(v) for v in log_geo_means]
    use = [g for g in range(len(counts)) if math.isfinite(lg[g])]  # @line L4
    if not use:  # @line L5
        raise ValueError("no gene has a positive count in every sample")
    s = []
    for j in range(m):  # @line L6
        r = [math.log(counts[g][j]) - lg[g] for g in use if counts[g][j] > 0]  # @line L7
        if not r:
            raise ValueError("sample %d has no usable gene" % j)
        s.append(math.exp(median(r)))  # @line L8
    return s  # @line L9


def normalized_counts(counts: Sequence[Sequence[float]],
                      factors: Optional[Sequence[float]] = None) -> List[List[float]]:
    """K[g][j] / s_j, with the median-of-ratios factors unless others are given."""
    s = size_factors(counts) if factors is None else list(factors)
    return [[row[j] / s[j] for j in range(len(s))] for row in counts]
test_median_of_ratios_normalization.py 144 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/median-of-ratios-normalization/. The authors are listed in prov/NF2283.jsonl.

import math
import random

import pytest

from biostoch import poisson
from median_of_ratios_normalization import log_geometric_means, normalized_counts, size_factors

PAGE = [
    [100, 200, 100],
    [50, 100, 50],
    [20, 40, 20],
    [300, 600, 3000],
    [0, 10, 5],
]


def close(a, b, rel=1e-12):
    return all(math.isclose(x, y, rel_tol=rel) for x, y in zip(a, b, strict=True))


def geomean(xs):
    return math.exp(sum(math.log(x) for x in xs) / len(xs))


def brute_force(counts):
    """Ratios on the plain scale, an explicit sort, and the median of the middle one or two."""
    m = len(counts[0])
    rows = [row for row in counts if all(k > 0 for k in row)]
    out = []
    for j in range(m):
        ratios = sorted(row[j] / math.prod(row) ** (1.0 / m) for row in rows)
        n = len(ratios)
        if n % 2:
            out.append(ratios[n // 2])
        else:
            out.append(math.sqrt(ratios[n // 2 - 1] * ratios[n // 2]))
    return out


def test_page_example():
    s = size_factors(PAGE)
    assert close(s, [2 ** (-1 / 3), 2 ** (2 / 3), 2 ** (-1 / 3)])
    assert math.isinf(log_geometric_means(PAGE)[4])


def test_exact_product_form_gives_factors_over_their_geometric_mean():
    rng = random.Random(11)
    for _ in range(50):
        m = rng.randint(2, 6)
        n = rng.randint(1, 30)
        s = [rng.uniform(0.2, 5.0) for _ in range(m)]
        q = [rng.uniform(1.0, 1000.0) for _ in range(n)]
        counts = [[s[j] * q[g] for j in range(m)] for g in range(n)]
        g = geomean(s)
        assert close(size_factors(counts), [x / g for x in s], rel=1e-10)


def test_matches_brute_force_on_random_counts():
    rng = random.Random(12)
    for _ in range(200):
        m = rng.randint(1, 5)
        n = rng.randint(1, 25)
        counts = [[rng.randint(0, 50) for _ in range(m)] for _ in range(n)]
        if not any(all(k > 0 for k in row) for row in counts):
            with pytest.raises(ValueError):
                size_factors(counts)
            continue
        assert close(size_factors(counts), brute_force(counts), rel=1e-9)


def test_a_majority_of_unchanged_genes_fixes_the_factors():
    rng = random.Random(13)
    s = [0.5, 1.0, 3.0]
    for _ in range(100):
        stable = rng.randint(3, 12)
        changed = rng.randint(0, stable - 1)
        counts = []
        for _ in range(stable):
            q = rng.uniform(5, 500)
            counts.append([s[j] * q for j in range(3)])
        for _ in range(changed):
            counts.append([rng.uniform(1, 5000) for _ in range(3)])
        rng.shuffle(counts)
        g = geomean(s)
        assert close(size_factors(counts), [x / g for x in s], rel=1e-10)


def test_scaling_one_sample_scales_its_ratio_to_the_others():
    rng = random.Random(14)
    for _ in range(50):
        counts = [[rng.randint(1, 100) for _ in range(4)] for _ in range(rng.randint(1, 20))]
        c = rng.choice([0.25, 2.0, 3.0, 10.0])
        scaled = [row[:2] + [row[2] * c] + row[3:] for row in counts]
        a = size_factors(counts)
        b = size_factors(scaled)
        for j in (0, 1, 3):
            assert math.isclose((b[2] / b[j]) / (a[2] / a[j]), c, rel_tol=1e-10)


def test_fixed_reference_scales_new_samples_the_same_way():
    rng = random.Random(15)
    counts = [[rng.randint(1, 200) for _ in range(5)] for _ in range(40)]
    lg = log_geometric_means(counts)
    full = size_factors(counts)
    part = size_factors([row[1:3] for row in counts], log_geo_means=lg)
    assert close(part, full[1:3])


def test_normalized_counts_divide_by_the_factors():
    s = size_factors(PAGE)
    nc = normalized_counts(PAGE)
    for g, row in enumerate(PAGE):
        assert close(nc[g], [row[j] / s[j] for j in range(3)])
    assert close(nc[0], [100 * 2 ** (1 / 3)] * 3)


def test_errors():
    with pytest.raises(ValueError):
        size_factors([])
    with pytest.raises(ValueError):
        size_factors([[0, 1], [3, 0]])
    with pytest.raises(ValueError):
        size_factors([[1, 2], [3]])
    with pytest.raises(ValueError):
        size_factors([[1, -2]])


def test_poisson_counts_measurement():
    # A measurement, not a theorem: with Poisson counts of mean s_j q_g and
    # q_g from 50 to 1000, the factors come within 3 percent of s / geomean(s).
    rng = random.Random(16)
    s = [0.5, 1.0, 2.0, 4.0]
    counts = []
    for _ in range(600):
        q = math.exp(rng.uniform(math.log(50), math.log(1000)))
        counts.append([poisson(rng, s[j] * q) for j in range(4)])
    g = geomean(s)
    est = size_factors(counts)
    for j in range(4):
        assert abs(est[j] / (s[j] / g) - 1) < 0.03

History

Anders and Huber (2010) introduced the size factors in DESeq, with the motivation that the total count is dominated by a few highly expressed genes. In the same year, Robinson and Oshlack (2010) described the composition effect and proposed TMM. Love, Huber and Anders (2014) kept median of ratios as the default of DESeq2 and allowed gene-specific factors in its place.

References

  1. Simon Anders and Wolfgang Huber, Differential expression analysis for sequence count data, Genome Biology 11(10) (2010), article R106, the size factor estimator, the median over genes of the ratio of a count to the geometric mean of its gene over all samples
  2. Michael I. Love, Wolfgang Huber and Simon Anders, Moderated estimation of fold change and dispersion for RNA-seq data with DESeq2, Genome Biology 15(12) (2014), article 550, the size factors as offsets of the negative binomial GLM, and the gene-specific normalization factors
  3. 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 composition effect that makes the total count a poor size factor

Where this leads

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