### Install GeneTrajectory R Package Source: https://github.com/klugerlab/genetrajectory/blob/main/README.md Installs the GeneTrajectory package from GitHub using devtools. Ensure devtools is installed first. ```r install.packages("devtools") devtools::install_github("KlugerLab/GeneTrajectory") ``` -------------------------------- ### Load and Preprocess Example Data Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/articles/GeneTrajectory.html Imports a preprocessed Seurat object and relabels cell types for visualization. This step requires the 'human_myeloid_seurat_obj.rds' file. ```r # Import the tutorial dataset and relabel the celltypes for visualization data_S <- readRDS("../../data/human_myeloid_seurat_obj.rds") cluster_relabel <- c("0" = "CD14+ monocytes", "1" = "Intermediate monocytes", "2" = "CD16+ monocytes", "3" = "Myeloid type-2 dendritic cells") data_S$celltype <- cluster_relabel[as.character(data_S$cluster)] DimPlot(data_S, group.by = "celltype", shuffle = T) ``` -------------------------------- ### Setup Python Virtual Environment for Gene Trajectory Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/articles/fast_computation.html Creates and activates a Python virtual environment named 'gene_trajectory' using reticulate, installing the 'gene_trajectory' package. This is necessary for using Python-based gene distance computation functions within R. ```r # Create a virtualenv using reticulate for gene-gene distance computation if(!reticulate::virtualenv_exists('gene_trajectory')){ reticulate::virtualenv_create('gene_trajectory', packages=c('gene_trajectory')) } reticulate::use_virtualenv('gene_trajectory') # Import the function to compute gene-gene distances cal_ot_mat_from_numpy <- reticulate::import('gene_trajectory.compute_gene_distance_cmd')$cal_ot_mat_from_numpy ``` -------------------------------- ### Create and Use Python Virtual Environment for GeneTrajectory Source: https://github.com/klugerlab/genetrajectory/blob/main/README.md Creates a new Python virtual environment named 'gene_trajectory' and installs the 'gene_trajectory' package into it. If the environment already exists, it will be used. ```r if(!reticulate::virtualenv_exists('gene_trajectory')){ reticulate::virtualenv_create('gene_trajectory', packages=c('gene_trajectory')) } reticulate::use_virtualenv('gene_trajectory') ``` -------------------------------- ### Install GeneTrajectory Development Version from GitHub Source: https://github.com/klugerlab/genetrajectory/blob/main/README.md Installs the latest development version of the 'gene-trajectory' Python package directly from its GitHub repository. This method works for both virtualenv and conda environments. ```r system(sprintf('%s -m pip install git+https://github.com/Klugerlab/GeneTrajectory-python.git', reticulate::py_exe())) ``` -------------------------------- ### Load Required R Libraries Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/articles/fast_computation.html Loads essential R libraries for data manipulation, visualization, and GeneTrajectory analysis. Ensure these packages are installed before running. ```r require(Seurat) require(scales) require(ggplot2) require(viridis) require(dplyr) require(GeneTrajectory) require(Matrix) require(plot3D) require(FNN) ``` -------------------------------- ### Add GeneTrajectory to Existing Python Virtual Environment Source: https://github.com/klugerlab/genetrajectory/blob/main/README.md Installs the 'gene-trajectory' Python package into an existing virtual environment using reticulate. ```r reticulate::py_install("gene-trajectory") ``` -------------------------------- ### Full Workflow Example for Gene Trajectory Analysis Source: https://context7.com/klugerlab/genetrajectory/llms.txt An end-to-end pipeline for single-cell RNA sequencing data analysis using GeneTrajectory and Seurat. This includes data loading, preprocessing, diffusion map computation, coarse-graining, Wasserstein distance calculation, gene embedding, trajectory extraction, and visualization. ```r library(Seurat) library(GeneTrajectory) library(reticulate) library(ggplot2) library(scales) library(plot3D) # 1. Load and preprocess data data_S <- readRDS("human_myeloid_seurat_obj.rds") # 2. Select variable genes assay <- "RNA" DefaultAssay(data_S) <- assay data_S <- FindVariableFeatures(data_S, nfeatures = 500) all_genes <- data_S@assays[[assay]]@var.features expr_percent <- apply(as.matrix(data_S[[assay]]@data[all_genes, ]) > 0, 1, sum) / ncol(data_S) genes <- all_genes[which(expr_percent > 0.01 & expr_percent < 0.5)] # 3. Compute diffusion map and graph distance data_S <- RunDM(data_S) cell.graph.dist <- GetGraphDistance(data_S, K = 10) # 4. Coarse-grain for efficiency cg_output <- CoarseGrain(data_S, cell.graph.dist, genes, N = 500) # 5. Compute gene-gene Wasserstein distances (requires Python) use_virtualenv('gene_trajectory') cal_ot_mat <- import('gene_trajectory.compute_gene_distance_cmd')$cal_ot_mat_from_numpy gene.dist.mat <- cal_ot_mat( ot_cost = cg_output[["graph.dist"]], gene_expr = cg_output[["gene.expression"]], num_iter_max = 50000 ) rownames(gene.dist.mat) <- colnames(gene.dist.mat) <- cg_output[["features"]] # 6. Generate gene embedding and extract trajectories gene_embedding <- GetGeneEmbedding(gene.dist.mat, K = 5)$diffu.emb gene_trajectory <- ExtractGeneTrajectory(gene_embedding, gene.dist.mat, N = 3, t.list = c(4, 7, 7), K = 5) # 7. Visualize gene trajectories in 3D scatter3D( gene_embedding[, 1], gene_embedding[, 2], gene_embedding[, 3], bty = "b2", colvar = as.integer(as.factor(gene_trajectory$selected)) - 1, col = ramp.col(c(hue_pal()(3))), main = "Gene Trajectories", pch = 19, cex = 1 ) # 8. Add gene bin scores and visualize on cells data_S <- AddGeneBinScore(data_S, gene_trajectory, N.bin = 5, trajectories = 1:3, assay = "RNA") FeaturePlot(data_S, features = paste0("Trajectory1_genes", 1:5), ncol = 5) ``` -------------------------------- ### Install GeneTrajectory using Pip in Conda Environment Source: https://github.com/klugerlab/genetrajectory/blob/main/README.md Installs the 'gene-trajectory' Python package using pip within a conda environment. This command is executed via R's system() function, ensuring compatibility with reticulate's Python executable. ```r system(sprintf('%s -m pip install gene-trajectory', reticulate::py_exe())) ``` -------------------------------- ### Import Tutorial Dataset and Preprocess Genes Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/articles/fast_computation.html Imports a preprocessed Seurat object and identifies genes for analysis based on expression percentage among the top variable genes. This step prepares the data for subsequent distance computations. ```r # Import the tutorial dataset data_S <- readRDS("../../data/human_myeloid_seurat_obj.rds") # In this tutorial, we demonstrate gene-gene distance computation by selecting the genes expressed by 1% to 50% of cells among the top 500 variable genes. assay <- "RNA" DefaultAssay(data_S) <- assay data_S <- FindVariableFeatures(data_S, nfeatures = 500) all_genes <- data_S@assays[[assay]]@var.features expr_percent <- apply(as.matrix(data_S[[assay]]@data[all_genes, ]) > 0, 1, sum)/ncol(data_S) genes <- all_genes[which(expr_percent > 0.01 & expr_percent < 0.5)] length(genes) ``` -------------------------------- ### Display Session Information Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/articles/fast_computation.html Prints the current R session information, including version, platform, locale, and attached packages. This is useful for reproducibility. ```R sessionInfo() ``` -------------------------------- ### simulate_linear() Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/reference/index.html Simulates a linear gene process. ```APIDOC ## simulate_linear() ### Description Simulate linear gene process. ### Method Not specified ### Endpoint Not specified ### Parameters Not specified ### Request Example Not specified ### Response Not specified ``` -------------------------------- ### Gene-Gene Distance Computation with Python Source: https://context7.com/klugerlab/genetrajectory/llms.txt Computes pairwise Wasserstein distances between gene distributions using Python's Optimal Transport library. This requires the `gene_trajectory` Python package to be installed and accessible via `reticulate`. ```APIDOC ## Gene-Gene Distance Computation with Python ### Description Computes pairwise Wasserstein distances between gene distributions using Python's Optimal Transport library. Requires the `gene_trajectory` Python package installed via reticulate. ### Method `cal_ot_mat_from_numpy` (imported from Python) ### Setup Ensure the `gene_trajectory` Python package is installed in a virtual environment accessible by `reticulate`. ### Request Example ```r library(reticulate) # Set up Python virtual environment with gene_trajectory package if (!reticulate::virtualenv_exists('gene_trajectory')) { reticulate::virtualenv_create('gene_trajectory', packages = c('gene_trajectory')) } reticulate::use_virtualenv('gene_trajectory') # Import the Python function for Wasserstein distance computation cal_ot_mat_from_numpy <- reticulate::import('gene_trajectory.compute_gene_distance_cmd')$cal_ot_mat_from_numpy # Example usage (assuming cg_gene_expression and cg_graph_dist are available) # gene_dist_matrix <- cal_ot_mat_from_numpy(cg_gene_expression, cg_graph_dist) ``` ### Response A matrix of pairwise Wasserstein distances between gene distributions. ``` -------------------------------- ### simulate_bifurcation() Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/reference/index.html Simulates a bifurcating gene process. ```APIDOC ## simulate_bifurcation() ### Description Simulate bifurcating gene process. ### Method Not specified ### Endpoint Not specified ### Parameters Not specified ### Request Example Not specified ### Response Not specified ``` -------------------------------- ### simulate_cyclic() Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/reference/index.html Simulates a cyclic gene process. ```APIDOC ## simulate_cyclic() ### Description Simulate cyclic gene process. ### Method Not specified ### Endpoint Not specified ### Parameters Not specified ### Request Example Not specified ### Response Not specified ``` -------------------------------- ### simulate_linear Source: https://context7.com/klugerlab/genetrajectory/llms.txt Generates a simulated gene-by-cell count matrix representing a linear developmental process. Genes are modeled to peak at different pseudotime points. ```APIDOC ## simulate_linear ### Description Generates a simulated gene-by-cell count matrix representing a linear developmental process where genes peak at different pseudotime points. ### Method `simulate_linear` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **N_cells** (integer) - Number of cells. Default is 1000. - **N_genes** (integer) - Number of genes. Default is 200. - **model** (character) - Count model: "poisson" or "negbin". Default is "poisson". - **meanlog** (numeric) - Log-normal mean for gene parameters. Default is 0. - **sdlog** (numeric) - Log-normal SD for gene parameters. Default is 0.25. - **scale** (numeric) - Scale of UMI counts. Default is 25. - **seed** (integer) - Random seed for reproducibility. Default is 1. - **maxT** (numeric) - Maximum pseudotime value. Default is 15. - **sort** (logical) - Whether to sort genes by peak time. Default is TRUE. - **sparsity** (numeric) - Sparsity level (NULL for no sparsification). Default is 0.1. - **theta** (numeric) - Dispersion for negative binomial. Default is 10. ### Request Example ```r # Simulate linear trajectory data gc_mat <- simulate_linear( N_cells = 1000, N_genes = 200, model = "poisson", meanlog = 0, sdlog = 0.25, scale = 25, seed = 1, maxT = 15, sort = TRUE, sparsity = 0.1, theta = 10 ) ``` ### Response #### Success Response (200) - **gc_mat** (matrix) - A gene-by-cell count matrix. #### Response Example ```r dim(gc_mat) head(rownames(gc_mat)) ``` ``` -------------------------------- ### RunDM() Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/reference/index.html Runs Diffusion Map on a Seurat object. ```APIDOC ## RunDM() ### Description Run Diffusion Map on a Seurat object. ### Method Not specified ### Endpoint Not specified ### Parameters Not specified ### Request Example Not specified ### Response Not specified ``` -------------------------------- ### diffusion.map() Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/reference/index.html Runs Diffusion Map on a precomputed distance matrix. ```APIDOC ## diffusion.map() ### Description Run Diffusion Map on a precomputed distance matrix. ### Method Not specified ### Endpoint Not specified ### Parameters Not specified ### Request Example Not specified ### Response Not specified ``` -------------------------------- ### Simulate Bifurcating Gene Process Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/reference/simulate_bifurcation.html Simulates a bifurcating gene process using specified parameters. ```APIDOC ## simulate_bifurcation ### Description Simulate bifurcating gene process. ### Method Not applicable (function call in R) ### Endpoint Not applicable (function call in R) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```R simulate_bifurcation( N_cells = 5 * c(100, 50, 50), N_genes = 5 * c(100, 50, 50), model = "poisson", meanlog = 0, sdlog = 0.25, scale = 25, seed = 1, maxT = 15, sort = TRUE, sparsity = 0.1, theta = 10 ) ``` ### Arguments - **N_cells** (integer vector) - Number of cells in the parent process and two daughter processes - **N_genes** (integer vector) - Number of genes associated with the parent process and two daughter processes - **model** (character) - Count model ("poisson" or "negbin") - **meanlog** (numeric) - Mean of log normal distribution - **sdlog** (numeric) - Standard deviation of log normal distribution - **scale** (numeric) - Scale of UMI counts - **seed** (integer) - Random seed - **maxT** (numeric) - Maximum cell pseudotime - **sort** (boolean) - Whether to sort genes based on their peak times - **sparsity** (numeric) - Sparsity of count matrix - **theta** (numeric) - Dipersion parameter for negative binomial model ### Value Returns a gene-by-cell count matrix ### Response #### Success Response (200) - **count_matrix** (matrix) - A gene-by-cell count matrix #### Response Example ```json { "example": "A gene-by-cell count matrix" } ``` ``` -------------------------------- ### Simulate Cyclic Trajectory Source: https://context7.com/klugerlab/genetrajectory/llms.txt Simulates a cyclic trajectory, such as a cell cycle, with specified parameters for number of cells, genes, model, and sparsity. The output is a matrix of gene expression. ```r gc_mat <- simulate_cyclic( N_cells = 1000, N_genes = 500, model = "poisson", meanlog = 0, sdlog = 0.25, scale_l = 1, # Scale for gene width scale = 25, # Scale for UMI counts seed = 1, maxT = 15, sparsity = 0.1, theta = 10 ) dim(gc_mat) #> [1] 500 1000 ``` -------------------------------- ### coarse.grain() Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/reference/index.html Base function called by CoarseGrain. ```APIDOC ## coarse.grain() ### Description Base function called by CoarseGrain. ### Method Not specified ### Endpoint Not specified ### Parameters Not specified ### Request Example Not specified ### Response Not specified ``` -------------------------------- ### Apply ALRA Imputation for Gene Expression Smoothing Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/articles/GeneTrajectory.html Applies the ALRA (Accelerated, Robust, and Lightweight Imputation) method to smooth gene expression values. Requires SeuratWrappers package. ```R library(SeuratWrappers) data_S <- RunALRA(data_S) ``` -------------------------------- ### Simulate Cyclic Gene Process Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/reference/simulate_cyclic.html The simulate_cyclic function simulates a cyclic gene process by generating a gene-by-cell count matrix. It allows customization of the number of cells, genes, count model, and various simulation parameters. ```APIDOC ## simulate_cyclic ### Description Simulate cyclic gene process ### Method N/A (This is an R function, not a REST API endpoint) ### Endpoint N/A ### Parameters #### Arguments - **N_cells** (integer) - Number of cells - **N_genes** (integer) - Number of genes - **model** (character) - Count model ("poisson" or "negbin") - **meanlog** (numeric) - Mean of log normal distribution - **sdlog** (numeric) - Standard deviation of log normal distribution - **scale_l** (numeric) - Scale of UMI counts (Note: This parameter is present in the function signature but not described in the provided text. It is included here for completeness based on the signature.) - **scale** (numeric) - Scale of UMI counts - **seed** (integer) - Random seed - **maxT** (numeric) - Maximum cell pseudotime - **sparsity** (numeric) - Sparsity of count matrix - **theta** (numeric) - Dispersion parameter for negative binomial model ### Request Example N/A (This is an R function, not a REST API endpoint) ### Response #### Success Response Returns a gene-by-cell count matrix #### Response Example ```R # Example of a gene-by-cell count matrix structure (actual values will vary) matrix(data = sample(0:100, 1000*500, replace = TRUE), nrow = 500, ncol = 1000) ``` ``` -------------------------------- ### simulate_coral Function Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/reference/simulate_coral.html Simulates a multi-level lineage differentiation process coupled with cell cycle. ```APIDOC ## simulate_coral ### Description Simulate a multi-level lineage differentiation process coupled with cell cycle. ### Method N/A (This is an R function, not a REST API endpoint) ### Endpoint N/A ### Parameters #### Arguments - **N_cells** (integer vector) - Number of cells associated with the differentiation process - **N_genes** (integer vector) - Number of genes associated with the cell cycle process - **N_genes_CC** (integer) - Number of genes associated with the cell cycle process - **model** (character) - Count model ("poisson" or "negbin") - **meanlog** (numeric) - Mean of log normal distribution - **sdlog** (numeric) - Standard deviation of log normal distribution - **scale** (numeric) - Scale of UMI counts - **scale_l** (numeric) - Scale parameter - **seed** (integer) - Random seed - **maxT** (numeric) - Maximum cell pseudotime of each lineage in the differentiation process - **maxT_CC** (numeric) - Maximum cell pseudotime of the cell cycle process - **sparsity** (numeric) - Sparsity of count matrix - **theta** (numeric) - Dispersion parameter for negative binomial model ### Request Example N/A (This is an R function) ### Response #### Success Response Returns a gene-by-cell count matrix #### Response Example N/A (Output depends on simulation parameters) ``` -------------------------------- ### Prepare Input for Gene-Gene Distance Computation Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/articles/GeneTrajectory.html Computes Diffusion Map embedding, constructs a cell-cell kNN graph with graph distances, and coarse-grains the graph into meta-cells for computational efficiency. Requires the 'genes' object from the previous step. ```r # Compute the Diffusion Map cell embedding data_S <- GeneTrajectory::RunDM(data_S) # Calculate cell-cell graph distances over a cell-cell kNN graph cell.graph.dist <- GetGraphDistance(data_S, K = 10) # Coarse-grain the cell graph by grouping cells into `N`=500 "meta-cells" cg_output <- CoarseGrain(data_S, cell.graph.dist, genes, N = 500) ``` -------------------------------- ### Visualize Gene Trajectories in 3D Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/articles/GeneTrajectory.html Visualizes the gene embedding and trajectories in a 3D scatter plot. Uses scatter3D from the plot3D package and hue_pal from the scales package. ```R par(mar = c(1.5,1.5,1.5,1.5)) scatter3D(gene_embedding[,1], gene_embedding[,2], gene_embedding[,3], bty = "b2", colvar = as.integer(as.factor(gene_trajectory$selected))-1, main = "trajectory", pch = 19, cex = 1, theta = 45, phi = 0, col = ramp.col(c(hue_pal()(3)))) ``` -------------------------------- ### Convert Distance Matrix to Random-Walk Matrix Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/reference/get.RW.matrix.html Use this function to convert a precomputed distance matrix into a random-walk matrix. The adaptive Gaussian kernel bandwidth is determined by the distance to the K-th nearest neighbor. ```R get.RW.matrix(dist.mat, K = 10) ``` -------------------------------- ### Compute Graph Distances with GetGraphDistance Source: https://context7.com/klugerlab/genetrajectory/llms.txt Constructs a cell-cell kNN graph and computes the graph distance matrix. Use this to obtain shortest path lengths between cell pairs based on a dimensional reduction embedding. Requires GeneTrajectory library. ```r library(GeneTrajectory) # Calculate cell-cell graph distances using the diffusion map embedding cell.graph.dist <- GetGraphDistance( object = data_S, reduction = "dm", # Use diffusion map embedding dims = 1:5, # Dimensions to use for kNN construction K = 10 # Number of nearest neighbors ) # Result is a symmetric cell-by-cell distance matrix dim(cell.graph.dist) #> [1] 2500 2500 # Check the largest graph distance (ensures connectivity) max(cell.graph.dist) #> [1] 15 # If disconnected components exist, increase K parameter # Error: "The cell-cell kNN graph has disconnected components. Please increase K." ``` -------------------------------- ### Simulate Linear Gene Trajectory Data Source: https://context7.com/klugerlab/genetrajectory/llms.txt Generates a simulated gene-by-cell count matrix representing a linear developmental process. Allows specifying count model, gene expression parameters, and trajectory properties. Use 'seed' for reproducibility. ```r library(GeneTrajectory) # Simulate linear trajectory data gc_mat <- simulate_linear( N_cells = 1000, # Number of cells N_genes = 200, # Number of genes model = "poisson", # Count model: "poisson" or "negbin" meanlog = 0, # Log-normal mean for gene parameters sdlog = 0.25, # Log-normal SD for gene parameters scale = 25, # Scale of UMI counts seed = 1, # Random seed for reproducibility maxT = 15, # Maximum pseudotime value sort = TRUE, # Sort genes by peak time sparsity = 0.1, # Sparsity level (NULL for no sparsification) theta = 10 # Dispersion for negative binomial ) dim(gc_mat) ``` ```r # Row names are gene peak times, column names are cell pseudotimes head(rownames(gc_mat)) ``` -------------------------------- ### get.RW.matrix Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/reference/get.RW.matrix.html Converts a distance matrix into a random-walk matrix based on an adaptive Gaussian kernel. ```APIDOC ## get.RW.matrix ### Description Convert a distance matrix into a random-walk matrix based on adaptive Gaussian kernel. ### Method GET ### Endpoint /get.RW.matrix ### Parameters #### Query Parameters - **dist.mat** (matrix) - Required - Precomputed distance matrix (symmetric) - **K** (integer) - Optional - Adaptive kernel bandwidth for each point set to be the distance to its `K`-th nearest neighbor. Defaults to 10. ### Response #### Success Response (200) - **Random-walk matrix** (matrix) - The resulting random-walk matrix. ``` -------------------------------- ### Simulate Linear Gene Process Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/reference/simulate_linear.html This function simulates a linear gene expression process, generating a gene-by-cell count matrix. ```APIDOC ## simulate_linear ### Description Simulate linear gene process ### Method Not applicable (R function) ### Endpoint Not applicable (R function) ### Parameters #### Arguments - **N_cells** (integer) - Number of cells - **N_genes** (integer) - Number of genes - **model** (character) - Count model ("poisson" or "negbin") - **meanlog** (numeric) - Mean of log normal distribution - **sdlog** (numeric) - Standard deviation of log normal distribution - **scale** (numeric) - Scale of UMI counts - **seed** (integer) - Random seed - **maxT** (numeric) - Maximum cell pseudotime - **sort** (boolean) - Whether to sort genes based on their peak times - **sparsity** (numeric) - Sparsity of count matrix - **theta** (numeric) - Dispersion parameter for negative binomial model ### Request Example ```R simulate_linear( N_cells = 1000, N_genes = 200, model = "poisson", meanlog = 0, sdlog = 0.25, scale = 25, seed = 1, maxT = 15, sort = TRUE, sparsity = NULL, theta = 10 ) ``` ### Response #### Value Returns a gene-by-cell count matrix ``` -------------------------------- ### Compute Gene-Gene Wasserstein Distances Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/articles/GeneTrajectory.html Computes the Wasserstein distance matrix between genes using POT package. Requires cg_output data. Computation can be time-consuming. ```R cal_ot_mat_from_numpy <- reticulate::import('gene_trajectory.compute_gene_distance_cmd')$cal_ot_mat_from_numpy gene.dist.mat <- cal_ot_mat_from_numpy(ot_cost = cg_output[["graph.dist"]], gene_expr = cg_output[["gene.expression"]], num_iter_max = 50000, show_progress_bar = TRUE) rownames(gene.dist.mat) <- cg_output[["features"]] colnames(gene.dist.mat) <- cg_output[["features"]] dim(gene.dist.mat) ``` -------------------------------- ### Coarse-Grain Cell Graph (N=1000) Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/articles/fast_computation.html Applies cell graph coarse-graining with N=1000 meta-cells. This larger N value increases computation time but potentially preserves more local geometry compared to N=500. ```r cg_output2 <- CoarseGrain(data_S, cell.graph.dist, genes, N = 1000) gene.dist.mat2 <- cal_ot_mat_from_numpy(ot_cost = cg_output2[["graph.dist"]], gene_expr = cg_output2[["gene.expression"]]) ``` -------------------------------- ### Convert Distance Matrix to Random Walk Matrix Source: https://context7.com/klugerlab/genetrajectory/llms.txt Converts a distance matrix into a row-normalized random walk transition matrix using an adaptive Gaussian kernel. Useful for diffusion simulations. The input 'gene.dist.mat' must be a symmetric distance matrix. ```r library(GeneTrajectory) # Convert distance matrix to random walk matrix rw_matrix <- get.RW.matrix( dist.mat = gene.dist.mat, K = 10 # Adaptive kernel bandwidth ) # Result is a row-stochastic matrix (rows sum to 1) dim(rw_matrix) ``` ```r rowSums(rw_matrix)[1:5] ``` ```r # Can be used for diffusion/random walk simulations initial_distribution <- rep(0, nrow(rw_matrix)) initial_distribution[1] <- 1 # Start from first gene # Diffuse for t steps diffused <- initial_distribution for (t in 1:5) { diffused <- as.vector(rw_matrix %*% diffused) } ``` -------------------------------- ### GetGenePseudoorder() Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/reference/index.html Orders genes along a given trajectory. ```APIDOC ## GetGenePseudoorder() ### Description Order genes along a given trajectory. ### Method Not specified ### Endpoint Not specified ### Parameters Not specified ### Request Example Not specified ### Response Not specified ``` -------------------------------- ### Simulate Coral Function Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/reference/simulate_coral.html Use this function to simulate a multi-level lineage differentiation process coupled with cell cycle. It allows customization of cell and gene counts, model type, and simulation parameters. ```R simulate_coral( N_cells = 15 * rep(100, 7), N_genes = 2 * rep(100, 7), N_genes_CC = 400, model = "poisson", meanlog = 0, sdlog = 0.25, scale = 25, scale_l = 2, seed = 1, maxT = 10, maxT_CC = 20, sparsity = NULL, theta = 10 ) ``` -------------------------------- ### simulate_cylinder Function Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/reference/simulate_cylinder.html Simulates concurrent independent linear and cyclic gene processes. ```APIDOC ## simulate_cylinder ### Description Simulate concurrent independent linear and cyclic gene processes. ### Method N/A (This is an R function, not a REST API endpoint) ### Endpoint N/A ### Parameters #### Arguments - **N_cells** (integer) - Number of cells - **N_genes** (integer vector) - Number of genes associated with the linear and cyclic processes - **model** (character) - Count model ("poisson" or "negbin") - **meanlog** (numeric) - Mean of log normal distribution - **sdlog** (numeric) - Standard deviation of log normal distribution - **scale** (numeric) - Scale of UMI counts - **seed** (integer) - Random seed - **maxT** (numeric) - Maximum cell pseudotime - **sort** (boolean) - Whether to sort genes based on their peak times - **sparsity** (numeric) - Sparsity of count matrix - **theta** (numeric) - Dipersion parameter for negative binomial model ### Request Example ```R simulate_cylinder( N_cells = 5000, N_genes = c(500, 500), model = "poisson", meanlog = 0, sdlog = 0.25, scale = 25, seed = 1, maxT = 15, sort = TRUE, sparsity = 0.1, theta = 10 ) ``` ### Response #### Value Returns a gene-by-cell count matrix ``` -------------------------------- ### ExtractGeneTrajectory() Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/reference/index.html Extracts gene trajectories from the data. ```APIDOC ## ExtractGeneTrajectory() ### Description Extract gene trajectories. ### Method Not specified ### Endpoint Not specified ### Parameters Not specified ### Request Example Not specified ### Response Not specified ``` -------------------------------- ### Simulate bifurcating gene process Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/reference/simulate_bifurcation.html Use this function to simulate a gene expression process that bifurcates. It allows customization of cell and gene counts, count model, and simulation parameters. ```R simulate_bifurcation( N_cells = 5 * c(100, 50, 50), N_genes = 5 * c(100, 50, 50), model = "poisson", meanlog = 0, sdlog = 0.25, scale = 25, seed = 1, maxT = 15, sort = TRUE, sparsity = 0.1, theta = 10 ) ``` -------------------------------- ### GetGenePseudoorder Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/reference/GetGenePseudoorder.html Orders genes along a given trajectory. ```APIDOC ## GetGenePseudoorder ### Description Orders genes along a given trajectory. ### Method Not specified (likely an R function call) ### Endpoint Not applicable (R function) ### Parameters #### Arguments - **dist.mat** (matrix) - Required - Gene-gene Wasserstein distance matrix (symmetric) - **subset** (vector) - Required - Genes in a given trajectory - **max.id** (integer) - Optional - Index of the terminal gene ### Value Pseudoorder of genes along a given trajectory ``` -------------------------------- ### GetGraphDistance() Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/reference/index.html Runs Diffusion Map on a Seurat object. ```APIDOC ## GetGraphDistance() ### Description Run Diffusion Map on a Seurat object. ### Method Not specified ### Endpoint Not specified ### Parameters Not specified ### Request Example Not specified ### Response Not specified ``` -------------------------------- ### get.RW.matrix Source: https://context7.com/klugerlab/genetrajectory/llms.txt Converts a distance matrix into a row-normalized random walk transition matrix using an adaptive Gaussian kernel. This is a key step for trajectory inference. ```APIDOC ## get.RW.matrix ### Description Converts a distance matrix into a row-normalized random walk transition matrix using an adaptive Gaussian kernel. Used internally for trajectory extraction. ### Method `get.RW.matrix` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **dist.mat** (matrix) - Symmetric distance matrix. - **K** (integer) - Adaptive kernel bandwidth. Default is 10. ### Request Example ```r # Convert distance matrix to random walk matrix rw_matrix <- get.RW.matrix( dist.mat = gene.dist.mat, K = 10 ) ``` ### Response #### Success Response (200) - **rw_matrix** (matrix) - A row-stochastic matrix representing random walk transitions. #### Response Example ```r dim(rw_matrix) rowSums(rw_matrix)[1:5] ``` ``` -------------------------------- ### Load Precomputed Gene-Gene Distance Matrix Source: https://context7.com/klugerlab/genetrajectory/llms.txt Loads a precomputed gene-gene Wasserstein distance matrix from CSV files. Requires 'emd.csv' and 'gene_names.csv' in the specified directory. Row and column names are automatically assigned. ```r library(GeneTrajectory) # Load precomputed gene-gene distance matrix gene.dist.mat <- LoadGeneDistMat( dir.path = "/path/to/data/", file_name = "emd.csv" # EMD matrix file ) # Also requires "gene_names.csv" in the same directory dim(gene.dist.mat) # Gene names are automatically assigned as row/column names head(rownames(gene.dist.mat)) ``` -------------------------------- ### Simulate concurrent independent linear and cyclic gene processes Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/reference/simulate_cylinder.html Use this function to simulate gene expression data with both linear and cyclic components. It supports Poisson and negative binomial count models. Ensure 'N_genes' is a vector specifying counts for each process type. ```R simulate_cylinder( N_cells = 5000, N_genes = rep(500, 2), model = "poisson", meanlog = 0, sdlog = 0.25, scale = 25, seed = 1, maxT = 15, sort = TRUE, sparsity = 0.1, theta = 10 ) ``` -------------------------------- ### Run Diffusion Map Embedding with RunDM Source: https://context7.com/klugerlab/genetrajectory/llms.txt Computes a Diffusion Map embedding on a Seurat object. Use this to generate a low-dimensional representation of cells for trajectory inference. Requires Seurat and GeneTrajectory libraries. ```r library(Seurat) library(GeneTrajectory) # Load preprocessed Seurat object data_S <- readRDS("human_myeloid_seurat_obj.rds") # Compute Diffusion Map embedding from PCA data_S <- RunDM( object = data_S, reduction = "pca", # Input reduction (default: "pca") dims = 1:30, # PCA dimensions to use K = 10, # Adaptive kernel bandwidth (k-nearest neighbor) n.components = 30, # Number of diffusion map components t = 1 # Number of diffusion times ) # Access the diffusion map embedding dm_embedding <- data_S@reductions[["dm"]]@cell.embeddings head(dm_embedding[, 1:5]) #> DM_1 DM_2 DM_3 DM_4 DM_5 #> AAACCCAAGCCTGAAC -0.0152 0.0234 -0.0089 0.0145 -0.0078 #> AAACCCAAGCTGATAA -0.0187 0.0156 0.0234 -0.0112 0.0098 ``` -------------------------------- ### Visualize Gene Bin Plots Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/articles/GeneTrajectory.html Generates feature plots for gene bin scores across different trajectories. Uses Seurat's FeaturePlot function. ```R FeaturePlot(data_S, pt.size = 0.05, features = paste0("Trajectory",1,"_genes", 1:5), ncol = 5, order = T) & ``` -------------------------------- ### Simulate Bifurcating Gene Trajectory Data Source: https://context7.com/klugerlab/genetrajectory/llms.txt Simulates a bifurcating gene expression process where a parent trajectory splits into two daughter trajectories. Useful for testing trajectory inference on branched data. Specify cell and gene counts for each branch. ```r library(GeneTrajectory) # Simulate bifurcation with parent + 2 daughter processes gc_mat <- simulate_bifurcation( N_cells = c(500, 250, 250), # Cells in parent, daughter1, daughter2 N_genes = c(500, 250, 250), # Genes associated with each process model = "poisson", meanlog = 0, sdlog = 0.25, scale = 25, seed = 1, maxT = 15, sparsity = 0.1, theta = 10 ) dim(gc_mat) ``` -------------------------------- ### Coarse-Grain Cells with CoarseGrain Source: https://context7.com/klugerlab/genetrajectory/llms.txt Reduces computational complexity by grouping cells into meta-cells using k-means clustering. This function prepares gene expression and graph distance matrices for efficient Wasserstein distance computation. Requires Seurat and GeneTrajectory libraries. ```r library(GeneTrajectory) # Select variable genes for analysis assay <- "RNA" DefaultAssay(data_S) <- assay data_S <- FindVariableFeatures(data_S, nfeatures = 500) all_genes <- data_S@assays[[assay]]@var.features # Filter genes by expression percentage (1% to 50% of cells) expr_percent <- apply(as.matrix(data_S[[assay]]@data[all_genes, ]) > 0, 1, sum) / ncol(data_S) genes <- all_genes[which(expr_percent > 0.01 & expr_percent < 0.5)] # Coarse-grain the cell graph into N=500 meta-cells cg_output <- CoarseGrain( object = data_S, graph.dist = cell.graph.dist, features = genes, N = 500, # Number of meta-cells assay = "RNA", reduction = "dm", dims = 1:5, slot = "data", random.seed = 1 ) # Access coarse-grained outputs cg_gene_expression <- cg_output[["gene.expression"]] # Meta-cell x gene matrix cg_graph_dist <- cg_output[["graph.dist"]] # Meta-cell distance matrix feature_names <- cg_output[["features"]] # Gene names dim(cg_gene_expression) #> [1] 500 245 ``` -------------------------------- ### Construct Gene Embeddings using Diffusion Map Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/articles/fast_computation.html Generates gene embeddings using the Diffusion Map algorithm based on precomputed gene-gene distance matrices. These embeddings are used for trajectory analysis and visual comparison. ```R # Construct the gene embedding by employing Diffusion Map gene_embedding1 <- GetGeneEmbedding(gene.dist.mat1, K = 5)$diffu.emb gene_embedding2 <- GetGeneEmbedding(gene.dist.mat2, K = 5)$diffu.emb gene_embedding3 <- GetGeneEmbedding(gene.dist.mat3, K = 5)$diffu.emb ``` -------------------------------- ### Extract Gene Trajectories Source: https://context7.com/klugerlab/genetrajectory/llms.txt Extracts sequential gene trajectories from the gene embedding. Trajectories are defined by terminal genes and genes along the diffusion path. Requires matching 'K' and 'dims' parameters with GetGeneEmbedding. 'quantile' determines the threshold for gene selection. ```r library(GeneTrajectory) # Extract 3 gene trajectories gene_trajectory <- ExtractGeneTrajectory( gene.embedding = gene_embedding, dist.mat = gene.dist.mat, N = 3, # Number of trajectories to extract t.list = c(4, 7, 7), # Diffusion time steps for each trajectory dims = 1:5, # Embedding dimensions for terminus detection K = 5, # Kernel bandwidth (should match GetGeneEmbedding) quantile = 0.02 # Threshold for gene selection ) # View trajectory assignments table(gene_trajectory$selected) # Result includes embedding coordinates and pseudoorder for each trajectory head(gene_trajectory[, c("selected", "Pseudoorder1", "Pseudoorder2", "Pseudoorder3")]) # Extract ordered gene lists for each trajectory gene_lists <- list() for (i in 1:3) { traj_genes <- gene_trajectory[gene_trajectory$selected == paste0("Trajectory-", i), ] gene_lists[[i]] <- rownames(traj_genes)[order(traj_genes[, paste0("Pseudoorder", i)])] } print(gene_lists[[1]][1:10]) ``` -------------------------------- ### Compute Diffusion Map and Cell Graph Distances Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/articles/fast_computation.html Calculates the Diffusion Map embedding for cells and then computes cell-cell graph distances based on a k-nearest neighbors (kNN) graph. This is a prerequisite for coarse-graining strategies. ```r # Compute the Diffusion Map cell embedding data_S <- GeneTrajectory::RunDM(data_S) # Calculate cell-cell graph distances over a cell-cell kNN graph cell.graph.dist <- GetGraphDistance(data_S, K = 10) ``` -------------------------------- ### LoadGeneDistMat Source: https://context7.com/klugerlab/genetrajectory/llms.txt Loads a precomputed gene-gene Wasserstein distance matrix from CSV files. Expects an EMD matrix file and a gene names file in the specified directory. ```APIDOC ## LoadGeneDistMat Loads a precomputed gene-gene Wasserstein distance matrix from CSV files. Expects an EMD matrix file and a gene names file in the specified directory. ```r library(GeneTrajectory) # Load precomputed gene-gene distance matrix gene.dist.mat <- LoadGeneDistMat( dir.path = "/path/to/data/", file_name = "emd.csv" # EMD matrix file ) # Also requires "gene_names.csv" in the same directory dim(gene.dist.mat) #> [1] 245 245 # Gene names are automatically assigned as row/column names head(rownames(gene.dist.mat)) #> [1] "S100A9" "S100A8" "LYZ" "FCN1" "CD14" "VCAN" ``` ``` -------------------------------- ### GetGraphDistance: Compute Cell-Cell Graph Distances Source: https://context7.com/klugerlab/genetrajectory/llms.txt Constructs a cell-cell kNN graph from a dimensional reduction embedding and computes the graph distance matrix, representing the shortest path lengths between all cell pairs. ```APIDOC ## GetGraphDistance ### Description Constructs a cell-cell kNN graph from a dimensional reduction embedding and computes the graph distance matrix (shortest path lengths between all cell pairs). ### Method `GetGraphDistance` ### Parameters #### Arguments - **object** (Seurat) - The input Seurat object containing the dimensional reduction. - **reduction** (character) - The name of the dimensional reduction to use for kNN construction (e.g., "dm"). - **dims** (numeric vector) - Dimensions from the specified reduction to use for kNN construction. - **K** (numeric) - The number of nearest neighbors to consider for constructing the kNN graph. ### Request Example ```r library(GeneTrajectory) # Calculate cell-cell graph distances using the diffusion map embedding cell.graph.dist <- GetGraphDistance( object = data_S, reduction = "dm", # Use diffusion map embedding dims = 1:5, # Dimensions to use for kNN construction K = 10 # Number of nearest neighbors ) # Result is a symmetric cell-by-cell distance matrix dim(cell.graph.dist) # Check the largest graph distance (ensures connectivity) max(cell.graph.dist) # If disconnected components exist, increase K parameter # Error: "The cell-cell kNN graph has disconnected components. Please increase K." ``` ### Response A symmetric cell-by-cell distance matrix representing graph distances. ``` -------------------------------- ### LoadGeneDistMat() Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/reference/index.html Loads a precomputed gene-gene Wasserstein distance matrix. ```APIDOC ## LoadGeneDistMat() ### Description Load gene-gene Wasserstein matrix. ### Method Not specified ### Endpoint Not specified ### Parameters Not specified ### Request Example Not specified ### Response Not specified ``` -------------------------------- ### AddGeneBinScore() Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/reference/index.html Adds gene bin scores to the analysis. ```APIDOC ## AddGeneBinScore() ### Description Adds gene bin score. ### Method Not specified ### Endpoint Not specified ### Parameters Not specified ### Request Example Not specified ### Response Not specified ``` -------------------------------- ### LoadGeneDistMat Source: https://github.com/klugerlab/genetrajectory/blob/main/docs/reference/LoadGeneDistMat.html Loads a pre-computed gene-gene Wasserstein matrix from a specified directory and file. ```APIDOC ## LoadGeneDistMat ### Description Loads a gene-gene Wasserstein matrix from a CSV file. ### Method N/A (This is an R function, not a REST API endpoint) ### Endpoint N/A ### Parameters #### Path Parameters - **dir.path** (string) - Required - Path to the directory containing the gene-gene Wasserstein matrix file. #### Query Parameters N/A #### Request Body N/A ### Request Example ```R LoadGeneDistMat(dir.path = "/path/to/your/data", file_name = "emd.csv") ``` ### Response #### Success Response (200) - **matrix** (matrix) - The loaded gene-gene Wasserstein matrix. #### Response Example ```R # Example of a returned matrix (structure depends on the input file) # gene1 gene2 gene3 # gene1 0.0 0.1 0.2 # gene2 0.1 0.0 0.15 # gene3 0.2 0.15 0.0 ``` ```