Algorithm Search⌘K

Algorithmcore

Moderated t-statistic

Also called limma moderated t-test.

A t-test whose gene-wise variance is shrunk toward a common prior by empirical Bayes, which gains power with few samples.

Time
Θ(n m + n log n) worst · best
Space
Θ(n) extra
Where
m = the number of samples; n = the number of genes
Properties
deterministicnot exactofflineiterative
Origin
Gordon K. Smyth, 2004

The moderated t-statistic is a t-test for one gene among thousands, in which the sample variance of the gene is replaced by a weighted mean of that variance and a prior variance estimated from all genes. With three samples per group, the sample variance of one gene has only 4 degrees of freedom, so it is often far too small or far too large, and the ordinary t-test ranks genes poorly. Smyth (2004) put a scaled inverse chi-squared prior on the gene variances, estimated its two parameters from the variances of all genes, and showed that, with the prior known, the statistic has an exact tt distribution with d0+dd_0 + d degrees of freedom under the null hypothesis, where d0d_0 is the prior degrees of freedom. This is empirical Bayes with a conjugate prior. It is the core of limma, for microarrays and, with voom weights, for RNA-seq. Dispersion shrinkage applies the same idea to the dispersion of a negative binomial model, where there is no conjugate prior and no exact null distribution.

In plain words

To decide whether a gene changed, you compare the difference between the groups with the spread of the gene's values. With three samples per group, that spread is a poor guess: by chance it can come out almost zero, which makes a tiny difference look very significant, or very large, which hides a real change. The moderated t-test also looks at how much a typical gene spreads, using all the genes. It then uses a mix of the gene's own spread and the typical spread. The fewer samples you have, the more the typical value counts. Because the mix contains more information, the test also counts it as if it had more samples, which gives it more power.

The problem

Input. For each gene g=1,…,ng = 1, \dots, n, its values in two groups of samples, mm samples in all, on a log scale such as log intensities or log counts per million.

Output. For each gene, a statistic t~g\tilde t_g and a two-sided p-value, and the prior parameters d0d_0 and s02s_0^2.

Model. The difference of the group means is β^g∼N(βg,vσg2)\hat\beta_g \sim N(\beta_g, v\sigma_g^2), with v=1/mA+1/mBv = 1/m_A + 1/m_B. The pooled sample variance is sg2∼σg2χd2/ds_g^2 \sim \sigma_g^2\chi^2_d/d, with d=m−2d = m - 2, independent of β^g\hat\beta_g. The prior is 1/σg2∼χd02/(d0s02)1/\sigma_g^2 \sim \chi^2_{d_0}/(d_0s_0^2). In limma the same holds for any coefficient or contrast of a linear model per gene.

The algorithm

  1. MODERATED-T(A, B) ▷ values of each gene in groups A and B
  2. 1for each gene g: β̂_g ← mean_A - mean_B; s²_g ← pooled variance on d = m - 2 df; v ← 1/m_A + 1/m_B
  3. 2e_g ← ln s²_g - ψ(d/2) + ln(d/2) ▷ ψ: digamma
  4. 3ē ← mean of e; w ← sample variance of e - ψ'(d/2) ▷ ψ': trigamma
  5. 4if w > 0 then d₀ ← 2 ψ'⁻¹(w); s₀² ← exp(ē + ψ(d₀/2) - ln(d₀/2))
  6. 5else d₀ ← ∞; s₀² ← mean of s²
  7. 6for each gene g: s̃²_g ← (d₀ s₀² + d s²_g) / (d₀ + d) ▷ s₀² if d₀ = ∞
  8. 7t̃_g ← β̂_g / (s̃_g √v)
  9. 8p_g ← 2 P(T > |t̃_g|), with T ~ t on min(d₀ + d, n d) df
  10. 9return t̃, p, d₀, s₀²

Line L1 computes the usual statistics of each gene. Lines L2 to L5 estimate the prior by the method of moments on the log variances, as limma's fitFDist does without a covariate. Under the model, ln⁡sg2=ln⁡s02+ln⁡(χd2/d)−ln⁡(χd02/d0)\ln s_g^2 = \ln s_0^2 + \ln(\chi^2_d/d) - \ln(\chi^2_{d_0}/d_0), whose mean and variance are given by the digamma and trigamma functions. Line L2 removes the known mean of the χd2\chi^2_d part, and line L3 removes its known variance, so what is left of the variance belongs to the prior, and ψ′(d0/2)=w\psi'(d_0/2) = w fixes d0d_0. If the observed variance of the ege_g is no larger than the sampling variance alone, the data are consistent with one common variance, and line L5 sets d0=∞d_0 = \infty. Line L6 is the posterior variance, a weighted mean of s02s_0^2 and sg2s_g^2 with weights d0d_0 and dd. Lines L7 and L8 form the statistic and its p-value. The cap ndnd on the degrees of freedom at line L8 follows limma: the prior cannot carry more information than all genes together. Before the logs, the code raises each sg2s_g^2 to at least 10−510^{-5} times their median, so that a zero variance does not give ln⁡0\ln 0.

