Algorithm Search⌘K

Algorithmcore

Gene set enrichment analysis

Also called GSEA.

Walk down the genes ranked by association and test whether a set's members gather at the top with a weighted Kolmogorov-Smirnov statistic.

Time
Θ(b (n m + s n log n)) worst · best
Space
Θ(n + s b) extra
Where
b = the number of permutations; m = the number of samples; n = the number of genes; s = the number of gene sets
Properties
randomizednot exactofflineiterative
Origin
Vamsi K. Mootha, Aravind Subramanian, Pablo Tamayo, Jill P. Mesirov, 2003

Gene set enrichment analysis tests whether the members of a gene set tend to lie near the top or near the bottom of a ranking of all genes by their association with a phenotype. It does not need a cutoff. It walks down the ranked list, going up at each member of the set by an amount that depends on the member's score, and down at each other gene by a fixed step. The enrichment score is the point of the walk farthest from zero. With all members weighted equally, it is the signed two-sample Kolmogorov-Smirnov statistic of the positions of the members against the positions of the other genes. Its significance is assessed by a permutation test that shuffles the sample labels and recomputes the ranking, which keeps the correlation between genes. Mootha et al. (2003) introduced it, and Subramanian et al. (2005) gave its standard form. Unlike over-representation analysis, which counts members in a list cut at a threshold, it uses the full ranking, so a set of many genes that each change a little can be found.

In plain words

Sort all your genes from the most increased to the most decreased. Now take a pathway and mark its genes on that sorted list. If the pathway does not matter, its genes are spread evenly. If it matters, they bunch up near one end. To measure the bunching, walk down the list with a counter. Each time you pass a pathway gene, the counter goes up, more for genes with large changes. Each time you pass another gene, it goes down a little. The highest point the counter reaches is the score. To see whether that score is large, shuffle which samples are cases and which are controls many times, and see how often a shuffle gives a score as large.

The problem

Input. An expression matrix of nn genes in mm samples, a label per sample (group A or B), and a collection of ss gene sets.

Output. For each gene set: the enrichment score ES, the normalized score NES, a p-value, and the leading edge, the members that account for the score.

The walk. Let the genes in order of decreasing score be g1,…,gng_1, \dots, g_n, with scores r1≥⋯≥rnr_1 \ge \dots \ge r_n. Let SS have NHN_H members, and let NR=∑gj∈S∣rj∣pN_R = \sum_{g_j \in S}|r_j|^p. The running sum is

P(i)=∑j≤i, gj∈S∣rj∣pNR−∑j≤i, gj∉S1n−NH,P(i) = \sum_{j \le i,\ g_j \in S}\frac{|r_j|^p}{N_R} - \sum_{j \le i,\ g_j \notin S}\frac{1}{n - N_H},

and ES is the value of P(i)P(i) with the largest absolute value. The exponent pp is 1 by default; p=0p = 0 gives the unweighted walk.

The algorithm

  1. ENRICHMENT-SCORE(genes, r, S, p)
  2. 1order the genes by decreasing r, keeping the given order for equal scores
  3. 2w_j ← |r_j|^p for each member j of S; N_R ← Σ w_j
  4. 3P ← 0; ES ← 0
  5. 4for each gene j in that order do
  6. 5if j ∈ S then P ← P + w_j / N_R
  7. 6else P ← P - 1 / (n - N_H)
  8. 7if |P| > |ES| then ES ← P
  9. 8return ES

Line L1 ranks the genes. In the full method the scores rr are the signal-to-noise ratios (xˉA−xˉB)/(σA+σB)(\bar x_A - \bar x_B)/(\sigma_A + \sigma_B) of the genes, with the sample standard deviations. Line L2 sets the step of each member: with p=1p = 1, members with large scores count more. Lines L4 to L7 walk down the list and keep the running sum farthest from 0. The steps up add to 1 and the steps down add to 1, so the walk ends at 0. If all members have score 0, the code gives them equal weights.

