### Install MultiVelo Source: https://multivelo.readthedocs.io/en/latest/_sources/usage.rst.txt Commands to install the package using common Python package managers. ```console $ pip install multivelo ``` ```console $ conda install -c bioconda multivelo ``` -------------------------------- ### Environment Setup Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig2.html Imports and autoreload configuration for the analysis environment. ```python %load_ext autoreload %autoreload 2 import os import scipy import numpy as np import pandas as pd import sys import multivelo as mv import scanpy as sc import scvelo as scv import matplotlib.pyplot as plt sys.path.append("/..") ``` -------------------------------- ### Import required libraries Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig6.html Initializes the environment by importing necessary data science and bioinformatics libraries. ```python import os import scipy import numpy as np import pandas as pd import sys import multivelo as mv import scanpy as sc import scvelo as scv import matplotlib.pyplot as plt import requests ``` -------------------------------- ### Project Directory Structure Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Demo.html The expected file structure for the MultiVelo demonstration project. ```text . |-- MultiVelo_Demo.ipynb |-- cell_annotations.tsv |-- outs | |-- analysis | | `-- feature_linkage | | `-- feature_linkage.bedpe | |-- filtered_feature_bc_matrix | | |-- barcodes.tsv.gz | | |-- features.tsv.gz | | `-- matrix.mtx.gz | `-- peak_annotation.tsv |-- seurat_wnn | |-- nn_cells.txt | |-- nn_dist.txt | `-- nn_idx.txt `-- velocyto `-- 10X_multiome_mouse_brain.loom ``` -------------------------------- ### Import Dependencies Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Demo.html Required libraries for running the MultiVelo analysis. ```python import os import scipy import numpy as np import pandas as pd import scanpy as sc import scvelo as scv import multivelo as mv import matplotlib.pyplot as plt ``` -------------------------------- ### Import necessary libraries Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig4.html Initial imports for data processing, analysis, and visualization. ```python import os import scipy import numpy as np import pandas as pd import math import sys import multivelo as mv import scanpy as sc import scvelo as scv import matplotlib.pyplot as plt import requests from dtw import * ``` -------------------------------- ### Generate pie chart summary with MultiVelo Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig6.html Creates a summary pie chart visualization from the provided result object. ```python mv.pie_summary(adata_result) ``` -------------------------------- ### Run scVelo Dynamical Modeling Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig5.html Perform standard scVelo dynamical recovery and velocity computation. ```python scv.tl.recover_dynamics(adata_rna_scv) scv.tl.velocity(adata_rna_scv, mode="dynamical") scv.tl.velocity_graph(adata_rna_scv, n_jobs=1) scv.tl.latent_time(adata_rna_scv) scv.pl.velocity_embedding_stream(adata_rna_scv, basis='umap', color='leiden') ``` ```python scv.tl.recover_dynamics(adata_rna) scv.tl.velocity(adata_rna, mode="dynamical") scv.tl.velocity_graph(adata_rna, n_jobs=1) ``` -------------------------------- ### Set scVelo and pandas parameters Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig6.html Configures global settings for scVelo, pandas, and numpy to ensure consistent output and display. ```python scv.settings.verbosity = 3 scv.settings.presenter_view = True scv.set_figure_params('scvelo') pd.set_option('display.max_columns', 100) pd.set_option('display.max_rows', 200) np.set_printoptions(suppress=True) ``` -------------------------------- ### Import MultiVelo Source: https://multivelo.readthedocs.io/en/latest/_sources/api.rst.txt Standard import statement for accessing the MultiVelo library. ```python import multivelo as mv ``` -------------------------------- ### Directory structure for MultiVelo analysis Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig3.html Displays the expected file organization for the MultiVelo Fig3 notebook. ```text . |-- MultiVelo_Fig3.ipynb |-- cell_annotations.tsv |-- outs | |-- analysis | | `-- feature_linkage | | `-- feature_linkage.bedpe | |-- filtered_feature_bc_matrix | | |-- barcodes.tsv.gz | | |-- features.tsv.gz | | `-- matrix.mtx.gz | `-- peak_annotation.tsv |-- seurat_wnn | |-- nn_cells.txt | |-- nn_dist.txt | `-- nn_idx.txt `-- velocyto `-- 10X_multiome_mouse_brain.loom ``` -------------------------------- ### Directory Structure Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig2.html The expected file structure for the MultiVelo Fig2 analysis. ```text . |-- MultiVelo_Fig2.ipynb |-- cell_annotations.tsv |-- outs | |-- analysis | | `-- feature_linkage | | `-- feature_linkage.bedpe | |-- filtered_feature_bc_matrix | | |-- barcodes.tsv.gz | | |-- features.tsv.gz | | `-- matrix.mtx.gz | `-- peak_annotation.tsv |-- seurat_wnn | |-- nn_cells.txt | |-- nn_dist.txt | `-- nn_idx.txt `-- velocyto `-- 10X_multiome_mouse_brain.loom ``` -------------------------------- ### multivelo.switch_time_summary Source: https://multivelo.readthedocs.io/en/latest/_sources/multivelo.switch_time_summary.rst.txt Calculates the summary of switch times within the multivelo framework. ```APIDOC ## multivelo.switch_time_summary ### Description Calculates and returns a summary of switch times based on the provided data within the multivelo library. ### Signature `multivelo.switch_time_summary()` ``` -------------------------------- ### Configure logging Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig6.html Sets the log filename for the MultiVelo session using a timestamp. ```python import time mv.settings.LOG_FILENAME = "Fig6_" + str(time.time()) + ".txt" ``` -------------------------------- ### multivelo.knn_smooth_chrom Source: https://multivelo.readthedocs.io/en/latest/_sources/multivelo.knn_smooth_chrom.rst.txt Documentation for the knn_smooth_chrom function. ```APIDOC ## multivelo.knn_smooth_chrom ### Description Performs k-nearest neighbor smoothing on chromatin data. ### Signature `multivelo.knn_smooth_chrom(adata, ...)` ``` -------------------------------- ### Run scVelo Dynamical Modeling Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig6.html Perform standard scVelo dynamical velocity analysis on the RNA data. ```python scv.tl.recover_dynamics(adata_rna_scv) scv.tl.velocity(adata_rna_scv, mode="dynamical") scv.tl.velocity_graph(adata_rna_scv, n_jobs=1) scv.tl.latent_time(adata_rna_scv) scv.pl.velocity_embedding_stream(adata_rna_scv, basis='umap', color='cluster') ``` ```python scv.tl.recover_dynamics(adata_rna) scv.tl.velocity(adata_rna, mode="dynamical") scv.tl.velocity_graph(adata_rna, n_jobs=1) ``` -------------------------------- ### Load datasets Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig6.html Reads the RNA and ATAC-seq data files, downloading them from the provided URLs if they are not present locally. ```python adata_rna = sc.read(rna_path, backup_url=rna_url) adata_atac = sc.read(atac_path, backup_url=atac_url) ``` -------------------------------- ### Generate switch time summary Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig5.html Visualizes the switch time summary for the provided AnnData object. ```python mv.switch_time_summary(adata_result) ``` -------------------------------- ### Configure Logging Source: https://multivelo.readthedocs.io/en/latest/adam_example.html Sets the log filename for the current session using a timestamp. ```python import time mv.settings.LOG_FILENAME = "adam_example_" + str(time.time()) + ".txt" ``` -------------------------------- ### Run multi-omic dynamical model with neural network Source: https://multivelo.readthedocs.io/en/latest/neural_net_example.html Executes the MultiVelo dynamics recovery using a neural network for time prediction. This process is computationally intensive and benefits from parallelization. ```python # This will take a while. Parallelization is high recommended. mv.settings.VERBOSITY = 0 adata_result = mv.recover_dynamics_chrom(adata_rna, adata_atac, max_iter=5, init_mode="invert", parallel=True, n_jobs = 10, save_plot=False, rna_only=False, fit=True, n_anchors=500, neural_net=True, # device="cuda:0", extra_color_key='cluster' ) ``` -------------------------------- ### Load Analysis Results Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig4.html Loads the analysis results from a local file or downloads from a remote URL if missing. ```python h5ad_url = "https://figshare.com/ndownloader/files/40064263" adata_result = sc.read("multivelo_result_fig4.h5ad", backup_url = h5ad_url) ``` -------------------------------- ### Print AnnData Summary Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig4.html Displays the summary information of the AnnData object. ```python print(adata_result) ``` -------------------------------- ### Save and Load Results Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig3.html Persist the MultiVelo result object to disk and reload it. ```python # Save the result for use later on adata_result.write("multivelo_result_fig3.h5ad") ``` ```python adata_result = sc.read_h5ad("multivelo_result_fig3.h5ad") ``` -------------------------------- ### Save and Load MultiVelo Results Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig6.html Save the computed AnnData object to disk or load it from a remote URL. ```python # Save the result for use later on adata_result.write("multivelo_result_fig6.h5ad") ``` ```python h5ad_url = "https://figshare.com/ndownloader/files/40064449" adata_result = sc.read("multivelo_result_fig6.h5ad", backup_url = h5ad_url) ``` -------------------------------- ### Visualize model summaries Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Demo.html Generates diagnostic plots to summarize the dynamical model results. ```python mv.pie_summary(adata_result) ``` ```python mv.switch_time_summary(adata_result) ``` ```python mv.likelihood_plot(adata_result) ``` -------------------------------- ### multivelo.switch_time_summary(adata, genes=None) Source: https://multivelo.readthedocs.io/en/latest/multivelo.switch_time_summary.html Plots a box plot for observed switch times based on the provided AnnData object. ```APIDOC ## multivelo.switch_time_summary(adata, genes=None) ### Description This function plots a box plot for observed switch times. It categorizes intervals into primed, coupled-on (coupled induction), decoupled, and coupled-off (coupled repression). ### Parameters - **adata** (AnnData) - Required - Anndata result from dynamics recovery. - **genes** (str, list of str) - Optional (default: None) - If None, will use velocity genes. ``` -------------------------------- ### Load Seurat Neighbors Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig2.html Loads precomputed Seurat WNN neighbor indices and distances. ```python # Read in Seurat WNN neighbors. nn_idx = np.loadtxt("seurat_wnn/nn_idx.txt", delimiter=',') nn_dist = np.loadtxt("seurat_wnn/nn_dist.txt", delimiter=',') nn_cells = pd.Index(pd.read_csv("seurat_wnn/nn_cells.txt", header=None)[0]) # Make sure cell names match. np.all(nn_cells == adata_atac.obs_names) ``` -------------------------------- ### multivelo.velocity_graph(adata, vkey='velo_s', xkey='Ms', **kwargs) Source: https://multivelo.readthedocs.io/en/latest/multivelo.velocity_graph.html Computes the velocity graph by normalizing the velocity matrix and invoking scvelo.tl.velocity_graph. ```APIDOC ## multivelo.velocity_graph ### Description Computes the velocity graph for the provided AnnData object. This function normalizes the velocity matrix and utilizes scvelo.tl.velocity_graph to compute the graph. ### Parameters - **adata** (AnnData) - Required - Anndata result from dynamics recovery. - **vkey** (str) - Optional (default: 'velo_s') - Key to use for spliced velocities. - **xkey** (str) - Optional (default: 'Ms') - Key to use for smoothed spliced counts. - **kwargs** (dict) - Optional - Additional parameters passed to scvelo.tl.velocity_graph. ### Returns - Normalized velocity matrix, associated velocity genes, parameters, and the outputs of scvelo.tl.velocity_graph. ``` -------------------------------- ### calculate_qc_metrics(adata, **kwargs) Source: https://multivelo.readthedocs.io/en/latest/multivelo.calculate_qc_metrics.html Calculates basic QC metrics for an AnnData object, including unspliced/spliced ratios and cell cycle scores. ```APIDOC ## calculate_qc_metrics(adata, **kwargs) ### Description Calculates basic QC metrics using scanpy.pp.calculate_qc_metrics. Additionally computes total counts, the ratio of unspliced and spliced matrices, and cell cycle scores using scvelo.tl.score_genes_cell_cycle. ### Parameters - **adata** (AnnData) - Required - RNA anndata object. Required fields: unspliced and spliced. - **kwargs** (dict) - Optional - Additional parameters passed to scanpy.pp.calculate_qc_metrics. ### Returns - **qc_metrics** (dict) - Outputs of scanpy.pp.calculate_qc_metrics and scvelo.tl.score_genes_cell_cycle. - **total_unspliced** (.var) - Total counts of unspliced matrix. - **total_spliced** (.var) - Total counts of spliced matrix. - **unspliced_ratio** (.var) - Ratio of unspliced counts vs (unspliced + spliced counts). - **cell_cycle_score** (.var) - Cell cycle score difference between G2M_score and S_score. ``` -------------------------------- ### Recover RNA Velocity Dynamics Source: https://multivelo.readthedocs.io/en/latest/adam_example.html Standard workflow for recovering RNA velocity dynamics using scVelo. ```python scv.tl.recover_dynamics(adata_rna) scv.tl.velocity(adata_rna, mode="dynamical") scv.tl.velocity_graph(adata_rna, n_jobs=1) ``` -------------------------------- ### Save and Load Results Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig5.html Persist the computed AnnData object to disk or download from a remote URL. ```python # Save the result for use later on adata_result.write("multivelo_result_fig5.h5ad") ``` ```python h5ad_url = "https://figshare.com/ndownloader/files/40066924" adata_result = sc.read("multivelo_result_fig5.h5ad", backup_url = h5ad_url) ``` -------------------------------- ### Import required libraries Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig5.html Imports necessary data science and bioinformatics libraries, including scanpy, scvelo, and multivelo. ```python import os import scipy import numpy as np import pandas as pd import scanpy as sc import scvelo as scv import sys import multivelo as mv import matplotlib.pyplot as plt import requests sys.path.append('../') print(sys.path) ``` -------------------------------- ### multivelo.dynamic_plot(adata, genes, by='expression', color_by='state', gene_time=True, axis_on=True, frame_on=True, show_anchors=True, show_switches=True, downsample=1, full_range=False, figsize=None, pointsize=2, linewidth=1.5, cmap='coolwarm') Source: https://multivelo.readthedocs.io/en/latest/multivelo.dynamic_plot.html Plots accessibility, expression, or velocity by time for specified genes. ```APIDOC ## dynamic_plot(adata, genes, by='expression', color_by='state', gene_time=True, axis_on=True, frame_on=True, show_anchors=True, show_switches=True, downsample=1, full_range=False, figsize=None, pointsize=2, linewidth=1.5, cmap='coolwarm') ### Description Plots accessibility, expression, or velocity by time for specified genes using an AnnData object containing dynamics recovery results. ### Parameters - **adata** (AnnData) - Required - Anndata result from dynamics recovery. - **genes** (str, list of str) - Required - List of genes to plot. - **by** (str) - Optional - Plot accessibilities and expressions if 'expression'. Plot velocities if 'velocity'. Default: 'expression'. - **color_by** (str) - Optional - Color by the four potential states if 'state'. Other common values are 'leiden', 'louvain', 'celltype', etc. Default: 'state'. - **gene_time** (bool) - Optional - Whether to use individual gene fitted time, or shared global latent time. Default: True. - **axis_on** (bool) - Optional - Whether to show axis labels. Default: True. - **frame_on** (bool) - Optional - Whether to show plot frames. Default: True. - **show_anchors** (bool) - Optional - Whether to display anchors. Default: True. - **show_switches** (bool) - Optional - Whether to show switch times indicated by vertical dotted lines. Default: True. - **downsample** (int) - Optional - How much to downsample the cells. Default: 1. - **full_range** (bool) - Optional - Whether to show the full time range of velocities before smoothing. Default: False. - **figsize** (tuple) - Optional - Total figure size. Default: None. - **pointsize** (float) - Optional - Point size for scatter plots. Default: 2. - **linewidth** (float) - Optional - Line width for anchor line or mean line. Default: 1.5. - **cmap** (str) - Optional - Color map for continuous color key. Default: 'coolwarm'. ``` -------------------------------- ### Generate Dynamic Plots (Fig 3c) Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig3.html Visualize the dynamics of specific genes. ```python mv.dynamic_plot(adata_result, genes=["Robo2"], color_by="state") mv.dynamic_plot(adata_result, genes=["Gria2"], color_by="state") mv.dynamic_plot(adata_result, genes=["Grin2b"], color_by="state") ``` -------------------------------- ### multivelo.pie_summary(adata, genes=None) Source: https://multivelo.readthedocs.io/en/latest/multivelo.pie_summary.html Plots a pie chart representing the distribution of gene directions and models, such as induction-only, repression-only, and complete models. ```APIDOC ## multivelo.pie_summary ### Description This function creates a pie chart to summarize the directions and models of genes within an AnnData object. It categorizes genes into groups like induction-only, repression-only, model 1 complete, and model 2 complete. ### Parameters - **adata** (AnnData) - Required - Anndata result from dynamics recovery. - **genes** (str, list of str) - Optional (default: None) - If None, will use all fitted genes. ``` -------------------------------- ### multivelo.pie_summary Source: https://multivelo.readthedocs.io/en/latest/_sources/multivelo.pie_summary.rst.txt The pie_summary function is used to generate a summary of data represented as a pie chart. It is part of the multivelo module. ```APIDOC ## multivelo.pie_summary ### Description Generates a summary of data in a pie chart format. ### Signature `multivelo.pie_summary()` ``` -------------------------------- ### Generate Dynamic Gene Plots (Fig 4e) Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig4.html Creates dynamic plots for a list of genes, colored by their state. ```python genes = ["Wnt3", "Dsc1", "Cux1", "Dlx3", "Cobll1"] for gene in genes: mv.dynamic_plot(adata_result, genes=gene, color_by="state") ``` -------------------------------- ### Export Cells and Load Seurat Neighbors Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig3.html Export cell names for external processing and load precomputed Seurat WNN neighbors. ```python # Write out filtered cells and prepare to run Seurat WNN --> R script can be found on Github. adata_rna.obs_names.to_frame().to_csv('filtered_cells.txt', header=False, index=False) ``` ```python # Read in Seurat WNN neighbors. nn_idx = np.loadtxt("seurat_wnn/nn_idx.txt", delimiter=',') nn_dist = np.loadtxt("seurat_wnn/nn_dist.txt", delimiter=',') nn_cells = pd.Index(pd.read_csv("seurat_wnn/nn_cells.txt", header=None)[0]) # Make sure cell names match. np.all(nn_cells == adata_atac.obs_names) ``` -------------------------------- ### Import required libraries Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig3.html Imports necessary data science and bioinformatics libraries for the analysis. ```python import os import scipy import numpy as np import pandas as pd import scanpy as sc import scvelo as scv import sys import multivelo as mv import matplotlib.pyplot as plt ``` -------------------------------- ### Preprocess Time-Series Data Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig4.html Normalizes and bins non-time data based on time intervals to prepare for DTW analysis. ```python from pandas import DataFrame # preprocess the data before we perform Dynamic Time Warping # arr = an array of non-time data # time = time data # bins = the number of bins we want to put the data into def preprocess(arr, time, bins): # normalize the time data new_time = time / max(time) # multiply the time data by the number of bins we want new_time = new_time*bins # make an arrow of the time data converted into integer bins arr_window = np.floor(new_time) # group our non-time data into our time bins and take the mean df = DataFrame({'arr': arr, 'window': arr_window}) arr_df = df.groupby(['window'], group_keys=False).mean() # our binned data arr2 = np.array(arr_df['arr']) # our time bins arr_t = np.arange(-1, bins, 1) # normalize our non-time data arr_vec = arr2 - min(arr2) arr_vec = arr_vec / max(arr_vec) return arr_t, arr_vec ``` -------------------------------- ### multivelo.calculate_qc_metrics Source: https://multivelo.readthedocs.io/en/latest/_sources/multivelo.calculate_qc_metrics.rst.txt Calculates quality control metrics for the provided dataset. ```APIDOC ## multivelo.calculate_qc_metrics ### Description Calculates quality control metrics for multi-omics data within the multivelo framework. ### Signature `multivelo.calculate_qc_metrics()` ``` -------------------------------- ### multivelo.gen_wnn(adata_rna, adata_adt, dims, nn, random_state=0) Source: https://multivelo.readthedocs.io/en/latest/multivelo.gen_wnn.html Computes the nn_idx and nn_dist matrices necessary for running knn_smooth_chrom(). ```APIDOC ## multivelo.gen_wnn ### Description Computes inputs for KNN smoothing by calculating the nn_idx and nn_dist matrices needed to run knn_smooth_chrom(). ### Parameters - **adata_rna** (AnnData) - Required - RNA anndata object. - **adata_atac** (AnnData) - Required - ATAC anndata object. - **dims** (List[int]) - Required - Dimensions of data for RNA (index=0) and ATAC (index=1). - **nn** (int) - Optional - Top N neighbors to extract for each cell in the connectivities matrix. - **random_state** (int) - Optional - Random seed for reproducibility (default: 0). ### Returns - **nn_idx** (np.darray) - KNN index matrix of size (cells, k). - **nn_dist** (np.darray) - KNN distance matrix of size (cells, k). ``` -------------------------------- ### Generate gene scatter plots with MultiVelo Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig6.html Visualizes gene expression patterns for a specified list of genes using the scatter_plot function. ```python gene_list = ["ROBO2", "MEF2C"] mv.scatter_plot(adata_result, color_by='c', genes=gene_list) ``` -------------------------------- ### Generate Velocity Stream Plots Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig5.html Visualize velocity embeddings using MultiVelo or scVelo plotting functions. ```python mv.velocity_embedding_stream(adata_result, basis='umap', color='leiden', show=True) ``` ```python scv.pl.velocity_embedding_stream(adata_result, basis='umap', color='leiden') ``` -------------------------------- ### recover_dynamics_chrom() Source: https://multivelo.readthedocs.io/en/latest/multivelo.recover_dynamics_chrom.html Optimizes the joint chromatin and RNA model parameters in ODE solutions. ```APIDOC ## recover_dynamics_chrom(adata_rna, adata_atac=None, gene_list=None, max_iter=5, init_mode='invert', device='cpu', neural_net=False, adam=False, adam_lr=None, adam_beta1=None, adam_beta2=None, batch_size=None, model_to_run=None, plot=False, parallel=True, n_jobs=None, save_plot=False, plot_dir=None, rna_only=False, fit=True, fit_decoupling=True, n_anchors=500, k_dist=1, thresh_multiplier=1.0) ### Description Multi-omic dynamics recovery. This function optimizes the joint chromatin and RNA model parameters in ODE solutions. ### Parameters - **adata_rna** (AnnData) - Required - RNA anndata object. Required fields: Mu, Ms, and connectivities. - **adata_atac** (AnnData) - Optional - ATAC anndata object. Required fields: Mc. - **gene_list** (str, list of str) - Optional - Genes to use for model fitting. - **max_iter** (int) - Optional - Iterations to run for parameter optimization. - **init_mode** (str) - Optional - Initialization method for switch times ('invert', 'grid', 'simple'). - **device** (str) - Optional - The CUDA device for pytorch tensor calculations. - **neural_net** (bool) - Optional - Whether to run time predictions with a neural network. - **adam** (bool) - Optional - Whether MSE minimization is handled by the Adam algorithm. - **adam_lr** (float) - Optional - Learning rate for Adam algorithm. - **adam_beta1** (float) - Optional - Beta1 parameter for Adam algorithm. - **adam_beta2** (float) - Optional - Beta2 parameter for Adam algorithm. - **batch_size** (int) - Optional - Number of cells to use per run of MSE when running the Adam algorithm. - **model_to_run** (int or list of int) - Optional - User specified models for each gene. - **plot** (bool or None) - Optional - Whether to interactively plot the 3D gene portraits. - **parallel** (bool) - Optional - Whether to fit genes in a parallel fashion. - **n_jobs** (int) - Optional - Number of parallel jobs. - **save_plot** (bool) - Optional - Whether to save the fitted gene portrait figures as files. - **plot_dir** (str) - Optional - Directory to save the plots. - **rna_only** (bool) - Optional - Whether to only use RNA for fitting. - **fit** (bool) - Optional - Whether to fit the models. - **fit_decoupling** (bool) - Optional - Whether to fit decoupling phase. - **n_anchors** (int) - Optional - Number of anchor time-points to generate. - **k_dist** (int) - Optional - Number of anchors to use to determine a cell’s gene time. - **thresh_multiplier** (float) - Optional - Multiplier for the heuristic threshold of partial versus complete trajectory pre-determination. ``` -------------------------------- ### Plot phase portraits Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Demo.html Generates phase portraits for different planes (us, cu, cus) to visualize gene dynamics. ```python # Unspliced-spliced phase portraits, colored by celltype. mv.scatter_plot(adata_result, gene_list, color_by='celltype', by='us', axis_on=False, frame_on=False) ``` ```python # Unspliced-spliced phase portraits, colored by log chromatin accessibility. # title_more_info shows more information in each subplot title: model, direction, and likelihood. mv.scatter_plot(adata_result, gene_list, color_by='c', by='us', cmap='coolwarm', title_more_info=True, axis_on=False, frame_on=False) ``` ```python # Chromatin-unspliced phase portraits, colored by celltype. mv.scatter_plot(adata_result, gene_list, color_by='celltype', by='cu', axis_on=False, frame_on=False) ``` ```python # 3D phase portraits, colored by celltype. mv.scatter_plot(adata_result, gene_list, color_by='celltype', by='cus', axis_on=False, downsample=2) ``` -------------------------------- ### Copy RNA Data Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig6.html Create a copy of the RNA AnnData object for dynamical modeling. ```python adata_rna_scv = adata_rna.copy() ``` -------------------------------- ### Generate UMAP Plots (Fig 3b) Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig3.html Create UMAP visualizations for specific genes across different layers. ```python from matplotlib import colors cmap = colors.ListedColormap(['tab:red', 'tab:orange', 'tab:green', 'tab:blue']) bounds=[-0.5,0.5,1.5,2.5,3.5] norm = colors.BoundaryNorm(bounds, cmap.N) genes = ["Robo2", "Gria2", "Grin2b"] layers = ["ATAC", "Mu", "fit_state"] colors = ["plasma", "plasma", cmap] norms = [None, None, norm] plt.figure() i = 0 for layer in layers: titles = [] for gene in genes: titles.append(gene + " " + layer) sc.pl.umap(adata_result, color=genes, layer=layer, color_map=colors[i], title=titles, norm=norms[i]) i += 1 ``` -------------------------------- ### Save and load analysis results Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Demo.html Persists the resulting AnnData object to disk and reloads it for downstream analysis. ```python # Save the result for use later on adata_result.write("multivelo_result.h5ad") ``` ```python adata_result = sc.read_h5ad("multivelo_result.h5ad") ``` -------------------------------- ### Compute Velocity Graph and Latent Time Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig6.html Calculate the velocity graph and latent time for the MultiVelo result object. ```python mv.velocity_graph(adata_result) mv.latent_time(adata_result) ``` -------------------------------- ### Notebook Cell Markers Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Demo.html Markers used to denote cell blocks in the demonstration notebook. ```text [1]: ``` ```text [2]: ``` -------------------------------- ### multivelo.aggregate_peaks_10x(adata_atac, peak_annot_file, linkage_file, peak_dist=10000, min_corr=0.5, gene_body=False, return_dict=False, parallel=False, n_jobs=1) Source: https://multivelo.readthedocs.io/en/latest/multivelo.aggregate_peaks_10x.html Aggregates promoter and enhancer peaks to genes based on the 10X linkage file. ```APIDOC ## multivelo.aggregate_peaks_10x ### Description Aggregates promoter and enhancer peaks to genes based on the 10X linkage file. ### Parameters - **adata_atac** (AnnData) - Required - ATAC anndata object which stores raw peak counts. - **peak_annot_file** (str) - Required - Peak annotation file from 10X CellRanger ARC. - **linkage_file** (str) - Required - Peak-gene linkage file from 10X CellRanger ARC. - **peak_dist** (int) - Optional (default: 10000) - Maximum distance for peaks to be included for a gene. - **min_corr** (float) - Optional (default: 0.5) - Minimum correlation for a peak to be considered as enhancer. - **gene_body** (bool) - Optional (default: False) - Whether to add gene body peaks to the associated promoters. - **return_dict** (bool) - Optional (default: False) - Whether to return promoter and enhancer dictionaries. - **parallel** (bool) - Optional (default: False) - Whether to run in parallel. - **n_jobs** (int) - Optional (default: 1) - Number of jobs for parallel processing. ### Returns - A new ATAC anndata object which stores gene aggregated peak counts. - If return_dict is True, returns a dictionary storing genes and promoter peaks, and a dictionary storing genes and enhancer peaks. ``` -------------------------------- ### multivelo.velocity_embedding_stream(adata, vkey='velo_s', show=True, **kwargs) Source: https://multivelo.readthedocs.io/en/latest/multivelo.velocity_embedding_stream.html Plots a velocity streamplot using scvelo.pl.velocity_embedding_stream. ```APIDOC ## velocity_embedding_stream(adata, vkey='velo_s', show=True, **kwargs) ### Description Plots a velocity streamplot using scvelo.pl.velocity_embedding_stream. ### Parameters - **adata** (AnnData) - Required - Anndata result from dynamics recovery. - **vkey** (str) - Optional (default: 'velo_s') - Default to use spliced velocities. The normalized matrix will be used. - **show** (bool) - Optional (default: True) - Whether to show the plot. - **kwargs** (dict) - Optional - Additional parameters passed to scvelo.tl.velocity_graph. ### Returns - **matplotlib.axes.Axes** - If show is set to False, returns a matplotlib axis object. ``` -------------------------------- ### Save MultiVelo Results Source: https://multivelo.readthedocs.io/en/latest/adam_example.html Persists the resulting AnnData object to an h5ad file. ```python # Save the result for use later on adata_result.write("multivelo_result_fig6_adam.h5ad") ``` -------------------------------- ### Run Multi-omic Dynamics with Adam Source: https://multivelo.readthedocs.io/en/latest/adam_example.html Executes the recover_dynamics_chrom function with the Adam algorithm enabled on a CUDA device. ```python # This will take a while. Parallelization is high recommended. mv.settings.VERBOSITY = 0 adata_result = mv.recover_dynamics_chrom(adata_rna, adata_atac, max_iter=5, init_mode="invert", parallel=True, n_jobs = 10, save_plot=False, rna_only=False, fit=True, n_anchors=500, adam=True, device="cuda:0", adam_lr=7e-3, adam_beta1=0.9, adam_beta2=0.99, batch_size=1024, extra_color_key='cluster' ) ``` -------------------------------- ### Generate heatmaps for model-specific genes Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig2.html Filters genes by fit model and displays heatmaps using scVelo's plotting utility. ```python # get the model 1 genes adata1 = adata_result[:, adata_result.var['fit_model'].values == 1] # get the model 2 genes adata2 = adata_result[:, adata_result.var['fit_model'].values == 2] # heatmaps! scv.pl.heatmap(adata1, var_names=adata1.var_names, col_color='celltype', figsize=(8, 5)) scv.pl.heatmap(adata2, var_names=adata2.var_names, col_color='celltype', figsize=(8, 5)) ``` -------------------------------- ### Run multi-omic dynamical model Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Demo.html Executes the MultiVelo dynamical model recovery, which integrates RNA and ATAC data. Parallelization is recommended for performance. ```python # This will take a while. Parallelization is high recommended. mv.settings.VERBOSITY = 0 adata_result = mv.recover_dynamics_chrom(adata_rna, adata_atac, max_iter=5, init_mode="invert", parallel=True, save_plot=False, rna_only=False, fit=True, n_anchors=500, extra_color_key='celltype' ) ``` -------------------------------- ### Subset AnnData by lineage Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig5.html Defines boolean masks for myeloid, erythrocyte, and platelet lineages based on leiden clusters. ```python # variables for subsetting the AnnData object to just the myeloid lineage hsc_check = adata_result.obs['leiden'] == "HSC" mpp_check = adata_result.obs['leiden'] == "MPP" lmpp_check = adata_result.obs['leiden'] == "LMPP" gmp_check = adata_result.obs['leiden'] == "GMP" myeloid_check = (hsc_check | mpp_check | lmpp_check | gmp_check) # variables for subsetting the AnnData object to just the erythrocyte lineage erythrocyte_check = adata_result.obs['leiden'] == "Erythrocyte" mep_check = adata_result.obs['leiden'] == "MEP" hsc_check = adata_result.obs['leiden'] == "HSC" progdc_check = adata_result.obs['leiden'] == "ProgDC" erythroid_check = (erythrocyte_check | mep_check | hsc_check | progdc_check) # variables for subsetting the AnnData object to just the platelet lineage platelet_check = adata_result.obs['leiden'] == "Platelet" progmk_check = adata_result.obs['leiden'] == "Prog MK" mep_check = adata_result.obs['leiden'] == "MEP" platelet_lineage_check = (platelet_check | progmk_check | mep_check | hsc_check) ``` -------------------------------- ### Perform Leiden Clustering Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig3.html Executes Leiden clustering on the provided AnnData object. ```python sc.tl.leiden(adata_result) ``` -------------------------------- ### Generate Scatter Plots for Genes (Fig 2d) Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig2.html Create scatter plots for specific genes using both 'us' and 'cu' modes. ```python gene_list = ["Eomes", "Tle4"] mv.scatter_plot(adata_result, by='us', show_anchors=False, color_by='celltype', genes=gene_list) mv.scatter_plot(adata_result, by='cu', show_anchors=False, color_by='celltype', genes=gene_list) ``` -------------------------------- ### multivelo.latent_time(adata, vkey='velo_s', **kwargs) Source: https://multivelo.readthedocs.io/en/latest/multivelo.latent_time.html Computes latent time for an AnnData object using scvelo.tl.latent_time. ```APIDOC ## multivelo.latent_time ### Description Computes latent time for the provided AnnData object. This function acts as a wrapper for scvelo.tl.latent_time. ### Parameters - **adata** (AnnData) - Required - Anndata result from dynamics recovery. - **vkey** (str) - Optional (default: 'velo_s') - The key to use for spliced velocities. - **kwargs** (dict) - Optional - Additional parameters passed to scvelo.tl.latent_time. ### Returns - **Returns** (Any) - Outputs of scvelo.tl.latent_time. ``` -------------------------------- ### Examine Count Distribution Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig2.html Optional visualization of total count distribution to identify outliers. ```python # Let's examine the total count distribution and remove outliers. # plt.hist(adata_atac.X.sum(1), bins=100, range=(0, 100000)); ``` -------------------------------- ### Load and apply cell annotations Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig3.html Reads cell annotations from a TSV file and applies them to the AnnData object. ```python # Load cell annotations cell_annot = pd.read_csv('cell_annotations.tsv', sep='\t', index_col=0) ``` ```python adata_rna = adata_rna[cell_annot.index,:] adata_rna.obs['celltype'] = cell_annot['celltype'] ``` -------------------------------- ### Recover MultiVelo Dynamics Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig6.html Execute the MultiVelo dynamics recovery process using both RNA and ATAC data. ```python # This will take a while. Parallelization is high recommended. mv.settings.VERBOSITY = 0 adata_result = mv.recover_dynamics_chrom(adata_rna, adata_atac, max_iter=5, init_mode="invert", parallel=True, n_jobs = 15, save_plot=False, rna_only=False, fit=True, n_anchors=500, extra_color_key='cluster' ) ``` -------------------------------- ### Subset lineages Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig3.html Subsets the data to focus on specific neural lineages. ```python # We subset for lineages towards neurons and astrocytes. adata_rna = adata_rna[adata_rna.obs['celltype'].isin(['RG, Astro, OPC', 'IPC', 'V-SVZ', 'Upper Layer', 'Deeper Layer', 'Ependymal cells', 'Subplate'])] adata_rna ``` -------------------------------- ### Perform DTW Alignment Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig4.html Executes Dynamic Time Warping with asymmetric step patterns to align data layers and plots the results. ```python # perform DTW for the data and plot cs_aligned = dtw(c_a, s_a, keep_internals=True, open_end=True, open_begin=True, step_pattern="asymmetric") cs_aligned.plot(type="twoway", label=["c", "s"]) us_aligned = dtw(u_a, s_a, keep_internals=True, open_end=True, open_begin=True, step_pattern="asymmetric") us_aligned.plot(type="twoway") ``` -------------------------------- ### multivelo.likelihood_plot Source: https://multivelo.readthedocs.io/en/latest/_sources/multivelo.likelihood_plot.rst.txt Visualizes the likelihood of the model fit. ```APIDOC ## multivelo.likelihood_plot ### Description Plots the likelihood of the model fit for the provided data. ### Signature `multivelo.likelihood_plot()` ``` -------------------------------- ### Define data paths and URLs Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig6.html Specifies the remote URLs and local file paths for the RNA and ATAC-seq datasets. ```python rna_url = "https://figshare.com/ndownloader/files/40064350" atac_url = "https://figshare.com/ndownloader/files/40064347" rna_path = "human_brain_rna_after_filt_r2.h5ad" atac_path = "human_brain_atac_gene_after_filt_r2.h5ad" ``` -------------------------------- ### Visualize Velocity and Latent Time Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig6.html Generate plots for velocity embeddings and latent time distributions. ```python mv.velocity_embedding_stream(adata_result, basis='umap', color='cluster', show=True) ``` ```python scv.pl.scatter(adata_result, color='latent_time', color_map='gnuplot', size=80) ``` ```python scv.pl.velocity_embedding_stream(adata_result, basis='umap', color='cluster') ``` -------------------------------- ### multivelo.scatter_plot(adata, genes, ...) Source: https://multivelo.readthedocs.io/en/latest/multivelo.scatter_plot.html Generates phase portraits for specified genes using an AnnData object. ```APIDOC ## multivelo.scatter_plot(adata, genes, by='us', color_by='state', n_cols=5, axis_on=True, frame_on=True, show_anchors=True, show_switches=True, show_all_anchors=False, title_more_info=False, velocity_arrows=False, downsample=1, figsize=None, pointsize=2, markersize=5, linewidth=2, cmap='coolwarm', view_3d_elev=None, view_3d_azim=None, full_name=False) ### Description Plots phase portraits of the specified plane for given genes. ### Parameters - **adata** (AnnData) - Required - Anndata result from dynamics recovery. - **genes** (str, list of str) - Required - List of genes to plot. - **by** (str) - Optional (default: 'us') - Plot unspliced-spliced plane if 'us', chromatin-unspliced if 'cu', or 3D phase portraits if 'cus'. - **color_by** (str) - Optional (default: 'state') - Color by state or other keys present in .uns. - **n_cols** (int) - Optional (default: 5) - Number of columns to plot on each row. - **axis_on** (bool) - Optional (default: True) - Whether to show axis labels. - **frame_on** (bool) - Optional (default: True) - Whether to show plot frames. - **show_anchors** (bool) - Optional (default: True) - Whether to display anchors. - **show_switches** (bool) - Optional (default: True) - Whether to show switch times. - **show_all_anchors** (bool) - Optional (default: False) - Whether to display full range of anchors. - **title_more_info** (bool) - Optional (default: False) - Whether to display model, direction, and likelihood info in title. - **velocity_arrows** (bool) - Optional (default: False) - Whether to show velocity arrows. - **downsample** (int) - Optional (default: 1) - Downsampling factor for cells. - **figsize** (tuple) - Optional (default: None) - Total figure size. - **pointsize** (float) - Optional (default: 2) - Point size for scatter plots. - **markersize** (float) - Optional (default: 5) - Point size for switch time points. - **linewidth** (float) - Optional (default: 2) - Line width for connected anchors. - **cmap** (str) - Optional (default: 'coolwarm') - Color map for continuous color keys. - **view_3d_elev** (float) - Optional (default: None) - Matplotlib 3D plot elev argument. - **view_3d_azim** (float) - Optional (default: None) - Matplotlib 3D plot azim argument. - **full_name** (bool) - Optional (default: False) - Show full names for chromatin, unspliced, and spliced. ``` -------------------------------- ### Load Cell Annotations Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig2.html Reads cell annotations from a TSV file. ```python # Load cell annotations cell_annot = pd.read_csv('cell_annotations.tsv', sep='\t', index_col=0) ``` -------------------------------- ### Visualize Cell States via Scatter Plot Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig3.html Generates a scatter plot visualizing the calculated state counts for specific cell types. ```python colors = ['state0 count','state1 count','state2 count','state3 count'] titles = ['Primed state count', "Coupled-on state count", "Decoupled state count", "Coupled-off state count"] remove_cells = adata_result.obs['celltype'] != 'RG, Astro, OPC' scv.pl.scatter(adata_result[remove_cells, :], color=colors, size=30, frameon=True, color_map="coolwarm", title=titles) ``` -------------------------------- ### Annotate and Visualize RNA Clusters Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig3.html Assign cell type annotations and visualize clusters using UMAP. ```python adata_rna.obs['celltype'] = cell_annot.loc[adata_rna.obs_names, 'celltype'] adata_rna.obs['celltype'] = adata_rna.obs['celltype'].astype('category') ``` ```python # Reorder the categories for color consistency with the manuscript. all_clusters = ['Upper Layer', 'Deeper Layer', 'V-SVZ', 'RG, Astro, OPC', 'Ependymal cells', 'IPC', 'Subplate'] adata_rna.obs['celltype'] = adata_rna.obs['celltype'].cat.reorder_categories(all_clusters) ``` ```python scv.tl.umap(adata_rna) scv.pl.umap(adata_rna, color='celltype') ``` -------------------------------- ### Visualize UMAP Source: https://multivelo.readthedocs.io/en/latest/MultiVelo_Fig2.html Computes and plots UMAP embedding for the RNA dataset. ```python scv.tl.umap(adata_rna) scv.pl.umap(adata_rna, color='celltype') ```