Example

Three genes, three samples per group, so d=4d = 4 and v=2/3v = 2/3. Take the prior as given, d0=4d_0 = 4 and s02=0.05s_0^2 = 0.05, as if it had been estimated from many genes. The total degrees of freedom are 8.

gene group A group B β^g\hat\beta_g sg2s_g^2 s~g2\tilde s_g^2 t p t~g\tilde t_g p~g\tilde p_g
1 5.1, 5.3, 5.2 4.6, 4.7, 4.8 0.5 0.01 0.03 6.12 0.0036 3.54 0.0077
2 7, 8, 9 6, 7.5, 6.6 1.3 0.785 0.4175 1.80 0.147 2.46 0.0391
3 3, 3.05, 2.95 2.6, 2.7, 2.65 0.35 0.0025 0.02625 8.57 0.0010 2.65 0.0294

For gene 1, s~12=(4⋅0.05+4⋅0.01)/8=0.03\tilde s_1^2 = (4 \cdot 0.05 + 4 \cdot 0.01)/8 = 0.03 and t~1=0.5/0.03⋅2/3=3.54\tilde t_1 = 0.5/\sqrt{0.03 \cdot 2/3} = 3.54. The ordinary t-test ranks gene 3 first, because its values happen to be very close; its variance of 0.0025 is a twentieth of the prior. The moderated test raises it to 0.02625 and ranks gene 3 below gene 1. Gene 2 has a large variance, which the prior lowers, so its p-value falls from 0.147 to 0.039. Each moderated p-value uses 8 degrees of freedom instead of 4.

Correctness

The proof shows that, given the data of a gene, the precision 1/σg21/\sigma_g^2 has a gamma posterior whose mean is 1/s~g21/\tilde s_g^2, which is the formula of line L6. It then proves the main theorem: when βg=0\beta_g = 0 and the prior parameters are the true ones, t~g\tilde t_g has a tt distribution with d0+dd_0 + d degrees of freedom, for every d0>0d_0 > 0. So the p-values of line L8 are exact under the hierarchical model with a known prior. As d0→0d_0 \to 0 the statistic becomes the ordinary t, and as d0→∞d_0 \to \infty it becomes a z-like statistic with the common variance s02s_0^2. The proof also derives the moment equations that lines L2 to L4 solve. With an estimated prior, the td0+dt_{d_0+d} law is an approximation, good when nn is large; this is a heuristic backed by Smyth's asymptotic argument and by simulation, not an exact result.

Proof: Under the hierarchical model, the moderated t has a t distribution with d0 + d degrees of freedomfull

We prove the main result of Smyth (2004) for one coefficient: under the hierarchical model, with the prior parameters known, the moderated t has a tt distribution with d0+dd_0 + d degrees of freedom under the null hypothesis (Theorem 2). The posterior variance is the inverse of the posterior mean of the precision (Lemma 1), which explains the formula at line L6. We also derive the moment equations that lines L2 to L4 solve (Lemma 3). With estimated d0d_0 and s02s_0^2, the td0+dt_{d_0+d} law holds only approximately. Smyth (2004) gives the asymptotic argument; it is cited, not proved here, and the page labels it as an approximation.

The model. For each gene gg, given its variance σg2\sigma_g^2:

  • the estimated coefficient (here a difference of two group means) is β^g∼N(βg,vσg2)\hat\beta_g \sim N(\beta_g, v\sigma_g^2), with a known vv (here 1/nA+1/nB1/n_A + 1/n_B);
  • the residual variance is sg2∼σg2χd2/ds_g^2 \sim \sigma_g^2\chi^2_d/d, with dd residual degrees of freedom;
  • β^g\hat\beta_g and sg2s_g^2 are independent.

The prior is 1/σg2∼χd02/(d0s02)1/\sigma_g^2 \sim \chi^2_{d_0}/(d_0s_0^2), a scaled inverse chi-squared prior on σg2\sigma_g^2. The posterior variance is s~g2=(d0s02+dsg2)/(d0+d)\tilde s_g^2 = (d_0s_0^2 + ds_g^2)/(d_0 + d), and the moderated t is t~g=β^g/(s~gv)\tilde t_g = \hat\beta_g/(\tilde s_g\sqrt v).

These assumptions hold exactly for normal data with equal variances in the two groups. For read counts they hold only after a transformation, as in voom, and then only approximately.

Lemma 1 (posterior of the precision). Write τ=1/σg2\tau = 1/\sigma_g^2. Given sg2s_g^2, τ\tau has a gamma distribution with shape (d0+d)/2(d_0 + d)/2 and rate (d0s02+dsg2)/2(d_0s_0^2 + ds_g^2)/2. Its posterior mean is 1/s~g21/\tilde s_g^2.

