OSCR

Spatial architecture of autism pathogenesis reveals mosaic structural disarray during early development.

Code ↔ Paper

10 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

7 blocks of code here have a permanent identifier (oscr:b:…), listed with the matches below: citable for good, with a page of its own. Select a match and press Cite to copy it. What a block identifier is.

The 10 matches
  1. [1] § Methods › Spatial Signaling Score (S3) ↔ Spatial signaling score/CalculateSpatialSignalingScore.R, lines 87 to 167 · score 0.88 · edge weight, ligand expression, cell contact, receptor expression, scaled S3, sender cell · block oscr:b:SGH067D1BK77D-Y · Report a mismatch
  2. [2] § Methods › Spatial Signaling Score (S3) ↔ Spatial signaling score/CalculateSpatialSignalingScore.R, lines 87 to 167 · score 0.75 · cell contact graph, edge weights, Scaled S3, receiver cell identity, sum, sender · block oscr:b:SGH067D1BK77D-Y · Report a mismatch
  3. [3] § Methods › Spatial Signaling Score (S3) ↔ Spatial signaling score/Spatialsignalingscore_main.R, lines 1 to 42 · score 0.71 · literature supported, receptor genes, shortlisted ligand, ligand receptor pairs, S3, Score · block oscr:b:7ZD6VYP711NKA-Q · Report a mismatch
  4. [4] § Methods › MERFISH spot assignment ↔ Spot assigment/Assign_spots_EDT.py, lines 231 to 281 · score 0.67 · segmented cell, RNA spot, cell mask, nucleus, assignment, dilated · block oscr:b:FBZTTPCHZT5Z4-M · Report a mismatch
  5. [5] § Results › Cell adhesion between ASD progenitors is dysregulated ↔ Spatial signaling score/CalculateSpatialSignalingScore.R, lines 47 to 85 · score 0.66 · interacting cell pairs, receptor expression, Spatial Signaling Score, receiver cell identity, ligand receptor, sender · block oscr:b:MH7T9AXZXP74V-H · Report a mismatch
  6. [6] § Methods › Spatial Signaling Score (S3) ↔ Spatial signaling score/Spatialsignalingscore_main.R, lines 330 to 392 · score 0.64 · edge weight, cell contact, ligand receptor pair, sender, S3, receiver · block oscr:b:KCF179NG0Y6BJ-D · Report a mismatch
  7. [7] § Methods › Spatial Signaling Score (S3) ↔ Spatial signaling score/Spatialsignalingscore_main.R, lines 330 to 392 · score 0.60 · cell contact graph, edge weights, cell identity, sender, S3, receiver · block oscr:b:KCF179NG0Y6BJ-D · Report a mismatch
  8. [8] § Methods › MERFISH spot assignment ↔ Spot assigment/Assign_spots_EDT.py, lines 231 to 281 · score 0.59 · segmented region, RNA spots, nuclei, assignment, DAPI, mask · block oscr:b:FBZTTPCHZT5Z4-M · Report a mismatch
  9. [9] § Methods › Spatial Signaling Score (S3) ↔ Spatial signaling score/Spatialsignalingscore_main.R, lines 394 to 455 · score 0.53 · randomized control, diagnosis, disorganized, signaling, cell identities, S3 · block oscr:b:M9ZMP98MYNT5A-T · Report a mismatch
  10. [10] § Methods › MERFISH spot decoding ↔ Spot assigment/Assign_spots_EDT.py, lines 39 to 130 · score 0.52 · Euclidean distance, closest, spots, pixels, frame, cell · block oscr:b:FPTZV9EY3BRGG-5 · Report a mismatch

Paper

Loaded from Europe PMC by your browser; OSCR does not store it: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

