OSCR

Scalable discovery of spatial multicellular patterns via neighborhood-to-sequence transformation.

Code ↔ Paper

1 match 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.

The 1 match
  1. [1] § Methods › Spatial annotation of hepatic cell types and vascular structures in the MERFISH Liver Atlas ↔ code/simu_utils.R, lines 302–329 · score 0.54 · cell populations, spatial transcriptomic, inferred, gene, tissue

Paper

Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

R · 677 lines · 21 KB · no license · 1 match

  1. # Author: Zheng Li
  2. # Date: 2021-05-19
  3. # Purpose:
  4. # This script includes all functions to conduct the simulation study for BASS
  5. suppressPackageStartupMessages({
  6. library(BASS)
  7. library(Giotto)
  8. library(BayesSpace)
  9. library(Seurat)
  10. library(SC3)
  11. library(GapClust)
  12. library(mclust)
  13. library(tidyverse)
  14. library(scater)
  15. library(gtools)
  16. library(splatter)
  17. library(reticulate)
  18. library(CVXR)
  19. })
  20. #' Concatenate two strings
  21. "%&%" <- function(x, y) paste0(x, y)
  22. #' Cluster cells with Seurat
  23. seu_cluster <- function(sim_dat, C, resolutions = seq(0.1, 4, by = 0.1))
  24. {
  25. cnts <- do.call(cbind, sim_dat[[1]])
  26. colnames(cnts) <- "Cell" %&% 1:ncol(cnts)
  27. seu <- CreateSeuratObject(counts = cnts, min.cells = 1, min.features = 1)
  28. seu <- NormalizeData(seu, verbose = F)
  29. seu <- ScaleData(seu, features = rownames(seu), verbose = F)
  30. seu <- RunPCA(seu, features = rownames(seu), verbose = F)
  31. seu <- FindNeighbors(seu, dims = 1:20, verbose = F)
  32. seu <- FindClusters(seu, resolution = resolutions, verbose = F)
  33. kest <- sapply("RNA_snn_res." %&% resolutions, function(res){
  34. length(unique(seu[[res, drop = T]]))
  35. })
  36. out_res <- names(which.min(abs(kest - C)))
  37. c_est <- as.numeric(as.character(seu[[out_res, drop = T]])) + 1
  38. # evaluation
  39. ctrue <- unlist(sim_dat[[2]])
  40. ari <- eval_ARI(c_est, ctrue)
  41. F1 <- eval_F1(c_est, ctrue)
  42. MCC <- eval_MCC(c_est, ctrue)
  43. C_est <- length(unique(c_est))
  44. clust_props <- calc_clust_prop(c_est, ctrue)
  45. list(metric = c(ari, F1, MCC), C_est = C_est, clust_props = clust_props)
  46. }
  47. #' Cluster cells with SC3
  48. sc3_cluster <- function(sim_dat, C, seed = 0)
  49. {
  50. set.seed(seed)
  51. cnts <- do.call(cbind, sim_dat[[1]])
  52. x <- scater::normalizeCounts(cnts, log = TRUE)
  53. sce <- SingleCellExperiment(assays = list(counts = cnts, logcounts = x))
  54. rowData(sce)$feature_symbol <- rownames(sce)
  55. sce <- tryCatch({
  56. sc3(sce, ks = C, n_cores = 1)},
  57. error = function(e){
  58. print(e)
  59. return("error")}
  60. )
  61. if(is.character(sce)){
  62. out <- list(metric = rep("error", 9), C_est = "error",
  63. clust_props = "error")
  64. } else{
  65. if(ncol(x) > 5000) sce <- sc3_run_svm(sce, ks = C)
  66. c_est <- colData(sce)[, "sc3_" %&% C %&% "_clusters"]
  67. ctrue <- unlist(sim_dat[[2]])
  68. ari <- eval_ARI(c_est, ctrue)
  69. F1 <- eval_F1(c_est, ctrue)
  70. MCC <- eval_MCC(c_est, ctrue)
  71. C_est <- length(unique(c_est))
  72. clust_props <- calc_clust_prop(c_est, ctrue)
  73. out <- list(metric = c(ari, F1, MCC), C_est = C_est,
  74. clust_props = clust_props)
  75. }
  76. return(out)
  77. }
  78. #' Cluster cells with FICT
  79. #' FICT input files:
  80. #' 1.expression, NxJ
  81. #' 2.coordinates,
  82. fict_cluster <- function(sim_dat, xy, C, case, rep)
  83. {
  84. # The following environmental variables need to be set
  85. # to run FICT successfully
  86. PYTHONPATH <- paste(
  87. "/net/mulan/home/zlisph/BASS_pjt/9_FICT/FICT-SAMPLE/FICT/",
  88. "/net/mulan/home/zlisph/BASS_pjt/9_FICT/FICT-SAMPLE/GECT/", sep = ":")
  89. Sys.setenv(PYTHONPATH = PYTHONPATH)
  90. Sys.setenv(MPLBACKEND = 'Agg')
  91. fict <- "~/softwares/miniconda3/bin/fict"
  92. tmp_fder <- "~/BASS_pjt/2_simu/fict_tmp/case" %&% case %&% "/rep" %&% rep
  93. if(!file.exists(tmp_fder)) dir.create(tmp_fder, recursive = T)
  94. # prepare input
  95. # 1.coordinates
  96. write.table(xy, file = tmp_fder %&% "/simu.coordinates",
  97. col.names = F, quote = F)
  98. # 2.expression
  99. cnts <- do.call(cbind, sim_dat[[1]])
  100. ge <- scater::normalizeCounts(cnts, log = TRUE)
  101. ge <- t(ge) # ncell x ngene
  102. write.table(ge, file = tmp_fder %&% "/simu.expression",
  103. col.names = F, quote = F)
  104. # run FICT
  105. # Note:
  106. # by default hidden = 20, size of denoise auto-encoder
  107. cmd <- paste(fict, "-p", tmp_fder %&% "/simu", "-o",
  108. tmp_fder %&% "/out/", "--n_type", C)
  109. system(cmd, ignore.stdout = T, ignore.stderr = T)
  110. # evaluate
  111. # occasionally have error: numpy.linalg.LinAlgError: Internal Error.
  112. c_est <- tryCatch({
  113. read.table(tmp_fder %&% "/out/cluster_result.csv")
  114. }, error = function(e) e)
  115. if(!is.data.frame(c_est)){
  116. out <- list(metric = rep("error", 9), C_est = "error",
  117. clust_props = "error")
  118. } else{
  119. c_est <- c_est$V1+1
  120. ctrue <- unlist(sim_dat[[2]])
  121. ari <- eval_ARI(c_est, ctrue)
  122. F1 <- eval_F1(c_est, ctrue)
  123. MCC <- eval_MCC(c_est, ctrue)
  124. C_est <- length(unique(c_est))
  125. clust_props <- calc_clust_prop(c_est, ctrue)
  126. out <- list(metric = c(ari, F1, MCC), C_est = C_est,
  127. clust_props = clust_props)
  128. }
  129. # remove tmp files
  130. unlink(tmp_fder, recursive = T)
  131. return(out)
  132. }
  133. #' Match spatial domain labels and cell type labels
  134. #' in the estimated proportion matrix (pi_est) with
  135. #' labels in the true proportion matrix
  136. match_pi <- function(pi_est, pi_true, z_est, z_true)
  137. {
  138. C <- nrow(pi_true)
  139. R <- ncol(pi_true)
  140. # 1. Find spatial domain label correspondence
  141. perms_R <- permutations(n = R, r = R)
  142. accur <- rep(NA, nrow(perms_R))
  143. for(i in 1:nrow(perms_R))
  144. {
  145. perm <- perms_R[i, ]
  146. z_true_perm <- case_when(
  147. z_true == 1 ~ perm[1],
  148. z_true == 2 ~ perm[2],
  149. z_true == 3 ~ perm[3],
  150. z_true == 4 ~ perm[4])
  151. accur[i] <- mean(z_est == z_true_perm)
  152. }
  153. perm_final_R <- perms_R[which.max(accur), ]
  154. # 2. Match spatial domain label in pi_est
  155. pi_est_match <- pi_est[, perm_final_R]
  156. # 3. Match cell type label
  157. perms_C <- permutations(n = C, r = C)
  158. sse <- rep(NA, nrow(perms_C))
  159. for(i in 1:nrow(perms_C))
  160. {
  161. perm <- perms_C[i, ]
  162. sse[i] <- sum((pi_est_match[perm, ] - pi_true)^2)
  163. }
  164. perm_final_C <- perms_C[which.min(sse), ]
  165. pi_est_match <- pi_est_match[perm_final_C, ]
  166. out <- list(
  167. pi = pi_est_match,
  168. perm_K = perm_final_R,
  169. perm_C = perm_final_C)
  170. }
  171. #' Map spatial domain label to cell types in that domain
  172. #' 1 -> (1, 2, 3), 2 -> (2, 3, 4)
  173. #' 3 -> (3, 4, 1), 4 -> (4, 1, 2)
  174. map_z2c <- function(z)
  175. {
  176. case_when(
  177. z == 1 ~ c(1, 2, 3),
  178. z == 2 ~ c(2, 3, 4),
  179. z == 3 ~ c(3, 4, 1),
  180. z == 4 ~ c(4, 1, 2)
  181. )
  182. }
  183. #' Produce the confusion matrix
  184. #' One difficulty for constructing the confusion matrix is that
  185. #' the labeling from the clustering and truth may not match.
  186. #' We get around this difficulty by identifying the confusion matrix
  187. #' such that the number of true positives (sum of diagonal values)
  188. #' is maximized.
  189. #' Note the number of clusters in est_labels needs to be smaller than
  190. #' or equal to the number of clusters in true_labels
  191. confusion <- function(est_labels, true_labels)
  192. {
  193. C <- length(unique(true_labels))
  194. est_labels <- factor(est_labels, 1:C)
  195. A <- matrix(table(est_labels, true_labels), C, C)
  196. P <- Variable(C, C, boolean = T) # row permutation matrix
  197. Y <- Variable(C, C)
  198. problem <- Problem(Maximize(matrix_trace(Y)), list(Y == P %*% A,
  199. sum_entries(P, axis = 1) == 1, sum_entries(P, axis = 2) == 1))
  200. result <- solve(problem)
  201. P <- result$getValue(P)
  202. confusion_mtx <- P %*% A
  203. }
  204. #' Evaluate the F1-score
  205. #' Refer to paper Chicco and Jurman, BMC Genomics, 2020
  206. eval_F1 <- function(est_labels, true_labels)
  207. {
  208. C <- length(unique(true_labels))
  209. confusion_mtx <- suppressMessages(confusion(est_labels, true_labels))
  210. TP <- diag(confusion_mtx)
  211. FP <- apply(confusion_mtx, 1, sum) - diag(confusion_mtx)
  212. FN <- apply(confusion_mtx, 2, sum) - diag(confusion_mtx)
  213. F1 <- 2 * TP / (2 * TP + FP + FN)
  214. c(all_F1 = mean(F1), major_F1 = mean(F1[1:4]), rare_F1 = mean(F1[5:C]))
  215. }
  216. #' Evaluate Matthew correlation coefficient (MCC) score
  217. #' Refer to paper Chicco and Jurman, BMC Genomics, 2020
  218. eval_MCC <- function(est_labels, true_labels)
  219. {
  220. C <- length(unique(true_labels))
  221. confusion_mtx <- suppressMessages(confusion(est_labels, true_labels))
  222. TP <- diag(confusion_mtx)
  223. FP <- apply(confusion_mtx, 1, sum) - diag(confusion_mtx)
  224. FN <- apply(confusion_mtx, 2, sum) - diag(confusion_mtx)
  225. TN <- sum(confusion_mtx) - TP - FP - FN
  226. MCC <- (TP * TN - FP * FN) /
  227. sqrt((TP + FP) * (TP + FN) * (TN + FP) * (TN + FN))
  228. MCC[is.na(MCC)] <- 0
  229. c(all_MCC = mean(MCC), major_MCC = mean(MCC[1:4]), rare_MCC = mean(MCC[5:C]))
  230. }
  231. #' Evaluate the adjusted Random Index(ARI)
  232. eval_ARI <- function(est_labels, true_labels)
  233. {
  234. major_cells <- true_labels %in% 1:4
  235. rare_cells <- !major_cells
  236. all_ari <- adjustedRandIndex(est_labels, true_labels)
  237. major_ari <- adjustedRandIndex(
  238. est_labels[major_cells], true_labels[major_cells])
  239. rare_ari <- adjustedRandIndex(
  240. est_labels[rare_cells], true_labels[rare_cells])
  241. c(all_ari = all_ari, major_ari = major_ari, rare_ari = rare_ari)
  242. }
  243. #' Reorder the labeling of cell type clusters/spatial domains to
  244. #' cell types/spatial domains 1, 2, 3, 4 and then order the remaining
  245. #' redundant clusters/domains based on their cluster/domain size from
  246. #' large to small. Finally, calculate the proportion. Note this quantity
  247. #' is specifically used for evaluation in the case of a mis-specified
  248. #' number of cell types/spatial domains.
  249. calc_clust_prop <- function(est_labels, true_labels)
  250. {
  251. C <- length(unique(true_labels))
  252. C_est <- length(unique(est_labels))
  253. C_min <- min(C, C_est)
  254. C_max <- max(C, C_est)
  255. mtx <- matrix(table(est_labels, true_labels), C_est, C)
  256. P <- Variable(C_est, C_est, boolean = T) # row permutation matrix
  257. Y <- Variable(C_est, C)
  258. problem <- suppressMessages(Problem(
  259. Maximize(matrix_trace(Y[1:C_min, 1:C_min])),
  260. list(Y == P %*% mtx, sum_entries(P, axis = 1) == 1,
  261. sum_entries(P, axis = 2) == 1)))
  262. result <- suppressMessages(solve(problem))
  263. P <- result$getValue(P)
  264. mtx <- P %*% mtx
  265. order_idx <- order(apply(mtx, 1, sum)[-c(1:C_min)], decreasing = T)
  266. mtx <- mtx[c(1:C_min, order_idx+C_min), , drop = F]
  267. props <- apply(mtx, 1, sum) / sum(mtx)
  268. names(props) <- 1:C_est
  269. paste(props, collapse = ",")
  270. }
  271. #' Generate simulated spatial transcriptomic data with splatter package
  272. #'
  273. #' Spatial domain labels are based on STARmap (20180417_BZ5_control) data
  274. #' and annotated based on the marker genes. Spatial domain labels for
  275. #' section 1 to section 9 are generated based on the annotated labels.
  276. #'
  277. #' @param starmap STARmap data for inferring simulation parameters and for
  278. #' providing realistic cell coordinates and spatial domains.
  279. #' @param scenario Simulation scenario (refer to the manuscript for details)
  280. #' @param rare_dist Rare cell types either randomly ditributed across the entire
  281. #' tissue section or located in certain spatial domians.
  282. #' @param C Number of cell types that consist of 4 major cell types and (C-4)
  283. #' rare cell types. Rare cell types together consist of 30% of the total cell
  284. #' population and randomly distribued across the entire tissue region.
  285. #' Each rare cell type consist of 30%/(C-4) of the total cell population.
  286. #' @param J Number of genes.
  287. #' @param I Number of randomly selected genes among the J genes to remain in
  288. #' the final dataset.
  289. #' @param L Number of tissue sections.
  290. #' @param batch_facLoc Batch factor location (refer to the splatter package).
  291. #' Zero if there is no batch effect.
  292. #' @param de_prop Probability that a gene will be selected to be differentially
  293. #' expressed for each cell type (refer to splatter package).
  294. #' @param de_facLoc DE factor location (refer to splatter package).
  295. #' @param de_facScale DE factor scale (refer to splatter package).
  296. #' @param sim_seed Random seed.
  297. #' @param debug Output DE genes for each cell type.
  298. simu <- function(
  299. starmap,
  300. scenario,
  301. rare_dist = c("random", "spatial"),
  302. C,
  303. J,
  304. I = NULL,
  305. L,
  306. batch_facLoc,
  307. de_prop,
  308. de_facLoc,
  309. de_facScale,
  310. sim_seed,
  311. debug = FALSE
  312. )
  313. {
  314. cnts <- starmap$cnts
  315. info <- starmap$info
  316. N <- nrow(info)
  317. init_params <- splatEstimate(cnts[, which(info$c == "eL2/3")])
  318. # reproduce randomness in cell type assignment and
  319. # count data selection.
  320. set.seed(sim_seed)
  321. # 1.simulate count data
  322. noBatch <- ifelse(batch_facLoc == 0, TRUE, FALSE)
  323. group_prob <- if(C == 4){
  324. rep(0.25, 4)
  325. } else if(C > 4){
  326. c(rep(0.7 / 4, 4), rep(1 / (C - 4), C - 4) * 0.3)
  327. }
  328. params <- setParams(
  329. init_params,
  330. batchCells = rep(3 * N, L), # 3N here represents a large number such that
  331. # we have sufficient cells of each type to be
  332. # allocated to the spatial transcriptomics data
  333. batch.rmEffect = noBatch,
  334. batch.facLoc = batch_facLoc,
  335. nGenes = J,
  336. group.prob = group_prob,
  337. out.prob = 0,
  338. de.prob = de_prop,
  339. de.facLoc = de_facLoc,
  340. de.facScale = de_facScale,
  341. seed = sim_seed)
  342. sim_groups <- splatSimulate(
  343. params = params,
  344. method = "groups",
  345. verbose = FALSE)
  346. if(!is.null(I)){
  347. # down-sample J genes to I genes
  348. keep_idx <- sort(sample(1:J, I, replace = F))
  349. sim_groups <- sim_groups[keep_idx, ]
  350. } else{
  351. I <- J
  352. }
  353. # remove cells having no expressed genes
  354. idx_zerosize <- apply(counts(sim_groups), MARGIN = 2, sum) == 0
  355. sim_groups <- sim_groups[, !idx_zerosize]
  356. # 2.parse proportion of cells types in each spatial domain
  357. if(scenario == 2){
  358. prop <- c(0.8, 0.1, 0.1)
  359. } else if(scenario == 3){
  360. prop <- c(0.5, 0.25, 0.25)
  361. } else if(scenario == 4){
  362. prop <- rep(1, 3) / 3
  363. }
  364. c_simu <- list()
  365. sim_cnt <- list()
  366. for(l in 1:L)
  367. {
  368. # 3.set spatial domain labels
  369. if(l == 1){
  370. ztrue <- info$z
  371. } else{
  372. ztrue <- info[["slice" %&% (l-1)]]
  373. }
  374. # 4.generate cell types
  375. c_simu[[l]] <- rep(NA, length(ztrue))
  376. if(scenario == 1){
  377. c_simu[[l]] <- ztrue
  378. } else if(scenario %in% c(2, 3, 4)){
  379. for(z in unique(info$z))
  380. {
  381. zi_idx <- ztrue == z
  382. c_simu[[l]][zi_idx] <- sample(map_z2c(z), sum(zi_idx), prob = prop,
  383. replace = T)
  384. }
  385. } else if(scenario == 5){ # more challenging scenario with rare cell types
  386. # assign rare cell types
  387. if(rare_dist[1] == "spatial"){
  388. rare_idx <- rep(NA, length(ztrue))
  389. nrare_each <- round(0.3 / (C - 4) * length(ztrue))
  390. for(c in 5:C)
  391. {
  392. repeat{
  393. zi_idx <- sample(unique(info$z), 1) == ztrue
  394. zi_noAlloc_idx <- zi_idx & is.na(rare_idx)
  395. if(sum(zi_noAlloc_idx) >= nrare_each) break
  396. }
  397. ci_idx <- sample(which(zi_noAlloc_idx), nrare_each, replace = F)
  398. c_simu[[l]][ci_idx] <- c
  399. rare_idx[ci_idx] <- TRUE
  400. }
  401. rare_idx[is.na(rare_idx)] <- FALSE
  402. } else if(rare_dist[1] == "random"){
  403. rare_idx <- sample(c(TRUE, FALSE), length(ztrue), prob = c(0.3, 0.7),
  404. replace = T)
  405. c_simu[[l]][rare_idx] <- sample(5:C, sum(rare_idx), replace = T)
  406. }
  407. major_idx <- !rare_idx
  408. # assign major cell types using proportion of
  409. # cell types in scenario 3
  410. for(z in unique(info$z))
  411. {
  412. zi_idx <- ztrue == z
  413. zi_major_idx <- zi_idx & major_idx
  414. c_simu[[l]][zi_major_idx] <- sample(map_z2c(z), sum(zi_major_idx),
  415. prob = c(0.5, 0.25, 0.25), replace = T)
  416. }
  417. }
  418. # 5.assign count data
  419. groups <- as.data.frame(colData(sim_groups)) %>%
  420. filter(Batch == "Batch" %&% l)
  421. sim_cnt[[l]] <- array(NA, c(I, N))
  422. for(c in 1:C)
  423. {
  424. c_size <- sum(c_simu[[l]] == c)
  425. c_cells <- groups$Cell[grepl("Group" %&% c %&% "$", groups$Group)]
  426. cells_select <- sample(as.character(c_cells), c_size, replace = F)
  427. sim_cnt[[l]][, c_simu[[l]] == c] <-
  428. as.matrix(counts(sim_groups)[, cells_select])
  429. }
  430. colnames(sim_cnt[[l]]) <- "Cell" %&% 1:N
  431. rownames(sim_cnt[[l]]) <- "Gene" %&% 1:I
  432. }
  433. # return DE genes for each group
  434. if(debug){
  435. de_genes <- list()
  436. for(c in 1:C)
  437. {
  438. de_genes[[c]] <- rownames(rowData(sim_groups))[
  439. rowData(sim_groups)[, "DEFacGroup" %&% c] != 1]
  440. }
  441. return(list(sim_cnt, c_simu, sim_seed, de_genes))
  442. }
  443. return(list(sim_cnt, c_simu, sim_seed))
  444. }
  445. #' Run BASS algorithm
  446. run_BASS <- function(sim_dat, xy, beta_method, beta, C, R,
  447. init_method)
  448. {
  449. L <- length(sim_dat[[1]])
  450. xys <- lapply(1:L, function(x) xy)
  451. sim_cnt <- sim_dat[[1]]
  452. for(l in 1:L)
  453. {
  454. colnames(sim_cnt[[l]]) <- rownames(xys[[l]])
  455. }
  456. # run algorithms
  457. BASS <- createBASSObject(sim_cnt, xys, C = C, R = R,
  458. init_method = init_method, beta_method = "SW",
  459. beta = beta, tol = 1e-4, burnin = 2000, nsample = 2000)
  460. BASS <- BASS.preprocess(BASS)
  461. BASS <- BASS.run(BASS)
  462. BASS <- BASS.postprocess(BASS)
  463. ctrue <- unlist(sim_dat[[2]])
  464. ztrue <- unlist(info[, 4:(L+3)])
  465. pi_true <- table(ctrue, ztrue)
  466. pi_true <- pi_true %*% diag(1 / apply(pi_true, 2, sum))
  467. c_est <- unlist(BASS@results$c)
  468. z_est <- unlist(BASS@results$z)
  469. pi_est <- BASS@results$pi
  470. # evaluation
  471. c_ari <- eval_ARI(c_est, ctrue)
  472. F1 <- eval_F1(c_est, ctrue)
  473. MCC <- eval_MCC(c_est, ctrue)
  474. z_ari <- adjustedRandIndex(ztrue, z_est)
  475. if(C != 4 | R != 4){ # only evaluate in the main simulation
  476. pi_est <- NA
  477. mse_pi <- NA
  478. } else{
  479. pi_est <- match_pi(pi_est, pi_true, z_est, ztrue)$pi
  480. mse_pi <- sqrt(sum((pi_est - pi_true)^2))
  481. }
  482. C_est <- length(unique(c_est))
  483. R_est <- length(unique(z_est))
  484. c_clust_prop <- calc_clust_prop(c_est, ctrue)
  485. z_clust_prop <- calc_clust_prop(z_est, ztrue)
  486. output <- list(
  487. c_ari = c_ari,
  488. c_F1 = F1,
  489. c_MCC = MCC,
  490. C_est = C_est,
  491. c_clust_prop = c_clust_prop,
  492. z_ari = z_ari,
  493. R_est = R_est,
  494. z_clust_prop = z_clust_prop,
  495. pi_est = pi_est,
  496. mse_pi = mse_pi,
  497. beta = BASS@results$beta)
  498. return(output)
  499. }
  500. #' Run HMRF algorithm
  501. run_HMRF <- function(sim_dat, xy, ztrue, R, case, rep,
  502. usePCs = F, SEgenes = NULL, dosearchSEgenes = T)
  503. {
  504. sim_cnt <- sim_dat[[1]][[1]]
  505. J <- nrow(sim_cnt)
  506. # 0.prepare
  507. my_python_path <- "/net/mulan/home/zlisph//softwares/miniconda3/bin/python"
  508. results_folder <- "/net/mulan/home/zlisph/BASS_pjt/2_simu/HMRF_tmp/case" %&%
  509. case %&% "/rep" %&% rep
  510. if(!file.exists(results_folder)) dir.create(results_folder, recursive = T)
  511. instrs <- createGiottoInstructions(python_path = my_python_path)
  512. # 1.run HMRF
  513. starmap <- createGiottoObject(
  514. raw_exprs = as.data.frame(sim_cnt),
  515. spatial_locs = xy,
  516. instructions = instrs)
  517. starmap <- filterGiotto(
  518. gobject = starmap,
  519. expression_threshold = 0.5,
  520. gene_det_in_min_cells = 20,
  521. min_det_genes_per_cell = 0)
  522. starmap <- normalizeGiotto(starmap)
  523. starmap <- addStatistics(starmap)
  524. starmap <- createSpatialNetwork(starmap, minimum_k = 2)
  525. # select SE genes using
  526. if(dosearchSEgenes){
  527. genes <- binSpect(starmap, bin_method = 'kmeans')$genes
  528. genes <- if(length(genes) < 100) genes else genes[1:100]
  529. } else{
  530. genes <- rownames((starmap@norm_scaled_expr))
  531. }
  532. if(usePCs){
  533. starmap <- Giotto::runPCA(
  534. gobject = starmap,
  535. genes_to_use = genes,
  536. ncp = 20)
  537. betas <- c(0, 1, 21)
  538. output_folder <- results_folder %&% "/result_k" %&% R %&% "_pca"
  539. HMRF_out <- doHMRF(
  540. gobject = starmap,
  541. dim_reduction_to_use = "pca",
  542. dimensions_to_use = 1:20,
  543. k = R,
  544. betas = betas,
  545. output_folder = output_folder,
  546. overwrite_output = T)
  547. } else{
  548. betas <- c(0, 2, 26)
  549. output_folder <- results_folder %&% "/result_k" %&% R
  550. HMRF_out <- doHMRF(
  551. gobject = starmap,
  552. expression_values = "scaled",
  553. spatial_genes = genes,
  554. k = R,
  555. betas = betas,
  556. output_folder = output_folder,
  557. overwrite_output = T)
  558. }
  559. # 2.evaluate results
  560. res_dir <- output_folder %&% "/result.spatial.zscore/k_" %&% R
  561. allbetas <- seq(betas[1], by = betas[2], length = betas[3])
  562. ari <- list()
  563. R_est <- list()
  564. z_clust_prop <- list()
  565. for(beta in allbetas)
  566. {
  567. beta <- beta %&% ".0"
  568. probs <- tryCatch(
  569. read.table(res_dir %&% "/ftest.beta." %&% beta %&% ".unnormprob.txt",
  570. row.names = 1),
  571. error = function(e) "error",
  572. warning = function(w) "warning")
  573. if(!is.data.frame(probs)){
  574. out <- list(ari = rep("error", length(allbetas)),
  575. R_est = rep("error", length(allbetas)),
  576. z_clust_prop = rep("error", length(allbetas)))
  577. return(out)
  578. } else{
  579. z_est <- apply(probs, MARGIN = 1, which.max)
  580. ari[[beta]] <- adjustedRandIndex(ztrue, z_est)
  581. R_est[[beta]] <- length(unique(z_est))
  582. z_clust_prop[[beta]] <- calc_clust_prop(z_est, ztrue)
  583. }
  584. }
  585. unlink(results_folder, recursive = T)
  586. out <- list(ari = ari, R_est = R_est, z_clust_prop = z_clust_prop)
  587. return(out)
  588. }
  589. #' Run BayesSpace
  590. run_BayesSpace <- function(sim_dat, xy, ztrue, R, seed = 0)
  591. {
  592. set.seed(seed)
  593. sim_cnt <- sim_dat[[1]][[1]]
  594. colnames(xy) <- c("row", "col")
  595. info <- data.frame(xy)
  596. sce <- SingleCellExperiment(assays = list(counts = sim_cnt), colData = info)
  597. sce <- spatialPreprocess(sce, n.PCs = 15, n.HVGs = nrow(sce), log.normalize = T)
  598. sce <- spatialCluster(sce, q = R, d = 15,
  599. init.method = "mclust", model = "t",
  600. nrep = 10000, burn.in = 1000)
  601. z_est <- colData(sce)$spatial.cluster
  602. ari <- adjustedRandIndex(ztrue, z_est)
  603. R_est <- length(unique(z_est))
  604. z_clust_prop <- calc_clust_prop(z_est, ztrue)
  605. out <- list(ari = ari, R_est = R_est, z_clust_prop = z_clust_prop)
  606. return(out)
  607. }
  608. #' run_SpGCN
  609. run_SpaGCN <- function(sim_dat, xy, ztrue, R, p = 0.5)
  610. {
  611. sim_cnt <- sim_dat[[1]][[1]]
  612. xy <- data.frame(xy)
  613. z_est <- run_SpaGCN_py(t(sim_cnt), xy, R, p)$refined_pred
  614. ari <- adjustedRandIndex(ztrue, z_est)
  615. R_est <- length(unique(z_est))
  616. z_clust_prop <- calc_clust_prop(z_est, ztrue)
  617. out <- list(ari = ari, R_est = R_est, z_clust_prop = z_clust_prop)
  618. return(out)
  619. }

