• Introduction
  • Preprocessing
  • Loading Pathology Data
  • Feature Selection with SPARK
  • Principal Component Analysis (PCA)
  • Processing Pathology Data
  • Visualization of Pathology Data
  • Running KODAMA for Analysis
  • GSVA Enrichment Analysis with MSigDB

Last updated: 2024-07-19

Checks: 7 0

Knit directory: KODAMA-Analysis/

This reproducible R Markdown analysis was created with workflowr (version 1.7.1). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20240618) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version 3f7aad6. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Unstaged changes:
    Deleted:    analysis/figure/DLPFC-12.Rmd/unnamed-chunk-10-1.png
    Modified:   analysis/index.Rmd

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/Prostate.Rmd) and HTML (docs/Prostate.html) files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view the files as they were in that past version.

File Version Author Date Message
Rmd 3f7aad6 Stefano Cacciatore 2024-07-19 Start my new project
Rmd 75d2c78 GitHub 2024-07-15 Update Prostate.Rmd
Rmd 95c6aaf GitHub 2024-07-15 Update Prostate.Rmd
html 7be8f59 tkcaccia 2024-07-15 updates
Rmd f8ca54a tkcaccia 2024-07-14 update
html f8ca54a tkcaccia 2024-07-14 update
Rmd 39586a6 GitHub 2024-07-12 Update Prostate.Rmd
html 60a4b0d GitHub 2024-07-12 Update Prostate.html
html 6660a41 GitHub 2024-07-12 Update Prostate.html
html b9679c8 GitHub 2024-07-12 Update Prostate.html
html 9b0bdad GitHub 2024-07-12 Update Prostate.html
html 4c71aaa GitHub 2024-07-12 Update Prostate.html
Rmd 4a7b4ca GitHub 2024-07-12 Update Prostate.Rmd
html d652bc6 GitHub 2024-07-08 Update Prostate.html
html cac859c GitHub 2024-07-04 Update Prostate.html
html ee4ee17 GitHub 2024-06-19 Add files via upload
Rmd 615fc05 GitHub 2024-06-19 Add files via upload

Introduction

The data used in this analysis come from the Visium database, a reference resource for spatial transcriptomics data. This database provides detailed information on gene expression in various tissue contexts, offering high-resolution spatial data.

For this tutorial, we focus on different types of prostate tissues, including normal prostate, adenocarcinoma, acinar cell carcinoma, and adjacent normal sections. These data are crucial for understanding the variations in gene expression between healthy and cancerous tissues and for identifying potential diagnostic and therapeutic markers.

The data can be downloaded using the following script: Prostate_download.sh. This script facilitates access to the raw data, which will then be preprocessed and analyzed in the subsequent steps of our pipeline.

Preprocessing

This section details the preprocessing of spatial transcriptomics data, which is a crucial step for cleaning and preparing the data for further analysis.

Loading Libraries and Defining Tissue Types

library(SpatialExperiment)
library(scater)
library(nnSVG)
library(SPARK)
library(harmony)
library(scuttle)
library(BiocSingular)

tissues <- c("Normal_prostate",
             "Acinar_Cell_Carcinoma",
             "Adjacent_normal_section",
             "Adenocarcinoma")

Begin by loading the necessary libraries for the analysis. Next, define the different types of prostate tissues to be studied: normal prostate, acinar cell carcinoma, adjacent normal sections, and adenocarcinoma.

Reading Visium Data

dir <- "../Prostate/"
address <- file.path(dir, tissues, "")

spe <- read10xVisium(address, tissues,
                     type = "sparse", data = "raw",
                     images = "lowres", load = FALSE)

Visualization

par(mfrow = c(1, 4))

img=as.raster(getImg(spe, sample_id = "Normal_prostate" , image_id = NULL))
plot(img)
box(col="#77cc66",lwd=3)
mtext("Normal prostate")

img=as.raster(getImg(spe, sample_id = "Acinar_Cell_Carcinoma" , image_id = NULL))
plot(img)
box(col="#77cc66",lwd=3)
mtext("Acinar cell carcinoma")

img=as.raster(getImg(spe, sample_id = "Adenocarcinoma" , image_id = NULL))
plot(img)
box(col="#77cc66",lwd=3)
mtext("Adenocarcinoma")

