### Install Cottrazm Source: https://github.com/yelab2020/cottrazm/blob/main/doc/my-vignette.Rmd Install the Cottrazm package from GitHub or a local source file. ```r #from local path devtools::install_github('Yelab2020/Cottrazm') #from github install.packages("Cottrazm.tar.gz", repos = NULL, type = "source") library(Cottrazm) ``` -------------------------------- ### Install Cottrazm via devtools Source: https://github.com/yelab2020/cottrazm/blob/main/README.md Install the development version of Cottrazm from GitHub using the devtools package. ```R # Install devtools, if necessary if (!requireNamespace("devtools", quietly = TRUE)) install.packages("devtools") devtools::install_github("Yelab2020/Cottrazm") ``` -------------------------------- ### SpatialDecon Workflow Example Source: https://github.com/yelab2020/cottrazm/blob/main/man/SpatialDecon.Rd This example demonstrates the full workflow for preparing data and executing the SpatialDecon function. It includes reading input files, normalizing ST data, calculating signature scores, filtering features, and running the enrichment analysis. ```R # read boundary definde data TumorST <- readr::read_rds("YourPath/TumorBoundary/Fig/1.BoundaryDefine/CRC1/TumorSTBoundaryDefine.rds.gz") sig_exp <- readr::read_rds("YourPath/TumorBoundary/sig_exp.rds.gz") clustermarkers_list <- readr::read_rds("YourPath/clustermarkers_list.rds.gz") # get st and sc filtered expr data TumorST <- NormalizeData(TumorST,assay = "Spatial") TumorST@meta.data$Decon_topics <- paste(TumorST@meta.data$Location,TumorST@meta.data$seurat_clusters,sep = "_") expr_values = as.matrix(TumorST@assays$Spatial@data) #ST expr log nolog_expr = 2^(expr_values)-1 #ST expr nolog meta_data <- TumorST@meta.data[,c("nCount_Spatial","Decon_topics","Location")] # Signature score for(cluster in names(clustermarkers_list)){ cluster_markers = clustermarkers_list[[cluster]][1:25] cluster_score <- apply(TumorST@assays$Spatial@data[rownames(TumorST@assays$Spatial@data) %in% cluster_markers,],2,mean) meta_data <- cbind(meta_data,cluster_score) } colnames(meta_data) <- c("nCount_Spatial","Decon_topics","Location",names(clustermarkers_list)) # filter st and sc feature intersect_gene = intersect(rownames(sig_exp), rownames(nolog_expr)) filter_sig = sig_exp[intersect_gene,] filter_expr = nolog_expr[intersect_gene,] filter_log_expr = expr_values[intersect_gene,] # get enrich matrix enrich_matrix <- get_enrich_matrix(filter_sig = filter_sig,clustermarkers_list = clustermarkers_list) # get enrich result enrich_result <- enrich_analysis(filter_log_expr = filter_log_expr,enrich_matrix = enrich_matrix) DeconData <- SpatialDecon(enrich_matrix = enrich_matrix, enrich_result = enrich_result, filter_expr = filter_expr, filter_sig = filter_sig, clustermarkers_list = clustermarkers_list, meta_data = meta_data, malignant_cluster = malignant_clsuter, tissue_cluster = tissue_clsuter, stromal_cluster = stromal_cluster ) ``` -------------------------------- ### Perform enrichment analysis Source: https://github.com/yelab2020/cottrazm/blob/main/man/enrich_analysis.Rd Example demonstrating how to prepare data and execute the enrich_analysis function. ```R TumorST <- readr::read_rds("YourPath/TumorBoundary/Fig/1.BoundaryDefine/CRC1/TumorSTBoundaryDefine.rds.gz") sig_exp <- readr::read_rds("YourPath/sig_exp.rds.gz") clustermarkers_list <- readr::read_rds("YourPath/clustermarkers_list.rds.gz") # get st and sc filtered expr data TumorST <- NormalizeData(TumorST,assay = "Spatial") TumorST@meta.data$Decon_topics <- paste(TumorST@meta.data$Location,TumorST@meta.data$seurat_clusters,sep = "_") expr_values = as.matrix(TumorST@assays$Spatial@data) #ST expr log nolog_expr = 2^(expr_values)-1 #ST expr nolog # filter st and sc feature intersect_gene = intersect(rownames(sig_exp), rownames(nolog_expr)) filter_sig = sig_exp[intersect_gene,] filter_log_expr = expr_values[intersect_gene,] # get enrich matrix enrich_matrix <- get_enrich_matrix(filter_sig = filter_sig,clustermarkers_list = clustermarkers_list) enrich_result <- enrich_analysis(filter_log_expr = filter_log_expr,enrich_matrix = enrich_matrix) ``` -------------------------------- ### FindDiffGenes usage example Source: https://github.com/yelab2020/cottrazm/blob/main/man/FindDiffGenes.Rd Demonstrates how to load a Seurat object and execute the FindDiffGenes function using the Spatial assay. ```R TumorST <- readr::read_rds("YourPath/TumorBoundary/1.BoundaryDefine/CRC1/TumorSTBoundaryDefine.rds.gz") assay <- "Spatial" DiffGenes <- FindDiffGenes(TumorST = TumorST, assay = assay) ``` -------------------------------- ### Visualize ST boundary results Source: https://github.com/yelab2020/cottrazm/blob/main/man/BoundaryPlot.Rd This example demonstrates how to prepare the necessary Seurat objects and call BoundaryPlot to visualize the boundary definition results for a specific sample. ```R Sample <- "CRC1" OutDir <- "YourPath/TumorBoundary/Fig/1.BoundaryDefine/CRC1/" TumorST <- readr::read_rds("YourPath/TumorBoundary/1.BoundaryDefine/CRC1/TumorSTClustered.rds.gz") TumorST <- STCNVScore(TumorST = TumorST, assay = "Spatial", OutDir = OutDir, Sample = Sample) MalLabel <- c(1, 2) TumorSTn <- BoundaryDefine(TumorST = TumorST, MalLabel = MalLabel, OutDir = OutDir, Sample = Sample) TumorST <- BoundaryPlot(TumorSTn = TumorSTn, TumorST = TumorST, OutDir = OutDir, Sample = Sample) ``` -------------------------------- ### Generate a DeconPieplot Source: https://github.com/yelab2020/cottrazm/blob/main/man/DeconPieplot.Rd This example demonstrates how to load the necessary data and generate a pie plot of deconvolution results using the DeconPieplot function. ```R TumorST <- readr::read_rds("YourPath/TumorBoundary/1.BoundaryDefine/CRC1/TumorSTBoundaryDefine.rds.gz") DeconData <- openxlsx::read.xlsx(system.file("extdata/DeconData.xlsx", package = "Cottrazm")) plot_col <- colnames(DeconData)[2:ncol(DeconData)] img_path <- system.file("extdata/outs/spatial/tissue_lowres_image.png", package = "Cottrazm") DeconPieplot(DeconData = DeconData, TumorST = TumorST, plot_col = plot_col, img_path = img_path, pie_scale = 0.4, scatterpie_alpha = 0.8, border_color = "grey") ``` -------------------------------- ### Run STCNV on Tumor Spatial Transcriptomics Data Source: https://github.com/yelab2020/cottrazm/blob/main/man/STCNV.Rd This example demonstrates the workflow of preprocessing, clustering, and running infercnv on a Seurat object. ```R InDir <- paste(system.file("extdata/outs", package = "Cottrazm"), "/", sep = "") Sample <- "CRC1" OutDir <- "YourPath/TumorBoundary/Fig/1.BoundaryDefine/CRC1/" TumorST <- STPreProcess(InDir = InDir, OutDir = OutDir, Sample = Sample) TumorST <- STModiCluster(InDir = InDir, Sample = Sample, OutDir = OutDir, TumorST = TumorST, res = 1.5) STInferCNV <- STCNV(TumorST = TumorST, OutDir = OutDir, Sample = Sample,assay = "Spatial") ``` -------------------------------- ### Generate a Deconvolution Bar Plot Source: https://github.com/yelab2020/cottrazm/blob/main/man/DeconBarplot.Rd This example demonstrates how to load the necessary data and generate a bar plot using the DeconBarplot function. ```R TumorST <- readr::read_rds("YourPath/TumorBoundary/1.BoundaryDefine/CRC1/TumorSTBoundaryDefine.rds.gz") DeconData <- oepnxlsx::read.xlsx(system.file("extdata/DeconData.xlsx", package = "Cottrazm")) plot_col <- colnames(DeconData)[2:ncol(DeconData)] DeconBarplot(DeconData = DeconData, TumorST = TumorST, plot_col = plot_col) ``` -------------------------------- ### Preprocess Spatial Transcriptomics Data with STPreProcess Source: https://github.com/yelab2020/cottrazm/blob/main/man/STPreProcess.Rd Example usage of the STPreProcess function to load and process spatial transcriptomics data from a specified directory. ```R InDir <- paste(system.file("extdata/outs", package = "Cottrazm"), "/", sep = "") Sample <- "CRC1" OutDir <- "YourPath/TumorBoundary/Fig/1.BoundaryDefine/CRC1/" TumorST <- STPreProcess(InDir = InDir, OutDir = OutDir, Sample = Sample) ``` -------------------------------- ### Reconstruct spatial tumor microenvironment with SpatialRecon Source: https://github.com/yelab2020/cottrazm/blob/main/man/SpatialRecon.Rd Example usage of the SpatialRecon function to reconstruct the tumor microenvironment at a specific location. ```R TumorST <- readr::read_rds("YourPath/TumorBoundary/1.BoundaryDefine/CRC1/TumorSTBoundaryDefine.rds.gz") sig_exp <- readr::read_rds("YourPath/sig_exp.rds.gz") clustermarkers_list <- readr::read_rds("YourPath/clustermarkers_list.rds.gz") DeconData <- oepnxlsx::read.xlsx(system.file("extdata/DeconData.xlsx", package = "Cottrazm")) TumorSTSub <- SpatialRecon(TumorST = TumorST, sig_exp = sig_exp, clustermarkers_list = clustermarkers_list, DeconData = DeconData, Location = "Bdy") ``` -------------------------------- ### Perform Feature Enrichment Analysis Source: https://github.com/yelab2020/cottrazm/blob/main/man/FeatureEnrichment.Rd Example showing how to load spatial data, identify differentially expressed genes, and perform enrichment analysis for a specific location. ```R TumorST <- readr::read_rds("YourPath/TumorBoundary/1.BoundaryDefine/CRC1/TumorSTBoundaryDefine.rds.gz") DiffGenes <- FindDiffGenes(TumorST = TumorST, assay = "Spatial") BdyFeatureEnrich <- FeatureEnrichment(DiffGenes = DiffGenes, cut_off_logFC = 0.25, cut_off_pvalue = 0.05, Location = "Bdy") ``` -------------------------------- ### Manual Implementation of Spatial Pie and Bar Plots Source: https://github.com/yelab2020/cottrazm/blob/main/doc/my-vignette.Rmd This example demonstrates the manual workflow for generating spatial scatter pie plots and location-based bar plots using ggplot2 and related spatial data processing. ```r plot_col <- colnames(DeconData)[2:ncol(DeconData)] img_path = "/work/xzz123/Project/2021/TumorBoundary/package/Cottrazm/inst/extdata/outs/spatial/tissue_lowres_image.png" DeconData = DeconData; TumorST = TumorST; plot_col = plot_col; img_path = img_path; pie_scale = 0.4; scatterpie_alpha = 0.8; border_color = "grey" DeconData <- DeconData[DeconData$cell_ID %in% rownames(TumorST@meta.data), ] ## Preprocess data slice <- names(TumorST@images)[1] spatial_coord <- data.frame(TumorST@images[[slice]]@coordinates) %>% tibble::rownames_to_column("cell_ID") %>% dplyr::mutate( imagerow_scaled = imagerow * TumorST@images[[slice]]@scale.factors$lowres, imagecol_scaled = imagecol * TumorST@images[[slice]]@scale.factors$lowres ) %>% dplyr::inner_join(DeconData, by = "cell_ID") ### Load histological image into R img_path <- img_path # lowers image png(input dir) img_frmt <- base::tolower(stringr::str_sub(img_path, -4, -1)) if (img_frmt %in% c(".jpg", "jpeg")) { img <- jpeg::readJPEG(img_path) } else if (img_frmt == ".png") { img <- png::readPNG(img_path) } # Convert image to grob object img_grob <- grid::rasterGrob(img, interpolate = FALSE, width = grid::unit(1, "npc"), height = grid::unit(1, "npc") ) ## Plot spatial scatterpie plot scatterpie_plt <- ggplot2::ggplot() + ggplot2::annotation_custom( grob = img_grob, xmin = 0, xmax = ncol(img), ymin = 0, ymax = -nrow(img) ) + scatterpie::geom_scatterpie( data = spatial_coord, ggplot2::aes( x = imagecol_scaled, y = imagerow_scaled ), cols = plot_col, color = border_color, alpha = scatterpie_alpha, pie_scale = pie_scale, lwd = 0.1 ) + ggplot2::scale_y_reverse() + ggplot2::ylim(nrow(img), 0) + ggplot2::xlim(0, ncol(img)) + cowplot::theme_half_open(11, rel_small = 1) + ggplot2::theme_void() + ggplot2::coord_fixed( ratio = 1, xlim = NULL, ylim = NULL, expand = TRUE, clip = "on" ) print(scatterpie_plt) ##Decon Bar DeconData = DeconData; TumorST = TumorST; plot_col = plot_col metadata <- DeconData metadata[, "Location"] <- TumorST@meta.data$Location[match(metadata$cell_ID, rownames(TumorST@meta.data))] Location <- do.call(rbind, lapply(unique(metadata$Location), function(x) { metadata_split <- metadata[metadata$Location == x, ] %>% as.data.frame() sub <- colSums(metadata_split[, plot_col], na.rm = T) %>% data.frame() %>% tibble::rownames_to_column() %>% set_colnames(., c("Types", "Sum")) %>% dplyr::mutate(Per = 100 * Sum / sum(Sum)) })) Location$Group <- rep(unique(metadata$Location), each = length(plot_col)) Location$Types <- factor(Location$Types, levels = plot_col) Barplot <- ggplot(Location, aes(x = Group, y = Per, fill = Types)) + geom_bar(stat = "identity") + theme_bw() print(Barplot) ``` -------------------------------- ### Define tumor boundaries in ST data Source: https://github.com/yelab2020/cottrazm/blob/main/man/BoundaryDefine.Rd This example demonstrates how to load a clustered Seurat object, calculate CNV scores, and define tumor boundaries using the BoundaryDefine function. ```R TumorST <- readr::read_rds("YourPath/TumorBoundary/1.BoundaryDefine/CRC1/TumorSTClustered.rds.gz") Sample <- "CRC1" OutDir <- "YourPath/TumorBoundary/Fig/1.BoundaryDefine/CRC1/" TumorST <- STCNVScore(TumorST = TumorST, assay = "Spatial", OutDir = OutDir, Sample = Sample) MalLabel <- c(1, 2) TumorSTn <- BoundaryDefine(TumorST = TumorST, MalLabel = MalLabel, OutDir = OutDir, Sample = Sample) ``` -------------------------------- ### Generate enrichment matrix Source: https://github.com/yelab2020/cottrazm/blob/main/man/get_enrich_matrix.Rd Example usage of get_enrich_matrix to create a binary matrix from filtered signature data and a list of cluster markers. ```R enrich_matrix <- get_enrich_matrix(filter_sig = filter_sig,clustermarkers_list = clustermarkers_list) ``` -------------------------------- ### Generate a volcano plot for differential expression Source: https://github.com/yelab2020/cottrazm/blob/main/man/DiffVolcanoplot.Rd This example demonstrates how to load spatial transcriptomics data, identify differentially expressed genes using FindDiffGenes, and visualize the results with a volcano plot. ```R TumorST <- readr::read_rds("YourPath/TumorBoundary/1.BoundaryDefine/CRC1/TumorSTBoundaryDefine.rds.gz") DiffGenes <- FindDiffGenes(TumorST = TumorST, assay = "Spatial") DiffVolcanoplot(DiffGenes = DiffGenes, Location = "Bdy", cut_off_pvalue = 2, cut_off_logFC = 0.25, n = 10) ``` -------------------------------- ### Calculate mean expression of significant features Source: https://github.com/yelab2020/cottrazm/blob/main/man/get_sig_exp.Rd Example usage of the get_sig_exp function to retrieve mean expression values for significant features across defined cell types. ```R sig_exp <- get_sig_exp(se.obj = sc_obj,DefineTypes = "MajorTypes",sig_scran = unique(unlist(clustermarkers_list))) ``` -------------------------------- ### Perform morphological adjusted cluster determination Source: https://github.com/yelab2020/cottrazm/blob/main/man/STModiCluster.Rd Example usage of STModiCluster to process spatial transcriptomics data, including setting up input/output paths and running the clustering workflow. ```R InDir <- paste(system.file("extdata/outs", package = "Cottrazm"), "/", sep = "") Sample <- "CRC1" OutDir <- "YourPath/TumorBoundary/Fig/1.BoundaryDefine/CRC1/" TumorST <- STPreProcess(InDir = InDir, OutDir = OutDir, Sample = Sample) TumorST <- STModiCluster(InDir = InDir, Sample = Sample, OutDir = OutDir, TumorST = TumorST, res = 1.5) ``` -------------------------------- ### hello() Source: https://github.com/yelab2020/cottrazm/blob/main/man/hello.Rd Prints 'Hello, world!' to the console. ```APIDOC ## hello() ### Description Prints 'Hello, world!' to the console. ### Usage hello() ### Examples ```r hello() ``` ``` -------------------------------- ### Create Conda Environment Source: https://github.com/yelab2020/cottrazm/blob/main/doc/my-vignette.Rmd Commands to set up the required environment and dependencies for Cottrazm. ```bash # conda create -n TumorBoundary python=3.8 # conda activate TumorBoundary # pip install -U stlearn ``` -------------------------------- ### STPreProcess(InDir, Sample, OutDir = NULL) Source: https://github.com/yelab2020/cottrazm/blob/main/man/STPreProcess.Rd Reads ST raw data and performs quality control on the provided sample data. ```APIDOC ## STPreProcess ### Description Reads spatial transcriptomics raw data and performs quality control. This function expects Spaceranger output files and returns a Seurat object. ### Arguments - **InDir** (string) - Required - Path to file containing Spaceranger output results (must include 'filtered_feature_bc_matrix', 'filtered_feature_bc_matrix.h5', and 'spatial'). - **Sample** (string) - Required - Name of the sample. - **OutDir** (string) - Optional - Path to save figures and processed data. ### Returns - **Seurat object** - The processed spatial transcriptomics data. ### Example ```R InDir <- paste(system.file("extdata/outs", package = "Cottrazm"), "/", sep = "") Sample <- "CRC1" OutDir <- "YourPath/TumorBoundary/Fig/1.BoundaryDefine/CRC1/" TumorST <- STPreProcess(InDir = InDir, OutDir = OutDir, Sample = Sample) ``` ``` -------------------------------- ### Execute hello function Source: https://github.com/yelab2020/cottrazm/blob/main/man/hello.Rd Call the hello function to print the greeting to the console. ```R hello() ``` -------------------------------- ### Score ST data with infercnv result Source: https://github.com/yelab2020/cottrazm/blob/main/man/STCNVScore.Rd Example usage of the STCNVScore function to process a Seurat object with spatial transcriptomics data. ```R TumorST <- readr::read_rds("YourPath/TumorBoundary/1.BoundaryDefine/CRC1/TumorSTClustered.rds.gz") OutDir <- "YourPath/TumorBoundary/Fig/1.BoundaryDefine/CRC1/" Sample <- "CRC1" assay = "Spatial" TumorST <- STCNVScore(TumorST = TumorST, assay = assay, OutDir = OutDir, Sample = Sample) ``` -------------------------------- ### Pull Cottrazm Docker image Source: https://github.com/yelab2020/cottrazm/blob/main/README.md Download the Cottrazm environment using Docker. ```bash docker pull skye12138/cottrazm:latest ``` -------------------------------- ### Load Required R Libraries Source: https://github.com/yelab2020/cottrazm/blob/main/doc/my-vignette.Rmd Load all necessary R packages for the Cottrazm workflow. ```r library(Seurat) library(magrittr) library(dplyr) library(Matrix) library(ggplot2) library(stringr) library(RColorBrewer) library(patchwork) library(ggtree) library(BiocGenerics) library(readr) library(rtracklayer) library(infercnv) library(phylogram) library(utils) library(dendextend) library(assertthat) library(reticulate) library(openxlsx) library(scatterpie) library(cowplot) library(stats) library(quadprog) library(data.table) library(Rfast) library(ggrepel) library(tibble) library(clusterProfiler) library(utils) library(org.Hs.eg.db) ``` -------------------------------- ### Display R session information Source: https://github.com/yelab2020/cottrazm/blob/main/doc/my-vignette.Rmd Prints the current R session details including loaded packages and system information. ```r sessionInfo() ``` -------------------------------- ### Set Stack Size Limit Source: https://github.com/yelab2020/cottrazm/blob/main/vignettes/my-vignette.Rmd System command to increase stack size before running InferCNV. ```bash # unlimit -s 102400 ``` -------------------------------- ### Configure knitr options Source: https://github.com/yelab2020/cottrazm/blob/main/doc/my-vignette.Rmd Sets global options for code chunk execution, including collapsing output and defining the comment prefix. ```r knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` -------------------------------- ### Run InferCNV on ST Data Source: https://github.com/yelab2020/cottrazm/blob/main/doc/my-vignette.Rmd Run InferCNV analysis to separate malignant and non-malignant spots. ```r print('STCNV' ) STInferCNV <- STCNV( TumorST = TumorST, OutDir = OutDir, assay = "Spatial" ) ``` -------------------------------- ### Visualize Deconvolution Results with Cottrazm Functions Source: https://github.com/yelab2020/cottrazm/blob/main/doc/my-vignette.Rmd Use DeconPieplot and DeconBarplot to visualize cell type infiltration. These functions require the deconvolution data, the TumorST object, and the column names representing cell types. ```r plot_col <- colnames(DeconData)[2:ncol(DeconData)] img_path = system.file("inst/extdata/outs/spatial/tissue_lowres_image.png",package = "Cottrazm") DeconPieplot( DeconData = DeconData, TumorST = TumorST, plot_col = plot_col, img_path = img_path, pie_scale = 0.4, scatterpie_alpha = 0.8, border_color = "grey" ) DeconBarplot( DeconData = DeconData, TumorST = TumorST, plot_col = plot_col ) ``` -------------------------------- ### Preprocess scRNA-seq data for deconvolution Source: https://github.com/yelab2020/cottrazm/blob/main/doc/my-vignette.Rmd Generates a list of cluster markers and a signature expression matrix from a Seurat object. The vignette also demonstrates loading pre-processed files from the Cottrazm package. ```r #clustermarkers_list sc_obj <- readr::read_rds("YourPath/scRNAseqRef.rds.gz") clustermarkers <- Seurat::FindAllMarkers(object = sc_obj, logfc.threshold = 0.25, only.pos = TRUE) clustermarkers_list <- split(clustermarkers, clustermarkers$cluster) clustermarkers_list <- lapply(names(clustermarkers_list), function(cluster) { sub_markers <- clustermarkers_list[[cluster]]$gene }) names(clustermarkers_list) <- names(split(clustermarkers, clustermarkers$cluster)) #sig_exp sig_exp <- get_sig_exp( se.obj = sc_obj, DefineTypes = "MajorTypes", sig_scran = unique(unlist(clustermarkers_list)) ) #In this vignette we read processed clustermarkers_list and sig_exp clustermarkers_list <- readr::read_rds(system.file("inst/extdata/clustermarkers_list.rds.gz",package = "Cottrazm")) sig_exp <- readr::read_rds(system.file("inst/extdata/sig_exp.rds.gz",package = "Cottrazm")) ``` -------------------------------- ### STCNV(TumorST, assay, OutDir, Sample) Source: https://github.com/yelab2020/cottrazm/blob/main/man/STCNV.Rd Run infercnv of clustered Seurat object of tumor ST data. ```APIDOC ## STCNV ### Description Run infercnv of clustered Seurat object of tumor ST data. ### Parameters - **TumorST** (Seurat object) - Required - A Seurat object with morphological adjusted expression matrix and determined clusters. - **assay** (character) - Required - The name of assay used in InferCNV (Morph: Morphological adjusted gene expression, Spatial: gene expression). - **OutDir** (character) - Optional - Path to file save infercnv results. - **Sample** (character) - Required - Name of your sample. ### Returns - **A large CNV object** ### Example ```R STInferCNV <- STCNV(TumorST = TumorST, OutDir = OutDir, Sample = Sample, assay = "Spatial") ``` ``` -------------------------------- ### find_neighbors(position, radius, method) Source: https://github.com/yelab2020/cottrazm/blob/main/man/find_neighbors.Rd Calculates the neighbors for spatial spots given their positions and a search radius. ```APIDOC ## find_neighbors ### Description Identifies all neighbors for spatial spots based on provided spatial information and a defined radius. ### Signature `find_neighbors(position, radius, method = c("manhattan", "euclidean"))` ### Parameters - **position** (data.frame) - Required - Spatial spots information containing spot id, row, cols, imagerow, and imagecol. - **radius** (numeric) - Required - Predicted radius of spatial spots. - **method** (string) - Optional - Method to calculate distance. Options are "manhattan" or "euclidean". Defaults to "manhattan". ### Returns - **list** - A list containing all spatial spots' neighbors. ``` -------------------------------- ### BoundaryPlot(TumorSTn, TumorST, OutDir, Sample) Source: https://github.com/yelab2020/cottrazm/blob/main/man/BoundaryPlot.Rd Visualizes the boundary definition results for spatial transcriptomics data and returns an updated Seurat object. ```APIDOC ## BoundaryPlot ### Description Visualize boundary define results of ST data. ### Signature BoundaryPlot(TumorSTn, TumorST, OutDir, Sample) ### Parameters - **TumorSTn** (Seurat object) - Required - A subset Seurat object of ST data with defined malignant (Mal) spots, boundary (Bdy) spots, and non-malignant (nMal) spots. - **TumorST** (Seurat object) - Required - A Seurat object with morphological adjusted expression matrix and determined clusters. - **OutDir** (string) - Required - Path to file save figures and processed data. - **Sample** (string) - Required - Name of your sample. ### Returns - **Seurat object** - A Seurat object with defined malignant (Mal) spots, boundary (Bdy) spots, and non-malignant (nMal) spots. ``` -------------------------------- ### Project Boundary to Spatial Plot Source: https://github.com/yelab2020/cottrazm/blob/main/doc/my-vignette.Rmd Project malignant, boundary, and non-malignant spots onto the spatial staining plot. ```r TumorST <- BoundaryPlot( TumorSTn = TumorSTn, TumorST = TumorST, OutDir = OutDir, Sample = Sample ) ``` -------------------------------- ### SpatialRecon(TumorST, sig_exp, clustermarkers_list, DeconData, Location = NULL) Source: https://github.com/yelab2020/cottrazm/blob/main/man/SpatialRecon.Rd Reconstructs the spatial tumor microenvironment at the sub-spot level using spot deconvolution results and scRNA-seq data. ```APIDOC ## SpatialRecon ### Description Reconstructs the spatial tumor microenvironment at the sub-spot level using spot deconvolution results and scRNA-seq data. ### Arguments - **TumorST** (Seurat object) - Required - A seurat object with defined malignant (Mal) spots, boundary (Bdy) spots, and non-malignant (nMal) spots. - **sig_exp** (matrix/data.frame) - Required - Mean expression of each feature across cell types generated by scRNAseq data. - **clustermarkers_list** (list) - Required - A list of markers of each cell type of scRNAseq dataset. - **DeconData** (data.frame) - Required - A data frame of deconvolution result of each spatial spot. - **Location** (string) - Optional - Name of location to reconstruct TME. More spots selected, reconstruct will take longer time. ### Returns - **Seurat object** - A reconstructed Seurat object of ST tumor data. ### Example ```R TumorSTSub <- SpatialRecon(TumorST = TumorST, sig_exp = sig_exp, clustermarkers_list = clustermarkers_list, DeconData = DeconData, Location = "Bdy") ``` ``` -------------------------------- ### Perform Feature Enrichment Analysis Source: https://github.com/yelab2020/cottrazm/blob/main/doc/my-vignette.Rmd Explores KEGG and GO pathways for the identified boundary spot DEGs to speculate on the function of the tumor boundary. ```r boundary_enrich <- FeatureEnrichment( DiffGenes = DiffGenes, cut_off_logFC = 0.25, cut_off_pvalue = 0.05, Location = "Bdy" ) ``` -------------------------------- ### get_enrich_matrix(filter_sig, clustermarkers_list) Source: https://github.com/yelab2020/cottrazm/blob/main/man/get_enrich_matrix.Rd Constructs a binary matrix for PAGE enrichment based on provided signature data and cluster markers. ```APIDOC ## get_enrich_matrix ### Description Constructs a binary matrix for PAGE enrichment using filtered signature data and a list of cluster markers from an scRNAseq dataset. ### Parameters - **filter_sig** (object) - Required - The sig_exp filtered by features. - **clustermarkers_list** (list) - Required - A list of markers for each cell type of the scRNAseq dataset. ### Returns - **matrix** (binary) - A binary matrix with features as rows and cell types as columns. ### Example ```r enrich_matrix <- get_enrich_matrix(filter_sig = filter_sig, clustermarkers_list = clustermarkers_list) ``` ``` -------------------------------- ### Preprocess Tumor ST Data Source: https://github.com/yelab2020/cottrazm/blob/main/doc/my-vignette.Rmd Read Spaceranger results and perform quality control. ```r print('STPreProcess') InDir = paste(system.file("extdata/outs",package = "Cottrazm"),"/",sep = "") Sample = "CRC1" OutDir = paste(getwd(),"/",Sample,"/",sep = "") TumorST <- STPreProcess( InDir = InDir, OutDir = OutDir, Sample = Sample ) ``` -------------------------------- ### Reconstruct TSME with SpatialRecon Source: https://github.com/yelab2020/cottrazm/blob/main/doc/my-vignette.Rmd Reconstructs the ST gene expression profile of scRNAseq cell types at the sub-spot level. The Location parameter defaults to 'Bdy' for boundary spots, but can be set to c('Mal', 'Byd', 'nMal') for whole ST data. ```r TumorSTRecon <- SpatialRecon( TumorST = TumorST, sig_exp = sig_exp, clustermarkers_list = clustermarkers_list, DeconData = DeconData, Location = "Bdy" ) ``` -------------------------------- ### DeconPieplot(DeconData, TumorST, plot_col, img_path, pie_scale, scatterpie_alpha, border_color) Source: https://github.com/yelab2020/cottrazm/blob/main/man/DeconPieplot.Rd Generates a pie plot of deconvolution results overlaid on a tissue image. ```APIDOC ## DeconPieplot ### Description Generates a ggplot object representing deconvolution results as pie charts for each spatial spot. Each part of the pie represents the percentage of cell types infiltrated in the ST spot. ### Parameters - **DeconData** (data frame) - Required - A data frame of deconvolution result of each spatial spot. - **TumorST** (Seurat object) - Required - A Seurat object with defined malignant (Mal) spots, boundary (Bdy) spots, and non-malignant (nMal) spots. - **plot_col** (vector) - Required - Names of cell types to plot. - **img_path** (string) - Required - Path to tissue_lowers_image.jpg in Spaceranger output file. - **pie_scale** (numeric) - Required - Size of spot in pie plot. - **scatterpie_alpha** (numeric) - Required - Transparency of spot in pie plot. - **border_color** (string) - Required - Color of border in pie plot. ### Returns - **ggplot object** - A plot where each pie represents a ST spot. ### Example ```R DeconPieplot(DeconData = DeconData, TumorST = TumorST, plot_col = plot_col, img_path = img_path, pie_scale = 0.4, scatterpie_alpha = 0.8, border_color = "grey") ``` ``` -------------------------------- ### BoundaryDefine(TumorST, MalLabel = NULL, OutDir = NULL, Sample) Source: https://github.com/yelab2020/cottrazm/blob/main/man/BoundaryDefine.Rd Identifies the boundary of a tumor within spatial transcriptomics data by analyzing CNV labels and morphological expression matrices. ```APIDOC ## BoundaryDefine ### Description Finds the boundary of a tumor in spatial transcriptomics (ST) data. It classifies spots as malignant (Mal), boundary (Bdy), or non-malignant (nMal). ### Parameters - **TumorST** (Seurat object) - Required - A Seurat object containing the morphological adjusted expression matrix and determined clusters. - **MalLabel** (vector) - Optional - CNV labels with high CNV scores defined as malignant. If NULL, the function defaults to the two labels with the highest average CNV scores. - **OutDir** (string) - Optional - The file path where figures and processed data will be saved. - **Sample** (string) - Required - The name of the sample being processed. ### Returns - **Seurat object** - A subset Seurat object of ST data with defined malignant (Mal), boundary (Bdy), and non-malignant (nMal) spots. ``` -------------------------------- ### Visualize Spatial Boundary Source: https://github.com/yelab2020/cottrazm/blob/main/doc/my-vignette.Rmd Visualize the defined tumor boundary on the spatial plot. ```r TumorST <- readr::read_rds('/work/xzz123/Project/2021/TumorBoundary/package/CRC1/CRC1_BoundaryDefine.rds.gz') Seurat::SpatialDimPlot(TumorST,group.by = 'Location',cols = c("#CB181D", "#1f78b4", "#fdb462")) ``` -------------------------------- ### Score ST Data with InferCNV Results Source: https://github.com/yelab2020/cottrazm/blob/main/doc/my-vignette.Rmd Score ST data based on InferCNV results and assign malignant labels. ```r print('STCNVScore') TumorST <- STCNVScore( TumorST = TumorST, assay = "Spatial", Sample = Sample, OutDir = OutDir ) ``` -------------------------------- ### ClusterUpdate(MalCellIDN, position, df_j, UMAPembeddings, NormalCellID, BdyCellID, MalCellID, x) Source: https://github.com/yelab2020/cottrazm/blob/main/man/ClusterUpdate.Rd Updates the cluster data frame by calculating neighbors for newly defined malignant spots based on spatial and UMAP data. ```APIDOC ## ClusterUpdate ### Description Updates the cluster data frame by identifying neighbors for newly defined malignant spots. ### Signature `ClusterUpdate(MalCellIDN, position, df_j, UMAPembeddings, NormalCellID, BdyCellID, MalCellID, x)` ### Parameters - **MalCellIDN** - Barcodes of newly defined malignant (Mal) spots. - **position** () - Spatial spots information including spot id, row, cols, imagerow, and imagecol. - **df_j** - A list containing spatial spots and their neighbors. - **UMAPembeddings** () - Spatial spots' UMAP reduction coordinates. - **NormalCellID** - Barcodes of normal spots. - **BdyCellID** - Barcodes of boundary (Bdy) spots. - **MalCellID** - Barcodes of all malignant spots. - **x** - Repeat times. ### Returns - **** - Neighbors of newly defined malignant spots' IDs and their defined types. ``` -------------------------------- ### compute_interspot_distances(position, scale.factor = 1.05) Source: https://github.com/yelab2020/cottrazm/blob/main/man/compute_interspot_distances.Rd Calculates the inter-spot distances to determine the predicted radius for spatial spots. ```APIDOC ## compute_interspot_distances ### Description Calculates predicted radius for spatial spots based on provided spatial information. ### Usage compute_interspot_distances(position, scale.factor = 1.05) ### Parameters - **position** (data.frame) - Required - A data frame containing spatial spots' information including spot id, row, cols, imagerow, and imagecol. - **scale.factor** (numeric) - Optional - The scale factor to apply. Defaults to 1.05. ### Returns - **list** - A list containing the predicted radius. ``` -------------------------------- ### Perform spot deconvolution Source: https://github.com/yelab2020/cottrazm/blob/main/doc/my-vignette.Rmd Applies DWLS deconvolution to estimate cell type proportions in spatial spots. The result can be loaded from an Excel file if the computation is skipped. ```r DeconData <- SpatialDecon( enrich_matrix = enrich_matrix, enrich_result = enrich_result, filter_expr = filter_expr, filter_sig = filter_sig, clustermarkers_list = clustermarkers_list, meta_data = meta_data, malignant_cluster = "Malignant epithelial cells", tissue_cluster = "Epithelial cells", stromal_cluster = "Fibroblast cells" ) ``` ```r DeconData <- openxlsx::read.xlsx(system.file("inst/extdata/DeconData.xlsx",package = "Cottrazm")) ``` ```r DeconData <- openxlsx::read.xlsx('/work/xzz123/Project/2021/TumorBoundary/package/Cottrazm/inst/extdata/DeconData.xlsx') print(head(DeconData)) ``` -------------------------------- ### FindDiffGenes(TumorST, assay) Source: https://github.com/yelab2020/cottrazm/blob/main/man/FindDiffGenes.Rd Identifies differentially expressed genes in malignant (Mal), boundary (Bdy), and non-malignant (nMal) spots within a Seurat object. ```APIDOC ## FindDiffGenes ### Description Finds differentially expressed genes (DEG) in malignant (Mal), boundary (Bdy), and non-malignant (nMal) spots from a Seurat object. ### Usage FindDiffGenes(TumorST, assay = c("Morph", "Spatial")) ### Arguments - **TumorST** (Seurat object) - Required - A Seurat object with defined malignant (Mal) spots, boundary (Bdy) spots, and non-malignant (nMal) spots. - **assay** (string) - Required - The name of the assay used to find DEG (Morph: Morphological adjusted gene expression, Spatial: gene expression). ### Returns - **list** - A list of data frames containing differential expressed genes, p-value, log2FC, and adjusted p-value in Mal, Bdy, and nMal spots. ### Example ```R TumorST <- readr::read_rds("YourPath/TumorBoundary/1.BoundaryDefine/CRC1/TumorSTBoundaryDefine.rds.gz") assay <- "Spatial" DiffGenes <- FindDiffGenes(TumorST = TumorST, assay = assay) ``` ``` -------------------------------- ### enrich_analysis(filter_log_expr, enrich_matrix) Source: https://github.com/yelab2020/cottrazm/blob/main/man/enrich_analysis.Rd Performs enrichment analysis to map cell types to spatial spots. ```APIDOC ## enrich_analysis ### Description Calculates enrichment results for spatial transcriptomics data by comparing filtered log-transformed expression data against a binary enrichment matrix. ### Parameters - **filter_log_expr** (matrix) - Required - A matrix of filtered log-transformed ST data expression. - **enrich_matrix** (matrix) - Required - A binary matrix with features as rows and cell types as columns. ### Returns - **matrix** - A matrix of enrichment results, with cell types as rows and spatial spots as columns. ``` -------------------------------- ### get_sig_exp(se.obj, DefineTypes, sig_scran) Source: https://github.com/yelab2020/cottrazm/blob/main/man/get_sig_exp.Rd Calculates the mean expression of significant features for each cell type defined in the metadata of a Seurat object. ```APIDOC ## get_sig_exp ### Description Get mean expression of scRNAseq significant features across each cell type. ### Signature `get_sig_exp(se.obj = WholeTissueSC, DefineTypes = "Majortypes", sig_scran = sig_scran)` ### Parameters - **se.obj** (Seurat object) - A scRNAseq Seurat object of corresponding tissue. - **DefineTypes** (string) - The column in scRNAseq Seurat object metadata representing cell types. - **sig_scran** (vector/list) - Markers of each scRNAseq cell type. ### Returns - **matrix** - A matrix with features as rows and scRNAseq cell types as columns. ### Example ```r sig_exp <- get_sig_exp(se.obj = sc_obj, DefineTypes = "MajorTypes", sig_scran = unique(unlist(clustermarkers_list))) ``` ``` -------------------------------- ### nbrs(df_j, MalCellIDAdd, CellIDRaw) Source: https://github.com/yelab2020/cottrazm/blob/main/man/nbrs.Rd Retrieves the neighbor spots' IDs for specified malignant spatial spots. ```APIDOC ## nbrs ### Description Get neighbor spots' ID of MalSpotIDAdd. ### Usage nbrs(df_j, MalCellIDAdd, CellIDRaw) ### Arguments - **df_j** (list) - A list containing spatial spots and their neighbors. - **MalCellIDAdd** (vector) - Barcodes of spatial malignant spots to find neighbors for. - **CellIDRaw** (vector) - Barcodes of spatial spots already defined by location. ### Returns - **list** - A list containing spatial spots and their neighbors. ``` -------------------------------- ### SpatialDecon(enrich_matrix, enrich_result, filter_expr, filter_sig, clustermarkers_list, meta_data, malignant_cluster, tissue_cluster, stromal_cluster) Source: https://github.com/yelab2020/cottrazm/blob/main/man/SpatialDecon.Rd Performs deconvolution of ST spots to explore the infiltration proportion of scRNA-seq cell types in each spot. ```APIDOC ## SpatialDecon ### Description Performs deconvolution of spatial transcriptomics spots to explore the infiltration proportion of scRNA-seq cell types in each spot using dampened weighted least squares (DWLS). ### Parameters - **enrich_matrix** (matrix) - A binary matrix with features as rows and cell types as columns. - **enrich_result** (matrix) - A matrix of enrichment results, with cell types as rows and spatial spots as columns. - **filter_expr** (matrix) - A matrix of filtered ST data expression. - **filter_sig** (matrix) - The sig_exp filtered by features (mean expression of each feature across cell types generated by scRNA-seq data). - **clustermarkers_list** (list) - A list of markers for each cell type of the scRNA-seq dataset. - **meta_data** (data.frame) - A data frame containing nCount_Spatial, decon_topics, and signature scores of each spot. - **malignant_cluster** (string) - The name of the malignant cluster in the scRNA-seq dataset. - **tissue_cluster** (string) - The name of the adjacent normal tissue cluster in the scRNA-seq dataset. - **stromal_cluster** (string) - The name of the stromal cluster. ### Returns - **data.frame** - A data frame containing the deconvolution result for each spatial spot. ``` -------------------------------- ### DiffVolcanoplot(DiffGenes, Location, cut_off_pvalue, cut_off_logFC, n) Source: https://github.com/yelab2020/cottrazm/blob/main/man/DiffVolcanoplot.Rd Draws a volcano plot of features in boundary-defined spatial transcriptomics data. ```APIDOC ## DiffVolcanoplot ### Description Draws a volcano plot of features in boundary defined ST data. ### Signature `DiffVolcanoplot(DiffGenes, Location = c("Mal", "Bdy", "nMal"), cut_off_pvalue = 2, cut_off_logFC = 0.25, n = NULL)` ### Parameters - **DiffGenes** (list of data frames) - Required - A list of data frames containing differential expressed genes, p-value, log2FC, and adjusted p-value in Mal, Bdy, and nMal spots. - **Location** (character) - Required - Name of the location defined in ST data (Mal, Bdy, or nMal). - **cut_off_pvalue** (numeric) - Optional - Cut off of p-value; features with p-value < 10^(-cut_off_pvalue) will be selected as significant. Default is 2. - **cut_off_logFC** (numeric) - Optional - Cut off of log2FC; features with log2FC > cut_off_logFC will be selected as significant. Default is 0.25. - **n** (integer) - Optional - Number of features labeled in the volcano plot. Default is 10. ### Returns - **ggplot object** - A visualization of the differential expression results. ### Example ```R DiffVolcanoplot(DiffGenes = DiffGenes, Location = "Bdy", cut_off_pvalue = 2, cut_off_logFC = 0.25, n = 10) ``` ``` -------------------------------- ### STCNVScore(TumorST, assay, OutDir, Sample) Source: https://github.com/yelab2020/cottrazm/blob/main/man/STCNVScore.Rd Scores spatial transcriptomics data using infercnv results and updates the provided Seurat object. ```APIDOC ## STCNVScore ### Description Adds CNV scores and sub-clusters to a Seurat object containing spatial transcriptomics data based on infercnv results. ### Arguments - **TumorST** (Seurat object) - Required - A Seurat object with morphological adjusted expression matrix and determined clusters. - **assay** (character) - Required - Name of the assay used in infercnv (e.g., "Spatial" or "Morph"). - **OutDir** (character) - Optional - Path to the directory where figures and processed data will be saved. - **Sample** (character) - Required - The name of the sample. ### Returns - **Seurat object** - A Seurat object of ST data updated with CNV sub-clusters and CNV scores. ### Example ```R TumorST <- readr::read_rds("YourPath/TumorBoundary/1.BoundaryDefine/CRC1/TumorSTClustered.rds.gz") OutDir <- "YourPath/TumorBoundary/Fig/1.BoundaryDefine/CRC1/" Sample <- "CRC1" assay = "Spatial" TumorST <- STCNVScore(TumorST = TumorST, assay = assay, OutDir = OutDir, Sample = Sample) ``` ```