Last updated: 2024-08-05

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 d5e7c3c. 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:


Untracked files:
    Untracked:  output/DLFPC-All-2-3000-300-0.4.RData
    Untracked:  output/DLFPC-All.RData
    Untracked:  output/DLFPC-Br5292-2-3000-300-0.3.RData
    Untracked:  output/DLFPC-Br5292.RData
    Untracked:  output/DLFPC-Br5595-2-3000-300-0.3.RData
    Untracked:  output/DLFPC-Br5595.RData
    Untracked:  output/DLFPC-Br8100-2-3000-300-0.3.RData
    Untracked:  output/DLFPC-Br8100.RData
    Untracked:  output/VisiumHD.RData

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

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/MERFISH.Rmd) and HTML (docs/MERFISH.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 d5e7c3c Stefano Cacciatore 2024-08-05 Start my new project
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.
html 7be8f59 tkcaccia 2024-07-15 updates
Rmd f8ca54a tkcaccia 2024-07-14 update
html f8ca54a tkcaccia 2024-07-14 update
Rmd 0638f93 GitHub 2024-07-08 Update MERFISH.Rmd
html d3de9e1 GitHub 2024-07-08 Update MERFISH.html
html 32f206e GitHub 2024-07-08 Update MERFISH.html
html 940ec13 GitHub 2024-07-04 Update MERFISH.html
Rmd 9ee53df GitHub 2024-06-26 Update MERFISH.Rmd
html 35e8f25 Stefano Cacciatore 2024-06-26 Update docs with MERFISH.html
Rmd c3eee75 GitHub 2024-06-26 Update MERFISH.Rmd
Rmd e7ddec6 GitHub 2024-06-26 Update MERFISH.Rmd
Rmd eb29180 GitHub 2024-06-26 Update MERFISH.Rmd
Rmd bd1988e GitHub 2024-06-26 Update MERFISH.Rmd
Rmd 911564c GitHub 2024-06-26 Update MERFISH.Rmd
Rmd 246f0bd GitHub 2024-06-25 Update MERFISH.Rmd
html 20a6dac Stefano Cacciatore 2024-06-25 Update docs with MERFISH.html
Rmd e56c4ff GitHub 2024-06-20 Update MERFISH.Rmd
Rmd 9df203d GitHub 2024-06-20 Update MERFISH.Rmd
Rmd be3cdeb GitHub 2024-06-20 Update MERFISH.Rmd
Rmd 2e7fa5e GitHub 2024-06-20 Update MERFISH.Rmd
Rmd a21b903 GitHub 2024-06-20 Update MERFISH.Rmd
html ee4ee17 GitHub 2024-06-19 Add files via upload
Rmd 615fc05 GitHub 2024-06-19 Add files via upload

MERFISH Data Analysis

Introduction

Spatial transcriptomics is a powerful technique for studying the spatial organization of gene expression within tissues. Here, we apply KODAMA to analyze the spatial transcriptomic data that measured the mouse preoptic region of the hypothalamus using the MERFISH technology from Moffitt et al., 2018. Link to study. We focus on the tissue sections Bregma -0.04, -0.09, -0.14, -0.19, and -0.24 mm from a consecutive brain hypothalamic region of animal 1. The original data can be downloaded from Dryad.

Loading and Preprocessing Data

# Load the necessary libraries
library(rgl)
library(irlba)
library(KODAMAextra)
library(scater)
library(SPARK)
library(ggplot2)
library(plotly)
library(mclust)
# Load the MERFISH data
load("../MERFISH_Animal1.RData")

# Define the slides to be analyzed
slides <- c("-0.04", "-0.09", "-0.14", "-0.19", "-0.24")

# Initialize variables
xyz <- NULL
tissue_segments <- NULL
cell_type <- NULL
RNA <- NULL

# Extract spatial and expression data from each slide
for (i in slides) {
  x <- info_mult[[i]]$x / 1000
  y <- info_mult[[i]]$y / 1000
  z <- as.numeric(i)
  slide_xyz <- cbind(x - min(x), y - min(y), z)
  xyz <- rbind(xyz, slide_xyz)
  tissue_segments <- c(tissue_segments, info_mult[[i]]$z)
  cell_type <- c(cell_type, info_mult[[i]]$Cell_class)
  RNA <- rbind(RNA, t(cnts_mult[[i]]))
}

# Normalize RNA counts
RNA <- t(normalizeCounts(t(RNA), log = TRUE))

# Convert tissue segments to factor with defined levels
tissue_segments <- factor(tissue_segments, levels = c("V3", "BST", "fx", "MPA", "MPN", "PV", "PVH", "PVT"))

# Convert xyz to numeric matrix
xyz <- matrix(as.numeric(as.matrix(xyz)), ncol = ncol(xyz))

Identifying Differentially Expressed Genes

# Initialize matrix to store p-values
pvalue_mat <- matrix(nrow = ncol(RNA), ncol = length(slides))
rownames(pvalue_mat) <- colnames(RNA)

# Calculate p-values using SPARK
for (i in 1:length(slides)) {
  sel <- xyz[, 3] == slides[i]
  RNA_sub <- RNA[sel,]
  xyz_sup <- xyz[sel, -3]
  sparkX <- sparkx(t(RNA_sub), xyz_sup, numCores = 1, option = "mixture")
  pvalue_mat[, i] <- sparkX$res_mtest$combinedPval
  print(slides[i])
}

# Order genes by median -log(p-value)
oo <- order(apply(pvalue_mat, 1, function(x) median(-log(x))), decreasing = TRUE)
top <- colnames(RNA)[oo]

Passing message

RNA.sel.2=RNA[,top[1:100]]
number_knn=10
RNA.sel.3=RNA.sel.2
knn=knn_Armadillo(xyz,xyz,number_knn)
for(h in 1:nrow(xyz)){
  temp=rep(0,ncol(RNA.sel.3))
  RNA.temp=RNA.sel.2[knn$nn_index[h,],]
  knn_gene=knn_Armadillo(RNA.temp,RNA.temp[1,,drop=FALSE],round(number_knn*0.5))$nn_index
  for(i in 1:number_knn){
    temp=temp+RNA.temp[i,]/(1+knn$distances[h,i]^2)
  }
  RNA.sel.3[h,]=temp
}

Dimensionality reduction

RNA.scaled=scale(RNA.sel.3)
pca_results <- irlba(A = RNA.scaled, nv = 50)
pca <- pca_results$u %*% diag(pca_results$d)
plot(pca,col=tissue_segments)

Version Author Date
6f7daac Stefano Cacciatore 2024-07-19
f8ca54a tkcaccia 2024-07-14
20a6dac Stefano Cacciatore 2024-06-25

Applying KODAMA

# Apply KODAMA to the PCA results
jj <- KODAMA.matrix.parallel(pca[,1:30],spatial = xyz,f.par.pls = 50, FUN = "PLS", landmarks = 100000, n.cores = 8,splitting=100)
socket cluster with 8 nodes on host 'localhost'
================================================================================[1] "Finished parallel computation"

[1] "Calculation of dissimilarity matrix..."
================================================================================
config=umap.defaults
config$n_neighbors=30
vis <- KODAMA.visualization(jj, method = "UMAP",config=config)

# Cluster the results
 #g <- makeSNNGraph(vis,k = 100)
 #g_walk <- cluster_walktrap(g)
 #clu = as.character(igraph::cut_at(g_walk, no=8))
 
clu=kmeans(vis,8,nstart = 100)$cluster
 
# Plot the clusters
par(mfrow = c(1, 2))
plot(vis, col = tissue_segments, main = "KODAMA tissue")
plot(vis, col = clu, main = "KODAMA Clusters")

ref=refine_SVM(xyz,clu,cost=10000)
[1] "1"
ARI=NULL
slides=unique(xyz[,3])
for(i in 1:length(slides)){
  sel=slides[i]==xyz[,3]
  ARI[i]=adjustedRandIndex(ref[sel], tissue_segments[sel])
}
print(ARI)
[1] 0.5421992 0.6090266 0.4803425 0.6161870 0.6220334

Refinement and Visualization

cols <- c("#669bbc", "#81b29a", "#f2cc8f", "#adc178",
          "#dde5b6", "#a8dadc", "#e5989b", "#e07a5f")

change=sort(tapply(ref,tissue_segments,function(x) which.max(table(x))))
ref=names(change)[ref]
ref=factor(ref,levels = levels(tissue_segments))

df <- data.frame(xyz, tissue_segments)
df <- data.frame(xyz, ref)
colnames(df)=c("x","y","z","tissue_segments")
df$z=as.factor(df$z)
df$tissue_segments=as.factor(df$tissue_segments)
ggplot(df, aes(x, y, color = tissue_segments)) +
  geom_point(size = 1) +
  facet_grid(~z) +
  theme_bw() +
  theme(
    legend.position = "bottom",
    axis.title = element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    panel.grid = element_blank())+
  
  scale_color_manual("Domain", values = cols) +
  guides(color = guide_legend(nrow = 1, 
                              override.aes = list(size = 2)))

# 3D Visualization for Slice -0.14

library(rgl)

library(MASS)

library(misc3d)

volume_rendering <- function(xyz,  tissue_segments,selection=NULL, alpha=NULL, colors=NULL,cells=c(20, 20, 20), level=exp(-3)) {
  if(!is.factor(tissue_segments)){
    stop("tissue_segments is not a factor")
  }
  option_tissue=levels(tissue_segments)
  if(is.null(colors)){
    colors=rainbow(length(option_tissue))
  }else{
    if(length(option_tissue)!=length(alpha)){
      stop("The number of color does not match")
    }
  }
  if(is.null(alpha)){ 
    alpha=rep(1,length(option_tissue))
  }else{
    if(length(option_tissue)!=length(alpha)){
      stop("The number of alpha does not match")
    }
  }
  if(!is.null(selection)){
    option_tissue=selection
  }
    ww=which(levels(tissue_segments) %in% option_tissue)
    colors=colors[ww]
    alpha=alpha[ww]
    
    

  cells[1]=min(cells[1],length(unique(xyz[,1])))
  cells[2]=min(cells[2],length(unique(xyz[,2])))
  cells[3]=min(cells[3],length(unique(xyz[,3])))
  sel.alpha=alpha>0
  option_tissue=option_tissue[sel.alpha]
  alpha=alpha[sel.alpha]
  colors=colors[sel.alpha]
  for (i in 1:length(option_tissue) ){
    segment <- option_tissue[i]
    sel <- tissue_segments == segment
    d <- kde3d(xyz[sel, 1], xyz[sel, 2], xyz[sel, 3], n = cells)
    e=array(0,dim=cells+2)
    e[2:(cells[1]+1),2:(cells[2]+1),2:(cells[3]+1)]=d$d
    dx=c(d$x[1]-d$x[2],d$x,d$x[cells[1]]+d$x[2]-d$x[1])
    dy=c(d$y[1]-d$y[2],d$y,d$y[cells[2]]+d$y[2]-d$y[1])
    dz=c(d$z[1]-d$z[2],d$z,d$z[cells[3]]+d$z[2]-d$z[1])
    contour3d(e, level=level, dx, dy, dz,
              color = colors[i],  scale = FALSE,
              engine = "rgl", draw = TRUE, alpha = alpha[i], add = (i != 1))
  }
  rglwidget()
}


volume_rendering(xyz,ref,selection = c("V3","PVH","PV","fx"),alpha = c(0.8,0.8,0.8,0.8,0.8,0.8,0.8,0.8) ,colors = cols,cells=c(20, 20, 20),level=exp(2.8))

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] stats4    parallel  stats     graphics  grDevices utils     datasets 
[8] methods   base     

