### Install Decoupler (Development Version) Source: https://github.com/scverse/decoupler/blob/main/README.md Installs the latest development version of decoupler directly from its GitHub repository. This is useful for testing the newest features or contributing to the project. ```bash pip install git+https://github.com/scverse/decoupler.git@main ``` -------------------------------- ### Install Decoupler (PyPI - Stable) Source: https://github.com/scverse/decoupler/blob/main/README.md Installs the latest stable release of the decoupler package from PyPI with minimal dependencies. This is the recommended method for most users. ```bash pip install decoupler ``` -------------------------------- ### Install Decoupler (PyPI - Full Release) Source: https://github.com/scverse/decoupler/blob/main/README.md Installs the latest stable full release of the decoupler package from PyPI, including extra dependencies. Use this if you need additional features or integrations. ```bash pip install decoupler[full] ``` -------------------------------- ### Install Decoupler (Conda-Forge) Source: https://github.com/scverse/decoupler/blob/main/README.md Installs the latest stable version of decoupler from the conda-forge channel using mamba or conda. Note the '-py' suffix in the package name. This method is suitable for users within the Conda ecosystem. ```bash mamba create -n=dcp conda-forge::decoupler-py ``` -------------------------------- ### Get Results from obsm Source: https://context7.com/scverse/decoupler/llms.txt Explains how to extract enrichment results stored in the 'obsm' slot of an AnnData object as a new AnnData object, suitable for further analysis and visualization. ```python import decoupler as dc import scanpy as sc import matplotlib.pyplot as plt # Run enrichment analysis adata, net = dc.ds.toy(nobs=100, nvar=30) dc.mt.ulm(adata, net, tmin=3) # Extract scores as new AnnData scores_adata = dc.pp.get_obsm(adata, key='score_ulm') print(scores_adata.shape) # Now can use scanpy functions sc.pp.scale(scores_adata) sc.tl.pca(scores_adata) sc.pp.neighbors(scores_adata) sc.tl.umap(scores_adata) # Visualize sc.pl.umap(scores_adata, color=scores_adata.var_names[0:3], cmap='RdBu_r', vcenter=0) # Compare p-values pvals_adata = dc.pp.get_obsm(adata, key='padj_ulm') print(f"Mean significant sources per cell: {(pvals_adata.X < 0.05).sum(axis=1).mean():.2f}") ``` -------------------------------- ### Generate Toy Dataset for decoupler Source: https://context7.com/scverse/decoupler/llms.txt Generates synthetic AnnData and network objects for testing decoupler functionalities. It supports basic toy data generation and can simulate pseudotime for more complex scenarios. Outputs include AnnData with expression data and a Pandas DataFrame representing the network. ```python import decoupler as dc # Basic toy dataset with 30 samples and 20 features adata, net = dc.ds.toy(nobs=30, nvar=20, bval=2.0, seed=42) print(adata.shape) # (30, 20) print(net.head()) # source target weight # 0 T1 G01 1.0 # 1 T1 G02 1.0 # 2 T1 G03 0.7 # 3 T2 G04 1.0 # 4 T2 G06 -0.5 # Generate toy dataset with pseudotime simulation adata_pt, net_pt = dc.ds.toy(nobs=50, nvar=25, pstime=True, verbose=True) print(adata_pt.obs['pstime'].head()) # C01 0.00 # C02 0.02 # C03 0.04 # ... ``` -------------------------------- ### Extract Data from AnnData Source: https://context7.com/scverse/decoupler/llms.txt Illustrates extracting expression matrices from AnnData objects, including options for different layers and raw data. It also shows how methods handle extraction internally. ```python import decoupler as dc import scanpy as sc import scipy.sparse as sp # Load data adata = sc.datasets.pbmc3k_processed() # Extract data from default layer (X) mat, obs_names, var_names = dc.pp.extract(adata, layer=None, use_raw=False) print(mat.shape) print(f"Type: {type(mat)}") # Extract from specific layer adata.layers['counts'] = adata.raw.X.copy() mat_counts, _, _ = dc.pp.extract(adata, layer='counts') # Convert to dense if needed if sp.issparse(mat_counts): mat_counts_dense = mat_counts.toarray() # Use with methods _, net = dc.ds.toy() # Methods automatically handle extraction internally dc.mt.ulm(adata, net, layer=None, use_raw=False, tmin=5) ``` -------------------------------- ### Shuffle Network and Compute Correlation Source: https://context7.com/scverse/decoupler/llms.txt Demonstrates shuffling a network for null distribution and computing network correlation using decoupler's utility functions. ```python import decoupler as dc # Shuffle network for null distribution shuffled_net = dc.pp.shuffle_net(net, target='target', seed=42) # Compute network correlation net_with_cor = dc.pp.net_corr(mat=adata.X, net=net, verbose=True) print(net_with_cor.head()) ``` -------------------------------- ### Build Adjacency Matrix Source: https://context7.com/scverse/decoupler/llms.txt Shows how to build an adjacency matrix from expression data and a network using the adjmat function. ```python import decoupler as dc # Build adjacency matrix for methods adj_matrix = dc.pp.adjmat(mat=adata.to_df(), net=net, verbose=True) print(adj_matrix.shape) ``` -------------------------------- ### Visualize Enrichment Results Source: https://context7.com/scverse/decoupler/llms.txt Demonstrates various plotting functions in decoupler for visualizing enrichment scores, including dotplots, barplots, volcano plots, and network visualizations. ```python import decoupler as dc import matplotlib.pyplot as plt # Run analysis adata, net = dc.ds.toy(nobs=50, nvar=25, seed=42) adata.obs['condition'] = (['A'] * 25) + (['B'] * 25) dc.mt.ulm(adata, net, tmin=3) # Dotplot of activities dc.pl.dotplot(adata, groupby='condition', var_names=net['source'].unique(), obsm_key='score_ulm', title='TF Activities') plt.tight_layout() plt.show() # Barplot for specific sample dc.pl.barplot(adata, obsm_key='score_ulm', obs_name='C01', top=10, title='Top 10 Activities') plt.show() # Volcano plot comparing groups dc.tl.rankby_group(adata, groupby='condition', groups=['A'], reference='B', obsm='score_ulm') dc.pl.volcano(adata, key='rankby_group') plt.show() # Network visualization dc.pl.network(net, n_sources=3, n_targets=10, source=['T1', 'T2', 'T3']) plt.show() ``` -------------------------------- ### Run Multiple Enrichment Methods (Decouple) in decoupler Source: https://context7.com/scverse/decoupler/llms.txt Executes multiple enrichment methods sequentially within the decoupler package and optionally computes consensus scores. The `decouple` function can run all available methods or a specified subset, storing results in adata.obsm. It requires an AnnData object and a network. ```python import decoupler as dc # Load data adata, net = dc.ds.toy(nobs=30, nvar=25) # Run all available methods dc.mt.decouple(adata, net, methods='all', tmin=3, verbose=True) # Check all results stored print([k for k in adata.obsm.keys() if 'score_' in k]) # ['score_aucell', 'score_gsea', 'score_gsva', 'score_mlm', # 'score_ulm', 'score_viper', 'score_waggr', 'score_zscore'] ``` -------------------------------- ### Translate Gene Symbols Source: https://context7.com/scverse/decoupler/llms.txt Shows how to translate gene symbols between different organisms using the `translate` function. It includes displaying available organisms and handling a sample DataFrame. ```python import decoupler as dc import pandas as pd # Show available organisms organisms = dc.op.show_organisms() print(organisms['name'].unique()[:10]) # Create sample data with human genes df = pd.DataFrame({ 'genesymbol': ['TP53', 'BRCA1', 'EGFR', 'MYC', 'KRAS'], 'value': [1.5, 2.3, -0.8, 1.9, -1.2] }) # Translate from human to mouse df_mouse = dc.op.translate(df, columns='genesymbol', target_organism='mouse', verbose=True) print(df_mouse) ``` -------------------------------- ### Run Decoupling Methods with Custom Parameters and Consensus Source: https://context7.com/scverse/decoupler/llms.txt Execute specific decoupling methods ('ulm', 'mlm', 'viper') with custom arguments or enable consensus scoring for aggregated results. This function takes an AnnData object and a network as input, allowing flexible analysis. ```python import decoupler as dc # Run specific methods with custom parameters methods_to_run = ['ulm', 'mlm', 'viper'] args = { 'ulm': {'tval': True}, 'mlm': {'tval': False}, 'viper': {'nes': True} } dc.mt.decouple(adata, net, methods=methods_to_run, args=args, tmin=5, verbose=True) # Run with consensus scoring adata2, net2 = dc.ds.toy(nobs=30, nvar=25) dc.mt.decouple(adata2, net2, methods=['ulm', 'mlm', 'viper'], cons=True, tmin=3) consensus = adata2.obsm['score_consensus'] print(consensus.head()) ``` -------------------------------- ### Access OmniPath Resources and Databases Source: https://context7.com/scverse/decoupler/llms.txt Query various biological resources through the OmniPath database, including PanglaoDB (cell markers), CollecTRI (TF-target interactions), and MSigDB Hallmark gene sets. This provides access to curated biological data for analysis. ```python import decoupler as dc # Show available resources resources = dc.op.show_resources() print(resources.head(10)) # Get specific resource (e.g., PanglaoDB cell markers) panglaodb = dc.op.resource(name='PanglaoDB', organism='human', license='academic', verbose=True) print(panglaodb.head()) # Get CollecTRI network collectri = dc.op.collectri(organism='human', verbose=True) print(f"CollecTRI interactions: {len(collectri)}") # Get MSigDB Hallmark gene sets hallmark = dc.op.hallmark(organism='human', verbose=True) print(hallmark['source'].unique()[:5]) ``` -------------------------------- ### Translate Network Between Organisms using Decoupler Source: https://context7.com/scverse/decoupler/llms.txt Translates a given network from one organism to another, specifying source and target columns. Requires the decoupler library. Handles organism translation for network data. ```python import decoupler as dc human_net = dc.op.dorothea(organism='human', levels=['A', 'B']) mouse_net = dc.op.translate(human_net, columns=['source', 'target'], target_organism='mouse', verbose=True) ``` -------------------------------- ### Compute Consensus Score Across Multiple Methods Source: https://context7.com/scverse/decoupler/llms.txt Calculate consensus enrichment scores and p-values by combining results from multiple decoupling methods. This involves running decouple, then computing consensus using `dc.mt.consensus`, and visualizing the results. ```python import decoupler as dc import matplotlib.pyplot as plt # Load data and run multiple methods adata, net = dc.ds.toy(nobs=25, nvar=20) dc.mt.decouple(adata, net, methods=['ulm', 'mlm', 'waggr'], tmin=3) # Compute consensus manually dc.mt.consensus(adata, verbose=True) # Access consensus results consensus_scores = adata.obsm['score_consensus'] consensus_pvals = adata.obsm['padj_consensus'] # Compare consensus with individual methods fig, axes = plt.subplots(1, 3, figsize=(15, 4)) adata.obsm['score_ulm'].iloc[0].plot(kind='bar', ax=axes[0], title='ULM') adata.obsm['score_mlm'].iloc[0].plot(kind='bar', ax=axes[1], title='MLM') consensus_scores.iloc[0].plot(kind='bar', ax=axes[2], title='Consensus') plt.tight_layout() plt.show() ``` -------------------------------- ### Filter AnnData by Expression Source: https://context7.com/scverse/decoupler/llms.txt Demonstrates filtering genes from an AnnData object based on expression levels and proportions, with options for in-place modification and grouping. ```python import decoupler as dc import scanpy as sc # Load data adata = sc.datasets.pbmc3k_processed() print(f"Before filtering: {adata.shape}") # Filter by expression level (at least 10 cells with min counts) dc.pp.filter_by_expr(adata, group=None, min_count=10, min_total_count=15, inplace=True) print(f"After expression filter: {adata.shape}") # Filter by proportion (expressed in at least 10% of cells) adata2 = sc.datasets.pbmc3k_processed() dc.pp.filter_by_prop(adata2, min_prop=0.1, min_smpls=5, inplace=True) print(f"After proportion filter: {adata2.shape}") # Use with grouping variable adata3 = sc.datasets.pbmc3k_processed() dc.pp.filter_by_expr(adata3, group='louvain', min_count=5, min_total_count=10, inplace=True) print(f"After group-aware filter: {adata3.shape}") ``` -------------------------------- ### Preprocess Network Data with Pruning Source: https://context7.com/scverse/decoupler/llms.txt Filter and manipulate network data before enrichment analysis using functions like `dc.pp.prune`. This function removes sources (e.g., transcription factors) that have fewer than a specified minimum number of targets. ```python import decoupler as dc import numpy as np # Load data adata, net = dc.ds.toy(nobs=30, nvar=30) # Prune network - remove sources with fewer than tmin targets pruned_net = dc.pp.prune(features=adata.var_names, net=net, tmin=3, verbose=True) print(f"Original sources: {net['source'].nunique()}") print(f"Pruned sources: {pruned_net['source'].nunique()}") # Read gene sets from GMT file # net = dc.pp.read_gmt("path/to/geneset.gmt") ``` -------------------------------- ### Access PROGENy Pathway Activity Network Source: https://context7.com/scverse/decoupler/llms.txt Retrieve the PROGENy network, which maps transcription factors to 14 cancer-relevant pathways. This function allows specifying the organism and the number of top genes per pathway to consider. ```python import decoupler as dc # Get PROGENy network for human progeny_net = dc.op.progeny(organism='human', top=500, verbose=True) print(progeny_net['source'].unique()) print(progeny_net.head()) # Get top 100 genes per pathway progeny_top100 = dc.op.progeny(organism='human', top=100) # Mouse data progeny_mouse = dc.op.progeny(organism='mouse', top=500) # Apply to analyze pathway activities adata, _ = dc.ds.toy(nobs=100, nvar=500) dc.mt.mlm(adata, progeny_net, tmin=10, verbose=True) pathway_scores = adata.obsm['score_mlm'] print(pathway_scores.head()) ``` -------------------------------- ### Access DoRothEA Gene Regulatory Network Source: https://context7.com/scverse/decoupler/llms.txt Retrieve the DoRothEA gene regulatory network, which contains transcription factor-target interactions. You can filter by confidence levels ('A', 'B', 'C') and customize weights for network analysis. ```python import decoupler as dc import scanpy as sc # Get DoRothEA network with high-confidence interactions (A, B, C) dorothea_net = dc.op.dorothea(organism='human', levels=['A', 'B', 'C'], verbose=True) print(dorothea_net.head()) print(f"Total interactions: {len(dorothea_net)}") print(f"Unique TFs: {dorothea_net['source'].nunique()}") print(f"Unique targets: {dorothea_net['target'].nunique()}") # Use only highest confidence level dorothea_A = dc.op.dorothea(levels='A', verbose=False) # Custom weights by confidence level custom_weights = {'A': 1, 'B': 3, 'C': 5} dorothea_custom = dc.op.dorothea(levels=['A', 'B', 'C'], dict_weights=custom_weights) # Apply to real data adata = sc.datasets.pbmc3k_processed() dc.mt.ulm(adata, dorothea_net, tmin=5, verbose=True) ``` -------------------------------- ### Univariate Linear Model (ULM) in decoupler Source: https://context7.com/scverse/decoupler/llms.txt Fits univariate linear models to infer enrichment scores using correlation-based statistics within the decoupler package. It takes an AnnData object and a network as input and stores results (scores and adjusted p-values) in adata.obsm. Minimum target filtering can be applied. ```python import decoupler as dc import numpy as np # Load data adata, net = dc.ds.toy(nobs=50, nvar=30, seed=123) # Run ULM with minimum target filtering dc.mt.ulm(adata, net, tmin=3, verbose=True) # Results stored in adata.obsm print(adata.obsm.keys()) # dict_keys(['score_ulm', 'padj_ulm']) # Access enrichment scores scores = adata.obsm['score_ulm'] print(scores.head()) # T1 T2 T3 T4 T5 # C01 8.234 -0.123 0.456 -1.234 2.345 # C02 7.891 0.234 -0.789 -2.456 1.987 # ... # Access adjusted p-values pvals = adata.obsm['padj_ulm'] print(f"Significant activities: {(pvals < 0.05).sum().sum()}") ``` -------------------------------- ### Rank Gene Activities by Group using Decoupler Source: https://context7.com/scverse/decoupler/llms.txt Computes differential activity scores between groups of samples using decoupler's rankby_group function. It requires an AnnData object and a network. The function calculates scores and p-values for ranked genes, allowing visualization via barplots. ```python import decoupler as dc # Prepare data adata, net = dc.ds.toy(nobs=60, nvar=30, seed=123) adata.obs['celltype'] = (['TypeA'] * 20 + ['TypeB'] * 20 + ['TypeC'] * 20) # Run enrichment dc.mt.ulm(adata, net, tmin=3) # Rank activities comparing TypeA vs rest dc.tl.rankby_group(adata, groupby='celltype', groups=['TypeA'], obsm='score_ulm', method='wilcoxon') # Access results rank_results = adata.uns['rankby_group'] print(rank_results['names'].head()) # Top ranked sources print(rank_results['scores'].head()) # Test statistics print(rank_results['pvals_adj'].head()) # Adjusted p-values # Compare specific groups dc.tl.rankby_group(adata, groupby='celltype', groups=['TypeA'], reference='TypeB', obsm='score_ulm') # Visualize dc.pl.barplot(adata.uns['rankby_group'], top=5) ``` -------------------------------- ### Over Representation Analysis (ORA) in decoupler Source: https://context7.com/scverse/decoupler/llms.txt Performs Fisher's exact test-based enrichment analysis for binary feature sets using decoupler. It takes an AnnData object and a network, allowing specification of columns for sources and targets. Outputs include log odds ratios and adjusted p-values stored in adata.obsm. ```python import decoupler as dc import numpy as np # Create data with significant features adata, net = dc.ds.toy(nobs=20, nvar=30) # Mark top expressed genes as significant (e.g., from differential expression) top_n = 10 pvals = np.random.uniform(0, 1, adata.n_vars) pvals[:top_n] = 0.001 # Make first 10 genes significant adata.var['pvals'] = pvals # Run ORA using p-value threshold dc.mt.ora(adata, net, source='pvals', target='pvals', min_n=3, verbose=True) # Access ORA results ora_scores = adata.obsm['score_ora'] # Log odds ratios ora_pvals = adata.obsm['padj_ora'] # Fisher's exact test p-values print(f"Enriched sources (padj < 0.05): {(ora_pvals < 0.05).sum(axis=1)}") ``` -------------------------------- ### Multivariate Linear Model (MLM) in decoupler Source: https://context7.com/scverse/decoupler/llms.txt Fits multivariate linear models in decoupler to infer enrichment scores while accounting for simultaneous correlations between sources. It requires an AnnData object and a network, storing results in adata.obsm. This method can be compared against ULM results. ```python import decoupler as dc # Load data adata, net = dc.ds.toy(nobs=40, nvar=25) # Run MLM - accounts for dependencies between transcription factors dc.mt.mlm(adata, net, tmin=5, verbose=True) # Compare with ULM results dc.mt.ulm(adata, net, tmin=5, verbose=False) # Extract both results mlm_scores = adata.obsm['score_mlm'] ulm_scores = adata.obsm['score_ulm'] # Check correlation between methods import scipy.stats as sts corr = sts.spearmanr(mlm_scores.values.flatten(), ulm_scores.values.flatten()) print(f"Spearman correlation: {corr.correlation:.3f}, p={corr.pvalue:.2e}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.