Proof. The prior says d0s02τ∼χd02d_0s_0^2\tau \sim \chi^2_{d_0}, so the prior density of τ\tau is proportional to τd0/2−1e−d0s02τ/2\tau^{d_0/2 - 1}e^{-d_0s_0^2\tau/2}. Given τ\tau, W=dsg2τ∼χd2W = d s_g^2\tau \sim \chi^2_d, so the density of sg2s_g^2 is proportional to τd/2(sg2)d/2−1e−dsg2τ/2\tau^{d/2}(s_g^2)^{d/2-1}e^{-ds_g^2\tau/2}, as a function of τ\tau and sg2s_g^2. By Bayes' theorem, the posterior density of τ\tau is proportional to τ(d0+d)/2−1e−(d0s02+dsg2)τ/2\tau^{(d_0+d)/2 - 1}e^{-(d_0s_0^2 + ds_g^2)\tau/2}, which is the stated gamma law. A gamma law with shape aa and rate bb has mean a/b=(d0+d)/(d0s02+dsg2)=1/s~g2a/b = (d_0 + d)/(d_0s_0^2 + ds_g^2) = 1/\tilde s_g^2. □\square

Theorem 2 (null distribution). If βg=0\beta_g = 0, then t~g\tilde t_g has a tt distribution with d0+dd_0 + d degrees of freedom, for every d0>0d_0 > 0, s02>0s_0^2 > 0 and d≥1d \ge 1.

Proof. Let Z=β^g/(σgv)Z = \hat\beta_g/(\sigma_g\sqrt v), W1=dsg2/σg2W_1 = ds_g^2/\sigma_g^2 and W0=d0s02/σg2W_0 = d_0s_0^2/\sigma_g^2. Given σg\sigma_g, Z∼N(0,1)Z \sim N(0, 1) and W1∼χd2W_1 \sim \chi^2_d, and they are independent. These conditional laws do not depend on σg\sigma_g. So ZZ, W1W_1 and σg\sigma_g are mutually independent: for any sets B1,B2,B3B_1, B_2, B_3, P(Z∈B1,W1∈B2,σg∈B3)=E[1{σg∈B3}P(Z∈B1)P(W1∈B2)]P(Z \in B_1, W_1 \in B_2, \sigma_g \in B_3) = E[\mathbf 1\{\sigma_g \in B_3\}P(Z \in B_1)P(W_1 \in B_2)]. The variable W0W_0 is a function of σg\sigma_g, and by the prior W0∼χd02W_0 \sim \chi^2_{d_0}. So ZZ, W0W_0 and W1W_1 are independent, and W0+W1∼χd0+d2W_0 + W_1 \sim \chi^2_{d_0 + d}, independent of ZZ. Now

t~g=β^gs~gv=Zσgs~g=Z(W0+W1)/(d0+d),\tilde t_g = \frac{\hat\beta_g}{\tilde s_g\sqrt v} = \frac{Z\sigma_g}{\tilde s_g} = \frac{Z}{\sqrt{(W_0 + W_1)/(d_0 + d)}},

because (d0+d)s~g2/σg2=W0+W1(d_0 + d)\tilde s_g^2/\sigma_g^2 = W_0 + W_1. This is the definition of a tt variable with d0+dd_0 + d degrees of freedom. □\square

Limits. With d0=0d_0 = 0, s~g2=sg2\tilde s_g^2 = s_g^2 and the moderated t is the ordinary pooled t-test on dd degrees of freedom. As d0→∞d_0 \to \infty with s02s_0^2 fixed, s~g2→s02\tilde s_g^2 \to s_0^2 and t~g\tilde t_g tends to a zz statistic with known variance s02s_0^2; the code uses the normal law when d0=∞d_0 = \infty. For finite d0d_0, s~g2\tilde s_g^2 is a weighted mean of sg2s_g^2 and s02s_0^2, so it lies between them.

Lemma 3 (the moment equations). Under the model, let eg=ln⁡sg2−ψ(d/2)+ln⁡(d/2)e_g = \ln s_g^2 - \psi(d/2) + \ln(d/2), with ψ\psi the digamma function and ψ′\psi' the trigamma function. Then

E[eg]=ln⁡s02−ψ(d0/2)+ln⁡(d0/2),Var⁡(eg)=ψ′(d/2)+ψ′(d0/2).E[e_g] = \ln s_0^2 - \psi(d_0/2) + \ln(d_0/2), \qquad \operatorname{Var}(e_g) = \psi'(d/2) + \psi'(d_0/2).

