### Estimate Normalization Factors and Dispersions in R Source: https://context7.com/maxmeieran/monocle2/llms.txt Estimates size factors for library size normalization and dispersion parameters for differential expression analysis using negative binomial models. This step is crucial for accurate downstream analyses. ```r # Estimate size factors (library size normalization) cds <- estimateSizeFactors(cds) # Estimate dispersions for negative binomial model cds <- estimateDispersions(cds) # Access size factors sf <- sizeFactors(cds) # Returns: Named numeric vector of size factors for each cell # Get dispersion table for quality control disp_table <- dispersionTable(cds) # Returns: Data frame with columns: gene_id, mean_expression, dispersion_fit, dispersion_empirical ``` -------------------------------- ### Build Branch CellDataSet for Analysis Source: https://context7.com/maxmeieran/monocle2/llms.txt Creates a CellDataSet subset specifically for detailed branch analysis. It duplicates progenitor cells to both branches for proper comparison, allowing for focused analysis of divergence. Options include different progenitor handling methods and pseudotime stretching. ```r # Build branch CellDataSet cds_branch <- buildBranchCellDataSet( cds, branch_point = 1, branch_states = NULL, # Auto-detect from branch_point branch_labels = c("Fate1", "Fate2"), progenitor_method = "duplicate", # or "sequential_split" stretch = TRUE # Normalize pseudotime 0-100 ) # Examine branch assignments table(pData(cds_branch)$Branch) # Access stretched pseudotime range(pData(cds_branch)$Pseudotime) ``` -------------------------------- ### Order Cells by Pseudotime and Identify Branch Points Source: https://context7.com/maxmeieran/monocle2/llms.txt Orders cells based on pseudotime and identifies key branching points in the trajectory. The `orderCells` function reorders the cell trajectories, and branch points are extracted from the DDRTree auxiliary data. This is crucial for understanding developmental progression and cell fate decisions. ```r # Re-order with specific root state cds <- orderCells(cds, root_state = 1) # Get branch points branch_points <- cds@auxOrderingData(("DDRTree"))$branch_points # Returns: Character vector of branch point vertex names ``` -------------------------------- ### Cell Clustering using Density Peak Detection (R) Source: https://context7.com/maxmeieran/monocle2/llms.txt Clusters cells based on density peak detection in a reduced dimension space (e.g., t-SNE). This method is useful for identifying distinct cell populations. Requires a CellDataSet object and outputs cluster assignments and visualizations. ```r # First reduce dimensions with t-SNE cds <- reduceDimension( cds, max_components = 2, reduction_method = "tSNE", num_dim = 50, verbose = TRUE ) # Cluster cells using density peaks cds <- clusterCells( cds, method = "densityPeak", rho_threshold = 2, delta_threshold = 10, skip_rho_sigma = FALSE, verbose = TRUE ) # View cluster assignments table(pData(cds)$Cluster) # 1 2 3 4 # 25 30 28 17 # Plot clustering results plot_cell_clusters(cds, color_by = "Cluster", cell_size = 1.5) # Plot decision map plot_rho_delta(cds, rho_threshold = 2, delta_threshold = 10) ``` -------------------------------- ### Create CellDataSet Object in R Source: https://context7.com/maxmeieran/monocle2/llms.txt Initializes a CellDataSet object, the primary data structure in Monocle, from an expression matrix and associated cell/gene metadata. It requires the 'monocle' library and can specify the expression family for downstream analysis. ```r library(monocle) # Create expression matrix (genes x cells) expression_matrix <- matrix( rpois(10000, lambda = 5), nrow = 100, ncol = 100 ) rownames(expression_matrix) <- paste0("Gene", 1:100) colnames(expression_matrix) <- paste0("Cell", 1:100) # Create phenotype data (cell metadata) pd <- new("AnnotatedDataFrame", data = data.frame( cell_type = sample(c("TypeA", "TypeB"), 100, replace = TRUE), batch = sample(c("Batch1", "Batch2"), 100, replace = TRUE), row.names = colnames(expression_matrix) )) # Create feature data (gene metadata) fd <- new("AnnotatedDataFrame", data = data.frame( gene_short_name = paste0("Gene", 1:100), biotype = sample(c("protein_coding", "lncRNA"), 100, replace = TRUE), row.names = rownames(expression_matrix) )) # Create CellDataSet with negative binomial distribution cds <- newCellDataSet( as(expression_matrix, "sparseMatrix"), phenoData = pd, featureData = fd, expressionFamily = negbinomial.size(), lowerDetectionLimit = 0.5 ) # Output: CellDataSet object with 100 features and 100 samples ``` -------------------------------- ### Order Cells Along Trajectory in R Source: https://context7.com/maxmeieran/monocle2/llms.txt Assigns pseudotime and state values to each cell based on its position within the inferred trajectory. The root state can be specified to define the direction of the trajectory. ```r # Order cells (initial ordering) cds <- orderCells(cds) # View pseudotime assignments head(pData(cds)[, c("Pseudotime", "State")]) ``` -------------------------------- ### Accessing and Modifying CellDataSet Components (R) Source: https://context7.com/maxmeieran/monocle2/llms.txt Demonstrates how to access and modify various components of the Monocle 2 CellDataSet object, including expression matrices, metadata, reduced dimensions, and the minimum spanning tree. Essential for data inspection and manipulation. ```r # Access expression data expr_matrix <- exprs(cds) # Access and modify phenotype data (cell metadata) cell_metadata <- pData(cds) pData(cds)$custom_annotation <- "value" # Access and modify feature data (gene metadata) gene_metadata <- fData(cds) fData(cds)$custom_gene_info <- "info" # Access reduced dimension components S_matrix <- reducedDimS(cds) # Cell coordinates K_matrix <- reducedDimK(cds) # Principal graph vertices (DDRTree) W_matrix <- reducedDimW(cds) # Weight matrix A_matrix <- reducedDimA(cds) # Mixing matrix (ICA) # Access minimum spanning tree mst <- minSpanningTree(cds) # igraph object # Access cell pairwise distances dist_matrix <- cellPairwiseDistances(cds) ``` -------------------------------- ### Plot Genes in Pseudotime with Fitted Trends (R) Source: https://context7.com/maxmeieran/monocle2/llms.txt Visualizes the expression of selected genes as a function of pseudotime, including fitted trend lines. Requires a CellDataSet object and gene identifiers. Outputs plots showing gene expression dynamics over pseudotime. ```r # Select genes to plot genes_to_plot <- row.names(subset(fData(cds), gene_short_name %in% c("Gene1", "Gene2", "Gene3"))) cds_subset <- cds[genes_to_plot, ] # Plot expression vs pseudotime plot_genes_in_pseudotime( cds_subset, color_by = "State", cell_size = 0.75, nrow = 1, ncol = 3, min_expr = 0.1, trend_formula = "~sm.ns(Pseudotime, df = 3)" ) ``` -------------------------------- ### Plot Cell Trajectories Source: https://context7.com/maxmeieran/monocle2/llms.txt Visualizes cell trajectories, allowing cells to be colored by various attributes such as state, pseudotime, or gene expression. It displays the minimum spanning tree structure learned by DDRTree and can overlay specific marker gene expression patterns. ```r # Basic trajectory plot colored by State plot_cell_trajectory( cds, color_by = "State", cell_size = 1.5, show_tree = TRUE, show_branch_points = TRUE ) # Color by pseudotime plot_cell_trajectory( cds, color_by = "Pseudotime", cell_size = 1.5 ) + scale_color_viridis_c() # Overlay marker gene expression plot_cell_trajectory( cds, markers = "MYH3", use_color_gradient = TRUE, cell_size = 1.5 ) ``` -------------------------------- ### Plot Pseudotime Expression Heatmap (R) Source: https://context7.com/maxmeieran/monocle2/llms.txt Generates a clustered heatmap of gene expression over pseudotime, identifying groups of genes with similar expression patterns. Requires a CellDataSet with significant pseudotime-varying genes. Outputs a heatmap visualization and cluster assignments. ```r # Select significant pseudotime-varying genes sig_gene_ids <- row.names(subset(diff_test_res, qval < 0.01)) cds_subset <- cds[sig_gene_ids, ] # Generate pseudotime heatmap heatmap_result <- plot_pseudotime_heatmap( cds_subset, cluster_rows = TRUE, num_clusters = 4, hclust_method = "ward.D2", show_rownames = FALSE, norm_method = "log", scale_max = 3, scale_min = -3, return_heatmap = TRUE, cores = 4 ) # Access cluster assignments cluster_assignments <- cutree(heatmap_result$tree_row, k = 4) ``` -------------------------------- ### Differential Expression Testing with VGAM Spline Models Source: https://context7.com/maxmeieran/monocle2/llms.txt Performs differential expression testing to identify genes that change significantly over pseudotime using likelihood ratio tests with VGAM spline models. It requires a CellDataSet object and model formulas. The output includes p-values and adjusted q-values for each gene. ```r # Test for genes that change over pseudotime diff_test_res <- differentialGeneTest( cds, fullModelFormulaStr = "~sm.ns(Pseudotime, df = 3)", reducedModelFormulaStr = "~1", cores = 1, relative_expr = TRUE, verbose = TRUE ) # View results head(diff_test_res[order(diff_test_res$qval), ]) # Select significant genes sig_genes <- subset(diff_test_res, qval < 0.01) ``` -------------------------------- ### Fit VGAM Expression Models Source: https://context7.com/maxmeieran/monocle2/llms.txt Fits vector generalized additive models (VGAM) to expression data as a function of pseudotime. This function allows for custom modeling of gene expression trends along the trajectory. It can be used to generate smooth curves representing these trends. ```r # Fit spline models for all genes model_fits <- fitModel( cds, modelFormulaStr = "~sm.ns(Pseudotime, df = 3)", relative_expr = TRUE, cores = 4 ) # Generate smooth curves from models new_data <- data.frame(Pseudotime = seq(0, max(pData(cds)$Pseudotime), length.out = 100)) smooth_curves <- genSmoothCurves( cds, new_data = new_data, trend_formula = "~sm.ns(Pseudotime, df = 3)", relative_expr = TRUE, cores = 4 ) # Returns: Matrix with genes as rows, pseudotime points as columns dim(smooth_curves) ``` -------------------------------- ### BEAM: Branch Expression Analysis Modeling Source: https://context7.com/maxmeieran/monocle2/llms.txt Identifies genes with branch-dependent expression patterns using the BEAM method. This is useful for understanding cell fate decisions at trajectory branch points. It requires a CellDataSet object, a branch point, and model formulas. The function returns a data frame with results including p-values and q-values for branch-specific gene expression. ```r # Run BEAM analysis at branch point 1 beam_res <- BEAM( cds, branch_point = 1, fullModelFormulaStr = "~sm.ns(Pseudotime, df = 3) * Branch", reducedModelFormulaStr = "~sm.ns(Pseudotime, df = 3)", relative_expr = TRUE, cores = 4, verbose = TRUE ) # View branch-dependent genes beam_genes <- subset(beam_res, qval < 0.01) head(beam_genes[order(beam_genes$qval), c("gene_short_name", "pval", "qval")]) # Calculate branch divergence scores (Area Between Curves) abc_res <- calABCs( cds, branch_point = 1, trajectory_states = NULL, relative_expr = TRUE, stretch = TRUE, cores = 4 ) ``` -------------------------------- ### Reduce Dimensionality with DDRTree and t-SNE in R Source: https://context7.com/maxmeieran/monocle2/llms.txt Performs dimensionality reduction using DDRTree for trajectory inference or t-SNE for clustering visualization. DDRTree is recommended for trajectory analysis and can automatically select parameters. ```r # Reduce dimensions using DDRTree (recommended) cds <- reduceDimension( cds, max_components = 2, reduction_method = "DDRTree", norm_method = "log", pseudo_expr = 1, relative_expr = TRUE, auto_param_selection = TRUE, verbose = TRUE ) # Access reduced dimension coordinates K <- reducedDimK(cds) # Principal graph vertices S <- reducedDimS(cds) # Cell projections W <- reducedDimW(cds) # Weight matrix # Alternative: Use t-SNE for clustering visualization cds_tsne <- reduceDimension( cds, max_components = 2, reduction_method = "tSNE", num_dim = 50, # PCA dimensions before t-SNE verbose = TRUE ) ``` -------------------------------- ### Plot Branched Gene Expression Patterns (R) Source: https://context7.com/maxmeieran/monocle2/llms.txt Visualizes how gene expression changes across different trajectory branches after a branch point. It requires a CellDataSet object with branch-specific gene information. Outputs plots illustrating expression divergence. ```r # Select branch-dependent genes branch_genes <- row.names(subset(beam_res, qval < 0.01)) cds_branch_subset <- cds[branch_genes[1:6], ] # Plot branched expression patterns plot_genes_branched_pseudotime( cds_branch_subset, branch_point = 1, branch_labels = c("Fate1", "Fate2"), color_by = "State", cell_size = 0.5, ncol = 2, method = "fitting" ) ``` -------------------------------- ### Select Genes for Trajectory Ordering in R Source: https://context7.com/maxmeieran/monocle2/llms.txt Filters genes based on their dispersion relative to mean expression to identify those suitable for trajectory construction. These selected genes are then marked within the CellDataSet object. ```r # Get dispersion table disp_table <- dispersionTable(cds) # Select genes with high dispersion relative to mean ordering_genes <- subset( disp_table, mean_expression >= 0.1 & dispersion_empirical >= 1.5 * dispersion_fit )$gene_id # Mark genes for ordering cds <- setOrderingFilter(cds, ordering_genes) # Verify selected genes table(fData(cds)$use_for_ordering) # Output: FALSE TRUE # 75 25 ``` -------------------------------- ### Plot Branched Gene Expression Heatmap (R) Source: https://context7.com/maxmeieran/monocle2/llms.txt Creates a heatmap visualizing gene expression divergence across specified trajectory branches. It takes a CellDataSet with branch-dependent genes as input. Outputs a heatmap showing expression patterns across branches. ```r # Plot branch-dependent gene heatmap plot_genes_branched_heatmap( cds[branch_genes, ], branch_point = 1, branch_labels = c("Fate1", "Fate2"), num_clusters = 6, show_rownames = FALSE, use_gene_short_name = TRUE, branch_colors = c("#979797", "#F05662", "#7990C8"), return_heatmap = FALSE, cores = 4 ) ``` -------------------------------- ### Census: Convert Relative Expression to Absolute Counts Source: https://context7.com/maxmeieran/monocle2/llms.txt Transforms relative expression values (like FPKM or TPM) into estimated absolute mRNA counts per cell. This conversion enables more accurate downstream analysis, particularly with negative binomial models. It involves estimating a scaling factor 't' and then applying the `relative2abs` function. ```r # Estimate t* (most abundant expression value = 1 mRNA copy) t_estimate <- estimate_t(exprs(cds)) # Convert relative to absolute counts absolute_counts <- relative2abs( cds, t_estimate = t_estimate, modelFormulaStr = "~1", method = "num_genes", expected_capture_rate = 0.25, verbose = TRUE, cores = 4 ) # Replace expression matrix with absolute counts cds_abs <- cds exprs(cds_abs) <- absolute_counts # Re-estimate size factors for absolute counts cds_abs <- estimateSizeFactors(cds_abs) cds_abs <- estimateDispersions(cds_abs) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.