img=as.raster(getImg(spe, sample_id = "Adjacent_normal_section" , image_id = NULL))
plot(img)
box(col="#77cc66",lwd=3)
mtext("Adjacent Normal section with IF")

Loading Pathology Data

To begin the pathology data analysis, load the corresponding pathology data for adenocarcinoma samples. Ensure to replace the file path with the correct location of your data.

patho <- read.csv("data/Pathology.csv")

Loading Preprocessed Data

metaData <- SingleCellExperiment::colData(spe)
expr <- SingleCellExperiment::counts(spe)
sample_names <- unique(colData(spe)$sample_id)

Load the preprocessed data and extract the metadata and gene expression counts.

Filtering Tissue Spots and Identifying Mitochondrial Genes

spe <- spe[, colData(spe)$in_tissue]

# Identify mitochondrial genes
is_mito <- grepl("(^MT-)|(^mt-)", rowData(spe)$gene_name)
table(is_mito)
< table of extent 0 >

Filter the spots located in the tissue and identify mitochondrial genes, which are often used as quality indicators.

Calculating Quality Control (QC) Metrics per Spot

# Calculate per-spot QC metrics
spe <- addPerCellQC(spe, subsets = list(mito = is_mito))

# Select QC thresholds
qc_lib_size <- colData(spe)$sum < 500
qc_detected <- colData(spe)$detected < 250
qc_mito <- colData(spe)$subsets_mito_percent > 30
qc_cell_count <- colData(spe)$cell_count > 12

# Spots to discard
discard <- qc_lib_size | qc_detected | qc_mito | qc_cell_count

if (length(discard) > 0) {
  table(discard)
  colData(spe)$discard <- discard
  
  # Filter low-quality spots
  spe <- spe[, !colData(spe)$discard]
}
dim(spe)
[1] 36945 13417

Calculate several QC metrics per spot, such as library size, number of detected genes, percentage of mitochondrial genes, and cell count. Define thresholds for these metrics and filter out low-quality spots.

Filtering Genes

colnames(rowData(spe)) <- "gene_name"

spe <- filter_genes(
  spe,
  filter_genes_ncounts = 2,   # Minimum counts
  filter_genes_pcspots = 0.5, # Minimum percentage of spots
  filter_mito = TRUE          # Filter mitochondrial genes
)

dim(spe)
[1] 12527 13417

Filter genes based on the number of counts and the percentage of spots in which they are present. Mitochondrial genes are also filtered out.

Adjusting Spatial Coordinates

xy <- spatialCoords(spe)
samples <- unique(colData(spe)$sample_id)

for (j in 1:length(samples)) {
  sel <- samples[j] == colData(spe)$sample_id
  xy[sel, 1] <- spatialCoords(spe)[sel, 1] + 25000 * (j - 1)
}
spatialCoords(spe) <- xy

Adjust the spatial coordinates of each sample to separate them visually, facilitating data analysis and visualization.

Normalizing Counts

spe <- computeLibraryFactors(spe)
spe <- logNormCounts(spe)

normalize the counts using library size factors and apply a logarithmic transformation to obtain data ready for more precise analysis.

This preprocessing process cleans and normalizes the spatial transcriptomics data, ensuring high-quality data ready for subsequent analyses.

Feature Selection with SPARK

After preprocessing the data, the next step involves feature selection using SPARK, which is crucial for identifying significant genes across different tissue samples.

pvalue_mat <- matrix(NA, nrow = nrow(spe), ncol = length(sample_names))
rownames(pvalue_mat) <- rownames(rowData(spe))