Proof. Write sg2=s02⋅(W1/d)/(W0/d0)s_g^2 = s_0^2 \cdot (W_1/d)/(W_0/d_0) with W0W_0 and W1W_1 as in Theorem 2, which are independent. So ln⁡sg2=ln⁡s02+ln⁡(W1/d)−ln⁡(W0/d0)\ln s_g^2 = \ln s_0^2 + \ln(W_1/d) - \ln(W_0/d_0). A χk2\chi^2_k variable is a gamma variable with shape k/2k/2 and scale 2. For a gamma variable XX with shape aa and scale θ\theta, Eln⁡X=ψ(a)+ln⁡θE\ln X = \psi(a) + \ln\theta and Var⁡ln⁡X=ψ′(a)\operatorname{Var}\ln X = \psi'(a); both follow by differentiating ln⁡Γ(a+s)\ln\Gamma(a + s) at s=0s = 0, since E[Xs]=θsΓ(a+s)/Γ(a)E[X^s] = \theta^s\Gamma(a + s)/\Gamma(a). So Eln⁡(Wk/k)=ψ(k/2)−ln⁡(k/2)E\ln(W_k/k) = \psi(k/2) - \ln(k/2) and Var⁡ln⁡(Wk/k)=ψ′(k/2)\operatorname{Var}\ln(W_k/k) = \psi'(k/2). Adding the means and, by independence, the variances gives the claim. □\square

Lines L2 to L4 replace E[eg]E[e_g] and Var⁡(eg)\operatorname{Var}(e_g) by the sample mean eˉ\bar e and the sample variance of the ege_g, and solve the two equations: ψ′(d0/2)=Var⁡^(e)−ψ′(d/2)\psi'(d_0/2) = \widehat{\operatorname{Var}}(e) - \psi'(d/2) and s02=exp⁡(eˉ+ψ(d0/2)−ln⁡(d0/2))s_0^2 = \exp(\bar e + \psi(d_0/2) - \ln(d_0/2)). The function ψ′(x)=∑k≥0(x+k)−2\psi'(x) = \sum_{k \ge 0}(x + k)^{-2} decreases strictly from ∞\infty to 0 on (0,∞)(0, \infty), so the first equation has exactly one solution when its right side is positive. When it is not, the sample variance of the ege_g is no larger than the variance that sampling error alone gives, and line L5 sets d0=∞d_0 = \infty. Then, as in limma, s02s_0^2 is the mean of the sg2s_g^2. The method of moments is consistent as the number of genes grows when the genes are independent; that is a standard fact and is cited, not proved here. Genes are not independent in practice, so the estimates are a heuristic.

Degrees of freedom cap. limma caps d0+dd_0 + d at the total residual degrees of freedom of all genes, GdGd, and the code does the same. This changes nothing unless d0d_0 is very large.

Special functions. The code computes ψ\psi, ψ′\psi' and ψ′′\psi'' by the recurrences ψ(x)=ψ(x+1)−1/x\psi(x) = \psi(x+1) - 1/x, ψ′(x)=ψ′(x+1)+1/x2\psi'(x) = \psi'(x+1) + 1/x^2 and ψ′′(x)=ψ′′(x+1)−2/x3\psi''(x) = \psi''(x+1) - 2/x^3 up to x≥10x \ge 10, and then by their asymptotic series. It inverts ψ′\psi' by Newton's method on 1/ψ′(x)=1/y1/\psi'(x) = 1/y, from x=0.5+1/yx = 0.5 + 1/y, as limma does. The tt tail is P(T>t)=12Id/(d+t2)(d/2,1/2)P(T > t) = \frac12 I_{d/(d+t^2)}(d/2, 1/2) for t≥0t \ge 0, with the regularized incomplete beta function II computed by its continued fraction. The tests check these against known values: ψ(1)=−γ\psi(1) = -\gamma, ψ′(1)=π2/6\psi'(1) = \pi^2/6, ψ′(1/2)=π2/2\psi'(1/2) = \pi^2/2, the closed forms of the tt tail for 1 and 2 degrees of freedom, and the binomial sum for Ix(a,b)I_x(a, b) with integer aa and bb.

What the tests check. Theorem 2 is checked by simulation from the model with the true prior: over 4000 null genes, the fraction of p-values below 0.01, 0.05 and 0.5 must be within 4u(1−u)/40004\sqrt{u(1-u)/4000} of uu. The estimation of d0d_0 and s02s_0^2 is only measured.

Complexity. For GG genes and nn samples, the gene-wise statistics take Θ(Gn)\Theta(Gn) time. The fit of the prior takes Θ(G)\Theta(G) plus a sort for the median floor, O(Glog⁡G)O(G\log G). Each p-value needs one continued fraction, which takes a bounded number of steps for the degrees of freedom met in practice. The extra space is Θ(G)\Theta(G).

Complexity

On a real RAM, line L1 reads every value once, which takes Θ(nm)\Theta(nm) time. The median used for the floor takes O(nlog⁡n)O(n\log n) by sorting, and O(n)O(n) with linear-time selection. Lines L2 to L8 take O(1)O(1) time per gene, counting each special function as O(1)O(1) for a fixed accuracy: the digamma and trigamma functions use a recurrence and an asymptotic series, the inverse trigamma uses Newton's method, and the tt tail uses a continued fraction for the incomplete beta function. The extra space is Θ(n)\Theta(n).

