Enrichment#

Gene set enrichment analysis allows for the determination of gene sets that are significantly upregulated or downregulated in one population compared to another, providing insights into cellular functions and disease mechanisms. It is typically performed by aggregating differential expression results across cells, then using statistical methods to determine if specific sets of genes are disproportionately represented among the differentially expressed genes.

Although commonly done for pathways, any gene set can be tested for enrichment. Pertpy offers rich access to metadata which we can leverage for this purpose. Here, we’ll reproduce drug2cell [KCM+23] where we’ll enrich cells using the chEMBL database which contains bioactive molecules with drug-like properties and their corresponding gene sets.

Setup#

We’ll be using the standard processed pbmc3k dataset from scanpy.

import warnings

warnings.filterwarnings("ignore")
import pandas as pd
import pertpy as pt
import scanpy as sc
import seaborn as sns

Dataset#

adata = sc.datasets.pbmc3k_processed()
adata
AnnData object with n_obs × n_vars = 2638 × 1838
    obs: 'n_genes', 'percent_mito', 'n_counts', 'louvain'
    var: 'n_cells'
    uns: 'draw_graph', 'louvain', 'louvain_colors', 'neighbors', 'pca', 'rank_genes_groups'
    obsm: 'X_pca', 'X_tsne', 'X_umap', 'X_draw_graph_fr'
    varm: 'PCs'
    obsp: 'distances', 'connectivities'
    layers: None (.X)

Fetching chEMBL metadata#

As a (currently optional!) step we will fetch the chEMBL metadata and examine it:

pt_chembl = pt.md.Drug()
pt_chembl.annotate(adata)
AnnData object with n_obs × n_vars = 2638 × 1838
    obs: 'n_genes', 'percent_mito', 'n_counts', 'louvain'
    var: 'n_cells', 'compounds'
    uns: 'draw_graph', 'louvain', 'louvain_colors', 'neighbors', 'pca', 'rank_genes_groups'
    obsm: 'X_pca', 'X_tsne', 'X_umap', 'X_draw_graph_fr'
    varm: 'PCs'
    obsp: 'distances', 'connectivities'
    layers: None (.X)
non_empty_compounds = adata.var["compounds"][adata.var["compounds"] != ""]
non_empty_compounds
index
CDA                                CHEMBL3237547|CEDAZURIDINE
HDAC1       CHEMBL343448|ROMIDEPSIN|CHEMBL3545368|PANOBINO...
FAAH                                  CHEMBL112|ACETAMINOPHEN
PKN2        CHEMBL1421|DASATINIB|CHEMBL1983268|ENTRECTINIB...
CD2                                   CHEMBL1201571|ALEFACEPT
                                  ...                        
C5AR1                                  CHEMBL3989871|AVACOPAN
FPR1        CHEMBL101|PHENYLBUTAZONE|CHEMBL1223|PENICILLIN...
APOBEC3A                               CHEMBL474579|CEFOTETAN
APOBEC3G                               CHEMBL474579|CEFOTETAN
TYMP                      CHEMBL65375|TIPIRACIL HYDROCHLORIDE
Name: compounds, Length: 94, dtype: str

94 of the genes are included in one or several (divided by the ‘|’ character) gene sets of the chEMBL database.

But are any of these associations statistically significant? Let’s test this with a hypergeometric test. As a first step, we’ll score the genes which computes the mean gene expression of each gene group per cell.

Scoring gene sets#

pt_enricher = pt.tl.Enrichment()
pt_enricher.score(adata)

This added several new keys in uns such as the pertpy_enrichment_score:

adata.uns["pertpy_enrichment_score"]
array([[-0.23824894, -0.17137621, -0.17137621, ..., -0.24132079,
        -0.12806633, -0.17137621],
       [-0.30187321, -0.22021136, -0.22021136, ..., -0.05865689,
        -0.21009679, -0.22021136],
       [-0.3140685 , -0.21615721, -0.21615721, ..., -0.10235345,
        -0.09656522, -0.21615721],
       ...,
       [-0.23376985, -0.16457197, -0.16457197, ..., -0.27393138,
        -0.0898563 , -0.16457197],
       [-0.21525031, -0.15072401, -0.15072401, ..., -0.32494837,
        -0.06951345, -0.15072401],
       [-0.2774846 , -0.18967144, -0.18967144, ..., -0.19803014,
        -0.0647603 , -0.18967144]], shape=(2638, 601))

Let’s calculate the differentially expressed genes using a simple Wilcoxon test:

sc.tl.rank_genes_groups(adata, method="wilcoxon", groupby="louvain")

It’s possible to subset the drug space based on their ATC level 1 and 2 categories for more fine-grained plots:

pt_enricher.plot_dotplot(adata, categories=["B01", "B02", "B03"], groupby="louvain")
../../_images/39c2f5a339cac9f836e2b55a6fca33897bbf34749f6bc18049b55145b355cacb.png

Hypergeometric test#

We can now apply pertpy’s hypergeometric test to test for significance. By default, it uses the scoring output, but it can also be used with custom targets that can be passed. The output is a dictionary of DataFrames with the clusters used to compute the markers in the original expression space as the keys.