# Perform SPARK analysis for each sample
for (i in 1:length(sample_names)) {
  sel <- colData(spe)$sample_id == sample_names[i]
  spe_sub <- spe[, sel]
  
  sparkX <- sparkx(logcounts(spe_sub), spatialCoords(spe_sub), numCores = 1, option = "mixture",verbose=FALSE)
  
  pvalue_mat[rownames(sparkX$res_mtest), i] <- sparkX$res_mtest$combinedPval
  print(sample_names[i])
}
## ===== SPARK-X INPUT INFORMATION ==== 
## number of total samples: 2543 
## number of total genes: 12519 
## Running with single core, may take some time 
## Testing With Projection Kernel
## Testing With Gaussian Kernel 1
## Testing With Gaussian Kernel 2
## Testing With Gaussian Kernel 3
## Testing With Gaussian Kernel 4
## Testing With Gaussian Kernel 5
## Testing With Cosine Kernel 1
## Testing With Cosine Kernel 2
## Testing With Cosine Kernel 3
## Testing With Cosine Kernel 4
## Testing With Cosine Kernel 5
[1] "Normal_prostate"
## ===== SPARK-X INPUT INFORMATION ==== 
## number of total samples: 3043 
## number of total genes: 12524 
## Running with single core, may take some time 
## Testing With Projection Kernel
## Testing With Gaussian Kernel 1
## Testing With Gaussian Kernel 2
## Testing With Gaussian Kernel 3
## Testing With Gaussian Kernel 4
## Testing With Gaussian Kernel 5
## Testing With Cosine Kernel 1
## Testing With Cosine Kernel 2
## Testing With Cosine Kernel 3
## Testing With Cosine Kernel 4
## Testing With Cosine Kernel 5
[1] "Acinar_Cell_Carcinoma"
## ===== SPARK-X INPUT INFORMATION ==== 
## number of total samples: 3460 
## number of total genes: 12521 
## Running with single core, may take some time 
## Testing With Projection Kernel
## Testing With Gaussian Kernel 1
## Testing With Gaussian Kernel 2
## Testing With Gaussian Kernel 3
## Testing With Gaussian Kernel 4
## Testing With Gaussian Kernel 5
## Testing With Cosine Kernel 1
## Testing With Cosine Kernel 2
## Testing With Cosine Kernel 3
## Testing With Cosine Kernel 4
## Testing With Cosine Kernel 5
[1] "Adjacent_normal_section"
## ===== SPARK-X INPUT INFORMATION ==== 
## number of total samples: 4371 
## number of total genes: 12525 
## Running with single core, may take some time 
## Testing With Projection Kernel
## Testing With Gaussian Kernel 1
## Testing With Gaussian Kernel 2
## Testing With Gaussian Kernel 3
## Testing With Gaussian Kernel 4
## Testing With Gaussian Kernel 5
## Testing With Cosine Kernel 1
## Testing With Cosine Kernel 2
## Testing With Cosine Kernel 3
## Testing With Cosine Kernel 4
## Testing With Cosine Kernel 5
[1] "Adenocarcinoma"
pvalue_mat=pvalue_mat[!is.na(rowSums(pvalue_mat)),]

oo=order(apply(pvalue_mat,1,function(x) mean(-log(x))),decreasing = TRUE)
top=rownames(pvalue_mat)[oo]

Principal Component Analysis (PCA)

After feature selection, principal component analysis (PCA) is performed to explore the variance in the dataset and visualize sample relationships.

sample_id=colData(spe)$sample_id

library(ggplot2)

# Run PCA with top selected genes
spe <- runPCA(spe, subset_row = top[1:3000], scale = TRUE)

# Run Harmony to adjust for batch effects
spe <- RunHarmony(spe, group.by.vars = "sample_id", lambda = NULL)

# Visualize PCA and Harmony results
plot(reducedDim(spe, type = "PCA"), col = as.factor(colData(spe)$sample_id), main = "PCA")

plot(reducedDim(spe, type = "HARMONY"), col = as.factor(colData(spe)$sample_id), main = "Harmony")

pca=reducedDim(spe,type = "HARMONY")[,1:50]
samples=as.factor(colData(spe)$sample_id)
xy=as.matrix(spatialCoords(spe))
data=t(logcounts(spe))

Processing Pathology Data

The processing involves creating row names and associating pathology information with the corresponding columns in the spe object.

rownames(patho) <- patho[,1]
pathology <- rep(NA, ncol(spe))
sel <- colData(spe)$sample_id == "Adenocarcinoma"
pathology[sel] <- patho[rownames(colData(spe))[sel], "Pathology"]
pathology[pathology == ""] <- NA
pathology <- factor(pathology, levels = c("Invasive carcinoma",
                                          "Blood vessel",
                                          "Fibro-muscular tissue",
                                          "Fibrous tissue",
                                          "Immune Cells",
                                          "Nerve",
                                          "Normal gland"))

