### Install CellphoneDB Package Source: https://github.com/ventolab/cellphonedb/blob/master/notebooks/T1_Method3.ipynb Installs the latest version of the CellphoneDB package using pip. The `--quiet` flag can be removed to view detailed installation logs. This step is necessary to make the CellphoneDB analysis tools available in the current environment. ```bash pip install --quiet cellphonedb ``` -------------------------------- ### Compile Documentation with Make Source: https://github.com/ventolab/cellphonedb/blob/master/docs/README.md This snippet shows the shell commands to navigate to the documentation directory, install necessary Python dependencies, and then compile the HTML documentation using the 'make html' command. It assumes a Unix-like environment. ```shell cd docs/api pip install -r requirements.txt pip install -r ../../requirements.txt make html ``` -------------------------------- ### Install CellphoneDB and Configure Jupyter Kernel Source: https://github.com/ventolab/cellphonedb/blob/master/docs/RESULTS-DOCUMENTATION.md Installs the CellphoneDB package via pip and configures the environment as a kernel for use within Jupyter Notebooks. ```bash pip install cellphonedb pip install -U ipykernel python -m ipykernel install --user --name 'cpdb' ``` -------------------------------- ### Setup Python Environment for CellphoneDB Source: https://github.com/ventolab/cellphonedb/blob/master/notebooks/T1_Method3.ipynb Initializes the Python environment by setting display options for pandas and changing the current working directory to the analysis base. This ensures CellphoneDB can access necessary files and configurations. ```python import pandas as pd import sys import os pd.set_option('display.max_columns', 100) # Define our base directory for the analysis os.chdir('/home/jovyan/cpdb_tutorial') ``` -------------------------------- ### Setup Rpy2 and Load AnnData into R (Python/R) Source: https://github.com/ventolab/cellphonedb/blob/master/notebooks/DEGs_calculation/0_prepare_your_data_from_anndata.ipynb This snippet initializes rpy2 for interaction with R, suppresses R warning messages, and loads an AnnData object into an R environment for further analysis. It also activates the rpy2 extension for IPython. ```python import rpy2.rinterface_lib.callbacks import logging # Ignore R warning messages #Note: this can be commented out to get more verbose R output rpy2.rinterface_lib.callbacks.logger.setLevel(logging.ERROR) import anndata2ri anndata2ri.activate() %load_ext rpy2.ipython ``` ```R %%R -i adata adata ``` -------------------------------- ### Install CellphoneDB and Import Libraries (Python) Source: https://github.com/ventolab/cellphonedb/blob/master/NatureProtocols2024_case_studies/T0_DownloadDB.ipynb This snippet shows the initial Python imports required for using CellphoneDB, including pandas, glob, and os. It assumes CellphoneDB is installed within a conda environment. ```python import pandas as pd import glob import os ``` -------------------------------- ### Execute Standard CellphoneDB Analysis Source: https://github.com/ventolab/cellphonedb/blob/master/README.md Runs a standard analysis method without statistical testing. This example demonstrates usage with both text-based and h5ad count files. ```python from cellphonedb.src.core.methods import cpdb_analysis_method # Using text files cpdb_results_txt = cpdb_analysis_method.call( cpdb_file_path = 'cellphonedb.zip', meta_file_path = 'test_meta.txt', counts_file_path = 'test_counts.txt', counts_data = 'hgnc_symbol', score_interactions = True, output_path = 'out_path') # Using h5ad count file cpdb_results_h5ad = cpdb_analysis_method.call( cpdb_file_path = 'cellphonedb.zip', meta_file_path = 'test_meta.txt', counts_file_path = 'test_counts.h5ad', counts_data = 'hgnc_symbol', output_path = 'out_path') ``` -------------------------------- ### Run CellphoneDB with Differential Analysis (Method 3) Source: https://github.com/ventolab/cellphonedb/blob/master/notebooks/T1_Method3.ipynb This section provides a comprehensive Python code example for running CellPhoneDB's differential expression analysis. It outlines the necessary input files and parameters, such as counts, metadata, DEGs, and optional active transcription factors and microenvironments. ```APIDOC ## Run CellphoneDB with Differential Analysis (Method 3) ### Description This method runs CellphoneDB using differential expression analysis. It requires normalized count data, metadata, and a list of differentially expressed genes (DEGs). Optional inputs include active transcription factors and microenvironment definitions. ### Method `cpdb_degs_analysis_method.call()` ### Parameters #### Mandatory Parameters - **cpdb_file_path** (str) - Path to the CellphoneDB database zip file. - **meta_file_path** (str) - Path to the TSV file defining barcodes to cell labels. - **counts_file_path** (str) - Path to the normalized count matrix (or an in-memory AnnData object). - **degs_file_path** (str) - Path to the TSV file with DEGs to account for. #### Optional Parameters - **counts_data** (str) - Defines the gene annotation in the counts matrix. Default is 'hgnc_symbol'. - **active_tfs_file_path** (str) - Optional path to a file defining cell types and their active TFs. - **microenvs_file_path** (str) - Optional path to a file defining cells per microenvironment. Default is None. - **score_interactions** (bool) - Whether to score interactions. Default is True. - **threshold** (float) - Minimum percentage of cells expressing a gene for it to be considered in the analysis. Default is 0.1. - **result_precision** (int) - Rounding precision for mean values in `significant_means`. Default is 3. - **separator** (str) - String to separate cells in results dataframes (e.g., 'cellA|CellB'). Default is '|'. - **debug** (bool) - Saves intermediate tables in PKL format if True. Default is False. - **output_path** (str) - Path to save the analysis results. - **output_suffix** (str) - User-defined string to replace the timestamp in output files. Default is None. - **threads** (int) - Number of threads to use for the analysis. Default is 25. ### Request Example ```python from cellphonedb.src.core.methods import cpdb_degs_analysis_method cpdb_results = cpdb_degs_analysis_method.call( cpdb_file_path = cpdb_file_path, # mandatory meta_file_path = meta_file_path, # mandatory counts_file_path = counts_file_path, # mandatory degs_file_path = degs_file_path, # mandatory counts_data = 'hgnc_symbol', active_tfs_file_path = active_tf_path, # optional microenvs_file_path = microenvs_file_path, # optional score_interactions = True, threshold = 0.1, result_precision = 3, separator = '|', debug = False, output_path = out_path, output_suffix = None, threads = 25 ) ``` ### Response #### Success Response The function returns a dictionary `cpdb_results` containing various dataframes related to the analysis, including: - `deconvoluted`: Deconvoluted expression values. - `deconvoluted_percents`: Percentage of cells expressing each gene. - `means`: Mean expression values. - `relevant_interactions`: Interactions deemed relevant. - `significant_means`: Significant mean expression values. - `CellSign_active_interactions`: Active interactions identified by CellSign. - `CellSign_active_interactions_deconvoluted`: Deconvoluted active interactions. - `interaction_scores`: Scores for identified interactions. #### Response Example ```python list(cpdb_results.keys()) # Result: ['deconvoluted', 'deconvoluted_percents', 'means', 'relevant_interactions', 'significant_means', 'CellSign_active_interactions', 'CellSign_active_interactions_deconvoluted', 'interaction_scores'] ``` ``` -------------------------------- ### Importing Libraries for CellphoneDB Analysis (Python) Source: https://github.com/ventolab/cellphonedb/blob/master/NatureProtocols2024_case_studies/CaseExample2_spatialNiches/analysis_method3_microenvironments.ipynb Imports essential Python libraries including pandas for data manipulation, sys for system-specific parameters, and os for interacting with the operating system. Sets pandas to display a maximum of 100 columns for better data overview. This setup is crucial for preparing data and running CellphoneDB analyses. ```python import pandas as pd import sys import os pd.set_option('display.max_columns', 100) ``` -------------------------------- ### GET /utils/db_releases Source: https://github.com/ventolab/cellphonedb/blob/master/docs/cellphonedb.utils.md Retrieves an HTML table of available CellphoneDB database versions and their release dates. ```APIDOC ## GET /utils/db_releases ### Description Retrieve a html table containing CellphoneDB database versions and release dates. ### Method GET ### Endpoint cellphonedb.utils.db_releases_utils.get_remote_database_versions_html ### Parameters #### Query Parameters - **include_file_browsing** (bool) - Optional - If true, enables browsing of individual input files. - **min_version** (float) - Optional - Filters results to versions >= min_version. ### Response #### Success Response (200) - **data** (string) - HTML string containing the version table. ``` -------------------------------- ### Initialize CellphoneDB Environment Source: https://github.com/ventolab/cellphonedb/blob/master/notebooks/T1_Method1.ipynb Sets up the Python environment by importing necessary libraries and configuring pandas display options. This is the first step before performing any analysis. ```python import pandas as pd import sys import os pd.set_option('display.max_columns', 100) os.chdir('/home/jovyan/cpdb_tutorial') ``` -------------------------------- ### Initialize ktplotspy for CellphoneDB Source: https://github.com/ventolab/cellphonedb/blob/master/NatureProtocols2024_case_studies/CaseExample2_spatialNiches/analysis_method3_microenvironments.ipynb Imports necessary libraries and sets up the environment for visualizing CellphoneDB results. ```python import os import anndata as ad import pandas as pd import ktplotspy as kpy import matplotlib.pyplot as plt %matplotlib inline ``` -------------------------------- ### GET /search Source: https://github.com/ventolab/cellphonedb/blob/master/docs/cellphonedb.utils.md Searches the CellphoneDB database for interactions based on provided gene, protein, or complex identifiers. ```APIDOC ## GET /search ### Description Searches CellphoneDB interactions for genes, proteins, or complexes based on a query string. ### Method GET ### Endpoint /search ### Parameters #### Query Parameters - **query_str** (str) - Required - A comma- or space-separated list of Ensembl IDs, Gene names, UniProt IDs, or Complex names. - **cpdb_file_path** (str) - Optional - The file path to the CellphoneDB database. ### Request Example GET /search?query_str=ABCA1,ENSG00000165029 ### Response #### Success Response (200) - **data** (list) - A list of sub-lists representing interaction details. - **complex_map** (map) - Mapping of complexes to their constituent proteins. ``` -------------------------------- ### Deploy CellphoneDBViz with Docker Compose Source: https://github.com/ventolab/cellphonedb/blob/master/docs/RESULTS-DOCUMENTATION.md Commands to build and manage the CellphoneDBViz service container. These commands handle the image creation, service startup, and shutdown processes. ```bash #Create Docker image docker-compose build --no-cache #Deploy the image in a Docker container docker-compose up -d #Shut down the Docker container when you no longer need the service docker-compose down ``` -------------------------------- ### Configure CellphoneDB Input File Paths (Python) Source: https://github.com/ventolab/cellphonedb/blob/master/notebooks/T1_Method3.ipynb Sets the file paths for CellphoneDB analysis, including database, metadata, counts, DEGs, microenvironments, and active transcription factors. These paths are essential for running the CellphoneDB analysis pipeline. ```python cpdb_file_path = 'db/v5/cellphonedb.zip' meta_file_path = 'data/metadata.tsv' counts_file_path = 'data/normalised_log_counts.h5ad' microenvs_file_path = 'data/microenvironment.tsv' degs_file_path = 'data/DEGs_inv_trophoblast.tsv' active_tf_path = 'data/active_TFs.tsv' out_path = 'results/method3_withScore' ``` -------------------------------- ### Check Gene Presence in Seurat Object Source: https://github.com/ventolab/cellphonedb/blob/master/notebooks/DEGs_calculation/0_prepare_your_data_from_Seurat.ipynb This Python code snippet checks if a specific gene, 'DKK1' in this example, is present in the raw counts of a Seurat object. This is a common preliminary step before performing differential expression analysis to ensure the gene of interest is available in the dataset. ```Python 'DKK1' %in% rownames(so@assays$RNA@counts) ``` -------------------------------- ### Load Database Input Files and List Directory Source: https://github.com/ventolab/cellphonedb/blob/master/notebooks/T0_BuildDBfromFiles.ipynb This code snippet defines the directory path for CellphoneDB input files and lists the files present in that directory. This is a preliminary step before building the database. ```python # -- Path where the input files to generate the database are located cpdb_input_dir = '/home/jovyan/cpdb_tutorial/db/v5/' os.listdir(cpdb_input_dir) ``` -------------------------------- ### Create and Activate Python Environment Source: https://github.com/ventolab/cellphonedb/blob/master/docs/RESULTS-DOCUMENTATION.md Commands to create and activate an isolated Python 3.8 environment using either Conda or virtualenv to ensure dependency compatibility. ```bash # Using Conda conda create -n cpdb python=3.8 conda activate cpdb # Using virtualenv python -m venv cpdb source cpdb/bin/activate ``` -------------------------------- ### Define Input File Paths Source: https://github.com/ventolab/cellphonedb/blob/master/notebooks/T1_Method1.ipynb Defines the file paths for the database, metadata, normalized counts, and microenvironment files required for the statistical method. ```python cpdb_file_path = 'db/v5/cellphonedb.zip' meta_file_path = 'data/metadata.tsv' counts_file_path = 'data/normalised_log_counts.h5ad' microenvs_file_path = 'data/microenvironment.tsv' out_path = 'results/method1' ``` -------------------------------- ### Prepare AnnData for CellPhoneDB Analysis (Python) Source: https://github.com/ventolab/cellphonedb/blob/master/notebooks/DEGs_calculation/0_prepare_your_data_from_anndata.ipynb This snippet demonstrates how to load an AnnData object, set verbosity, and read a .h5ad file. It also shows how to inspect cell type distributions and generate a metadata CSV file required for CellPhoneDB. ```python import numpy as np import pandas as pd import scanpy as sc import anndata import os import sys from scipy import sparse sc.settings.verbosity = 1 # verbosity: errors (0), warnings (1), info (2), hints (3) sys.executable adata = sc.read('endometrium_example_counts.h5ad') adata.obs['cell_type'].values.describe() df_meta = pd.DataFrame(data={'Cell':list(adata.obs.index), 'cell_type':[ i for i in adata.obs['cell_type']] }) df_meta.set_index('Cell', inplace=True) df_meta.to_csv('endometrium_example_meta.tsv', sep = '\t') ``` -------------------------------- ### Create Custom CellphoneDB Database (Python) Source: https://context7.com/ventolab/cellphonedb/llms.txt Creates a custom CellphoneDB database from user-provided input files. This allows users to modify existing interaction data or add new entries before generating a new database. ```python from cellphonedb.utils import db_utils # Directory containing modified input files: # - gene_input.csv # - protein_input.csv # - complex_input.csv # - interaction_input.csv # - transcription_factor_input.csv (optional) # - sources/uniprot_synonyms.tsv (optional) cpdb_input_dir = "./my_custom_db" db_utils.create_db(cpdb_input_dir) ``` -------------------------------- ### Prepare Metadata File Source: https://context7.com/ventolab/cellphonedb/llms.txt Creates a tab-separated metadata file linking cell barcodes to their respective cell types, which is a requirement for CellphoneDB analysis methods. ```python import pandas as pd meta_df = pd.DataFrame({ 'Cell': adata.obs_names, 'cell_type': adata.obs['cell_type'] }) meta_df.to_csv('./data/meta.txt', sep='\t', index=False) ``` -------------------------------- ### Define Database Version and Download Path (Python) Source: https://github.com/ventolab/cellphonedb/blob/master/NatureProtocols2024_case_studies/T0_DownloadDB.ipynb This section defines the specific CellphoneDB version to be downloaded and the target directory on the local system where the database and input files will be stored. It uses the os.path.join function for cross-platform compatibility. ```python # -- Version of the databse cpdb_version = 'v5.0.0' # -- Path where the input files to generate the database are located cpdb_target_dir = os.path.join('/home/jovyan/cellphonedb_v500_NatProtocol/', cpdb_version) ``` -------------------------------- ### Run Basic CellphoneDB Analysis (Python) Source: https://github.com/ventolab/cellphonedb/blob/master/notebooks/T1_Method1.ipynb This snippet demonstrates how to execute the core analysis function of CellphoneDB. It takes paths to the database, metadata, and count files as mandatory inputs, along with several optional parameters to control the analysis process, such as gene annotation, microenvironment definition, scoring, output path, and performance settings. The function returns a dictionary containing various results. ```python from cellphonedb.src.core.methods import cpdb_analysis_method cpdb_results = cpdb_analysis_method.call( cpdb_file_path = cpdb_file_path, # mandatory: CellphoneDB database zip file. meta_file_path = meta_file_path, # mandatory: tsv file defining barcodes to cell label. counts_file_path = counts_file_path, # mandatory: normalized count matrix - a path to the counts file, or an in-memory AnnData object counts_data = 'hgnc_symbol', # defines the gene annotation in counts matrix. microenvs_file_path = microenvs_file_path, # optional (default: None): defines cells per microenvironment. score_interactions = True, # optional: whether to score interactions or not. output_path = out_path, # Path to save results microenvs_file_path = None, separator = '|', # Sets the string to employ to separate cells in the results dataframes "cellA|CellB". threads = 5, # number of threads to use in the analysis. threshold = 0.1, # defines the min % of cells expressing a gene for this to be employed in the analysis. result_precision = 3, # Sets the rounding for the mean values in significan_means. debug = False, # Saves all intermediate tables emplyed during the analysis in pkl format. output_suffix = None # Replaces the timestamp in the output files by a user defined string in the (default: None) ) ``` -------------------------------- ### Define CellphoneDB Input File Paths Source: https://github.com/ventolab/cellphonedb/blob/master/notebooks/T1_Method2.ipynb Sets the file paths for the mandatory and optional input files required to run the CellphoneDB analysis. ```python cpdb_file_path = 'db/v5/cellphonedb.zip' meta_file_path = 'data/metadata.tsv' counts_file_path = 'data/normalised_log_counts.h5ad' microenvs_file_path = 'data/microenvironment.tsv' active_tf_path = 'data/active_TFs.tsv' out_path = 'results/method2_withScore' ``` -------------------------------- ### POST /utils/create_db Source: https://github.com/ventolab/cellphonedb/blob/master/docs/cellphonedb.utils.md Creates a local CellphoneDB database file (cellphonedb.zip) from input CSV files in a target directory. ```APIDOC ## POST /utils/create_db ### Description Creates CellphoneDB database file (cellphonedb.zip) in the specified target directory. ### Method POST ### Endpoint cellphonedb.utils.db_utils.create_db ### Parameters #### Request Body - **target_dir** (string) - Required - Directory containing the required input CSV files. ``` -------------------------------- ### Initialize CellphoneDB Analysis Source: https://github.com/ventolab/cellphonedb/blob/master/NatureProtocols2024_case_studies/CaseExample1_differentiation/analysis_method3_CellSign_microenvironments.ipynb Initializes the CellphoneDB analysis with various parameters to filter interactions and specify cell types. It takes results from a previous CellphoneDB run and sets up parameters for searching interactions. ```python query_interactions = [''], # filter intereactions based on their name (list). significant_means = cpdb_results['significant_means'] deconvoluted = cpdb_results['deconvoluted'] separator = '|' long_format = True query_classifications = ['Signaling by Notch'] ``` -------------------------------- ### Checking Python Version for CellphoneDB Compatibility (Python) Source: https://github.com/ventolab/cellphonedb/blob/master/NatureProtocols2024_case_studies/CaseExample2_spatialNiches/analysis_method3_microenvironments.ipynb Prints the current Python version to the console. This is a validation step to ensure the environment meets the minimum Python version requirement (>= 3.8) for CellphoneDB, which is essential for the tool's proper functioning. ```python print(sys.version) ``` -------------------------------- ### Execute Statistical Analysis Method Source: https://github.com/ventolab/cellphonedb/blob/master/docs/RESULTS-DOCUMENTATION.md This Python snippet demonstrates how to invoke the CellPhoneDB statistical analysis method to identify significant receptor-ligand interactions between cell types using input metadata and count files. ```python from cellphonedb.src.core.methods import cpdb_statistical_analysis_method cpdb_results = cpdb_statistical_analysis_method.call( cpdb_file_path = "cellphonedb.zip", meta_file_path = "test_meta.txt", counts_file_path = "test_counts.h5ad", counts_data = "hgnc_symbol", output_path = "out_path") ``` -------------------------------- ### Display Remote Database Versions (Python) Source: https://github.com/ventolab/cellphonedb/blob/master/NatureProtocols2024_case_studies/T0_DownloadDB.ipynb This code uses IPython.display and CellphoneDB's db_releases_utils to fetch and display available remote database versions in an HTML table format. This helps users choose which version to download. ```python from IPython.display import HTML, display from cellphonedb.utils import db_releases_utils display(HTML(db_releases_utils.get_remote_database_versions_html()['db_releases_html_table'])) ``` -------------------------------- ### Download CellphoneDB Database (Python) Source: https://github.com/ventolab/cellphonedb/blob/master/NatureProtocols2024_case_studies/T0_DownloadDB.ipynb This code snippet utilizes the db_utils module from CellphoneDB to download the specified database version and its associated input files to the previously defined target directory. The output confirms the successful download of various files. ```python from cellphonedb.utils import db_utils db_utils.download_database(cpdb_target_dir, cpdb_version) ``` -------------------------------- ### Retrieve Remote Database Versions as HTML Source: https://github.com/ventolab/cellphonedb/blob/master/docs/cellphonedb.utils.md Fetches a list of available CellphoneDB database versions and their release dates from the remote repository. Returns an HTML table string, with optional filtering by minimum version. ```python from cellphonedb.utils import db_releases_utils # Retrieve HTML table of versions >= 4.1 html_table = db_releases_utils.get_remote_database_versions_html(include_file_browsing=False, min_version=4.1) ``` -------------------------------- ### List Available CellphoneDB Database Versions (Python) Source: https://context7.com/ventolab/cellphonedb/llms.txt Retrieves and displays available CellphoneDB database versions from GitHub, including their release dates. This function is useful for checking for the latest versions and requires specifying a minimum version to filter results. ```python from IPython.display import HTML, display from cellphonedb.utils import db_releases_utils # Get HTML table of available database versions (v4.1.0 and newer) result = db_releases_utils.get_remote_database_versions_html(min_version=4.1) if result['error'] is None: display(HTML(result['db_releases_html_table'])) else: print(f"Error: {result['error']}") ``` -------------------------------- ### Load and Inspect Microenvironments File (Python) Source: https://github.com/ventolab/cellphonedb/blob/master/notebooks/T1_Method3.ipynb Loads the microenvironment definition file using pandas. This file groups cell types into specific microenvironments, and CellphoneDB will only analyze interactions within these defined groups. `head(3)` shows the initial entries. ```python import pandas as pd microenv = pd.read_csv(microenvs_file_path, sep = '\t') microenv.head(3) ``` -------------------------------- ### Run CellphoneDB Statistical Analysis (Python) Source: https://github.com/ventolab/cellphonedb/blob/master/notebooks/T1_Method2.ipynb Executes the core statistical analysis for CellphoneDB. This function takes paths to the database, metadata, and counts files as mandatory inputs. Optional parameters allow for subsampling, setting thresholds, controlling the number of iterations, and specifying output details. The output is saved to a specified path and also returned. ```python from cellphonedb.src.core.methods import cpdb_statistical_analysis_method cpdb_results = cpdb_statistical_analysis_method.call( cpdb_file_path = cpdb_file_path, # mandatory: CellphoneDB database zip file. meta_file_path = meta_file_path, # mandatory: tsv file defining barcodes to cell label. counts_file_path = counts_file_path, # mandatory: normalized count matrix - a path to the counts file, or an in-memory AnnData object counts_data = 'hgnc_symbol', # defines the gene annotation in counts matrix. active_tfs_file_path = active_tf_path, # optional: defines cell types and their active TFs. microenvs_file_path = microenvs_file_path, # optional (default: None): defines cells per microenvironment. score_interactions = True, # optional: whether to score interactions or not. iterations = 1000, # denotes the number of shufflings performed in the analysis. threshold = 0.1, # defines the min % of cells expressing a gene for this to be employed in the analysis. threads = 5, # number of threads to use in the analysis. debug_seed = 42, # debug randome seed. To disable >=0. result_precision = 3, # Sets the rounding for the mean values in significan_means. pvalue = 0.05, # P-value threshold to employ for significance. subsampling = False, # To enable subsampling the data (geometri sketching). subsampling_log = False, # (mandatory) enable subsampling log1p for non log-transformed data inputs. subsampling_num_pc = 100, # Number of componets to subsample via geometric skectching (dafault: 100). subsampling_num_cells = 1000, # Number of cells to subsample (integer) (default: 1/3 of the dataset). separator = '|', # Sets the string to employ to separate cells in the results dataframes "cellA|CellB". debug = False, # Saves all intermediate tables employed during the analysis in pkl format. output_path = out_path, # Path to save results. output_suffix = None # Replaces the timestamp in the output files by a user defined string in the (default: None). ) ``` -------------------------------- ### Download CellphoneDB Database Source: https://github.com/ventolab/cellphonedb/blob/master/notebooks/T0_DownloadDB.ipynb Defines the target version and local directory path, then triggers the download of the specified CellphoneDB database files. Ensure the target directory exists before executing the download command. ```python import os from cellphonedb.utils import db_utils cpdb_version = 'v5.0.0' cpdb_target_dir = os.path.join('/home/jovyan/cpdb_tutorial/db/test', cpdb_version) db_utils.download_database(cpdb_target_dir, cpdb_version) ``` -------------------------------- ### Create CellphoneDB Database Source: https://github.com/ventolab/cellphonedb/blob/master/notebooks/T0_BuildDBfromFiles.ipynb This snippet utilizes the `db_utils.create_db` function from the CellphoneDB library to generate a new database file (.zip) using the specified input directory. The function performs integrity checks on the input files. ```python from cellphonedb.utils import db_utils # -- Creates new database db_utils.create_db(cpdb_input_dir) ``` -------------------------------- ### Run CellphoneDB Simple Analysis Source: https://github.com/ventolab/cellphonedb/blob/master/docs/RESULTS-DOCUMENTATION.md Executes the basic analysis method to retrieve interaction expression means without statistical inference. It requires a database zip, metadata file, and count matrix as inputs. ```python from cellphonedb.src.core.methods import cpdb_analysis_method cpdb_results = cpdb_analysis_method.call( cpdb_file_path = "cellphonedb.zip", meta_file_path = "test_meta.txt", counts_file_path = "test_counts.h5ad", counts_data = "hgnc_symbol", output_path = "out_path") ``` -------------------------------- ### Run Simple Analysis Method (Python) Source: https://context7.com/ventolab/cellphonedb/llms.txt Performs a simple, non-statistical analysis of receptor-ligand interactions based on mean expression values. It identifies interactions where genes are expressed above a specified threshold fraction of cells and can optionally score interactions. ```python from cellphonedb.src.core.methods import cpdb_analysis_method cpdb_results = cpdb_analysis_method.call( cpdb_file_path="./cellphonedb_data/cellphonedb.zip", meta_file_path="./data/meta.txt", counts_file_path="./data/counts.h5ad", counts_data="hgnc_symbol", # or "ensembl", "gene_name" output_path="./output", threshold=0.1, # Min fraction of cells expressing gene (10%) result_precision=3, # Decimal places in results score_interactions=True, # Enable interaction scoring threads=4 ) # Access results as DataFrames means_df = cpdb_results['means_result'] deconvoluted_df = cpdb_results['deconvoluted'] deconvoluted_percents_df = cpdb_results['deconvoluted_percents'] interaction_scores_df = cpdb_results.get('interaction_scores') # if score_interactions=True ``` -------------------------------- ### POST /utils/generate_input_files Source: https://github.com/ventolab/cellphonedb/blob/master/docs/cellphonedb.utils.md Generates custom CellphoneDB input files by combining user-provided data with curated database interactions. ```APIDOC ## POST /utils/generate_input_files ### Description Generate your own CellphoneDB input files, using your own complexes and interactions. ### Method POST ### Endpoint cellphonedb.utils.generate_input_files.generate_all ### Parameters #### Request Body - **target_dir** (string) - Required - Directory to place generated files. - **cpdb_version** (string) - Required - Version of the curated database to use. - **user_complex** (string) - Optional - Path to user complex CSV file. - **user_interactions** (string) - Optional - Path to user interactions CSV file. - **user_interactions_only** (bool) - Optional - If true, excludes curated interactions. ``` -------------------------------- ### Process Microenvironment Definitions Source: https://github.com/ventolab/cellphonedb/blob/master/notebooks/T1_Method2.ipynb Loads the microenvironment configuration file and groups cell types by their assigned microenvironment to restrict interaction calculations. ```python microenv = pd.read_csv(microenvs_file_path, sep = '\t') microenv.head(3) # Group cells per microenvironment microenv.groupby('microenvironment', group_keys = False)['cell_type'].apply(lambda x : list(x.value_counts().index)) ``` -------------------------------- ### Generate Custom Input Files Source: https://github.com/ventolab/cellphonedb/blob/master/docs/cellphonedb.utils.md Generates CellphoneDB input files by combining user-provided interaction and complex data with curated data from the repository. Useful for running analyses with custom datasets. ```python from cellphonedb.utils import generate_input_files generate_input_files.generate_all( target_dir="/path/to/output", cpdb_version="v4.1.0", user_complex="/path/to/complex.csv", user_interactions="/path/to/interactions.csv", user_interactions_only=False ) ``` -------------------------------- ### Set Analysis Working Directory Source: https://github.com/ventolab/cellphonedb/blob/master/NatureProtocols2024_case_studies/CaseExample1_differentiation/analysis_method3_CellSign_microenvironments.ipynb Sets the current working directory to the project base path for CellPhoneDB analysis. ```python import os os.chdir('/home/jovyan/cellphonedb_v500_NatProtocol/CaseExample1_differentiation/') ``` -------------------------------- ### Manage Local Database Files Source: https://github.com/ventolab/cellphonedb/blob/master/docs/cellphonedb.utils.md Functions to locate, create, and load CellphoneDB database files. These utilities allow for the creation of the database zip file from CSV inputs and loading the data into memory as DataFrames. ```python from cellphonedb.utils import db_utils # Create database file from CSVs in directory db_utils.create_db(target_dir="/path/to/csvs") # Get path to local database db_path = db_utils.get_db_path(user_dir_root="/home/user/.cpdb", db_version="v4.1.0") # Load database into memory interactions, genes, comp, exp, syn, tfs = db_utils.get_interactions_genes_complex(cpdb_file_path=db_path) ``` -------------------------------- ### Create Microenvironments DataFrame and Save to File (Python) Source: https://context7.com/ventolab/cellphonedb/llms.txt This code creates a Pandas DataFrame defining cell types and their associated microenvironments, then saves it to a tab-separated file. This file is used to restrict cell-cell interaction analysis to co-localized cell types. ```Python import pandas as pd microenvs_df = pd.DataFrame({ 'cell_type': ['T_cell', 'Macrophage', 'Dendritic', 'Fibroblast', 'Endothelial'], 'microenvironment': ['immune_niche', 'immune_niche', 'immune_niche', 'stromal_niche', 'stromal_niche'] }) microenvs_df.to_csv('./data/microenvironments.txt', sep=' ', index=False) ``` -------------------------------- ### Generate CellphoneDB Heatmaps Source: https://github.com/ventolab/cellphonedb/blob/master/NatureProtocols2024_case_studies/CaseExample2_spatialNiches/analysis_method3_microenvironments.ipynb Creates heatmaps to visualize the sum of significant interactions. Supports global analysis or filtered views by microenvironment. ```python kpy.plot_cpdb_heatmap(pvals = cpdb_results['relevant_interactions'], degs_analysis=True, figsize=(8, 8), title="Sum of significant interactions") kpy.plot_cpdb_heatmap(pvals = cpdb_results['relevant_interactions'], degs_analysis=True, cell_types=microenv_dic['SecretoryMid_glands'], figsize=(3, 3), title="Sum of significant interactions in outer cortex") ``` -------------------------------- ### Integrating Microenvironments in CellphoneDB Analysis Source: https://github.com/ventolab/cellphonedb/blob/master/docs/RESULTS-DOCUMENTATION.md This shell command snippet shows how to include spatial information by specifying the path to a microenvironments file. CellphoneDB will then restrict interaction analysis to cell type pairs that coexist within the defined microenvironments. ```shell microenvs = test_microenvs.txt ``` -------------------------------- ### Load and Inspect Metadata File (Python) Source: https://github.com/ventolab/cellphonedb/blob/master/notebooks/T1_Method3.ipynb Loads the metadata file using pandas, which links cell barcodes to their assigned cluster labels. The `head(3)` function displays the first three rows to verify the structure and content. ```python import pandas as pd metadata = pd.read_csv(meta_file_path, sep = '\t') metadata.head(3) ``` -------------------------------- ### Load Metadata File - Python Source: https://github.com/ventolab/cellphonedb/blob/master/NatureProtocols2024_case_studies/CaseExample1_differentiation/analysis_method3_CellSign_microenvironments.ipynb Loads the metadata file, which contains cell barcodes and their assigned cell types. It uses pandas to read a tab-separated file and displays the first few rows. ```python import pandas as pd meta_file_path = 'input/dataset_meta.tsv' metadata = pd.read_csv(meta_file_path, sep = '\t') metadata.head(3) ``` -------------------------------- ### Download CellphoneDB Database (Python) Source: https://context7.com/ventolab/cellphonedb/llms.txt Downloads a specific version of the CellphoneDB database from a remote repository. This function requires the target directory and the desired database version as input. ```python from cellphonedb.utils import db_utils # Download specific database version to target directory cpdb_target_dir = "./cellphonedb_data" cpdb_version = "v5.0.0" db_utils.download_database(cpdb_target_dir, cpdb_version) ``` -------------------------------- ### Load and Prepare Seurat Object for CellPhoneDB Source: https://github.com/ventolab/cellphonedb/blob/master/notebooks/DEGs_calculation/0_prepare_your_data_from_Seurat.ipynb Loads a Seurat object from an RDS file and sets the active assay and cell type identifiers. Assumes data is already normalized and log-transformed; otherwise, normalization is recommended. ```R library(Seurat) library(SeuratObject) library(Matrix) so = readRDS('endometrium_example_counts_seurat.rds') Idents(so) = so$cell_type # If your data is not normalized, do it accordingly # For example # so <- NormalizeData(object = so) ``` -------------------------------- ### Import Libraries for CellphoneDB Analysis (Python) Source: https://github.com/ventolab/cellphonedb/blob/master/NatureProtocols2024_case_studies/CaseExample3_specificityScoring/analysis_method2_scoring.ipynb Imports essential Python libraries for data manipulation, analysis, and plotting, commonly used in bioinformatics workflows with CellphoneDB. This includes pandas for data handling, sys and os for system interactions, anndata for single-cell data, and plotting libraries. ```Python import pandas as pd import sys import os import anndata as ad import ktplotspy as kpy import matplotlib.pyplot as plt %matplotlib inline pd.set_option('display.max_columns', 100) ``` -------------------------------- ### Database Management Source: https://github.com/ventolab/cellphonedb/blob/master/README.md Provides functionality to list available remote database versions and download specific versions for use with CellphoneDB. ```APIDOC ## Database Operations ### Description Manage CellphoneDB database versions, including listing available remote versions and downloading specific versions. ### Method GET (list versions), POST (download version) ### Endpoints - `/db/versions/remote` (List available versions) - `/db/download` (Download a specific version) ### Parameters #### List Remote Versions No specific parameters required for listing. #### Download Version ##### Path Parameters - **cpdb_target_dir** (string) - Required - The directory where the database will be downloaded. - **cpdb_version** (string) - Required - The specific version of the database to download (e.g., '4.0.0'). ### Request Example (List Versions) ```python from IPython.display import HTML, display from cellphonedb.utils import db_releases_utils display(HTML(db_releases_utils.get_remote_database_versions_html()['db_releases_html_table'])) ``` ### Request Example (Download Version) ```python from cellphonedb.utils import db_utils cpdb_target_dir = '/path/to/your/directory' cpdb_version = '4.1.0' # Example version db_utils.download_database(cpdb_target_dir, cpdb_version) ``` ### Response #### Success Response (200) - **List Versions**: HTML table displaying available database versions. - **Download Version**: Confirmation message or status of the download. #### Response Example (List Versions) ```html
| Version | Date |
|---|---|
| 4.1.0 | 2023-01-01 |