simu_utils.R at commit 81dfe73, no license · at the source

Overview

Authors: Fangyuan Zhao1,2,3,4, Sheng Wang1,2, Zhikang Wang3,4, Yan Cui3,4, Yi Zhao1,2, Zhiyuan Yuan3,4
  1. Institute of Computing Technology, Chinese Academy of Sciences, Beijing, China
  2. University of Chinese Academy of Sciences, Beijing, China
  3. Institute of Science and Technology for Brain-Inspired Intelligence; MOE Key Laboratory of Computational Neuroscience and Brain-Inspired Intelligence; MOE Frontiers Center for Brain Science, Fudan University, Shanghai, China
  4. Center for Medical Research and Innovation, Shanghai Pudong Hospital, Fudan University Pudong Medical Center, Fudan University, Shanghai, China
Journal: Communications biology, volume 9, issue 1, article 725
Dates: received 15 September 2025; accepted 13 March 2026; published online 1 April 2026
Type: Research article · Language: English
License: CC BY-NC-ND
Identifiers: DOI 10.1038/s42003-026-09923-1 · PMID 41922721 · PMCID PMC13216563 · OpenAlex W7147007029
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: human (organism), Alzheimer's / dementia (population)
Methods: Connectivity, Machine learning
Keywords: Data mining, Data integration
MeSH: Computational Biology*, Data Mining*, Algorithms, Animals, Humans (* major topic)
Topic: Single-cell and spatial transcriptomics (Molecular Biology, Biochemistry, Genetics and Molecular Biology), according to OpenAlex
Funding: Shanghai Science and Technology Development Foundation (23YF1403000)
Citations: cited by 1 paper (Europe PMC); 101 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 1 match between paragraphs and lines of code.