overrepresentation = pt_enricher.hypergeometric(adata)
overrepresentation["B cells"]
intersection gene_group markers universe pvals pvals_adj
CHEMBL1261|CITRIC ACID 0 1 695 1838 1.000000 1.0
CHEMBL1255943|GLUTAMIC ACID HYDROCHLORIDE 0 1 695 1838 1.000000 1.0
CHEMBL1201130|BETAINE HYDROCHLORIDE 0 1 695 1838 1.000000 1.0
CHEMBL1200585|OXYMETHOLONE 0 2 695 1838 1.000000 1.0
CHEMBL1705709|SODIUM FEREDETATE 0 1 695 1838 1.000000 1.0
... ... ... ... ... ... ...
CHEMBL1691|BETAXOLOL HYDROCHLORIDE 0 1 695 1838 1.000000 1.0
CHEMBL3137318|TALAZOPARIB TOSYLATE 1 1 695 1838 0.378128 1.0
CHEMBL544665|FINGOLIMOD HYDROCHLORIDE 0 1 695 1838 1.000000 1.0
CHEMBL1562610|MECLOFENAMATE SODIUM 0 1 695 1838 1.000000 1.0
CHEMBL1200467|HYDROXYZINE PAMOATE 0 1 695 1838 1.000000 1.0

601 rows × 6 columns

Pertpy provides a GSEA (gene set enrichment analysis) wrapper, executed through blitzgsea. Unlike standard overrepresentation testing, GSEA evaluates gene sets based on their marker scores and assesses the distribution of the gene group members.

enrichment = pt_enricher.gsea(adata)
pt_enricher.plot_gsea(adata, enrichment, interactive_plot=True)
../../_images/ab5c5d845263cf7a93a8e4a604930ef78273cafeb069a13b4aa92006681692ff.png ../../_images/a8ee0f586210b403810cebdfd3ba9eccc03746756ecf31c010202ab8028b9ad5.png ../../_images/99b5a931c95678df84a6da2d7adc7a24a90842397a3ae6dd36a5482b9bdf2b07.png ../../_images/aa98c5be63cc7797c3b4274e37f5037df696f72361555f03cc600cb2785f3a80.png ../../_images/d91756c24911eb348d944356ce21f5ae66b12571d3a0335ec465566387a3a15a.png ../../_images/8a1d66aad1a50c8677f3078e9e3bd19aca4b06398e06d9ec083fcd96d3a7914c.png ../../_images/c775e3165421faac3427e27e555c49bbb9d66313fba84e83de8b410795946738.png ../../_images/5d08431db0e0c3fa3bda6063efd0eeeccd9952127681f871e23abb199e886cbd.png

Using custom gene sets#

By default, the score function uses the chEMBL dataset, but other it is possible to score any gene sets of choice. The input takes the form of a dictionary with group names as keys and corresponding gene sets as values.

import blitzgsea as blitz

targets = blitz.enrichr.get_library("GO_Molecular_Function_2021")
targets["MHC class II receptor activity (GO:0032395)"]
['HLA-DOA',
 'HLA-DOB',
 'HLA-DPA1',
 'HLA-DQA1',
 'HLA-DQA2',
 'HLA-DQB1',
 'HLA-DQB2',
 'HLA-DRA',
 'HLA-DRB1',
 'HLA-DRB3']

We can pass these gene sets to the score function’s targets parameter:

pt_enricher.score(adata, targets=targets)
enrichment = pt_enricher.gsea(adata, targets=targets)
fig = blitz.plot.running_sum(
    signature=adata.uns["pertpy_enrichment_gsea"]["scores"]["B cells"],
    library=adata.uns["pertpy_enrichment_gsea"]["targets"],
    result=enrichment["B cells"],
    geneset="MHC class II receptor activity (GO:0032395)",
    interactive_plot=True,
)
fig.show()
../../_images/dd90095d9b6e942ca2eaeb7bc7399fcf78d36636397d464e7987c7898eb07c8a.png

Signature reversal#

Enrichment.signature_reversal ranks perturbations by how strongly their gene-level effects oppose an up/down query signature. The method expects signed perturbation effects relative to matched controls rather than raw expression.

cell_adata = pt.ds.distance_example()
ps = pt.tl.PseudobulkSpace()
ps_adata = ps.compute(
    cell_adata,
    target_col="perturbation",
    mode="mean",
)
ps_adata = ps.compute_control_diff(
    ps_adata,
    target_col="perturbation",
    reference_key="control",
)
ps_adata = ps_adata[ps_adata.obs["perturbation"] != "control"].copy()

To keep this example self-contained, the query is defined as the opposite of one observed CRISPR perturbation signature. In a real analysis, use an independently derived disease or state signature.

query_profile = -ps_adata[ps_adata.obs["perturbation"] == "p-sgCREB1-2"].to_df().iloc[0]
up_genes = query_profile[query_profile > 0].nlargest(20).index.tolist()
down_genes = query_profile[query_profile < 0].nsmallest(20).index.tolist()

