### Pertpy Installation Guide Source: https://pertpy.readthedocs.io/en/stable/installation Instructions for installing the pertpy library. Covers installation via PyPI and conda-forge, as well as optional dependency groups for specific functionalities like differential gene expression or specific tools. ```bash # Install stable release via PyPI pip install pertpy # Install stable release via conda-forge conda install -c conda-forge pertpy # Install with additional dependency groups (example for differential gene expression) # pip install pertpy[degs] # conda install -c conda-forge pertpy python-deseq2 # Install with additional dependency groups (example for milo) # pip install pertpy[milo] # conda install -c conda-forge pertpy milo # Install with additional dependency groups (example for tascCODA) # pip install pertpy[tasccoda] # conda install -c conda-forge pertpy tasccoda ``` -------------------------------- ### Python Example: Guide Assignment and Heatmap Plotting Source: https://pertpy.readthedocs.io/en/stable/api/preprocessing/pertpy.preprocessing.GuideAssignment Demonstrates how to load data, assign guides based on a threshold, and visualize the assignments using a heatmap. ```python import pertpy as pt mdata = pt.dt.papalexi_2021() gdo = mdata.mod["gdo"] ga = pt.pp.GuideAssignment() ga.assign_by_threshold(gdo, assignment_threshold=5) ga.plot_heatmap(gdo) ``` -------------------------------- ### pertpy GuideAssignment Example Usage Source: https://pertpy.readthedocs.io/en/stable/api/preprocessing/pertpy.preprocessing.GuideAssignment Demonstrates the basic usage of the GuideAssignment class by loading data and performing guide assignment. ```python >>> mdata = pt.dt.papalexi_2021() >>> gdo = mdata.mod["gdo"] >>> ga = pt.pp.GuideAssignment() >>> ga.assign_mixture_model(gdo) ``` -------------------------------- ### Install Pertpy Development Dependencies Source: https://pertpy.readthedocs.io/en/stable/_sources/contributing This snippet shows how to clone the pertpy repository and install the necessary development dependencies, including those for testing and documentation, using pip. It's a common first step for contributors. ```bash git clone https://github.com/scverse/pertpy.git cd pertpy pip install -e ".[dev,test,doc]" ``` -------------------------------- ### Assigning Guides with pertpy Source: https://pertpy.readthedocs.io/en/stable/api/preprocessing_index This example demonstrates how to use the `GuideAssignment` class from the pertpy library to assign cells to guide RNAs. It involves loading data, preprocessing it, initializing the `GuideAssignment` object, assigning guides based on a threshold, and visualizing the results with a heatmap. Dependencies include pertpy and scanpy. ```python import pertpy as pt import scanpy as sc mdata = pt.dt.papalexi_2021() gdo = mdata.mod["gdo"] gdo.layers["counts"] = gdo.X.copy() sc.pp.log1p(gdo) ga = pt.pp.GuideAssignment() ga.assign_by_threshold(gdo, 5, layer="counts", output_layer="assigned_guides") ga.plot_heatmap(gdo, layer="assigned_guides") ``` -------------------------------- ### Pertpy Augur Initialization and Prediction Example Source: https://pertpy.readthedocs.io/en/stable/api/tools/pertpy.tools.Augur Demonstrates how to initialize the Augur tool with a specific classifier and load data for prediction. This setup is a prerequisite for using Augur's analytical methods. ```python import pertpy as pt # Load example data adata = pt.dt.bhattacherjee() # Initialize Augur with a Random Forest Classifier ag_rfc = pt.tl.Augur("random_forest_classifier") # Load data for a specific condition and treatment data_15 = ag_rfc.load(adata, condition_label="Maintenance_Cocaine", treatment_label="withdraw_15d_Cocaine") # Predict augur scores adata_15, results_15 = ag_rfc.predict(data_15, random_state=None, n_threads=4) # Predict permuted augur scores for differential analysis adata_15_permute, results_15_permute = ag_rfc.predict(data_15, augur_mode="permute", n_subsamples=100, random_state=None, n_threads=4) ``` -------------------------------- ### Install Pre-commit Hooks Source: https://pertpy.readthedocs.io/en/stable/_sources/contributing This command installs pre-commit hooks locally in the repository. These hooks automatically check and format code to enforce consistent code styles before commits are made. ```bash pre-commit install ``` -------------------------------- ### Pertpy Tutorial: Guide RNA Assignment Source: https://pertpy.readthedocs.io/en/stable/tutorials/notebooks/ontology_mapping A tutorial demonstrating the process of Guide RNA assignment within the pertpy library. ```python # This is a placeholder for actual code. The provided text only links to the tutorial. # Example: Guide RNA assignment might involve loading data and applying a specific function. # import pertpy as pt # data = pt.data.load_dataset('example_dataset') # assigned_rna = pt.preprocessing.GuideAssignment(data) ``` -------------------------------- ### Tasccoda Example Workflow Source: https://pertpy.readthedocs.io/en/stable/api/tools/pertpy.tools.Tasccoda Illustrates a complete workflow using the Tasccoda tool from Pertpy, starting with loading an example dataset, aggregating lineage information, preparing the model with a tree structure, and running the NUTS sampler. This showcases advanced usage with tree-based aggregation. ```python import pertpy as pt adata = pt.dt.tasccoda_example() tasccoda = pt.tl.Tasccoda() mdata = tasccoda.load( adata, type="sample_level", levels_agg=["Major_l1", "Major_l2", "Major_l3", "Major_l4", "Cluster"], key_added="lineage", add_level_name=True ) mdata = tasccoda.prepare( mdata, formula="Health", reference_cell_type="automatic", tree_key="lineage", pen_args={"phi": 0} ) tasccoda.run_nuts(mdata, num_samples=1000, num_warmup=100, rng_key=42) tasccoda.summary(mdata) ``` -------------------------------- ### Pertpy Tutorial: Guide RNA Assignment Source: https://pertpy.readthedocs.io/en/stable/tutorials/tools A tutorial demonstrating how to perform Guide RNA assignment using Pertpy's preprocessing tools. ```python # Example usage for Guide RNA assignment # import pertpy as pt # guide_assignment = pt.preprocessing.GuideAssignment() # guide_assignment.assign_guides(adata, ...) ``` -------------------------------- ### Tutorial: Guide RNA assignment Source: https://pertpy.readthedocs.io/en/stable/tutorials/notebooks/tasccoda A tutorial demonstrating how to perform Guide RNA assignment using pertpy's preprocessing tools. ```python # Example usage for Guide RNA assignment # from pertpy.preprocessing import GuideAssignment # guide_assignment = GuideAssignment() # guide_assignment.assign_guides(adata, ...) # Placeholder for actual code ``` -------------------------------- ### Guide RNA Assignment Tutorial Source: https://pertpy.readthedocs.io/en/stable/api/data/pertpy.data.datlinger_2017 Details the process of guide RNA assignment in single-cell experiments using pertpy. ```APIDOC Tutorial: Guide RNA assignment - Path: tutorials/notebooks/guide_rna_assignment.html - Focus: CRISPR screen analysis preprocessing. ``` -------------------------------- ### Build Documentation Locally Source: https://pertpy.readthedocs.io/en/stable/_sources/contributing This snippet outlines the steps to build the project's documentation locally using the 'make html' command within the 'docs' directory. It also shows how to open the generated HTML index file. ```bash cd docs make html open _build/html/index.html ``` -------------------------------- ### Load Example Data and Plot Spatial Scatter Source: https://pertpy.readthedocs.io/en/stable/tutorials/notebooks/sccoda_extended Demonstrates loading an example dataset using pertpy and creating a spatial scatter plot, colored by cell type. This is a common starting point for spatial analysis workflows. ```python # Example usage import pertpy as pt adata = pt.dt.load_adata_example() pt.pl.spatial_scatter(adata, color_by="cell_type", title="Spatial Scatter Plot") ``` -------------------------------- ### Tasccoda Example Usage Source: https://pertpy.readthedocs.io/en/stable/api/tools/pertpy.tools.Tasccoda Demonstrates a typical workflow for using the Tasccoda class, including loading example data, preparing it for analysis, running the tascCODA model, and retrieving node effects. ```python import pertpy as pt adata = pt.dt.tasccoda_example() tasccoda = pt.tl.Tasccoda() mdata = tasccoda.load( adata, type="sample_level", levels_agg=["Major_l1", "Major_l2", "Major_l3", "Major_l4", "Cluster"], key_added="lineage", add_level_name=True ) mdata = tasccoda.prepare( mdata, formula="Health", reference_cell_type="automatic", tree_key="lineage", pen_args={"phi" : 0} ) tasccoda.run_nuts(mdata, num_samples=1000, num_warmup=100, rng_key=42) node_effects = tasccoda.get_node_df(mdata) ``` -------------------------------- ### Setup and Imports Source: https://pertpy.readthedocs.io/en/stable/tutorials/notebooks/sccoda_extended Initializes the environment by importing necessary libraries and suppressing warnings. Libraries include arviz for visualization, matplotlib for plotting, pandas for data manipulation, and pertpy for single-cell analysis functionalities. ```python import warnings warnings.filterwarnings("ignore") import arviz as az import matplotlib.pyplot as plt import pandas as pd import pertpy as pt ``` -------------------------------- ### Pertpy Sccoda Initialization and Preparation Example Source: https://pertpy.readthedocs.io/en/stable/api/tools/pertpy.tools.Sccoda Demonstrates loading data, preparing it for differential abundance analysis, and setting up MCMC states using the Sccoda class in pertpy. ```python import pertpy as pt haber_cells = pt.dt.haber_2017_regions() sccoda = pt.tl.Sccoda() mdata = sccoda.load(haber_cells, type="cell_level", generate_sample_level=True, cell_type_identifier="cell_label", sample_identifier="batch", covariate_obs=["condition"]) mdata = sccoda.prepare(mdata, formula="condition", reference_cell_type="Endocrine") sccoda.set_init_mcmc_states(rng_key=None, ref_index=0, sample_adata=mdata) ``` -------------------------------- ### Tutorial: scGen Perturbation Response Prediction Source: https://pertpy.readthedocs.io/en/stable/api/data/pertpy.data.cinemaot_example Guides users on using scGen for predicting perturbation responses in single-cell data. This tutorial covers the setup and execution of scGen. ```python # Example usage of scGen (conceptual, actual code would be in notebook) # import pertpy as pt #adata = pt.dt.scgen_example() #scgen_result = pt.tl.Scgen(adata, ...) #print(scgen_result) ``` -------------------------------- ### Sccoda Usage Example Source: https://pertpy.readthedocs.io/en/stable/api/tools/pertpy.tools.Sccoda Demonstrates loading data, preparing it for Sccoda analysis, running the NUTS sampler, and preparing summary dataframes. ```python >>> import pertpy as pt >>> haber_cells = pt.dt.haber_2017_regions() >>> sccoda = pt.tl.Sccoda() >>> mdata = sccoda.load(haber_cells, type="cell_level", generate_sample_level=True, cell_type_identifier="cell_label", sample_identifier="batch", covariate_obs=["condition"]) >>> mdata = sccoda.prepare(mdata, formula="condition", reference_cell_type="Endocrine") >>> sccoda.run_nuts(mdata, num_warmup=100, num_samples=1000, rng_key=42) >>> intercept_df, effect_df = sccoda.summary_prepare(mdata["coda"]) ``` -------------------------------- ### Tutorial: Milo Differential Abundance Analysis Source: https://pertpy.readthedocs.io/en/stable/api/data/pertpy.data.cinemaot_example Guides users through using Milo for KNN-based differential abundance analysis in single-cell data. Covers setup and analysis steps. ```python # Example usage of Milo (conceptual, actual code would be in notebook) # import pertpy as pt #adata = pt.dt.milo_example() #milo_result = pt.tl.Milo(adata, ...) #print(milo_result) ``` -------------------------------- ### Pertpy EdgeR plot_multicomparison_fc Example Source: https://pertpy.readthedocs.io/en/stable/api/preprocessing/pertpy.tools.Statsmodels Demonstrates how to use the plot_multicomparison_fc function from Pertpy's EdgeR module to visualize differential expression results. It includes setup with sample data and calling the plotting function. ```python >>> # Example with EdgeR >>> import pertpy as pt >>> adata = pt.dt.zhang_2021() >>> adata.layers["counts"] = adata.X.copy() >>> ps = pt.tl.PseudobulkSpace() >>> pdata = ps.compute( ... adata, ... target_col="Patient", ... groups_col="Cluster", ... layer_key="counts", ... mode="sum", ... min_cells=10, ... min_counts=1000, ... ) >>> edgr = pt.tl.EdgeR(pdata, design="~Efficacy+Treatment") >>> res_df = edgr.compare_groups(pdata, column="Efficacy", baseline="SD", groups_to_compare=["PR", "PD"]) >>> edgr.plot_multicomparison_fc(res_df) ``` -------------------------------- ### Build Documentation Locally Source: https://pertpy.readthedocs.io/en/stable/contributing This snippet shows the shell commands to build the project documentation. It involves changing the directory to 'docs', running 'make html' to generate the documentation, and then opening the resulting 'index.html' file in a web browser. ```shell cd docs make html open _build/html/index.html ``` -------------------------------- ### Plotting Regression Mean with Pertpy Scgen Source: https://pertpy.readthedocs.io/en/stable/api/tools/pertpy.tools.Scgen This example demonstrates how to use the `pertpy` library's `Scgen` model to train a model, predict gene expression, and then visualize the regression mean plot. It covers data loading, model setup, training, prediction, and plotting steps for single-cell gene expression analysis. ```python import pertpy as pt data = pt.dt.kang_2018() pt.tl.Scgen.setup_anndata(data, batch_key="label", labels_key="cell_type") scg = pt.tl.Scgen(data) scg.train(max_epochs=10, batch_size=64, early_stopping=True, early_stopping_patience=5) pred, delta = scg.predict(ctrl_key='ctrl', stim_key='stim', celltype_to_predict='CD4 T cells') pred.obs['label'] = 'pred' eval_adata = data[data.obs['cell_type'] == 'CD4 T cells'].copy().concatenate(pred) r2_value = scg.plot_reg_mean_plot(eval_adata, condition_key='label', axis_keys={"x": "pred", "y": "stim"}, labels={"x": "predicted", "y": "ground truth"}, save=False, show=True) ``` -------------------------------- ### Verify Guide Assignment Match Source: https://pertpy.readthedocs.io/en/stable/tutorials/notebooks/guide_rna_assignment Compares the assigned guide IDs with the actual guide IDs to check for discrepancies. This snippet helps verify the accuracy of the guide assignment process by counting mismatches. ```python sum(gdo.obs["assigned_guide"] != gdo.obs["guide_ID"]) ``` -------------------------------- ### Python Setup Imports Source: https://pertpy.readthedocs.io/en/stable/tutorials/notebooks/guide_rna_assignment Imports essential Python libraries for data analysis and scientific computing, including JAX, NumPy, Pandas, Pertpy, Scanpy, and SciPy, setting up the environment for perturbation analysis. ```python import jax.numpy as jnp import numpy as np import pandas as pd import pertpy as pt import scanpy as sc import scipy from jax import random ``` -------------------------------- ### Plot Guide Assignment Heatmap Source: https://pertpy.readthedocs.io/en/stable/tutorials/notebooks/guide_rna_assignment Visualizes the guide assignment results using a heatmap. This plot helps in understanding the distribution and relationships between assigned guides and actual guides, ordered by a specified plot order. ```python ga.plot_heatmap(gdo, order_by="plot_order") ``` -------------------------------- ### Install pertpy with pip Source: https://pertpy.readthedocs.io/en/stable/installation Installs the latest stable release of pertpy using pip, the standard Python package installer. This is the recommended method for most users. ```Shell pip install pertpy ``` -------------------------------- ### Tasccoda Data Loading and Preparation Example Source: https://pertpy.readthedocs.io/en/stable/_modules/pertpy/tools/_coda/_tasccoda Example usage demonstrating how to initialize Tasccoda, load sample-level data with specified aggregation levels, and prepare the data for analysis using a phylogenetic tree. ```python >>> import pertpy as pt >>> tasccoda = pt.tl.Tasccoda() >>> mdata = tasccoda.load( >>> adata, type="sample_level", >>> levels_agg=["Major_l1", "Major_l2", "Major_l3", "Major_l4", "Cluster"], >>> key_added="lineage", add_level_name=True >>> ) >>> mdata = tasccoda.prepare( >>> mdata, formula="Health", reference_cell_type="automatic", tree_key="lineage", pen_args={"phi": 0} >>> ) ``` -------------------------------- ### Import and Use pertpy API Source: https://pertpy.readthedocs.io/en/stable/api Demonstrates how to import the pertpy library and access its tools and modules. This is the standard way to begin using the pertpy functionalities. ```python import pertpy as pt pt.tl.cool_fancy_tool() ``` -------------------------------- ### Retrieve Dialogue Example Data Source: https://pertpy.readthedocs.io/en/stable/api/metadata/pertpy.metadata.CellLine Fetches an example AnnData object for dialogue analysis. This function is useful for testing and demonstrating pertpy functionalities. It returns an AnnData object with pre-loaded example data. ```python >>> import pertpy as pt >>> adata = pt.dt.dialogue_example() >>> adata.obs["cell_line_name"] = "MCF7" >>> pt_metadata = pt.md.CellLine() >>> adata_annotated = pt_metadata.annotate( ... adata=adata, reference_id="cell_line_name", query_id="cell_line_name", copy=True ... ) >>> pt_metadata.annotate_bulk_rna(adata_annotated) ``` -------------------------------- ### GuideAssignment Class Methods Source: https://pertpy.readthedocs.io/en/stable/_sources/api/preprocessing/pertpy.preprocessing.GuideAssignment This entry documents the methods available within the pertpy.preprocessing.GuideAssignment class. It covers methods for assigning guides using different strategies and for visualization. ```APIDOC pertpy.preprocessing.GuideAssignment This class provides functionalities for assigning guides to cells or data points, often in the context of biological experiments like spatial transcriptomics. Methods: assign_by_threshold Assigns guides based on a specified threshold. Parameters: (Details not provided in source text) Returns: (Details not provided in source text) assign_mixture_model Assigns guides using a mixture model approach. Parameters: (Details not provided in source text) Returns: (Details not provided in source text) assign_to_max_guide Assigns each data point to the guide with the maximum score. Parameters: (Details not provided in source text) Returns: (Details not provided in source text) assign_to_max_guide_anndata Assigns guides to an AnnData object based on maximum scores. Parameters: (Details not provided in source text) Returns: (Details not provided in source text) assign_to_max_guide_numpy Assigns guides to NumPy arrays based on maximum scores. Parameters: (Details not provided in source text) Returns: (Details not provided in source text) assign_to_max_guide_sparse Assigns guides to sparse matrices based on maximum scores. Parameters: (Details not provided in source text) Returns: (Details not provided in source text) plot_heatmap Generates a heatmap visualization for guide assignments. Parameters: (Details not provided in source text) Returns: (Details not provided in source text) Related Methods: All methods listed above are part of the GuideAssignment class and are related to guide assignment and visualization. ``` -------------------------------- ### Install pertpy with Milo dependencies Source: https://pertpy.readthedocs.io/en/stable/installation Installs pertpy with dependencies required for the Milo functionality. This can be done either by including the 'de' extra for the 'pydeseq2' solver or by installing 'edger', 'statmod', and 'rpy2' for the 'edger' solver. ```Shell pip install 'pertpy[de]' ``` ```R BiocManager::install("edgeR") ``` ```R BiocManager::install("statmod") ``` ```Shell pip install rpy2 ``` -------------------------------- ### DistanceTest.test_precomputed Example Source: https://pertpy.readthedocs.io/en/stable/api/tools/pertpy.tools.DistanceTest Example usage of the test_precomputed method to perform a permutation test on precomputed distances. ```python import pertpy as pt adata = pt.dt.distance_example() distance_test = pt.tl.DistanceTest("edistance", n_perms=1000) test_results = distance_test.test_precomputed(adata, groupby="perturbation", contrast="control") ``` -------------------------------- ### sccoda Workflow Example Source: https://pertpy.readthedocs.io/en/stable/api/tools/pertpy.tools.Sccoda Demonstrates a typical workflow using the sccoda module, including loading data, preparing it for analysis, running the NUTS sampler, and plotting results. ```python >>> import pertpy as pt >>> haber_cells = pt.dt.haber_2017_regions() >>> sccoda = pt.tl.Sccoda() >>> mdata = sccoda.load(haber_cells, type="cell_level", generate_sample_level=True, cell_type_identifier="cell_label", sample_identifier="batch", covariate_obs=["condition"]) >>> mdata = sccoda.prepare(mdata, formula="condition", reference_cell_type="Endocrine") >>> sccoda.run_nuts(mdata, num_warmup=100, num_samples=1000, rng_key=42) >>> sccoda.plot_rel_abundance_dispersion_plot(mdata) ``` -------------------------------- ### Install pertpy with Differential Gene Expression (DGE) dependencies Source: https://pertpy.readthedocs.io/en/stable/installation Installs pertpy along with the necessary dependencies for its Differential Gene Expression (DGE) interface. This includes 'edger' and 'rpy2', which may require separate installation steps for R packages. ```Shell pip install pertpy[de] ``` ```R BiocManager::install("edgeR") ``` ```Shell pip install rpy2 ``` -------------------------------- ### DistanceTest.test_xy Example Source: https://pertpy.readthedocs.io/en/stable/api/tools/pertpy.tools.DistanceTest Example usage of the test_xy method to perform a permutation test on raw data points. ```python import pertpy as pt adata = pt.dt.distance_example() distance_test = pt.tl.DistanceTest("edistance", n_perms=1000) test_results = distance_test.test_xy(adata, groupby="perturbation", contrast="control") ``` -------------------------------- ### Milo: Load and Prepare Data Source: https://pertpy.readthedocs.io/en/stable/api/tools/pertpy.tools.Milo Demonstrates loading data into the Milo object and performing initial neighborhood analysis steps like computing neighbors and making neighborhoods. ```python >>> import pertpy as pt >>> import scanpy as sc >>> adata = pt.dt.bhattacherjee() >>> milo = pt.tl.Milo() >>> mdata = milo.load(adata) >>> sc.pp.neighbors(mdata["rna"]) >>> milo.make_nhoods(mdata["rna"]) ``` -------------------------------- ### Assign to Most Frequent Guide Source: https://pertpy.readthedocs.io/en/stable/tutorials/notebooks/guide_rna_assignment Assigns guide RNAs to cells based on the highest detection frequency. This method is useful for identifying the most prevalent guide assignment in a dataset. It requires an AnnData object and specifies a layer for counts and an assignment threshold. ```python ga = pt.pp.GuideAssignment() ga.assign_to_max_guide(gdo, assignment_threshold=5, layer="counts") ``` -------------------------------- ### Pertpy Milo Example Workflow Source: https://pertpy.readthedocs.io/en/stable/api/tools/pertpy.tools.Milo Demonstrates a typical workflow using the Pertpy Milo module, including loading data, calculating neighbors, making and counting neighborhoods, differential abundance testing, annotation, and plotting. ```python import pertpy as pt import scanpy as sc adata = pt.dt.bhattacherjee() milo = pt.tl.Milo() mdata = milo.load(adata) sc.pp.neighbors(mdata["rna"]) milo.make_nhoods(mdata["rna"]) mdata = milo.count_nhoods(mdata, sample_col="orig.ident") milo.da_nhoods(mdata, design="~label") milo.annotate_nhoods(mdata, anno_col="cell_type") milo.plot_da_beeswarm(mdata) ```