Properties

  • Exact under the model. With a known prior, the null distribution is td0+dt_{d_0+d}, not an approximation.
  • More degrees of freedom. The test behaves as if it had d0+dd_0 + d degrees of freedom, so its critical values are smaller than those of the ordinary t-test, and its power is higher when the prior fits.
  • Between two extremes. It interpolates between the gene-wise t-test (d0=0d_0 = 0) and a test with one common variance (d0=∞d_0 = \infty), and the data choose the point.
  • Robust to tiny variances. A gene with a variance near zero cannot get a huge statistic, since s~g2≥d0s02/(d0+d)\tilde s_g^2 \ge d_0s_0^2/(d_0 + d).
  • Order not kept. The ranking by t~g\tilde t_g differs from the ranking by the ordinary t and from the ranking by fold change; it is a compromise between the two.

Variants and improvements

  • Moderated F. For several coefficients at once, the same posterior variance gives an F statistic with d0+dd_0 + d denominator degrees of freedom.
  • Trended prior. The prior variance s02s_0^2 is a smooth function of the mean expression of each gene, instead of a constant. This helps for RNA-seq log counts and for arrays where low intensities are noisier.
  • Robust prior. Phipson et al. (2016) estimate d0d_0 and s02s_0^2 in a way that a few hypervariable genes cannot spoil, and give those genes a smaller prior weight.
  • voom. Law et al. (2014) transform RNA-seq counts to log counts per million and give each value a precision weight from the trend of the variance over the mean. The weighted linear model then uses the moderated t.
  • Fudge factor. Older methods, such as SAM, add a constant to the standard error of each gene. It has the same aim, but no null distribution in closed form, so they use permutations.
  • Count models. For counts, dispersion shrinkage in a negative binomial GLM replaces the variance shrinkage; edgeR's quasi-likelihood F test shrinks a second, gene-wise variance factor in the same way as limma.

When to use it

Use it for microarray data after quantile normalization, for other continuous omics data on a log scale, and for RNA-seq with voom, especially when there are few samples. It works best when the variances of the genes look like draws from one distribution, maybe with a trend over the mean. For raw counts with very low means, a negative binomial model is closer to the data. Correct the p-values for multiple testing with the Benjamini-Hochberg procedure, as part of differential expression analysis.

Pitfalls

  • Counts without a transformation. The model assumes normal values with a variance that does not depend on the mean. Raw counts break both assumptions; use voom or a count model.
  • Too few genes. The prior is estimated from the spread of the gene variances. With tens of genes, d0d_0 is very uncertain, and the exact null distribution no longer holds.
  • A prior that fits badly. If a group of genes has much larger variances than the rest, a constant prior shrinks them too much and gives false positives. Use the robust or the trended prior.
  • Filtering after the fit. The prior should be estimated from the genes that are tested. Removing many genes after the fit, or fitting on a selected set, changes d0d_0 and s02s_0^2.
  • Unequal variances between groups. The pooled variance assumes the same variance in both groups, like the ordinary t-test and unlike the Welch t-test.

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.

moderated_t_statistic.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/moderated-t-statistic/. The authors are listed in prov/SC6381.jsonl.
"""The moderated t-statistic of Smyth (2004), as in limma, for two groups.

Each gene g has a sample variance s2_g on d residual degrees of freedom. The
prior is 1 / sigma2_g ~ chi2_{d0} / (d0 s0^2). The hyperparameters d0 and
s0^2 are found by matching the mean and variance of log s2_g (fit_f_dist,
the method of limma's fitFDist without covariate), the posterior variance
is (d0 s0^2 + d s2_g) / (d0 + d), and under the null hypothesis the
moderated t has a t distribution with d0 + d degrees of freedom.

Special functions (digamma, trigamma, tetragamma, the regularized incomplete
beta function) are written here with the standard library only.
"""

from __future__ import annotations

import math
from statistics import NormalDist
from typing import List, Optional, Sequence, Tuple

_NORMAL = NormalDist()


def digamma(x: float) -> float:
    """psi(x) for x > 0, by the recurrence psi(x) = psi(x + 1) - 1 / x and the asymptotic series."""
    if x <= 0:
        raise ValueError("x must be > 0")
    acc = 0.0
    while x < 10.0:
        acc -= 1.0 / x
        x += 1.0
    f = 1.0 / (x * x)
    series = f * (1 / 12 - f * (1 / 120 - f * (1 / 252 - f * (1 / 240 - f / 132))))
    return acc + math.log(x) - 0.5 / x - series


def trigamma(x: float) -> float:
    """psi'(x) for x > 0."""
    if x <= 0:
        raise ValueError("x must be > 0")
    acc = 0.0
    while x < 10.0:
        acc += 1.0 / (x * x)
        x += 1.0
    f = 1.0 / (x * x)
    series = 1.0 + 0.5 / x + f * (1 / 6 - f * (1 / 30 - f * (1 / 42 - f * (1 / 30 - f * 5 / 66))))
    return acc + series / x


