### Install gseapy with uv Source: https://github.com/zqfang/gseapy/blob/master/README.rst Install gseapy using the uv package manager. Ensure Rust is installed if pip installation fails. ```shell # install rust toolchain curl https://sh.rustup.rs -sSf | sh -s -- -y export PATH="$PATH:$HOME/.cargo/bin" # then install via pip or uv $ pip install gseapy # or $ uv add gseapy ``` -------------------------------- ### GSEA Command Line Prerank Example Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Example of how to run gseapy prerank analysis using the command line interface. ```bash # !gseapy prerank -r temp.rnk -g temp.gmt -o prerank_report_temp ``` -------------------------------- ### Install gseapy Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_tutorial.md Install gseapy using pip or conda. ```bash pip install gseapy # if you have conda conda install -c bioconda gseapy ``` -------------------------------- ### Install GSEAPY with Pip Source: https://github.com/zqfang/gseapy/blob/master/docs/introduction.md Install the gseapy package using pip. This is an alternative installation method. ```shell pip install gseapy ``` -------------------------------- ### Setup gseapy development environment Source: https://github.com/zqfang/gseapy/blob/master/README.rst Instructions for cloning the gseapy repository, setting up the development environment using uv, and running tests. ```shell # clone and set up dev environment (requires Rust toolchain) $ git clone https://github.com/zqfang/GSEApy.git $ cd GSEApy $ uv sync --extra dev # run tests $ uv run pytest # lint and format ``` -------------------------------- ### Start Timing Source: https://github.com/zqfang/gseapy/blob/master/docs/singlecell_example.ipynb Records the start time using the time module. This is often used for performance benchmarking of subsequent code blocks. ```python import time t1 = time.time() ``` -------------------------------- ### Run gseapy commands Source: https://github.com/zqfang/gseapy/blob/master/README.rst Examples of using gseapy from the command line for various analyses like replot, gsea, prerank, ssgsea, gsva, and enrichr. ```bash # An example to reproduce figures using replot module. $ gseapy replot -i ./Gsea.reports -o test ``` ```bash # An example to run GSEA using gseapy gsea module $ gseapy gsea -d exptable.txt -c test.cls -g gene_sets.gmt -o test ``` ```bash # An example to run Prerank using gseapy prerank module $ gseapy prerank -r gsea_data.rnk -g gene_sets.gmt -o test ``` ```bash # An example to run ssGSEA using gseapy ssgsea module $ gseapy ssgsea -d expression.txt -g gene_sets.gmt -o test ``` ```bash # An example to run GSVA using gseapy ssgsea module $ gseapy gsva -d expression.txt -g gene_sets.gmt -o test ``` ```bash # An example to use enrichr api # see details for -g input -> ``get_library_name`` $ gseapy enrichr -i gene_list.txt -g KEGG_2016 -o test ``` -------------------------------- ### Install GSEAPY with Conda Source: https://github.com/zqfang/gseapy/blob/master/docs/introduction.md Install the gseapy package using the bioconda channel. This is the recommended method for users with conda. ```shell conda install -c bioconda gseapy ``` -------------------------------- ### Install GSEApy using Conda or Pip Source: https://github.com/zqfang/gseapy/blob/master/README.rst Install the gseapy package using either the conda/mamba package manager or pip. ```shell # if you have conda/mamba $ conda install -c bioconda gseapy ``` ```shell # or pip $ pip install gseapy ``` ```shell # or uv ``` -------------------------------- ### Import Libraries and Setup Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Imports pandas, gseapy, and matplotlib for data manipulation, GSEA analysis, and plotting. Sets up inline plotting and autoreload for interactive environments. ```python # %matplotlib inline # %config InlineBackend.figure_format='retina' # mac %load_ext autoreload %autoreload 2 import pandas as pd import gseapy as gp import matplotlib.pyplot as plt ``` -------------------------------- ### Check GSEApy Version Source: https://github.com/zqfang/gseapy/blob/master/docs/singlecell_example.ipynb Displays the installed version of the GSEApy library. Useful for ensuring compatibility and reproducibility. ```python gp.__version__ ``` -------------------------------- ### GSEA Command Line Usage Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Example of running GSEA from the command line. Use the '-v' flag for verbose output and '--no-plot' to disable plotting. ```bash # !gseapy gsea -d ./data/P53_resampling_data.txt \ # -g KEGG_2016 -c ./data/P53.cls \ # -o test/gsea_reprot_2 \ # -v --no-plot \ # -t phenotype ``` -------------------------------- ### Run gseapy functions in Python console (file inputs) Source: https://github.com/zqfang/gseapy/blob/master/README.rst Examples of running gseapy functions like gsea, prerank, ssgsea, gsva, and replot using file paths as input within a Python console. ```python import gseapy # run GSEA. gseapy.gsea(data='expression.txt', gene_sets='gene_sets.gmt', cls='test.cls', outdir='test') # run prerank gseapy.prerank(rnk='gsea_data.rnk', gene_sets='gene_sets.gmt', outdir='test') # run ssGSEA gseapy.ssgsea(data="expression.txt", gene_sets= "gene_sets.gmt", outdir='test') # run GSVA gseapy.gsva(data="expression.txt", gene_sets= "gene_sets.gmt", outdir='test') # An example to reproduce figures using replot module. gseapy.replot(indir='./Gsea.reports', outdir='test') ``` -------------------------------- ### Import GSEApy and Scanpy Source: https://github.com/zqfang/gseapy/blob/master/docs/singlecell_example.ipynb Imports the GSEApy library for gene set enrichment analysis and Scanpy for single-cell data processing. Ensure these libraries are installed before running. ```python import gseapy as gp import scanpy as sc ``` -------------------------------- ### Install GSEAPY with Conda (Bioconda and Conda-Forge) Source: https://github.com/zqfang/gseapy/blob/master/docs/introduction.md Install the gseapy package using both conda-forge and bioconda channels. This ensures compatibility with a wider range of dependencies. ```shell conda install -c conda-forge -c bioconda gseapy ``` -------------------------------- ### Command-line Enrichment Analysis Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Example of running gseapy's enrichment analysis directly from the command line using the 'enrichr' command. Includes options for input file, gene sets, verbosity, and output file. ```bash # !gseapy enrichr -i ./data/gene_list.txt \ # -g GO_Biological_Process_2017 \ # -v -o test/enrichr_BP ``` -------------------------------- ### Run gseapy functions in Python console (DataFrame inputs) Source: https://github.com/zqfang/gseapy/blob/master/README.rst Examples of using gseapy functions with pandas DataFrames, including gsea, prerank, ssgsea, and gsva, specifying Enrichr library names. ```python # assign dataframe, and use enrichr library data set 'KEGG_2016' expression_dataframe = pd.DataFrame() sample_name = ['A','A','A','B','B','B'] # always only two group,any names you like # assign gene_sets parameter with enrichr library name or gmt file on your local computer. gseapy.gsea(data=expression_dataframe, gene_sets='KEGG_2016', cls= sample_names, outdir='test') # prerank tool gene_ranked_dataframe = pd.DataFrame() gseapy.prerank(rnk=gene_ranked_dataframe, gene_sets='KEGG_2016', outdir='test') # ssGSEA gseapy.ssgsea(data=expression_dataframe, gene_sets='KEGG_2016', outdir='test') # gsva gseapy.gsva(data=expression_dataframe, gene_sets='KEGG_2016', outdir='test') ``` -------------------------------- ### Get Yeast Gene Library Names Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Fetches a list of available gene library names for the Yeast organism. The output is a list of strings, and the first 10 are displayed. ```python yeast = gp.get_library_name(organism='Yeast') yeast[:10] ``` -------------------------------- ### Get gseapy supported library names Source: https://github.com/zqfang/gseapy/blob/master/README.rst Retrieves a list of supported gene set library names for use with gseapy functions, such as 'KEGG_2016'. ```python #see full list of latest enrichr library names, which will pass to -g parameter: names = gseapy.get_library_name() # show top 20 entries. print(names[:20]) ``` -------------------------------- ### Example Gene List File Content Source: https://github.com/zqfang/gseapy/blob/master/docs/introduction.md Content of a sample gene list text file used as input for the gseapy.enrichr() function. ```text CTLA2B SCARA3 LOC100044683 CMBL CLIC6 IL13RA1 TACSTD2 DKKL1 CSF1 CITED1 SYNPO2L TINAGL1 PTX3 ``` -------------------------------- ### List Msigdb Categories for a Specific Version Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Lists the available categories within a specific Msigdb database version, for example, for human or mouse data. ```python # list categories given dbver. msig.list_category(dbver="2023.1.Hs") # mouse ``` -------------------------------- ### Load IPython Extensions and Libraries Source: https://github.com/zqfang/gseapy/blob/master/docs/singlecell_example.ipynb Loads necessary IPython extensions and core Python libraries for data manipulation and visualization. This is a common setup for interactive data analysis notebooks. ```python %load_ext autoreload %autoreload 2 import os import numpy as np import pandas as pd import matplotlib.pyplot as plt ``` -------------------------------- ### Get Available Gene Set Library Names Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_tutorial.md Retrieve and print a list of all available gene set library names that can be used for enrichment analysis. ```python import gseapy names = gseapy.get_library_name() print(names) ``` -------------------------------- ### GSEApy Enrichr Module Input: Gene List File Source: https://github.com/zqfang/gseapy/blob/master/docs/introduction.md Example of providing a gene list from a text file to the gseapy.enrichr() function. Each gene ID should be on a new line. ```python with open('data/gene_list.txt') as genes: print(genes.read()) ``` -------------------------------- ### Get Supported Enrichr Library Names Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Retrieves a list of all supported Enrichr library names, categorized by species (Human, Mouse, Yeast, Fly, Fish, Worm). ```python # default: Human names = gp.get_library_name() names[:10] ``` -------------------------------- ### GSEApy Enrichr Module Input: Python List Source: https://github.com/zqfang/gseapy/blob/master/docs/introduction.md Example of providing a gene list as a Python list object to the gseapy.enrichr() function. Gene names should be converted to uppercase. ```python gene_list = ['SCARA3', 'LOC100044683', 'CMBL', 'CLIC6', 'IL13RA1', 'TACSTD2', 'DKKL1', 'CSF1', 'CITED1', 'SYNPO2L'] ``` -------------------------------- ### Build Wheel and sdist Locally Source: https://github.com/zqfang/gseapy/blob/master/README.rst Build the Python wheel and source distribution packages locally. ```bash uv build ``` -------------------------------- ### Get Shape of Ranking Metric Source: https://github.com/zqfang/gseapy/blob/master/docs/singlecell_example.ipynb Retrieves and prints the shape of the ranking metric generated by the GSEA analysis. ```python res.ranking.shape # raking metric ``` -------------------------------- ### Create a CLS file Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_tutorial.md Programmatically create a CLS file in Python, defining sample groups for GSEA analysis. ```python groups = ['C1OE', 'C1OE', 'C1OE', 'Vector', 'Vector', 'Vector'] with open('gsea/edb/C1OE.cls', "w") as cl: line = f"{len(groups)} 2 1\n# C10E Vector\n" cl.write(line) cl.write(" ".join(groups) + "\n") ``` -------------------------------- ### Using Yeast Database in gseapy.prerank() Source: https://github.com/zqfang/gseapy/blob/master/docs/faq.md For gseapy.prerank(), you can input Enrichr libraries for specific organisms by first retrieving the library names and then optionally a custom GMT dictionary. ```python # get libraries you'd like to use gss = gseapy.get_library_name(organism='Yeast') # get a custom gmt_dict gmt_dict = gseapy.get_library('GO_Biological_Process_2018', organism='Yeast') # run prn_res = gseapy.prerank( ..., gene_sets=gmt_dict, ...) ``` -------------------------------- ### Get Ranking Data Shape Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Retrieves the dimensions (number of rows and columns) of the loaded ranking data DataFrame. ```python rnk.shape ``` -------------------------------- ### Get Shape of Down-regulated Genes Source: https://github.com/zqfang/gseapy/blob/master/docs/singlecell_example.ipynb Returns the shape (number of rows and columns) of the DataFrame containing significantly down-regulated genes. ```python degs_dw.shape ``` -------------------------------- ### Command Line Usage of ssGSEA Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Demonstrates how to run ssGSEA analysis directly from the command line using the gseapy tool. This is useful for batch processing or integrating into shell scripts. ```bash # !gseapy ssgsea -d ./data/testSet_rand1200.gct \ # -g data/temp.gmt \ # -o test/ssgsea_report2 \ # -p 4 --no-plot ``` -------------------------------- ### Get Shape of Up-regulated Genes Source: https://github.com/zqfang/gseapy/blob/master/docs/singlecell_example.ipynb Returns the shape (number of rows and columns) of the DataFrame containing significantly up-regulated genes. ```python degs_up.shape ``` -------------------------------- ### Reproduce GSEA Desktop Plots via Command Line Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_tutorial.md Execute the replot command from the command line to reproduce GSEA desktop plots. Specify the input and output directories. ```bash gseapy replot -i gsea -o gseapy_out ``` -------------------------------- ### Format Code with Ruff Source: https://github.com/zqfang/gseapy/blob/master/README.rst Use this command to format the gseapy codebase using Ruff. ```bash uv run ruff format gseapy ``` -------------------------------- ### Run GSEA with Manual Phenotype Setting Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Initialize GSEA with a gene expression dataset, a specific gene set (e.g., KEGG_2016), and a class vector. Manually define positive and negative phenotypes (e.g., 'AML' and 'ALL') before running the analysis. This is useful when class labels are not directly inferable from the cls file. ```python from gseapy import GSEA gs = GSEA(data=gene_exp, gene_sets='KEGG_2016', classes = class_vector, # cls=class_vector # set permutation_type to phenotype if samples >=15 permutation_type='phenotype', permutation_num=1000, # reduce number to speed up test outdir=None, method='signal_to_noise', threads=4, seed= 8) gs.pheno_pos = "AML" gs.pheno_neg = "ALL" gs.run() ``` -------------------------------- ### List Available Msigdb Versions Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Lists all available database versions for querying the Msigdb API. ```python # list msigdb version you wanna query msig.list_dbver() ``` -------------------------------- ### Initialize Msigdb API Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Initializes the Msigdb API client for accessing the Molecular Signatures Database. ```python from gseapy import Msigdb ``` ```python msig = Msigdb() ``` -------------------------------- ### Initialize SciPalette Colormap Source: https://github.com/zqfang/gseapy/blob/master/docs/singlecell_example.ipynb Initializes the SciPalette object and creates a colormap. This is likely used for subsequent visualizations, although the colormap itself is not directly displayed in this snippet. ```python from gseapy.scipalette import SciPalette sci = SciPalette() NbDr = sci.create_colormap() # NbDr ``` -------------------------------- ### Reproduce GSEA Desktop Plots with replot() Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_tutorial.md Use the replot function to reproduce GSEA desktop plots. This requires an input directory containing specific GSEA output files (edb folder with .cls, .gmt, .rnk, and results.edb). ```python import gseapy gseapy.replot(indir ='gsea', outdir = 'gseapy_out') ``` -------------------------------- ### Command line GSVA usage Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Demonstrates the command-line interface for running GSVA. It specifies the expression data file, gene set file, and the output directory for the report. ```bash # !gseapy ssgsea -d ./tests/data/expr.gsva.csv \ # -g ./tests/data/geneset.gsva.gmt \ # -o test/gsva_report ``` -------------------------------- ### Test Rust Extension Source: https://github.com/zqfang/gseapy/blob/master/README.rst Run tests specifically for the Rust extension module. ```bash cargo test --features=extension-module ``` -------------------------------- ### Importing gseapy Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Imports the gseapy library, typically done at the beginning of a Python script or notebook to access its functionalities. ```python import gseapy as gp ``` -------------------------------- ### Initialize Network Visualization Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Imports the `enrichment_map` function for building network visualizations from GSEA results. The generated nodes and edges can be used for external visualization tools like Cytoscape. ```python from gseapy import enrichment_map ``` -------------------------------- ### Replot module initialization Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Initializes the replot module within a Python console to generate plots from GSEA results. It requires specifying the input directory containing the GSEA output and the desired output directory for the plots. ```python # run command inside python console rep = gp.replot(indir="./tests/data", outdir="tests/replot_test") ``` -------------------------------- ### Check Code with Ruff Source: https://github.com/zqfang/gseapy/blob/master/README.rst Use this command to check the gseapy codebase for linting errors with Ruff. ```bash uv run ruff check gseapy ``` -------------------------------- ### Initialize Biomart API Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Initializes the Biomart API client. This API is useful for retrieving gene-related data from biological databases. ```python from gseapy import Biomart bm = Biomart() ``` -------------------------------- ### Importing NetworkX Library Source: https://github.com/zqfang/gseapy/blob/master/docs/singlecell_example.ipynb Imports the `networkx` library, commonly used for graph and network analysis in Python. This import is often a prerequisite for advanced data visualization or manipulation tasks. ```python import networkx as nx ``` -------------------------------- ### Running ssGSEA with Permutations Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Performs ssGSEA analysis with permutations enabled. Setting `permutation_num > 0` makes ssGSEA behave like the prerank tool. It's recommended to use this only if you understand its implications. ```python ss_permut = gp.ssgsea(data="./tests/extdata/Leukemia_hgu95av2.trim.txt", gene_sets="./tests/extdata/h.all.v7.0.symbols.gmt", outdir=None, sample_norm_method='rank', # choose 'custom' for your custom metric permutation_num=20, # set permutation_num > 0, it will act like prerank tool no_plot=True, # skip plotting, because you don't need these figures processes=4, seed=9) ssp_permut.res2d.head(5) ``` -------------------------------- ### Run gseapy.enrichr with list or file Source: https://github.com/zqfang/gseapy/blob/master/README.rst Demonstrates how to use the gseapy.enrichr function with a Python list of genes or a text file containing gene names. ```python # assign a list object to enrichr gl = ['SCARA3', 'LOC100044683', 'CMBL', 'CLIC6', 'IL13RA1', 'TACSTD2', 'DKKL1', 'CSF1', 'SYNPO2L', 'TINAGL1', 'PTX3', 'BGN', 'HERC1', 'EFNA1', 'CIB2', 'PMP22', 'TMEM173'] gseapy.enrichr(gene_list=gl, gene_sets='KEGG_2016', outdir='test') # or a txt file path. gseapy.enrichr(gene_list='gene_list.txt', gene_sets='KEGG_2016', outdir='test', cutoff=0.05, format='png' ) ``` -------------------------------- ### Using Yeast Database in gseapy.enrichr() Source: https://github.com/zqfang/gseapy/blob/master/docs/faq.md To use the Yeast database with gseapy.enrichr(), specify 'organism="Yeast"'. This is necessary when library names might be ambiguous across different organisms. ```python gss = gseapy.get_library_name(organism='Yeast') enr = gseapy.enrichr(gene_list=..., gene_sets=gss, organism='Yeast', ) ``` -------------------------------- ### Single Sample GSEA with File Input Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Performs ssGSEA using a text file for data and a GMT file for gene sets. 'sample_norm_method' can be set to 'rank' or 'custom'. ```python import gseapy as gp # txt, gct file input ss = gp.ssgsea(data='./tests/extdata/Leukemia_hgu95av2.trim.txt', gene_sets='./tests/extdata/h.all.v7.0.symbols.gmt', outdir=None, sample_norm_method='rank', # choose 'custom' will only use the raw value of `data` no_plot=True) ``` -------------------------------- ### Download Mouse Hallmark Gene Sets from Msigdb Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Downloads mouse hallmark gene sets from the Msigdb database using a specified version. The GMT file can be downloaded from the provided URL. ```python # mouse hallmark gene sets gmt = msig.get_gmt(category='mh.all', dbver="2023.1.Mm") ``` -------------------------------- ### Run GSEA Analysis Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Placeholder for running the GSEA analysis using the parsed data and specified parameters. ```python # run gsea ``` -------------------------------- ### Read and print CLS file content Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_tutorial.md Read the content of a CLS file and print it to the console. This file specifies sample attributes for GSEA. ```python with open('gsea/edb/C1OE.cls') as cls: print(cls.read()) # or assign a list object to parameter 'cls' like this # cls=['C1OE', 'C1OE', 'C1OE', 'Vector', 'Vector', 'Vector'] ``` -------------------------------- ### Command line replot usage Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Shows the command-line usage for the replot function in gseapy. This command is used to regenerate plots from existing GSEA analysis results, specifying the input directory and output directory. ```bash # !gseapy replot -i data -o test/replot_test ``` -------------------------------- ### Convert Seurat Data to Scanpy Format (R) Source: https://github.com/zqfang/gseapy/blob/master/docs/singlecell_example.ipynb This R code snippet demonstrates how to load Seurat data, save it as an H5Seurat file, and then convert it to the AnnData (.h5ad) format compatible with Scanpy. Requires Seurat and SeuratDisk packages. ```r library(Seurat) library(SeuratDisk) ifnb = SeuratData::LoadData("ifnb") SaveH5Seurat(ifnb, "ifnb.h5seurat", overwrite = T) Convert("ifnb.h5seurat", "ifnb.h5ad", overwrite = T) ``` -------------------------------- ### Load Data from Tab-Separated File Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Reads a tab-separated ranking file into a pandas DataFrame, setting the first column as the index. ```python ssdf = pd.read_csv("./tests/data/temp.rnk", header=None,index_col=0, sep="\t") ssdf.head() ``` -------------------------------- ### Using Yeast Database with gseapy.enrichr Source: https://github.com/zqfang/gseapy/wiki/FAQ When using Enrichr databases other than Human, specify the 'organism' argument to avoid library name conflicts. First, retrieve the library names for the desired organism. ```python gss = gseapy.get_library_name('Yeast') enr = gseapy.enrichr(gene_list=..., gene_sets=gss, organism='Yeast',# don't forget to set organism="Yeast" ...) ``` -------------------------------- ### Visualize Network Graph with Node Attributes Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Draws a NetworkX graph using a spiral layout, coloring nodes by NES and sizing them by Hits_ratio. Edges are weighted by jaccard_coef. ```python import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(8, 8)) # init node cooridnates pos=nx.layout.spiral_layout(G) #node_size = nx.get_node_attributes() # draw node nx.draw_networkx_nodes(G, pos=pos, cmap=plt.cm.RdYlBu, node_color=list(nodes.NES), node_size=list(nodes.Hits_ratio *1000)) # draw node label nx.draw_networkx_labels(G, pos=pos, labels=nodes.Term.to_dict()) # draw edge edge_weight = nx.get_edge_attributes(G, 'jaccard_coef').values() nx.draw_networkx_edges(G, pos=pos, width=list(map(lambda x: x*10, edge_weight)), edge_color='#CDDBD4') plt.show() ``` -------------------------------- ### List of Available Gene Set Libraries Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_tutorial.md A comprehensive list of gene set libraries available for use with gseapy. ```json ['Genome_Browser_PWMs', 'TRANSFAC_and_JASPAR_PWMs', 'ChEA_2013', 'Drug_Perturbations_from_GEO_2014', 'ENCODE_TF_ChIP-seq_2014', 'BioCarta_2013', 'Reactome_2013', 'WikiPathways_2013', 'Disease_Signatures_from_GEO_up_2014', 'KEGG_2013', 'TF-LOF_Expression_from_GEO', 'TargetScan_microRNA', 'PPI_Hub_Proteins', 'GO_Molecular_Function_2015', 'GeneSigDB', 'Chromosome_Location', 'Human_Gene_Atlas', 'Mouse_Gene_Atlas', 'GO_Cellular_Component_2015', 'GO_Biological_Process_2015', 'Human_Phenotype_Ontology', 'Epigenomics_Roadmap_HM_ChIP-seq', 'KEA_2013', 'NURSA_Human_Endogenous_Complexome', 'CORUM', 'SILAC_Phosphoproteomics', 'MGI_Mammalian_Phenotype_Level_3', 'MGI_Mammalian_Phenotype_Level_4', 'Old_CMAP_up', 'Old_CMAP_down', 'OMIM_Disease', 'OMIM_Expanded', 'VirusMINT', 'MSigDB_Computational', 'MSigDB_Oncogenic_Signatures', 'Disease_Signatures_from_GEO_down_2014', 'Virus_Perturbations_from_GEO_up', 'Virus_Perturbations_from_GEO_down', 'Cancer_Cell_Line_Encyclopedia', 'NCI-60_Cancer_Cell_Lines', 'Tissue_Protein_Expression_from_ProteomicsDB', 'Tissue_Protein_Expression_from_Human_Proteome_Map', 'HMDB_Metabolites', 'Pfam_InterPro_Domains', 'GO_Biological_Process_2013', 'GO_Cellular_Component_2013', 'GO_Molecular_Function_2013', 'Allen_Brain_Atlas_up', 'ENCODE_TF_ChIP-seq_2015', 'ENCODE_Histone_Modifications_2015', 'Phosphatase_Substrates_from_DEPOD', 'Allen_Brain_Atlas_down', 'ENCODE_Histone_Modifications_2013', 'Achilles_fitness_increase', 'Achilles_fitness_decrease', 'MGI_Mammalian_Phenotype_2013', 'BioCarta_2015', 'HumanCyc_2015', 'KEGG_2015', 'NCI-Nature_2015', 'Panther_2015', 'WikiPathways_2015', 'Reactome_2015', 'ESCAPE', 'HomoloGene', 'Disease_Perturbations_from_GEO_down', 'Disease_Perturbations_from_GEO_up', 'Drug_Perturbations_from_GEO_down', 'Genes_Associated_with_NIH_Grants', 'Drug_Perturbations_from_GEO_up', 'KEA_2015', 'Single_Gene_Perturbations_from_GEO_up', 'Single_Gene_Perturbations_from_GEO_down', 'ChEA_2015', 'dbGaP', 'LINCS_L1000_Chem_Pert_up', 'LINCS_L1000_Chem_Pert_down', 'GTEx_Tissue_Sample_Gene_Expression_Profiles_down', 'GTEx_Tissue_Sample_Gene_Expression_Profiles_up', 'Ligand_Perturbations_from_GEO_down', 'Aging_Perturbations_from_GEO_down', 'Aging_Perturbations_from_GEO_up', 'Ligand_Perturbations_from_GEO_up', 'MCF7_Perturbations_from_GEO_down', 'MCF7_Perturbations_from_GEO_up', 'Microbe_Perturbations_from_GEO_down', 'Microbe_Perturbations_from_GEO_up', 'LINCS_L1000_Ligand_Perturbations_down', 'LINCS_L1000_Ligand_Perturbations_up', 'LINCS_L1000_Kinase_Perturbations_down', 'LINCS_L1000_Kinase_Perturbations_up', 'Reactome_2016', 'KEGG_2016', 'WikiPathways_2016', 'ENCODE_and_ChEA_Consensus_TFs_from_ChIP-X', 'Kinase_Perturbations_from_GEO_down', 'Kinase_Perturbations_from_GEO_up', 'BioCarta_2016', 'Humancyc_2016', 'NCI-Nature_2016', 'Panther_2016'] ``` -------------------------------- ### Parse GSEA Class File Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Parses a .cls file to extract phenotype labels and class vectors for GSEA analysis. ```python import gseapy as gp import pandas as pd phenoA, phenoB, class_vector = gp.parser.gsea_cls_parser("./tests/extdata/Leukemia.cls") ``` -------------------------------- ### Run GSEA with Phenotype Permutation Source: https://github.com/zqfang/gseapy/blob/master/docs/singlecell_example.ipynb Performs Gene Set Enrichment Analysis using the GSEA algorithm. This snippet uses phenotype permutation and specifies the number of permutations, the GSEA method, and output directory. ```python res = gp.gsea(data=bdata.to_df().T, # row -> genes, column-> samples gene_sets="GO_Biological_Process_2021", cls=bdata.obs.stim, permutation_num=1000, permutation_type='phenotype', outdir=None, method='s2n', # signal_to_noise threads= 16) t2=time.time() print(t2-t1) ``` -------------------------------- ### Import Plotting Functions Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Imports the necessary functions for creating bar plots and dot plots from the gseapy library. ```python # simple plotting function from gseapy import barplot, dotplot ``` -------------------------------- ### Run GSEA with Enrichr Library Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Perform Gene Set Enrichment Analysis using a specified gene expression dataset, gene sets from an Enrichr library, and a class vector. Ensure the permutation type is set to 'phenotype' if sample size is 15 or more. ```python gs_res = gp.gsea(data=gene_exp, # or data='./P53_resampling_data.txt' gene_sets='./tests/extdata/h.all.v7.0.symbols.gmt', # or enrichr library names cls= "./tests/extdata/Leukemia.cls", # cls=class_vector # set permutation_type to phenotype if samples >=15 permutation_type='phenotype', permutation_num=1000, # reduce number to speed up test outdir=None, # do not write output to disk method='signal_to_noise', threads=4, seed= 7) ``` -------------------------------- ### Convert Human Gene Symbols to Mouse Symbols for GMT file Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Creates a dictionary mapping human gene symbols to their corresponding mouse symbols. This is useful for running GSEA on non-human species using human-formatted GMT files. ```python # get a dict symbol mappings h2m_dict = {} for i, row in h2m.loc[:,["external_gene_name", "mmusculus_homolog_associated_gene_name"]].iterrows(): if row.isna().any(): continue h2m_dict[row['external_gene_name']] = row["mmusculus_homolog_associated_gene_name"] # read gmt file into dict kegg = gp.read_gmt(path="tests/extdata/enrichr.KEGG_2016.gmt") print(kegg['MAPK signaling pathway Homo sapiens hsa04010'][:10]) ``` ```python kegg_mouse = {} for term, genes in kegg.items(): new_genes = [] for gene in genes: if gene in h2m_dict: new_genes.append(h2m_dict[gene]) kegg_mouse[term] = new_genes print(kegg_mouse['MAPK signaling pathway Homo sapiens hsa04010'][:10]) ``` -------------------------------- ### Parse Enrichr Library into Dictionary Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Downloads a specified Enrichr library (e.g., GO Molecular Function) for a given organism and prints a subset of its parsed dictionary representation. This allows direct access to gene sets within the library. ```python ## download library or read a .gmt file go_mf = gp.get_library(name='GO_Molecular_Function_2018', organism='Yeast') print(go_mf['ATP binding (GO:0005524)']) ``` -------------------------------- ### Display First Few Rows of Observation Metadata Source: https://github.com/zqfang/gseapy/blob/master/docs/singlecell_example.ipynb Shows the first five rows of the observation (cell) metadata DataFrame. Useful for inspecting cell annotations, counts, and experimental conditions. ```python adata.obs.head() ``` -------------------------------- ### Load Ranking Data Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Loads a ranking file (e.g., .rnk) into a pandas DataFrame for use with the prerank module. The file is expected to be tab-separated with gene names as the index. ```python rnk = pd.read_csv("./tests/data/temp.rnk", header=None, index_col=0, sep="\t") rnk.head() ``` -------------------------------- ### Display Class Vector Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Prints the class vector obtained from parsing a .cls file, indicating group attributes for each sample. ```python #class_vector used to indicate group attributes for each sample print(class_vector) ``` -------------------------------- ### GSVA with TXT and GMT files Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Performs Gene Set Variation Analysis (GSVA) using a text file for expression data and a GMT file for gene sets. The output directory is set to None, meaning results are not saved to disk by default. ```python import gseapy as gp es = gp.gsva(data='./tests/extdata/Leukemia_hgu95av2.trim.txt', gene_sets='./tests/extdata/h.all.v7.0.symbols.gmt', outdir=None) ``` -------------------------------- ### Read and print GMT file content Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_tutorial.md Read the content of a GMT file, which defines gene sets for enrichment analysis, and print it. ```python with open('gsea/edb/gene_sets.gmt') as gmt: print(gmt.read()) ``` -------------------------------- ### Build NetworkX Graph from Pandas Edges Source: https://github.com/zqfang/gseapy/blob/master/docs/singlecell_example.ipynb Constructs a NetworkX graph object from the edges DataFrame. It also ensures that all nodes from the nodes DataFrame are included in the graph, even if they have no edges. ```python G = nx.from_pandas_edgelist(edges, source='src_idx', target='targ_idx', edge_attr=['jaccard_coef', 'overlap_coef', 'overlap_genes']) # Add missing node if there is any for node in nodes.index: if node not in G.nodes(): G.add_node(node) ``` -------------------------------- ### Print a Specific Gene Set from Msigdb Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Prints the list of genes belonging to the 'HALLMARK_WNT_BETA_CATENIN_SIGNALING' gene set from the downloaded Msigdb GMT data. ```python print(gmt['HALLMARK_WNT_BETA_CATENIN_SIGNALING']) ``` -------------------------------- ### Display Preranked Enrichment Results Head Source: https://github.com/zqfang/gseapy/blob/master/docs/singlecell_example.ipynb Displays the first five rows of the results from the preranked gene set enrichment analysis. This helps in understanding the top enriched pathways or gene sets. ```python pre_res.res2d.head(5) ``` -------------------------------- ### Print Phenotype Labels Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Displays the phenotype labels for positively correlated samples (phenoA) and negatively correlated samples (phenoB). ```python print("positively correlated: ", phenoA) print("negtively correlated: ", phenoB) ``` -------------------------------- ### Offline Enrichment Analysis with Local Gene Sets Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Performs an offline enrichment analysis using a local gene list file and a GMT file for gene sets. It also shows how to handle a dictionary of gene sets and skips unknown libraries. ```python # NOTE: `enrich` instead of `enrichr` enr2 = gp.enrich(gene_list="./tests/data/gene_list.txt", # or gene_list=glist gene_sets=["./tests/data/genes.gmt", "unknown", kegg ], # kegg is a dict object background=None, # or "hsapiens_gene_ensembl", or int, or text file, or a list of genes outdir=None, verbose=True) ``` -------------------------------- ### Generate Gene Expression Heatmap Source: https://github.com/zqfang/gseapy/blob/master/docs/singlecell_example.ipynb Creates a heatmap visualization for a specific gene set identified by GSEA. It extracts the lead genes for a given term and plots their expression levels. ```python i = 7 genes = res.res2d.Lead_genes.iloc[i].split(";") ax = gp.heatmap(df = res.heatmat.loc[genes], z_score=None, title=res.res2d.Term.iloc[i], figsize=(6,5), cmap=plt.cm.viridis, xticklabels=False) ``` -------------------------------- ### Prerank Gene Set Enrichment Analysis Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Performs preranked gene set enrichment analysis using specified parameters. Ensure the input file and gene sets are correctly provided. The `threads` parameter can accelerate computation. ```python import gseapy as gp pre_res = gp.prerank(rnk="./tests/data/temp.rnk", # or rnk = rnk, gene_sets='KEGG_2016', threads=4, min_size=5, max_size=1000, permutation_num=1000, # reduce number to speed up testing outdir=None, # don't write to disk seed=6, verbose=True, # see what's going on behind the scenes ) ``` -------------------------------- ### Display Enrichr Results Head Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Displays the first few rows of the enrichment analysis results from Enrichr. ```python enr_bg.results.head() ``` -------------------------------- ### Map Mouse Genes to Human Homologs using Biomart Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Uses the Biomart API to query for mouse genes and their human homologs, retrieving Ensembl IDs and associated gene names. ```python from gseapy import Biomart bm = Biomart() # note the dataset and attribute names are different m2h = bm.query(dataset='mmusculus_gene_ensembl', attributes=['ensembl_gene_id','external_gene_name', 'hsapiens_homolog_ensembl_gene', 'hsapiens_homolog_associated_gene_name']) h2m = bm.query(dataset='hsapiens_gene_ensembl', attributes=['ensembl_gene_id','external_gene_name', 'mmusculus_homolog_ensembl_gene', 'mmusculus_homolog_associated_gene_name']) ``` -------------------------------- ### Display GSEA Results Table Source: https://github.com/zqfang/gseapy/blob/master/docs/singlecell_example.ipynb Displays the first 10 rows of the GSEA results table, which includes terms, enrichment scores, p-values, and associated genes. ```python res.res2d.head(10) ``` -------------------------------- ### Display Offline Enrichment Results Head Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Displays the first few rows of the offline enrichment analysis results. ```python enr2.results.head() ``` -------------------------------- ### Enrichr with Background Gene List Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Performs an Enrichr analysis using a provided gene list and a background file. The organism argument is ignored when a background is specified. ```python enr_bg = gp.enrichr(gene_list=gene_list, gene_sets=['MSigDB_Hallmark_2020','KEGG_2021_Human'], background="tests/data/background.txt", outdir=None) # don't write to disk ``` -------------------------------- ### Displaying Multi-Dataset Dot Plot Source: https://github.com/zqfang/gseapy/blob/master/docs/singlecell_example.ipynb Generates a dot plot to visualize multi-dataset enrichment results. Requires `gseapy` and `matplotlib`. Customize plot appearance with arguments like `figsize`, `x`, `x_order`, `title`, `cmap`, `size`, and `show_ring`. ```python ax = gp.dotplot(enr_res,figsize=(3,5), x='UP_DW', x_order = ["UP","DOWN"], title="GO_BP", cmap = NbDr.reversed(), size=3, show_ring=True) ax.set_xlabel("") plt.show() ``` -------------------------------- ### Dot Plot Visualization Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Generates a dot plot for gene set enrichment results. Ensure 'ofname' is set to save the figure. ```python ax = dotplot(gs_res.res2d, column="FDR q-val", title='KEGG_2021_Human', cmap=plt.cm.viridis, size=5, figsize=(4,5), cutoff=1) ``` -------------------------------- ### Enrichr with a List of Genes Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_tutorial.md Perform enrichment analysis by providing a Python list of gene IDs. Specify the gene set library and an output file name. ```python l = ['SCARA3', 'LOC100044683', 'CMBL', 'CLIC6', 'IL13RA1', 'TACSTD2', 'DKKL1', 'CSF1', 'SYNPO2L', 'TINAGL1', 'PTX3', 'BGN', 'HERC1', 'EFNA1', 'CIB2', 'PMP22', 'TMEM173'] gseapy.enrichr(gene_list=l, gene_sets='KEGG_2016', outfile='test') ``` -------------------------------- ### Display Head of Edges DataFrame Source: https://github.com/zqfang/gseapy/blob/master/docs/singlecell_example.ipynb Displays the first few rows of the edges DataFrame, detailing the connections between nodes, including source and target indices, names, and overlap coefficients. ```python edges.head() ``` -------------------------------- ### Load and view gene expression data Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_tutorial.md Load gene expression data from a text file into a pandas DataFrame and display the first few rows. This format is compatible with GSEA desktop. ```python import pandas as pd df = pd.read_table('./test/gsea_data.txt') df.head() #or assign dataframe to the parameter 'data' ``` -------------------------------- ### Enrichr with a Gene List File Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_tutorial.md Perform enrichment analysis using a text file containing gene IDs, one per line. Specify the gene set library and an output file name. ```python gseapy.enrichr(gene_list='gene_list.txt', gene_sets='KEGG_2016', outfile='test') ``` -------------------------------- ### Perform Enrichr Over-representation Analysis Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Conducts an over-representation analysis using Enrichr web services with a provided gene list and specified gene sets. The organism is set to 'human'. The output is returned as an object, and the top 5 results are displayed. ```python # if you are only intrested in dataframe that enrichr returned, please set outdir=None enr = gp.enrichr(gene_list=gene_list, # or "./tests/data/gene_list.txt", gene_sets=['MSigDB_Hallmark_2020','KEGG_2021_Human'], organism='human', # don't forget to set organism to the one you desired! e.g. Yeast outdir=None, # don't write to disk ) ``` ```python # obj.results stores all results enr.results.head(5) ``` -------------------------------- ### Plot Multiple Pathway Enrichments Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Generates plots for multiple enriched pathways. The `terms` parameter accepts a list of terms. `show_ranking=True` displays the gene ranking on a secondary y-axis. Adjust `figsize` for plot dimensions. ```python axs = pre_res.plot(terms=terms[1:5], #legend_kws={'loc': (1.2, 0)}, # set the legend loc show_ranking=True, # whether to show the second yaxis figsize=(3,4) ) ``` -------------------------------- ### Count Cells per Annotation and Condition Source: https://github.com/zqfang/gseapy/blob/master/docs/singlecell_example.ipynb Groups cells by their 'seurat_annotations' and 'stim' (condition) and counts the number of cells in each group. Helps understand the distribution of cell types across conditions. ```python adata.obs.groupby('seurat_annotations')['stim'].value_counts() ``` -------------------------------- ### Generate Dot Plot for GSEA Results Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Creates a dot plot to visualize GSEA results, showing enrichment significance based on a specified column (e.g., 'FDR q-val'). Customize dot size, colormap, and cutoff. `show_ring=False` removes the ring effect. ```python from gseapy import dotplot import matplotlib.pyplot as plt ax = dotplot(pre_res.res2d, column="FDR q-val", title='KEGG_2016', cmap=plt.cm.viridis, size=6, # adjust dot size figsize=(4,5), cutoff=0.25, show_ring=False) ``` -------------------------------- ### Display Differential Gene Expression Head Source: https://github.com/zqfang/gseapy/blob/master/docs/singlecell_example.ipynb Displays the first few rows of the differential gene expression DataFrame. This is useful for quickly inspecting the structure and content of the results. ```python degs.head() ``` -------------------------------- ### Plot Preranked Enrichment Results Source: https://github.com/zqfang/gseapy/blob/master/docs/singlecell_example.ipynb Generates a plot for the top 5 terms from the preranked enrichment analysis results. This visualization aids in interpreting the enrichment findings. ```python term2 = pre_res.res2d.Term axes = pre_res.plot(terms=term2[:5]) ``` -------------------------------- ### Generate Nodes and Edges for Enrichment Map Source: https://github.com/zqfang/gseapy/blob/master/docs/singlecell_example.ipynb Converts enrichment results into nodes and edges suitable for network visualization. This is a prerequisite for building the enrichment map graph. ```python nodes, edges = gp.enrichment_map(res.res2d) ``` -------------------------------- ### Custom Gene Sets Dictionary Input Source: https://github.com/zqfang/gseapy/blob/master/docs/faq.md When using custom GMT files, the 'gene_sets' argument can accept a dictionary. This is useful for defining your own gene sets for analysis. ```python gene_sets = { "term_1": ["gene_A", "gene_B", ...], "term_2": ["gene_B", "gene_C", ...], ... "term_100": ["gene_A", "gene_T", ...] } ``` -------------------------------- ### Read H5AD Data with Scanpy Source: https://github.com/zqfang/gseapy/blob/master/docs/singlecell_example.ipynb Loads single-cell data from an H5AD file into a Scanpy AnnData object. This file is typically generated from Seurat or other single-cell analysis tools. ```python adata = sc.read_h5ad("tests/data/ifnb.h5ad") # data from SeuratData::ifnb ``` -------------------------------- ### Generating Bar Plot for Enrichment Results Source: https://github.com/zqfang/gseapy/blob/master/docs/singlecell_example.ipynb Creates a bar plot to visualize enrichment results, useful for comparing enrichment scores across groups. Requires `gseapy`. Customize with `figsize`, `group`, `title`, and `color`. ```python ax = gp.barplot(enr_res, figsize=(3,5), group ='UP_DW', title ="GO_BP", color = ['b','r']) ``` -------------------------------- ### Displaying Top Results from ssGSEA Source: https://github.com/zqfang/gseapy/blob/master/docs/gseapy_example.ipynb Shows the top results of an ssGSEA analysis, sorted by 'Name'. This is useful for quickly inspecting the most significant gene sets. ```python ss.res2d.sort_values('Name').head() ```