Fast gene set enrichment analysis ================================= * Gennady Korotkevich * Vladimir Sukhov * Nikolay Budin * Boris Shpak * Maxim N. Artyomov * Alexey Sergushichev ## Abstract Gene set enrichment analysis (GSEA) is an ubiquitously used tool for evaluating pathway enrichment in transcriptional data. Typical experimental design consists in comparing two conditions with several replicates using a differential gene expression test followed by preranked GSEA performed against a collection of hundreds and thousands of pathways. However, the reference implementation of this method cannot accurately estimate small P-values, which significantly limits its sensitivity due to multiple hypotheses correction procedure. Here we present FGSEA (Fast Gene Set Enrichment Analysis) method that is able to estimate arbitrarily low GSEA P-values with a high accuracy in a matter of minutes or even seconds. To confirm the accuracy of the method, we also developed an exact algorithm for GSEA P-values calculation for integer gene-level statistics. Using the exact algorithm as a reference we show that FGSEA is able to routinely estimate P-values up to 10−100 with a small and predictable estimation error. We systematically evaluate FGSEA on a collection of 605 datasets and show that FGSEA recovers much more statistically significant pathways compared to other implementations. FGSEA is open source and available as an R package in Bioconductor ([http://bioconductor.org/packages/fgsea/](http://bioconductor.org/packages/fgsea/)) and on GitHub ([https://github.com/ctlab/fgsea/](https://github.com/ctlab/fgsea/)). ## 1 Main Preranked gene set enrichment analysis (GSEA) [1] is a widely used method for analyzing gene expression data, particularly for datasets with small number of replicates. It allows to select from an *a priori* defined collection of pathways those which have non-random behavior in a considered experiment (Fig 1a). The method uses an enrichment score (ES) statistic which is calculated based on a vector of gene-level signed statistics, such as *t*-statistic from a differential expression test. As the analytical form of the null distribution for the ES statistic is not known, empirical null distribution has to be calculated. That can be done in a straightforward manner by sampling random gene sets as was done in the reference implementation [1] and reimplementations [2, 3], In this case for each of the input pathways a number of random gene sets of the same size are generated, and for each of them an ES value is calculated. Then a P-value is estimated as the number of random gene sets with the same or more extreme ES value divided by the total number of generated gene sets (a formal definition is available in the section 2.1). Finally, a multiple hypothesis correction procedure is applied to get adjusted P-values. ![Figure 1:](http://biorxiv.org/https://www.biorxiv.org/content/biorxiv/early/2021/02/01/060012/F1.medium.gif) [Figure 1:](http://biorxiv.org/content/early/2021/02/01/060012/F1) Figure 1: Gene Set Enrichment Analsyis (GSEA) sensitivity depends on the ability to reach high sampling depth, **a**, Overview of preranked GSEA method, **b**, The number of pathways reaching Benjamini-Hochberg adjusted P-value threshold depends on the sampling depth in a phase transition manner. The critical sampling depth, where the transition happens, varies with the dataset, **c**, Distribution of critical sampling depth values across 605 curated datasets from Gene Expression Omnibus, as estimated for three pathway collections, **d**, Time required for the reference GSEA implementation to estimate P-values for different gene set collections and sampling depth values for dataset GSE22293. N/A values indicate out of memory errors. However, a large number of generated random gene sets can be required to reach a given false discovery rate (FDR) level on some datasets. As an example, we calculated GSEA P-values for Gene Ontology Biological Pathways collection (C5_BP subset of MSigDB collection [1]) on four datasets from Gene Expression Omnibus (GEO) varying the sampling depth, and calculated the number of pathways reaching FDR level of 0.01 after Benjamini-Hochberg (BH) correction. Due to the properties of BH procedure, the dependence of the number of significant pathways in these experiments has a phase transition behavior (Fig 1b): for each of the datasets there exist a certain critical sampling depth after which the number of significant pathways becomes non-zero and stays on the same level. This critical sampling depth is different for different datasets, but ultimately can reach the order of *M*/*α*, where *α* is the selected FDR threshold and *M* is the number of considered pathways. To systematically asses the distribution of GSEA critical sampling depth on real datasets we prepared a collection of 605 microarray datasets from Gene Expression Omnibus (GEO) containing only two biological condistions. For each of these datasets we ran the differential expression analysis and used the results as gene-level statistics. We discovered that more than half of the datasets has the critical sampling depth of at least 104 and a noticeable portion (10–20% depending on the collection) has the critical sampling depth of at least 105 (Fig 1c). When a large pathway collection is considered (entire MSigDB collection) individual datasets has values of critical sampling depths reaching 5 · 106. However, even running the reference implementation with the sampling depth of *n* = 104 routinely is inconvenient and running it with *n* = 105 can be impossible due to the time and memory consumption (Fig 1d): time and memory requirements grow linearly with the number of samples and the collection size. To improve applicability of preranked GSEA analysis we present a fast gene set enrichment analysis (FGSEA) method for accurate and efficient estimation of GSEA P-values for a collection of pathways. The method consist of two main procedures: *FGSEA-simple* and *FGSEA-multilevel*. FGSEA-simple procedure allows to efficiently estimate P-values with a limited accuracy but simultaneously for the whole *collection* of gene sets, while FGSEA-multilevel procedure allows to accurately estimate arbitrarily low P-values but for *individual* gene sets. FGSEA-simple procedure is based on an idea that generated random gene set samples can be shared between different input pathways. Indeed, consider *M* gene sets of the sizes *K*1 ⩽ *K*2 ⩽ … ⩽ *KM* = *K* and a collection of *n* independent samples *gi* of size *K* (Fig 2a). As in the naive approach, due to *gi* being independent samples of the size *K* the P-value for the pathway *M* can be estimated as a proportion of samples *gi* having the same or more extreme ES value as the pathway *M*. However, for any other pathway *j* we can construct a set of *n* independent samples of size *Kj* by considering the prefixes *g**i*,1..*Kj*. Again, given a set of independent samples, the P-value can be estimated as a proportion of the samples having the same or more extreme ES value. ![Figure 2:](http://biorxiv.org/https://www.biorxiv.org/content/biorxiv/early/2021/02/01/060012/F2.medium.gif) [Figure 2:](http://biorxiv.org/content/early/2021/02/01/060012/F2) Figure 2: Preranked gene set enrichment analysis can be sped up by sharing sampling information between different gene set sizes, **a**, It is sufficient to generate *n* independent samples of size *KM* to calculate empirical distribution for any sizes *Kj* ⩽ *KM* by considering only the prefix of the samples of the size *Kj* **b**, For a given gene sample enrichment scores for all the prefixes can be efficiently calculated by employing a square root heuristic, **c**, The P-values calculated with the FGSEA-simple method are consistent with the reference implementation, but the results are obtained hundreds times faster. The next important idea is that given a gene set sample *gi* of the size *K* the ES values for *all* the prefixes *g**i*,1..*j* can be calculated in an efficient manner using a square root heuristic (Fig 2b). Briefly, a variant of an enrichment curve is considered: the genes are enumerated starting from the most up-regulated to the most down-regulated, with the curve going to the right if the gene is not present in the pathway, and the curve goes upward if the gene is present in the pathway. It can be shown that the enrichment score can be easily calculated if curve point most distant from the diagonal is known. Let us split *K* genes from the gene set into ![Graphic][1] consecutive blocks of size ![Graphic][2] and consider what happens with the curve when we change the prefix from *g**i*,1..*j*−1 to *g**i*,1..*j* by adding gene *gi,j*. The curve in the blocks to the left of *gi,j* are not changed at all, while the blocks to the right of *gi,j* are uniformly shifted. This observation allows us to consider the prefixes in an increasing order and update the position of the most distant point in ![Graphic][3] time. Briefly, for the each block which is either not changed or shifted the update procedure takes *O*(1) time, while for the changed block the update procedure is proportional to its size and takes ![Graphic][4] time. Finally, aggregating the blocks takes additional ![Graphic][5] time. Overall this results in time complexity of ![Graphic][6] to calculate ES values for all the prefixes. In total, the time complexity of the calculating P-values for the set of *M* pathways is ![Graphic][7], which gives around ![Graphic][8] speed up compared to a naive approach. The full description of the algorithm is given in the section 2.3. As an example we ran FGSEA-simple and the reference implementations on the same example dataset of genes differentially regulated on Thl activation [4] against a set of 700 Reactome [5] pathways (see section 2.2) and compared the resulting nominal P-values (Fig 2c). Both methods were ran with *n* = 10000 and the results are indistinguishable from each other up to the random noise inherent to both methods. However, on this example the reference implementation took about 420 seconds, while FGSEA-simple finished in about 4 seconds. The two order of magnitude speed-up is consistent with the theoretical one due to the algorithm time complexity. Given a highly parallel implementation of FGSEA-simple, its performance allows to routinely achieve sampling depth of 105 and accurately estimate P-values as low as 10−5. However, accurately estimating P-values lower than 10−5 with FGSEA-simple can be impractical or even infeasible. To estimate such low P-values we developed *FGSEA-multilevel* method, which is based on an adaptive multi-level split Monte Carlo scheme [6], The method takes as an input an ES value *γ* > 0 and a gene set size *K*, and calculates the probability *PK* (ES ⩾ *γ*) of a random gene set of size *K* to have an enrichment score no less than *γ*. The method sequentially finds ES levels *li* for which the probability *PK*(ES ⩾ *li*) is approximately equal to 2−*i* (see Fig 3a for a toy example). The method stops when *li* becomes greater than *γ* and the P-value can be crudely approximated as 2−*i*. ![Figure 3:](http://biorxiv.org/https://www.biorxiv.org/content/biorxiv/early/2021/02/01/060012/F3.medium.gif) [Figure 3:](http://biorxiv.org/content/early/2021/02/01/060012/F3) Figure 3: Adaptive multilevel Monte Carlo sampling scheme can be used to calculate arbitrarily low P-values. **a**, A toy illustration of the multilevel split Monte Carlo scheme for sample size of *Z* = 5. **b**, Comparison of GSEA P-values as calculated by FGSEA-simple method run with the sampleing depth *n* = 108 and FGSEA-multilevel with the sample size of Z=101. **c**, Comparison of P-values as calculated with an exact method and FGSEA-multilevel method. Both methods were run on gene-level statistic values rounded to integers. **d**, Comparison between estimated and an observed error of *log*2 P-values for different P-values (from 10−4 to 10−100), gene set sizes (from 15 to 250) and sample sizes (from 101 to 1001). **d**, An example of FGSEA results as run with FGSEA-multilevel method for Th0 vs Th1 comparison and Reactome pathways. The analysis was run with sample size of *Z* =101. Redundant pathways were filtered. The intermediate *li* thresholds are calculated as follows. First, a set of *Z* (an odd number, parameter of the method) random gene sets of size *K* are generated uniformly and ES values for them are calculated. The median value of the ES values is calculated and assigned to *l*1. By construction, the probability *PK*(*γ* ⩾ *l*1) of a random gene set to have an ES value no less than *l*1 can be approximated as ![Graphic][9]. Next ![Graphic][10] generated gene sets with the ES values less than *l*1 are discarded, while ![Graphic][11] gene sets with the ES values greater than *l*1 are duplicated. This results in a sample of *Z* gene sets with the ES values no less than *l*1, but the distribution is non-uniform. However, it can be made into a uniform sample with a Metropolis algorithm. On each Metropolis algorithm step each gene set sample is tried to be modified by swapping a random gene from the set with a gene outside of the set. The change is accepted if an enrichment score of the new set is no less then current threshold *l*1, otherwise the change is rejected. Metropolis algorithm guarantees, that after enough steps the sample becomes close to uniformly distributed. Thus, a median of the enrichment scores (*l*2) would correspond to probability of ![Graphic][12] for a gene set to have an enrichment score no less than *l*2 given it has an enrichment score no less than *l*1: ![Formula][13] Which means ![Formula][14] The same procedure is applied to calculate the next *li* values. The iterations stop when *li* becomes greater than *γ*. On this iteration the probability of a random gene set to have a ES value no less than *γ* can be approximated as: ![Formula][15] When estimating small P-values it becomes practical to carry out the estimation in logscale. In particular, the values become practically unbiased both in median and mean sense and it becomes simple to estimate the approximation error and condifence intervals (see section 2.5.4). The full formal description of the algorithm is available in the section 2.5. For the example dataset we show that P-values are as low as 10−26 for some of the pathways and the results are consistent with FGSEA-simple P-values ran on 108 permutations (Fig 3b). Note, that FGSEA-multilevel calculation with sample size of Z=lOl took only 10 seconds working on a single thread while 108 permutations on FGSEA-simple took 40 minutes working in 32 threads. To further prove the approximation quality of FGSEA-multilevel algorithm we developed an exact method for calculating GSEA P-values, but limited to integer weights. The method is based on dynamic programming, the full description is given in section 2.4. The complexity of the algorithm is *O*(*NKT*2), where *N* is the number of genes, *K* is the size of gene sets and *T* is the sum of the top *K* absolute values of gene-level statistics. With a number of optimizations this method allows to calculate P-values for rounded weights in the example dataset in a couple of hours. When run on the same integer weights FGSEA-multilevel and the exact method give highly concordant results (Fig 3c). Additionally, using the exact P-values, real approximation errors can be compared with the estimated ones. We show, that the FGSEA-multilevel error estimation are highly concordant with the real errors (Fig 3d) for a wide range of P-values (from 10−4 to 10−100), gene set sizes (from 15 to 250) and sample sizes (from 101 to 1001). In practice FGSEA-multilevel method is combined with FGSEA-simple. First, for all the input pathways FGSEA-simple method can be run with a limited sample size. Next, for the pathways that have high relative error after FGSEA-simple (i.e. pathways with low p-values) FGSEA-multilevel method is executed. As many of the pathways in an input collection usually are not enriched, they have a relatively high P-value and will be batch-processed with a highly efficient FGSEA-simple algorithm with deterministic time boundaries. The more interesting pathways with lower P-values will then be processed with FGSEA-multilevel algorithm individually and the amount of processing time will depend on their P-values. As FGSEA allows to practically estimate the P-values for a large collections of gene sets, it can lead to a large number of statistically significant hits with high overlaps. To deal with this issue and make the representation of FGSEA results more concise we developed a procedure to filter the redundant gene sets. The procedure is similar to GO Trimming method [7] but is based on the Bayesian network construction approaches. It considers the significant pathways one by one and tries to remove gene sets that do not provide new information given some other pathway already present in the output. In this case, we consider a pathway *P*1 to give a new information given a pathway *P*2 if the P-value of pathway *P*1 in the universe of genes just from *P*2, or just from genes out side of *P*2, is less than some threshold. This procedure allows to filter redundant pathways without requirement of having any explicit hierarchy of pathways. The full description of the procedure is given in section 2.6. The table resulting from running FGSEA on the example dataset with filtering of redundant hits is shown on Fig 3e. Finally, we have explored FGSEA performance on the collection of 605 curated GEO datasets described earlier and the C5_BP pathway collection. Notably, it took less then a minute per dataset of running time to finish FGSEA analysis with the multilevel algorithm (Fig 4a) on a laptop with 4-core Intel Core i5 processor, with a median time of 8 seconds. Besides the multilevel algorithm, the same analysis was carried out with FGSEA-simple algorithm with the sampling depth values of *n* = 10/ 104 and 105, and the reference implementation (Broad GSEA) with the sampling depth of 104. For all these methods we compared the number of pathways reaching FDR level of 0.01: BH-adjusted P-values were used for FGSEA and reported Q-values (*Broad Q-values*) were used for the reference implementation (Fig 4b). The results reiterate that even sampling depth of 105 is not enough to detect statistically significant enriched pathways for some of the datasets when BH-adjustment procedure is used. ![Figure 4:](http://biorxiv.org/https://www.biorxiv.org/content/biorxiv/early/2021/02/01/060012/F4.medium.gif) [Figure 4:](http://biorxiv.org/content/early/2021/02/01/060012/F4) Figure 4: FGSEA method with the multilevel approach detects more statistically significant pathways compared to other GSEA implementations in a fraction of time. All plots represent data from analysis of the collection of 605 cureated GEO datasets with C5_BP used as a gene set collection, **a**, Wall clock time of running FGSEA. **b**, The number of detected statistically significant pathways for different adjusted P-value calculation procedures. Pathways with small BH-adjusted P-value after FGSEA-multilevel are shown in grey. Pathways with small BH-adjusted P-value after FGSEA-simple are shown in blue, orange and green, depending on the sampling depth. Pathways with small Q-values as reported by Broad GSEA are shown in red. **c**, Comparison of BH-adjusted P-values for FGSEA-multilevel and Q-values reported by Broad GSEA. For illustration purposes all values are capped at 10−5. **d**, Same as *c* but average pathway sizes are shown. The *ad hoc* procedure implemented in Broad GSEA aggregates ES values generated across different pathways increasing the sensitivity on some of the datasets compared to BH-adjusted P-values for the same sampling depth of 104, however this increase in sensitivity comes with overall more conservative behavior. The total number of pathways reaching FDR level of 0.01 for Broad Q-values is 39467, which is only 60% of 65690 pathways for BH-adjustment P-values with the sampling depth of 104 and 48% of 81628 pathways for the multilevel algorithm. We further characterized this behavior by directly comparing Broad Q-values with BH-adjusted P-values and have shown that Broad Q-values are individually more conservative (Fig 4c) in a pathway size dependent manner (Fig 4d). To conclude, here we have presented FGSEA method for fast preranked gene set enrichment analysis. The method allows to routinely estimate even very low P-values and can be used with conjunction with standard multiple hypothesis testing correction methods, such as Benjamini-Hochberg procedure. This, in turn, leads to better sensitivity and the ability to detect significant pathways in hard cases, where other implementations fail. FGSEA method is freely available as an R package at Bioconductor ([http://bioconductor.org/packages/fgsea](http://bioconductor.org/packages/fgsea)) and on GitHub ([https://github.com/ctlab/fgsea](https://github.com/ctlab/fgsea)). ## 2 Methods ### 2.1 Formal definitions The preranked gene set enrichment analysis takes as input two objects: an array of gene-level statistic values *S* for the genes *U* = {1, 2,…, *N*} and a list of query gene sets (pathways) *P*. The goal of the analysis is to determine which of the gene sets from *P* has a non-random behavior. The statistic array *S* of the size |*S*| = *N* for each gene *i* ∈ *U* contains a value ![Graphic][16] that characterizes the gene behavior in a considered biological process. Commonly, if *Si* > 0 the expression of gene *i* goes up on treatment compared to control and *Si* < 0 means that the expression goes down. Absolute values |*Si*| represent magnitude of the change. Array *S* is sorted in a decreasing order: *Si* > *Sj* for *i* < *j*. The value of *N* in practice is about 10000–20000. The list of gene sets *P* = {*P*1, *P*2,…, *PM*} of length *M* usually contains groups of genes that are commonly regulated in some biological process. We assume that the gene sets *Pi* are ordered by their size (denoted as *Ki*): *K*1 ⩽ *K*2 ⩽ … ⩽ *KM* = *K*. Usually only relatively small gene sets are considered with *K* ≈ 500 genes. To quantify a co-regulation of genes in a gene set *p* Subramanian *et al*.[1] introduced a gene set enrichment score function *sr*(*p*) that uses gene rankings (values of *S*). The more positive is the value of *sr*(*p*) the more enriched the gene set is in the positively-regulated genes (with *Si* > 0). Accordingly, negative *sr*(*p*) corresponds to enrichment in the negatively regulated genes. Value of *sr*(*p*) can be calculated as follows. Let *k* = |*p*|, NS = Σ*i*∈*p*|*Si*|. Let al so ES be an array specified by the following formula: ![Formula][17] The value of *sr*(*p*) corresponds to the largest by the absolute value entry of ES: ![Formula][18] For convenience, we also introduce the following notation: ![Formula][19] From these two values it easy to find value of *sr*(*p*), which is equal to ![Graphic][20] if ![Graphic][21] or ![Graphic][22] otherwise. Often we will consider only the positive values of the gene set enrichment score function since: ![Formula][23] where ![Graphic][24] and ![Graphic][25] corresponds to the gene set enrichment score function for array *S*′ such that ![Graphic][26]. Next, following Subramanian *et al* for a pathway *p* we define GSEA P-value as: ![Formula][27] where *q* is a random gene set of size *k*. ### 2.2 The datasets A collection of 605 curated datasets was generated from a set of all curated datasets (GDS) in Gene Expression Omnibus. Only the datasets with two biological conditions were kept. Differential expression was done using limma. The moderated t-statistic was used for gene ranking. Only top 10000 genes by average expression were used in ranking. The final rankings are available at [https://ctlab.itmo.ru/files/software/fgsea/geo_ranks/](https://ctlab.itmo.ru/files/software/fgsea/geo_ranks/). Pathway collections C2\_REACTOME, C5\_BP, C2, C5, MSigDB were obtained via msigdbr package. LINCS perturbation collection was downloaded from Enrichr web-site. The corresponding gmt files are available at [https://ctlab.itmo.ru/files/software/fgsea/gmts/](https://ctlab.itmo.ru/files/software/fgsea/gmts/). As the example ranking ThO vs Thl comparison was used from dataset GSE14308 [4], The differential expression was calculated using limma [8], Only top 12000 genes by mean expression were used. Limma t-statistic was used as gene-level statistic. The script to generate rankings is available on GitHub: [https://github.com/ctlab/fgsea/blob/master/inst/gen\_gene\_ranks.R](https://github.com/ctlab/fgsea/blob/master/inst/gen_gene_ranks.R). Reactome [5] database was used as an example collection via reactome.db R package. For the analysis only the pathways of the size from 15 to 500 were used. The script to generate pathway collection is available on GitHub: [https://github.com/ctlab/fgsea/blob/master/inst/gene\_reactome\_pathwavs.R](https://github.com/ctlab/fgsea/blob/master/inst/gene_reactome_pathwavs.R) ### 2.3 FGSEA-simple: an algorithm for fast calculation of GSEA P-values simultaneously for many pathways In this section we describe an algorithm for fast estimation of GSEA P-values simultaneously for a collection of pathways *P*. There, for each pathway *p* a set of *n* uniformly random gene sets *qi* are considered. Then P-value is estimated as: ![Formula][28] for positively enriched pathway *p* and as: ![Formula][29] for negatively enriched pathway. These two formulas follow Subramanian *et al*. implementation, except of +1 terms, which are recommended by Phipson and Smyth [9], Otherwise, the nominal P-values from FGSEA-simple and reference implementation are indistinguishable, however FGSEA-simple works orders of magnitude faster. #### 2.3.1 Cumulative statistic calculation for the mean statistic Let first describe the idea of the proposed algorithm on a simple mean statistic *sm*: ![Formula][30] The main idea of the algorithm is to reuse sampling for different query gene sets. This can be done due to the fact that for an estimation of null distributions samples have to be independent only for a specific gene set size, while they can be dependent between different sizes. Instead of generating *nM* independent random gene sets: *n* for each of *M* input gene sets, we will generate only *n* random gene sets of size *K*. Let *πi* be an *i*-th random gene set of size *K*. From that gene set we can generate gene sets for a all the query pathways *Pj* by using its prefix: *πi,j* = *πi*[1..*Kj*]. The next step is to calculate the enrichment scores for all gene sets *πi,j*. Instead of calculating enrichment scores separately for each gene set we will calculate simultaneously scores for all *πi,j* for a fixed *i*. Using a simple procedure it can be done in Θ(*K*) time. Let us find enrichment scores for all prefixes of *πi*. This can be done by element-wise dividing of cumulative sums array by the length of the corresponding prefix: ![Formula][31] Selecting only the required prefixes takes an additional Θ(*m*) time. The described procedure allows to find P-values for all query gene sets in Θ(*n*(*K* + *m*)) time. This is about min(*K, m*) times faster than the straightforward procedure. #### 2.3.2 Cumulative statistic calculation for enrichment score For the enrichment score *Sr* we use the similar idea as above: we will also be sampling only gene sets of size *K* and from that sample will calculate statistic values for all the other sizes. However, calculation of the cumulative statistic values for the subsamples is more complex in this case. In this section we only be considering the positive mode of enrichment statistic ![Graphic][32]. It is helpful to look at enrichment score from a geometric point of view. Let us consider for a pathway *p* of size |*p*| = *k* a graph of *N* + 1 points (Fig. S1) with the coordinates (*xi, yi*) for 0 ⩽ *i* ⩽ *N* such that: ![Formula][33] ![Formula][34] ![Formula][35] ![Figure S1:](http://biorxiv.org/https://www.biorxiv.org/content/biorxiv/early/2021/02/01/060012/F5.medium.gif) [Figure S1:](http://biorxiv.org/content/early/2021/02/01/060012/F5) Figure S1: A graph that corresponds to a calculation of enrichment score. Each breakpoint on a graph corresponds to a gene present in the pathway. Dotted lines cross at a point which is the farthest up from a diagonal (dashed line). This point correspond to gene *i*+, where the maximal value of ES*i* is reached. The calculation of ![Graphic][36] corresponds to finding the point farthest up from a diagonal ((*x*, *y*), (*xN, yN*)). Indeed, it is easy to see that *xN* = *N* – |*p*| = *N* – *K* and *yN* = Σ*j*∈*p*|*Sj*| = NS, while the individual enrichment scores ES*i* can be calculated as ![Graphic][37]. Value of ES*i* is proportional to the directed distance from the line going through (*x*, *y*) and (*xN, yN*) to the point (*xi, yi*). Let us fix a sample *π* of size *K*. To efficiently calculate cumulative values ![Graphic][38] for all *k* ⩽ *K* we need a fast method of updating the farthest point when a new gene is added. In that case we can add genes from *π* one by one and calculate values ![Graphic][39] from the corresponding maximal distances. Because we are calculating values for *π*[1..*k*] for *k* ⩽ *K* we know in advance which *K* genes will be added. This allows us to consider *K* + 1 points instead of *N* + 1 for each iteration *k*. Let array *o* of size *K* contain the sorted order of genes in *π*: that is, *π**o*1 is the minimal among *π, π**θ*2 is the second minimal and so on. The coordinates can be calculated as follows: ![Formula][40] ![Formula][41] ![Formula][42] where we set *π**θ* to be zero. It can be shown that finding the farthest up point among (4)–(6) is equivalent to finding the farthest up point among (1)–(3) with ![Graphic][43] being equal to ![Graphic][44] calculated for *p* = *π*[1..*k*]. Consider ![Graphic][45]. By the definition of *x* it is equal to: ![Formula][46] By the definition of *o*, in the interval [*π**o**i*-1 + 1, *πoi* – 1] there are no genes from *π* and, thus, from *π*[1..*k*]. Thus we can replace the sum with its last member: ![Formula][47] We got the same difference as in (5). Now consider ![Graphic][48]. By the definition of *y* it is equal to: ![Formula][49] Again, in the interval [*π**o**i*−1 + 1, *πoi* – 1] there are no genes from *π*[1..*k*]. Thus we can replace the sum with only the last member: ![Formula][50] We got the same difference as in (6). We do not need to consider other points, because points from *o**i*−1 to *oi* − 1 have the same *y* coordinate and *o**i*−1 is the leftmost of them. Thus, when at least one gene is added the diagonal ((*x*, *y*), (*xN, yN*)) is not horizontal and *o**i*−1 is the farthest point among *o**i*−1,…, *oi* − 1. Now let consider what happens with the enrichment score graph when gene *πk* is added to the query set *π*[1..*k* – 1] (Fig. S2). Let *rk* be a rank of gene *π*2 among genes *π*, then coordinate of points (*xi, yi*) for *i* < *rk* do not change, while all (*xi, yi*) for *i* ⩾ *rk* are changed on (Δ*x*, Δ*y*) = (−1, |*Sπk*|). ![Figure S2:](http://biorxiv.org/https://www.biorxiv.org/content/biorxiv/early/2021/02/01/060012/F6.medium.gif) [Figure S2:](http://biorxiv.org/content/early/2021/02/01/060012/F6) Figure S2: Update of an enrichment score graph when gene *πk* ≈ 800 is added. Only a fragment is shown. Black graph corresponds to a graph for gene set *π*[1..*k* − 1], gray graph corresponds to *π*[1..*k*], A part of the graph to the left of *x* = *xrk* does not change and the other part is shifted to the top-left corner. The diagonal ((*x*, *y*), (*xN, yN*)) is rotated counterclockwise. To make fast incremental updates we will decompose the problem into multiple smaller ones. For simplicity we assume that *K* + 1 is an exact square of an integer *b*. Let split *K* +1 points into *b* consecutive blocks of the size *b*:![Graphic][51] and so on. For each of *b* blocks we will store and update the farthest up point from the diagonal. When we know for each block its farthest point we can find the globally farthest point by a simple pass in *O*(*b*) time. Next, we show how to update the farthest points in blocks in amortized time *O*(*b*). This taken together with one *O*(*b*) pass will get us an algorithm to update the globally farthest point in amortized *O*(*b*) time. Below we use *c* = ⌊*rk*/*b*⌋ as an index of a block where gene *πk* belongs, where *rk* is the ranking of the genes from *π*, i.e. *roi* = *i*. First, we describe the procedure to update point coordinates. We will store *xi* coordinates using two vectors: *B* of size *b* and D of size *K* + 1, such th at *xi* = *Bi/b* + *Di*. When gene *πk* is added all *xi* for *i* ⩾ *rk* are decremented by one. To reflect this we will decrement all *Bj* for *j* > *c* and decrement all *Di* for *rk* ⩽ *i* < *cb*. The update takes *O*(*b*) time. After this update procedure we can get value *xi* in *O*(1) time. The same procedure is applied for *y* coordinates. Second, for each block we will maintain an upper part of its convex hull. Having convex hull is useful because the farthest point in block always lays on its convex hull. All blocks except *c* have the points either not changed or shifted simultaneously on the same value. That means that the lists of points on the convex hulls for these blocks remain unchanged. For the block *c* we can reconstruct convex hull from scratch using Graham scan algorithm [10]. Because the points are already sorted by *x* coordinate, this reconstruction takes *O*(*b*) time. In total, it takes *O*(*b*) time to update the convex hulls. Third, the farthest points in blocks can be updated using the stored convex hulls. Consider a block where the convex hull was not changed (every block except, possibly, block *c*). Because diagonal always rotates in the same counterclockwise direction, the farthest point in block on iteration *k* either stays the same or moves on the convex hull to the left of the farthest point on the (*k* − 1)-th iteration. Thus, for each such block we can compare current farthest point with its left neighbor on the convex hull and update the point if necessary. It is repeated until the next neighbor is closer to the diagonal than the current farthest point. In the block c we just find the farthest point in a single pass by the points on the convex hull. To show that the updating the farthest points takes *O*(*b*) amortized time we will use potential method. Let a potential after adding *k*-th gene Φ*k* be a sum of relative indexes of the farthest points for all the blocks. As there are *b* blocks of size *b* the sum of relative indexes lies between 0 and *b*2. Thus, Φ*k* = *O*(*b*2). For an update of all *b* − 1 blocks except *c* we need to make *tk* = *b* − 1 + *z* operations of comparing two points, where *z* is the number of times the farthest points were updated. This can take up to Θ(*b*2) time in the worst case. However, it can be noticed, that potential change Φ*k* − Φ*k*−1 is equal to −*z* + *O*(*b*): the sum of indexes is decreased by a number of times the farthest points were updated plus *O*(*b*) for the block c where the index can go from 0 to *b* − 1. This gives an amortized cost of *k*-th iteration to be *ak* = *tk* + Φ*k* − Φ*k*−1 = *b* − 1 + *z* − *z* + *O*(*b*) = *O*(*b*). The total real cost of *K* iterations is ![Graphic][52], which means amortized cost of one iteration to be *O*(*b*). Taken together the algorithm allows to find all cumulative enrichment scores *sr*(*π*[1..*k*]) in ![Graphic][53] time. The straightforward implementation of calculating cumulative values from scratch would take *O*(*K*2 log *K*) time. Thus, we have improved the performance ![Graphic][54] times. #### 2.3.3 Implementation details We also implemented an optimization so that the algorithm does not build convex hull from scratch for a changed block *c*, but only updates the changed points. This does not influence the asymptotic performance, but decreases the constant factor. First, we start updating the convex hull from position *rk* and not from the start. To be able to do this, we have an array prev that for each gene *g* ∈ *π* stores the previous point on the convex hull if *g* were the last gene in the block. This actually is the same as the top of the stack in Graham algorithm and represent the algorithms state for any given point. As all points *h* to the left of *g* are not changed prev*h* also remains unchanged and need not to be recalculated. Second, we stop updating the hull, when we reach the point on the previous iteration convex hull. We can do this because every point to the left of *g* is rotated counterclockwise of any point to the right of *g*, which means that the first point on the convex hull right of *g* on (*k* – 1)-th iteration remains being a convex hull point at *k*-th iteration. ### 2.4 An algorithm for exact calculation of GSEA P-values for integer gene-level statistics In this section we describe a polynomial algorithm to calculate GSEA P-value exactly, but only for the case when gene-level statistics are integer numbers: ![Graphic][55]. For simplicity we will consider a problem of calculating the following probability: ![Formula][56] where *q* is a random gene set of size *k*. We also assume *γ* > 0. Let denote the sum of *k* largest absolute values of gene ranks by *T*. The algorithm will be polynomial in terms of *N, k* and *T*. #### 2.4.1 The basic algorithm Let us consider a gene set *q* = {*q*1, *q*2,…, *qk*}. Recall the formula for *s*+(*q*): ![Formula][57] First, let rewrite the formula for ES*i* in an equivalent fashion, grouping positive and negative summands: ![Formula][58] Then for calculating ES*i* the following values are sufficient: * *i*: the index of the current gene; * ![Graphic][59]: the number of genes included into the set *q* among genes 1..*i*; * ![Graphic][60]: the sum of the absolute values of gene-level statistics for genes included in the set among genes 1..*i*; * ![Graphic][61]: the sum of the absolute values of gene-level statistics for *all* genes in the set. Knowing the values above, ES*i* can be calculated as ![Graphic][62]. Notice that NS can take only integer values from 0 to *T* (for a set of genes with the largest absolute values of gene-level statistics). Let us split the desired probability to a sum of independent probabilities based on the value of NS: ![Formula][63] Our algorithm will be based on *dynamic programming*. For each possible value of NS we will process the genes one by one in increasing order of index and calculate an array *f*NS(*i, c, s*). The value *f*NS(*i, c, s*) will contain the probability for a uniformly random gene set *q*′ of *c* genes selected from genes 1..*i* to simultaneously have the following two properties: 1. the sum of the absolute values of gene-level statistics of genes from *q*′ is equal to *s*; 2. ES*j* < *γ* holds for all *j* ⩽ *i*, where the values of ES are calculated for the gene set *q*′ but using the selected values of NS and *k*, not the ones calculated for the set *q*′. Suppose that we have calculated all values of *f*NS(*i, c, s*), then ![Formula][64] and ![Formula][65] Finally, the sought probability is equal to: ![Formula][66] Let us find a formula for *f*NS(*i, c, s*). The base case of dynamic programming is *i* = 0 for all NS: ![Formula][67] Suppose we want to calculate *f*NS(*i, c, s*) for some *i* > 0. First, calculate ![Formula][68] and compare it to *γ*. If ES*i* ⩾ *γ*, then *f*NS(*i, c, s*) = 0 by definition. Otherwise, condition “ES*j* < *γ* holds for all *j* ⩽ *i*” can be simplified to “ES*j* < *γ* holds for all *j* ⩽ *i* – 1”. This observation allows us to use values of *f* that have already been calculated. Consider two cases: 1. Gene *i* does not belong to the set *q*′. As *q*′ is a set of *c* genes chosen uniformly at random from *i* genes, this case happens with the probability ![Graphic][69]. The conditional probability that such set satisfies the two necessary properties is *f*NS(*i* – 1, *c, s*). Indeed, any set of size *c* with the sum of absolute values of gene-level statistics values equal to *s*, chosen among genes 1..*i* – 1 and satisfying the conditions on ES, is a valid set chosen among genes 1..*i*. Similarly, if a set does not satisfy the condition on ES*j* for some *j* ⩽ *i* – 1, this set should not be counted towards *f*NS(*i, c, s*) since obviously *j* ⩽ *i*. 2. Gene *i* belongs to the set. This case happens with the probability ![Graphic][70]. The probability that this set satisfies the necessary conditions is *f*NS(*i* − 1, *c* − 1, *s* − *Si*). Indeed, any set of size *c* − 1 with the sum of absolute values of gene-level statistics equal to *s* − *Si*, chosen among genes 1..*i* − 1 and satisfying the conditions on ES, can be extended with gene *i*, thus forming a set of size *c* satisfying both necessary properties. Similarly, if a set does not satisfy the condition on ES*j* for some *j* ⩽ *i* − 1, adding gene *i* will not fix the situation. Then we can calculate *f*NS(*i, c, s*) using the law of total probability: ![Formula][71] in the case when *i* > 0 and ES*i* < *γ*. Putting all the cases together, we arrive to the final formula for *f*NS(*i, c, s*): ![Formula][72] The overall complexity of the algorithm is *O*(*NkT*2). The values of *f* can be evaluated sequentially in increasing order of *i*. It is enough to evaluate *f*NS(*i, c, s*) for 0 ⩽ *i* ⩽ *N*, 0 ⩽ *c* ⩽ *k*, and 0 ⩽ *s* ⩽ NS ⩽ *T*. Each value of *f* can be evaluated in constant time. #### 2.4.2 Optimizations and implementation details While the algorithm described above is polynomial, a number of further optimizations are required to make execution on real size inputs feasible. First, let note that the following property holds: *f*NS2(*i, c, s*) ⩾ *f*NS1(*i, c, s*) as long as NS2 ⩾ NS1. Indeed, ES values calculated using different values of NS are decreasing when NS is increased. That means all gene sets counted towards *f*NS1(*i, c, s*) should also be counted towards *f*NS2(*i, c, s*) if NS2 ⩾ NS1. Following the observation above, instead of calculating values of *f*NS(*i, c, s*) we will con-sider the values *g*(*i, c, s, b*) = *f**b*+1(*i, c, s*) − *fb*(*i, c, s*). These values will contain the probability of a random gene set *q* of size *k* selected uniformly from genes 1..*N* to satisfy simultaneously the following three properties: 1. set *q* contains exactly *c* genes from the genes 1..*i*. 2. the sum of the absolute values of gene-level statistics of the first *c* genes from *q* is equal to *s*; 3. ES*j* < *γ* holds for all *j* ⩽ *i*, where the values of ES are calculated for the gene set *q* using NS = *b* +1 (and for all higher values of NS); 4. ES*j* ⩾ *γ* holds for at least one *j* ⩽ *i*, where the values of ES are calculated for the gene set *q* using NS = *b* (and for all lower values of NS). The sought probability can be calculated from values of *g* as follows: ![Formula][73] To calculate the values of *g* we will use the forward dynamic programming algorithm. In this algorithm we expand a tree of reachable dynamic programming states, starting from *g*(0, 0, 0, 0) which is equal to 1. The states will be considered by “levels” in an increasing order of *i*. The values *g*(*i* + 1, *c, s, b*) from (*i* + 1)-th level are calculated based on level *i*. Note, that the sum of values on *i*-th level is always equal to 1. To calculate all values from the (*i* + 1)-th level all non-zero values from the *i*-th level are considered sequentially. Let consider state (*i, c, s, b*) and let define *p* = (*k* – *c*)/(*N* – *i*) – the probability that gene *i* + 1 will be added to the set. The corresponding set *G*(*i, c, s, b*) can be divided into two groups. 1. The gene sets from *G*(*i, c, s, b*) that do not include gene *i* + 1. These gene sets are included into gene sets *G*(*i* + 1, *c, s, b*) on the level *i* + 1. Thus the corresponding probability *g*(*i, c, s, b*) · (1 – *p*) is added to the value of *g*(*i* + 1, *c, s, b*). 2. The gene sets from *G*(*i, c, s, b*) that do include gene *i* + 1. These gene sets are included into *G*(*i* + 1, *c* + 1, *s*′ = *s* + |*S**i*+1|, *b*′) where *b*′ is an updated bound. To calculate *b*′ let note th at ES*j* will be greater or equal to *γ* iff ![Graphic][74] which is equivalent to ![Graphic][75]. Thus ![Graphic][76] The probability that is added to *g*(*i* + 1, *c* + 1, *s*′, *b*′) is equal to *g*(*i, c, s, b*) · *p*. While the asymptotic number of states remains to be *O*(*NkT*2) the forward dynamic programming allows to consider only “reachable” gene stats with *g*(*i, c, s, b*) > 0. In practice the number of reachable stats can be several orders of magnitude smaller then the total states. Furthermore, for the algorithm we can consider only states with *g*(*i, c, s, b*) > *ε* to be reachable for some small value of *ε*. If we do not consider the unreachable states we would not be able to calculated the desired probability exactly. However, if we calculate the value of *δ* as a sum of all the skipped states values, the desired probability will be calculated with the absolute error no more than *δ*. The algorithm implementation with few other optimizations is available at: [https://github.com/ctlab/fgsea/blob/master/inst/exact/exact.cpp](https://github.com/ctlab/fgsea/blob/master/inst/exact/exact.cpp). ### 2.5 FGSEA-multilevel: an algorithm for calculation of arbitrarily low P-values using adaptive multilevel split Monte Carlo scheme In this section we describe FGSEA-multilevel algorithm that can accurately estimate GSEA P-value for a pathway *p* of size *k* even when the true P-value is very small. Let *γ* = *sr*(*p*) > 0 be the enrichment score of the query pathway *p* for which we want to calculate the following value: ![Formula][77] where *q* is a random gene set of size *k*. This probability can be rewritten as follows: ![Formula][78] First, we focus on determining the probability ![Graphic][79]. This probability can be extremely small, so using a naive sampling gives a bad estimation. We use the adaptive multilevel split Monte Carlo method [6] to solve this problem. To estimate the probability ![Graphic][80] we split the enrichment scores into levels 0 = *l* < *l*1 < … < *lt* = *γ*. Then we can define the following probabilities: ![Formula][81] Now the probability ![Graphic][82] can be rewritten as ![Graphic][83]. To estimate *αi* we can draw a sample ![Graphic][84] of size *Z* from a conditional distribution ![Graphic][85]. Then ![Formula][86] where *Zi* is the number of elements in the set ![Graphic][87]. Below we show how levels *li* can be chosen and how to sample from the corresponding conditional distributions. #### 2.5.1 Choosing the enrichment score levels We propose to chose value for a level *li* as a median of the enrichment scores for the ![Graphic][88] sample. For simplicity *Z* is required to be an odd number. Then the procedure for estimating probability ![Graphic][89] consists of repetition of the following steps: 1. On iteration *i* ⩾ 1 sample *Z* gene sets ![Graphic][90] of size *k* from the distribution ![Graphic][91]. 2. Set the level ![Graphic][92] to be equal to the median of values ![Graphic][93]. 3. If ![Graphic][94] then stop the iterations and set *li* = *γ* mid *t* = *i*, otherwise set ![Graphic][95]. As a result, by construction, *αi* ≈ 1/2 for 1 ⩽ *i* ⩽ *t* − 1. The value of can be approximated as *Zt*/*Z* (which is always ⩾ 1/2). Together we get the following expression for estimating the desired probability: ![Formula][96] #### 2.5.2 The conditional sampling implementation To generate a uniform sample ![Graphic][97] from the conditional distribution ![Graphic][98] we use the Metropolis algorithm. First, we generate a sample ![Graphic][99] of size *Z* from the distribution ![Graphic][100]. Since *l* = 0 and values of ![Graphic][101] are always non-negative it can be done by generating a uniformly random subset of size *k* from the genes {1, 2,…, *N*}. Now let consider a sample ![Graphic][102] at a step *i* > 1. The sample can be sorted in an increasing order of enrichment score values: ![Graphic][103]. Let *d* = ⌈*Z*/2⌉. The level *l**i*−1 is the median of the values ![Graphic][104] and, thus, is equal to ![Graphic][105]. Let first populate ![Graphic][106] in the following way: ![Formula][107] This gives us a sample from the conditional distribution ![Graphic][108], however it is not uniform. To make the sample uniform we apply a number of the Metropolis algorithm iterations. On each iteration for each gene set ![Graphic][109] we apply the following steps: 1. Choose a random gene ![Graphic][110]. 2. Choose a random gene ![Graphic][111]. 3. Consider ![Graphic][112]. If ![Graphic][113] then we replace ![Graphic][114] with ![Graphic][115]. The iterations are repeated until the total number of successful replacements becomes greater or equal to *k* · *Z*. In practice, this number of steps is enough to get a sufficiently uniform sample to obtain a good estimation of probability, without a significant increase in the running time of the algorithm. #### 2.5.3 Estimating the P-value In order to estimate the desired P-value we also need to calculate the probabilities P (*sr*(*q*) ⩾ 0) and ![Graphic][116]. To calculate the probability P (*sr*(*q*) ⩾ 0) we generate gene sets *q*1, *q*2,…, *qZ*′, where each sample *qi* is selected uniformly at random from all the subsets of size *k* from the set {1, 2,…, *N*}. The samples are generated until the number of samples *qi* with *sr*(*qi*) ⩾ 0 becomes equal to *Z*. Then the probability P (*sr*(*q*) ⩾ 0) is estimated as follows ![Formula][117] To determine the remaining probability ![Graphic][118] we calculate the number of gene sets in ![Graphic][119] with value of the enrichment score function *sr* is greater than zero. After that, the probability can be estimated as follows: ![Formula][120] #### 2.5.4 Estimating log-probability To properly estimate a logarithm of the desired probability let note that the *j*-th order statistic of a standard uniform sample of size *Z* is a random variable from the beta distribution Beta (*j, Z* + 1 − *j*). Therefore, we can use the properties of the beta distribution and make correct transition to the logarithm of probability. So for the median value of sample of odd size *Z* we have: ![Formula][121] where *ψ* is digamma function. In the same way, we can calculate the expectation of the logarithm *αt*: ![Formula][122] Then the logarithm of probability ![Graphic][123] is estimated as ![Formula][124] Similarly, we can estimate the variance of the estimates ![Graphic][125], where *ψ*1 is trigamma function. From this we can approximate a standard error of our estimator as: ![Formula][126] The same approach with digamma functions is used to calculate the logarithm of the probabilities ![Graphic][127] and P (*sr* (*q*) ⩾ 0). #### 2.5.5 Optimizations and implementation details The most demanding step of FGSEA-multilevel algorithm is to check whether the newly obtained gene set has the enrichments score value of at least *li*. Importantly, this does not require full computation of enrichment score value. It is enough to show that there is at least one gene that has the running enrichment score value of at least *li* or, in other words, that at least one point on the enrichment score graph is farther away from the diagonal (Fig. S1) than some value calculated from *li*. Similarly to FGSEA-simple algorithm, a square root decomposition is used to split all the genes into approximately ![Graphic][128] blocks. The block boundaries are determined automatically on each level based on the existing sample in such a way, that each block contains approximately ![Graphic][129] genes. In particular this decomposition enables adding and removing genes in ![Graphic][130] time while keeping the gene set sorted. Unlike FGSEA-simple algorithm we will not maintain the convex hull but will apply a few heuristics to do the required check faster. First we check a “candidate” point which has a high chance to be at the required distance from the diagonal. If it is so, we do not have to continue the check. The “candidate” gene is carried our from the previous iterations, as the point where the successful check has been interrupted. Next we go block by block. At the beginning we construct a “rectangle” upper bound on the enrichment score value at the block, which can be obtained by moving all the genes of the block to its start. If this upper bound does not satisfy our criterion we can skip the block. Otherwise, we go gene by gene and calculate the enrichment score values until it reaches the required value or the end of the block is reached. In the former case the check is interrupted with a successful result. #### 2.5.6 Comparison with the exact method To compare FGSEA-multilevel and the exact method on the same dataset we used rounded values of the gene-level statistics from the example data (section 2.2) as input data for both algorithms. Both algorithms calculated the probability ![Graphic][131]. The results of the algorithms for the pathways from the example data are shown on Fig 3c. The exact algorithm was run with *ε* = 10−40, all the probabilities were obtained with accuracy of at least six significant digits. For FGSEA-multilevel *Z* = 101 was used. We also calculated empirical estimation errors and compared it to the theoretical ones (Fig 3d). For this we generated 100 independent estimates for a range of ES values (corresponding to P-values of 10−4 to 10−100, gene set sizes (from 15 to 250) and sample size (from 101 to 1001). The raw values are available in the Supplementary Table. ### 2.6 Filtering redundant pathways In this section we describe an algorithm to filter redundant pathways from the results of FGSEA. Let consider two pathways *p*1 and *p*2 that both have a significant GSEA P-value. There are two situations in which we will consider *p*2 to be non-redundant given *p*1: 1. If pathway *p*2 is enriched even if we do not consider the genes from *p*1 at all. Formally, we calculate GSEA P-value for gene set *p*2 \*p*1 and gene-level statistics vector *S*[*U* \*p*1] for all the genes except *p*1. If the P-value is less than a pre-defined threshold, then pathway *p*2 is considered as non-redundant given *p*1. 2. If pathway *p*2 is enriched even if we consider only genes from *p*1. Formally, we calculate GSEA P-value for gene set *p*2 ∩ *p*1 and gene-level statistics vector *S*[*p*1] for the genes from *p*1. Again, if the P-value is less than a pre-defined thresh old, then pathway *p*2 is considered as non-redundant given *p*1. Otherwise pathway *p*2 is considered to be redundant. The filtering procedure starts with a set of significantly enriched pathways *Psig* selected by the user: for example the pathways with GSEA P-values less than 0.01 after Benjamini-Hochberg correction, sorted by P-value. The output of the procedure is a list *Pmain* ⊂ *Psig* of pathways that are pairwise non-redundant. At the same time, all the other pathways *Pred* = *Psig* \ *Pmain* are redundant given some pathway from *Psig*. The procedure itself is similar to Sieve of Eratothenes algorithm. The pathways are considered one by one and some of them are marked as redundant. For a pathway *p* we first check if it is already marked as redundant, if yes, we go to the next pathway. Otherwise, we first run FGSEA-simple algorithm on a vector of statistics *S*[*U* \ *p*] and all the pathway currently not marked as redundant (including the ones that already have been considered, but excluding pathway *p*). Then, similarly, we run FGSEA-simple algorithm on a vector of statistics *S*[*p*]. Pathways that do not achieve non-redundant P-value threshold in both tests are marked as redundant. ## Supporting information Supplementary Table [[supplements/060012_file02.xlsx]](pending:yes) ## Footnotes * A systematic analysis of GSEA performance on 605 datasets has been added. * [https://github.com/ctlab/fgsea/](https://github.com/ctlab/fgsea/) * Received June 20, 2016. * Revision received February 1, 2021. * Accepted February 1, 2021. * © 2021, Posted by Cold Spring Harbor Laboratory This pre-print is available under a Creative Commons License (Attribution 4.0 International), CC BY 4.0, as described at [http://creativecommons.org/licenses/by/4.0/](http://creativecommons.org/licenses/by/4.0/) ## References 1. [1]. Aravind Subramanian, Pablo Tamayo, Vamsi K Mootha, Sayan Mukherjee, Benjamin L Ebert, Michael A Gillette, Amanda Paulovich, Scott L Pomeroy, Todd R Golub, Eric S Lander, and Jill P Mesirov. Gene set enrichment analysis: a knowledge-based approach for interpreting genome-wide expression profiles. Proceedings of the National Academy of Sciences of the United States of America, 102(43): 15545–50, 2005. [Abstract/FREE Full Text](http://biorxiv.org/lookup/ijlink/YTozOntzOjQ6InBhdGgiO3M6MTQ6Ii9sb29rdXAvaWpsaW5rIjtzOjU6InF1ZXJ5IjthOjQ6e3M6ODoibGlua1R5cGUiO3M6NDoiQUJTVCI7czoxMToiam91cm5hbENvZGUiO3M6NDoicG5hcyI7czo1OiJyZXNpZCI7czoxMjoiMTAyLzQzLzE1NTQ1IjtzOjQ6ImF0b20iO3M6Mzc6Ii9iaW9yeGl2L2Vhcmx5LzIwMjEvMDIvMDEvMDYwMDEyLmF0b20iO31zOjg6ImZyYWdtZW50IjtzOjA6IiI7fQ==) 2. [2]. G. Yu, L. G. Wang, G. R. Yan, and Q. Y. He. DOSE: an R/Bioconductor package for disease ontology semantic and enrichment analysis. Bioinformatics, 3l(4):6O8–6O9, Feb 2015. 3. [3]. L. Varemo, J. Nielsen, and I. Nookaew. Enriching the gene set analysis of genomewide data by incorporating directionality of gene expression and combining statistical hypotheses and methods. Nucleic Acids Res., 4l(8):4378–439l, Apr 2013. 4. [4]. Gang Wei, Lai Wei, Jinfang Zhu, Chongzhi Zang, Jane Hu-Li, Zhengju Yao, Kairong Cui, Yuka Kanno, Tae-Young Roh, Wendy T Watford, Dustin E Schones, Weiqun Peng, Hong-Wei Sun, William E Paul, John J O’Shea, and Keji Zhao. Global mapping of H3K4me3 and H3K27me3 reveals specificity and plasticity in lineage fate determination of differentiating CD4+ T cells. Immunity, 3O(l):l55—67, 2009. 5. [5]. G Joshi-Tope, M Gillespie, I Vastrik, P D’Eustachio, E Schmidt, B de Bono, B Jassal, G R Gopinath, G R Wu, L Matthews, S Lewis, E Birney, and L Stein. Reactome: a knowledgebase of biological pathways. Nucleic acids research, 33(Database issue):D428–32, 2005. [CrossRef](http://biorxiv.org/lookup/external-ref?access_num=10.1093/nar/gki072&link_type=DOI) [PubMed](http://biorxiv.org/lookup/external-ref?access_num=15608231&link_type=MED&atom=%2Fbiorxiv%2Fearly%2F2021%2F02%2F01%2F060012.atom) [Web of Science](http://biorxiv.org/lookup/external-ref?access_num=000226524300088&link_type=ISI) 6. [6]. Zdravko I Botev and Dirk P Kroese. An efficient algorithm for rare-event probability estimation, combinatorial optimization, and counting. Methodology and Computing in Applied Probability, lO(4):47l–5O5, 2008. 7. [7]. S. G. Jantzen, B. J. Sutherland, D. R. Minkley, and B. F. Koop. GO Trimming: Systematically reducing redundancy in large Gene Ontology datasets. BMC Res Notes, 4:267, Jul 2011. [CrossRef](http://biorxiv.org/lookup/external-ref?access_num=10.1186/1756-0500-4-267&link_type=DOI) [PubMed](http://biorxiv.org/lookup/external-ref?access_num=21798041&link_type=MED&atom=%2Fbiorxiv%2Fearly%2F2021%2F02%2F01%2F060012.atom) 8. [8]. M. E. Ritchie, B. Phipson, D. Wu, Y. Hu, C. W. Law, W. Shi, and G. K. Smyth, limma powers differential expression analyses for RNA-sequencing and microarray studies. Nucleic Acids Research, pages gkvOO7-, 2015. 9. [9]. Belinda Phipson and Gordon K Smyth. Permutation p-values should never be zero: calculating exact p-values when permutations are randomly drawn. Statistical applications in genetics and molecular biology, 9(1), 2010. 10. [10]. Thomas H Cormen, Charles E Leiserson, Ronald L Rivest, and Clifford Stein. Intro-duction to Algorithms, Second Edition, volume 7. 2001. [1]: /embed/inline-graphic-1.gif [2]: /embed/inline-graphic-2.gif [3]: /embed/inline-graphic-3.gif [4]: /embed/inline-graphic-4.gif [5]: /embed/inline-graphic-5.gif [6]: /embed/inline-graphic-6.gif [7]: /embed/inline-graphic-7.gif [8]: /embed/inline-graphic-8.gif [9]: /embed/inline-graphic-9.gif [10]: /embed/inline-graphic-10.gif [11]: /embed/inline-graphic-11.gif [12]: /embed/inline-graphic-12.gif [13]: /embed/graphic-4.gif [14]: /embed/graphic-5.gif [15]: /embed/graphic-6.gif [16]: /embed/inline-graphic-13.gif [17]: /embed/graphic-8.gif [18]: /embed/graphic-9.gif [19]: /embed/graphic-10.gif [20]: /embed/inline-graphic-14.gif [21]: /embed/inline-graphic-15.gif [22]: /embed/inline-graphic-16.gif [23]: /embed/graphic-11.gif [24]: /embed/inline-graphic-17.gif [25]: /embed/inline-graphic-18.gif [26]: /embed/inline-graphic-19.gif [27]: /embed/graphic-12.gif [28]: /embed/graphic-13.gif [29]: /embed/graphic-14.gif [30]: /embed/graphic-15.gif [31]: /embed/graphic-16.gif [32]: /embed/inline-graphic-20.gif [33]: /embed/graphic-17.gif [34]: /embed/graphic-18.gif [35]: /embed/graphic-19.gif [36]: /embed/inline-graphic-21.gif [37]: /embed/inline-graphic-22.gif [38]: /embed/inline-graphic-23.gif [39]: /embed/inline-graphic-24.gif [40]: /embed/graphic-20.gif [41]: /embed/graphic-21.gif [42]: /embed/graphic-22.gif [43]: /embed/inline-graphic-25.gif [44]: /embed/inline-graphic-26.gif [45]: /embed/inline-graphic-27.gif [46]: /embed/graphic-23.gif [47]: /embed/graphic-24.gif [48]: /embed/inline-graphic-28.gif [49]: /embed/graphic-25.gif [50]: /embed/graphic-26.gif [51]: /embed/inline-graphic-29.gif [52]: /embed/inline-graphic-30.gif [53]: /embed/inline-graphic-31.gif [54]: /embed/inline-graphic-32.gif [55]: /embed/inline-graphic-33.gif [56]: /embed/graphic-27.gif [57]: /embed/graphic-28.gif [58]: /embed/graphic-29.gif [59]: /embed/inline-graphic-34.gif [60]: /embed/inline-graphic-35.gif [61]: /embed/inline-graphic-36.gif [62]: /embed/inline-graphic-37.gif [63]: /embed/graphic-30.gif [64]: /embed/graphic-31.gif [65]: /embed/graphic-32.gif [66]: /embed/graphic-33.gif [67]: /embed/graphic-34.gif [68]: /embed/graphic-35.gif [69]: /embed/inline-graphic-38.gif [70]: /embed/inline-graphic-39.gif [71]: /embed/graphic-36.gif [72]: /embed/graphic-37.gif [73]: /embed/graphic-38.gif [74]: /embed/inline-graphic-40.gif [75]: /embed/inline-graphic-41.gif [76]: /embed/inline-graphic-42.gif [77]: /embed/graphic-39.gif [78]: /embed/graphic-40.gif [79]: /embed/inline-graphic-43.gif [80]: /embed/inline-graphic-44.gif [81]: /embed/graphic-41.gif [82]: /embed/inline-graphic-45.gif [83]: /embed/inline-graphic-46.gif [84]: /embed/inline-graphic-47.gif [85]: /embed/inline-graphic-48.gif [86]: /embed/graphic-42.gif [87]: /embed/inline-graphic-49.gif [88]: /embed/inline-graphic-50.gif [89]: /embed/inline-graphic-51.gif [90]: /embed/inline-graphic-52.gif [91]: /embed/inline-graphic-53.gif [92]: /embed/inline-graphic-54.gif [93]: /embed/inline-graphic-55.gif [94]: /embed/inline-graphic-56.gif [95]: /embed/inline-graphic-57.gif [96]: /embed/graphic-43.gif [97]: /embed/inline-graphic-58.gif [98]: /embed/inline-graphic-59.gif [99]: /embed/inline-graphic-60.gif [100]: /embed/inline-graphic-61.gif [101]: /embed/inline-graphic-62.gif [102]: /embed/inline-graphic-63.gif [103]: /embed/inline-graphic-64.gif [104]: /embed/inline-graphic-65.gif [105]: /embed/inline-graphic-66.gif [106]: /embed/inline-graphic-67.gif [107]: /embed/graphic-44.gif [108]: /embed/inline-graphic-68.gif [109]: /embed/inline-graphic-69.gif [110]: /embed/inline-graphic-70.gif [111]: /embed/inline-graphic-71.gif [112]: /embed/inline-graphic-72.gif [113]: /embed/inline-graphic-73.gif [114]: /embed/inline-graphic-74.gif [115]: /embed/inline-graphic-75.gif [116]: /embed/inline-graphic-76.gif [117]: /embed/graphic-45.gif [118]: /embed/inline-graphic-77.gif [119]: /embed/inline-graphic-78.gif [120]: /embed/graphic-46.gif [121]: /embed/graphic-47.gif [122]: /embed/graphic-48.gif [123]: /embed/inline-graphic-79.gif [124]: /embed/graphic-49.gif [125]: /embed/inline-graphic-80.gif [126]: /embed/graphic-50.gif [127]: /embed/inline-graphic-81.gif [128]: /embed/inline-graphic-82.gif [129]: /embed/inline-graphic-83.gif [130]: /embed/inline-graphic-84.gif [131]: /embed/inline-graphic-85.gif