Algorithm Search⌘K

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
Properties
deterministicexactofflineiterative
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 UU of NN genes, the genes that were measured and could have been selected; a list DD of selected genes; and a collection of gene sets S1,…,SsS_1, \dots, S_s.

Output. For each gene set SS: the number K=∣S∩U∣K = |S \cap U| of its members in the universe, the number k=∣S∩D∣k = |S \cap D| of selected members, the expected number nK/NnK/N with n=∣D∩U∣n = |D \cap U|, a p-value, and an adjusted p-value.

Null hypothesis. The selected list is a uniformly random subset of UU of size nn, independent of membership in SS. 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

  1. ORA(D, U, sets)
  2. 1D ← D ∩ U; N ← |U|; n ← |D| ▷ drop genes outside the universe
  3. 2for each gene set S in sets do
  4. 3S ← S ∩ U; K ← |S|; k ← |S ∩ D|
  5. 4p_S ← Σ_{i=k}^{min(K, n)} C(K, i) C(N - K, n - i) / C(N, n) ▷ hypergeometric upper tail
  6. 5q ← BENJAMINI-HOCHBERG(p)
  7. 6return (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 KK counts only the members that could have been selected. Line L4 sums the hypergeometric probabilities of kk 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 U={g1,…,g20}U = \{g_1, \dots, g_{20}\}, so N=20N = 20. The list is g1,…,g5g_1, \dots, g_5 and a gene x1x_1 that is not in UU, so line L1 drops x1x_1 and n=5n = 5.

set members KK kk expected p q
A g1,g2,g3,g6g_1, g_2, g_3, g_6 4 3 1 0.0320 0.0960
B g4,g7,…,g11g_4, g_7, \dots, g_{11} 6 1 1.5 0.871 1
C g12,g13,y1g_{12}, g_{13}, y_1 2 0 0.5 1 1

For set A, P(X≥3)=((43)(162)+(44)(161))/(205)=(480+16)/15504=31/969=0.0320P(X \ge 3) = (\binom43\binom{16}{2} + \binom44\binom{16}{1})/\binom{20}{5} = (480 + 16)/15504 = 31/969 = 0.0320. For set B, P(X≥1)=1−(145)/(205)=1−2002/15504=0.871P(X \ge 1) = 1 - \binom{14}{5}/\binom{20}{5} = 1 - 2002/15504 = 0.871. Set C loses y1y_1 at line L3, so K=2K = 2. The adjusted value of A is 3⋅0.0320/1=0.09603 \cdot 0.0320/1 = 0.0960. 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 UU of size nn has at least kk members in SS, so it is a valid p-value for the null hypothesis above: P(pS≤a)≤aP(p_S \le a) \le a for every aa, 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 nn genes from the universe puts at least kk 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 UU has NN genes. Line L1 cuts the list of selected genes to UU, which gives D⊆UD \subseteq U with n=∣D∣n = |D|. Line L3 cuts each set to UU, which gives S⊆US \subseteq U with K=∣S∣K = |S| and k=∣S∩D∣k = |S \cap D|. Line L4 computes

p=∑i=kmin⁡(K,n)(Ki)(N−Kn−i)(Nn),p = \sum_{i=k}^{\min(K, n)} \frac{\binom{K}{i}\binom{N-K}{n-i}}{\binom{N}{n}},

with the terms outside the range max⁡(0,n−(N−K))≤i\max(0, n - (N - K)) \le i left out, since they are 0.

Lemma 1 (the hypergeometric law). Let X=∣S∩R∣X = |S \cap R|, where RR is a subset of UU of size nn chosen uniformly at random and SS is fixed. Then P(X=i)=(Ki)(N−Kn−i)/(Nn)P(X = i) = \binom{K}{i}\binom{N-K}{n-i}\big/\binom{N}{n}.

Proof. There are (Nn)\binom{N}{n} subsets of size nn, all equally likely. A subset with ∣S∩R∣=i|S \cap R| = i is fixed by choosing ii members of SS and n−in - i genes of U∖SU \setminus S, which can be done in (Ki)(N−Kn−i)\binom{K}{i}\binom{N-K}{n-i} ways. □\square

Theorem 2 (exact p-value). The value returned for SS is P(X≥k)P(X \ge k) for XX as in Lemma 1, computed without rounding before the final conversion to a float.

Proof. By Lemma 1, P(X≥k)P(X \ge k) 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 (Nn)\binom{N}{n} as an exact fraction. Only the final call to float rounds. □\square

The exact arithmetic matters in the far tail. A sum of floating point terms near 10−30010^{-300} can underflow, and the complement 1−P(X<k)1 - P(X < k) loses all its digits when P(X≥k)P(X \ge k) is small.

Theorem 3 (equality with the one-sided Fisher test). Write the 2 by 2 table with rows "in SS" and "not in SS" and columns "selected" and "not selected", with margins KK, N−KN - K, nn and N−nN - n. Suppose the genes of SS are selected independently with probability π1\pi_1 each, and the genes outside SS with probability π0\pi_0 each. If π1=π0\pi_1 = \pi_0, then given nn, the count kk has the law of Lemma 1. So pp is the p-value of the one-sided Fisher exact test of π1=π0\pi_1 = \pi_0 against π1>π0\pi_1 > \pi_0.

Proof. Let Y1=k∼Bin⁡(K,π)Y_1 = k \sim \operatorname{Bin}(K, \pi) and Y0=n−k∼Bin⁡(N−K,π)Y_0 = n - k \sim \operatorname{Bin}(N - K, \pi), independent, with the common value π∈(0,1)\pi \in (0, 1). Then Y1+Y0∼Bin⁡(N,π)Y_1 + Y_0 \sim \operatorname{Bin}(N, \pi), and

P(Y1=i∣Y1+Y0=n)=(Ki)πi(1−π)K−i(N−Kn−i)πn−i(1−π)N−K−n+i(Nn)πn(1−π)N−n=(Ki)(N−Kn−i)(Nn).P(Y_1 = i \mid Y_1 + Y_0 = n) = \frac{\binom{K}{i}\pi^i(1-\pi)^{K-i}\binom{N-K}{n-i}\pi^{n-i}(1-\pi)^{N-K-n+i}}{\binom{N}{n}\pi^n(1-\pi)^{N-n}} = \frac{\binom{K}{i}\binom{N-K}{n-i}}{\binom{N}{n}}.

The factor π\pi cancels, so the conditional law does not depend on the unknown π\pi. 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 π1>π0\pi_1 > \pi_0, which are the tables with Y1≥kY_1 \ge k. □\square

Validity. Under the null hypothesis, XX is a discrete variable and p=P(X≥k)p = P(X \ge k) is its upper tail at the observed value. For a discrete variable, P(P(X≥Xobs)≤u)≤uP(P(X \ge X_{\text{obs}}) \le u) \le u for every u∈[0,1]u \in [0, 1]: let x∗x^* be the smallest value with P(X≥x∗)≤uP(X \ge x^*) \le u; then the event is {Xobs≥x∗}\{X_{\text{obs}} \ge x^*\}, which has probability P(X≥x∗)≤uP(X \ge x^*) \le u. 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 UU. A gene outside UU is removed from the list and from every set, so it changes nn and KK. Taking all genes of the genome as UU, when only the expressed genes could have been selected, makes NN too large and pp too small for every set of expressed genes. This is a fact about the model, and the tests check that the cut to UU changes pp as the formula says.

What the tests check. The test file enumerates every subset RR of size nn of a small universe and counts the subsets with ∣S∩R∣≥k|S \cap R| \ge k (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, p=31/969p = 31/969 for set A.

Complexity. The cut to UU takes O(N+∑S∣S∣)O(N + \sum_S |S|) expected time with hash sets. For one set, line L4 sums at most min⁡(K,n)+1\min(K, n) + 1 terms with integers of O(N)O(N) bits, so the cost is polynomial in NN; a floating point version on the log scale costs O(min⁡(K,n))O(\min(K, n)) operations. The BH step sorts the mm p-values in O(mlog⁡m)O(m\log m) time.

Complexity

On a real RAM, with hash sets, line L1 takes O(u)O(u) time, where u=Nu = N is the size of the universe. For a set of KK members, line L3 takes O(K)O(K) time, and line L4 takes O(min⁡(K,n))O(\min(K, n)) arithmetic operations if each term is computed from the previous one by the ratio of binomial coefficients. Since K≤uK \le u, the loop takes O(su)O(su) time in the worst case and less when the sets are small. The adjustment at line L5 sorts the ss p-values, in Θ(slog⁡s)\Theta(s\log s) 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 Θ(u+s)\Theta(u + s).

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, P(pS≤a)P(p_S \le a) is often less than aa, so the test is valid but loses some power.
  • Depends on the cutoff. The list DD 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 NN even when DD and SS 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.

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)
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

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

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