pertpy.tools.Enrichment#
- class Enrichment[source]#
Methods table#
gsea(adata, *[, targets, nested, ...])Perform gene set enrichment analysis on the marker gene scores using blitzgsea.
hypergeometric(adata, *[, targets, nested, ...])Perform a hypergeometric test to assess the overrepresentation of gene group members.
plot_dotplot(adata, *[, targets, source, ...])Plots a dotplot by groupby and categories.
plot_gsea(adata, enrichment, *[, n, key, ...])Generates a blitzgsea top_table plot.
score(adata, *[, layer, targets, nested, ...])Obtain per-cell scoring of gene groups of interest.
signature_reversal(adata[, query_signature, ...])Score perturbations by how strongly they reverse a disease/query signature.
Methods#
- gsea(adata, *, targets=None, nested=False, categories=None, absolute=False, key_added='pertpy_enrichment_gsea')[source]#
Perform gene set enrichment analysis on the marker gene scores using blitzgsea.
- Parameters:
- adata
AnnData AnnData object with marker genes computed via
sc.tl.rank_genes_groups()in the original expression space.- targets
dict[str,list[str] |dict[str,list[str]]] |None, default:None The gene groups to evaluate, either as a dictionary with names of the groups as keys and gene lists as values, or a dictionary of dictionaries with names of gene group categories as keys. case it uses
d2c.score()output or loads ChEMBL-derived drug target sets.- nested
bool, default:False Indicates if
targetsis a dictionary of dictionaries with group categories as keys.- categories
str|list[str] |None, default:None Used to subset the gene groups to one or more categories, applicable if
targets=Noneornested=True.- absolute
bool, default:False If True, passes the absolute values of scores to GSEA, improving statistical power.
- key_added
str, default:'pertpy_enrichment_gsea' Prefix key that adds the results to
uns.
- adata
- Return type:
dict[str,DataFrame] |tuple[dict[str,DataFrame],dict[str,dict]]- Returns:
A dictionary with clusters as keys and data frames of test results sorted on q-value as the items.
- hypergeometric(adata, *, targets=None, nested=False, categories=None, padj_threshold=0.05, pvals_adj_thresh=None, direction='both', corr_method='benjamini-hochberg')[source]#
Perform a hypergeometric test to assess the overrepresentation of gene group members.
- Parameters:
- adata
AnnData With marker genes computed via
sc.tl.rank_genes_groups()in the original expression space.- targets
dict[str,list[str] |dict[str,list[str]]] |None, default:None The gene groups to evaluate. Can be targets of known drugs, GO terms, pathway memberships, anything you can assign genes to. If
None, will used2c.score()output if present, and if not present load the ChEMBL-derived drug target sets distributed with the package. Accepts two forms: - A dictionary with the names of the groups as keys, and the entries being the corresponding gene lists. - A dictionary of dictionaries defined like above, with names of gene group categories as keys. If passing one of those, specifynested=True.- nested
bool, default:False Whether
targetsis a dictionary of dictionaries with group categories as keys.- categories
str|list[str] |None, default:None If
targets=Noneornested=True, this argument can be used to subset the gene groups to one or more categories (keys of the original dictionary). In case of the ChEMBL drug targets, these are ATC level 1/level 2 category codes.- padj_threshold
float, default:0.05 The
pvals_adjcutoff to use on thesc.tl.rank_genes_groups()output to identify markers.- direction
str, default:'both' Whether to seek out up/down-regulated genes for the groups, based on the values from
scores. Can beup,down, orboth(for no selection).- corr_method
Literal['benjamini-hochberg','bonferroni'], default:'benjamini-hochberg' Which FDR correction to apply to the p-values of the hypergeometric test. Can be
benjamini-hochbergorbonferroni.- pvals_adj_thresh
float|None, default:None Deprecated and will be removed in a future release. Use
padj_threshold.
- adata
- Returns:
Dictionary with clusters for which the original object markers were computed as the keys, and data frames of test results sorted on q-value as the items.
- plot_dotplot(adata, *, targets=None, source='chembl', category_name='interaction_type', categories=None, groupby=None, key='pertpy_enrichment', ax=None, return_fig=False, **kwargs)[source]#
Plots a dotplot by groupby and categories.
Wraps scanpy’s dotplot but formats it nicely by categories.
- Parameters:
- adata
AnnData An AnnData object with enrichment results stored in
.uns["pertpy_enrichment_score"].- targets
dict[str,dict[str,list[str]]] |None, default:None Gene groups to evaluate, which can be targets of known drugs, GO terms, pathway memberships, etc. Accepts a dictionary of dictionaries with group categories as keys. If not provided, ChEMBL-derived or dgbidb drug target sets are used, given by
source.- source
Literal['chembl','dgidb','pharmgkb'], default:'chembl' Source of drug target sets when
targets=None,chembl,dgidborpharmgkb.- categories
Sequence[str] |None, default:None To subset the gene groups to specific categories, especially when
targets=None. For ChEMBL drug targets, these are ATC level 1/level 2 category codes.- category_name
str, default:'interaction_type' The name of category used to generate a nested drug target set when
targets=Noneandsource=dgidb|pharmgkb.- groupby
str|None, default:None dotplot groupby such as clusters or cell types.
- key
str, default:'pertpy_enrichment' Prefix key of enrichment results in
uns.- return_fig
bool, default:False if
True, returns figure of the plot, that can be used for saving.- kwargs
Passed to scanpy dotplot.
- adata
- Return type:
- Returns:
If
return_figisTrue, returns the figure, otherwiseNone.
Examples
>>> import pertpy as pt >>> import scanpy as sc >>> pt_enrichment = pt.tl.Enrichment() >>> adata = sc.datasets.pbmc3k_processed() >>> pt_enrichment.score(adata) >>> sc.tl.rank_genes_groups(adata, method="wilcoxon", groupby="louvain") >>> pt_enrichment.plot_dotplot(adata, categories=["B01", "B02", "B03"], groupby="louvain")
- Preview:
- plot_gsea(adata, enrichment, *, n=10, key='pertpy_enrichment_gsea', interactive_plot=False)[source]#
Generates a blitzgsea top_table plot.
This function is designed to visualize the results from a Gene Set Enrichment Analysis (GSEA). It uses the output from the
gsea()method, which provides the enrichment data, and displays the top results using blitzgsea’stop_table()plot.- Parameters:
- adata
AnnData AnnData object to plot.
- enrichment
dict[str,DataFrame] Cluster names as keys, blitzgsea’s
gsea()output as values.- n
int, default:10 How many top scores to show for each group.
- key
str, default:'pertpy_enrichment_gsea' GSEA results key in
uns.- interactive_plot
bool, default:False Whether to plot interactively or not.
- adata
- Return type:
Examples
>>> import pertpy as pt >>> import scanpy as sc >>> pt_enrichment = pt.tl.Enrichment() >>> adata = sc.datasets.pbmc3k_processed() >>> pt_enrichment.score(adata) >>> sc.tl.rank_genes_groups(adata, method="wilcoxon", groupby="louvain") >>> enrichment = pt_enrichment.gsea(adata) >>> pt_enrichment.plot_gsea(adata, enrichment, interactive_plot=True)
- Preview:
- score(adata, *, layer=None, targets=None, nested=False, categories=None, method='mean', n_bins=25, ctrl_size=50, random_state=0, key_added='pertpy_enrichment')[source]#
Obtain per-cell scoring of gene groups of interest.
Inspired by drug2cell score: Teichlab/drug2cell. Ensure that the gene nomenclature in your target sets is compatible with your
.var_names. The ChEMBL drug targets use HGNC.- Parameters:
- adata
AnnData An AnnData object. It is recommended to use log-normalised data.
- targets
dict[str,list[str]] |dict[str,dict[str,list[str]]] |None, default:None Gene groups to evaluate, which can be targets of known drugs, GO terms, pathway memberships, etc. Accepts two forms: - A dictionary with group names as keys and corresponding gene lists as entries. - A dictionary of dictionaries with group categories as keys. Use
nested=Truein this case. If not provided, ChEMBL-derived drug target sets are used.- nested
bool, default:False Indicates if
targetsis a dictionary of dictionaries with group categories as keys.- categories
Sequence[str] |None, default:None To subset the gene groups to specific categories, especially when
targets=Noneornested=True. For ChEMBL drug targets, these are ATC level 1/level 2 category codes.- method
Literal['mean','seurat'], default:'mean' Method for scoring gene groups.
"mean"calculates the mean over all genes, while"seurat"uses a background profile subtraction approach.- layer
str|None, default:None Specifies which
.layersof AnnData to use for expression values.- n_bins
int, default:25 The number of expression bins for the
'seurat'method.- ctrl_size
int, default:50 The number of genes to randomly sample from each expression bin for the
"seurat"method.- random_state
int|Generator|RandomState|None, default:0 Seed or random generator for sampling the control genes of the
"seurat"method.- key_added
str, default:'pertpy_enrichment' Prefix key that adds the results to
uns. Note that the actual values arekey_added_score,key_added_variables,key_added_genes,key_added_all_genes.
- adata
- Return type:
- Returns:
An AnnData object with scores.
- signature_reversal(adata, query_signature=None, *, up_genes=None, down_genes=None, layer=None, gene_symbols_key=None, min_genes=1, key_added='signature_reversal')[source]#
Score perturbations by how strongly they reverse a disease/query signature.
This computes a raw CMap-style weighted connectivity score (WTCS) on a perturbation-level AnnData object, where observations are perturbations and variables are genes. Values must be finite, signed perturbation effects relative to an appropriate matched control, such as z-scores, log-fold changes, or control-subtracted expression. Raw or pseudobulk mean expression is not a perturbation signature.
Positive query genes are up-regulated in the query state and negative genes are down-regulated. Only the sign of values in
query_signatureis used. Connectivity ranges from -1 (opposing) to 1 (similar), and the stored reversal score is its negative so that higher values indicate stronger opposition. This method does not compute CMap’s normalized connectivity score, tau, p-values, or false-discovery rates. Genes with equal perturbation values are treated as a single rank group so their input order cannot affect the score.A high reversal score is a hypothesis for follow-up, not evidence of efficacy or safety. In particular, suppressing a compensatory or protective transcriptional response can also produce a high reversal score.
- Parameters:
- adata
AnnData Perturbation-level AnnData with perturbations as observations, genes as variables, and finite signed perturbation effects relative to matched controls in
.Xorlayer.- query_signature
Mapping[str,float] |Series|None, default:None Signed query signature. Positive values indicate query-up genes and negative values query-down genes; magnitudes are ignored.
- up_genes
Sequence[str] |None, default:None Query-up genes. Used when
query_signatureis not provided.- down_genes
Sequence[str] |None, default:None Query-down genes. Used when
query_signatureis not provided.- layer
str|None, default:None Layer containing perturbation signatures. Defaults to
.X.- gene_symbols_key
str|None, default:None Optional
.varcolumn used to match query gene names instead of.var_names. Gene identifiers used for matching must be unique and non-missing.- min_genes
int, default:1 Minimum total number of query genes that must be present in
adata. CMap recommends query sets containing roughly 10 to 200 genes; very small matches should be treated as exploratory.- key_added
str, default:'signature_reversal' Prefix used to store results in
.obsand.uns.
- adata
- Return type:
- Returns:
Updates
adatawith{key_added}_score,{key_added}_connectivityand{key_added}_rankin.obs, and query metadata in.uns[key_added].
Examples
>>> import numpy as np >>> import pertpy as pt >>> from anndata import AnnData >>> effect_adata = AnnData(np.array([[-2.0, 1.0, 0.5]])) >>> effect_adata.var_names = ["IL6", "CCR7", "other"] >>> enr = pt.tl.Enrichment() >>> enr.signature_reversal(effect_adata, up_genes=["IL6"], down_genes=["CCR7"])