Significance. The full method repeats the computation for bb shuffles of the sample labels: each shuffle gives new signal-to-noise ratios, a new ranking and a null score ES∗\mathrm{ES}^* per set. The code reports two p-values. The GSEA convention compares ES only with the null scores of the same sign: psign=(1+#{ES∗≥ES})/(1+#{ES∗≥0})p_{\text{sign}} = (1 + \#\{\mathrm{ES}^* \ge \mathrm{ES}\})/(1 + \#\{\mathrm{ES}^* \ge 0\}) when ES≥0\mathrm{ES} \ge 0, and the mirror image when it is negative. The second is the plain permutation p-value of the absolute score, pabs=(1+#{∣ES∗∣≥∣ES∣})/(1+b)p_{\text{abs}} = (1 + \#\{|\mathrm{ES}^*| \ge |\mathrm{ES}|\})/(1 + b). The normalized score NES divides ES by the mean absolute value of the null scores of the same sign, so that sets of different sizes can be compared. The leading edge is the set of members at or before the peak of the walk, for a positive ES.

Example

Eight genes, already ranked, with scores 2, 1.5, 1, 0.5, -0.2, -0.6, -1.2 and -2.5, and the set S={g1,g3,g6}S = \{g_1, g_3, g_6\}. So NH=3N_H = 3, each other gene moves the walk down by 1/5=0.21/5 = 0.2, and with p=1p = 1, NR=2+1+0.6=3.6N_R = 2 + 1 + 0.6 = 3.6.

ii 1 2 3 4 5 6 7 8
member yes no yes no no yes no no
step 0.556 -0.2 0.278 -0.2 -0.2 0.167 -0.2 -0.2
P(i)P(i) 0.556 0.356 0.633 0.433 0.233 0.400 0.200 0

The peak is at i=3i = 3, so ES=0.633\mathrm{ES} = 0.633 and the leading edge is {g1,g3}\{g_1, g_3\}. With p=0p = 0, each member adds 1/31/3, and the peak is again at i=3i = 3, with ES=2/3−0.2=0.467\mathrm{ES} = 2/3 - 0.2 = 0.467. This is the Kolmogorov-Smirnov statistic: at position 3, two of the three members and one of the five other genes have been passed, and 2/3−1/5=0.4672/3 - 1/5 = 0.467.

Correctness

The proof shows that the walk starts and ends at 0 and stays in [−1,1][-1, 1], so ES lies in [−1,1][-1, 1]. It shows that, with p=0p = 0, ES is the signed two-sample Kolmogorov-Smirnov statistic of the positions of the members, which is the sense in which the method is a weighted Kolmogorov-Smirnov test. The order of equal scores can change ES, so the code fixes it. For significance, the proof shows that pabsp_{\text{abs}} is a valid p-value, P(pabs≤a)≤aP(p_{\text{abs}} \le a) \le a, when the sample labels are exchangeable under the null hypothesis: by a rank argument with exact enumeration of the labellings, and by exchangeability with random shuffles, where the added 1 in the numerator and the denominator is needed. The p-value psignp_{\text{sign}} of the GSEA convention conditions on the sign of the null scores, and has no such guarantee. NES and the false discovery rates that GSEA computes from it are heuristics.

Proof: The GSEA running sum is a weighted Kolmogorov-Smirnov walk, and the absolute permutation p-value is validfull

We prove four facts. The running sum starts and ends at 0 and stays in [−1,1][-1, 1] (Lemma 1). With weight exponent p=0p = 0, the enrichment score is the signed two-sample Kolmogorov-Smirnov statistic of the positions of the members against the positions of the other genes (Theorem 2). The p-value p_abs from label permutations is valid when the sample labels are exchangeable under the null hypothesis, both with full enumeration (Theorem 3) and with random shuffles (Theorem 4). The GSEA p-value p_sign, which compares a score only with null scores of the same sign, has no such guarantee, and we do not claim one. That the signal-to-noise ratio is a good gene score is a heuristic.

Setting. There are NN genes with scores r1,…,rNr_1, \dots, r_N. Line L1 sorts them by decreasing score with a stable sort, so genes with equal scores keep their input order. Let g1,…,gNg_1, \dots, g_N be the genes in this order. The set SS has NHN_H members, with 0<NH<N0 < N_H < N. Line L2 sets the member weights wj=∣rgj∣pw_j = |r_{g_j}|^p and NR=∑gj∈SwjN_R = \sum_{g_j \in S} w_j; if NR=0N_R = 0 the code uses wj=1w_j = 1. Lines L3 to L6 compute

P(i)=∑j≤i, gj∈SwjNR−∑j≤i, gj∉S1N−NH,i=0,…,N,P(i) = \sum_{j \le i,\ g_j \in S}\frac{w_j}{N_R} - \sum_{j \le i,\ g_j \notin S}\frac{1}{N - N_H}, \qquad i = 0, \dots, N,

and line L7 keeps ES=P(i∗)\mathrm{ES} = P(i^*) for the first i∗i^* with the largest ∣P(i)∣|P(i)|.

Lemma 1 (range of the walk). P(0)=0P(0) = 0, P(N)=0P(N) = 0, and −1≤P(i)≤1-1 \le P(i) \le 1 for every ii. So −1≤ES≤1-1 \le \mathrm{ES} \le 1.

Proof. Write P(i)=H(i)−M(i)P(i) = H(i) - M(i), where H(i)H(i) is the first sum and M(i)M(i) the second. Both are sums of nonnegative terms that grow with ii, so 0≤H(i)≤H(N)0 \le H(i) \le H(N) and 0≤M(i)≤M(N)0 \le M(i) \le M(N). Here H(N)=∑gj∈Swj/NR=1H(N) = \sum_{g_j \in S} w_j/N_R = 1, and M(N)=(N−NH)/(N−NH)=1M(N) = (N - N_H)/(N - N_H) = 1. So P(N)=0P(N) = 0 and P(i)∈[−1,1]P(i) \in [-1, 1]. □\square

So ES is positive when the members gather at the top of the list, and negative when they gather at the bottom. In floating point, P(N)P(N) can differ from 0 by a rounding error.

Theorem 2 (the case p = 0). With p=0p = 0, ES=±D\mathrm{ES} = \pm D, where D=max⁡x∣FS(x)−FSˉ(x)∣D = \max_x |F_S(x) - F_{\bar S}(x)| is the two-sample Kolmogorov-Smirnov statistic of the positions {j:gj∈S}\{j : g_j \in S\} against the positions {j:gj∉S}\{j : g_j \notin S\}, with FSF_S and FSˉF_{\bar S} their empirical distribution functions. The sign is that of FS−FSˉF_S - F_{\bar S} at a point where the maximum is reached.

Proof. With p=0p = 0, every wj=1w_j = 1 and NR=NHN_R = N_H. So H(i)=#{j≤i:gj∈S}/NH=FS(i)H(i) = \#\{j \le i : g_j \in S\}/N_H = F_S(i) and M(i)=FSˉ(i)M(i) = F_{\bar S}(i). Both functions are step functions that change only at the integers 1,…,N1, \dots, N, so the supremum of ∣FS(x)−FSˉ(x)∣|F_S(x) - F_{\bar S}(x)| over all real xx is reached at an integer i∈{0,…,N}i \in \{0, \dots, N\}. Line L7 takes the value with the largest absolute value over exactly these ii. □\square

When the largest value max⁡iP(i)\max_i P(i) and the smallest value min⁡iP(i)\min_i P(i) have the same absolute value, the code keeps the one that comes first. The test file accepts either sign in this case. With p=1p = 1, the steps of the members are proportional to ∣r∣|r|, so the walk is a weighted version of the same statistic, and its null distribution is no longer the Kolmogorov-Smirnov law. This is why GSEA uses permutations.

Ties in the scores. The walk depends on the order of the genes, and so on the order of genes with equal scores. The code keeps the input order. Another tie rule can give another ES. This is a choice, not a theorem.

The permutation null. Let XX be the expression matrix with nn sample columns, and let LL be the observed vector of labels with nAn_A ones. For a labelling ℓ\ell, let T(ℓ,X)T(\ell, X) be the ES of SS when the genes are scored by the signal-to-noise ratio under ℓ\ell. The null hypothesis is exchangeability: for every permutation σ\sigma of the samples, the matrix XσX^\sigma with its columns permuted by σ\sigma has the same law as XX. Permuting the columns of the data and permuting the labels have the same effect on TT: T(L,Xσ)=T(Lσ−1,X)T(L, X^\sigma) = T(L^{\sigma^{-1}}, X), where Lσ−1L^{\sigma^{-1}} is LL with its entries moved by σ−1\sigma^{-1}.

Theorem 3 (exact enumeration). Let G\mathcal G be the set of all M=(nnA)M = \binom{n}{n_A} labellings with nAn_A ones. With exact set to True, the code computes

pabs=1+#{ℓ∈G, ℓ≠L:∣T(ℓ,X)∣≥∣T(L,X)∣}1+(M−1)=#{ℓ∈G:∣T(ℓ,X)∣≥∣T(L,X)∣}M.p_{\text{abs}} = \frac{1 + \#\{\ell \in \mathcal G,\ \ell \ne L : |T(\ell, X)| \ge |T(L, X)|\}}{1 + (M - 1)} = \frac{\#\{\ell \in \mathcal G : |T(\ell, X)| \ge |T(L, X)|\}}{M}.

Under exchangeability, P(pabs≤u)≤uP(p_{\text{abs}} \le u) \le u for every u∈[0,1]u \in [0, 1].

Proof. The first equality is what the code does, since it skips LL in the loop over G\mathcal G. For the second, add LL itself to the count.

For a fixed matrix xx, write π(ℓ,x)=#{ℓ′∈G:∣T(ℓ′,x)∣≥∣T(ℓ,x)∣}/M\pi(\ell, x) = \#\{\ell' \in \mathcal G : |T(\ell', x)| \ge |T(\ell, x)|\}/M, and let Au(x)={ℓ∈G:π(ℓ,x)≤u}A_u(x) = \{\ell \in \mathcal G : \pi(\ell, x) \le u\}. If Au(x)A_u(x) is not empty, take ℓ∗\ell^* in it with the smallest ∣T(ℓ∗,x)∣|T(\ell^*, x)|. Every ℓ∈Au(x)\ell \in A_u(x) has ∣T(ℓ,x)∣≥∣T(ℓ∗,x)∣|T(\ell, x)| \ge |T(\ell^*, x)|, so ∣Au(x)∣≤Mπ(ℓ∗,x)≤Mu|A_u(x)| \le M\pi(\ell^*, x) \le Mu.

Now let σ\sigma be a uniformly random permutation of the samples, independent of XX. By exchangeability, XX has the same law as XσX^\sigma, so P(π(L,X)≤u)=P(π(L,Xσ)≤u)P(\pi(L, X) \le u) = P(\pi(L, X^\sigma) \le u). Permuting the columns of xx permutes the labellings in G\mathcal G, so π(L,Xσ)=π(Lσ−1,X)\pi(L, X^\sigma) = \pi(L^{\sigma^{-1}}, X). Given XX, the labelling Lσ−1L^{\sigma^{-1}} is uniform on G\mathcal G, because every labelling with nAn_A ones is reached by the same number nA!(n−nA)!n_A!(n - n_A)! of permutations. So

P(pabs≤u)=E[∣Au(X)∣M]≤u.□P(p_{\text{abs}} \le u) = E\left[\frac{|A_u(X)|}{M}\right] \le u. \qquad \square

Theorem 4 (random shuffles). With exact set to False, the code draws labellings L1,…,LBL_1, \dots, L_B by shuffling with the given random generator, and computes pabs=(1+#{b:∣T(Lb,X)∣≥∣T(L,X)∣})/(1+B)p_{\text{abs}} = (1 + \#\{b : |T(L_b, X)| \ge |T(L, X)|\})/(1 + B). If each shuffle is a uniform permutation independent of the others and of XX, then P(pabs≤u)≤uP(p_{\text{abs}} \le u) \le u under exchangeability.

Proof. An in-place shuffle that is uniform gives a uniform arrangement whatever the starting order, so Lb=LσbL_b = L^{\sigma_b} for independent uniform permutations σb\sigma_b (up to the side on which they act, which does not change the argument). Let ρ\rho be one more uniform permutation, independent of all the others, and let Y=XρY = X^\rho, which has the law of XX under the null hypothesis. Then T(L,X)=T(Lτ0,Y)T(L, X) = T(L^{\tau_0}, Y) and T(Lb,X)=T(Lτb,Y)T(L_b, X) = T(L^{\tau_b}, Y) with τ0=ρ\tau_0 = \rho and τb=σbρ\tau_b = \sigma_b\rho in the matching order. Given ρ\rho, the τb\tau_b are independent and uniform, so τ0,τ1,…,τB\tau_0, \tau_1, \dots, \tau_B are independent uniform permutations, independent of YY in law. Hence the B+1B + 1 values ∣T(L,X)∣,∣T(L1,X)∣,…,∣T(LB,X)∣|T(L, X)|, |T(L_1, X)|, \dots, |T(L_B, X)| are exchangeable. The rank argument of Theorem 3, applied to these B+1B + 1 values, shows that the probability that the first one is among the values that give pabs≤up_{\text{abs}} \le u is at most uu. □\square

The added 1 in the numerator and the denominator is what makes Theorem 4 hold. Without it, pp can be 0 and the test is too liberal.

The same-sign p-value. GSEA compares a positive ES only with the nonnegative null scores, and a negative ES only with the negative ones. The number of null scores of each sign is random, and the comparison is not a rank among a fixed exchangeable collection, so the argument above does not apply. The code reports p_sign for comparison with the GSEA software and labels it as a convention. The normalized score NES, the ES divided by the mean absolute null score of the same sign, is a heuristic for comparing sets of different sizes.

Phenotype against gene permutation. Permuting sample labels keeps the correlation between genes, so the null includes the effect of coexpressed members. Permuting gene labels instead treats the members as a random set of genes. That null is too narrow when the members are correlated, and the p-values are then too small. This is a property of the model, not a theorem proved here.

What the tests check. The test file checks the page example, compares the walk with a brute force that recomputes H(i)H(i) and M(i)M(i) from their definitions, checks Theorem 2 against the Kolmogorov-Smirnov statistic computed from the two empirical distribution functions, checks the extreme cases ES=1\mathrm{ES} = 1 and ES=−1\mathrm{ES} = -1, and checks the signal-to-noise ratio. It checks Theorem 3 by measurement: over 300 null data sets with exact enumeration, the fraction of p_abs values at or below uu must not exceed uu by more than a sampling tolerance.

Complexity. One enrichment score takes O(Nlog⁡N)O(N\log N) time for the sort and O(N)O(N) for the walk. Scoring all genes takes O(Nn)O(Nn). With BB permutations and mm sets, the total is O(B(Nn+mNlog⁡N))O(B(Nn + m N\log N)); the sort can be shared between the sets, which gives O(B(Nn+Nlog⁡N+mN))O(B(Nn + N\log N + mN)). The extra space is O(N+mB)O(N + mB).

Complexity

On a real RAM, one enrichment score takes Θ(nlog⁡n)\Theta(n\log n) time for the sort at line L1 and Θ(n)\Theta(n) for the walk. Each permutation computes the nn signal-to-noise ratios in Θ(nm)\Theta(nm) time and then the scores of the ss sets. The code sorts again for each set, so the total is Θ(b(nm+snlog⁡n))\Theta(b(nm + sn\log n)). Sorting once per permutation and sharing the order between the sets lowers it to Θ(b(nm+nlog⁡n+sn))\Theta(b(nm + n\log n + sn)). The extra space is Θ(n)\Theta(n) for the ranking and Θ(sb)\Theta(sb) for the null scores.

Properties

  • No cutoff. All genes count, and the result does not depend on a threshold for significance.
  • Sign. A positive ES means that the members gather at the top, a negative ES at the bottom.
  • Weighted. With p=1p = 1, a few members with very large scores can produce a large ES alone. With p=0p = 0 the statistic depends only on the ranks.
  • Sample permutation keeps the correlation. Shuffling sample labels moves the values of all genes of a sample together, so the null distribution reflects the correlation between genes.
  • Few samples, few permutations. With 3 samples per group, there are only 20 labellings, so pabsp_{\text{abs}} cannot be smaller than 0.05.

Variants and improvements

  • Gene permutation. Shuffle the membership of the genes instead of the sample labels, as preranked GSEA does when only a ranked list is available. This tests a competitive null hypothesis and needs no samples, but it treats genes as independent, so correlated sets get p-values that are too small (Goeman and Bühlmann 2007).
  • Other gene scores. The signal-to-noise ratio can be replaced by a moderated t-statistic or a signed statistic from a count model, which handle few samples better.
  • Maxmean and restandardization. Efron and Tibshirani (2007) proposed a simpler statistic, the larger of the mean positive part and the mean negative part of the scores in the set, and combined the sample permutations with a gene randomization.
  • CAMERA. Wu and Smyth (2012) estimate the correlation between the genes of a set and correct the variance of a competitive test for it, without permutations.
  • Single-sample scores. Methods such as ssGSEA compute a walk per sample, giving a score for each set in each sample, which can then be used as a new variable.

When to use it

Use it when you have a statistic for every gene and want to know which pathways or programs move as a whole, especially when single genes change too little to pass a threshold. Use sample permutation when there are enough samples per group that the permutation p-values can be small. With fewer samples, use a ranked method that accounts for correlation, such as CAMERA, or interpret preranked results with care. When all you have is a list of genes, use over-representation analysis.

Pitfalls

  • Which p-value. psignp_{\text{sign}} compares ES with only part of the null distribution, and it is not a valid p-value in general. State which p-value is reported.
  • Ties. Many genes with the same score, such as genes with zero counts, make ES depend on their order. Break ties at random or remove such genes.
  • Few samples. With few samples, the number of distinct labellings is small. GSEA then often falls back to gene permutation, with the problem above.
  • Large sets. Very large sets almost always reach a moderate ES, and very small ones are noisy. Filter the sets by size before testing, and report the bounds.
  • Overlapping sets. Many sets share their leading edge genes and so report the same signal. Look at the leading edges before reporting many sets.
  • Standard deviations near zero. The signal-to-noise ratio is unstable when a gene barely varies. Filter such genes first.

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.

gene_set_enrichment_analysis.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gene-set-enrichment-analysis/. The authors are listed in prov/W39J2F.jsonl.
"""Gene set enrichment analysis (Subramanian et al. 2005).

enrichment_score walks down the genes in order of decreasing score r. A
member j of the set S adds |r_j|^p / N_R, with N_R the sum of |r_j|^p over
the members; a non-member subtracts 1 / (N - N_H), with N_H members among
N genes. The enrichment score ES is the value of the running sum farthest
from 0. With p = 0 it is the signed two-sample Kolmogorov-Smirnov statistic
of the member positions against the other positions. Genes with equal scores
keep the order in which they are given.

gsea scores the genes by the signal-to-noise ratio
(mean_A - mean_B) / (sd_A + sd_B), with sample standard deviations, and
builds a null by permuting the sample labels (all distinct assignments when
exact is True). It reports two p-values:

- p_sign, the GSEA convention: compare ES with the null scores of the same
  sign only, here with one added to both counts so that p is never 0;
- p_abs = (1 + #{|ES*| >= |ES|}) / (1 + B), a permutation p-value that is
  valid when the labels are exchangeable under the null hypothesis.

The normalized score is NES = ES / mean of the null scores with the sign of ES.
"""

from __future__ import annotations

import itertools
import math
from typing import Dict, Hashable, List, Mapping, Sequence, Tuple


def enrichment_score(genes: Sequence[Hashable], scores: Sequence[float],
                     gene_set, p: float = 1.0) -> Tuple[float, List[float]]:
    """(ES, running sum) for genes with these scores; the order is by decreasing score."""
    n = len(genes)
    if len(scores) != n:
        raise ValueError("need one score per gene")
    members = set(gene_set)
    order = sorted(range(n), key=lambda i: -scores[i])  # @line L1
    hits = [i for i in order if genes[i] in members]
    n_h = len(hits)
    if n_h == 0 or n_h == n:
        raise ValueError("the set must hold some but not all of the genes")
    weights = [abs(scores[i]) ** p for i in hits]  # @line L2
    n_r = sum(weights)
    if n_r == 0:
        weights = [1.0] * n_h
        n_r = float(n_h)
    weight = dict(zip(hits, weights))
    miss = 1.0 / (n - n_h)
    run = 0.0  # @line L3
    best = 0.0
    path = []
    for i in order:  # @line L4
        if i in weight:
            run += weight[i] / n_r  # @line L5
        else:
            run -= miss  # @line L6
        path.append(run)
        if abs(run) > abs(best):  # @line L7
            best = run
    return best, path  # @line L8


def leading_edge(genes: Sequence[Hashable], scores: Sequence[float], gene_set, p: float = 1.0) -> List[Hashable]:
    """The members at or before the peak (for ES > 0) or at or after it (for ES < 0)."""
    es, path = enrichment_score(genes, scores, gene_set, p)
    order = sorted(range(len(genes)), key=lambda i: -scores[i])
    peak = next(i for i, v in enumerate(path) if v == es)
    members = set(gene_set)
    part = order[: peak + 1] if es >= 0 else order[peak:]
    return [genes[i] for i in part if genes[i] in members]


def signal_to_noise(row: Sequence[float], labels: Sequence[int]) -> float:
    """(mean_A - mean_B) / (sd_A + sd_B), for label 1 (A) against label 0 (B)."""
    a = [x for x, c in zip(row, labels) if c == 1]
    b = [x for x, c in zip(row, labels) if c == 0]
    if len(a) < 2 or len(b) < 2:
        raise ValueError("need two samples in each group")
    ma, mb = sum(a) / len(a), sum(b) / len(b)
    sa = math.sqrt(sum((x - ma) ** 2 for x in a) / (len(a) - 1))
    sb = math.sqrt(sum((x - mb) ** 2 for x in b) / (len(b) - 1))
    if sa + sb == 0:
        raise ValueError("a gene has no variation")
    return (ma - mb) / (sa + sb)


def _all_es(expr, genes, labels, gene_sets, p):
    r = [signal_to_noise(row, labels) for row in expr]
    return {name: enrichment_score(genes, r, s, p)[0] for name, s in gene_sets.items()}


def gsea(expr: Sequence[Sequence[float]], genes: Sequence[Hashable], labels: Sequence[int],
         gene_sets: Mapping[str, Sequence[Hashable]], rng=None, n_perm: int = 1000,
         p: float = 1.0, exact: bool = False) -> Dict[str, dict]:
    """ES, NES, p_sign and p_abs for each set, by phenotype permutation."""
    labels = list(labels)
    observed = _all_es(expr, genes, labels, gene_sets, p)
    null: Dict[str, List[float]] = {name: [] for name in gene_sets}
    if exact:
        n_a = sum(labels)
        for chosen in itertools.combinations(range(len(labels)), n_a):
            lab = [0] * len(labels)
            for i in chosen:
                lab[i] = 1
            if lab == labels:
                continue
            for name, v in _all_es(expr, genes, lab, gene_sets, p).items():
                null[name].append(v)
    else:
        if rng is None:
            raise ValueError("a random.Random object is needed for sampled permutations")
        lab = labels[:]
        for _ in range(n_perm):
            rng.shuffle(lab)
            for name, v in _all_es(expr, genes, lab, gene_sets, p).items():
                null[name].append(v)
    out = {}
    for name, es in observed.items():
        z = null[name]
        same = [v for v in z if (v >= 0) == (es >= 0)]
        if es >= 0:
            beyond = sum(v >= es for v in same)
        else:
            beyond = sum(v <= es for v in same)
        nes = es / (sum(abs(v) for v in same) / len(same)) if same else math.nan
        out[name] = {
            "es": es,
            "nes": nes,
            "p_sign": (1 + beyond) / (1 + len(same)),
            "p_abs": (1 + sum(abs(v) >= abs(es) for v in z)) / (1 + len(z)),
        }
    return out
test_gene_set_enrichment_analysis.py 150 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gene-set-enrichment-analysis/. The authors are listed in prov/W39J2F.jsonl.

import math
import random

import pytest

from gene_set_enrichment_analysis import enrichment_score, gsea, leading_edge, signal_to_noise

GENES = ["g%d" % i for i in range(1, 9)]
SCORES = [2.0, 1.5, 1.0, 0.5, -0.2, -0.6, -1.2, -2.5]


def brute_es(genes, scores, members, p):
    """For each cut i, hit(i) - miss(i) from the definition, and the value farthest from 0."""
    order = sorted(range(len(genes)), key=lambda i: -scores[i])
    hits = [i for i in order if genes[i] in members]
    nr = sum(abs(scores[i]) ** p for i in hits)
    miss_total = len(genes) - len(hits)
    devs = [0.0]
    for cut in range(1, len(order) + 1):
        top = order[:cut]
        hit = sum(abs(scores[i]) ** p for i in top if genes[i] in members) / nr
        miss = sum(1 for i in top if genes[i] not in members) / miss_total
        devs.append(hit - miss)
    return max(devs), min(devs)


def agrees(es, extremes):
    """ES is the extreme deviation; when the largest and the smallest have equal size, either sign is right."""
    hi, lo = extremes
    if math.isclose(hi, -lo, rel_tol=1e-9, abs_tol=1e-12):
        return math.isclose(abs(es), hi, rel_tol=1e-9, abs_tol=1e-12)
    want = hi if hi > -lo else lo
    return math.isclose(es, want, rel_tol=1e-9, abs_tol=1e-12)


def ks_statistic(sample_a, sample_b):
    """The signed two-sample Kolmogorov-Smirnov statistic sup (F_a - F_b), by the empirical cdfs."""
    devs = [0.0]
    for x in sorted(set(sample_a) | set(sample_b)):
        fa = sum(v <= x for v in sample_a) / len(sample_a)
        fb = sum(v <= x for v in sample_b) / len(sample_b)
        devs.append(fa - fb)
    return max(devs), min(devs)


def test_page_example():
    s = {"g1", "g3", "g6"}
    es, path = enrichment_score(GENES, SCORES, s, p=1)
    assert math.isclose(es, 5 / 6 - 0.2, rel_tol=1e-12)
    expected = [5 / 9, 5 / 9 - 0.2, 5 / 6 - 0.2, 5 / 6 - 0.4, 5 / 6 - 0.6, 0.4, 0.2, 0.0]
    for a, b in zip(path, expected):
        assert math.isclose(a, b, rel_tol=1e-12, abs_tol=1e-12)
    assert leading_edge(GENES, SCORES, s) == ["g1", "g3"]
    es0, _ = enrichment_score(GENES, SCORES, s, p=0)
    assert math.isclose(es0, 2 / 3 - 0.2, rel_tol=1e-12)


def test_matches_brute_force():
    rng = random.Random(61)
    for _ in range(200):
        n = rng.randint(2, 30)
        genes = list(range(n))
        scores = [rng.gauss(0, 1) for _ in range(n)]
        k = rng.randint(1, n - 1)
        members = set(rng.sample(genes, k))
        for p in (0, 1, 2):
            assert agrees(enrichment_score(genes, scores, members, p)[0],
                          brute_es(genes, scores, members, p))


def test_p_zero_is_the_kolmogorov_smirnov_statistic():
    rng = random.Random(62)
    for _ in range(100):
        n = rng.randint(2, 25)
        genes = list(range(n))
        scores = [rng.random() for _ in range(n)]
        members = set(rng.sample(genes, rng.randint(1, n - 1)))
        order = sorted(range(n), key=lambda i: -scores[i])
        pos_in = [r for r, i in enumerate(order) if i in members]
        pos_out = [r for r, i in enumerate(order) if i not in members]
        es = enrichment_score(genes, scores, members, p=0)[0]
        assert agrees(es, ks_statistic(pos_in, pos_out))


def test_extremes_and_end_of_walk():
    genes = list(range(10))
    scores = [10 - i for i in range(10)]
    assert enrichment_score(genes, scores, {0, 1, 2}, p=0)[0] == pytest.approx(1.0)
    assert enrichment_score(genes, scores, {7, 8, 9}, p=0)[0] == pytest.approx(-1.0)
    assert abs(enrichment_score(genes, scores, {2, 5, 7}, p=1)[1][-1]) < 1e-12
    with pytest.raises(ValueError):
        enrichment_score(genes, scores, set(), p=1)
    with pytest.raises(ValueError):
        enrichment_score(genes, scores, set(genes), p=1)


def test_signal_to_noise():
    assert math.isclose(signal_to_noise([1, 3, 6, 10], [1, 1, 0, 0]), (2 - 8) / (math.sqrt(2) + math.sqrt(8)))
    with pytest.raises(ValueError):
        signal_to_noise([1, 2, 3], [1, 0, 0])


def make_data(rng, genes, shift_genes, shift, labels):
    expr = []
    for g in range(genes):
        row = [rng.gauss(0, 1) for _ in labels]
        if g in shift_genes:
            row = [x + shift * c for x, c in zip(row, labels)]
        expr.append(row)
    return expr


def test_permutation_results_and_determinism():
    rng = random.Random(63)
    labels = [1] * 5 + [0] * 5
    expr = make_data(rng, 60, set(range(10)), 2.0, labels)
    genes = list(range(60))
    sets = {"up": list(range(10)), "random": list(range(30, 40))}
    a = gsea(expr, genes, labels, sets, rng=random.Random(7), n_perm=200)
    b = gsea(expr, genes, labels, sets, rng=random.Random(7), n_perm=200)
    assert a == b
    assert a["up"]["es"] > 0 and a["up"]["nes"] > 1
    assert a["up"]["p_abs"] < 0.05 and a["up"]["p_sign"] < 0.05
    for v in a.values():
        assert 0 < v["p_abs"] <= 1 and 0 < v["p_sign"] <= 1
        assert (v["nes"] >= 0) == (v["es"] >= 0)
    with pytest.raises(ValueError):
        gsea(expr, genes, labels, sets)


def test_exact_enumeration_p_value_is_valid_under_the_null():
    # Under the null every one of the C(6, 3) = 20 label assignments is equally
    # likely, so P(p_abs <= u) <= u. Checked at u = 0.1 and 0.25 over 300 null data sets,
    # with the binomial tolerance 4 sqrt(u (1 - u) / 300).
    rng = random.Random(64)
    labels = [1, 1, 1, 0, 0, 0]
    genes = list(range(12))
    sets = {"S": [0, 1, 2, 3]}
    ps = []
    for _ in range(300):
        expr = make_data(rng, 12, set(), 0.0, labels)
        res = gsea(expr, genes, labels, sets, exact=True)
        ps.append(res["S"]["p_abs"])
    assert min(ps) >= 1 / 20
    for u in (0.1, 0.25):
        frac = sum(p <= u for p in ps) / len(ps)
        assert frac <= u + 4 * math.sqrt(u * (1 - u) / len(ps))

History

Mootha et al. (2003) introduced the method to find that genes of oxidative phosphorylation, each only slightly lower, were together lower in muscle from people with type 2 diabetes. That first form used an unweighted Kolmogorov-Smirnov statistic. Subramanian et al. (2005) added the weights, the normalized score, the leading edge and the MSigDB collection of gene sets, and released the software. Goeman and Bühlmann (2007), Efron and Tibshirani (2007) and Wu and Smyth (2012) analysed its null hypotheses and proposed alternatives.

References

  1. 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 weighted running sum, the enrichment score, the phenotype permutations, the nominal p-value from the part of the null distribution with the sign of the score, the normalized score, and the leading edge
  2. Vamsi K. Mootha, Cecilia M. Lindgren, Karl-Fredrik Eriksson and others, PGC-1 alpha-responsive genes involved in oxidative phosphorylation are coordinately downregulated in human diabetes, Nature Genetics 34(3) (2003), pages 267 to 273, the first form of the method, with a Kolmogorov-Smirnov statistic over the ranked genes and permutations of the sample labels
  3. 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 why permuting genes rather than samples ignores the correlation between genes
  4. Bradley Efron and Robert Tibshirani, On testing the significance of sets of genes, Annals of Applied Statistics 1(1) (2007), pages 107 to 129, the maxmean statistic and restandardization, which combine the sample permutations with the gene randomization
  5. Di Wu and Gordon K. Smyth, Camera, a competitive gene set test accounting for inter-gene correlation, Nucleic Acids Research 40(17) (2012), article e133, the variance inflation of competitive tests from the correlation between genes, and a test that estimates it

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