R · 685 lines · 40 KB · no license · 4 matches

  1. # The main script for quantifying spatial ligand-receptor interactions
  2. # load libraries
  3. library(patchwork) #1.1.1
  4. library(Rmisc) #1.5
  5. library(reticulate) #1.22
  6. library(data.table) #1.14.2
  7. library(readxl) #1.3.1
  8. library(reshape2) #1.4.4
  9. library(pheatmap) #1.0.12
  10. library(Seurat) #4.0.2
  11. library(ggplot2)
  12. library(readxl)
  13. library(quantmod)
  14. # load our own functions
  15. source("/home/ubuntu/SpatialSignalingScore/DistToDataframe.R")
  16. source("/home/ubuntu/SpatialSignalingScore/AnalysisSpatialNetworks.R")
  17. source("/home/ubuntu/SpatialSignalingScore/CalculateSpatialSignalingScore.R")
  18. source("/home/ubuntu/SpatialSignalingScore/ScaleSpatialSignalingScore.R")
  19. source("/home/ubuntu/SpatialSignalingScore/FindDifferentialSpatialSignalingScore.R")
  20. source("/home/ubuntu/SpatialSignalingScore/VisualizeS3Dotplot.R")
  21. source("/home/ubuntu/SpatialSignalingScore/LoadAllMetrics.R")
  22. #======================================== 1. SHORTLIST LIGANDS AND RECEPTORS FOR ANALYSIS ==============================================
  23. #---------------- Load ligand-receptor pairs from literature: https://static-content.springer.com/esm/art%3A10.1038%2Fs41467-020-18873-z/MediaObjects/41467_2020_18873_MOESM4_ESM.xlsx ---------------
  24. ligand.receptor = read_excel('/home/ubuntu/41467_2020_18873_MOESM4_ESM.xlsx',sheet='literature_support')
  25. #---------------- Select ligands and receptors that exist in scRNAseq panel ---------------
  26. scrnaP <- readRDS("/home/ubuntu/scrnaP.rds")
  27. scrnaN <- readRDS("/home/ubuntu/scrnaN.rds")
  28. scrna<-merge(scrnaN,y = scrnaP)
  29. selected_pairs = data.frame(ligand = character(length=0L),receptor=character(length=0L))
  30. for (i in 1:nrow(ligand.receptor)){
  31. if (ligand.receptor[i,"Ligand gene symbol"] %in% rownames(scrna@assays[["SCT"]])){
  32. if (ligand.receptor[i,"Receptor gene symbol"] %in% rownames(scrna@assays[["SCT"]])){
  33. temp = cbind(as.character(ligand.receptor[i,"Ligand gene symbol"]),
  34. as.character(ligand.receptor[i,"Receptor gene symbol"]),
  35. as.character(ligand.receptor[i,"Ligand location"]))
  36. colnames(temp) = c('ligand','receptor','ligand.location')
  37. selected_pairs=rbind(selected_pairs,temp)
  38. }}}
  39. write.csv(selected_pairs,file='/home/ubuntu/differentialS3/selected_ligand-receptor_pairs_latest2020_20230714.txt')
  40. #---------------- Filter out ligands and receptors that are lowly expressed in scRNAseq ---------------
  41. lig.rec = unique(c(as.character(selected_pairs$ligand),as.character(selected_pairs$receptor)))
  42. # get highest mean expression per cell identity across all cell identities
  43. best.avg = data.frame(row.names=lig.rec)
  44. avg.scRNAseq <- AverageExpression(scrna, features=lig.rec, assays="SCT",slot='counts',group.by = "cell_identity",verbose =F)
  45. best.avg$scRNAseq <- apply(avg.scRNAseq$SCT,1,max)
  46. p <- hist(log(best.avg$scRNAseq),breaks=60)
  47. p$breaks[findValleys(p$density, thresh=0)]
  48. lig.rec.good = lig.rec[(best.avg$scRNAseq)>exp(-2.4)] # threshold selected is at the valley of the bimodel distribution
  49. selected_pairs2= data.frame(ligand = character(length=0L),receptor=character(length=0L))
  50. for (i in 1:nrow(selected_pairs)){
  51. if (selected_pairs[i,"ligand"] %in% lig.rec.good){
  52. if (selected_pairs[i,"receptor"] %in% lig.rec.good){
  53. temp = cbind(as.character(selected_pairs[i,"ligand"]),
  54. as.character(selected_pairs[i,"receptor"]))
  55. colnames(temp) = c('ligand','receptor')
  56. selected_pairs2=rbind(selected_pairs2,temp)
  57. }}}
  58. lig.rec.left = unique(c(as.character(selected_pairs2$ligand),as.character(selected_pairs2$receptor)))
  59. selected_pairs = selected_pairs2
  60. selected_pairs$LR_comb = paste0(as.character(selected_pairs$ligand),'--',as.character(selected_pairs$receptor))
  61. write.csv(selected_pairs,file=paste0(root_dir,'selected_ligand-receptor_pairs_threshold_valley_20230714.txt'))
  62. #---------------- Initialze all paremeters and paths ---------------
  63. meta.mfish <- read.csv("/home/ubuntu/metadata_mfish.csv", header = T)
  64. data_name = meta.mfish$data_name
  65. ctrl_name = meta.mfish$data_name[meta.mfish$diagnosis=="ctrl"]
  66. case_name = meta.mfish$data_name[meta.mfish$diagnosis=="ASD"]
  67. ##--- choose assay 'SCT': measured expression,'SCTpred': imputed expression. Both use 'counts' slot ---
  68. assay = 'SCTpred'
  69. ##--- choose method of Spatial Signaling Score 1:demoninator being # of interacted receiver cells,
  70. ## 2:demoninator being # of all receiver cells,
  71. save.id = 2 # default is 2
  72. ##--- directory of results for all datasets ---
  73. root_dir = '/home/ubuntu/differentialS3/'
  74. data_dir = '/home/ubuntu/differentialS3/panel1/'
  75. results_folder = '/home/ubuntu/differentialS3/results/'
  76. data_dir_wilcoxtest = '/home/ubuntu/differentialS3/wilcoxtest/'
  77. ##--- choose cell identity labels to be processed ---
  78. # labels from imputed expression: 'imputed.cell_identity'
  79. # labels from measured expression: 'cell_identity'
  80. cluster_column = "imputed.cell_identity"
  81. ##--- choose the spatial network, 'SN_2median':physical distance < 2*median are connected
  82. ## 'SN_touched':two cells are touched, juxtacrine signalling
  83. spatial_network_name = 'SN_touched'
  84. ##--- threshold of proportion of interacting receiver cells ---
  85. prop_thrd = 0.2
  86. ##--- load SFARI gene list ---
  87. sfari.gene = read.csv("/home/ubuntu/SFARI-Gene_genes_01-23-2023release_03-02-2023export.csv")
  88. ##--- Format of selected ligand-receptor pairs ---
  89. # "ligand" "receptor" "ligand.location" "LR_comb"
  90. # 1 ...
  91. # 2 ...
  92. # ...
  93. ##--- load selected ligand-receptor pairs ---
  94. LRname = "_exp-5_intersect"
  95. selected_pairs = read.csv(file=paste0(root_dir,'selected_ligand-receptor_pairs_threshold_valley_20230714.txt'))
  96. selected_pairs = selected_pairs[,-1]
  97. selected_pairs$LR_comb = paste0(selected_pairs$ligand,'--',selected_pairs$receptor)
  98. ##--- Subset ligand-receptor pairs for which ligand and/or receptor are SFARI genes ---
  99. selected_pairs_sfari = NULL
  100. for (i in 1:nrow(selected_pairs)){
  101. if ( selected_pairs$ligand[i] %in% sfari.gene$gene.symbol | selected_pairs$receptor[i] %in% sfari.gene$gene.symbol){
  102. selected_pairs_sfari=rbind(selected_pairs_sfari,selected_pairs[i,])
  103. }
  104. }
  105. write.csv(selected_pairs_sfari,file=paste0(root_dir,'sfari_ligand-receptor_pairs_20230714.txt'))
  106. ## NOTE: all steps will saved intermediate results. Subsequent steps will directly load the saved results
  107. #======================================== 2. GENERATE SPATIAL NETWORKS & CALCULATE PROPORTION OF INTERACTING RECEIVER CELLS ==============================================
  108. for (x in c(1:length(data_name))){
  109. results_folder = paste0(root_dir,'panel1/',data_name[x],'/')
  110. if (!dir.exists(results_folder)){
  111. dir.create(results_folder)
  112. }
  113. Mer <- readRDS(paste0("/home/ubuntu/label transfer/dataset/",meta.mfish$data_name[[x]],"_imputed_18k_genes_-SCT-anchor-SCT.rds"))
  114. gene.list = unique(c(rownames(Mer@assays$SCT), selected_pairs$ligand, selected_pairs$receptor))
  115. gene.list = gene.list[gene.list %in% rownames(Mer)]
  116. Mer <- subset(Mer, features = gene.list)
  117. cell_id = names(Idents(Mer))
  118. cell_id = substr(cell_id,7+nchar(data_name[x]),16+nchar(data_name[x]))
  119. Idents(Mer) = as.numeric(cell_id)
  120. Mer<-RenameCells(Mer, new.names =as.character(Idents(Mer)))
  121. mer.loc <- data.frame(row.names = Idents(Mer))
  122. mer.loc$X = Mer$X
  123. mer.loc$Y = Mer$Y
  124. actual_height = max(Mer$Y) - min(Mer$Y)
  125. actual_width = max(Mer$X) - min(Mer$X)
  126. height = actual_height/1000 # plot height
  127. width = actual_width/1000
  128. size = width/100
  129. #---------------- generate spatial networks ----------------
  130. if (spatial_network_name == 'SN_touched'){
  131. # cell-cell contact network/graph generated on python, directly load here
  132. annot_network = read.csv(paste0('/home/ubuntu/',meta.mfish$data_name[[x]],'/touched_cell_networks.csv'))
  133. # delete the edge of cells filtered in preprocessing
  134. annot_network = annot_network[annot_network$from %in% Idents(Mer) &annot_network$to %in% Idents(Mer),]
  135. annot_network$from = factor(annot_network$from)
  136. annot_network$to = factor(annot_network$to)
  137. annot_network$distance = sqrt((annot_network$sdimx_begin-annot_network$sdimx_end)**2+(annot_network$sdimy_begin-annot_network$sdimy_end)**2)
  138. print(paste0(meta.mfish$data_name[[x]], ":median of cell cell distance is ", median(annot_network$distance)))
  139. Mer@graphs[[spatial_network_name]] = list(name = spatial_network_name, method = 'touched',networkDT = annot_network)
  140. } else if ( spatial_network_name == 'SN_2median'){
  141. # find median of nearest neighbor
  142. nn_spatial <- dbscan::kNN(loc , k=1)
  143. median_neighbors = median(nn_spatial[["dist"]])
  144. print(paste0(data_name[dataset],': median of nearest neighbor is ',median_neighbors))
  145. # spatial networks, distance < 2* median
  146. Mer<-GenerateSpatialNetwork(Mer, threshold=median_neighbors*2,
  147. name = spatial_network_name,full_network = FALSE)
  148. }
  149. #---------------- Calculate proportion of interacting receiver cells. results are stored in Mer@graphs[[spatial_network_name]][['proportion']][[cluster_column]] ----------------
  150. Mer<-AnalysisSpatialNetworks(object=Mer,
  151. cluster_column = 'imputed.cell_identity',
  152. selected_clusters = selected_clusters,
  153. selected_pairs = selected_pairs,
  154. networks = spatial_network_name)
  155. Mer<-AnalysisSpatialNetworks(object=Mer,
  156. cluster_column = 'cell_identity',
  157. selected_clusters = selected_clusters,
  158. selected_pairs = selected_pairs,
  159. networks = spatial_network_name)
  160. saveRDS(Mer,paste0(results_folder,"Seurat_object_",spatial_network_name,".rds"))
  161. }
  162. #---------------- Filter proportion of interacting receiver cells ----------------
  163. ##--- Load proportion for all datasets ----
  164. cluster_column = 'imputed.cell_identity'
  165. proportion_all = NULL
  166. for(dataset in c(ctrl_name, case_name)){
  167. data_folders = paste0(data_dir, dataset, '/')
  168. print(dataset)
  169. Mer<-readRDS(paste0(data_folders,"Seurat_object_", spatial_network_name, ".rds"))
  170. print(unique(Mer$imputed.cell_identity))
  171. spatial_all_scores<-Mer@graphs[[spatial_network_name]][['proportion']][[cluster_column]]
  172. spatial_all_scores$data = dataset
  173. proportion_all = rbind(proportion_all,spatial_all_scores)
  174. }
  175. write.csv(proportion_all,paste0(root_dir,'proportion/proportion_all_',cluster_column,'_',spatial_network_name,'.csv'))
  176. ##--- Calculate the mean proportions within each diagnosis ----
  177. proportion_mean = data.frame(row.names = unique(proportion_all$LR_cell_comb))
  178. for (cell_identity_pairs in unique(proportion_all$LR_cell_comb)){
  179. # control
  180. temp =proportion_all[proportion_all$LR_cell_comb %in%cell_identity_pairs &proportion_all$data %in% ctrl_name,]
  181. proportion_mean[cell_identity_pairs,'mean_ctrl'] = mean(temp$proportion)
  182. proportion_mean[cell_identity_pairs,'standard_error_ctrl'] = sd(temp$proportion)/sqrt(nrow(temp)-1)
  183. # case
  184. temp =proportion_all[proportion_all$LR_cell_comb %in%cell_identity_pairs &proportion_all$data %in% case_name,]
  185. proportion_mean[cell_identity_pairs,'mean_case'] = mean(temp$proportion)
  186. proportion_mean[cell_identity_pairs,'standard_error_case'] = sd(temp$proportion)/sqrt(nrow(temp)-1)
  187. }
  188. proportion_mean = proportion_mean[!is.na(proportion_mean$standard_error_ctrl) &!is.na(proportion_mean$standard_error_case),]
  189. proportion_mean$LR_cell_comb = rownames(proportion_mean)
  190. write.csv(proportion_mean,paste0(root_dir,'proportion/proportion_mean_',cluster_column,'_',spatial_network_name,'.csv'))
  191. ##--- give the cell identities we are interested ----
  192. selected_clusters = unique(Mer$imputed.cell_identity)
  193. ##--- all the homotypical cell identity pairs A-A and its proportions ---
  194. same_DT = data.table(V1 = selected_clusters, V2 = selected_clusters)
  195. same_DT$LR_cell_comb = paste0(same_DT$V1,'--',same_DT$V2)
  196. proportion_all_homo = proportion_mean[proportion_mean$LR_cell_comb %in% same_DT$LR_cell_comb,]
  197. write.csv(proportion_all_homo,paste0(root_dir,'proportion/proportion_mean_homo_',cluster_column,'_',spatial_network_name,'.csv'))
  198. ##--- apply threshold for homotypical cell identity pairs ---
  199. proportion_homo_filtered = proportion_all_homo[proportion_all_homo$mean_ctrl>prop_thrd,]
  200. ##--- heterotypic cell identity pairs: A-B, B-A ---
  201. combn_DT = as.data.table(t(combn(selected_clusters, m = 2)))
  202. # direction 1: A-B
  203. combn_DT$LR_cell_comb_1 = paste0(combn_DT$V1,'--',combn_DT$V2)
  204. # direction 2: B-A
  205. combn_DT$LR_cell_comb_2 = paste0(combn_DT$V2,'--',combn_DT$V1)
  206. combn_DT$proportion_1 =NA
  207. combn_DT$proportion_2=NA
  208. ##--- for any two cell identities, find the maximum proportion in either direction ---
  209. for (i in seq(1,nrow(combn_DT))){
  210. if (length(proportion_mean[proportion_mean$LR_cell_comb %in% combn_DT$LR_cell_comb_1[i],"mean_ctrl"]!=0)){
  211. combn_DT$proportion_1[i] = proportion_mean[proportion_mean$LR_cell_comb %in% combn_DT$LR_cell_comb_1[i],"mean_ctrl"]
  212. }
  213. if (length(proportion_mean[proportion_mean$LR_cell_comb %in% combn_DT$LR_cell_comb_2[i],"mean_ctrl"]!=0)){
  214. combn_DT$proportion_2[i] = proportion_mean[proportion_mean$LR_cell_comb %in% combn_DT$LR_cell_comb_2[i],"mean_ctrl"]
  215. }
  216. combn_DT$proportion[i] = max(combn_DT$proportion_1[i],combn_DT$proportion_2[i])
  217. }
  218. proportion_hetero_all = combn_DT[!is.na(combn_DT$proportion_1),]
  219. write.csv(proportion_hetero_all,paste0(root_dir,'proportion/proportion_mean_hetero_',cluster_column,'_',spatial_network_name,'.csv'))
  220. ##--- apply threshold for heterotypic cell identity pairs: find the maximum proportion in either direction > threshold ---
  221. proportion_hetero_filtered = proportion_hetero_all[proportion_hetero_all$proportion>prop_thrd,]
  222. ##--- all the cell identity pairs after applying filtering ---
  223. selected_cluster_pairs = c(proportion_hetero_filtered$LR_cell_comb_1,proportion_hetero_filtered$LR_cell_comb_2,rownames(proportion_homo_filtered))
  224. write.csv(selected_cluster_pairs,paste0(root_dir,'proportion/selected_cluster_pairs_proportion_',prop_thrd,'_',cluster_column,'_',spatial_network_name,'.csv'),col.names = NA, row.names = FALSE)
  225. #---------------- Visualize selected proportions of interacting receiver cells ----------------
  226. ##--- load cell identity pairs after applying filtering ---
  227. selected_cluster_pairs = read.csv(paste0(root_dir,'proportion/selected_cluster_pairs_proportion_0.2_',cluster_column,'_',spatial_network_name,'.csv'))
  228. selected_cluster_pairs = sort(selected_cluster_pairs$x)
  229. ##--- load proportion for all cell identity pairs and all datasets ---
  230. proportion_all = read.csv(paste0(root_dir,'proportion/proportion_all_',cluster_column,'_',spatial_network_name,'.csv'))
  231. selDT = as.data.table(proportion_all)
  232. selDT_d = data.table::dcast.data.table(selDT, data~LR_cell_comb, value.var = 'proportion', fill = 0)
  233. dataname = c(ctrl_name,case_name)
  234. rownames = selDT_d$data
  235. selDT_d = selDT_d[,-1]
  236. selDT_d = as.matrix(selDT_d)
  237. rownames(selDT_d) = rownames
  238. selDT_g = selDT_d[dataname,]
  239. ##--- do wilcoxon test on proportions to identify cell identity pairs with significant difference between case and control, p.value<0.05 ---
  240. sign_cluster_pairs = NULL
  241. for (col in 1:ncol(selDT_g)) {
  242. ttest=t.test(selDT_g[ctrl_name,col],selDT_g[case_name,col],na.action=na.omit)
  243. print(paste0(colnames(selDT_g)[col]," proportion p.value: ",ttest$p.value))
  244. if (ttest$p.value<=0.05) sign_cluster_pairs = c(sign_cluster_pairs,colnames(selDT_g)[col])
  245. }
  246. sign_cluster_pairs = intersect(sign_cluster_pairs,selected_cluster_pairs)
  247. ##--- mean case vs mean ctrl ---
  248. proportion_case = data.frame(row.names = selected_cluster_pairs )
  249. proportion_sub = proportion_all[proportion_all$data %in% case_name,]
  250. for (cell_identity_pairs in selected_cluster_pairs ){
  251. temp =proportion_sub[proportion_sub$LR_cell_comb %in%cell_identity_pairs,]
  252. proportion_case[cell_identity_pairs,'mean'] = mean(temp$proportion)
  253. proportion_case[cell_identity_pairs,'standard_error'] = sd(temp$proportion)/sqrt(nrow(temp)-1)
  254. }
  255. proportion_case$diagnosis = 'Case'
  256. proportion_case$cell_identity_pairs = rownames(proportion_case)
  257. proportion_ctrl = data.frame(row.names = selected_cluster_pairs)
  258. proportion_sub = proportion_all[proportion_all$data %in% ctrl_name,]
  259. for (cell_identity_pairs in selected_cluster_pairs ){
  260. temp =proportion_sub[proportion_sub$LR_cell_comb %in%cell_identity_pairs,]
  261. proportion_ctrl[cell_identity_pairs,'mean'] = mean(temp$proportion)
  262. proportion_ctrl[cell_identity_pairs,'standard_error'] = sd(temp$proportion)/sqrt(nrow(temp)-1)
  263. }
  264. proportion_ctrl$diagnosis = 'Control'
  265. proportion_ctrl$cell_identity_pairs = rownames(proportion_ctrl)
  266. proportion_mean = rbind(proportion_case,proportion_ctrl)
  267. x.text <- transpose(as.data.frame(strsplit(sort(unique(proportion_mean$cell_identity_pairs)), split = "--")))
  268. colnames(x.text) = c('sender', 'receiver')
  269. x.text$sender.receiver = paste0(x.text$sender,'--',x.text$receiver)
  270. x.text$color = 'black'
  271. x.text$color[x.text$sender.receiver %in% sign_cluster_pairs] = 'red'
  272. ggplot(data = proportion_mean,aes(x=mean,y=cell_identity_pairs,color=diagnosis))+geom_point(alpha=0.5)+#position = position_dodge(width = 1)
  273. geom_errorbar(aes(xmin = mean-standard_error,xmax = mean+standard_error,color=diagnosis),alpha=0.5) +
  274. theme_bw() + scale_color_manual(values = c('orange','black'))+
  275. theme(axis.text.x = element_text(angle = 0, vjust = 0.5, hjust=0.5,size=16),
  276. legend.title = element_text(size=16), #change legend title font size
  277. legend.text = element_text(size=15))+
  278. annotate(geom = "text", y=c(nrow(x.text)+1), x = -0.5, label = c('receiver'), size = 7,hjust = 0,fontface="bold")+
  279. annotate(geom = "text", y=c(nrow(x.text)+1), x = -0.55, label = c('sender'), size = 7, hjust = 1,fontface="bold")+
  280. annotate(geom = "text", y=c(nrow(x.text)+1), x = -0.525, label = c('-'), size = 7, hjust = 0.5,fontface="bold")+
  281. annotate(geom = "text", y = seq_len(nrow(x.text)), x = -0.5, label = x.text$receiver, size = 6,colour = x.text$color,hjust = 0)+
  282. annotate(geom = "text", y = seq_len(nrow(x.text)), x = -0.55, label = x.text$sender, size = 6,colour = x.text$color,hjust = 1)+
  283. annotate(geom = "text", y = seq_len(nrow(x.text)), x = -0.525, label = '-', size = 6,colour = x.text$color,hjust = 0.5)+
  284. coord_cartesian(xlim=c(0,1),ylim=c(0.5,nrow(x.text)+0.5),expand = FALSE, clip = "off")+
  285. theme(plot.margin=unit(c(2,1,1,20),'lines'),axis.text.y = element_blank(),axis.title = element_blank())
  286. ggsave(paste0(root_dir,'proportion/',cluster_column,'_proportion_',prop_thrd,'_case_vs_ctrl_',spatial_network_name,'_20230714.png'),
  287. width = 9.3,height=30,units = 'in')
  288. #======================================== 3. EVALUATE LARB CUTOFF ==============================================
  289. assay='SCTpred'
  290. data_folders = paste0(data_dir,data_name[4],'/')
  291. ##--- load the merfish dataset with the spatial networks ---
  292. Mer<-readRDS(paste0(data_folders,"Seurat_object_",spatial_network_name,".rds"))
  293. Mer<-subset(Mer,feature = unique(c(selected_pairs$ligand,selected_pairs$receptor)))
  294. expr_select = GetAssayData(object = Mer, assay = assay, slot = 'data')
  295. cell_metadata = [email hidden]
  296. ##--- the annotation of spatial network ---
  297. annot_network_directional = Mer@graphs[[spatial_network_name]][["networkDT"]]
  298. ##--- get the expression ---
  299. colnames(expr_select) = colnames(Mer)
  300. ##--- check if ligand or receptor existing in the expression ---
  301. selected_pairs_sub = selected_pairs[selected_pairs$ligand %in% rownames(expr_select),]
  302. selected_pairs_sub = selected_pairs_sub[selected_pairs_sub$receptor %in% rownames(expr_select),]
  303. ##--- only keep the ligand-receptor pairs for ligand and receptor existing in the expression ---
  304. select_ligands = as.character(selected_pairs_sub$ligand)
  305. select_receptors = as.character(selected_pairs_sub$receptor)
  306. sender.expr = as.matrix(expr_select[select_ligands,as.character(annot_network_directional$from)])
  307. receiver.expr = as.matrix(expr_select[select_receptors,as.character(annot_network_directional$to)])
  308. ##--- edge weight in cell-cell contact graph ---
  309. LARB_expr = sender.expr*receiver.expr
  310. hist(log(LARB_expr),breaks=100)
  311. LARB_cutoff = exp(-5) # 2x peak of log distribution
  312. #======================================== 4. CALCULATE SPATIAL SIGNALING SCORE ==============================================
  313. assay="SCTpred"
  314. cluster_column = "imputed.cell_identity"
  315. for (x in c(1:length(data_name))){
  316. print(data_name[x])
  317. results_folder = paste0('/home/ubuntu/differentialS3/panel1/',data_name[x],'/')
  318. if (!dir.exists(results_folder)){
  319. dir.create(results_folder)
  320. }
  321. data_folders = paste0(data_dir,data_name[x],'/')
  322. Mer<-readRDS(paste0(data_folders,"Seurat_object_",spatial_network_name,".rds"))
  323. if(!dir.exists(paste0(results_folder,'3_lig-rec_cell-cell_communication'))){
  324. dir.create(paste0(results_folder,'3_lig-rec_cell-cell_communication'))
  325. }
  326. ##--- only run for the cell_identity pairs shortlist ---
  327. selected_cluster_pairs = read.csv(paste0(root_dir,'proportion/selected_cluster_pairs_proportion_',prop_thrd,'_imputed.cell_identity_',spatial_network_name,'.csv'))
  328. selected_cluster_pairs = sort(selected_cluster_pairs$x)
  329. Mer<-CalculateSpatialSignalingScore(object=Mer,
  330. cluster_column = cluster_column,
  331. selected_cluster_pairs = selected_cluster_pairs,
  332. normalization = FALSE,
  333. LARB_cutoff = LARB_cutoff,
  334. assay = assay,
  335. slot = 'data',
  336. selected_pairs = selected_pairs,
  337. networks = spatial_network_name,
  338. save.id = save.id)
  339. saveRDS(Mer,paste0(results_folder,save.id,"_Seurat_object_SpatialSignalingScore",spatial_network_name, "_assay_",assay,LRname,".rds"))#"_LARB_",LARB_cutoff,"_scale.factor_",scale.factor,
  340. }
  341. #======================================== 5. CALCULATE CASE-CONTROL DIFFERENTIAL SPATIAL SIGNALING SCORE ==============================================
  342. # get shortlist cell_identity pairs
  343. assay='SCTpred'
  344. cluster_column = 'imputed.cell_identity'
  345. selected_cluster_pairs = read.csv(paste0(root_dir,'proportion/selected_cluster_pairs_proportion_0.2_',cluster_column,'_',spatial_network_name,'.csv'))
  346. selected_cluster_pairs = sort(selected_cluster_pairs$x)
  347. ctrl_name = meta.mfish$data_name[meta.mfish$diagnosis=="ctrl"]
  348. case_name = meta.mfish$data_name[meta.mfish$diagnosis=="ASD"]
  349. phenotypeA = meta.mfish$data_name[meta.mfish$layering=="disorganized" & # bud_mis_layering_no_desease_state_case
  350. meta.mfish$diagnosis=="ASD" &
  351. meta.mfish$state=="canonical" &
  352. meta.mfish$bud=="present"]
  353. phenotypeA = c(phenotypeA, "20221006_JY_T2_B4_108A")
  354. phenotypeA = phenotypeA[! phenotypeA %in% "20220916_JY_T2_B4_50"]
  355. phenotypeB = meta.mfish$data_name[ meta.mfish$diagnosis=="ASD" &
  356. meta.mfish$state=="diseased"]
  357. grps = list("case_name" = case_name,
  358. "phenotypeA" = phenotypeA,
  359. "phenotypeB" = phenotypeB)
  360. for (group in names(grps)){
  361. score_all_dataset = FindDifferentialSpatialSignalingScore(case_name=get(group),
  362. ctrl_name=ctrl_name, selected_pairs= selected_pairs,
  363. cluster_column=cluster_column, selected_cluster_pairs = selected_cluster_pairs,
  364. spatial_network_name=spatial_network_name, data_dir=data_dir,save.id=save.id,
  365. assay = assay,LRname = LRname)
  366. saveRDS(score_all_dataset,paste0(root_dir,'wilcoxtest/',save.id,'_dS3_', group, '_vs-all-ctrls_',cluster_column,'_',spatial_network_name,"_assay_",assay,LRname,'.rds'))
  367. }
  368. #--- compare random sets of controls: we use mean 99th percentile of NMD distribution in 50 randomized control-to-control comparisons as threshold ----
  369. df <- data.frame()
  370. for (itr in 1:50){
  371. ctrl1 <- union(sample(meta.mfish$data_name[meta.mfish$layering %in% "disorganized"], 3), sample(meta.mfish$data_name[meta.mfish$layering %in% "layered"], 4))
  372. ctrl2 <- ctrl_name[!ctrl_name %in% ctrl1]
  373. score_all_dataset = FindDifferentialSpatialSignalingScore(case_name=ctrl2,
  374. ctrl_name=ctrl1, selected_pairs= selected_pairs,
  375. cluster_column=cluster_column, selected_cluster_pairs = selected_cluster_pairs,
  376. spatial_network_name=spatial_network_name, data_dir=data_dir,save.id=save.id,
  377. assay = assay,LRname = LRname)
  378. saveRDS(score_all_dataset,paste0(root_dir,'wilcoxtest/',save.id,'_dS3_ctrlvsctrl-itr', itr, '_',cluster_column,'_',spatial_network_name,"_assay_",assay,LRname,'.rds'))
  379. metric_score = readRDS(paste0(data_dir_wilcoxtest, save.id,'_dS3_ctrlvsctrl-itr', itr, '_',cluster_column,'_',spatial_network_name,"_assay_",assay, LRname, '.rds'))
  380. metric_score <- metric_score[metric_score$p.adjust < thr.padjust, ]
  381. print(nrow(metric_score[metric_score$p.adjust < thr.padjust,]))
  382. df[itr, 1:6] <- summary(metric_score$differential_S3_normalized)
  383. df[itr, 7] <- mean(abs(metric_score$differential_S3_normalized))
  384. }
  385. colnames(df) <- c("min","Q1", "median", "mean", "Q3", "max", "mean abs NMD")
  386. for (itr in 1:50){
  387. metric_score = readRDS(paste0(data_dir_wilcoxtest, save.id,'_dS3_ctrlvsctrl-itr', itr, '_',cluster_column,'_',spatial_network_name,"_assay_",assay, LRname, '.rds'))
  388. print(nrow(metric_score[metric_score$p.adjust < thr.padjust & abs(metric_score$differential_S3_normalized) > mean(df$V9), ]))
  389. }
  390. colnames(df[, 8:10]) <- c("95th percentile", "99th percentile", "99.9th percentile")
  391. saveRDS(df, "/home/ubuntu/differentialS3/wilcoxtest/ctrl-vs-ctrl_iterations.rds")
  392. #======================================== 6. DOTPLOT VISUALIZATION OF CASE-CONTROL DIFFERENTIAL SPATIAL SIGNALING SCORE ==============================================
  393. assay='SCTpred'
  394. cluster_column = 'imputed.cell_identity'
  395. selected_pairs_sfari = read.csv(file=paste0(root_dir,'sfari_ligand-receptor_pairs_20230714.txt'))
  396. selected_pairs_nosfari = selected_pairs[!selected_pairs$LR_comb %in% selected_pairs_sfari$LR_comb,]
  397. # set the parameter
  398. size = "p.adjust"
  399. diff = "differential_S3_normalized"
  400. color = "differential_S3_normalized"
  401. metrics = "score"
  402. thr.pvalue = NULL
  403. filtering = TRUE
  404. thr.diff = 0.006 # mean 99th percentile of NMD distribution in 50 randomized control-to-control comparisons
  405. thr.padjust = 0.05
  406. orderby = color
  407. top_num_per_pair = NULL
  408. top_num_all = 200L
  409. sfari = ""
  410. highlight = sfari.gene$gene.symbol
  411. cluster_on = color
  412. max_diff=NULL
  413. p.circle = 0.05
  414. meanlig_thr = NULL
  415. meanrec_thr = NULL
  416. control.grp = "all"
  417. for (option in c("case_name", "phenotypeA", "phenotypeB")){
  418. metric_score = readRDS(paste0(data_dir_wilcoxtest, save.id, '_dS3_', option, '_vs-', control.grp, '-ctrls_', cluster_column,'_', spatial_network_name, "_assay_", assay, LRname,'.rds'))
  419. print(paste0(option, " ", nrow(metric_score[metric_score$p.adjust<thr.padjust & abs(metric_score$differential_S3_normalized) > 0.006,]), " significant LRCC"))
  420. lig.rep_order = VisualizeS3Dotplot(metric_score=metric_score, size=size,color=color,diff=diff,metrics = metrics,
  421. filtering = filtering, thr.pvalue = thr.pvalue, thr.diff = thr.diff,thr.padjust = thr.padjust,
  422. orderby = orderby,top_num_per_pair = top_num_per_pair,top_num_all=top_num_all,
  423. cluster_on =cluster_on, max_diff=max_diff,results_folder=data_dir_wilcoxtest,
  424. cluster_column=cluster_column,spatial_network_name=spatial_network_name,assay = assay,
  425. selected_pairs=selected_pairs,#_sfari,sfari = sfari,
  426. highlight = highlight, selected_clusters_pairs = selected_clusters_pairs,
  427. clustering='col',cluster_order_row = selected_clusters_pairs$sender.receiver,#cluster_order_col = cluster_order_col,
  428. p.circle=p.circle,save.id=save.id,w.adjust = 5, h.adjust = 4.5, saving_name = paste0('_pearson_',option,'_', control.grp, 'ctrls', LRname))
  429. }
  430. #======================================== 7. HEATMAP VISUALIZATION OF POSITIVE-CONTROL LIGAND-RECEPTOR INTERACTIONS ==============================================
  431. ##--- ligand-receptor pairs from literature ---
  432. lig_rep_positive = read.csv(file='/home/ubuntu/positive_ctrl/lig-rec-shortlist_230705_v2.txt')
  433. ##--- shortlist cell_identity pairs ---
  434. cell_identity_select_1 = expand.grid(selected_clusters,selected_clusters)
  435. colnames(cell_identity_select_1) = c('receiver','sender')
  436. cell_identity_select_1$sender.receiver = paste0(cell_identity_select_1$sender,'--',cell_identity_select_1$receiver)
  437. cell_identity_select = read.csv(file='/home/ubuntu/differentialS3/positive_ctrl/selected cell_identity pairs sender_v4.csv')[,-1]
  438. cell_identity_select_1 = cell_identity_select_1[cell_identity_select_1$sender.receiver %in% cell_identity_select,]
  439. cell_identity_select_1 = transpose(as.data.frame(strsplit(cell_identity_select, split = "--")))
  440. colnames(cell_identity_select_1) = c('sender','receiver')
  441. ##--- get scaled S3 for all datasets and all ligand-receptor pairs ---
  442. ScaledSpatialSignalingScore = readRDS(paste0(data_dir_wilcoxtest,save.id,'_all_ScaledSpatialSignalingScore_',cluster_column,'_',spatial_network_name,"_assay_",assay,LRname,'.rds'))
  443. cell_identity_select_1 = cell_identity_select_1[cell_identity_select_1$sender.receiver %in% unique(ScaledSpatialSignalingScore$LR_cell_comb),]
  444. #cell_identity_select_1 = cell_identity_select_1[cell_identity_select_1$sender.receiver %in% sign_cell_identity_pairs,]
  445. ##--- subset control datasets and their positive-control ligand-receptor interactions
  446. ScaledSpatialSignalingScore = ScaledSpatialSignalingScore[ScaledSpatialSignalingScore$LR_comb %in% lig_rep_positive_1$LR_comb,]
  447. #subset selected cell_identity pairs
  448. ScaledSpatialSignalingScore = ScaledSpatialSignalingScore[ScaledSpatialSignalingScore$LR_cell_comb %in% cell_identity_select_1$sender.receiver,]
  449. cluster_on = "mean_ctrl"
  450. ScaledSpatialSignalingScore_temp = expand.grid(cell_identity_select_1$sender.receiver,lig_rep_positive_1$LR_comb)
  451. colnames(ScaledSpatialSignalingScore_temp) = c("LR_cell_comb","LR_comb" )
  452. ScaledSpatialSignalingScore_temp$LR_CC = paste0(ScaledSpatialSignalingScore_temp$LR_comb,'---',ScaledSpatialSignalingScore_temp$LR_cell_comb)
  453. ScaledSpatialSignalingScore_temp$mean_ctrl = 0
  454. ##--- get the mean scaled S3 across all controls ---
  455. ScaledSpatialSignalingScore = rbind(ScaledSpatialSignalingScore[,c("LR_cell_comb","LR_comb","LR_CC" ,"mean_ctrl" )],
  456. ScaledSpatialSignalingScore_temp[!ScaledSpatialSignalingScore_temp$LR_CC%in%ScaledSpatialSignalingScore$LR_CC,])
  457. selDT = as.data.table(ScaledSpatialSignalingScore)
  458. selDT_d = data.table::dcast.data.table(selDT, LR_cell_comb ~LR_comb, value.var = cluster_on, fill = 0)
  459. rownames = as.character(selDT_d[[1]])
  460. write.csv(selDT_d,file=paste0(root_dir,"wilcoxtest/","pos-ctrl-ScaledSpatialSignalingScore.csv"))
  461. clus_sort_names_row = cell_identity_select_1$sender.receiver
  462. y.text <- transpose(as.data.frame(strsplit(clus_sort_names_row, split = "--")))
  463. colnames(y.text ) = c('sender', 'receiver')
  464. y.text$sender.receiver = paste0(y.text$sender,"--",y.text$receiver)
  465. y.text$color = 'black'
  466. y.text$symble = "-"
  467. selDT[, `:=`(LR_cell_comb, factor(LR_cell_comb, clus_sort_names_row))]
  468. ##--- change the col order ---
  469. clus_sort_names_col = lig_rep_positive_1$LR_comb
  470. x.text <- transpose(as.data.frame(strsplit(clus_sort_names_col, split = "--")))
  471. colnames(x.text) = c('ligand', 'receptor')
  472. selDT[, `:=`(LR_comb, factor(LR_comb, clus_sort_names_col))]
  473. selDT$mean_ctrl[selDT$mean_ctrl>0.05]=0.05
  474. max = max(selDT$mean_ctrl)
  475. median = median(selDT$mean_ctrl)
  476. mean = mean(selDT$mean_ctrl)
  477. min= min(selDT$mean_ctrl)
  478. ggplot()+ geom_tile(data = selDT, aes_string(x = "LR_comb", y = "LR_cell_comb", fill = "mean_ctrl")) +
  479. theme_classic() +
  480. labs(fill='mean\ncontrol\nScaledSpatialSignalingScore')+
  481. annotate(geom = "text", x=c(0), y = -3.5, label = c('receptor'), size = 3.5, angle=90,hjust = 0,fontface="bold")+
  482. annotate(geom = "text", x=c(0), y = -4, label = c('ligand'), size = 3.5, angle=90,hjust = 1,fontface="bold")+
  483. annotate(geom = "text", y =c(nrow(y.text)+1), x = -6.5, label = c('sender'), size = 3.5,hjust = 1,fontface="bold")+
  484. annotate(geom = "text", y = c(nrow(y.text)+1), x = -6, label = c('receiver'), size = 3.5,hjust = 0,fontface="bold")+
  485. annotate(geom = "text", y = c(nrow(y.text)+1), x = -6.25, label = c('-'), size = 3.5,hjust = 0.5,fontface="bold")+
  486. annotate(geom = "text", x = seq_len(nrow(x.text)), y = -3.5, label = x.text$receptor, size = 2.7, angle=90,hjust = 0)+
  487. annotate(geom = "text", x = seq_len(nrow(x.text)), y = -4, label = x.text$ligand, size = 2.7, angle=90,hjust = 1)+
  488. annotate(geom = "text", y = seq_len(nrow(y.text)), x = -6.5, label = y.text$sender, colour=y.text$color,size = 2.7,hjust = 1)+
  489. annotate(geom = "text", y = seq_len(nrow(y.text)), x = -6.25, label = y.text$symble, colour=y.text$color,size = 2.7,hjust = 0.5)+
  490. annotate(geom = "text", y = seq_len(nrow(y.text)), x = -6, label = y.text$receiver, colour=y.text$color,size = 2.7,hjust = 0)+
  491. coord_cartesian(ylim = c(0.5, nrow(y.text)+0.5),xlim=c(0.5,nrow(x.text)+0.5),expand = FALSE, clip = "off")+
  492. theme(plot.margin=unit(c(1.5,1,6,11),'lines'),axis.text = element_blank(),axis.title = element_blank())+
  493. scale_fill_gradient2(low='blue',high='red',mid='yellow',midpoint =(min+max)/2)
  494. ggsave(paste0(root_dir,"wilcoxtest/",save.id,'_',cluster_column,'_mean_ScaledSpatialSignalingScore_of_positive_lig-rep_on_ctrl_dataset_',spatial_network_name,LRname,'_colclip0.05.png'),
  495. width = 7.5,height=5.6,units = 'in')
  496. #======================================== 8. COMPARE SCALED S3 CALCULATED WITH MEASURED AND IMPUTED EXPRESSION ==============================================
  497. assay = 'SCT'
  498. cluster_column = 'cell_identity'
  499. ScaledSpatialSignalingScore_measured = readRDS(paste0(data_dir_wilcoxtest,save.id,'_all_ScaledSpatialSignalingScore_',cluster_column,'_',spatial_network_name,"_assay_",assay,LRname,'.rds'))
  500. assay = 'SCTpred'
  501. cluster_column = 'imputed.cell_identity'
  502. ScaledSpatialSignalingScore_imputed = readRDS(paste0(data_dir_wilcoxtest,save.id,'_all_ScaledSpatialSignalingScore_',cluster_column,'_',spatial_network_name,"_assay_",assay,LRname,'.rds'))
  503. ##--- get all ligand-receptor pairs present in MERFISH panel ---
  504. lig_rec = unique(ScaledSpatialSignalingScore_measured$LR_comb)
  505. ##--- calculate max LR_expr across all cell identity pairs for measured and imputed separately ---
  506. max_LR_expr_pred = data.frame(row.names = paste(lig_rec))
  507. assay = 'SCTpred'
  508. cluster_column = 'imputed.cell_identity'
  509. for (dataset in data_name){
  510. results_folder = paste0(data_dir,'/',dataset,'/')
  511. Mer = readRDS(paste0(results_folder,save.id,"_Seurat_object_SpatialSignalingScore",spatial_network_name, "_assay_",assay,LRname,".rds"))
  512. spatial_all_scores<-Mer@graphs[[spatial_network_name]]$SpatialSignalingScore[[cluster_column]]
  513. LR_expr = spatial_all_scores[,c('LR_comb','LR_cell_comb','LR_expr')]
  514. colnames(LR_expr)[3] = 'Value'
  515. LR_expr = dcast(LR_expr,LR_comb~LR_cell_comb)
  516. rownames(LR_expr) = LR_expr$LR_comb
  517. LR_expr = LR_expr[lig_rec,]
  518. LR_expr = LR_expr[,-1]
  519. # max lig_expr across all cell identity pairs for each ligand-receptor pair
  520. max_LR_expr_pred[[dataset]] = apply(LR_expr,1,max)
  521. }
  522. max_LR_expr = data.frame(row.names = paste(lig_rec))
  523. assay = 'SCT'
  524. cluster_column = 'cell_identity'
  525. for (dataset in data_name){
  526. results_folder = paste0(data_dir,'/',dataset,'/')
  527. Mer = readRDS(paste0(results_folder,save.id,"_Seurat_object_SpatialSignalingScore",spatial_network_name, "_assay_",assay,LRname,".rds"))
  528. spatial_all_scores<-Mer@graphs[[spatial_network_name]]$SpatialSignalingScore[[cluster_column]]
  529. LR_expr = spatial_all_scores[,c('LR_comb','LR_cell_comb','LR_expr')]
  530. colnames(LR_expr)[3] = 'Value'
  531. LR_expr = dcast(LR_expr,LR_comb~LR_cell_comb)
  532. rownames(LR_expr) = LR_expr$LR_comb
  533. LR_expr = LR_expr[lig_rec,]
  534. LR_expr = LR_expr[,-1]
  535. # max lig_expr across all interactions for each ligand-receptor pair
  536. max_LR_expr[[dataset]] = apply(LR_expr,1,max)
  537. }
  538. max_LR_expr$LR = rownames(max_LR_expr)
  539. max_LR_expr_pred$LR = rownames(max_LR_expr_pred)
  540. max_LR_expr_1 = melt(max_LR_expr,id.vars =c("LR"))
  541. colnames(max_LR_expr_1)[3] = 'measured'
  542. max_LR_expr_pred_1 = melt(max_LR_expr_pred,id.vars =c("LR"))
  543. colnames(max_LR_expr_pred_1)[3] = 'imputed'
  544. max_LR_expr_all = max_LR_expr_1
  545. max_LR_expr_all$imputed = max_LR_expr_pred_1$imputed
  546. ggplot(max_LR_expr_all,aes(x=measured,y=imputed))+geom_point(color='red',shape=1)+ggtitle('max_LR_expr_all')
  547. ggsave(paste0(root_dir,'/measured_imputed/imputed-measured.png'),height=10,width=10)
  548. ##--- filter out the lowly expressed ligand-receptor pairs in both measured and imputed expression ---
  549. cutoff = 0.05
  550. max_LR_expr_all_select = max_LR_expr_all[max_LR_expr_all$imputed>cutoff & !is.na(max_LR_expr_all$measured)&max_LR_expr_all$measured>cutoff,]
  551. ##--- scatter plot ---
  552. all_scores = NULL
  553. for (dataset in data_name){
  554. results_folder = paste0(data_dir,'/',dataset,'/')
  555. print(dataset)
  556. if (!dir.exists(results_folder)){
  557. dir.create(results_folder)}
  558. LR_comb_select = max_LR_expr_all_select$LR[max_LR_expr_all_select$variable %in% dataset ]
  559. if (length(LR_comb_select)!=0){
  560. assay = 'SCTpred'
  561. cluster_column = "imputed.cell_identity"
  562. Mer = readRDS(paste0(results_folder,save.id,"_Seurat_object_SpatialSignalingScore",spatial_network_name, "_assay_",assay,LRname,".rds"))
  563. spatial_all_scores<-Mer@graphs[[spatial_network_name]]$SpatialSignalingScore[[cluster_column]]
  564. spatial_all_scores_pred = spatial_all_scores[spatial_all_scores$LR_comb %in% LR_comb_select,c('LR_comb',"LR_cell_comb","ScaledSpatialSignalingScore")]
  565. assay = 'SCT'
  566. cluster_column = "cell_identity"
  567. Mer = readRDS(paste0(results_folder,save.id,"_Seurat_object_SpatialSignalingScore",spatial_network_name, "_assay_",assay,LRname,".rds"))
  568. spatial_all_scores<-Mer@graphs[[spatial_network_name]]$SpatialSignalingScore[[cluster_column]]
  569. spatial_all_scores = spatial_all_scores[spatial_all_scores$LR_comb %in% LR_comb_select,c('LR_comb',"LR_cell_comb","ScaledSpatialSignalingScore")]
  570. colnames(spatial_all_scores)[3] = c("ScaledSpatialSignalingScore_measured")
  571. spatial_all_scores$LRCC = paste0(spatial_all_scores$LR_comb,"---",spatial_all_scores$LR_cell_comb)
  572. spatial_all_scores_pred$LRCC = paste0(spatial_all_scores_pred$LR_comb,"---",spatial_all_scores_pred$LR_cell_comb)
  573. lrcc.common = intersect(spatial_all_scores$LRCC,spatial_all_scores_pred$LRCC )
  574. spatial_all_scores = spatial_all_scores[spatial_all_scores$LRCC %in%lrcc.common,]
  575. spatial_all_scores_pred = spatial_all_scores_pred[spatial_all_scores_pred$LRCC %in%lrcc.common,]
  576. spatial_all_scores$ScaledSpatialSignalingScore_imputed = spatial_all_scores_pred$ScaledSpatialSignalingScore[match(spatial_all_scores_pred$LRCC,spatial_all_scores$LRCC)]
  577. spatial_all_scores$dataset = dataset
  578. all_scores = rbind(all_scores,spatial_all_scores)
  579. }
  580. }
  581. saveRDS(all_scores,paste0(root_dir,"measured_imputed/ScaledSpatialSignalingScore_measured_vs_imputed_common_LR_0.05.rds"))
  582. all_scores<-readRDS(paste0(root_dir,"measured_imputed/ScaledSpatialSignalingScore_measured_vs_imputed_common_LR_0.05.rds"))
  583. hist(all_scores$ScaledSpatialSignalingScore_measured,breaks=100)
  584. cutoff = 0.0015
  585. all_scores_subset = all_scores[all_scores$ScaledSpatialSignalingScore_measured>cutoff & all_scores$ScaledSpatialSignalingScore_imputed>cutoff,]
  586. ggplot(data = all_scores_subset,aes(x=log2(ScaledSpatialSignalingScore_imputed),
  587. y=log2(ScaledSpatialSignalingScore_measured)))+geom_point(aes(color=dataset))+
  588. geom_abline(slope=1,intercept = 0)+theme_bw()+
  589. theme(title=element_text(size=20),axis.title= element_text(size=20),legend.text= element_text(size=20),axis.text = element_text(size=15) )
  590. ggsave(paste0(root_dir,"measured_imputed/log2_ScaledSpatialSignalingScore_measured_vs_imputed_color_data_cutoff_",cutoff,".png"),width = 15,height=7,units = 'in')
  591. cor(log2(all_scores_subset$ScaledSpatialSignalingScore_measured),log2(all_scores_subset$ScaledSpatialSignalingScore_imputed))