Visualization of Pathology Data

Assign specific colors to each pathology category and visualize the samples on a reduced dimension map (HARMONY), with each point colored according to its pathology category.

col_pathology <- c("#0000ff", "#e41a1c", "#006400", "#000000", "#ffd700", "#00ff00", "#b2dfee")
plot(reducedDim(spe, type = "HARMONY"), pch = 20, col = col_pathology[pathology])

Version Author Date
f8ca54a tkcaccia 2024-07-14
c4d73d4 GitHub 2024-07-12
e20ceb2 GitHub 2024-07-12
fe5a2ba GitHub 2024-07-12

Running KODAMA for Analysis

The next step is running KODAMA, a method for dimensionality reduction and visualization.

library(KODAMAextra)

spe <- RunKODAMAmatrix(spe,
                       reduction = "HARMONY",
                       FUN = "PLS",
                       landmarks = 100000,
                       splitting = 300,
                       f.par.pls = 50,
                       spatial.resolution = 0.4,
                       n.cores = 4)
socket cluster with 4 nodes on host 'localhost'
================================================================================[1] "Finished parallel computation"

[1] "Calculation of dissimilarity matrix..."
================================================================================
config <- umap.defaults
config$n_threads = 4
config$n_sgd_threads = "auto"

spe=RunKODAMAvisualization(spe,method="UMAP",config=config)

plot(reducedDim(spe,type = "KODAMA"),col=as.factor(colData(spe)$sample_id))

Version Author Date
4ca7eda GitHub 2024-07-12
fe5a2ba GitHub 2024-07-12
plot(reducedDim(spe,type = "KODAMA"),col=pathology)

Version Author Date
b8fa0b8 GitHub 2024-07-12
fe5a2ba GitHub 2024-07-12

This extended analysis includes principal component analysis (PCA), pathology data analysis, and the application of KODAMA for dimensionality reduction and visualization, enhancing the understanding of spatial transcriptomics data in different prostate tissue types.

GSVA Enrichment Analysis with MSigDB

To explore enriched biological processes in our spatial transcriptomics data, we employ Gene Set Variation Analysis (GSVA) using MSigDB gene sets as a reference. To download the necessary data, please follow the steps provided at this link and create an account if required.

Loading Packages and Data

We start by loading the necessary packages and preparing our gene data for analysis:

# library("GSVA")
# library("GSA")
# library("gprofiler2")
# library("VAM")
# geneset=GSA.read.gmt("../Genesets/msigdb_v2023.2.Hs_GMTs/h.all.v2023.2.Hs.symbols.gmt")
# names(geneset$genesets)=geneset$geneset.names
# genesets=geneset$genesets

# countdata <- t(as.matrix(logcounts(spe)))
# genes=gconvert(rownames(spe),organism="hsapiens",target="GENECARDS",filter_na = F)$target
# colnames(countdata)=genes
# rownames(countdata)=paste(gsub("-1","",colnames(spe)),spe$sample_id,sep="-")

# li=lapply(genesets,function(x) which(genes %in% x))

# VAM=vamForCollection(gene.expr=countdata, gene.set.collection=li)
# VAM$distance.sq

sessionInfo()
R version 4.4.1 (2024-06-14)
Platform: x86_64-pc-linux-gnu
Running under: Ubuntu 20.04.6 LTS

Matrix products: default
BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0 
LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

time zone: Etc/UTC
tzcode source: system (glibc)

attached base packages:
[1] parallel  stats4    stats     graphics  grDevices utils     datasets 
[8] methods   base     

other attached packages:
 [1] KODAMAextra_1.0             e1071_1.7-14               
 [3] doParallel_1.0.17           iterators_1.0.14           
 [5] foreach_1.5.2               KODAMA_3.1                 
 [7] umap_0.2.10.0               Rtsne_0.17                 
 [9] minerva_1.5.10              BiocSingular_1.20.0        