zhengli09/BASS-Analysis

License: none: the authors keep all their rights
State: the link answers, verified on 28 September 2026
Evidence: files inventoried
Commit: 81dfe7353093823eed68f403d9c4033031b73de4, 2 April 2023
Languages: R (22), JavaScript (19), Python (1)
Size: 321 files, 42 scripts
Software Heritage: not archived
Found in: “Data availability”
Holds: README, documentation, 7 notebooks
Not found: license file, CITATION.cff, environment file, tests, continuous integration
Tools: tidyverse (6 files), cowplot (3 files), Seurat (3 files), anndata (1 file), ggplot2 (1 file), NumPy (1 file), pandas (1 file), PyTorch (1 file), reticulate (1 file), Scanpy (1 file)
Availability: 1 check, the latest on 28 September 2026: the link answers
  • 28 September 2026: the link answers
43 files

zhaofangyuan98/FDPMining

License: none: the authors keep all their rights
State: the link answers, verified on 28 September 2026
Evidence: files inventoried
Commit: e2cccc564d3acc82c0aeffeb45b8886122dafddd, 7 March 2026
Languages: Python (7), Jupyter (2)
Size: 18 files, 9 scripts
Software Heritage: not archived
Found in: “Code availability”
Holds: README, environment (requirements.txt), 2 notebooks
Not found: license file, CITATION.cff, tests, continuous integration, documentation
Tools: NumPy (7 files), Scanpy (6 files), Matplotlib (4 files), pandas (4 files), scikit-learn (3 files), anndata (1 file)
Availability: 1 check, the latest on 28 September 2026: the link answers
  • 28 September 2026: the link answers