def tetragamma(x: float) -> float:
    """psi''(x) for x > 0."""
    if x <= 0:
        raise ValueError("x must be > 0")
    acc = 0.0
    while x < 10.0:
        acc -= 2.0 / (x * x * x)
        x += 1.0
    f = 1.0 / (x * x)
    series = 1.0 + 1.0 / x + f * (0.5 - f * (1 / 6 - f * (1 / 6 - f * (3 / 10 - f * 5 / 6))))
    return acc - f * series


def trigamma_inverse(y: float) -> float:
    """The x > 0 with trigamma(x) = y, by Newton's method from x = 0.5 + 1 / y."""
    if not y > 0:
        raise ValueError("y must be > 0")
    if y > 1e7:
        return 1.0 / math.sqrt(y)
    if y < 1e-6:
        return 1.0 / y
    x = 0.5 + 1.0 / y
    for _ in range(100):
        tri = trigamma(x)
        step = tri * (1.0 - tri / y) / tetragamma(x)
        x += step
        if abs(step) / x < 1e-12:
            break
    return x


def betainc(a: float, b: float, x: float) -> float:
    """The regularized incomplete beta function I_x(a, b), by a continued fraction."""
    if a <= 0 or b <= 0:
        raise ValueError("a and b must be > 0")
    if x <= 0:
        return 0.0
    if x >= 1:
        return 1.0
    if x > (a + 1) / (a + b + 2):
        return 1.0 - betainc(b, a, 1.0 - x)
    log_front = (math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
                 + a * math.log(x) + b * math.log1p(-x))
    tiny = 1e-300
    c = 1.0
    d = 1.0 - (a + b) * x / (a + 1)
    d = 1.0 / (d if abs(d) > tiny else tiny)
    h = d
    for k in range(1, 10000):
        num = k * (b - k) * x / ((a + 2 * k - 1) * (a + 2 * k))
        for _ in range(2):
            d = 1.0 + num * d
            d = 1.0 / (d if abs(d) > tiny else tiny)
            c = 1.0 + num / c
            c = c if abs(c) > tiny else tiny
            h *= d * c
            last = d * c
            num = -(a + k) * (a + b + k) * x / ((a + 2 * k) * (a + 2 * k + 1))
        if abs(last - 1.0) < 1e-15:
            break
    return math.exp(log_front) * h / a


def t_sf(t: float, df: float) -> float:
    """P(T > t) for T with a t distribution on df degrees of freedom (df = inf is normal)."""
    if not df > 0:
        raise ValueError("df must be > 0")
    if math.isinf(df):
        return _NORMAL.cdf(-t)
    tail = 0.5 * betainc(df / 2, 0.5, df / (df + t * t))
    return tail if t >= 0 else 1.0 - tail