enr = pt.tl.Enrichment()
enr.signature_reversal(
    ps_adata,
    up_genes=up_genes,
    down_genes=down_genes,
)
ps_adata.obs.sort_values("signature_reversal_rank")[
    ["perturbation", "signature_reversal_score", "signature_reversal_rank"]
].head(10)
perturbation signature_reversal_score signature_reversal_rank
p-sgCREB1-2 p-sgCREB1-2 1.000000 1
p-sgEGR1-4 p-sgEGR1-4 0.936307 2
p-sgGABPA-9 p-sgGABPA-9 0.931187 3
p-sgNR2C2-2 p-sgNR2C2-2 0.930610 4
p-sgYY1-3 p-sgYY1-3 0.930470 5
p-sgNR2C2-3 p-sgNR2C2-3 0.929137 6
p-sgELK1-1 p-sgELK1-1 0.925710 7
p-sgEGR1-2 p-sgEGR1-2 0.924965 8
p-sgELF1-5 p-sgELF1-5 0.924789 9
p-sgIRF1-2 p-sgIRF1-2 0.918981 10
top = ps_adata.obs.nsmallest(10, "signature_reversal_rank").index
plot_genes = up_genes[:5] + down_genes[:5]
sc.pl.matrixplot(
    ps_adata[top],
    var_names=plot_genes,
    groupby="perturbation",
    categories_order=top,
    colorbar_title="Control-relative effect",
)
../../_images/d6ab3be1872741974a8fbd28c5a0c9cf3074b9b6342064f2256f0466936b39c7.png

A high reversal score is a hypothesis for follow-up rather than evidence of efficacy or safety.

Cytokine responses#

The Human Cytokine Dictionary holds the genes that 90 cytokines up- or downregulate in 24 cell types of human PBMCs. pt.md.Cytokine provides them as gene sets, which the enrichment tests take as targets, to find the cytokine responses that a dataset resembles. We use PBMCs from Kang et al. that were stimulated with interferon-β, so the dictionary should point to interferon-β.

kang = pt.ds.kang_2018()
sc.pp.normalize_total(kang)
sc.pp.log1p(kang)

The dictionary names its cell types differently from the dataset:

pt_cytokine = pt.md.Cytokine()
pt_cytokine.dictionary["celltype"].cat.categories
Index(['Intermediate_B_cell', 'NKT', 'CD8_Memory_T_cell', 'NK_CD56low',
       'CD16_Mono', 'NK_CD56hi', 'CD8_Naive_T_cell', 'pDC', 'ILC', 'MAIT',
       'Naive_B_cell', 'CD4_Naive_T_cell', 'Treg', 'Plasmablast',
       'Granulocyte', 'B_cell', 'CD4_T_cell', 'HSPC', 'CD8_T_cell',
       'CD14_Mono', 'cDC', 'CD4_Memory_T_cell', 'NK', 'Mono'],
      dtype='str')
celltypes = {
    "CD14+ Monocytes": "CD14_Mono",
    "FCGR3A+ Monocytes": "CD16_Mono",
    "Dendritic cells": "cDC",
    "B cells": "B_cell",
    "CD4 T cells": "CD4_T_cell",
    "CD8 T cells": "CD8_T_cell",
    "NK cells": "NK",
}

For each cell type, we rank the genes between stimulated and control cells. GSEA then tests these rankings against the genes that each cytokine upregulates in the same cell type.

results = []
for kang_celltype, hcd_celltype in celltypes.items():
    cells = kang[kang.obs["cell_type"] == kang_celltype].copy()
    sc.tl.rank_genes_groups(cells, groupby="label", groups=["stim"], reference="ctrl", method="wilcoxon")
    enrichment = pt_enricher.gsea(cells, targets=pt_cytokine.gene_sets(hcd_celltype))
    results.append(enrichment["stim"].assign(cell_type=kang_celltype))
results = pd.concat(results)

We plot the normalized enrichment scores of the cytokines that rank among the top three in any cell type:

top = results.groupby("cell_type", sort=False).head(3).index.unique()
nes = results.loc[top].reset_index().pivot(index="cell_type", columns="Term", values="nes")
sns.heatmap(nes.loc[list(celltypes), top], cmap="Reds", annot=True, fmt=".1f").set(xlabel="Cytokine", ylabel="")
[Text(0.5, 23.185633680555554, 'Cytokine'), Text(50.38563368055554, 0.5, '')]
../../_images/4a8d5e07dd8932362e9f1f05e6c3ec2d2b3aa6f7825e3d48becff5120f52a0b2.png

Interferon-β and the closely related interferon-ω score highest in monocytes and dendritic cells, which respond most strongly to the stimulation. In lymphocytes, the IL-15 and IL-7 gene sets score about as high as interferon-β, because they share many interferon-stimulated genes with it. In CD4 T cells, for example, 184 of the 250 genes in the IL-15 set are also in the interferon-β set. Overlapping gene sets like these make the dictionary a source of cytokine candidates rather than a way to identify a single cytokine.

Conclusion#

Pertpy enables gene set enrichment analysis with the metadata in pertpy, such as the chEMBL drug targets and the Human Cytokine Dictionary. It identifies the gene sets that bioactive molecules and cytokines affect in different cell populations.