other attached packages:
 [1] misc3d_0.9-1                MASS_7.3-61                
 [3] mclust_6.1.1                plotly_4.10.4              
 [5] SPARK_1.1.1                 scater_1.32.1              
 [7] ggplot2_3.5.1               scuttle_1.14.0             
 [9] SingleCellExperiment_1.26.0 SummarizedExperiment_1.34.0
[11] Biobase_2.64.0              GenomicRanges_1.56.1       
[13] GenomeInfoDb_1.40.1         IRanges_2.38.1             
[15] S4Vectors_0.42.1            BiocGenerics_0.50.0        
[17] MatrixGenerics_1.16.0       matrixStats_1.3.0          
[19] KODAMAextra_1.0             e1071_1.7-14               
[21] doParallel_1.0.17           iterators_1.0.14           
[23] foreach_1.5.2               KODAMA_3.1                 
[25] umap_0.2.10.0               Rtsne_0.17                 
[27] minerva_1.5.10              irlba_2.3.5.1              
[29] Matrix_1.7-0                rgl_1.3.1                  
[31] 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] farver_2.1.2              rmarkdown_2.27           
  [7] fs_1.6.4                  zlibbioc_1.50.0          
  [9] vctrs_0.6.5               DelayedMatrixStats_1.26.0
 [11] CompQuadForm_1.4.3        askpass_1.2.0            
 [13] base64enc_0.1-3           htmltools_0.5.8.1        
 [15] S4Arrays_1.4.1            BiocNeighbors_1.22.0     
 [17] SparseArray_1.4.8         sass_0.4.9               
 [19] pracma_2.4.4              bslib_0.7.0              
 [21] htmlwidgets_1.6.4         cachem_1.1.0             
 [23] whisker_0.4.1             lifecycle_1.0.4          
 [25] pkgconfig_2.0.3           rsvd_1.0.5               
 [27] R6_2.5.1                  fastmap_1.2.0            
 [29] GenomeInfoDbData_1.2.12   digest_0.6.36            
 [31] colorspace_2.1-0          ps_1.7.7                 
 [33] rprojroot_2.0.4           RSpectra_0.16-1          
 [35] beachmat_2.20.0           labeling_0.4.3           
 [37] fansi_1.0.6               httr_1.4.7               
 [39] abind_1.4-5               compiler_4.4.1           
 [41] proxy_0.4-27              withr_3.0.0              
 [43] BiocParallel_1.38.0       viridis_0.6.5            
 [45] highr_0.11                openssl_2.2.0            
 [47] DelayedArray_0.30.1       tools_4.4.1              
 [49] vipor_0.4.7               beeswarm_0.4.0           
 [51] httpuv_1.6.15             glue_1.7.0               
 [53] callr_3.7.6               promises_1.3.0           
 [55] grid_4.4.1                getPass_0.2-4            
 [57] generics_0.1.3            snow_0.4-4               
 [59] gtable_0.3.5              class_7.3-22             
 [61] tidyr_1.3.1               data.table_1.15.4        
 [63] BiocSingular_1.20.0       ScaledMatrix_1.12.0      
 [65] utf8_1.2.4                XVector_0.44.0           
 [67] ggrepel_0.9.5             pillar_1.9.0             
 [69] stringr_1.5.1             later_1.3.2              
 [71] dplyr_1.1.4               lattice_0.22-6           
 [73] tidyselect_1.2.1          knitr_1.48               
 [75] git2r_0.33.0              gridExtra_2.3            
 [77] xfun_0.45                 stringi_1.8.4            
 [79] UCSC.utils_1.0.0          lazyeval_0.2.2           
 [81] yaml_2.3.9                evaluate_0.24.0          
 [83] codetools_0.2-20          tcltk_4.4.1              
 [85] tibble_3.2.1              cli_3.6.3                
 [87] matlab_1.0.4.1            reticulate_1.38.0        
 [89] munsell_0.5.1             processx_3.8.4           
 [91] jquerylib_0.1.4           Rcpp_1.0.12              
 [93] doSNOW_1.0.20             png_0.1-8                
 [95] sparseMatrixStats_1.16.0  viridisLite_0.4.2        
 [97] scales_1.3.0              purrr_1.0.2              
 [99] crayon_1.5.3              rlang_1.1.4