Last updated: 2025-01-08
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 2077f71. 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/
Ignored: analysis/figure/
Untracked files:
Untracked: Elemina.RData
Untracked: KODAMA.svg
Untracked: Rplots.pdf
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/VisiumHD-CRC.ipynb
Untracked: code/save tiles.py
Untracked: data/Adenocarcinoma.csv
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/spots_classification_ALL.csv
Untracked: data/spots_classification_Acinar_Cell_Carcinoma.csv
Untracked: data/spots_classification_IF.csv
Untracked: data/spots_classification_Normal_prostate.csv
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/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/DLPFC1.svg
Untracked: output/DLPFC_all_cluster.svg
Untracked: output/Figure 1 - boxplot.pdf
Untracked: output/Figure 2 - DLPFC 10.pdf
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/MERFISH.RData
Untracked: output/Nonspatial-results.RData
Untracked: output/PRECAST-results.RData
Untracked: output/Prostate.RData
Untracked: output/VisiumHD3.RData
Untracked: output/a1.RData
Untracked: output/a2.RData
Untracked: output/a3.RData
Untracked: output/a4.RData
Untracked: output/a5.RData
Untracked: output/a6.RData
Untracked: output/a7.RData
Untracked: output/a8.RData
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/prostate4.svg
Untracked: output/prostate5.svg
Untracked: output/prostate6.svg
Untracked: output/prostate7.svg
Untracked: output/tight_boundary.geojson
Untracked: remove.RData
Untracked: remove2.RData
Unstaged changes:
Deleted: analysis/D1.Rmd
Deleted: analysis/DLPFC-12.Rmd
Deleted: analysis/DLPFC-4.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
Deleted: analysis/STARmap.Rmd
Modified: analysis/VisiumHD.Rmd
Modified: code/VisiumHD_CRC_download.sh
Deleted: data/Pathology.csv
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 | 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/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/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/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/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=t(logcounts(spe))
library(ggplot2)
cols_tissue <- c("#0000b6cc", "#81b29acc", "#f2cc8fcc","#e07a5fcc")
# 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
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/prostate1.svg",height = 3)
plot1
dev.off()
png
2
svg("output/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("#0000ff", "#e41a1c", "#006400", "#000000", "#ffd700",
"#00ff00", "#b2dfee","#669bbc", "#81b29a", "#f2cc8f",
"#adc178", "#aa1133", "#1166dc", "#e5989b", "#e07a5f")
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/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)
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/prostate4.svg",height = 4)
plot4
dev.off()
png
2
svg("output/prostate5.svg",height = 4)
plot5
dev.off()
png
2
annotations
clu benign blood vessel fibromuscular Gleason 3 Gleason 4 Gleason 5
1 0 0 5 0 0 0
2 0 41 716 0 0 0
3 1 0 32 0 0 0
4 0 3 0 0 0 0
5 0 0 99 0 0 0
6 0 0 4 0 0 0
7 22 0 12 76 57 0
8 0 0 1 0 0 0
9 27 0 1 35 3 54
10 18 0 8 9 74 16
11 1 0 4 0 0 0
12 0 0 119 0 0 0
annotations
clu hyperplasia gland hyperplasia stroma immune cells Invasive carcinoma Nerve
1 658 17 0 3 0
2 3 0 7 2 4
3 11 5 0 1 0
4 41 333 0 0 0
5 1 4 0 0 0
6 0 0 0 0 36
7 0 0 2 4 0
8 0 14 0 0 0
9 0 0 14 40 0
10 0 0 0 0 0
11 0 0 0 1222 0
12 0 0 0 670 0
annotations
clu normal gland normal stroma tumor stroma
1 422 0 0
2 87 853 0
3 987 42 0
4 7 14 0
5 125 757 0
6 1 11 0
7 3 0 0
8 3 349 0
9 0 0 0
10 0 0 20
11 0 0 0
12 95 0 1
png
2
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)))
# 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[1:2000]]
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 ENSG00000134339 0.85 1.01e-17 2.02e-14
940 ENSG00000166741 0.81 6.97e-15 6.96e-12
1743 ENSG00000134248 -0.80 2.24e-14 1.49e-11
210 ENSG00000125534 -0.80 3.09e-14 1.54e-11
1895 ENSG00000144837 -0.79 3.97e-14 1.59e-11
217 ENSG00000012223 0.78 3.12e-13 1.04e-10
625 ENSG00000087086 -0.77 6.5e-13 1.86e-10
480 ENSG00000103202 -0.75 3.24e-12 8.09e-10
285 ENSG00000243649 0.75 4.18e-12 8.50e-10
1172 ENSG00000160336 -0.75 4.26e-12 8.50e-10
102 ENSG00000072042 -0.74 1.56e-11 2.84e-09
128 ENSG00000142515 -0.73 2.93e-11 4.88e-09
950 ENSG00000211450 -0.73 3.93e-11 6.04e-09
1957 ENSG00000148824 -0.73 4.79e-11 6.48e-09
677 ENSG00000173432 0.73 4.86e-11 6.48e-09
263 ENSG00000104154 -0.72 9.09e-11 1.14e-08
3 ENSG00000175130 -0.72 1.13e-10 1.33e-08
889 ENSG00000168280 -0.71 1.58e-10 1.75e-08
28 ENSG00000173890 -0.71 2.04e-10 2.14e-08
1539 ENSG00000099194 -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/1000)
par(mfrow=c(1,2))
a=data[,"ENSG00000134339"]
b=data[,"ENSG00000166741"]
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[,"ENSG00000134339"]
b=PMdata[,"ENSG00000166741"]
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)
Version | Author | Date |
---|---|---|
a11cbcc | Stefano Cacciatore | 2024-09-14 |
aaa=1
save(aaa,file="output/a1.RData")
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
# library("gprofiler2")
# genes=gconvert(rownames(spe),organism="hsapiens",target="GENECARDS",filter_na = F)$target
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 11
benign 0 0 1 0 0 0 22 0 27 18 1
blood vessel 0 41 0 3 0 0 0 0 0 0 0
fibromuscular 5 716 32 0 99 4 12 1 1 8 4
Gleason 3 0 0 0 0 0 0 76 0 35 9 0
Gleason 4 0 0 0 0 0 0 57 0 3 74 0
Gleason 5 0 0 0 0 0 0 0 0 54 16 0
hyperplasia gland 658 3 11 41 1 0 0 0 0 0 0
hyperplasia stroma 17 0 5 333 4 0 0 14 0 0 0
immune cells 0 7 0 0 0 0 2 0 14 0 0
Invasive carcinoma 3 2 1 0 0 0 4 0 40 0 1222
Nerve 0 4 0 0 0 36 0 0 0 0 0
normal gland 422 87 987 7 125 1 3 3 0 0 0
normal stroma 0 853 42 14 757 11 0 349 0 0 0
tumor stroma 0 0 0 0 0 0 0 0 0 20 0
clu
annotations 12
benign 0
blood vessel 0
fibromuscular 119
Gleason 3 0
Gleason 4 0
Gleason 5 0
hyperplasia gland 0
hyperplasia stroma 0
immune cells 0
Invasive carcinoma 670
Nerve 0
normal gland 95
normal stroma 0
tumor stroma 1
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.753 [726.721 808.664]
22 HALLMARK_HYPOXIA, median [IQR] 486.171 [454.712 519.543]
46 HALLMARK_UNFOLDED_PROTEIN_RESPONSE, median [IQR] 419.643 [396.848 441.575]
16 HALLMARK_ESTROGEN_RESPONSE_LATE, median [IQR] 388.108 [355.737 420.137]
50 HALLMARK_XENOBIOTIC_METABOLISM, median [IQR] 327.372 [306.716 348.838]
7 HALLMARK_APOPTOSIS, median [IQR] 477.703 [445.442 514.741]
36 HALLMARK_OXIDATIVE_PHOSPHORYLATION, median [IQR] 573.096 [543.612 605.328]
37 HALLMARK_P53_PATHWAY, median [IQR] 460.027 [423.245 502.271]
28 HALLMARK_KRAS_SIGNALING_DN, median [IQR] 151.557 [129.865 181.582]
33 HALLMARK_MYC_TARGETS_V2, median [IQR] 141.96 [126.646 158.115]
Tumor-phenotype p-value FDR
32 867.74 [830.132 901.834] 4.85e-38 2.43e-36
22 431.617 [407.804 458.745] 1.99e-24 4.98e-23
46 458.38 [434.348 481.661] 3.81e-22 6.35e-21
16 337.387 [319.008 362.577] 8.34e-21 1.04e-19
50 294.572 [279.265 310.438] 2.18e-20 2.18e-19
7 429.608 [403.98 460.946] 4.09e-19 3.41e-18
36 611.881 [587.995 652.444] 5.02e-16 3.59e-15
37 419.874 [395.981 445.386] 2.19e-15 1.34e-14
28 126.236 [113.487 140.152] 2.41e-15 1.34e-14
33 163.547 [146.033 176.671] 8.55e-15 4.27e-14
library(ggpubr)
library(gridExtra)
par(mai=c(3,3,3,3))
save(aaa,file="output/a2.RData")
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"))
save(aaa,file="output/a3.RData")
cols=cols_cluster[c(1,2,3,6,11)]
df=data.frame(variable=pathway[,"HALLMARK_MYC_TARGETS_V1"],labels=clu)
df=df[!is.na(clu2),]
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"))
save(aaa,file="output/a4.RData")
egg::ggarrange(Nplot1,Nplot2,widths = c(2,1.2),nrow=1,labels = c('A', 'B'))
save(aaa,file="output/a5.RData")
QuPath
save(aaa,file="output/a6.RData")
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 )
save(aaa,file="output/a7.RData")
par(opar)
plot(xy_HR_final[newsamples==levels(newsamples)[3],],col=clu3[newsamples==levels(newsamples)[3]])
save(aaa,file="output/a8.RData")
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.2 (2024-10-31)
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-19
[5] gridExtra_2.3 ggpubr_0.6.0
[7] VAM_1.1.0 MASS_7.3-61
[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-1 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.13-1
[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.4.1
[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.2
[7] utf8_1.2.4 R6_2.5.1
[9] DT_0.33 HDF5Array_1.32.1
[11] lazyeval_0.2.2 rhdf5filters_1.16.0
[13] withr_3.0.1 cli_3.6.3
[15] labeling_0.4.3 sass_0.4.9
[17] proxy_0.4-27 pbapply_1.7-2
[19] askpass_1.2.1 Rsamtools_2.20.0
[21] R.utils_2.12.3 sessioninfo_1.2.2
[23] attempt_0.3.1 maps_3.4.2.1
[25] limma_3.60.3 rstudioapi_0.17.1
[27] RSQLite_2.3.9 generics_0.1.3
[29] BiocIO_1.14.0 car_3.1-3
[31] ggbeeswarm_0.7.2 fansi_1.0.6
[33] abind_1.4-8 terra_1.7-78
[35] R.methodsS3_1.8.2 lifecycle_1.0.4
[37] whisker_0.4.1 yaml_2.3.10
[39] edgeR_4.2.2 carData_3.0-5
[41] CompQuadForm_1.4.3 rhdf5_2.48.0
[43] SparseArray_1.4.8 BiocFileCache_2.12.0
[45] paletteer_1.6.0 grid_4.4.2
[47] blob_1.2.4 misc3d_0.9-1
[49] dqrng_0.4.1 promises_1.3.2
[51] ExperimentHub_2.12.0 crayon_1.5.3
[53] egg_0.4.5 lattice_0.22-6
[55] beachmat_2.20.0 cowplot_1.1.3
[57] annotate_1.82.0 KEGGREST_1.44.1
[59] magick_2.8.4 pillar_1.9.0
[61] knitr_1.49 tcltk_4.4.2
[63] rjson_0.2.23 codetools_0.2-20
[65] Rnanoflann_0.0.3 glue_1.8.0
[67] getPass_0.2-4 V8_6.0.0
[69] data.table_1.15.4 vctrs_0.6.5
[71] png_0.1-8 spam_2.11-0
[73] gtable_0.3.5 rematch2_2.1.2
[75] cachem_1.1.0 xfun_0.49
[77] S4Arrays_1.4.1 mime_0.12
[79] DropletUtils_1.24.0 pracma_2.4.4
[81] units_0.8-5 fields_16.3
[83] bluster_1.14.0 statmod_1.5.0
[85] bit64_4.5.2 filelock_1.0.3
[87] rprojroot_2.0.4 bslib_0.8.0
[89] irlba_2.3.5.1 KernSmooth_2.23-26
[91] vipor_0.4.7 matlab_1.0.4.1
[93] colorspace_2.1-1 DBI_1.2.3
[95] tidyselect_1.2.1 processx_3.8.4
[97] BRISC_1.0.6 bit_4.5.0.1
[99] compiler_4.4.2 curl_6.0.1
[101] git2r_0.33.0 graph_1.82.0
[103] BiocNeighbors_1.22.0 DelayedArray_0.30.1
[105] plotly_4.10.4 rtracklayer_1.64.0
[107] scales_1.3.0 classInt_0.4-10
[109] callr_3.7.6 rappdirs_0.3.3
[111] stringr_1.5.1 digest_0.6.37
[113] rmarkdown_2.29 benchmarkmeData_1.0.4
[115] RhpcBLASctl_0.23-42 XVector_0.44.0
[117] htmltools_0.5.8.1 pkgconfig_2.0.3
[119] sparseMatrixStats_1.16.0 dbplyr_2.5.0
[121] fastmap_1.2.0 rlang_1.1.4
[123] htmlwidgets_1.6.4 UCSC.utils_1.0.0
[125] shiny_1.10.0 DelayedMatrixStats_1.26.0
[127] farver_2.1.2 jquerylib_0.1.4
[129] jsonlite_1.8.9 BiocParallel_1.38.0
[131] R.oo_1.27.0 config_0.3.2
[133] RCurl_1.98-1.16 magrittr_2.0.3
[135] Formula_1.2-5 GenomeInfoDbData_1.2.12
[137] dotCall64_1.2 Rhdf5lib_1.26.0
[139] munsell_0.5.1 viridis_0.6.5
[141] reticulate_1.38.0 stringi_1.8.4
[143] zlibbioc_1.50.0 AnnotationHub_3.12.0
[145] ggrepel_0.9.6 doSNOW_1.0.20
[147] Biostrings_2.72.1 locfit_1.5-9.10
[149] rdist_0.0.5 ps_1.8.1
[151] igraph_2.0.3 ggsignif_0.6.4
[153] ScaledMatrix_1.12.0 BiocVersion_3.19.1
[155] XML_3.99-0.18 evaluate_1.0.1
[157] golem_0.5.1 BiocManager_1.30.25
[159] httpuv_1.6.15 RANN_2.6.2
[161] tidyr_1.3.1 openssl_2.2.2
[163] purrr_1.0.2 benchmarkme_1.0.8
[165] rsvd_1.0.5 broom_1.0.7
[167] xtable_1.8-4 restfulr_0.0.15
[169] RSpectra_0.16-2 rstatix_0.7.2
[171] later_1.4.0 viridisLite_0.4.2
[173] class_7.3-23 snow_0.4-4
[175] tibble_3.2.1 memoise_2.0.1
[177] beeswarm_0.4.0 AnnotationDbi_1.66.0
[179] GenomicAlignments_1.40.0 cluster_2.1.8
[181] shinyWidgets_0.8.7 GSEABase_1.66.0