Spatialsignalingscore_main.R at commit 0008b95, no license · at the source

Overview

Authors: Li Lin1, Tzuen Yih Saw2, Nigel Chou2, Jie Lin Jolene Goh2, Jing Eugene Kwa2, Wan Kee Chock2, Vipul Singhal2,3, Zheng Li2, Mike J. Huang2, Huck Hui Ng2,4,5,6,7,8, Chiea Chuen Khor2,9,10, Hwee Lee Kuan1,5,11,12,13, Kok Hao Chen2, Shyam Prabhakar2,14, Jinyue Liu2
14 affiliations
  1. Bioinformatics Institute (BII), Agency for Science, Technology and Research (A*STAR),Singapore, Republic of Singapore
  2. Genome Institute of Singapore (GIS), Agency for Science Technology and Research (A*STAR),Singapore, Republic of Singapore
  3. Terray Therapeutics Inc., Monrovia, CA USA
  4. Lee Kong Chian School of Medicine, Nanyang Technological University,Singapore, Republic of Singapore
  5. School of Biological Sciences, Nanyang Technological University,Singapore, Republic of Singapore
  6. Department of Biochemistry, Yong Loo Lin School of Medicine, National University of Singapore,Singapore, Republic of Singapore
  7. Department of Biological Sciences, National University of Singapore,Singapore, Republic of Singapore
  8. School of Medicine, Nazarbayev University,Astana, Republic of Kazakhstan
  9. Singapore Eye Research Institute (SERI),Singapore, Republic of Singapore
  10. SingHealth and Duke-NUS Ophthalmology & Visual Sciences Academic Clinical Programme (EYE ACP),Singapore, Republic of Singapore
  11. School of Computing, National University of Singapore,Singapore, Republic of Singapore
  12. International Research Laboratory on Artificial Intelligence, Institute for Infocomm Research, Agency for Science, Technology and Research (A*STAR),Singapore, Republic of Singapore
  13. Centre for Frontier AI Research (CFAR), Agency for Science, Technology and Research (A*STAR),Singapore, Republic of Singapore
  14. National Cancer Centre Singapore, 30 Hospital Boulevard,Singapore, Republic of Singapore