10 files

Zenodo 18902032

License: CC-BY-4.0
State: the link answers, verified on 28 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: NumPy (7 files), Scanpy (6 files), Matplotlib (4 files), pandas (4 files), scikit-learn (3 files), anndata (1 file)
Availability: 1 check, the latest on 28 September 2026: the link answers (HTTP 200)
  • 28 September 2026: the link answers (HTTP 200)
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:

Read it in the paper: doi.org/10.1038/s42003-026-09923-1.

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:

  • 3 repositories of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 60 scripts, each with its path and the digest of its content;
  • 1 match 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/s42003-026-09923-1.

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, 28 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 6 authors, 2 keywords, 5 MeSH terms, 1 funder, 91 references.

Cite

This paper

Zhao, F., Wang, S., Wang, Z., Cui, Y., Zhao, Y., & Yuan, Z. (2026). Scalable discovery of spatial multicellular patterns via neighborhood-to-sequence transformation. Communications biology, 9(1), 725. https://doi.org/10.1038/s42003-026-09923-1

BibTeX

@article{zhao2026scalable,
author = {Zhao, Fangyuan and Wang, Sheng and Wang, Zhikang and Cui, Yan and Zhao, Yi and Yuan, Zhiyuan},
title = {{Scalable discovery of spatial multicellular patterns via neighborhood-to-sequence transformation}},
journal = {Communications biology},
year = {2026},
month = apr,
volume = {9},
number = {1},
pages = {725},
publisher = {Nature Publishing Group},
issn = {2399-3642},
doi = {10.1038/s42003-026-09923-1},
url = {https://doi.org/10.1038/s42003-026-09923-1},
pmid = {41922721},
pmcid = {PMC13216563}
}

RIS

TY - JOUR
AU - Zhao, Fangyuan
AU - Wang, Sheng
AU - Wang, Zhikang
AU - Cui, Yan
AU - Zhao, Yi
AU - Yuan, Zhiyuan
TI - Scalable discovery of spatial multicellular patterns via neighborhood-to-sequence transformation
T2 - Communications biology
J2 - Commun Biol
PY - 2026
DA - 2026/04/01
VL - 9
IS - 1
SP - 725
SN - 2399-3642
PB - Nature Publishing Group
DO - 10.1038/s42003-026-09923-1
UR - https://doi.org/10.1038/s42003-026-09923-1
LA - en
ER -

CSL-JSON

{
"id": "10.1038/s42003-026-09923-1",
"type": "article-journal",
"title": "Scalable discovery of spatial multicellular patterns via neighborhood-to-sequence transformation",
"container-title": "Communications biology",
"author": [
{
"family": "Zhao",
"given": "Fangyuan"
},
{
"family": "Wang",
"given": "Sheng"
},
{
"family": "Wang",
"given": "Zhikang"
},
{
"family": "Cui",
"given": "Yan"
},
{
"family": "Zhao",
"given": "Yi"
},
{
"family": "Yuan",
"given": "Zhiyuan"
}
],
"container-title-short": "Commun Biol",
"volume": "9",
"issue": "1",
"page": "725",
"DOI": "10.1038/s42003-026-09923-1",
"PMID": "41922721",
"PMCID": "PMC13216563",
"ISSN": "2399-3642",
"publisher": "Nature Publishing Group",
"URL": "https://doi.org/10.1038/s42003-026-09923-1",
"language": "en",
"issued": {
"date-parts": [
[
2026,
4,
1
]
]
}
}

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/s41592-026-03194-8 [code]
Beyond benchmarking: an expert-guided consensus approach to spatially aware clustering.
Journal: Nature methods
In common: anndata, Scanpy, Seurat, 8 other tools, 8 references
[2] doi:10.21203/rs.3.rs-9676637/v1 [code]
A Comprehensive Benchmarking of Spatial Deconvolution and Domain Detection Methods across Diverse Tissues and Spatial Transcriptomic Technologies
Journal: Research Square (preprint)
In common: reticulate, anndata, Scanpy, 9 other tools, 5 references
[3] doi:10.1186/s13073-026-01704-z [code]
Gene expression profiling enables refined parcellation of cortical layers in the heterogeneous human cerebral cortex.
Journal: Genome medicine
In common: anndata, Scanpy, Seurat, 8 other tools, 4 references
[4] doi:10.1038/s41467-026-71759-4 [code]
CellNiche represents cellular microenvironments in atlas-scale spatial omics data with contrastive learning.
Journal: Nature communications
In common: anndata, Scanpy, PyTorch, 4 other tools, 7 references
[5] doi:10.1038/s41514-026-00391-9 [code]
Region-specific transcriptional signatures of brain aging in the absence of neuropathology at the single-cell level.
Journal: npj aging
In common: anndata, Scanpy, Seurat, 8 other tools, 4 references
[6] doi:10.1038/s41467-026-71803-3 [code]
Charting the transition from in vitro gliogenesis to the in vivo maturation of human glial progenitor cells transplanted into the hypomyelinated mouse brain.
Journal: Nature communications
In common: reticulate, anndata, Scanpy, 9 other tools, 2 references
[7] doi:10.1016/j.celrep.2026.117073 [code]
Single-cell epigenomics uncovers heterochromatin instability and transcription factor dysfunction during mouse brain aging.
Journal: Cell reports
In common: reticulate, anndata, Scanpy, 7 other tools, 2 references
[8] doi:10.1038/s41467-026-68596-w [code]
Spatial cartography of human thymus enables the geopositioning of lineage transcription factors in rare mimetic thymic epithelial cells.
Journal: Nature communications
In common: anndata, Scanpy, Seurat, 8 other tools, 2 references
[9] doi:10.1038/s41586-026-10214-2 [code]
Multidimensional profiling of heterogeneity in supratentorial ependymomas.
Journal: Nature
In common: reticulate, anndata, Scanpy, 8 other tools, 1 reference
[10] doi:10.1002/imt2.70163 [code]
Spatial multi-omics unveils sphingolipid metabolic reprogramming within the retinal pathological niche.
Journal: iMeta
In common: anndata, Scanpy, Seurat, 7 other tools, 3 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.

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: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.

Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.

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