### Install scCODA from source Source: https://github.com/theislab/sccoda/blob/master/docs/source/installation.rst Clones the repository from GitHub and installs the package along with all required dependencies from the requirements file. ```bash git clone https://github.com/theislab/scCODA cd scCODA pip install -r requirements.txt ``` -------------------------------- ### Setup and Import scCODA Environment Source: https://github.com/theislab/sccoda/blob/master/tutorials/Modeling_options_and_result_analysis.ipynb Initializes the necessary libraries for scCODA analysis, including pandas for data manipulation, matplotlib for plotting, and sccoda modules for composition analysis. ```python import warnings warnings.filterwarnings("ignore") import pandas as pd import matplotlib.pyplot as plt import arviz as az from sccoda.util import comp_ana as mod from sccoda.util import cell_composition_data as dat from sccoda.util import data_visualization as viz import sccoda.datasets as scd ``` -------------------------------- ### Import scCODA in Python Source: https://github.com/theislab/sccoda/blob/master/docs/source/installation.rst Verifies the installation by importing the library into a Python session. ```python import sccoda ``` -------------------------------- ### Run Alternative Differential Abundance Models Source: https://context7.com/theislab/sccoda/llms.txt Examples for initializing and fitting alternative models including HaberModel (Poisson regression), CLRModel (Centered log-ratio), and ALRModel_ttest (Additive log-ratio with t-test). ```python from sccoda.model.other_models import HaberModel, CLRModel, ALRModel_ttest # HaberModel haber = HaberModel(data=data_subset, covariate_column="x_0") haber.fit_model() # CLRModel clr = CLRModel(data=data_subset, covariate_column="x_0") clr.fit_model() # ALRModel_ttest alr = ALRModel_ttest(data=data_subset, covariate_column="x_0") alr.fit_model(reference_cell_type=4) ``` -------------------------------- ### ALDEx2 Model Integration Source: https://github.com/theislab/sccoda/blob/master/tutorials/using_other_compositional_methods.ipynb Demonstrates how to configure and run the ALDEx2 model, which requires an external R installation. ```APIDOC ## POST /models/aldex2 ### Description Fits an ALDEx2 model to the dataset. This requires valid paths to an R installation and the ALDEx2 package. ### Method POST ### Endpoint /models/aldex2 ### Parameters #### Request Body - **data** (object) - Required - The dataset containing cell counts. - **covariate_column** (string) - Required - The column name in the data. - **r_home** (string) - Required - Path to the R framework home directory. - **r_path** (string) - Required - Path to the R executable. ### Request Example { "data": "data_salm", "covariate_column": "Condition", "r_home": "/Library/Frameworks/R.framework/Resources", "r_path": "/Library/Frameworks/R.framework/Resources/bin/R" } ### Response #### Success Response (200) - **result** (object) - Contains p-values and BH-adjusted p-values for the tests. #### Response Example { "1": {"we.ep": 0.385566, "we.eBH": 0.520241, "wi.ep": 0.519792, "wi.eBH": 0.670258} } ``` -------------------------------- ### Initialize scCODA Environment and Dependencies Source: https://github.com/theislab/sccoda/blob/master/docs/source/_templates/using_other_compositional_methods.ipynb Imports necessary libraries for data manipulation and scCODA model wrappers. This setup is required before performing compositional analysis on single-cell data. ```python import warnings warnings.filterwarnings("ignore") import pandas as pd import patsy as pt import numpy as np from sccoda.model import other_models as om from sccoda.util import cell_composition_data as dat from sccoda.util import data_visualization as viz ``` -------------------------------- ### Install scCODA via pip Source: https://github.com/theislab/sccoda/blob/master/docs/source/installation.rst Installs the scCODA package and its dependencies using the Python package manager. This is the recommended method for most users. ```bash pip install sccoda ``` -------------------------------- ### GET /Inference/Algorithms Source: https://github.com/theislab/sccoda/blob/master/docs/source/Modeling_options_and_result_analysis.ipynb Retrieves information about available MCMC sampling algorithms for parameter inference. ```APIDOC ## GET /Inference/Algorithms ### Description Lists the supported MCMC sampling methods for scCODA models. ### Method GET ### Endpoint /Inference/Algorithms ### Response #### Success Response (200) - **algorithms** (array) - List of available methods: sample_hmc, sample_hmc_da, sample_nuts. #### Response Example { "algorithms": ["sample_hmc", "sample_hmc_da", "sample_nuts"] } ``` -------------------------------- ### Setup and Data Loading for scCODA Analysis Source: https://github.com/theislab/sccoda/blob/master/docs/source/_templates/Modeling_options_and_result_analysis.ipynb This Python code sets up the environment by importing necessary libraries and then loads and preprocesses cell count data into an AnnData object. It filters data for specific conditions (Control and Salm) and prints dataset information. Finally, it visualizes the data using boxplots. ```python # Setup import warnings warnings.filterwarnings("ignore") import pandas as pd import matplotlib.pyplot as plt import arviz as az from sccoda.util import comp_ana as mod from sccoda.util import cell_composition_data as dat from sccoda.util import data_visualization as viz ``` ```python # Load data cell_counts = pd.read_csv("../data/haber_counts.csv") # Convert data to anndata object data_all = dat.from_pandas(cell_counts, covariate_columns=["Mouse"]) # Extract condition from mouse name and add it as an extra column to the covariates data_all.obs["Condition"] = data_all.obs["Mouse"].str.replace(r"_[0-9]", "") print(f"Entire dataset: {data_all}") # Select control and salmonella data data_salm = data_all[data_all.obs["Condition"].isin(["Control", "Salm"])].copy() print(f"Salmonella dataset: {data_salm}") viz.boxplots(data_all, feature_name="Condition") plt.show() ``` -------------------------------- ### Compositional Data Visualization Source: https://github.com/theislab/sccoda/blob/master/docs/source/Data_import_and_visualization.ipynb Provides examples of visualizing compositional data using scCODA's `viz.stacked_barplot` and `viz.boxplots` functions. ```APIDOC ## Compositional Data Visualization ### Description scCODA offers several functions to visualize compositional data properties before analysis. This section details the usage of `viz.stacked_barplot` and `viz.boxplots`. ### Stacked Barplot The `viz.stacked_barplot` function creates stacked barplots, which are a common representation for cell count data. It can generate plots per covariate level or per sample. ```python import scdواع.viz as viz import matplotlib.pyplot as plt # Assuming data_mouse is loaded and available # Stacked barplot for each sample viz.stacked_barplot(data_mouse, feature_name="samples") plt.show() # Stacked barplot for the levels of "Condition" viz.stacked_barplot(data_mouse, feature_name="Condition") plt.show() ``` ### Grouped Boxplots The `viz.boxplots` function provides a visualization that includes data variance, addressing limitations of stacked barplots. It allows for grouped boxplots by cell type and condition, with options for log-scale, faceting, and adding individual data points. ```python # Grouped boxplots. No facets, relative abundance, no dots. viz.boxplots( data_mouse, feature_name="Condition", plot_facets=False, y_scale="relative", add_dots=False, ) plt.show() # Grouped boxplots. Facets, log scale, added dots and custom color palette. viz.boxplots( data_mouse, feature_name="Condition", plot_facets=True, y_scale="log", add_dots=True, cmap="Reds", ) plt.show() ``` ``` -------------------------------- ### Visualize Compositional Data Source: https://github.com/theislab/sccoda/blob/master/docs/source/Data_import_and_visualization.ipynb Provides examples for visualizing cell count data using stacked barplots and grouped boxplots to analyze variance and abundance. ```python from sccoda.util import viz import matplotlib.pyplot as plt # Stacked barplots viz.stacked_barplot(data_mouse, feature_name="samples") viz.stacked_barplot(data_mouse, feature_name="Condition") # Grouped boxplots viz.boxplots(data_mouse, feature_name="Condition", plot_facets=False, y_scale="relative", add_dots=False) viz.boxplots(data_mouse, feature_name="Condition", plot_facets=True, y_scale="log", add_dots=True, cmap="Reds") ``` -------------------------------- ### Import scCODA Modules Source: https://github.com/theislab/sccoda/blob/master/docs/source/api.rst Imports essential modules from the scCODA package for data handling, analysis, and visualization. This is the typical starting point for using the library. ```python import sccoda dat = sccoda.util.cell_composition_data ana = sccoda.util.compositional_analysis viz = sccoda.util.data_visualization ``` -------------------------------- ### Initialize Compositional Analysis Model (Python) Source: https://github.com/theislab/sccoda/blob/master/docs/source/api.rst Sets up the scCODA model by creating an instance of CompositionalAnalysis. This step involves specifying the statistical formula using patsy syntax and defining the reference cell type. ```python ana.CompositionalAnalysis(data, formula, reference_cell_type) ``` -------------------------------- ### Fit ALDEx2 Model with scCODA Source: https://github.com/theislab/sccoda/blob/master/docs/source/_templates/using_other_compositional_methods.ipynb Configures R environment paths and fits an ALDEx2 model for differential abundance analysis. Requires a valid R installation with the ALDEx2 package installed. ```python r_home = "/Library/Frameworks/R.framework/Resources" r_path = "/Library/Frameworks/R.framework/Resources/bin/R" aldex2_model = om.ALDEx2Model(data_salm, covariate_column="Condition") aldex2_model.fit_model(r_home=r_home, r_path=r_path) print(aldex2_model.result) ``` -------------------------------- ### Data Loading and Preparation Source: https://github.com/theislab/sccoda/blob/master/docs/source/Data_import_and_visualization.ipynb Demonstrates how to read AnnData objects, create copies, add sample information, concatenate them, and prepare covariate dataframes. ```APIDOC ## Data Loading and Preparation ### Description This section shows how to load AnnData objects, create multiple copies with distinct sample identifiers, concatenate them into a single object, and prepare a covariate DataFrame. ### Code Examples #### Reading and Inspecting Data ```python import anndata as ad import pandas as pd # Read data from H5AD file adata = ad.read_h5ad("../data/10x_pbmc68k_reduced.h5ad") print(adata) ``` #### Creating and Concatenating Sample Copies ```python # Make three copies of the AnnData object adata_1 = adata.copy() adata_1.obs["sample"] = 1 adata_2 = adata.copy() adata_2.obs["sample"] = 2 adata_3 = adata.copy() adata_3.obs["sample"] = 3 # Join them together again adata_all = ad.concat([adata_1, adata_2, adata_3]) print(adata_all) ``` #### Creating a Covariate DataFrame ```python # Make covariate DataFrame cov_df = pd.DataFrame({"Cond": ["A", "B", "A"]}, index=[1, 2, 3]) print(cov_df) ``` ``` -------------------------------- ### ALDEx2 Model Source: https://github.com/theislab/sccoda/blob/master/docs/source/using_other_compositional_methods.ipynb Details on using the ALDEx2 model with scCODA, including R installation requirements and fitting the model. ```APIDOC ## ALDEx2 Model The ALDEx2 model ([Fernandes et al., 2014](https://microbiomejournal.biomedcentral.com/articles/10.1186/2049-2618-2-15)) requires an R installation with the *ALDEx2* package available. The paths `r_home` and `r_path` must point to the installation folder and the R executable of your R version. The result columns show the p-values of various tests (see the [documentation](https://bioconductor.org/packages/release/bioc/vignettes/ALDEx2/inst/doc/ALDEx2_vignette.pdf) of ALDEx2 for details). ### Configuration ```python r_home = "/Library/Frameworks/R.framework/Resources" r_path = "/Library/Frameworks/R.framework/Resources/bin/R" ``` ### Method ```python aldex2_model = om.ALDEx2Model(data_salm, covariate_column="Condition") aldex2_model.fit_model(r_home=r_home, r_path=r_path) print(aldex2_model.result) ``` ### Output Example ``` R[write to console]: operating in serial mode R[write to console]: computing center with all features we.ep we.eBH wi.ep wi.eBH 1 0.385566 0.520241 0.519792 0.670258 2 0.055019 0.190518 0.133333 0.419444 3 0.554758 0.649357 0.742708 0.839306 4 0.549451 0.649280 0.890104 0.910625 5 0.045055 0.170609 0.146875 0.427778 6 0.211257 0.380195 0.436458 0.651677 7 0.165477 0.311701 0.277604 0.509593 8 0.644732 0.715048 0.594792 0.750084 ``` ``` -------------------------------- ### Execute Complete Compositional Analysis Workflow Source: https://context7.com/theislab/sccoda/llms.txt A full pipeline demonstrating data loading, preprocessing, visualization, model fitting using CompositionalAnalysis, and result interpretation including FDR adjustment and saving. ```python from sccoda.util import comp_ana as mod from sccoda.util import cell_composition_data as dat import sccoda.datasets as scd cell_counts = scd.haber() data_all = dat.from_pandas(cell_counts, covariate_columns=["Mouse"]) model = mod.CompositionalAnalysis( data=data_salm, formula="Condition", reference_cell_type="Goblet" ) results = model.sample_hmc(num_results=20000, num_burnin=5000) results.summary() ``` -------------------------------- ### HMC Sampling and Summary Source: https://github.com/theislab/sccoda/blob/master/docs/source/_templates/using_other_compositional_methods.ipynb Demonstrates how to run Hierarchical Markov Chain (HMC) sampling and display an extended summary of the results. ```APIDOC ## POST /sample_hmc ### Description Runs Hierarchical Markov Chain (HMC) sampling to generate posterior distributions for model parameters. ### Method POST ### Endpoint /sample_hmc ### Parameters #### Request Body - **mod** (object) - Required - The model object to sample from. ### Request Example ```json { "mod": "model_object" } ``` ### Response #### Success Response (200) - **result_simple** (object) - An object containing the results of the HMC sampling, with a method `summary_extended()` to display detailed statistics. #### Response Example ``` MCMC sampling finished. (33.735 sec) Acceptance rate: 65.9% Compositional Analysis summary (extended): Data: 6 samples, 8 cell types Reference index: 4 Formula: Condition MCMC Sampling: Sampled 20000 chain states (5000 burnin samples) in 33.735 sec. Acceptance rate: 65.9% Intercepts: Final Parameter HDI 3% HDI 97% SD Cell Type Endocrine 1.037 0.350 1.761 0.384 Enterocyte 2.312 1.732 2.888 0.313 Enterocyte.Progenitor 2.481 1.840 3.067 0.327 Goblet 1.612 0.933 2.220 0.349 Stem 2.743 2.208 3.356 0.308 TA 2.150 1.473 2.766 0.347 TA.Early 2.843 2.242 3.432 0.318 Tuft 0.406 -0.402 1.154 0.424 Expected Sample Cell Type Endocrine 32.412176 Enterocyte 115.993501 Enterocyte.Progenitor 137.350241 Goblet 57.600668 Stem 178.490284 TA 98.645653 TA.Early 197.262271 Tuft 17.245206 Effects: Final Parameter HDI 3% HDI 97% Covariate Cell Type Condition[T.Salm] Endocrine 0.540079 -0.338 1.387 Enterocyte 1.610449 1.117 2.175 Enterocyte.Progenitor 0.326290 -0.263 0.915 Goblet 0.580075 -0.130 1.281 Stem NaN 0.000 0.000 TA -0.044037 -0.726 0.612 TA.Early 0.236034 -0.308 0.762 Tuft 0.145120 -0.932 1.168 SD Inclusion probability Covariate Cell Type Condition[T.Salm] Endocrine 0.455 0.999733 Enterocyte 0.279 1.000000 Enterocyte.Progenitor 0.308 0.998867 Goblet 0.377 0.999667 Stem 0.000 0.000000 TA 0.358 0.997533 TA.Early 0.282 0.998067 Tuft 0.563 0.999067 Expected Sample log2-fold change Covariate Cell Type Condition[T.Salm] Endocrine 35.906737 0.147719 Enterocyte 374.763560 1.691937 Enterocyte.Progenitor 122.871105 -0.160714 Goblet 66.414879 0.205421 Stem NaN NaN TA 60.935108 -0.694982 TA.Early 161.237744 -0.290926 Tuft 12.870867 -0.422086 ``` ``` -------------------------------- ### GET /util/helper_functions/sample_size_estimate Source: https://github.com/theislab/sccoda/blob/master/docs/source/sccoda.util.helper_functions.sample_size_estimate.rst Calculates the necessary sample size for a given experimental design using scCODA helper functions. ```APIDOC ## GET /util/helper_functions/sample_size_estimate ### Description This function estimates the required sample size for scCODA analysis based on provided parameters to ensure sufficient statistical power. ### Method GET ### Endpoint /util/helper_functions/sample_size_estimate ### Parameters #### Query Parameters - **effect_size** (float) - Required - The expected effect size to be detected. - **power** (float) - Required - The desired statistical power (e.g., 0.8). - **alpha** (float) - Required - The significance level (e.g., 0.05). ### Request Example GET /util/helper_functions/sample_size_estimate?effect_size=0.5&power=0.8&alpha=0.05 ### Response #### Success Response (200) - **sample_size** (integer) - The estimated number of samples required. #### Response Example { "sample_size": 42 } ``` -------------------------------- ### GET /util/cell_composition_data/from_scanpy Source: https://github.com/theislab/sccoda/blob/master/docs/source/sccoda.util.cell_composition_data.from_scanpy.rst This function extracts cell composition data from a Scanpy AnnData object to prepare it for scCODA analysis. ```APIDOC ## from_scanpy ### Description Converts a Scanpy AnnData object into a compositional data structure suitable for scCODA models. ### Method Python Function Call ### Endpoint sccoda.util.cell_composition_data.from_scanpy ### Parameters #### Arguments - **data** (AnnData) - Required - The Scanpy AnnData object containing cell counts. - **formula** (str) - Required - The formula describing the experimental design. - **reference_cell_type** (str) - Optional - The cell type to be used as a reference in the model. ### Request Example ```python import scanpy as sc from sccoda.util.cell_composition_data import from_scanpy adata = sc.read_h5ad('data.h5ad') data = from_scanpy(adata, formula='condition', reference_cell_type='B cells') ``` ### Response #### Success Response - **data** (CompositionalData) - A structured object containing counts and covariates ready for the scCODA model. #### Response Example { "status": "success", "data_type": "CompositionalData" } ``` -------------------------------- ### Initialize scCODA Environment Source: https://github.com/theislab/sccoda/blob/master/docs/source/_templates/Data_import_and_visualization.ipynb Imports necessary libraries including pandas, matplotlib, and scCODA utilities to prepare the environment for compositional data analysis. ```python import pandas as pd import matplotlib.pyplot as plt import anndata as ad import warnings from sccoda.util import cell_composition_data as dat from sccoda.util import data_visualization as viz warnings.filterwarnings("ignore") ``` -------------------------------- ### GET /model/scCODAModel/get_y_hat Source: https://github.com/theislab/sccoda/blob/master/docs/source/sccoda.model.scCODA_model.scCODAModel.get_y_hat.rst Retrieves the predicted cell count distributions (y_hat) based on the fitted scCODA model parameters. ```APIDOC ## GET /model/scCODAModel/get_y_hat ### Description Calculates and returns the predicted cell counts (y_hat) for the given model state. This method is used to evaluate how well the model fits the observed data or to generate predictions for new covariate settings. ### Method GET ### Endpoint /model/scCODAModel/get_y_hat ### Parameters #### Path Parameters - None #### Query Parameters - **params** (dict) - Optional - A dictionary of model parameters to use for the prediction. If not provided, the current fitted parameters are used. ### Request Example { "params": { "beta": [0.1, -0.2], "intercept": 0.5 } } ### Response #### Success Response (200) - **y_hat** (array) - The predicted cell count matrix. #### Response Example { "y_hat": [[12.5, 8.2], [10.1, 9.4]] } ``` -------------------------------- ### GET /model/SimpleModel/get_chains_after_burnin Source: https://github.com/theislab/sccoda/blob/master/docs/source/sccoda.model.other_models.SimpleModel.get_chains_after_burnin.rst Retrieves the MCMC chains for the model after the initial burn-in phase to ensure posterior samples are used for inference. ```APIDOC ## GET /model/SimpleModel/get_chains_after_burnin ### Description Retrieves the MCMC chains after the burn-in period. This method is essential for accessing the valid posterior samples generated by the scCODA model. ### Method GET ### Endpoint /model/SimpleModel/get_chains_after_burnin ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example {} ### Response #### Success Response (200) - **chains** (object) - The MCMC chains collected after the burn-in period. #### Response Example { "chains": { "beta": [[...]], "intercept": [...] } } ``` -------------------------------- ### Comparison Models for Compositional Analysis (Python) Source: https://github.com/theislab/sccoda/blob/master/docs/source/api.rst Implementations of various other compositional and non-compositional models for comparative analysis. This includes methods from microbiome analysis and standard statistical tests. ```python sccoda.model.other_models.SimpleModel(...) sccoda.model.other_models.scdney_model(...) sccoda.model.other_models.HaberModel(...) sccoda.model.other_models.CLRModel(...) sccoda.model.other_models.TTest(...) sccoda.model.other_models.CLRModel_ttest(...) sccoda.model.other_models.ALDEx2Model(...) sccoda.model.other_models.ALRModel_ttest(...) sccoda.model.other_models.ALRModel_wilcoxon(...) sccoda.model.other_models.AncomModel(...) sccoda.model.other_models.DirichRegModel(...) sccoda.model.other_models.BetaBinomialModel(...) sccoda.model.other_models.ANCOMBCModel(...) ``` -------------------------------- ### Compositional Analysis Modeling Source: https://github.com/theislab/sccoda/blob/master/docs/source/_templates/Modeling_options_and_result_analysis.ipynb This snippet demonstrates how to initialize and run a compositional analysis model for multiple diseases simultaneously. It includes setting up the model with a specified formula and reference cell type, sampling the model using Markov Chain Monte Carlo (HMC), and then generating a summary of the results. ```APIDOC ## POST /api/sccoda/model_all ### Description Initializes and runs a compositional analysis model for multiple diseases at once, samples the model using HMC, and summarizes the results. ### Method POST ### Endpoint /api/sccoda/model_all ### Parameters #### Request Body - **data_all** (object) - Required - The dataset containing all samples and cell type information. - **formula** (string) - Required - The formula string defining the model, e.g., "Condition". - **reference_cell_type** (string) - Required - The name of the reference cell type for comparison, e.g., "Endocrine". ### Request Example ```json { "data_all": "[Your Data Here]", "formula": "Condition", "reference_cell_type": "Endocrine" } ``` ### Response #### Success Response (200) - **summary** (object) - Contains the summary of the compositional analysis, including intercepts, effects, and log2-fold changes. #### Response Example ```json { "summary": { "intercepts": { "Endocrine": 0.984, "Enterocyte": 1.914, "Enterocyte.Progenitor": 2.340, "Goblet": 1.464, "Stem": 2.410, "TA": 1.874, "TA.Early": 2.528, "Tuft": 0.621 }, "effects": { "Condition[T.H.poly.Day10]": { "Endocrine": 0.000000, "Enterocyte": 0.000000, "Enterocyte.Progenitor": 0.000000, "Goblet": 0.000000, "Stem": 0.000000, "TA": 0.000000, "TA.Early": 0.000000, "Tuft": 0.000000 }, "Condition[T.H.poly.Day3]": { "Endocrine": 0.000000, "Enterocyte": 0.000000, "Enterocyte.Progenitor": 0.000000, "Goblet": 0.000000, "Stem": 0.000000, "TA": 0.000000, "TA.Early": 0.000000, "Tuft": 0.000000 }, "Condition[T.Salm]": { "Endocrine": 0.000000, "Enterocyte": 1.529663, "Enterocyte.Progenitor": 0.000000, "Goblet": 0.000000, "Stem": 0.000000, "TA": 0.000000, "TA.Early": 0.000000, "Tuft": 0.000000 } }, "log2_fold_change": { "Condition[T.H.poly.Day10]": { "Endocrine": 0.000000, "Enterocyte": 0.000000, "Enterocyte.Progenitor": 0.000000, "Goblet": 0.000000, "Stem": 0.000000, "TA": 0.000000, "TA.Early": 0.000000, "Tuft": 0.000000 } } } } ``` ``` -------------------------------- ### ALDEx2 Model Integration Source: https://github.com/theislab/sccoda/blob/master/docs/source/_templates/using_other_compositional_methods.ipynb Details on how to use the ALDEx2 model with scCODA, including R environment setup, model fitting, and accessing results. ```APIDOC ## ALDEx2 Model The ALDEx2 model ([Fernandes et al., 2014](https://microbiomejournal.biomedcentral.com/articles/10.1186/2049-2618-2-15)) requires an R installation with the *ALDEx2* package available. The paths `r_home` and `r_path` must point to the installation folder and the R executable of your R version. The result columns show the p-values of various tests (see the [documentation](https://bioconductor.org/packages/release/bioc/vignettes/ALDEx2/inst/doc/ALDEx2_vignette.pdf) of ALDEx2 for details). ### Setup ```python r_home = "/Library/Frameworks/R.framework/Resources" r_path = "/Library/Frameworks/R.framework/Resources/bin/R" ``` ### Method ```python aldex2_model = om.ALDEx2Model(data_salm, covariate_column="Condition") aldex2_model.fit_model(r_home=r_home, r_path=r_path) print(aldex2_model.result) ``` ### Output Example ``` R[write to console]: operating in serial mode R[write to console]: computing center with all features we.ep we.eBH wi.ep wi.eBH 1 0.398795 0.520379 0.500000 0.649256 2 0.050981 0.193256 0.133333 0.393234 3 0.551999 0.642558 0.716667 0.800213 4 0.508581 0.611975 0.852083 0.891572 5 0.049631 0.173775 0.138542 0.395179 6 0.206381 0.356970 0.421875 0.613566 7 0.146195 0.279378 0.271354 0.474425 8 0.611966 0.684175 0.601562 0.735804 ``` ``` -------------------------------- ### CLRModel Class Overview Source: https://github.com/theislab/sccoda/blob/master/docs/source/sccoda.model.other_models.CLRModel.rst Overview of the CLRModel class and its available methods. ```APIDOC ## CLRModel Class ### Description Represents a CLR (Centered Log-Ratio) model within the scCODA framework. This class provides methods for fitting the model to data and evaluating its performance. ### Methods - **`eval_model()`**: Evaluates the performance of the fitted CLR model. - **`fit_model()`**: Fits the CLR model to the provided data. ``` -------------------------------- ### GET /result/summary_extended Source: https://github.com/theislab/sccoda/blob/master/docs/source/_templates/Modeling_options_and_result_analysis.ipynb Retrieves an extended summary of the scCODA model results, including MCMC sampling diagnostics and posterior density statistics for intercepts and effects. ```APIDOC ## GET /result/summary_extended ### Description Provides a comprehensive summary of the inferred posterior, including MCMC sampling performance (chain length, burn-in, acceptance rate) and statistical details for intercepts and effects such as standard deviation, high density interval (HDI) endpoints, and spike-and-slab inclusion probabilities. ### Method GET ### Endpoint /result/summary_extended ### Parameters #### Query Parameters - **hdi_prob** (float) - Optional - The probability mass for the high density interval (default is usually 0.95). ### Request Example ```python result.summary_extended(hdi_prob=0.9) ``` ### Response #### Success Response (200) - **intercepts** (DataFrame) - Summary statistics for model intercepts. - **effects** (DataFrame) - Summary statistics for model effects, including inclusion probabilities. - **mcmc_metrics** (Object) - Metadata regarding sampling duration, acceptance rate, and chain states. #### Response Example { "MCMC Sampling": "Sampled 20000 chain states (5000 burnin samples) in 47.011 sec. Acceptance rate: 74.6%", "Intercepts": "[DataFrame containing Final Parameter, HDI 5%, HDI 95%, SD]", "Effects": "[DataFrame containing Final Parameter, HDI 5%, HDI 95%, SD, Inclusion probability]" } ``` -------------------------------- ### Model All Diseases and Summarize Results Source: https://github.com/theislab/sccoda/blob/master/docs/source/Modeling_options_and_result_analysis.ipynb This snippet demonstrates how to initialize a compositional analysis model for all diseases at once, sample the model using HMC, and then display a summary of the results. ```APIDOC ## POST /model/all ### Description Initializes a compositional analysis model for all diseases simultaneously, samples the model using HMC, and displays a summary of the results. ### Method POST ### Endpoint /model/all ### Parameters #### Request Body - **data_all** (object) - Required - The dataset to be used for analysis. - **formula** (string) - Required - The formula string defining the model. - **reference_cell_type** (string) - Required - The reference cell type for the analysis. ### Request Example ```json { "data_all": "your_data_here", "formula": "Condition", "reference_cell_type": "Endocrine" } ``` ### Response #### Success Response (200) - **summary** (object) - A summary of the compositional analysis results, including intercepts and effects. #### Response Example ```json { "summary": { "intercepts": { "Endocrine": {"Final Parameter": 0.986, "Expected Sample": 46.634633}, "Enterocyte": {"Final Parameter": 1.905, "Expected Sample": 116.902874} }, "effects": { "Condition[T.Salm]": { "Enterocyte": {"Final Parameter": 1.554932, "Expected Sample": 116.902874} } } } } ``` ``` -------------------------------- ### CompositionalAnalysis Initialization Source: https://context7.com/theislab/sccoda/llms.txt Initializes the Bayesian compositional model for scCODA analysis. ```APIDOC ## CompositionalAnalysis ### Description The main entry point for scCODA analysis. Initializes the Bayesian compositional model with cell count data, covariate formula, and reference cell type specification. ### Method `mod.CompositionalAnalysis` ### Parameters - **data** (anndata.AnnData) - The input data object containing cell counts and covariates. - **formula** (str) - An R-style formula string for covariates (e.g., "Condition", "Condition + Treatment + Condition:Treatment"). - **reference_cell_type** (str) - The name of the reference cell type. Can be a specific cell type name, "automatic", or a custom reference level for categorical variables (e.g., "C(Condition, Treatment('Control'))"). - **automatic_reference_absence_threshold** (float, optional) - Maximum fraction of zeros allowed for automatic reference selection. Defaults to 0.05. ### Request Example ```python from sccoda.util import comp_ana as mod from sccoda.util import cell_composition_data as dat import sccoda.datasets as scd # Load and prepare data cell_counts = scd.haber() data = dat.from_pandas(cell_counts, covariate_columns=["Mouse"]) data.obs["Condition"] = data.obs["Mouse"].str.replace(r"_[0-9]", "", regex=True) # Subset to control vs disease comparison data_subset = data[data.obs["Condition"].isin(["Control", "Salm"])] # Initialize model with explicit reference cell type model = mod.CompositionalAnalysis( data=data_subset, formula="Condition", reference_cell_type="Goblet" ) # Alternative: automatic reference selection based on dispersion model_auto = mod.CompositionalAnalysis( data=data_subset, formula="Condition", reference_cell_type="automatic", automatic_reference_absence_threshold=0.05 ) # Prints: "Automatic reference selection! Reference cell type set to " # Multiple covariates with interaction # model_multi = mod.CompositionalAnalysis( # data=data_all, # Assuming data_all is defined elsewhere # formula="Condition + Treatment + Condition:Treatment", # reference_cell_type="Goblet" # ) # Categorical covariate with custom reference level model_cat = mod.CompositionalAnalysis( data=data_subset, formula="C(Condition, Treatment('Control'))", reference_cell_type="Goblet" ) ``` ### Response Returns a `CompositionalAnalysis` object. #### Success Response (200) - **CompositionalAnalysis object** - An initialized model ready for sampling. ``` -------------------------------- ### Configure and Run scCODA Compositional Analysis Source: https://github.com/theislab/sccoda/blob/master/docs/source/_templates/Modeling_options_and_result_analysis.ipynb Initializes the CompositionalAnalysis model with a custom reference condition using the formula interface. It then performs MCMC sampling to estimate parameters and generates a summary of the results. ```python model_salm_switch_cond = mod.CompositionalAnalysis(data_salm, formula="C(Condition, Treatment('Salm'))", reference_cell_type="Goblet") switch_results = model_salm_switch_cond.sample_hmc() switch_results.summary() ``` -------------------------------- ### Analyze data using the SCDC model Source: https://github.com/theislab/sccoda/blob/master/docs/source/_templates/using_other_compositional_methods.ipynb This snippet demonstrates how to initialize and run the SCDC model using the scdney package. It requires specifying the R environment paths and the covariate column for the analysis. ```python scdc_model = om.scdney_model(data_salm, covariate_column="Condition") result, _ = scdc_model.analyze(r_home=r_home, r_path=r_path) print(result) ``` -------------------------------- ### Load and Concatenate AnnData Samples Source: https://github.com/theislab/sccoda/blob/master/docs/source/Data_import_and_visualization.ipynb Demonstrates how to load an AnnData object, create multiple copies with distinct sample identifiers, and concatenate them into a single object for analysis. ```python import scanpy as sc import anndata as ad adata = ad.read_h5ad("../data/10x_pbmc68k_reduced.h5ad") adata_1 = adata.copy() adata_1.obs["sample"] = 1 adata_2 = adata.copy() adata_2.obs["sample"] = 2 adata_3 = adata.copy() adata_3.obs["sample"] = 3 adata_all = ad.concat([adata_1, adata_2, adata_3]) ``` -------------------------------- ### Alternative Reference Cell Type Selection Strategy Source: https://github.com/theislab/sccoda/blob/master/docs/source/Modeling_options_and_result_analysis.ipynb Explains and provides an example of an alternative strategy for analyzing scCODA results when a specific reference cell type is unknown. This involves sequentially running scCODA with each cell type as a reference and using a majority vote to identify credible effects. ```APIDOC ## Using All Cell Types as Reference ### Description This procedure demonstrates an alternative approach to reference selection in scCODA. Instead of pre-selecting a reference cell type, this method sequentially uses each cell type as a reference and then identifies cell types with credible effects across multiple references using a majority vote. This is useful when the true reference cell type is unknown. ### Procedure 1. Run scCODA, setting `reference_cell_type="automatic"` to find an initial reference or manually select one. 2. For each cell type: a. Run scCODA again, setting the current cell type as the reference. b. Identify credible effects for this reference. 3. Aggregate the results: A cell type is considered to have a credible effect if it showed one in more than half of the runs (i.e., with more than half of the possible reference cell types). ### Example Below is an example illustrating this procedure on the Salmonella infection data. It shows that only 'Enterocytes' were found to be credible more than half of the time, indicating they are credibly changing for every reference cell type except themselves. Other cell types did not show credible changes with any reference. ```python # Placeholder for the actual code implementation of the majority vote procedure. # This would involve iterating through cell types, re-running scCODA, and aggregating results. print("Example code for majority vote procedure would go here.") ``` ### Result Interpretation - If a cell type is consistently found to have credible effects across various references, it suggests a robust biological finding. - If results vary significantly with the choice of reference, it may indicate complex interactions or limitations in the data. ``` -------------------------------- ### Initialize scCODA Environment Source: https://github.com/theislab/sccoda/blob/master/docs/source/_templates/getting_started.ipynb Configures the environment by suppressing warnings and importing necessary modules for data manipulation, statistical analysis, and visualization. ```python import warnings warnings.filterwarnings("ignore") import pandas as pd import pickle as pkl from sccoda.util import comp_ana as mod from sccoda.util import cell_composition_data as dat from sccoda.util import data_visualization as viz ``` -------------------------------- ### Get Extended Model Summary with Custom HDI Probability (Python) Source: https://github.com/theislab/sccoda/blob/master/docs/source/_templates/Modeling_options_and_result_analysis.ipynb This function retrieves an extended summary of the compositional analysis model, including detailed posterior information and MCMC sampling statistics. It allows customization of the Highest Density Interval (HDI) probability. The output is presented in a structured format, including intercept and effect summaries with various statistical measures. ```python salm_results.summary_extended(hdi_prob=0.9) ``` -------------------------------- ### ANCOMBCModel Class Methods Source: https://github.com/theislab/sccoda/blob/master/docs/source/sccoda.model.other_models.ANCOMBCModel.rst Overview of the methods available for the ANCOMBCModel class, including model fitting and evaluation. ```APIDOC ## ANCOMBCModel Methods ### Description The ANCOMBCModel class allows users to execute ANCOM-BC analysis. It provides methods to fit the model to data and evaluate the results. ### Methods - **fit_model**: Fits the ANCOM-BC model to the provided dataset. - **eval_model**: Evaluates the performance or results of the fitted model. ### Usage Example ```python from sccoda.model.other_models import ANCOMBCModel # Initialize and fit model = ANCOMBCModel() model.fit_model(data) # Evaluate results = model.eval_model() ``` ``` -------------------------------- ### b_w_from_abs_change Utility Source: https://context7.com/theislab/sccoda/llms.txt Shows how to use the `b_w_from_abs_change` utility to calculate model parameters (intercepts and slopes) based on desired absolute changes in cell counts. ```APIDOC ## b_w_from_abs_change ### Description Utility function to calculate model parameters from desired absolute changes in cell counts. ### Method `gen.b_w_from_abs_change` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from sccoda.util import data_generation as gen import numpy as np # Define baseline counts and desired change counts_before = np.array([200, 200, 200, 200, 200]) # Equal baseline abs_change = np.array([100, 0, 0, 0, 0]) # Increase first type by 100 # Calculate parameters intercepts, slopes = gen.b_w_from_abs_change( counts_before=counts_before, abs_change=abs_change, n_total=1000 ) print("Intercepts:", intercepts) print("Slopes:", slopes) # Use these to generate data with known effect size data = gen.generate_case_control( cases=1, K=5, n_total=1000, n_samples=[10, 10], b_true=intercepts, w_true=slopes.reshape(1, -1) ) ``` ### Response #### Success Response (200) Returns intercepts and slopes as numpy arrays. #### Response Example ``` Intercepts: [ 1.38629436 1.38629436 1.38629436 1.38629436 1.38629436] Slopes: [[0.40546511 0. 0. 0. 0. ]] ``` ``` -------------------------------- ### Perform Compositional Analysis with scCODA Source: https://github.com/theislab/sccoda/blob/master/docs/source/_templates/Modeling_options_and_result_analysis.ipynb Initializes the CompositionalAnalysis model with a specified formula and reference cell type, then executes Hamiltonian Monte Carlo (HMC) sampling to estimate parameters. The resulting summary provides insights into intercepts, effects, and log2-fold changes across conditions. ```python model_all = mod.CompositionalAnalysis(data_all, formula="Condition", reference_cell_type="Endocrine") all_results = model_all.sample_hmc() all_results.summary() ``` -------------------------------- ### POST /model/ALRModel_wilcoxon/fit_model Source: https://github.com/theislab/sccoda/blob/master/docs/source/sccoda.model.other_models.ALRModel_wilcoxon.fit_model.rst Executes the model fitting process for the ALRModel_wilcoxon class. ```APIDOC ## POST /model/ALRModel_wilcoxon/fit_model ### Description This method fits the ALRModel_wilcoxon model to the provided dataset, performing statistical analysis based on the Wilcoxon test framework. ### Method POST ### Endpoint /model/ALRModel_wilcoxon/fit_model ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **data** (object) - Required - The input dataset containing cell counts or proportions. - **formula** (string) - Required - The statistical formula defining the model structure. ### Request Example { "data": "dataset_object", "formula": "condition ~ 1" } ### Response #### Success Response (200) - **model_results** (object) - The fitted model object containing statistical coefficients and p-values. #### Response Example { "status": "success", "model_results": { "coefficients": [0.1, -0.2], "p_values": [0.05, 0.01] } } ```