[11] harmony_1.2.0               Rcpp_1.0.12                
[13] SPARK_1.1.1                 nnSVG_1.8.0                
[15] scater_1.32.0               ggplot2_3.5.1              
[17] scuttle_1.14.0              SpatialExperiment_1.14.0   
[19] SingleCellExperiment_1.26.0 SummarizedExperiment_1.34.0
[21] Biobase_2.64.0              GenomicRanges_1.56.1       
[23] GenomeInfoDb_1.40.1         IRanges_2.38.1             
[25] S4Vectors_0.42.1            BiocGenerics_0.50.0        
[27] MatrixGenerics_1.16.0       matrixStats_1.3.0          
[29] workflowr_1.7.1            

loaded via a namespace (and not attached):
  [1] rstudioapi_0.16.0         jsonlite_1.8.8           
  [3] magrittr_2.0.3            ggbeeswarm_0.7.2         
  [5] magick_2.8.4              rmarkdown_2.27           
  [7] fs_1.6.4                  zlibbioc_1.50.0          
  [9] vctrs_0.6.5               DelayedMatrixStats_1.26.0
 [11] askpass_1.2.0             CompQuadForm_1.4.3       
 [13] htmltools_0.5.8.1         S4Arrays_1.4.1           
 [15] BiocNeighbors_1.22.0      Rhdf5lib_1.26.0          
 [17] SparseArray_1.4.8         rhdf5_2.48.0             
 [19] sass_0.4.9                pracma_2.4.4             
 [21] bslib_0.7.0               cachem_1.1.0             
 [23] whisker_0.4.1             lifecycle_1.0.4          
 [25] pkgconfig_2.0.3           rsvd_1.0.5               
 [27] Matrix_1.7-0              R6_2.5.1                 
 [29] fastmap_1.2.0             GenomeInfoDbData_1.2.12  
 [31] digest_0.6.36             colorspace_2.1-0         
 [33] ps_1.7.7                  rprojroot_2.0.4          
 [35] RSpectra_0.16-1           dqrng_0.4.1              
 [37] irlba_2.3.5.1             beachmat_2.20.0          
 [39] fansi_1.0.6               httr_1.4.7               
 [41] abind_1.4-5               compiler_4.4.1           
 [43] proxy_0.4-27              BRISC_1.0.5              
 [45] withr_3.0.0               BiocParallel_1.38.0      
 [47] viridis_0.6.5             highr_0.11               
 [49] HDF5Array_1.32.0          R.utils_2.12.3           
 [51] openssl_2.2.0             DelayedArray_0.30.1      
 [53] rjson_0.2.21              rdist_0.0.5              
 [55] tools_4.4.1               vipor_0.4.7              
 [57] beeswarm_0.4.0            httpuv_1.6.15            
 [59] R.oo_1.26.0               glue_1.7.0               
 [61] callr_3.7.6               rhdf5filters_1.16.0      
 [63] promises_1.3.0            grid_4.4.1               
 [65] getPass_0.2-4             snow_0.4-4               
 [67] generics_0.1.3            gtable_0.3.5             
 [69] class_7.3-22              R.methodsS3_1.8.2        
 [71] ScaledMatrix_1.12.0       utf8_1.2.4               
 [73] XVector_0.44.0            ggrepel_0.9.5            
 [75] RANN_2.6.1                pillar_1.9.0             
 [77] stringr_1.5.1             limma_3.60.3             
 [79] later_1.3.2               dplyr_1.1.4              
 [81] lattice_0.22-6            tidyselect_1.2.1         
 [83] locfit_1.5-9.10           pbapply_1.7-2            
 [85] knitr_1.48                git2r_0.33.0             
 [87] gridExtra_2.3             edgeR_4.2.1              
 [89] RhpcBLASctl_0.23-42       xfun_0.45                
 [91] statmod_1.5.0             DropletUtils_1.24.0      
 [93] stringi_1.8.4             UCSC.utils_1.0.0         
 [95] yaml_2.3.9                evaluate_0.24.0          
 [97] codetools_0.2-20          tibble_3.2.1             
 [99] cli_3.6.3                 matlab_1.0.4.1           
[101] reticulate_1.38.0         munsell_0.5.1            
[103] processx_3.8.4            jquerylib_0.1.4          
[105] doSNOW_1.0.20             png_0.1-8                
[107] sparseMatrixStats_1.16.0  viridisLite_0.4.2        
[109] scales_1.3.0              crayon_1.5.3             
[111] rlang_1.1.4               cowplot_1.1.3