gseapy

repository·master·Indexed 20 days ago

https://github.com/zqfang/gseapy

A Python/Rust implementation for Gene Set Enrichment Analysis (GSEA) and a wrapper for the Enrichr API. Designed for RNA-seq, ChIP-seq, and Microarray data analysis, it integrates with Pandas and Numpy to provide publication-quality figures. Key features include support for preranked GSEA, ssGSEA, GSVA, and over-representation analysis (both online via Enrichr and offline). It includes utilities for downloading MSigDB collections, converting gene identifiers via BioMart, and generating enrichment maps, dotplots, and barplots.

Tokens
25.1K
Snippets
81
Records
114
Agent score
72%

What's inside gseapy

  1. Overview of GSEApy sub-commands

    master

    GSEApy provides 7 main sub-commands for different enrichment analysis methods:

    • gsea: Produces GSEA results. Requires a text file (FPKM, TPM, etc.), a .cls file, and a .gmt gene sets file.
    • prerank: Produces Prerank tool results. Requires a pre-ranked gene list in .rnk format and a .gmt file. Supports the fgsea multilevel p-value method via method='multilevel'.
    • ssgsea: Performs single sample GSEA (ssGSEA). Accepts pd.Series, pd.DataFrame (including .gct files), or .gct files for multiple samples.
    • gsva: Performs GSVA method. Input format is the same as ssgsea.
    • replot: Reproduces GSEA desktop version results using the location of the desktop output.
    • enrichr: Wrapper for the Enrichr API for fast gene set enrichment.
    • biomart: Converts gene IDs using the BioMart API.
  2. Overview of GSEApy subcommands and modules

    master

    GSEApy provides several modules for different types of enrichment analysis and data processing. Each module serves a specific statistical method or data source:

    • gsea: Produces standard GSEA results. Requires a text file (e.g., FPKM, TPM, Expected Counts), a .cls file, and a gene set file in .gmt format.
    • prerank: An API for the GSEA pre-rank tool. Requires a pre-ranked gene list in .rnk format and a .gmt gene set file.
    • ssgsea: Performs single sample GSEA (ssGSEA) analysis. Requires a gene list with expression values (similar to .rnk format) and a .gmt gene set file.
    • gsva: Performs GSVA (Gene Set Variation Analysis).
    • replot: Reproduces results from the GSEA desktop version. The only required input is the path to the GSEA Desktop output results.
    • enrichr: Performs enrichment analysis using the Enrichr API (http://amp.pharm.mssm.edu/Enrichr).
    • biomart: Uses the BioMart API to assist with gene ID conversion.
  3. Reproduce GSEA Java desktop outputs with Prerank

    master
    GSEApy provides a Prerank module (and a replot module) that can reproduce the same figures generated by the GSEA Java desktop application. This is useful for maintaining visual consistency when moving from the desktop application to a Python-based workflow.
  4. Understand the difference between prerank and ssGSEA

    master

    Prerank (GSEA)

    • Use case: Comparing two groups of samples (e.g., control vs. treatment).
    • Input: A gene ranking defined by a custom method (e.g., t-statistic, signal-to-noise).
    • Enrichment Score (ES): Calculated as the max(running enrichment scores) or min(running enrichment scores).

    ssGSEA

    • Use case: Comparing individual samples against the rest of the population to find shared gene signatures. Best used when you have a large number of samples.
    • Enrichment Score (ES): Calculated as the sum(running enrichment scores).
    • Note: The original ssGSEA algorithm does not provide p-values or FDR. Consequently, gseaplot generated by ssgsea will not show p-values or FDR.
  5. Install GSEApy

    master

    You can install GSEApy using conda/mamba, pip, or uv.

    Note: For GSEApy versions > 0.11.0, a Rust compiler is required for building. If pip installation fails, you should install the Rust toolchain first and then install via pip or uv.

    # if you have conda/mamba
    $ conda install -c bioconda gseapy
    
    # or pip
    $ pip install gseapy
    
    # or uv
    $ uv add gseapy
    
    # If pip install failed, install rust first:
    $ curl https://sh.rustup.rs -sSf | sh -s -- -y
    $ export PATH="$PATH:$HOME/.cargo/bin"
    $ pip install gseapy
  6. Prepare data for the enrichr module

    master

    The enrichr module requires a list of genes. You can provide this data in two ways:

    1. A Python list object: A standard list of strings.
    2. A text file: A .txt file containing one gene ID per row.

    Important Requirements:

    • Enrichr uses Entrez gene symbols as input.
    • You must convert all gene names to uppercase.

    Generated plots are compatible with all matplotlib figure formats, allowing for easy modification of .pdf files.

    # Option 1: Using a Python list object
    gene_list = ['SCARA3', 'LOC100044683', 'CMBL', 'CLIC6', 'IL13RA1', 'TACSTD2', 'DKKL1', 'CSF1', 'CITED1', 'SYNPO2L']
    
    # Option 2: Using a text file (one gene per line)
    # The file content should look like:
    # CTLA2B
    # SCARA3
    # ...
  7. Use custom gene sets via dictionary in Jupyter

    master

    When working in Jupyter or when you have custom gene sets, the gene_sets argument in several APIs accepts a Python dict. This allows you to define your own terms and their corresponding gene lists directly in your code without needing an external GMT file.

    Supported APIs for dictionary input:

    • gsea
    • prerank
    • ssgsea
    • enrichr
    gene_sets = {
        "term_1": ["gene_A", "gene_B", ...],
        "term_2": ["gene_B", "gene_C", ...],
        "term_100": ["gene_A", "gene_T", ...]
    }
  8. Run GSEA using the `gsea` function or command

    master

    GSEA (Gene Set Enrichment Analysis) requires three main input components. The input file formats are compatible with the GSEA desktop application.

    1. Gene Expression Data

    Provide a tabular text file (supporting RNA-seq, ChIP-seq, or Microarray data) or a pandas.DataFrame. The table should have genes as rows and samples as columns.

    2. Phenotype Class File (.cls)

    A .cls file specifies column attributes. It must follow this structure:

    • Line 1: Total samples and phenotype numbers (e.g., 6 2 1). The third number should always be 1.
    • Line 2: Phenotype class names (prefixed with #).
    • Line 3: Column attributes (the class for each sample).

    Alternatively, you can pass a list of strings directly to the cls parameter.

    3. Gene Sets (.gmt)

    Provide a .gmt file containing gene sets. You can also use the enrichr library by providing a library name to the gene_sets parameter instead of a file path.

    import pandas as pd
    import gseapy
    
    # Example: Using a DataFrame for expression data
    df = pd.read_table('./test/gsea_data.txt')
    
    # Example: Defining classes as a list instead of a .cls file
    cls_list = ['C1OE', 'C1OE', 'C1OE', 'Vector', 'Vector', 'Vector']
    
    # Run GSEA (conceptual usage based on tutorial requirements)
    # gseapy.gsea(data=df, cls=cls_list, gene_sets='path/to/gene_sets.gmt', ...)
  9. Understand the GSEAbase class

    master

    GSEAbase is the base class for GSEA implementations in GSEApy. It handles data loading, preprocessing, and provides internal utilities for enrichment analysis.

    Key Responsibilities:

    • Data Loading: Supports loading expression data from pandas.DataFrame, pandas.Series, or files (including .gct, .csv, and .rnk formats) via _load_data.
    • Data Validation: _check_data handles missing values (filling NAs with 0), duplicate gene IDs (averaging them), and infinite values.
    • Gene ID Handling: Includes utilities to check if IDs are Entrez IDs (_is_entrez_id) and to handle case sensitivity (detecting if gene symbols are mostly uppercase).
    • Output Management: Manages output directories and logging via prepare_outdir.

    Note: This is a base class intended to be subclassed by specific GSEA modules (like gsea, ssgsea, or gsva).

  10. Handle zero P-values or FDR

    master

    If you see a P-value or FDR of 0 instead of a very small number, it is because the observed Enrichment Score (ES) falls outside the null distribution generated by the random permutation procedure (e.g., 1000 permutations).

    To resolve this, you can:

    1. Set the smallest possible p-value to 1 / (number of permutations).
    2. Increase the number of permutations (this will increase computation time).
  11. Troubleshoot gene identifier mismatches

    master

    Ensure your gene identifiers match the requirements of your chosen input:

    • Enrichr library: If using gene_sets from the Enrichr library, gene symbols must be in UPPER CASE.
    • Custom GMT files: The gene identifiers in your input gene list must match the identifier type used in your custom GMT file.

    Note on non-human organisms: Since GSEApy cannot change the Enrichr databases, if you are working with mouse, fly, fish, or worm data, you should convert your gene symbols to UPPER CASE before running the analysis.