Journal: Nature communications, volume 17, issue 1, article 7522
Dates: received 3 June 2025; accepted 7 May 2026; published online 13 June 2026
Type: Research article · Language: English
License: CC BY-NC-ND
Identifiers: DOI 10.1038/s41467-026-74320-5 · PMID 42288509 · PMCID PMC13408761 · OpenAlex W7164641945
Open access: gold, a free copy (OpenAlex)
Status: code verified (how the code is found and verified)
Categories: genetics / omics (modality), human (organism), autism (population), developmental (subfield)
Methods: Statistics, Smoothing, state filtering, decompositions, Connectivity, Machine learning
Keywords: Development of the nervous system, Computational biology and bioinformatics
MeSH: Autism Spectrum Disorder*, Brain*, Mosaicism*, Cerebral Cortex, Female, Humans, Male, Neurodevelopment, Neurons, Organoids, Single-Cell Analysis, Spatial Transcriptomics (* major topic)
Topic: Autism Spectrum Disorder Research (Cognitive Neuroscience, Neuroscience), according to OpenAlex
Funding: Funding was provided by Singapore Ministry of Health’s National Medical Research Council Open Fund – Young Individual Research Grant Project No. MOH-000239-00 (J.L.), Single-Cell In Situ Spatial Omics at subcellular Resolution (SCISSOR) IAF-PP-H18/01/a0/020 (K.H.C., H.K.L., S.P.), National Medical Research Council of Singapore OFIRG20nov-0056 (K.H.C.), National Research Foundation Singapore NRF-CRP25-10 2020-0001(K.H.C., J.L.), and Agency for Science, Technology and Research Career Development Award 202D800031 (J.L.)
Citations: cited by 1 paper (Europe PMC); 70 references in the paper

