Algorithmintro
Over-representation analysis
Also called hypergeometric enrichment test, gene ontology enrichment.
Test whether a gene set has more members in a list of selected genes than chance predicts, with a hypergeometric test per set.
- Time
- Θ(s u + s log s) worstΘ(u + s log s) best
- Space
- Θ(u + s) extra
- Where
- s = the number of gene sets; u = the number of genes in the universe
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ronald A. Fisher, 1935
Over-representation analysis asks, for each gene set in a collection, whether a list of selected genes, usually the genes found by differential expression analysis, contains more members of the set than a random list of the same size would. The gene sets come from databases of pathways, of Gene Ontology terms, or of targets of a regulator. For each set, the number of members in the list is compared with the hypergeometric distribution, which is the law of that number when the list is a uniformly random subset of the universe of genes. The p-value is the one-sided Fisher exact test on a 2 by 2 table, and the p-values of all sets are then adjusted for multiple testing. Gene Ontology is one source of gene sets, so "gene ontology enrichment" names the most common use, not a different method. Unlike gene set enrichment analysis, which uses the ranking of all genes, over-representation analysis needs a cutoff that splits the genes into selected and not selected.
In plain words
You have found 200 genes that changed in an experiment, out of 10,000 that you measured. A pathway has 50 genes, and 8 of them are in your list. Is that a lot? If you had picked 200 genes at random, you would expect 1 of them in the pathway. So 8 looks like a lot, and the test tells you exactly how unlikely 8 or more would be by chance. You do this for every pathway in your database, and then correct for doing thousands of tests. The answer depends on what "all genes" means: it must be the genes you could have found, not every gene in the genome.
The problem
Input. A universe of genes, the genes that were measured and could have been selected; a list of selected genes; and a collection of gene sets .
Output. For each gene set : the number of its members in the universe, the number of selected members, the expected number with , a p-value, and an adjusted p-value.
Null hypothesis. The selected list is a uniformly random subset of of size , independent of membership in . This is a competitive hypothesis in the sense of Goeman and Bühlmann (2007): it compares the set with the other genes, and it treats the genes, not the samples, as the units.
The algorithm
ORA(D, U, sets)- 1
D ← D ∩ U; N ← |U|; n ← |D| ▷ drop genes outside the universe - 2
for each gene set S in sets do - 3
S ← S ∩ U; K ← |S|; k ← |S ∩ D| - 4
p_S ← Σ_{i=k}^{min(K, n)} C(K, i) C(N - K, n - i) / C(N, n) ▷ hypergeometric upper tail - 5
q ← BENJAMINI-HOCHBERG(p) - 6
return (k, K, nK/N, p_S, q_S) for each set
Line L1 cuts the list to the universe, because a gene that could not have been measured cannot count. Line L3 does the same for each set, so that counts only the members that could have been selected. Line L4 sums the hypergeometric probabilities of or more selected members. The code computes the sum with exact integers and divides once, so no rounding happens before the final conversion. Line L5 adjusts the p-values of all tested sets with the Benjamini-Hochberg procedure. The code also skips sets with fewer than a given number of members in the universe, a common filter.
Example
The universe is , so . The list is and a gene that is not in , so line L1 drops and .
| set | members | expected | p | q | ||
|---|---|---|---|---|---|---|
| A | 4 | 3 | 1 | 0.0320 | 0.0960 | |
| B | 6 | 1 | 1.5 | 0.871 | 1 | |
| C | 2 | 0 | 0.5 | 1 | 1 |
For set A, . For set B, . Set C loses at line L3, so . The adjusted value of A is . So at a target of 0.05, no set is called, although A has three times the expected number of selected genes. With only 20 genes, the test has little power.
Correctness
The proof shows that the value of line L4 is the exact probability that a uniformly random subset of of size has at least members in , so it is a valid p-value for the null hypothesis above: for every , with equality only at the attainable values, since the law is discrete. It shows that this is also the p-value of the one-sided Fisher exact test, by writing the table as two independent binomial counts with the same success probability and conditioning on their sum. The Benjamini-Hochberg step controls the false discovery rate when the p-values are independent or positively dependent. Gene sets overlap and genes are correlated, so for real collections this control is a heuristic, not a theorem.
Proof: The over-representation p-value is the exact hypergeometric tail, and it equals the one-sided Fisher testfull
We prove that the code returns the exact probability that a uniformly random selection of genes from the universe puts at least genes in the set (Theorem 2). We also prove that this number is the p-value of the one-sided Fisher exact test on the 2 by 2 table of the set against the selection (Theorem 3), so that it is valid under any null model in which the selection and the set are independent given the margins. The claim that real gene selections behave like uniform draws is a modelling assumption. It fails when genes are correlated or when the chance of selection depends on gene length, and it is not proved here.
Setting. The universe has genes. Line L1 cuts the list of selected genes to , which gives with . Line L3 cuts each set to , which gives with and . Line L4 computes
with the terms outside the range left out, since they are 0.
Lemma 1 (the hypergeometric law). Let , where is a subset of of size chosen uniformly at random and is fixed. Then .
Proof. There are subsets of size , all equally likely. A subset with is fixed by choosing members of and genes of , which can be done in ways.
Theorem 2 (exact p-value). The value returned for is for as in Lemma 1, computed without rounding before the final conversion to a float.
Proof. By Lemma 1, is the sum at line L4. The code forms the numerator as an integer sum of products of binomial coefficients and divides by the integer as an exact fraction. Only the final call to float rounds.
The exact arithmetic matters in the far tail. A sum of floating point terms near can underflow, and the complement loses all its digits when is small.
Theorem 3 (equality with the one-sided Fisher test). Write the 2 by 2 table with rows "in " and "not in " and columns "selected" and "not selected", with margins , , and . Suppose the genes of are selected independently with probability each, and the genes outside with probability each. If , then given , the count has the law of Lemma 1. So is the p-value of the one-sided Fisher exact test of against .
Proof. Let and , independent, with the common value . Then , and
The factor cancels, so the conditional law does not depend on the unknown . The one-sided Fisher test conditions on both margins and sums this law over the tables at least as extreme as the observed one in the direction of , which are the tables with .
Validity. Under the null hypothesis, is a discrete variable and is its upper tail at the observed value. For a discrete variable, for every : let be the smallest value with ; then the event is , which has probability . So the test is valid, and it is conservative because the inequality is usually strict.
Adjustment. Line L5 applies the Benjamini-Hochberg procedure to the p-values of the tested sets. The tests of overlapping sets are positively dependent in many cases but not in all, so the control of the false discovery rate at the nominal level is a heuristic here, not a theorem. The adjusted value is not a q-value.
What the universe changes. Every quantity depends on . A gene outside is removed from the list and from every set, so it changes and . Taking all genes of the genome as , when only the expressed genes could have been selected, makes too large and too small for every set of expressed genes. This is a fact about the model, and the tests check that the cut to changes as the formula says.
What the tests check. The test file enumerates every subset of size of a small universe and counts the subsets with (Theorem 2). It checks Theorem 3 by computing the conditional law of two binomials from their joint law. It compares the probabilities with the hypergeometric mass function of the shared helper, checks the BH adjustment against its definition, and checks the page example, for set A.
Complexity. The cut to takes expected time with hash sets. For one set, line L4 sums at most terms with integers of bits, so the cost is polynomial in ; a floating point version on the log scale costs operations. The BH step sorts the p-values in time.
Complexity
On a real RAM, with hash sets, line L1 takes time, where is the size of the universe. For a set of members, line L3 takes time, and line L4 takes arithmetic operations if each term is computed from the previous one by the ratio of binomial coefficients. Since , the loop takes time in the worst case and less when the sets are small. The adjustment at line L5 sorts the p-values, in time. The code uses exact integers, whose cost grows with their length; this does not change the result, only the time on large inputs. The extra space is .
Properties
- Exact. The p-value is exact under the null hypothesis of a random list, with no approximation.
- One-sided. It tests for more selected members than expected. Depletion needs the lower tail.
- Conservative for discrete data. Since the law is discrete, is often less than , so the test is valid but loses some power.
- Depends on the cutoff. The list comes from a threshold on the results of another analysis. Different thresholds give different lists and different answers.
- Depends on the universe. The p-value changes with even when and stay the same.
Variants and improvements
- Chi-squared or z approximation. For large counts, the 2 by 2 table can be tested with a chi-squared test. The exact sum is cheap, so there is little reason to approximate.
- Up and down lists. Test the genes that went up and the genes that went down separately, since a pathway can be activated or repressed.
- Length bias correction. In RNA-seq, long and highly expressed genes have more reads, so they are more likely to be called. Young et al. (2010) estimate the probability of selection as a function of gene length and use a weighted null distribution, so that a set of long genes is not enriched only because of length.
- Using the structure of the ontology. Gene Ontology terms are nested, so a specific term and all terms above it are often called together. Some methods remove genes already explained by a more specific term before testing a more general one.
- Ranked methods. Gene set enrichment analysis uses the whole ranking and needs no cutoff. Methods such as CAMERA test sets with the sample correlation between genes taken into account.
When to use it
Use it when the result of an analysis is a list of genes, not a ranking: the genes of a cluster or a module of WGCNA, the targets of a factor from a binding experiment, or the genes near variants found in a genetic study. It is fast and easy to explain. When you have a statistic for every gene, a ranked method usually uses the data better, because it does not throw away the information below the cutoff.
Pitfalls
- The wrong universe. Using all genes in the genome as the universe, when only the expressed genes could be selected, makes almost every set of expressed genes look enriched. The universe must be the genes that were measured and passed the filters.
- Genes outside the universe. Genes of the list or of a set that are not in the universe must be removed before counting, as lines L1 and L3 do.
- Correlated genes. The test treats the genes as independent units. Genes in a pathway are often correlated across samples, so they tend to be selected together, and the test gives p-values that are too small for the claim that the condition affects the pathway.
- Many overlapping sets. Thousands of nested terms are tested, so many significant terms say the same thing. Report the overlap, or reduce the collection first.
- Small and large sets. Very small sets give few attainable p-values, and very large sets, such as "cellular process", are rarely informative. Filter by size before testing, and report the filter.
- Length bias. For RNA-seq lists, ignoring the length bias favours long genes.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the biology pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Random variates, exact probability mass functions and test helpers for
the stochastic pages of the biology area.
Every sampler takes a random.Random object as its first argument and never
uses the module-level random functions. Each sampler draws its random
numbers in the order that its docstring gives, so two runs with the same
seed give the same output.
Conventions:
- A reaction network with n species and m reactions is given by `stoich`, a
list of the m change vectors nu_1, ..., nu_m. So stoich[j][i] is the entry
S[i][j] of the n by m stoichiometric matrix S.
- `propensity(x)` takes the state as a tuple of n integer counts and returns
the m propensities a_1(x), ..., a_m(x) as a sequence of floats >= 0.
- nbinom_pmf uses the mean mu and the dispersion alpha, with
Var = mu + alpha mu^2. The size is r = 1 / alpha; alpha = 0 is Poisson.
- hypergeom_pmf(k, total, good, draws) is the probability of k good items
in `draws` draws without replacement from `total` items of which `good`
are good.
Requires Python 3.12 or later (random.Random.binomialvariate).
"""
from __future__ import annotations
import math
from statistics import NormalDist
from typing import Callable, List, Sequence, Tuple
State = Tuple[int, ...]
_POISSON_PART = 30.0
# Random variates
def poisson(rng, lam: float) -> int:
"""A Poisson(lam) variate.
For lam <= 30, inversion of the cumulative distribution with one
rng.random() draw. For lam > 30, the sum of p = ceil(lam / 30)
independent Poisson(lam / p) variates, drawn one after the other by
inversion (one rng.random() draw each).
"""
if lam < 0 or math.isnan(lam):
raise ValueError("lam must be >= 0")
if lam == 0:
return 0
if lam > _POISSON_PART:
parts = math.ceil(lam / _POISSON_PART)
part = lam / parts
return sum(_poisson_inversion(rng, part) for _ in range(parts))
return _poisson_inversion(rng, lam)
def _poisson_inversion(rng, lam: float) -> int:
u = rng.random()
k = 0
p = math.exp(-lam)
cdf = p
while u >= cdf:
k += 1
p *= lam / k
if p == 0.0:
# Rounding left u above the computed total mass; stop at the tail.
break
cdf += p
return k
def binomial(rng, n: int, p: float) -> int:
"""A Binomial(n, p) variate by rng.binomialvariate (one call)."""
if n < 0 or not 0.0 <= p <= 1.0:
raise ValueError("need n >= 0 and 0 <= p <= 1")
if n == 0 or p == 0.0:
return 0
if p == 1.0:
return n
return rng.binomialvariate(n, p)
def multinomial(rng, n: int, probs: Sequence[float]) -> List[int]:
"""A Multinomial(n, probs) vector by conditional binomials.
probs are weights >= 0 with a positive sum; they need not sum to 1. Cell
i gets Binomial(rest of n, probs[i] / rest of the weight), for i in
order; the last cell with positive weight gets the rest.
"""
if n < 0:
raise ValueError("n must be >= 0")
w = [float(q) for q in probs]
if any(q < 0 for q in w):
raise ValueError("weights must be >= 0")
total = sum(w)
if total <= 0:
raise ValueError("weights must have a positive sum")
last = max(i for i, q in enumerate(w) if q > 0)
out = [0] * len(w)
left = n
rest = total
for i in range(last):
if left == 0:
break
if w[i] == 0:
continue
x = binomial(rng, left, min(1.0, w[i] / rest))
out[i] = x
left -= x
rest -= w[i]
out[last] += left
return out
def categorical(rng, weights: Sequence[float]) -> int:
"""An index i with probability weights[i] / sum(weights).
One draw u = rng.random() * sum(weights), then a cumulative search from
index 0. Indices with weight 0 are never returned.
"""
total = 0.0
for w in weights:
if w < 0:
raise ValueError("weights must be >= 0")
total += w
if total <= 0:
raise ValueError("weights must have a positive sum")
u = rng.random() * total
acc = 0.0
last = -1
for i, w in enumerate(weights):
if w > 0:
acc += w
last = i
if u < acc:
return i
return last
def ssa_direct(rng, x0: Sequence[int], stoich: Sequence[Sequence[int]],
propensity: Callable[[State], Sequence[float]], t_end: float,
max_events: int = 10 ** 6):
"""Gillespie's direct method from state x0 at time 0 up to time t_end.
Each step computes a = propensity(x) and a0 = sum(a). If a0 = 0 the run
stops. Otherwise it draws tau = rng.expovariate(a0) first. If
t + tau > t_end the run stops, and no second number is drawn. Else it
draws u = rng.random() * a0 and fires the first reaction j with
a_1 + ... + a_j > u (a linear search), then adds stoich[j] to x.
Returns (times, states, complete). times[0] = 0.0 and states[0] =
tuple(x0); entry k > 0 is the time and the state just after event k.
The state at t_end is states[-1]. complete is False only when the run
stopped because max_events events had fired before t_end.
"""
x = tuple(int(v) for v in x0)
times = [0.0]
states = [x]
t = 0.0
m = len(stoich)
for _ in range(max_events):
a = propensity(x)
a0 = 0.0
for v in a:
if v < 0:
raise ValueError("propensities must be >= 0")
a0 += v
if a0 <= 0.0:
return times, states, True
t += rng.expovariate(a0)
if t > t_end:
return times, states, True
u = rng.random() * a0
acc = 0.0
j = -1
for i in range(m):
if a[i] > 0:
acc += a[i]
j = i
if u < acc:
break
nu = stoich[j]
x = tuple(x[i] + nu[i] for i in range(len(x)))
times.append(t)
states.append(x)
return times, states, False
# Sample statistics and test helpers
def mean_var(xs) -> Tuple[float, float]:
"""The mean and the unbiased sample variance (divisor n - 1) by the
Welford method. The variance is 0.0 for fewer than two values."""
n = 0
mean = 0.0
m2 = 0.0
for x in xs:
n += 1
d = x - mean
mean += d / n
m2 += d * (x - mean)
if n == 0:
raise ValueError("empty sample")
return mean, (m2 / (n - 1) if n > 1 else 0.0)
def check_mean(m: float, mu: float, var: float, n: int, z: float = 4.0) -> bool:
"""True when |m - mu| <= z sqrt(var / n): a sample mean m of n
independent values with exact mean mu and exact variance var."""
return abs(m - mu) <= z * math.sqrt(var / n)
# Exact probability mass functions
def log_choose(n: int, k: int) -> float:
"""ln C(n, k), or -inf when k < 0 or k > n."""
if k < 0 or k > n:
return -math.inf
return math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1)
def binom_pmf(k: int, n: int, p: float) -> float:
"""P(K = k) for K ~ Binomial(n, p)."""
if k < 0 or k > n:
return 0.0
if p == 0.0:
return 1.0 if k == 0 else 0.0
if p == 1.0:
return 1.0 if k == n else 0.0
return math.exp(log_choose(n, k) + k * math.log(p) + (n - k) * math.log1p(-p))
def poisson_pmf(k: int, lam: float) -> float:
"""P(K = k) for K ~ Poisson(lam)."""
if k < 0:
return 0.0
if lam == 0:
return 1.0 if k == 0 else 0.0
return math.exp(k * math.log(lam) - lam - math.lgamma(k + 1))
def nbinom_pmf(k: int, mu: float, alpha: float) -> float:
"""P(K = k) for the negative binomial with mean mu and Var = mu + alpha mu^2."""
if k < 0:
return 0.0
if alpha == 0:
return poisson_pmf(k, mu)
if mu == 0:
return 1.0 if k == 0 else 0.0
r = 1.0 / alpha
return math.exp(math.lgamma(k + r) - math.lgamma(r) - math.lgamma(k + 1)
+ r * math.log(r / (r + mu)) + k * math.log(mu / (r + mu)))
def hypergeom_pmf(k: int, total: int, good: int, draws: int) -> float:
"""P(K = k) for k good items in `draws` draws without replacement from
`total` items of which `good` are good."""
if k < 0 or k > good or draws - k < 0 or draws - k > total - good:
return 0.0
return math.exp(log_choose(good, k) + log_choose(total - good, draws - k)
- log_choose(total, draws))
def logsumexp(xs) -> float:
"""ln(sum of exp(x)) without overflow; -inf for an empty input."""
xs = list(xs)
if not xs:
return -math.inf
top = max(xs)
if top == -math.inf:
return -math.inf
if top == math.inf:
return math.inf
return top + math.log(sum(math.exp(x - top) for x in xs))
# Tail probabilities
def _gamma_q(a: float, x: float) -> float:
"""The regularized upper incomplete gamma function Q(a, x)."""
if a <= 0:
raise ValueError("a must be > 0")
if x <= 0:
return 1.0
log_front = -x + a * math.log(x) - math.lgamma(a)
if x < a + 1.0:
# Series for P(a, x).
ap = a
term = 1.0 / a
total = term
for _ in range(100000):
ap += 1.0
term *= x / ap
total += term
if abs(term) < abs(total) * 1e-16:
break
return max(0.0, 1.0 - total * math.exp(log_front))
# Continued fraction for Q(a, x), by the modified Lentz method.
tiny = 1e-300
b = x + 1.0 - a
c = 1.0 / tiny
d = 1.0 / b
h = d
for i in range(1, 100000):
an = -i * (i - a)
b += 2.0
d = an * d + b
if abs(d) < tiny:
d = tiny
c = b + an / c
if abs(c) < tiny:
c = tiny
d = 1.0 / d
delta = d * c
h *= delta
if abs(delta - 1.0) < 1e-16:
break
return math.exp(log_front) * h
def chi2_sf(x: float, df: float) -> float:
"""P(X > x) for X chi-squared with df degrees of freedom."""
if df <= 0:
raise ValueError("df must be > 0")
if x <= 0:
return 1.0
return _gamma_q(df / 2.0, x / 2.0)
_STD_NORMAL = NormalDist()
def normal_sf(x: float, mu: float = 0.0, sigma: float = 1.0) -> float:
"""P(X > x) for X ~ Normal(mu, sigma^2), by statistics.NormalDist."""
return _STD_NORMAL.cdf(-(x - mu) / sigma)
over_representation_analysis.py 70 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/over-representation-analysis/. The authors are listed in prov/4AHTW8.jsonl.
"""Over-representation analysis with the hypergeometric (one-sided Fisher) test.
The universe U holds the N genes that could have been selected. The list D
of selected genes is cut to U, so n = |D|. For a gene set S, cut to U, with
K = |S| members, of which k are selected, the p-value is
P(X >= k) = sum_{i=k}^{min(K, n)} C(K, i) C(N - K, n - i) / C(N, n),
the upper tail of the hypergeometric distribution. It is computed with
exact integers. The p-values of all sets are then adjusted by the
Benjamini-Hochberg method.
"""
from __future__ import annotations
import math
from fractions import Fraction
from typing import Dict, Hashable, Iterable, List, Mapping, Sequence
def hypergeom_upper_tail(k: int, total: int, good: int, draws: int) -> Fraction:
"""P(X >= k) for X good items among `draws` drawn without replacement from
`total` items of which `good` are good, as an exact fraction."""
if not 0 <= good <= total or not 0 <= draws <= total:
raise ValueError("need 0 <= good, draws <= total")
lo = max(k, 0, draws - (total - good))
hi = min(good, draws)
num = sum(math.comb(good, i) * math.comb(total - good, draws - i) for i in range(lo, hi + 1)) # @line L4
return Fraction(num, math.comb(total, draws))
def bh_adjust(p: Sequence[float]) -> List[float]:
"""Benjamini-Hochberg adjusted p-values, min over j >= r of m p_(j) / j, capped at 1."""
m = len(p)
order = sorted(range(m), key=lambda i: p[i])
out = [0.0] * m
run = 1.0
for r in range(m, 0, -1):
i = order[r - 1]
run = min(run, m * p[i] / r)
out[i] = run
return out
def ora(selected: Iterable[Hashable], universe: Iterable[Hashable],
gene_sets: Mapping[str, Iterable[Hashable]], min_size: int = 1) -> Dict[str, dict]:
"""Test every gene set with at least min_size members in the universe.
Returns, for each tested set: k (selected members), K (members in the
universe), expected (n K / N), p and q (the BH-adjusted p-value).
"""
u = set(universe)
d = set(selected) & u # @line L1
total, draws = len(u), len(d)
rows = {}
for name, members in gene_sets.items(): # @line L2
s = set(members) & u # @line L3
if len(s) < min_size:
continue
k = len(s & d)
p = hypergeom_upper_tail(k, total, len(s), draws)
rows[name] = {"k": k, "K": len(s), "expected": draws * len(s) / total if total else 0.0,
"p": float(p)}
names = list(rows)
q = bh_adjust([rows[x]["p"] for x in names]) # @line L5
for x, v in zip(names, q):
rows[x]["q"] = v
return rows # @line L6
test_over_representation_analysis.py 88 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/over-representation-analysis/. The authors are listed in prov/4AHTW8.jsonl.
import itertools
import math
import random
from fractions import Fraction
import pytest
from biostoch import hypergeom_pmf
from over_representation_analysis import bh_adjust, hypergeom_upper_tail, ora
def test_matches_enumeration_of_all_selections():
# The null: every n-subset of the universe is equally likely to be the list.
for total in range(1, 8):
for good in range(total + 1):
members = set(range(good))
for draws in range(total + 1):
counts = {}
for sub in itertools.combinations(range(total), draws):
k = len(members.intersection(sub))
counts[k] = counts.get(k, 0) + 1
n_sub = math.comb(total, draws)
for k in range(-1, draws + 2):
brute = Fraction(sum(c for x, c in counts.items() if x >= k), n_sub)
assert hypergeom_upper_tail(k, total, good, draws) == brute
def test_equals_one_sided_fisher_from_two_binomials():
# Condition two independent binomials with the same p on their sum: the
# conditional law of the first is hypergeometric, for every p.
for total, good, draws in [(7, 3, 4), (10, 4, 5), (9, 2, 6)]:
for p in (Fraction(1, 3), Fraction(3, 4)):
def b(n, i):
return math.comb(n, i) * p ** i * (1 - p) ** (n - i)
joint = {i: b(good, i) * b(total - good, draws - i)
for i in range(max(0, draws - total + good), min(good, draws) + 1)}
z = sum(joint.values())
for k in range(draws + 1):
cond = sum(v for i, v in joint.items() if i >= k) / z
assert hypergeom_upper_tail(k, total, good, draws) == cond
def test_agrees_with_the_shared_pmf():
rng = random.Random(51)
for _ in range(100):
total = rng.randint(1, 3000)
good = rng.randint(0, total)
draws = rng.randint(0, total)
k = rng.randint(0, min(good, draws))
tail = sum(hypergeom_pmf(i, total, good, draws) for i in range(k, min(good, draws) + 1))
assert math.isclose(float(hypergeom_upper_tail(k, total, good, draws)), tail,
rel_tol=1e-8, abs_tol=1e-300)
def test_bh_adjust():
q = bh_adjust([0.01, 0.04, 0.03, 0.2])
for x, y in zip(q, [0.04, 0.16 / 3, 0.16 / 3, 0.2]):
assert math.isclose(x, y, rel_tol=1e-12)
assert bh_adjust([]) == []
assert bh_adjust([0.9, 0.8]) == [0.9, 0.9]
def test_page_example():
universe = ["g%d" % i for i in range(1, 21)]
selected = ["g1", "g2", "g3", "g4", "g5", "x1"]
sets = {"A": ["g1", "g2", "g3", "g6"], "B": ["g4", "g7", "g8", "g9", "g10", "g11"],
"C": ["g12", "g13", "y1"]}
res = ora(selected, universe, sets)
assert (res["A"]["k"], res["A"]["K"]) == (3, 4)
assert res["A"]["p"] == float(Fraction(31, 969))
assert (res["B"]["k"], res["B"]["K"]) == (1, 6)
assert res["C"]["K"] == 2 and res["C"]["p"] == 1.0
assert math.isclose(res["A"]["expected"], 1.0)
assert ora(selected, universe, sets, min_size=3).keys() == {"A", "B"}
def test_universe_cuts_the_list_and_the_sets():
full = ora(["a", "b", "z"], ["a", "b", "c", "d"], {"S": ["a", "b", "q"]})
assert full["S"]["k"] == 2 and full["S"]["K"] == 2
assert full["S"]["p"] == float(Fraction(1, 6))
def test_errors():
with pytest.raises(ValueError):
hypergeom_upper_tail(1, 3, 4, 1)
History
Fisher described the exact test for a 2 by 2 table, whose null law is hypergeometric, in 1935. After the Gene Ontology was published in 2000 and microarrays gave long lists of changed genes, many tools tested the terms and pathways of a database for enrichment in a list, mostly with this test or the chi-squared test. Goeman and Bühlmann (2007) showed that such tests sample genes rather than subjects, and so assume that genes are independent. Young et al. (2010) corrected the length bias of RNA-seq. Subramanian et al. (2005) proposed gene set enrichment analysis, partly to remove the need for a cutoff.
References
- Matthew D. Young, Matthew J. Wakefield, Gordon K. Smyth and Alicia Oshlack, Gene ontology analysis for RNA-seq, accounting for selection bias, Genome Biology 11(2) (2010), article R14, the bias of RNA-seq toward calling long and highly expressed genes, the probability weighting function fitted against gene length, and the weighted null distribution that corrects the bias
- Jelle J. Goeman and Peter Bühlmann, Analyzing gene expression data in terms of gene sets, methodological issues, Bioinformatics 23(8) (2007), pages 980 to 987, competitive and self-contained null hypotheses, and the assumption of independent genes behind tests that sample genes, such as the hypergeometric test
- Aravind Subramanian, Pablo Tamayo, Vamsi K. Mootha and others, Gene set enrichment analysis, a knowledge-based approach for interpreting genome-wide expression profiles, PNAS 102(43) (2005), pages 15545 to 15550, the critique of methods that depend on an arbitrary cutoff for the list of selected genes
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 4AHTW8 Edit this page History Report an error Markdown