Last updated: 2025-04-14
Checks: 6 1
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.
The R Markdown file has unstaged changes. To know which version of
the R Markdown file created these results, you’ll want to first commit
it to the Git repo. If you’re still working on the analysis, you can
ignore this warning. When you’re finished, you can run
wflow_publish
to commit the R Markdown file and build the
HTML.
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 5f5ac63. 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:
Ignored files:
Ignored: .RData
Ignored: .Rhistory
Ignored: .Rproj.user/
Untracked files:
Untracked: KODAMA.svg
Untracked: analysis/singlecell_datamatrix.Rmd
Untracked: analysis/singlecell_seurat.Rmd
Untracked: code/Acinar_Cell_Carcinoma.ipynb
Untracked: code/Adenocarcinoma.ipynb
Untracked: code/Adjacent_normal_section.ipynb
Untracked: code/DLFPC_preprocessing.R
Untracked: code/DLPFC - BANKSY.R
Untracked: code/DLPFC - BASS.R
Untracked: code/DLPFC - BAYESPACE.R
Untracked: code/DLPFC - Nonspatial.R
Untracked: code/DLPFC - PRECAST.R
Untracked: code/DLPFC_comparison.R
Untracked: code/DLPFC_results_analysis.R
Untracked: code/MERFISH - BANKSY.R
Untracked: code/MERFISH - BASS.R
Untracked: code/MERFISH - BAYESPACE.R
Untracked: code/MERFISH - Nonspatial.R
Untracked: code/MERFISH - PRECAST.R
Untracked: code/MERFISH_comparison.R
Untracked: code/MERFISH_results_analysis.R
Untracked: code/VisiumHD-CRC.ipynb
Untracked: code/VisiumHDassignment.py
Untracked: code/deep learning code DLPFC.R
Untracked: code/save tiles.py
Untracked: data/Annotations/
Untracked: data/DLFPC-Br5292-input.RData
Untracked: data/DLFPC-Br5595-input.RData
Untracked: data/DLFPC-Br8100-input.RData
Untracked: data/DLPFC-general.RData
Untracked: data/MERFISH-input.RData
Untracked: data/trajectories.RData
Untracked: data/trajectories_VISIUMHD.RData
Untracked: output/BANSKY-results.RData
Untracked: output/BASS-results.RData
Untracked: output/BayesSpace-results.RData
Untracked: output/CRC-image.RData
Untracked: output/CRC-image2.RData
Untracked: output/CRC.png
Untracked: output/CRC2.png
Untracked: output/CRC7.png
Untracked: output/CRC8.png
Untracked: output/CRC_boxplot.png
Untracked: output/CRC_boxplot.svg
Untracked: output/CRC_boxplot2.svg
Untracked: output/CRC_linee.svg
Untracked: output/DL.RData
Untracked: output/DLFPC-All-2.RData
Untracked: output/DLFPC-All.RData
Untracked: output/DLFPC-Br5292.RData
Untracked: output/DLFPC-Br5595.RData
Untracked: output/DLFPC-Br8100.RData
Untracked: output/DLFPC-variablesXdeeplearning.RData
Untracked: output/DLPFC-BANSKY-results.RData
Untracked: output/DLPFC-BASS-results.RData
Untracked: output/DLPFC-BayesSpace-results.RData
Untracked: output/DLPFC-Nonspatial-results.RData
Untracked: output/DLPFC-PRECAST-results.RData
Untracked: output/DLPFC_all_cluster.svg
Untracked: output/DLPFCpathway.RData
Untracked: output/Figure 1 - boxplot.pdf
Untracked: output/Figure 2 - DLPFC 10.pdf
Untracked: output/Figures/
Untracked: output/KODAMA-results.RData
Untracked: output/KODAMA_DLPFC_All_original.svg
Untracked: output/KODAMA_DLPFC_Br5595.svg
Untracked: output/KODAMA_DLPFC_Br5595_slide.svg
Untracked: output/Loupe.csv
Untracked: output/MERFISH-BANSKY-results.RData
Untracked: output/MERFISH-BASS-results.RData
Untracked: output/MERFISH-BayesSpace-results.RData
Untracked: output/MERFISH-KODAMA-results.RData
Untracked: output/MERFISH-Nonspatial-results.RData
Untracked: output/MERFISH-PRECAST-results.RData
Untracked: output/MERFISH.RData
Untracked: output/Nonspatial-results.RData
Untracked: output/Prostate-GSEA.csv
Untracked: output/Prostate-KODAMA.RData
Untracked: output/Prostate-trajectory.csv
Untracked: output/Prostate.RData
Untracked: output/VisiumHD-RNA.RData
Untracked: output/VisiumHD-genes.pdf
Untracked: output/VisiumHD.RData
Untracked: output/boh.svg
Untracked: output/desmoplastic_distance_carcinoma.csv
Untracked: output/image.RData
Untracked: output/pp.RData
Untracked: output/pp2.RData
Untracked: output/pp3.RData
Untracked: output/pp4.RData
Untracked: output/pp5.RData
Untracked: output/prostate1.svg
Untracked: output/prostate2.svg
Untracked: output/prostate3.svg
Untracked: output/subclusters1.csv
Untracked: output/subclusters2.csv
Untracked: output/subclusters3.csv
Untracked: output/tight_boundary.geojson
Untracked: output/trajectory.csv
Unstaged changes:
Deleted: analysis/D1.Rmd
Deleted: analysis/DLPFC-12.Rmd
Deleted: analysis/DLPFC-4.Rmd
Modified: analysis/DLPFC.Rmd
Deleted: analysis/DLPFC1.Rmd
Deleted: analysis/DLPFC10.Rmd
Deleted: analysis/DLPFC2.Rmd
Deleted: analysis/DLPFC3.Rmd
Deleted: analysis/DLPFC4.Rmd
Deleted: analysis/DLPFC5.Rmd
Deleted: analysis/DLPFC6.Rmd
Deleted: analysis/DLPFC7.Rmd
Deleted: analysis/DLPFC8.Rmd
Deleted: analysis/DLPFC9.Rmd
Deleted: analysis/Du1.Rmd
Deleted: analysis/Du10.Rmd
Deleted: analysis/Du11.Rmd
Deleted: analysis/Du12.Rmd
Deleted: analysis/Du13.Rmd
Deleted: analysis/Du14.Rmd
Deleted: analysis/Du15.Rmd
Deleted: analysis/Du16.Rmd
Deleted: analysis/Du17.Rmd
Deleted: analysis/Du18.Rmd
Deleted: analysis/Du19.Rmd
Deleted: analysis/Du2.Rmd
Deleted: analysis/Du20.Rmd
Deleted: analysis/Du3.Rmd
Deleted: analysis/Du4.Rmd
Deleted: analysis/Du5.Rmd
Deleted: analysis/Du6.Rmd
Deleted: analysis/Du7.Rmd
Deleted: analysis/Du8.Rmd
Deleted: analysis/Du9.Rmd
Modified: analysis/Giotto.Rmd
Modified: analysis/MERFISH.Rmd
Deleted: analysis/MERFISH1a (copy).Rmd
Deleted: analysis/MERFISH1a.Rmd
Deleted: analysis/MERFISH1b (copy).Rmd
Deleted: analysis/MERFISH1b.Rmd
Deleted: analysis/MERFISH2a (copy).Rmd
Deleted: analysis/MERFISH2a.Rmd
Deleted: analysis/MERFISH2b (copy).Rmd
Deleted: analysis/MERFISH2b.Rmd
Deleted: analysis/MERFISH3a (copy).Rmd
Deleted: analysis/MERFISH3a.Rmd
Deleted: analysis/MERFISH3b (copy).Rmd
Deleted: analysis/MERFISH3b.Rmd
Deleted: analysis/MERFISH4a (copy).Rmd
Deleted: analysis/MERFISH4a.Rmd
Deleted: analysis/MERFISH4b (copy).Rmd
Deleted: analysis/MERFISH4b.Rmd
Modified: analysis/Prostate.Rmd
Deleted: analysis/STARmap.Rmd
Modified: analysis/Seurat.Rmd
Deleted: analysis/Simulation.Rmd
Deleted: analysis/Single-cell.Rmd
Modified: analysis/SpatialExperiment.Rmd
Modified: analysis/VisiumHD.Rmd
Modified: code/VisiumHD_CRC_download.sh
Deleted: data/Pathology.csv
Deleted: data/merfish.Rmd
Deleted: data/vis.R
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 |
---|---|---|---|---|
html | 24f5fe4 | Stefano Cacciatore | 2025-01-08 | Build site. |
Rmd | 2077f71 | Stefano Cacciatore | 2025-01-08 | Start my new project |
Rmd | ff717c1 | Stefano Cacciatore | 2025-01-08 | Start my new project |
html | a11cbcc | Stefano Cacciatore | 2024-09-14 | Build site. |
Rmd | edbb375 | Stefano Cacciatore | 2024-09-14 | Start my new project |
html | 460bb2d | Stefano Cacciatore | 2024-09-04 | Build site. |
Rmd | 3040393 | Stefano Cacciatore | 2024-09-04 | Start my new project |
html | ac43fcf | Stefano Cacciatore | 2024-09-02 | Build site. |
Rmd | be96835 | Stefano Cacciatore | 2024-09-02 | Start my new project |
html | 46cbd5a | Stefano Cacciatore | 2024-09-02 | Build site. |
Rmd | 9cc4b2b | Stefano Cacciatore | 2024-09-02 | Start my new project |
html | 202bc0e | Stefano Cacciatore | 2024-09-02 | Build site. |
Rmd | b9309f4 | Stefano Cacciatore | 2024-09-02 | Start my new project |
html | b1a5ea0 | Stefano Cacciatore | 2024-08-26 | Build site. |
Rmd | 22e2ac6 | Stefano Cacciatore | 2024-08-26 | Start my new project |
html | d1192e9 | Stefano Cacciatore | 2024-08-12 | Build site. |
html | 3374e66 | Stefano Cacciatore | 2024-08-06 | Build site. |
html | 35ce733 | Stefano Cacciatore | 2024-08-03 | Build site. |
html | 82fe167 | Stefano Cacciatore | 2024-07-24 | Build site. |
html | 6f7daac | Stefano Cacciatore | 2024-07-19 | Build site. |
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 |
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.
This section details the preprocessing of spatial transcriptomics data, which is a crucial step for cleaning and preparing the data for further analysis.
library(SpatialExperiment)
library(scater)
library(nnSVG)
library(SPARK)
library(harmony)
library(scuttle)
library(BiocSingular)
library(spatialLIBD)
library(KODAMAextra)
opar <- par() # make a copy of current settings
tissues <- c("Normal_prostate",
"Acinar_Cell_Carcinoma",
"Adjacent_normal_section",
"Adenocarcinoma")
n.cores=12
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.
dir <- "../Prostate/"
address <- file.path(dir, tissues, "")
spe <- read10xVisium(address, tissues,
type = "sparse", data = "raw",
images = "lowres", load = FALSE)
rownames(colData(spe))=paste(gsub("-1","",rownames(colData(spe))),colData(spe)$sample_id,sep="-")
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")
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.
ss <- read.csv("data/Annotations/Adenocarcinoma.csv")
annotation_Adenocarcinoma= ss[,2]
names(annotation_Adenocarcinoma)=ss[,1]
annotation_Adenocarcinoma=annotation_Adenocarcinoma[annotation_Adenocarcinoma!=""]
names(annotation_Adenocarcinoma)=paste(gsub("-1","",names(annotation_Adenocarcinoma)),"Adenocarcinoma",sep="-")
annotation_Acinar_Cell_Carcinoma=read_annotations("data/Annotations/spots_classification_Acinar_Cell_Carcinoma.csv")
names(annotation_Acinar_Cell_Carcinoma)=paste(gsub("-1","",names(annotation_Acinar_Cell_Carcinoma)),"Acinar_Cell_Carcinoma",sep="-")
annotation_Adjacent_normal_section=read_annotations("data/Annotations/spots_classification_IF.csv")
names(annotation_Adjacent_normal_section)=paste(gsub("-1","",names(annotation_Adjacent_normal_section)),"Adjacent_normal_section",sep="-")
annotation_Normal_Prostate=read_annotations("data/Annotations/spots_classification_Normal_prostate.csv")
names(annotation_Normal_Prostate)=paste(gsub("-1","",names(annotation_Normal_Prostate)),"Normal_prostate",sep="-")
annotations = c(annotation_Normal_Prostate,
annotation_Acinar_Cell_Carcinoma,
annotation_Adjacent_normal_section,
annotation_Adenocarcinoma)
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.
spe <- spe[, colData(spe)$in_tissue]
# Identify mitochondrial genes
is_mito <- grepl("(^MT-)|(^mt-)", rowData(spe)$gene_name)
Filter the spots located in the tissue and identify mitochondrial genes, which are often used as quality indicators.
# 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.
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.
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.
After preprocessing the data, the next step involves feature selection using SPARK, which is crucial for identifying significant genes across different tissue samples.
top=multi_SPARKX(spe,n.cores=n.cores)
After feature selection, principal component analysis (PCA) is performed to explore the variance in the dataset and visualize sample relationships.
samples=as.factor(colData(spe)$sample_id)
xy=as.matrix(spatialCoords(spe))
rownames(xy)=rownames(colData(spe))
data=as.matrix(t(logcounts(spe)))
gene_names=spe@rowRanges@elementMetadata$gene_name
gene_ids=names(spe@rowRanges)
colnames(data)=gene_names
names(gene_names)=gene_ids
top_genes=gene_names[top[1:2000]]
library(ggplot2)
cols_tissue <- c("#0000b6cc", "#81b29acc", "#f2cc8fcc","#e07a5fcc")
# Run PCA with top selected genes
spe <- runPCA(spe, subset_row = top[1:2000], scale = TRUE)
# Run Harmony to adjust for batch effects
spe <- RunHarmony(spe, group.by.vars = "sample_id", lambda = NULL)
# Visualize PCA and Harmony results
df <- data.frame(reducedDim(spe,type = "PCA")[,1:2], tissue=samples)
plot1 = ggplot(df, aes(PC1, PC2, color = tissue)) +labs(title="PCA") +
geom_point(size = 2) +
theme_bw() + theme(legend.position = "bottom")+
scale_color_manual("Domain", values = cols_tissue) +
guides(color = guide_legend(nrow = 2,
override.aes = list(size = 2)))
df <- data.frame(reducedDim(spe,type = "HARMONY")[,1:2], tissue=samples)
plot2 = ggplot(df, aes(HARMONY_1, HARMONY_2, color = tissue)) +labs(title="PCA") +
geom_point(size = 2) +
theme_bw() + theme(legend.position = "bottom")+
scale_color_manual("Domain", values = cols_tissue) +
guides(color = guide_legend(nrow = 2,
override.aes = list(size = 2)))
pca=reducedDim(spe,type = "HARMONY")[,1:50]
plot1
plot2
svg("output/Figures/Prostate/prostate1.svg",height = 3)
plot1
dev.off()
png
2
svg("output/Figures/Prostate/prostate2.svg",height = 3)
plot2
dev.off()
png
2
The processing involves creating row names and associating pathology information with the corresponding columns in the spe object.
annotations=annotations[rownames(colData(spe))]
annotations[annotations=="fibrous"]="fibromuscular"
names(annotations)=rownames(colData(spe))
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.
cols_pathology <- c("#0000ffcc", "#e41a1ccc", "#006400cc", "#000000cc", "#ffd700cc",
"#00ff00cc", "#b2dfeecc","#669bbccc", "#81b29acc", "#f2cc8fcc",
"#adc178cc", "#aa1133cc", "#1166dccc", "#e5989bcc", "#e07a5fcc")
df <- data.frame(pca[,1:2], tissue=annotations)
df=df[!is.na(annotations),]
plot3=ggplot(df, aes(HARMONY_1, HARMONY_2, color = tissue)) +labs(title="PCA") +
geom_point(size = 2) +
theme_bw() + theme(legend.position = "bottom")+
scale_color_manual("Domain", values = cols_pathology) +
guides(color = guide_legend(nrow = 2,
override.aes = list(size = 2)))
svg("output/Figures/Prostate/prostate3.svg",height = 3)
plot3
dev.off()
png
2
The next step is running KODAMA, a method for dimensionality reduction and visualization.
spe=RunKODAMAmatrix(spe,
reduction = "HARMONY",
FUN= "fastpls" ,
landmarks = 100000,
splitting = 300,
ncomp = 50,
spatial.resolution = 0.3,
n.cores=n.cores,
seed = 543210)
Calculating Network
Calculating Network spatial
socket cluster with 12 nodes on host 'localhost'
================================================================================
Finished parallel computation
[1] "Calculation of dissimilarity matrix..."
================================================================================
config <- umap.defaults
config$n_threads = n.cores
config$n_sgd_threads = "auto"
spe=RunKODAMAvisualization(spe,method="UMAP",config=config)
save(spe,file="output/Prostate-KODAMA.RData")
df <- data.frame(reducedDim(spe,type = "KODAMA")[,1:2], tissue=as.factor(colData(spe)$sample_id))
plot4=ggplot(df, aes(Dimension.1, Dimension.2, color = tissue)) +labs(title="KODAMA") +
geom_point(size = 2) +
theme_bw() + theme(legend.position = "bottom")+
scale_color_manual("Domain", values = cols_tissue) +
guides(color = guide_legend(nrow = 2,
override.aes = list(size = 2)))
df <- data.frame(reducedDim(spe,type = "KODAMA")[,1:2], tissue=annotations)
plot5=ggplot(df, aes(Dimension.1, Dimension.2, color = tissue)) +labs(title="KODAMA") +
geom_point(size = 2) +
theme_bw() + theme(legend.position = "bottom")+
scale_color_manual("Domain", values = cols_pathology) +
guides(color = guide_legend(nrow = 3,
override.aes = list(size = 2)))
plot4
plot5
svg("output/Figures/Prostate/prostate4.svg",height = 6,width = 10)
plot4
dev.off()
png
2
svg("output/Figures/Prostate/prostate5.svg",height = 6,width = 10)
plot5
dev.off()
png
2
ko=reducedDim(spe,type = "KODAMA")
g <- bluster::makeSNNGraph(as.matrix(ko), k = 50)
g_walk <- igraph::cluster_louvain(g,resolution = 0.2)
clu = g_walk$membership
table(clu,annotations)
annotations
clu benign blood vessel fibromuscular Gleason 3 Gleason 4 Gleason 5
1 0 0 5 0 0 0
2 0 19 710 0 0 0
3 0 0 54 0 0 0
4 0 21 85 0 0 0
5 0 4 0 0 0 0
6 24 0 11 78 57 0
7 0 0 4 0 0 0
8 42 0 99 42 77 70
9 1 0 30 0 0 0
10 2 0 3 0 0 0
annotations
clu hyperplasia gland hyperplasia stroma immune cells Invasive carcinoma Nerve
1 613 9 0 3 0
2 2 1 8 2 40
3 9 3 0 1 0
4 1 3 0 0 0
5 89 349 0 0 0
6 0 0 1 2 0
7 0 8 0 0 0
8 0 0 14 183 0
9 0 0 0 564 0
10 0 0 0 1187 0
annotations
clu normal gland normal stroma tumor stroma
1 412 0 0
2 53 819 0
3 1017 33 0
4 120 817 0
5 16 64 0
6 2 0 0
7 2 293 0
8 2 0 21
9 106 0 0
10 0 0 0
cols_cluster <- c("#0000b6cc", "#81b29acc", "#f2cc8fcc","#e07a5fcc",
"#cc00b6cc", "#81ccffcc", "#00cc8fcc","#e0aa5fcc",
"#0088ddcc", "#33b233cc", "#aa228fcc","#aa7a6fcc")
df <- data.frame(reducedDim(spe, type = "KODAMA")[, 1:2],
cluster = as.factor(clu),
tissue = annotations,
sample= spe$sample_id)
df$cluster <- as.factor(df$cluster)
plot6 <- ggplot(df, aes(Dimension.1, Dimension.2, color = cluster)) +
geom_point(size = 2) +
geom_point(data = subset(df, tissue == "normal gland" & sample=="Adenocarcinoma"),
shape = 3, color = "#000000aa", stroke = 1, size = 2) + # cross on top
theme_bw() +
theme(legend.position = "bottom") +
scale_color_manual("Domain", values = cols_cluster) +
guides(color = guide_legend(nrow = 2, override.aes = list(size = 2)))
plot6
plot7=plot_slide(xy,samples,as.factor(clu),nrow=1,col = cols_cluster)
plot6
plot7
svg("output/Figures/Prostate/prostate6.svg",height = 8,width = 10)
plot6
dev.off()
png
2
svg("output/Figures/Prostate/prostate7.svg",height = 4,width = 10)
plot7
dev.off()
png
2
par(opar)
sel=colData(spe)$sample_id=="Acinar_Cell_Carcinoma"
spe_sub=spe[,sel]
image=as.raster(imgData(spe_sub)$data[[1]])
xy_sel=spatialCoords(spe_sub)
xy_sel=xy_sel*scaleFactors(spe_sub)
xy_sel[,2]=nrow(image)-xy_sel[,2]
plot(image)
points(xy_sel,cex=0.5,pch=20,col="#33333333")
data_sub=as.matrix(t(logcounts(spe_sub)))
colnames(data_sub)=gene_names
# nn1=new_trajectory (xy_sel,data = data)
# nn2=new_trajectory (xy_sel,data = data)
# nn3=new_trajectory (xy_sel,data = data)
load("data/trajectories.RData")
mm1=new_trajectory (xy_sel,data = data_sub,trace=nn1$xy)
mm2=new_trajectory (xy_sel,data = data_sub,trace=nn2$xy)
mm3=new_trajectory (xy_sel,data = data_sub,trace=nn3$xy)
traj=rbind(mm1$trajectory,
mm2$trajectory,
mm3$trajectory)
traj=traj[,top_genes]
y=rep(1:20,3)
ma=multi_analysis(traj,y,FUN="correlation.test",method="spearman")
ma=ma[order(as.numeric(ma$`p-value`)),]
ma[1:20,]
Feature rho p-value FDR
270 SAA2 0.85 1.01e-17 2.02e-14
940 NNMT 0.81 6.97e-15 6.96e-12
1743 LAMTOR5 -0.80 2.24e-14 1.49e-11
210 PPDPF -0.80 3.09e-14 1.54e-11
1895 PLA1A -0.79 3.97e-14 1.59e-11
217 LTF 0.78 3.12e-13 1.04e-10
625 FTL -0.77 6.5e-13 1.86e-10
480 NME4 -0.75 3.24e-12 8.09e-10
285 CFB 0.75 4.18e-12 8.50e-10
1172 ZNF761 -0.75 4.26e-12 8.50e-10
102 RDH11 -0.74 1.56e-11 2.84e-09
128 KLK3 -0.73 2.93e-11 4.88e-09
950 SELENOH -0.73 3.93e-11 6.04e-09
1957 MTG1 -0.73 4.79e-11 6.48e-09
677 SAA1 0.73 4.86e-11 6.48e-09
263 SLC30A4 -0.72 9.09e-11 1.14e-08
3 MARCKSL1 -0.72 1.13e-10 1.33e-08
889 KIF5C -0.71 1.58e-10 1.75e-08
28 GPR160 -0.71 2.04e-10 2.14e-08
1539 SCD -0.71 2.69e-10 2.69e-08
par(opar)
vis_gene(spe,"Acinar_Cell_Carcinoma","ENSG00000134339")
par(opar)
vis_gene(spe,"Acinar_Cell_Carcinoma","ENSG00000166741")
rowData(spe)[c("ENSG00000134339","ENSG00000166741"),]
[1] "SAA2" "NNMT"
samples_sub=as.factor(colData(spe_sub)$sample_id)
xy_sub=as.matrix(spatialCoords(spe_sub))
PMdata=passing.message(data_sub,xy_sub,number_knn = 7)
par(mfrow=c(1,2))
a=data_sub[,"SAA2"]
b=data_sub[,"NNMT"]
cc=cor.test(a,b)
txt=paste("r=",round(cc$estimate,digits=2))
plot(a,b,main="Pearson correlation",xlab="SAA2",ylab="NNMT")
mtext(txt)
a=PMdata[,"SAA2"]
b=PMdata[,"NNMT"]
cc=cor.test(a,b)
txt=paste("r=",round(cc$estimate,digits=2))
plot(a,b,main="APM correlation",xlab="SAA2",ylab="NNMT")
mtext(txt)
svg("output/Figures/Prostate/prostate-correlation.svg",height = 8,width = 14)
par(mfrow=c(1,2))
a=data_sub[,"SAA2"]
b=data_sub[,"NNMT"]
cc=cor.test(a,b)
txt=paste("r=",round(cc$estimate,digits=2))
plot(a,b,main="Pearson correlation",xlab="SAA2",ylab="NNMT",pch=20,col="#000000aa")
mtext(txt)
a=PMdata[,"SAA2"]
b=PMdata[,"NNMT"]
cc=cor.test(a,b)
txt=paste("r=",round(cc$estimate,digits=2))
plot(a,b,main="APM correlation",xlab="SAA2",ylab="NNMT",pch=20,col="#000000aa")
mtext(txt)
dev.off()
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.
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.
We start by loading the necessary packages and preparing our gene data for analysis:
library("GSVA")
library("GSA")
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
genes=rowData(spe)[,"gene_name"]
spot_name=colnames(spe)
colnames(data)=genes
li=lapply(genesets,function(x) which(genes %in% x))
VAM=vamForCollection(gene.expr=data, gene.set.collection=li)
pathway=VAM$distance.sq
annotations=as.factor(annotations)
ta=table(annotations,clu)
path_clust=levels(annotations)[apply(ta,2,which.max)]
clu2=rep(NA,length(clu))
clu2[clu %in% names(which(ta["normal gland",]>50 & ta["Invasive carcinoma",]<50)) & annotations=="normal gland"]="Normal-phenotype"
clu2[clu %in% names(which(ta["normal gland",]>50 & ta["Invasive carcinoma",]>50)) & annotations=="normal gland"]="Tumor-phenotype"
bla
ta
clu
annotations 1 2 3 4 5 6 7 8 9 10
benign 0 0 0 0 0 24 0 42 1 2
blood vessel 0 19 0 21 4 0 0 0 0 0
fibromuscular 5 710 54 85 0 11 4 99 30 3
Gleason 3 0 0 0 0 0 78 0 42 0 0
Gleason 4 0 0 0 0 0 57 0 77 0 0
Gleason 5 0 0 0 0 0 0 0 70 0 0
hyperplasia gland 613 2 9 1 89 0 0 0 0 0
hyperplasia stroma 9 1 3 3 349 0 8 0 0 0
immune cells 0 8 0 0 0 1 0 14 0 0
Invasive carcinoma 3 2 1 0 0 2 0 183 564 1187
Nerve 0 40 0 0 0 0 0 0 0 0
normal gland 412 53 1017 120 16 2 2 2 106 0
normal stroma 0 819 33 817 64 0 293 0 0 0
tumor stroma 0 0 0 0 0 0 0 21 0 0
ma=multi_analysis(pathway[!is.na(clu2),],clu2[!is.na(clu2)])
ma=ma[order(as.numeric(ma$`p-value`)),]
ma[1:10,]
Feature Normal-phenotype
32 HALLMARK_MYC_TARGETS_V1, median [IQR] 768.647 [726.611 808.582]
22 HALLMARK_HYPOXIA, median [IQR] 486.527 [455.179 519.589]
16 HALLMARK_ESTROGEN_RESPONSE_LATE, median [IQR] 388.257 [355.903 420.169]
46 HALLMARK_UNFOLDED_PROTEIN_RESPONSE, median [IQR] 419.634 [396.73 441.259]
50 HALLMARK_XENOBIOTIC_METABOLISM, median [IQR] 327.539 [306.904 349.027]
7 HALLMARK_APOPTOSIS, median [IQR] 477.722 [445.253 514.822]
1 HALLMARK_ADIPOGENESIS, median [IQR] 666.7 [639.883 698.168]
33 HALLMARK_MYC_TARGETS_V2, median [IQR] 141.694 [126.662 158.104]
28 HALLMARK_KRAS_SIGNALING_DN, median [IQR] 151.545 [129.868 181.938]
17 HALLMARK_FATTY_ACID_METABOLISM, median [IQR] 351.567 [328.476 375.083]
Tumor-phenotype p-value FDR
32 863.132 [814.018 899.117] 3.27e-35 1.63e-33
22 435.231 [415.546 461.073] 6.5e-23 1.63e-21
16 339.735 [319.625 368.054] 2.62e-20 4.36e-19
46 455.502 [431.902 480.16] 5.35e-20 6.68e-19
50 298.05 [282.473 314.014] 5.3e-19 5.30e-18
7 440.981 [410.565 473.125] 7.84e-15 5.70e-14
1 633.917 [616.16 656.455] 7.98e-15 5.70e-14
33 162.81 [145.803 175.787] 2.94e-14 1.84e-13
28 128.098 [114.028 142.386] 8.91e-14 4.95e-13
17 323.622 [307.296 345.816] 3.63e-13 1.81e-12
library(ggpubr)
library(gridExtra)
par(mai=c(3,3,3,3))
df=data.frame(variable=pathway[,"HALLMARK_MYC_TARGETS_V1"],labels=annotations)
df=df[!is.na(df$labels) & samples=="Adenocarcinoma",]
my_comparisons=list(c("Invasive carcinoma","normal gland"))
Nplot1=ggboxplot(df, x = "labels", y = "variable", width = 0.8,palette = cols_pathology,las=2,
fill="labels",ylim=c(200,1400),
shape=21)+
ylab("HALLMARK_MYC_TARGETS_V1")+
xlab("")+
stat_compare_means(comparisons = my_comparisons,method="wilcox.test")+
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),legend.position = "none",plot.margin = unit(c(2,1,1,1), "cm"))
df=data.frame(variable=pathway[,"HALLMARK_MYC_TARGETS_V1"],labels=clu)
df=df[!is.na(clu2),]
cols=cols_cluster[as.numeric(names(table(df$labels)))]
my_comparisons=list(c(5,4),c(5,3),c(5,2),c(5,1))
Nplot2=ggboxplot(df, x = "labels", y = "variable", width = 0.8,palette = cols,
fill="labels",add = "jitter", ylim=c(200,1400),
add.params = list(size = 0.5, jitter = 0.2,fill=2),
shape=21)+
ylab("HALLMARK_MYC_TARGETS_V1")+
xlab("")+
stat_compare_means(comparisons = my_comparisons,method="wilcox.test")+
theme(legend.position = "none",plot.margin = unit(c(2,1,1,1), "cm"))
egg::ggarrange(Nplot1,Nplot2,widths = c(2,1.2),nrow=1,labels = c('A', 'B'))
svg("output/Figures/Prostate/prostate-boxplot.svg",height = 9,width = 20)
egg::ggarrange(Nplot1,Nplot2,widths = c(2,1.2),nrow=1,labels = c('A', 'B'))
dev.off()
QuPath
xy=as.matrix(spatialCoords(spe))
rownames(xy)=rownames(colData(spe))
x_HR=seq(range(xy[,1])[1],range(xy[,1])[2],length.out =200)
y_HR=seq(range(xy[,2])[1],range(xy[,2])[2],length.out =200)
xy_HR_final=NULL
newsamples=NULL
for(s in levels(samples)){
xy_HR=expand.grid(list(x_HR,y_HR))
t=Rnanoflann::nn(xy[s==samples,],xy_HR,1)
xy_HR=xy_HR[t$distances<(1.2*median(t$distances)),]
xy_HR_final=rbind(xy_HR_final,xy_HR)
newsamples=c(newsamples,rep(s,nrow(xy_HR)))
}
newsamples=as.factor(newsamples)
clu2=clu
clu2[clu %in% names(which(ta["normal gland",]>50 & ta["Invasive carcinoma",]<50)) & annotations=="normal gland"]="NP normal gland"
clu2[clu %in% names(which(ta["normal gland",]>50 & ta["Invasive carcinoma",]>50)) & annotations=="normal gland"]="TP normal gland"
clu3=refine_SVM(xy,clu2,samples,cost=100,tiles=c(5,5),newdata = xy_HR_final,newsamples = newsamples )
library(sf)
library(concaveman)
library(ggplot2)
library(dplyr)
# 1. Subset data and create a data frame
sel <- clu3 == "TP normal gland"
# Example: x, y are coordinates
x <- xy_HR_final[which(sel), 1]
y <- xy_HR_final[which(sel), 2]
data <- data.frame(x = x, y = y)
# 2. Perform K-means clustering (3 clusters as in your code)
km <- kmeans(data, 4)$cluster
g <- bluster::makeSNNGraph(as.matrix(data), k = 5)
g_walk <- igraph::cluster_louvain(g,resolution = 0.2)
km = g_walk$membership
# 3. Convert to sf object, add cluster attribute
sf_points <- st_as_sf(data, coords = c("x", "y"), crs = NA)
sf_points$cluster <- km
# Optional: Turn off spherical geometry if dealing with planar coordinates
sf_use_s2(FALSE)
# 4. Create separate concave hull polygons for each cluster
# Split the points by their cluster, then run concaveman on each subset.
concave_list <- lapply(split(sf_points, sf_points$cluster), function(subset_sf) {
hull <- concaveman(subset_sf, concavity = 2)
# Preserve the cluster ID for the resulting polygon
hull$cluster <- unique(subset_sf$cluster)
hull
})
# 5. Combine all polygons into one sf object
concave_polygons <- do.call(rbind, concave_list)
library(smoothr)
smoothed_polygons <- smooth(
concave_polygons,
method = "ksmooth", # or "chaikin"
smoothness = 3 # increase for more smoothing
)
# 6. Plot all points and polygons
ggplot() +
geom_sf(data = sf_points, aes(color = factor(cluster)), size = 2) +
geom_sf(data = smoothed_polygons, fill = NA, color = "black", size = 0.8) +
labs(title = "Concave Hull by Cluster", color = "Cluster")
# 7. Write all polygons to a single GeoJSON file
# Each polygon has the 'cluster' attribute, so you'll see multiple features.
st_write(smoothed_polygons, "output/tight_boundary.geojson",
driver = "GeoJSON",
delete_dsn = TRUE)
sessionInfo()
R version 4.4.3 (2025-02-28)
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] smoothr_1.0.1 dplyr_1.1.4
[3] concaveman_1.1.0 sf_1.0-20
[5] gridExtra_2.3 ggpubr_0.6.0
[7] VAM_1.1.0 MASS_7.3-65
[9] GSA_1.03.3 GSVA_1.52.3
[11] KODAMAextra_1.2 e1071_1.7-16
[13] doParallel_1.0.17 iterators_1.0.14
[15] foreach_1.5.2 KODAMA_3.0
[17] Matrix_1.7-3 umap_0.2.10.0
[19] Rtsne_0.17 minerva_1.5.10
[21] spatialLIBD_1.16.2 BiocSingular_1.20.0
[23] harmony_1.2.3 Rcpp_1.0.14
[25] SPARK_1.1.1 nnSVG_1.8.0
[27] scater_1.32.1 ggplot2_3.5.1
[29] scuttle_1.14.0 SpatialExperiment_1.14.0
[31] SingleCellExperiment_1.26.0 SummarizedExperiment_1.34.0
[33] Biobase_2.64.0 GenomicRanges_1.56.2
[35] GenomeInfoDb_1.40.1 IRanges_2.38.1
[37] S4Vectors_0.42.1 BiocGenerics_0.50.0
[39] MatrixGenerics_1.16.0 matrixStats_1.5.0
[41] workflowr_1.7.1
loaded via a namespace (and not attached):
[1] fs_1.6.5 bitops_1.0-9
[3] httr_1.4.7 RColorBrewer_1.1-3
[5] backports_1.5.0 tools_4.4.3
[7] R6_2.6.1 DT_0.33
[9] HDF5Array_1.32.1 lazyeval_0.2.2
[11] rhdf5filters_1.16.0 withr_3.0.2
[13] cli_3.6.4 labeling_0.4.3
[15] sass_0.4.9 proxy_0.4-27
[17] pbapply_1.7-2 askpass_1.2.1
[19] Rsamtools_2.20.0 R.utils_2.13.0
[21] sessioninfo_1.2.3 attempt_0.3.1
[23] maps_3.4.2.1 limma_3.60.6
[25] rstudioapi_0.17.1 RSQLite_2.3.9
[27] generics_0.1.3 BiocIO_1.14.0
[29] car_3.1-3 ggbeeswarm_0.7.2
[31] abind_1.4-8 terra_1.8-42
[33] R.methodsS3_1.8.2 lifecycle_1.0.4
[35] whisker_0.4.1 yaml_2.3.10
[37] edgeR_4.2.2 carData_3.0-5
[39] CompQuadForm_1.4.3 rhdf5_2.48.0
[41] SparseArray_1.4.8 BiocFileCache_2.12.0
[43] paletteer_1.6.0 grid_4.4.3
[45] blob_1.2.4 misc3d_0.9-1
[47] promises_1.3.2 dqrng_0.4.1
[49] ExperimentHub_2.12.0 crayon_1.5.3
[51] egg_0.4.5 lattice_0.22-7
[53] beachmat_2.20.0 cowplot_1.1.3
[55] annotate_1.82.0 KEGGREST_1.44.1
[57] magick_2.8.6 pillar_1.10.1
[59] knitr_1.50 tcltk_4.4.3
[61] rjson_0.2.23 codetools_0.2-20
[63] Rnanoflann_0.0.3 glue_1.8.0
[65] getPass_0.2-4 V8_6.0.3
[67] data.table_1.17.0 vctrs_0.6.5
[69] png_0.1-8 spam_2.11-1
[71] gtable_0.3.6 rematch2_2.1.2
[73] cachem_1.1.0 xfun_0.51
[75] S4Arrays_1.4.1 mime_0.13
[77] DropletUtils_1.24.0 pracma_2.4.4
[79] units_0.8-7 fields_16.3.1
[81] bluster_1.14.0 statmod_1.5.0
[83] bit64_4.6.0-1 filelock_1.0.3
[85] rprojroot_2.0.4 bslib_0.9.0
[87] irlba_2.3.5.1 KernSmooth_2.23-26
[89] vipor_0.4.7 matlab_1.0.4.1
[91] colorspace_2.1-1 DBI_1.2.3
[93] tidyselect_1.2.1 processx_3.8.6
[95] BRISC_1.0.6 bit_4.6.0
[97] compiler_4.4.3 curl_6.2.2
[99] git2r_0.33.0 graph_1.82.0
[101] BiocNeighbors_1.22.0 DelayedArray_0.30.1
[103] plotly_4.10.4 rtracklayer_1.64.0
[105] scales_1.3.0 classInt_0.4-11
[107] callr_3.7.6 rappdirs_0.3.3
[109] stringr_1.5.1 digest_0.6.37
[111] rmarkdown_2.29 benchmarkmeData_1.0.4
[113] RhpcBLASctl_0.23-42 XVector_0.44.0
[115] htmltools_0.5.8.1 pkgconfig_2.0.3
[117] sparseMatrixStats_1.16.0 dbplyr_2.5.0
[119] fastmap_1.2.0 rlang_1.1.5
[121] htmlwidgets_1.6.4 UCSC.utils_1.0.0
[123] shiny_1.10.0 DelayedMatrixStats_1.26.0
[125] farver_2.1.2 jquerylib_0.1.4
[127] jsonlite_2.0.0 BiocParallel_1.38.0
[129] config_0.3.2 R.oo_1.27.0
[131] RCurl_1.98-1.17 magrittr_2.0.3
[133] Formula_1.2-5 GenomeInfoDbData_1.2.12
[135] dotCall64_1.2 Rhdf5lib_1.26.0
[137] munsell_0.5.1 viridis_0.6.5
[139] reticulate_1.42.0 stringi_1.8.7
[141] zlibbioc_1.50.0 AnnotationHub_3.12.0
[143] ggrepel_0.9.6 doSNOW_1.0.20
[145] Biostrings_2.72.1 locfit_1.5-9.12
[147] rdist_0.0.5 ps_1.9.0
[149] igraph_2.1.4 ggsignif_0.6.4
[151] ScaledMatrix_1.12.0 BiocVersion_3.19.1
[153] XML_3.99-0.18 evaluate_1.0.3
[155] golem_0.5.1 BiocManager_1.30.25
[157] httpuv_1.6.15 RANN_2.6.2
[159] tidyr_1.3.1 openssl_2.3.2
[161] purrr_1.0.4 benchmarkme_1.0.8
[163] rsvd_1.0.5 broom_1.0.8
[165] xtable_1.8-4 restfulr_0.0.15
[167] RSpectra_0.16-2 rstatix_0.7.2
[169] later_1.4.1 viridisLite_0.4.2
[171] class_7.3-23 snow_0.4-4
[173] tibble_3.2.1 memoise_2.0.1
[175] beeswarm_0.4.0 AnnotationDbi_1.66.0
[177] GenomicAlignments_1.40.0 cluster_2.1.8.1
[179] shinyWidgets_0.9.0 GSEABase_1.66.0