Abstract

The abstract is not reproduced here: the paper's license (CC BY-NC-ND) does not allow it. Read it in the paper, at the publisher or on Europe PMC.

Repositories

Its files are read in the Code ↔ Paper reader above, with 10 matches between paragraphs and lines of code.

Zenodo 19229995

License: CC-BY-4.0
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Size: 1 file
Software Heritage: not checked
Found in: “code availability”
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: data.table (2 files), Matplotlib (2 files), NumPy (2 files), OpenCV (2 files), pandas (2 files), Pillow (2 files), scikit-image (2 files), ggplot2 (1 file), h5py (1 file), patchwork (1 file), pheatmap (1 file), reshape2 (1 file), reticulate (1 file), SciPy (1 file), Seurat (1 file), tifffile (1 file)
Availability: 1 check, the latest on 27 September 2026: the link answers (HTTP 200)
  • 27 September 2026: the link answers (HTTP 200)
10 files
At the source:

jinyueliu0/spatial-signaling-score

License: none: the authors keep all their rights
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Commit: 0008b95ed8775f1a50b48eb3051416de5e190318, 5 September 2023
Languages: R (7), Python (2)
Size: 13 files, 9 scripts
Software Heritage: not archived
Found in: the Zenodo archive record
Holds: README
Not found: license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: data.table (2 files), Matplotlib (2 files), NumPy (2 files), OpenCV (2 files), pandas (2 files), Pillow (2 files), scikit-image (2 files), ggplot2 (1 file), h5py (1 file), patchwork (1 file), pheatmap (1 file), reshape2 (1 file), reticulate (1 file), SciPy (1 file), Seurat (1 file), tifffile (1 file)
Availability: 1 check, the latest on 27 September 2026: the link answers
  • 27 September 2026: the link answers