def fit_f_dist(s2: Sequence[float], d: float) -> Tuple[float, float]:
    """(d0, s0^2) by moments of log s2, as fitFDist of limma without covariate.

    Values are floored at 1e-5 times their median, as limma does, so that a
    zero variance does not give log 0.
    """
    if len(s2) < 2:
        raise ValueError("need at least two genes")
    if any(v < 0 for v in s2) or not d > 0:
        raise ValueError("need s2 >= 0 and d > 0")
    srt = sorted(s2)
    n = len(srt)
    med = srt[n // 2] if n % 2 else (srt[n // 2 - 1] + srt[n // 2]) / 2
    if med == 0:
        med = 1.0
    x = [max(v, 1e-5 * med) for v in s2]
    e = [math.log(v) - digamma(d / 2) + math.log(d / 2) for v in x]  # @line L2
    emean = sum(e) / n
    evar = sum((v - emean) ** 2 for v in e) / (n - 1) - trigamma(d / 2)  # @line L3
    if evar > 0:
        d0 = 2.0 * trigamma_inverse(evar)  # @line L4
        s02 = math.exp(emean + digamma(d0 / 2) - math.log(d0 / 2))
    else:
        d0 = math.inf  # @line L5
        s02 = sum(x) / n
    return d0, s02


def squeeze_var(s2: float, d: float, d0: float, s02: float) -> float:
    """The posterior variance (d0 s0^2 + d s2) / (d0 + d); s0^2 when d0 is infinite."""
    if math.isinf(d0):
        return s02
    return (d0 * s02 + d * s2) / (d0 + d)  # @line L6


def group_stats(a: Sequence[float], b: Sequence[float]) -> Tuple[float, float, int, float]:
    """(mean of a - mean of b, pooled variance, its degrees of freedom, 1/n_a + 1/n_b)."""
    na, nb = len(a), len(b)
    d = na + nb - 2
    if na < 1 or nb < 1 or d < 1:
        raise ValueError("need at least three samples in all")
    ma, mb = sum(a) / na, sum(b) / nb
    ss = sum((x - ma) ** 2 for x in a) + sum((x - mb) ** 2 for x in b)
    return ma - mb, ss / d, d, 1.0 / na + 1.0 / nb


def moderated_t(group_a: Sequence[Sequence[float]], group_b: Sequence[Sequence[float]],
                prior: Optional[Tuple[float, float]] = None):
    """Moderated t for each gene; group_a[g] and group_b[g] hold the values of gene g.

    prior = (d0, s0^2) fixes the hyperparameters; otherwise fit_f_dist finds
    them. As in limma's eBayes, the total degrees of freedom are capped at
    the pooled residual degrees of freedom of all genes. Returns
    (t, p, d0, s0^2), with two-sided p-values.
    """
    if len(group_a) != len(group_b) or not group_a:
        raise ValueError("need the same genes in both groups")
    stats = [group_stats(a, b) for a, b in zip(group_a, group_b)]  # @line L1
    d = stats[0][2]
    if any(s[2] != d for s in stats):
        raise ValueError("every gene needs the same number of samples")
    s2 = [s[1] for s in stats]
    d0, s02 = fit_f_dist(s2, d) if prior is None else prior
    df_total = min(d0 + d, d * len(stats))
    ts: List[float] = []
    ps: List[float] = []
    for diff, var, _, v in stats:
        post = squeeze_var(var, d, d0, s02)
        t = diff / math.sqrt(post * v)  # @line L7
        ts.append(t)
        ps.append(min(1.0, 2.0 * t_sf(abs(t), df_total)))  # @line L8
    return ts, ps, d0, s02  # @line L9


def ordinary_t(a: Sequence[float], b: Sequence[float]) -> Tuple[float, float]:
    """The pooled two-sample t and its two-sided p-value."""
    diff, var, d, v = group_stats(a, b)
    t = diff / math.sqrt(var * v)
    return t, min(1.0, 2.0 * t_sf(abs(t), d))
test_moderated_t_statistic.py 131 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/moderated-t-statistic/. The authors are listed in prov/SC6381.jsonl.

import math
import random
from fractions import Fraction

import pytest

from moderated_t_statistic import (
    betainc,
    digamma,
    fit_f_dist,
    moderated_t,
    ordinary_t,
    squeeze_var,
    t_sf,
    tetragamma,
    trigamma,
    trigamma_inverse,
)

EULER = 0.5772156649015329


def test_special_values():
    assert math.isclose(digamma(1.0), -EULER, rel_tol=1e-13)
    assert math.isclose(digamma(0.5), -EULER - 2 * math.log(2), rel_tol=1e-13)
    assert math.isclose(trigamma(1.0), math.pi ** 2 / 6, rel_tol=1e-13)
    assert math.isclose(trigamma(0.5), math.pi ** 2 / 2, rel_tol=1e-13)
    assert math.isclose(tetragamma(1.0), -2.4041138063191885, rel_tol=1e-12)
    for x in (0.3, 1.7, 3.7, 12.5, 200.0):
        assert math.isclose(digamma(x + 1) - digamma(x), 1 / x, rel_tol=1e-12)
        h = 1e-5 * x
        assert math.isclose((digamma(x + h) - digamma(x - h)) / (2 * h), trigamma(x), rel_tol=1e-6)
        assert math.isclose((trigamma(x + h) - trigamma(x - h)) / (2 * h), tetragamma(x), rel_tol=1e-5)


def test_trigamma_inverse_round_trip():
    for x in (0.01, 0.2, 1.0, 2.5, 10.0, 100.0, 1e4):
        assert math.isclose(trigamma_inverse(trigamma(x)), x, rel_tol=1e-8)
    with pytest.raises(ValueError):
        trigamma_inverse(0.0)


def test_betainc_against_the_binomial_sum():
    rng = random.Random(41)
    for _ in range(200):
        a = rng.randint(1, 12)
        b = rng.randint(1, 12)
        x = Fraction(rng.randint(1, 99), 100)
        n = a + b - 1
        exact = sum(math.comb(n, j) * x ** j * (1 - x) ** (n - j) for j in range(a, n + 1))
        assert math.isclose(betainc(a, b, float(x)), float(exact), rel_tol=1e-11, abs_tol=1e-15)


def test_t_tail_closed_forms():
    for t in (-3.0, -0.5, 0.0, 0.7, 2.0, 10.0, 100.0):
        assert math.isclose(t_sf(t, 1), 0.5 - math.atan(t) / math.pi, rel_tol=1e-11, abs_tol=1e-15)
        assert math.isclose(t_sf(t, 2), 0.5 - t / (2 * math.sqrt(2 + t * t)), rel_tol=1e-11, abs_tol=1e-15)
    assert math.isclose(t_sf(1.96, 1e9), t_sf(1.96, math.inf), rel_tol=1e-6)
    assert t_sf(0.0, 7.5) == 0.5


def test_d0_zero_gives_the_ordinary_t_and_infinite_d0_a_fixed_variance():
    rng = random.Random(42)
    a = [[rng.gauss(0, 1) for _ in range(3)] for _ in range(20)]
    b = [[rng.gauss(0.5, 1) for _ in range(4)] for _ in range(20)]
    ts, ps, _, _ = moderated_t(a, b, prior=(0.0, 1.0))
    for g in range(20):
        t, p = ordinary_t(a[g], b[g])
        assert math.isclose(ts[g], t, rel_tol=1e-12)
        assert math.isclose(ps[g], p, rel_tol=1e-10)
    ts, ps, _, _ = moderated_t(a, b, prior=(math.inf, 2.0))
    for g in range(20):
        diff = sum(a[g]) / 3 - sum(b[g]) / 4
        assert math.isclose(ts[g], diff / math.sqrt(2.0 * (1 / 3 + 1 / 4)), rel_tol=1e-12)


def test_posterior_variance_lies_between_gene_and_prior():
    rng = random.Random(43)
    for _ in range(100):
        s2, s02 = rng.uniform(0.01, 5), rng.uniform(0.01, 5)
        post = squeeze_var(s2, 4, rng.uniform(0, 50), s02)
        assert min(s2, s02) - 1e-12 <= post <= max(s2, s02) + 1e-12


def test_equal_variances_give_infinite_prior_df():
    d0, s02 = fit_f_dist([0.3] * 10, 4)
    assert math.isinf(d0) and math.isclose(s02, 0.3)


def simulate(rng, genes, d0, s02, na=3, nb=3):
    a, b = [], []
    for _ in range(genes):
        sigma2 = d0 * s02 / rng.gammavariate(d0 / 2, 2)
        sd = math.sqrt(sigma2)
        a.append([rng.gauss(0, sd) for _ in range(na)])
        b.append([rng.gauss(0, sd) for _ in range(nb)])
    return a, b


def test_null_moderated_t_has_t_distribution_with_d0_plus_d_df():
    # The theorem: with the true prior, P(p <= u) = u. Checked at three levels
    # with the binomial tolerance 4 sqrt(u (1 - u) / G).
    rng = random.Random(44)
    genes = 4000
    a, b = simulate(rng, genes, 4.0, 1.0)
    _, ps, _, _ = moderated_t(a, b, prior=(4.0, 1.0))
    for u in (0.01, 0.05, 0.5):
        frac = sum(p <= u for p in ps) / genes
        assert abs(frac - u) <= 4 * math.sqrt(u * (1 - u) / genes)


def test_fit_f_dist_measurement():
    # A measurement: with 4000 genes, d = 4, d0 = 4 and s0^2 = 1, the moment
    # estimates come within these loose bounds.
    rng = random.Random(45)
    a, b = simulate(rng, 4000, 4.0, 1.0)
    _, _, d0, s02 = moderated_t(a, b)
    assert 2.5 < d0 < 7.0
    assert abs(s02 - 1.0) < 0.15


def test_errors():
    with pytest.raises(ValueError):
        moderated_t([[1.0, 2.0]], [[3.0, 4.0], [1.0]])
    with pytest.raises(ValueError):
        fit_f_dist([1.0], 3)
    with pytest.raises(ValueError):
        digamma(0.0)

History

Smyth (2004) built on earlier regularized and Bayesian t-tests for microarrays. His contribution was the general setting of linear models with any contrast, the closed-form estimate of the prior from the moments of the log variances, and the proof that the statistic has an exact tt distribution with augmented degrees of freedom. The method became the core of the limma package. Law et al. (2014) extended it to RNA-seq with voom, and Phipson et al. (2016) made the prior robust to hypervariable genes.

References

  1. Gordon K. Smyth, Linear models and empirical Bayes methods for assessing differential expression in microarray experiments, Statistical Applications in Genetics and Molecular Biology 3(1) (2004), Article 3, the hierarchical model with a scaled inverse chi-squared prior on the variances, the posterior variance, the moderated t with d0 + d degrees of freedom, and the estimation of the prior from the moments of the log variances
  2. Charity W. Law, Yunshun Chen, Wei Shi and Gordon K. Smyth, voom, precision weights unlock linear model analysis tools for RNA-seq read counts, Genome Biology 15(2) (2014), article R29, log counts per million with precision weights from the mean-variance trend, analysed with the moderated t-statistic
  3. Belinda Phipson, Stanley Lee, Ian J. Majewski, Warren S. Alexander and Gordon K. Smyth, Robust hyperparameter estimation protects against hypervariable genes and improves power to detect differential expression, Annals of Applied Statistics 10(2) (2016), pages 946 to 963, the robust estimation of the prior degrees of freedom and the prior variance, and the trend of the prior variance over the mean expression

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