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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 distribution with degrees of freedom under the null hypothesis, where 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 , its values in two groups of samples, samples in all, on a log scale such as log intensities or log counts per million.
Output. For each gene, a statistic and a two-sided p-value, and the prior parameters and .
Model. The difference of the group means is , with . The pooled sample variance is , with , independent of . The prior is . In limma the same holds for any coefficient or contrast of a linear model per gene.
The algorithm
MODERATED-T(A, B) ▷ values of each gene in groups A and B- 1
for each gene g: β̂_g ← mean_A - mean_B; s²_g ← pooled variance on d = m - 2 df; v ← 1/m_A + 1/m_B - 2
e_g ← ln s²_g - ψ(d/2) + ln(d/2) ▷ ψ: digamma - 3
ē ← mean of e; w ← sample variance of e - ψ'(d/2) ▷ ψ': trigamma - 4
if w > 0 then d₀ ← 2 ψ'⁻¹(w); s₀² ← exp(ē + ψ(d₀/2) - ln(d₀/2)) - 5
else d₀ ← ∞; s₀² ← mean of s² - 6
for each gene g: s̃²_g ← (d₀ s₀² + d s²_g) / (d₀ + d) ▷ s₀² if d₀ = ∞ - 7
t̃_g ← β̂_g / (s̃_g √v) - 8
p_g ← 2 P(T > |t̃_g|), with T ~ t on min(d₀ + d, n d) df - 9
return 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, , whose mean and variance are given by the digamma and trigamma functions. Line L2 removes the known mean of the part, and line L3 removes its known variance, so what is left of the variance belongs to the prior, and fixes . If the observed variance of the is no larger than the sampling variance alone, the data are consistent with one common variance, and line L5 sets . Line L6 is the posterior variance, a weighted mean of and with weights and . Lines L7 and L8 form the statistic and its p-value. The cap 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 to at least times their median, so that a zero variance does not give .
Example
Three genes, three samples per group, so and . Take the prior as given, and , as if it had been estimated from many genes. The total degrees of freedom are 8.
| gene | group A | group B | t | p | |||||
|---|---|---|---|---|---|---|---|---|---|
| 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, and . 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 has a gamma posterior whose mean is , which is the formula of line L6. It then proves the main theorem: when and the prior parameters are the true ones, has a distribution with degrees of freedom, for every . So the p-values of line L8 are exact under the hierarchical model with a known prior. As the statistic becomes the ordinary t, and as it becomes a z-like statistic with the common variance . The proof also derives the moment equations that lines L2 to L4 solve. With an estimated prior, the law is an approximation, good when 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 distribution with 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 and , the 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 , given its variance :
- the estimated coefficient (here a difference of two group means) is , with a known (here );
- the residual variance is , with residual degrees of freedom;
- and are independent.
The prior is , a scaled inverse chi-squared prior on . The posterior variance is , and the moderated t is .
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 . Given , has a gamma distribution with shape and rate . Its posterior mean is .
Proof. The prior says , so the prior density of is proportional to . Given , , so the density of is proportional to , as a function of and . By Bayes' theorem, the posterior density of is proportional to , which is the stated gamma law. A gamma law with shape and rate has mean .
Theorem 2 (null distribution). If , then has a distribution with degrees of freedom, for every , and .
Proof. Let , and . Given , and , and they are independent. These conditional laws do not depend on . So , and are mutually independent: for any sets , . The variable is a function of , and by the prior . So , and are independent, and , independent of . Now
because . This is the definition of a variable with degrees of freedom.
Limits. With , and the moderated t is the ordinary pooled t-test on degrees of freedom. As with fixed, and tends to a statistic with known variance ; the code uses the normal law when . For finite , is a weighted mean of and , so it lies between them.
Lemma 3 (the moment equations). Under the model, let , with the digamma function and the trigamma function. Then
Proof. Write with and as in Theorem 2, which are independent. So . A variable is a gamma variable with shape and scale 2. For a gamma variable with shape and scale , and ; both follow by differentiating at , since . So and . Adding the means and, by independence, the variances gives the claim.
Lines L2 to L4 replace and by the sample mean and the sample variance of the , and solve the two equations: and . The function decreases strictly from to 0 on , so the first equation has exactly one solution when its right side is positive. When it is not, the sample variance of the is no larger than the variance that sampling error alone gives, and line L5 sets . Then, as in limma, is the mean of the . 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 at the total residual degrees of freedom of all genes, , and the code does the same. This changes nothing unless is very large.
Special functions. The code computes , and by the recurrences , and up to , and then by their asymptotic series. It inverts by Newton's method on , from , as limma does. The tail is for , with the regularized incomplete beta function computed by its continued fraction. The tests check these against known values: , , , the closed forms of the tail for 1 and 2 degrees of freedom, and the binomial sum for with integer and .
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 of . The estimation of and is only measured.
Complexity. For genes and samples, the gene-wise statistics take time. The fit of the prior takes plus a sort for the median floor, . 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 .
Complexity
On a real RAM, line L1 reads every value once, which takes time. The median used for the floor takes by sorting, and with linear-time selection. Lines L2 to L8 take time per gene, counting each special function as 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 tail uses a continued fraction for the incomplete beta function. The extra space is .
Properties
- Exact under the model. With a known prior, the null distribution is , not an approximation.
- More degrees of freedom. The test behaves as if it had 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 () and a test with one common variance (), and the data choose the point.
- Robust to tiny variances. A gene with a variance near zero cannot get a huge statistic, since .
- Order not kept. The ranking by 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 denominator degrees of freedom.
- Trended prior. The prior variance 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 and 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, 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 and .
- 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.
# 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 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag SC6381 Edit this page History Report an error Markdown