10 files

Code availability statement

The paper has a code availability statement. Its license (CC BY-NC-ND) does not allow reproducing it here; in short, from what the harvester recognized in it:

  • it points to the authors' code: Zenodo 19229995

Read it in the paper: doi.org/10.1038/s41467-026-74320-5.

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 2 repositories of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 18 scripts, each with its path and the digest of its content;
  • 10 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

Datasets cited

Code and data availability statement

The paper has a code and data availability statement. Its license (CC BY-NC-ND) does not allow reproducing it here; in short, from what the harvester recognized in it:

Read it in the paper: doi.org/10.1038/s41467-026-74320-5.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 1, 27 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 15 authors, 2 keywords, 12 MeSH terms, 1 funder, 70 references.

Cite

This paper

Lin, L., Saw, T. Y., Chou, N., Goh, J. L. J., Kwa, J. E., Chock, W. K., Singhal, V., Li, Z., Huang, M. J., Ng, H. H., Khor, C. C., Kuan, H. L., Chen, K. H., Prabhakar, S., & Liu, J. (2026). Spatial architecture of autism pathogenesis reveals mosaic structural disarray during early development. Nature communications, 17(1), 7522. https://doi.org/10.1038/s41467-026-74320-5

BibTeX

@article{lin2026spatial,
author = {Lin, Li and Saw, Tzuen Yih and Chou, Nigel and Goh, Jie Lin Jolene and Kwa, Jing Eugene and Chock, Wan Kee and Singhal, Vipul and Li, Zheng and Huang, Mike J. and Ng, Huck Hui and Khor, Chiea Chuen and Kuan, Hwee Lee and Chen, Kok Hao and Prabhakar, Shyam and Liu, Jinyue},
title = {{Spatial architecture of autism pathogenesis reveals mosaic structural disarray during early development}},
journal = {Nature communications},
year = {2026},
month = jun,
volume = {17},
number = {1},
pages = {7522},
publisher = {Nature Portfolio},
issn = {2041-1723},
doi = {10.1038/s41467-026-74320-5},
url = {https://doi.org/10.1038/s41467-026-74320-5},
pmid = {42288509},
pmcid = {PMC13408761}
}

RIS

TY - JOUR
AU - Lin, Li
AU - Saw, Tzuen Yih
AU - Chou, Nigel
AU - Goh, Jie Lin Jolene
AU - Kwa, Jing Eugene
AU - Chock, Wan Kee
AU - Singhal, Vipul
AU - Li, Zheng
AU - Huang, Mike J.
AU - Ng, Huck Hui
AU - Khor, Chiea Chuen
AU - Kuan, Hwee Lee
AU - Chen, Kok Hao
AU - Prabhakar, Shyam
AU - Liu, Jinyue
TI - Spatial architecture of autism pathogenesis reveals mosaic structural disarray during early development
T2 - Nature communications
J2 - Nat Commun
PY - 2026
DA - 2026/06/13
VL - 17
IS - 1
SP - 7522
SN - 2041-1723
PB - Nature Portfolio
DO - 10.1038/s41467-026-74320-5
UR - https://doi.org/10.1038/s41467-026-74320-5
LA - en
ER -

CSL-JSON

{
"id": "10.1038/s41467-026-74320-5",
"type": "article-journal",
"title": "Spatial architecture of autism pathogenesis reveals mosaic structural disarray during early development",
"container-title": "Nature communications",
"author": [
{
"family": "Lin",
"given": "Li"
},
{
"family": "Saw",
"given": "Tzuen Yih"
},
{
"family": "Chou",
"given": "Nigel"
},
{
"family": "Goh",
"given": "Jie Lin Jolene"
},
{
"family": "Kwa",
"given": "Jing Eugene"
},
{
"family": "Chock",
"given": "Wan Kee"
},
{
"family": "Singhal",
"given": "Vipul"
},
{
"family": "Li",
"given": "Zheng"
},
{
"family": "Huang",
"given": "Mike J."
},
{
"family": "Ng",
"given": "Huck Hui"
},
{
"family": "Khor",
"given": "Chiea Chuen"
},
{
"family": "Kuan",
"given": "Hwee Lee"
},
{
"family": "Chen",
"given": "Kok Hao"
},
{
"family": "Prabhakar",
"given": "Shyam"
},
{
"family": "Liu",
"given": "Jinyue"
}
],
"container-title-short": "Nat Commun",
"volume": "17",
"issue": "1",
"page": "7522",
"DOI": "10.1038/s41467-026-74320-5",
"PMID": "42288509",
"PMCID": "PMC13408761",
"ISSN": "2041-1723",
"publisher": "Nature Portfolio",
"URL": "https://doi.org/10.1038/s41467-026-74320-5",
"language": "en",
"issued": {
"date-parts": [
[
2026,
6,
13
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.1038/s41588-024-01664-3 [code]
BANKSY unifies cell typing and tissue domain segmentation for scalable spatial omics data analysis.
Journal: Nature genetics
In common: reticulate, Seurat, OpenCV, 9 other tools, genetics / omics, 4 references, 3 authors
[2] doi:10.1016/j.isci.2026.114674 [code]
Single-cell transcriptomics revealed molecular vulnerability in a human midbrain-like organoid model of Parkinson's disease.
Journal: iScience
In common: reticulate, pheatmap, Seurat, 9 other tools, genetics / omics, 6 references, author Jinyue Liu
[3] doi:10.1038/s41586-025-10047-5 [code]
Developmental convergence and divergence in human stem cell models of autism.
Journal: Nature
In common: reticulate, pheatmap, Seurat, 6 other tools, autism, genetics / omics, 10 references
[4] doi:10.1016/j.xcrm.2026.102766 [code]
A longitudinal single-cell and spatial multiomic atlas of pediatric high-grade glioma.
Journal: Cell reports. Medicine
In common: tifffile, pheatmap, Seurat, 12 other tools, genetics / omics, 6 references
[5] doi:10.1038/s41586-025-09010-1 [code]
Spatial transcriptomics reveals human cortical layer and area specification.
Journal: Nature
In common: reticulate, tifffile, Seurat, 11 other tools, genetics / omics, 5 references
[6] doi:10.1038/s41467-025-61316-w [code]
Early developmental origins of cortical disorders modeled in human neural stem cells.
Journal: Nature communications
In common: Seurat, patchwork, h5py, 7 other tools, genetics / omics, 9 references
[7] doi:10.1016/j.stem.2023.09.003 [code]
Tissue morphology influences the temporal program of human brain organoid development.
Journal: Cell stem cell
In common: reticulate, pheatmap, Seurat, 7 other tools, developmental, genetics / omics, 9 references
[8] doi:10.1038/s41598-023-36638-8 [code]
Reference-based cell type matching of in situ image-based spatial transcriptomics data on primary visual cortex of mouse brain.
Journal: Scientific reports
In common: reticulate, tifffile, pheatmap, 10 other tools, genetics / omics, 5 references
[9] doi:10.1126/sciadv.adn9998 [code]
Multiple parallel cell lineages in the developing mammalian cerebral cortex.
Journal: Science advances
In common: pheatmap, Seurat, patchwork, 7 other tools, genetics / omics, 9 references
[10] doi:10.1038/s41586-023-06473-y [code]
Single-cell brain organoid screening identifies developmental defects in autism.
Journal: Nature
In common: reticulate, Seurat, patchwork, 1 other tool, autism, developmental, genetics / omics, 10 references

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Add the badge to the code's README

OSCR: the badge of this paper

If you are an author or a maintainer of this paper's code, you can add this badge. It says what OSCR knows of the paper (its code, its validated tracing map) and links the code to this page. Paste one of these snippets under the README's title. Keep the two marks around it, so that the badge can be replaced in place and is never added twice. OSCR changes nothing in your repository.

Markdown
<!-- oscr-badge:start -->
[![OSCR](https://openscicode.org/badge/doi/10.1038/s41467-026-74320-5.svg)](https://openscicode.org/badge/doi/10.1038/s41467-026-74320-5)
<!-- oscr-badge:end -->
reStructuredText
.. oscr-badge:start

.. image:: https://openscicode.org/badge/doi/10.1038/s41467-026-74320-5.svg
   :target: https://openscicode.org/badge/doi/10.1038/s41467-026-74320-5
   :alt: OSCR

.. oscr-badge:end
HTML
<!-- oscr-badge:start -->
<a href="https://openscicode.org/badge/doi/10.1038/s41467-026-74320-5"><img src="https://openscicode.org/badge/doi/10.1038/s41467-026-74320-5.svg" alt="OSCR"></a>
<!-- oscr-badge:end -->

On GitHub, open the README, choose Edit (the pencil), paste the snippet under the title, then "Commit changes".

If you choose to, you can have the badge kept up to date for you, with oscr badge --write from the command line or with the GitHub Action in your repository's workflows. Every other form and option (a card, AsciiDoc, LaTeX, shields.io) is on the badge page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: code errors and mismatches between the code and the paper about this paper and its code, from readers and its authors, beside the paper and its tracing map.

Report a mismatch between the code and the paper · Report a code error (signed in)

Reproductions: reports from readers who ran the authors' code and did not get the paper's result, what they ran, with which environment, commit and data.

Report a reproduction failure (signed in)

Versions of its code: the releases of its code tied to a version of this paper (the preprint, the accepted manuscript, the version of record…), each with the tracing map versioned with it.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.