OSCR

Comparative transcriptomics reveals differences in cortical cell type organization between metatherian and eutherian mammals.

Code ↔ Paper

14 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.

The 14 matches
  1. [1] § Methods › Analysis of single-nucleus transcriptomics data ↔ figure S1/S1B_intergenic_distance_pipeline.sh, lines 1–41 · score 0.83 · UTR annotation, nearest gene, intergenic, Samtools, stratifying, BEDtools
  2. [2] § Results › IT glutamatergic neurons have poor cross-species correspondence ↔ figure 2/2DEF_OpossumMouse_CrossSpeciesMapping.Rmd, lines 102–120 · score 0.79 · subclasses mapped, cross species, L5NP, L6CT, L5PT, L6IT
  3. [3] § Results › IT glutamatergic neurons have poor cross-species correspondence ↔ figure 3/3FGHIJ_OpossumMouse_PCGradients.Rmd, lines 644–752 · score 0.77 · Spearman correlations, PC space, mouse subclass, mouse cells, Opossum cells, opossum subclass
  4. [4] § Results › IT glutamatergic neurons have poor cross-species correspondence ↔ figure 1/1GHIJK_OpossumMouse_ClassSubclassProportions.Rmd, lines 40–102 · score 0.75 · L5NP, L6CT, L5PT, L6IT, GABAergic, CGE
  5. [5] § Methods › Analysis of single-nucleus transcriptomics data ↔ figure 2/2LMN_OpossumMouse_WGCNAModules.Rmd, lines 361–373 · score 0.70 · HubGeneNetworkPlot, preserved modules, hub genes, WGCNA, mouse, opossum
  6. [6] § Results › Gene expression continua reveal conserved and divergent features of IT neurons ↔ figure 2/2DEF_OpossumMouse_CrossSpeciesMapping.Rmd, lines 102–120 · score 0.66 · cortical layers, L6CT, L5PT, cross species, predicts, neurons
  7. [7] § Methods › Analysis of spatial transcriptomics data ↔ figure 3/3FGHIJ_OpossumMouse_PCGradients.Rmd, lines 156–200 · score 0.66 · PC space, delta, noc, L5IT, Stereo seq, PCHA
  8. [8] § Methods › Analysis of single-nucleus transcriptomics data ↔ figure 3/3FGHIJ_OpossumMouse_PCGradients.Rmd, lines 156–200 · score 0.63 · convex hull, PC spaces, PCHA, vertex, mice, subclass
  9. [9] § Methods › Analysis of single-nucleus transcriptomics data ↔ preprocessing/0_Opossum_ExtendGenomeAnnotation.Rmd, lines 70–122 · score 0.62 · gene biotype, FASTA, strand, shift, genome, GTF
  10. [10] § Results › A spatial gradient along the opossum IT_A–C transcriptomic axis ↔ figure 3/3FGHIJ_OpossumMouse_PCGradients.Rmd, lines 644–752 · score 0.55 · Spearman correlations, PC space, fitted, Ratio, distance, position
  11. [11] § Results › A spatial gradient along the opossum IT_A–C transcriptomic axis ↔ figure 3/3FGHIJ_OpossumMouse_PCGradients.Rmd, lines 238–338 · score 0.55 · triangle vertices, L5IT, Stereo seq, gradients, distance, PC
  12. [12] § Results › A single-nucleus transcriptomic atlas of the primary visual cortex in the gray short-tailed opossum ↔ figure 2/2DEF_OpossumMouse_CrossSpeciesMapping.Rmd, lines 122–135 · score 0.53 · Cross species, GABAergic, interneurons, Lamp5, Pvalb, Sst
  13. [13] § Results › A single-nucleus transcriptomic atlas of the primary visual cortex in the gray short-tailed opossum ↔ figure 1/1GHIJK_OpossumMouse_ClassSubclassProportions.Rmd, lines 40–102 · score 0.53 · GABAergic, MGE, subtypes, CGE, Lamp5, Pvalb
  14. [14] § Methods › Analysis of single-nucleus transcriptomics data ↔ figure 2/2DEF_OpossumMouse_CrossSpeciesMapping.Rmd, lines 137–150 · score 0.51 · Confusion matrices, cross species, rows, predicted, mouse, subclasses

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 Markdown · 1,108 lines · 39 KB · MIT · 5 matches

  1. ---
  2. title: "Figure 3F-J: IT Subclass PC Gradients in Opossum and Mouse"
  3. output:
  4. ---
  5. ```{r setup, include=FALSE}
  6. # This sets the project root based on the repo structure.
  7. # If you move this file, you may to set the root manually to find config.R
  8. knitr::opts_knit$set(root.dir = dirname(dirname(rstudioapi::getSourceEditorContext()$path)))
  9. knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE)
  10. ```
  11. ```{r libraries}
  12. # Conda environment with required packages: numpy pandas scipy scikit-learn networkx py-pcha
  13. Sys.setenv(RETICULATE_PYTHON = "C:/Users/TLab/anaconda3/envs/pcha/python.exe")
  14. library(Seurat)
  15. library(ggplot2)
  16. library(dplyr)
  17. library(reticulate)
  18. library(comparatome)
  19. source("config.R")
  20. use_condaenv("pcha")
  21. ```
  22. ```{r load_integrated_data}
  23. # Load integrated objects containing both snRNA-seq and Stereo-seq data
  24. obj.i.mouse <- readRDS(paste0(dir.list$spatial$seurat$processed, "mouse_stereoseq_integrated.rds"))
  25. obj.i.opossum <- readRDS(paste0(dir.list$spatial$seurat$processed, "opossum_stereoseq_integrated.rds"))
  26. cat(sprintf("Mouse integrated: %d cells\n", ncol(obj.i.mouse)))
  27. cat(sprintf("Opossum integrated: %d cells\n", ncol(obj.i.opossum)))
  28. ```
  29. ```{r, filter_IT_subtypes_mouse}
  30. # Mouse IT cells
  31. IT.sn.names.mouse <- colnames(obj.i.mouse)[obj.i.mouse$subclass %in% c("L2/3", "L4", "L5IT")]
  32. IT.sp.names.mouse <- colnames(obj.i.mouse)[obj.i.mouse$subclass_nn %in% c("L2/3", "L4", "L5IT")]
  33. IT.cells.mouse <- unique(c(IT.sn.names.mouse, IT.sp.names.mouse))
  34. # Subset without images
  35. obj.i.mouse.noimg <- obj.i.mouse
  36. obj.i.mouse.noimg@images <- list()
  37. obj.i.mouse.IT <- obj.i.mouse.noimg[, IT.cells.mouse]
  38. # Restore images with only spatial cells present in subset
  39. spatial_cells_in_subset <- intersect(IT.sp.names.mouse, colnames(obj.i.mouse.IT))
  40. if(length(spatial_cells_in_subset) > 0) {
  41. for(img_name in c("COL")) {
  42. obj.i.mouse.IT@images[[img_name]] <- subset(obj.i.mouse@images[[img_name]],
  43. cells = spatial_cells_in_subset)
  44. }
  45. }
  46. # Opossum IT cells
  47. IT.sn.names.opossum <- colnames(obj.i.opossum)[obj.i.opossum$subclass %in% c("IT_A", "IT_B", "IT_C")]
  48. IT.sp.names.opossum <- colnames(obj.i.opossum)[obj.i.opossum$subclass_nn %in% c("IT_A", "IT_B", "IT_C")]
  49. IT.cells.opossum <- unique(c(IT.sn.names.opossum, IT.sp.names.opossum))
  50. obj.i.opossum.noimg <- obj.i.opossum
  51. obj.i.opossum.noimg@images <- list()
  52. obj.i.opossum.IT <- obj.i.opossum.noimg[, IT.cells.opossum]
  53. spatial_cells_in_subset <- intersect(IT.sp.names.opossum, colnames(obj.i.opossum.IT))
  54. if(length(spatial_cells_in_subset) > 0) {
  55. for(img_name in c("COL")) {
  56. obj.i.opossum.IT@images[[img_name]] <- subset(obj.i.opossum@images[[img_name]],
  57. cells = spatial_cells_in_subset)
  58. }
  59. }
  60. ```
  61. ```{r}
  62. cat(sprintf("Mouse IT neurons: %d cells (%d snRNA, %d spatial)\n",
  63. ncol(obj.i.mouse.IT), length(IT.sn.names.mouse), length(IT.sp.names.mouse)))
  64. obj.i.mouse.IT$method[is.na(obj.i.mouse.IT$method)] <- "Stereo-seq"
  65. cat(sprintf("Opossum IT neurons: %d cells (%d snRNA, %d spatial)\n",
  66. ncol(obj.i.opossum.IT), length(IT.sn.names.opossum), length(IT.sp.names.opossum)))
  67. obj.i.opossum.IT$method[is.na(obj.i.opossum.IT$method)] <- "Stereo-seq"
  68. ```
  69. ```{r run_pca}
  70. # Run PCA - PC2 and PC3 typically capture IT continuum better than PC1 (technical variation)
  71. obj.i.mouse.IT$method[is.na(obj.i.mouse.IT$method)] <- "Stereo-seq"
  72. obj.i.mouse.IT <- RunPCA(obj.i.mouse.IT, npcs = 30, verbose = FALSE)
  73. obj.i.opossum.IT <- RunPCA(obj.i.opossum.IT, npcs = 30, verbose = FALSE)
  74. # Get all colors
  75. colors <- get_colors()
  76. # Function to plot PCA with snRNA gray and spatial colored by subclass
  77. plot_pca_by_method <- function(obj, colors, title, dims = c(2, 3)) {
  78. pca_coords <- Embeddings(obj, "pca")[, dims]
  79. df <- data.frame(
  80. PC_x = pca_coords[, 1],
  81. PC_y = pca_coords[, 2],
  82. method = obj$method,
  83. subclass = ifelse(obj$method == "Stereo-seq",
  84. as.character(obj$subclass_nn),
  85. "snRNA-seq")
  86. )
  87. # Order so spatial cells plot on top
  88. df <- df[order(df$method == "Stereo-seq"), ]
  89. # Build color vector: gray for snRNA, subclass colors for spatial
  90. spatial_subclasses <- unique(df$subclass[df$subclass != "snRNA-seq"])
  91. color_vec <- c("snRNA-seq" = "gray70", unlist(colors[spatial_subclasses]))
  92. p <- ggplot(df, aes(x = PC_x, y = PC_y, color = subclass)) +
  93. geom_point(size = 1.5, alpha = 1) +
  94. scale_color_manual(values = color_vec) +
  95. labs(x = paste0("PC", dims[1]), y = paste0("PC", dims[2]), title = title) +
  96. coord_equal() +
  97. theme_classic() +
  98. guides(color = guide_legend(override.aes = list(size = 3)))
  99. print(p)
  100. return(p)
  101. }
  102. # Mouse plots
  103. p.m <- plot_pca_by_method(obj.i.mouse.IT, colors, "Mouse IT - PC2 vs PC3")
  104. SavePNGandSVG(p.m, dir.list$fig3$plots, "3F_Mouse-SpatialITSubclass-PCAEmbeddings")
  105. # Opossum plots
  106. p.o <- plot_pca_by_method(obj.i.opossum.IT, colors, "Opossum IT - PC2 vs PC3")
  107. SavePNGandSVG(p.o, dir.list$fig3$plots, "3F_Opossum-SpatialITSubclass-PCAEmbeddings")
  108. ```
  109. ```{r export_pc_coordinates}
  110. # Export PC coordinates for Python RGB calculation
  111. df.mouse <- data.frame(
  112. cell = colnames(obj.i.mouse.IT),
  113. method = obj.i.mouse.IT$method,
  114. subclass_nn = ifelse(obj.i.mouse.IT$method == "Stereo-seq",
  115. obj.i.mouse.IT$subclass_nn,
  116. obj.i.mouse.IT$subclass),
  117. X = obj.i.mouse.IT@reductions$[email hidden][, 2],
  118. Y = obj.i.mouse.IT@reductions$[email hidden][, 3]
  119. )
  120. write.csv(df.mouse, paste0(dir.list$fig3$data, "mouse_integrated_PC_coords.csv"), row.names = FALSE)
  121. df.opossum <- data.frame(
  122. cell = colnames(obj.i.opossum.IT),
  123. method = obj.i.opossum.IT$method,
  124. subclass_nn = ifelse(obj.i.opossum.IT$method == "Stereo-seq",
  125. obj.i.opossum.IT$subclass_nn,
  126. obj.i.opossum.IT$subclass),
  127. X = obj.i.opossum.IT@reductions$[email hidden][, 2],
  128. Y = obj.i.opossum.IT@reductions$[email hidden][, 3]
  129. )
  130. write.csv(df.opossum, paste0(dir.list$fig3$data, "opossum_integrated_PC_coords.csv"), row.names = FALSE)
  131. cat("Exported PC coordinates\n")
  132. ```
  133. ```{python find_triangle_vertices_mouse}
  134. # Find convex hull vertices in PC space using PCHA
  135. # Identifies extreme points defining the IT subtype continuum
  136. import pandas as pd
  137. import numpy as np
  138. from py_pcha import PCHA
  139. from collections import Counter
  140. # Load and filter for spatial cells (cleaner spatial distribution)
  141. df = pd.read_csv(r['dir.list']['fig3']['data'] + "mouse_integrated_PC_coords.csv")
  142. df_spatial = df.loc[df["method"] == "Stereo-seq"]
  143. X = np.array(df_spatial[["X", "Y"]])
  144. # Find 3 vertices (triangle corners)
  145. XC, S, C, SSE, varexpl = PCHA(X.T, noc=3, delta=0.1)
  146. # Identify which vertex corresponds to which subclass
  147. # For each vertex, find nearest cells and determine majority subclass
  148. vertex_subclasses = []
  149. for i in range(3):
  150. vertex = XC[:, i].reshape(1, -1)
  151. # Calculate distances to all spatial cells
  152. coords = np.array(df_spatial[["X", "Y"]])
  153. distances = np.linalg.norm(coords - vertex, axis=1)
  154. # Get 50 nearest cells
  155. nearest_idx = np.argsort(distances)[:50]
  156. # Get subclass labels for these cells from the CSV
  157. nearest_subclasses = df_spatial.iloc[nearest_idx]['subclass_nn'].values
  158. subclass_counts = Counter(nearest_subclasses)
  159. vertex_subclasses.append(subclass_counts.most_common(1)[0][0])
  160. print(f"Vertex identification: {vertex_subclasses}")
  161. # Create mapping to desired order: A (L2/3), B (L4), C (L5IT)
  162. vertex_map = {}
  163. for i, subclass in enumerate(vertex_subclasses):
  164. vertex_map[subclass] = i
  165. # Reorder vertices: [L2/3, L4, L5IT] -> [A, B, C]
  166. XC_mouse = XC[:, [vertex_map['L2/3'], vertex_map['L4'], vertex_map['L5IT']]]
  167. print("Mouse PC vertices (ordered A, B, C):")
  168. print(XC_mouse.T)
  169. ```
  170. ```{python find_triangle_vertices_opossum}
  171. # Find vertices for opossum
  172. df = pd.read_csv(r['dir.list']['fig3']['data'] + "opossum_integrated_PC_coords.csv")
  173. df_spatial = df.loc[df["method"] == "Stereo-seq"]
  174. X = np.array(df_spatial[["X", "Y"]])
  175. XC, S, C, SSE, varexpl = PCHA(X.T, noc=3, delta=0.1)
  176. # Identify which vertex corresponds to which subclass
  177. # For each vertex, find nearest cells and determine majority subclass
  178. vertex_subclasses = []
  179. for i in range(3):
  180. vertex = XC[:, i].reshape(1, -1)
  181. coords = np.array(df_spatial[["X", "Y"]])
  182. distances = np.linalg.norm(coords - vertex, axis=1)
  183. nearest_idx = np.argsort(distances)[:50]
  184. # Get subclass labels for these cells from the CSV
  185. nearest_subclasses = df_spatial.iloc[nearest_idx]['subclass_nn'].values
  186. subclass_counts = Counter(nearest_subclasses)
  187. vertex_subclasses.append(subclass_counts.most_common(1)[0][0])
  188. print(f"Vertex identification: {vertex_subclasses}")
  189. # Create mapping to desired order: A (IT_A), B (IT_B), C (IT_C)
  190. vertex_map = {}
  191. for i, subclass in enumerate(vertex_subclasses):
  192. vertex_map[subclass] = i
  193. # Reorder vertices: [IT_A, IT_B, IT_C] -> [A, B, C]
  194. XC_opossum = XC[:, [vertex_map['IT_A'], vertex_map['IT_B'], vertex_map['IT_C']]]
  195. print("Opossum PC vertices (ordered A, B, C):")
  196. print(XC_opossum.T)
  197. ```
  198. ```{python calculate_rgb_mouse}
  199. # Calculate RGB colors using barycentric coordinates
  200. # Color interpolates based on position within triangle
  201. import numpy as np
  202. from scipy.spatial.distance import cdist
  203. import pandas as pd
  204. from sklearn.neighbors import kneighbors_graph
  205. import networkx as nx
  206. from collections import Counter
  207. def barycentric_coords(triangle, points):
  208. """Calculate barycentric coordinates for RGB interpolation."""
  209. # Ensure shapes: triangle -> (3, 2), points -> (N, 2)
  210. tri = np.asarray(triangle, dtype=float).reshape(-1, 2)
  211. pts = np.asarray(points, dtype=float)
  212. A, B, C = tri[0], tri[1], tri[2]
  213. v0 = B - A
  214. v1 = C - A
  215. v2 = pts - A # (N, 2)
  216. d00 = np.dot(v0, v0)
  217. d01 = np.dot(v0, v1)
  218. d11 = np.dot(v1, v1)
  219. d20 = np.sum(v2 * v0, axis=1)
  220. d21 = np.sum(v2 * v1, axis=1)
  221. denom = d00 * d11 - d01 * d01
  222. v = (d11 * d20 - d01 * d21) / denom
  223. w = (d00 * d21 - d01 * d20) / denom
  224. u = 1.0 - v - w
  225. return np.column_stack([u, v, w])
  226. # Load full dataset
  227. df = pd.read_csv(r['dir.list']['fig3']['data'] + "mouse_integrated_PC_coords.csv")
  228. df_spatial = df.loc[df["method"] == "Stereo-seq"]
  229. cells = np.array(df_spatial[["X", "Y"]], dtype=float)
  230. cell_names = df_spatial["cell"].to_numpy()
  231. # Triangle vertices: shape (3, 2)
  232. vertices = np.asarray(XC_mouse.T, dtype=float)
  233. # Vertex colors: A=Cyan (L2/3), B=Yellow (L4), C=Purple (L5IT)
  234. colors = np.array([
  235. [0.31764706, 0.94117647, 0.89019608], # A: L2/3 (cyan)
  236. [1.0, 0.95294118, 0.18823529], # B: L4 (yellow)
  237. [0.36863, 0.23529, 0.6 ] # C: L5IT (purple)
  238. ], dtype=float)
  239. # Calculate RGB via barycentric interpolation
  240. bary_coords = barycentric_coords(vertices, cells)
  241. bary_coords = np.clip(bary_coords, 0.0, 1.0)
  242. cell_colors = np.clip(bary_coords @ colors, 0.0, 1.0)
  243. rgb_df = pd.DataFrame(
  244. cell_colors,
  245. columns=["R", "G", "B"],
  246. index=cell_names
  247. )
  248. # Euclidean distances to vertices
  249. euclidean_distances = cdist(cells, vertices, metric='euclidean')
  250. for i, vertex_label in enumerate(['Vertex_A', 'Vertex_B', 'Vertex_C']):
  251. rgb_df[f'Euclidean_to_{vertex_label}'] = euclidean_distances[:, i]
  252. # Geodesic distances via KNN graph
  253. n_neighbors = 5
  254. knn_graph = kneighbors_graph(
  255. cells, n_neighbors=n_neighbors,
  256. mode='distance', include_self=False
  257. )
  258. G = nx.from_scipy_sparse_array(knn_graph, edge_attribute='weight')
  259. vertex_indices = [
  260. np.argmin(np.linalg.norm(cells - vertex, axis=1))
  261. for vertex in vertices
  262. ]
  263. geodesic_distances = np.zeros((cells.shape[0], len(vertices)))
  264. for idx, vertex_idx in enumerate(vertex_indices):
  265. lengths = nx.single_source_dijkstra_path_length(G, vertex_idx)
  266. geodesic_distances[:, idx] = [
  267. lengths.get(i, np.inf) for i in range(cells.shape[0])
  268. ]
  269. for i, vertex_label in enumerate(['Vertex_A', 'Vertex_B', 'Vertex_C']):
  270. rgb_df[f'Geodesic_to_{vertex_label}'] = geodesic_distances[:, i]
  271. # Use r['dir.list'] again here
  272. rgb_df.to_csv(r['dir.list']['fig3']['data'] + "mouse_integrated_PC_colors.csv")
  273. print(
  274. f"Mouse: {len(rgb_df)} cells | RGB range [0-1]: "
  275. f"R[{rgb_df.R.min():.2f}-{rgb_df.R.max():.2f}] "
  276. f"G[{rgb_df.G.min():.2f}-{rgb_df.G.max():.2f}] "
  277. f"B[{rgb_df.B.min():.2f}-{rgb_df.B.max():.2f}]"
  278. )
  279. ```
  280. ```{python calculate_rgb_opossum}
  281. # Calculate RGB for opossum
  282. df = pd.read_csv(r['dir.list']['fig3']['data'] + "opossum_integrated_PC_coords.csv")
  283. df_spatial = df.loc[df["method"] == "Stereo-seq"]
  284. cells = np.array(df_spatial[["X", "Y"]])
  285. cell_names = df_spatial["cell"]
  286. # Triangle vertices: shape (3, 2)
  287. vertices = np.asarray(XC_opossum.T, dtype=float)
  288. # Vertex colors: A=Cyan (IT_A/L2/3), B=Yellow (IT_B/L4), C=Purple (IT_C/L5IT)
  289. colors = np.array([
  290. [0.31764706, 0.94117647, 0.89019608], # A: IT_A (cyan)
  291. [1.0, 0.95294118, 0.18823529], # B: IT_B (yellow)
  292. [0.36863, 0.23529, 0.6 ] # C: IT_C (purple)
  293. ], dtype=float)
  294. # Calculate RGB via barycentric interpolation
  295. bary_coords = barycentric_coords(vertices, cells)
  296. bary_coords = np.clip(bary_coords, 0.0, 1.0)
  297. cell_colors = np.clip(bary_coords @ colors, 0.0, 1.0)
  298. rgb_df = pd.DataFrame(
  299. cell_colors,
  300. columns=["R", "G", "B"],
  301. index=cell_names
  302. )
  303. # Euclidean distances to vertices
  304. euclidean_distances = cdist(cells, vertices, metric='euclidean')
  305. for i, vertex_label in enumerate(['Vertex_A', 'Vertex_B', 'Vertex_C']):
  306. rgb_df[f'Euclidean_to_{vertex_label}'] = euclidean_distances[:, i]
  307. # Geodesic distances via KNN graph
  308. n_neighbors = 5
  309. knn_graph = kneighbors_graph(
  310. cells, n_neighbors=n_neighbors,
  311. mode='distance', include_self=False
  312. )
  313. G = nx.from_scipy_sparse_array(knn_graph, edge_attribute='weight')
  314. vertex_indices = [
  315. np.argmin(np.linalg.norm(cells - vertex, axis=1))
  316. for vertex in vertices
  317. ]
  318. geodesic_distances = np.zeros((cells.shape[0], len(vertices)))
  319. for idx, vertex_idx in enumerate(vertex_indices):
  320. lengths = nx.single_source_dijkstra_path_length(G, vertex_idx)
  321. geodesic_distances[:, idx] = [
  322. lengths.get(i, np.inf) for i in range(cells.shape[0])
  323. ]
  324. for i, vertex_label in enumerate(['Vertex_A', 'Vertex_B', 'Vertex_C']):
  325. rgb_df[f'Geodesic_to_{vertex_label}'] = geodesic_distances[:, i]
  326. # Use r['dir.list'] again here
  327. rgb_df.to_csv(r['dir.list']['fig3']['data'] + "opossum_integrated_PC_colors.csv")
  328. print(
  329. f"Opossum: {len(rgb_df)} cells | RGB range [0-1]: "
  330. f"R[{rgb_df.R.min():.2f}-{rgb_df.R.max():.2f}] "
  331. f"G[{rgb_df.G.min():.2f}-{rgb_df.G.max():.2f}] "
  332. f"B[{rgb_df.B.min():.2f}-{rgb_df.B.max():.2f}]"
  333. )
  334. ```
  335. ```{r plot_pc_gradients, fig.width=6, fig.height=6}
  336. # RGB gradients in PC space - Figure 3G
  337. DimPlotGradient <- function(obj, rgb_csv, pc1 = "PC_2", pc2 = "PC_3", size = 2) {
  338. # Load RGB colors from CSV
  339. rgb_data <- read.csv(rgb_csv, row.names = 1)
  340. # Extract PC coordinates from the Seurat object
  341. pc_coords <- Embeddings(obj, reduction = "pca")[, c(pc1, pc2)]
  342. # Create dataframe
  343. df <- data.frame(PC1 = pc_coords[, 1], PC2 = pc_coords[, 2], cells = rownames(pc_coords))
  344. # Merge colors with PC coordinates
  345. df <- merge(df, rgb_data, by.x = "cells", by.y = "row.names", all.x = TRUE)
  346. df <- df[!is.na(df$R), ]
  347. # Ensure RGB values are within range [0,1]
  348. df$R <- pmax(0, pmin(1, df$R))
  349. df$G <- pmax(0, pmin(1, df$G))
  350. df$B <- pmax(0, pmin(1, df$B))
  351. # Convert RGB to hex color codes
  352. df$hex_color <- with(df, rgb(R, G, B, maxColorValue = 1))
  353. # Reorder points for proper layering
  354. df <- df[order(df$R + df$G + df$B, decreasing = FALSE), ]
  355. # Generate scatter plot
  356. p <- ggplot(df, aes(x = PC1, y = PC2, color = hex_color)) +
  357. geom_point(shape = 19, size = size, alpha = 1) +
  358. scale_color_identity() + # Directly use hex colors, no legend
  359. theme_minimal() +
  360. theme(axis.text = element_blank(), axis.ticks = element_blank()) +
  361. guides(color = "none") + # Remove color legend
  362. coord_equal()
  363. return(p)
  364. }
  365. # Mouse
  366. p <- DimPlotGradient(
  367. obj = obj.i.mouse.IT,
  368. rgb_csv = paste0(dir.list$fig3$data, "mouse_integrated_PC_colors.csv"),
  369. size = 3
  370. )
  371. print(p)
  372. SavePNGandSVG(p, dir.list$fig3$plots, "3G_Mouse-SpatialIT-PCGradient")
  373. # Opossum
  374. p <- DimPlotGradient(
  375. obj = obj.i.opossum.IT,
  376. rgb_csv = paste0(dir.list$fig3$data, "opossum_integrated_PC_colors.csv"),
  377. pc1 = "PC_2",
  378. pc2 = "PC_3",
  379. size = 3
  380. )
  381. print(p)
  382. SavePNGandSVG(p, dir.list$fig3$plots, "3G_Opossum-SpatialIT-PCGradient")
  383. ```
  384. ```{r plot_spatial_gradients_mouse, fig.width=8, fig.height=5}
  385. # RGB gradients in spatial coordinates - Mouse (Figure 3H - top)
  386. mouse.rgb <- paste0(dir.list$fig3$data, "mouse_integrated_PC_colors.csv")
  387. # All IT subtypes
  388. p <- PlotImageDimGradient(obj = obj.i.mouse.IT, rgb_csv = mouse.rgb,
  389. ratio = 1.5, size = 2, yticks = c(0, 500, 1000, 1500)) +
  390. scale_y_continuous(limits = c(0, 1500)) +
  391. coord_fixed(ratio = 1.5) + theme(axis.text.y = element_text())
  392. print(p)
  393. # L2/3
  394. p <- PlotImageDimGradient(obj = subset(obj.i.mouse.IT, subclass_nn == "L2/3"),
  395. rgb_csv = mouse.rgb, ratio = 1.5, yticks = c(0, 500, 1000, 1500)) +
  396. scale_y_continuous(limits = c(0, 1500)) +
  397. coord_fixed(ratio = 1.5) + ggtitle("Mouse L2/3")
  398. print(p)
  399. SavePNGandSVG(p, dir.list$fig3$plots, "3H_Mouse-SpatialL23-ColumnGradient")
  400. # L4
  401. p <- PlotImageDimGradient(obj = subset(obj.i.mouse.IT, subclass_nn == "L4"),
  402. rgb_csv = mouse.rgb, ratio = 1.5, yticks = c(0, 500, 1000, 1500)) +
  403. scale_y_continuous(limits = c(0, 1500)) +
  404. coord_fixed(ratio = 1.5) + ggtitle("Mouse L4")
  405. print(p)
  406. SavePNGandSVG(p, dir.list$fig3$plots, "3H_Mouse-SpatialL4-ColumnGradient")
  407. # L5IT
  408. p <- PlotImageDimGradient(obj = subset(obj.i.mouse.IT, subclass_nn == "L5IT"),
  409. rgb_csv = mouse.rgb, ratio = 1.5, yticks = c(0, 500, 1000, 1500)) +
  410. scale_y_continuous(limits = c(0, 1500)) +
  411. coord_fixed(ratio = 1.5) + ggtitle("Mouse L5IT")
  412. print(p)
  413. SavePNGandSVG(p, dir.list$fig3$plots, "3H_Mouse-SpatialL5IT-ColumnGradient")
  414. ```
  415. ```{r plot_spatial_gradients_opossum, fig.width=8, fig.height=5}
  416. # RGB gradients in spatial coordinates - Opossum (Figure 3H - bottom)
  417. opossum.rgb <- paste0(dir.list$fig3$data, "opossum_integrated_PC_colors.csv")
  418. # All IT subtypes
  419. p <- PlotImageDimGradient(obj = obj.i.opossum.IT, rgb_csv = opossum.rgb,
  420. ratio = 0.77 * 1.5, size = 2, yticks = c(0, 400, 800, 1200, 1600)) +
  421. scale_y_continuous(limits = c(0, 1600)) +
  422. coord_fixed(ratio = 0.77 * 1.5) + theme(axis.text.y = element_text())
  423. print(p)
  424. # IT_A
  425. p <- PlotImageDimGradient(obj = subset(obj.i.opossum.IT, subclass_nn == "IT_A"),
  426. rgb_csv = opossum.rgb, ratio = 0.77 * 1.5,
  427. yticks = c(0, 400, 800, 1200, 1600)) +
  428. scale_y_continuous(limits = c(0, 1600)) +
  429. coord_fixed(ratio = 0.77 * 1.5) + ggtitle("Opossum IT_A")
  430. print(p)
  431. SavePNGandSVG(p, dir.list$fig3$plots, "3H_Opossum_SpatialITA-ColumnGradient")
  432. # IT_B
  433. p <- PlotImageDimGradient(obj = subset(obj.i.opossum.IT, subclass_nn == "IT_B"),
  434. rgb_csv = opossum.rgb, ratio = 0.77 * 1.5,
  435. yticks = c(0, 400, 800, 1200, 1600)) +
  436. scale_y_continuous(limits = c(0, 1600)) +
  437. coord_fixed(ratio = 0.77 * 1.5) + ggtitle("Opossum IT_B")
  438. print(p)
  439. SavePNGandSVG(p, dir.list$fig3$plots, "3H_Opossum_SpatialITB-ColumnGradient")
  440. # IT_C
  441. p <- PlotImageDimGradient(obj = subset(obj.i.opossum.IT, subclass_nn == "IT_C"),
  442. rgb_csv = opossum.rgb, ratio = 0.77 * 1.5,
  443. yticks = c(0, 400, 800, 1200, 1600)) +
  444. scale_y_continuous(limits = c(0, 1600)) +
  445. coord_fixed(ratio = 0.77 * 1.5) + ggtitle("Opossum IT_C")
  446. print(p)
  447. SavePNGandSVG(p, dir.list$fig3$plots, "3H_Opossum_SpatialITC-ColumnGradient")
  448. ```
  449. ```{r, fig.width=2, fig.height=3}
  450. calculate_density_by_layer_sample <- function(obj, subclass_query, subclass_ref, scale_to_mm = 0.0005) {
  451. coords <- as.data.frame(obj@images[[1]]$centroids@coords)
  452. colnames(coords) <- c("depth", "tangential")
  453. spatial_cells <- Cells(obj@images[[1]])
  454. coords$subclass_nn <- obj$subclass_nn[spatial_cells]
  455. coords$sample <- obj$sample[spatial_cells]
  456. coords <- coords[!is.na(coords$subclass_nn), ]
  457. # Get mean depth of reference layer (across all samples)
  458. ref_depth <- mean(coords$depth[coords$subclass_nn == subclass_ref], na.rm = TRUE)
  459. # Calculate per sample
  460. results <- lapply(unique(coords$sample), function(s) {
  461. coords_s <- coords[coords$sample == s, ]
  462. coords_query <- coords_s[coords_s$subclass_nn == subclass_query, ]
  463. coords_query$position <- ifelse(coords_query$depth > ref_depth, "above", "below")
  464. width_mm <- diff(range(coords_s$tangential)) * scale_to_mm
  465. depth_above <- coords_query$depth[coords_query$position == "above"]
  466. depth_below <- coords_query$depth[coords_query$position == "below"]
  467. height_above_mm <- abs(max(depth_above) - ref_depth) * scale_to_mm
  468. height_below_mm <- abs(ref_depth - min(depth_below)) * scale_to_mm
  469. area_above_mm2 <- width_mm * height_above_mm
  470. area_below_mm2 <- width_mm * height_below_mm
  471. count_above <- sum(coords_query$position == "above")
  472. count_below <- sum(coords_query$position == "below")
  473. density_above <- count_above / area_above_mm2
  474. density_below <- count_below / area_below_mm2
  475. data.frame(
  476. sample = s,
  477. density_above = density_above,
  478. density_below = density_below,
  479. ratio_below_above = density_below / density_above
  480. )
  481. })
  482. do.call(rbind, results)
  483. }
  484. # Calculate per-sample densities
  485. density_mouse_samples <- calculate_density_by_layer_sample(obj.i.mouse.IT, "L2/3", "L4")
  486. density_mouse_samples$species <- "Mouse"
  487. density_opossum_samples <- calculate_density_by_layer_sample(obj.i.opossum.IT, "IT_A", "IT_B")
  488. density_opossum_samples$species <- "Opossum"
  489. density_samples <- rbind(density_mouse_samples, density_opossum_samples)
  490. print(density_samples)
  491. # Wilcoxon rank sum test on ratios
  492. wilcox_result <- wilcox.test(
  493. ratio_below_above ~ species,
  494. data = density_samples
  495. )
  496. cat("\nWilcoxon rank sum test (below/above ratio):\n")
  497. cat(" W =", wilcox_result$statistic, "\n")
  498. cat(" p =", signif(wilcox_result$p.value, 3), "\n")
  499. # Summarize for barplot
  500. ratio_summary <- density_samples %>%
  501. group_by(species) %>%
  502. summarize(
  503. mean_ratio = mean(ratio_below_above),
  504. se_ratio = sd(ratio_below_above) / sqrt(n()),
  505. .groups = "drop"
  506. )
  507. p_ratio <- ggplot(ratio_summary, aes(x = species, y = mean_ratio, fill = species)) +
  508. geom_bar(stat = "identity", width = 0.7) +
  509. geom_errorbar(aes(ymin = mean_ratio - se_ratio, ymax = mean_ratio + se_ratio),
  510. width = 0.2) +
  511. geom_jitter(data = density_samples, aes(y = ratio_below_above),
  512. width = 0.1, size = 2, shape = 21, fill = "black") +
  513. scale_fill_manual(values = c("Opossum" = colors$Opossum, "Mouse" = colors$Mouse)) +
  514. scale_y_continuous(expand = expansion(mult = c(0, 0.1)), limits = c(0, 0.35)) +
  515. labs(x = NULL, y = "Density ratio (below / above L4)") +
  516. theme_classic() +
  517. theme(
  518. axis.text = element_text(color = "black"),
  519. legend.position = "none"
  520. ) +
  521. annotate("text", x = 1.5, y = max(ratio_summary$mean_ratio + ratio_summary$se_ratio) * 1.15,
  522. label = sprintf("p = %s", signif(wilcox_result$p.value, 2)), size = 4)
  523. print(p_ratio)
  524. SavePNGandSVG(p_ratio, dir.list$fig3$plots, "3I_OpossumMouse-L23ITADensityAboveBelowRatio-Bar")
  525. ```
  526. ```{r}
  527. # Correlation between spatial Y position and PC vertex distances
  528. # Tests whether cells' positions along cortical depth correlate with their PC-space distances
  529. # Parameters
  530. mouse_subclass <- "L2/3"
  531. opossum_subclass <- "IT_A"
  532. vertices <- c("B", "C") # Test distances to vertices B and C
  533. # Separate regimes for mouse and opossum (top of L2/3 to middle of L4)
  534. regimes <- list(
  535. list(mouse = c(1000, 1550), opossum = c(800, 1550))
  536. )
  537. # Load distance data (already contains Euclidean and Geodesic distances)
  538. mouse.rgb <- read.csv(paste0(dir.list$fig3$data, "mouse_integrated_PC_colors.csv"),
  539. row.names = 1)
  540. opossum.rgb <- read.csv(paste0(dir.list$fig3$data, "opossum_integrated_PC_colors.csv"),
  541. row.names = 1)
  542. for (vertex_label in vertices) {
  543. vertex_col <- paste0("Euclidean_to_Vertex_", vertex_label)
  544. # Extract mouse spatial coordinates and distances
  545. mouse_cells <- colnames(obj.i.mouse.IT)[
  546. !is.na(obj.i.mouse.IT$subclass_nn) &
  547. obj.i.mouse.IT$subclass_nn == mouse_subclass
  548. ]
  549. mouse_coords <- obj.i.mouse.IT@images[[1]]$centroids@coords[
  550. obj.i.mouse.IT$subclass_nn[!is.na(obj.i.mouse.IT$subclass_nn)] == mouse_subclass,
  551. ]
  552. rownames(mouse_coords) <- mouse_cells
  553. mouse_y_positions <- mouse_coords[mouse_cells, "x"]
  554. mouse_distance <- mouse.rgb[mouse_cells, vertex_col]
  555. # Extract opossum spatial coordinates and distances
  556. opossum_cells <- colnames(obj.i.opossum.IT)[
  557. !is.na(obj.i.opossum.IT$subclass_nn) &
  558. obj.i.opossum.IT$subclass_nn == opossum_subclass
  559. ]
  560. opossum_coords <- obj.i.opossum.IT@images[[1]]$centroids@coords[
  561. obj.i.opossum.IT$subclass_nn[!is.na(obj.i.opossum.IT$subclass_nn)] == opossum_subclass,
  562. ]
  563. rownames(opossum_coords) <- opossum_cells
  564. opossum_y_positions <- opossum_coords[opossum_cells, "x"]
  565. opossum_distance <- opossum.rgb[opossum_cells, vertex_col]
  566. for (regime in regimes) {
  567. mouse_xmin <- regime$mouse[1]
  568. mouse_xmax <- regime$mouse[2]
  569. opossum_xmin <- regime$opossum[1]
  570. opossum_xmax <- regime$opossum[2]
  571. # Filter by species-specific cortical depth regimes
  572. mouse_idx <- mouse_y_positions >= mouse_xmin & mouse_y_positions < mouse_xmax
  573. opossum_idx <- opossum_y_positions >= opossum_xmin & opossum_y_positions < opossum_xmax
  574. # Normalize Y positions to [0, 1] within each species' regime
  575. mouse_y_norm <- 1 - (mouse_y_positions[mouse_idx] - mouse_xmin) / (mouse_xmax - mouse_xmin)
  576. opossum_y_norm <- 1 - (opossum_y_positions[opossum_idx] - opossum_xmin) / (opossum_xmax - opossum_xmin)
  577. # Create combined dataframe with normalized positions
  578. df_combined <- data.frame(
  579. Y_Position_Normalized = c(mouse_y_norm, opossum_y_norm),
  580. Distance = c(mouse_distance[mouse_idx], opossum_distance[opossum_idx]),
  581. Species = c(rep("Mouse", sum(mouse_idx)), rep("Opossum", sum(opossum_idx)))
  582. )
  583. mouse_regime <- df_combined[df_combined$Species == "Mouse", ]
  584. opossum_regime <- df_combined[df_combined$Species == "Opossum", ]
  585. # Calculate Spearman correlations
  586. mouse_cor <- cor.test(mouse_regime$Y_Position_Normalized, mouse_regime$Distance,
  587. method = "spearman")
  588. opossum_cor <- cor.test(opossum_regime$Y_Position_Normalized, opossum_regime$Distance,
  589. method = "spearman")
  590. plot_title <- sprintf(
  591. "Y Position vs. Distance (%s / %s, Vertex %s)",
  592. mouse_subclass, opossum_subclass, vertex_label
  593. )
  594. p <- ggplot(df_combined, aes(x = Y_Position_Normalized, y = Distance, color = Species)) +
  595. geom_point(alpha = 0.75, size = 1) +
  596. geom_smooth(method = "lm", se = TRUE) +
  597. labs(
  598. title = plot_title,
  599. subtitle = sprintf(
  600. "Mouse [%d-%d], Opossum [%d-%d]\nSpearman r: Mouse=%.2f (p=%.3g), Opossum=%.2f (p=%.3g)",
  601. mouse_xmin, mouse_xmax, opossum_xmin, opossum_xmax,
  602. mouse_cor$estimate, mouse_cor$p.value,
  603. opossum_cor$estimate, opossum_cor$p.value
  604. ),
  605. x = "Normalized Y Position (0=superficial, 1=deep)",
  606. y = vertex_col
  607. ) +
  608. theme_bw(base_size = 14) +
  609. ylim(15, 45) +
  610. xlim(0, 1) +
  611. coord_fixed(ratio = 1 / 15) +
  612. scale_color_manual(values = c("Opossum" = "#c692b8", "Mouse" = "#aaaaaa"))
  613. print(p)
  614. SavePNGandSVG(p, dir.list$fig3$plots,
  615. sprintf("3J_OpossumMouse-Spatial%s%s-CorrVertex%s-ScatterFit",
  616. gsub("/", "", mouse_subclass), opossum_subclass, vertex_label))
  617. }
  618. }
  619. ```
  620. ```{r shuffle_control_setup}
  621. # Shuffle control: Randomize PC distance assignments
  622. # Tests if spatial gradient pattern is significant by shuffling distance values
  623. set.seed(9999)
  624. shuffle_distance_test <- function(y, x, n_perm = 10000L) {
  625. # y = depth (Y_Position), x = distance values
  626. obs_r <- suppressWarnings(cor(y, x, method = "spearman"))
  627. r_perm <- numeric(n_perm)
  628. for (i in seq_len(n_perm)) {
  629. x_perm <- sample(x, length(x), replace = FALSE)
  630. r_perm[i] <- suppressWarnings(cor(y, x_perm, method = "spearman"))
  631. }
  632. p_emp <- mean(abs(r_perm) >= abs(obs_r))
  633. list(obs_r = obs_r, p_emp = p_emp, r_perm = r_perm)
  634. }
  635. shuffle_results_mouse <- list()
  636. shuffle_results_opossum <- list()
  637. ```
  638. ```{r shuffle_control_mouse}
  639. # Mouse shuffle control
  640. cat("=== Mouse Shuffle Control (Distance Randomization) ===\n")
  641. mouse_subclass <- "L2/3"
  642. vertices <- c("B", "C")
  643. regimes <- list(list(mouse = c(1000, 1550), opossum = c(1000, 1550)))
  644. mouse.rgb <- read.csv(paste0(dir.list$fig3$data, "mouse_integrated_PC_colors.csv"),
  645. row.names = 1)
  646. for (vertex_label in vertices) {
  647. vertex_col <- paste0("Euclidean_to_Vertex_", vertex_label)
  648. mouse_cells <- colnames(obj.i.mouse.IT)[
  649. !is.na(obj.i.mouse.IT$subclass_nn) &
  650. obj.i.mouse.IT$subclass_nn == mouse_subclass
  651. ]
  652. mouse_coords <- obj.i.mouse.IT@images[[1]]$centroids@coords[
  653. obj.i.mouse.IT$subclass_nn[!is.na(obj.i.mouse.IT$subclass_nn)] == mouse_subclass,
  654. ]
  655. rownames(mouse_coords) <- mouse_cells
  656. mouse_y_positions <- mouse_coords[mouse_cells, "x"]
  657. mouse_distance <- mouse.rgb[mouse_cells, vertex_col]
  658. for (regime in regimes) {
  659. mouse_xmin <- regime$mouse[1]
  660. mouse_xmax <- regime$mouse[2]
  661. idx <- mouse_y_positions >= mouse_xmin & mouse_y_positions < mouse_xmax
  662. y_regime <- 1 - (mouse_y_positions[idx] - mouse_xmin) / (mouse_xmax - mouse_xmin)
  663. x_regime <- mouse_distance[idx]
  664. res_shuffle <- shuffle_distance_test(
  665. y = y_regime,
  666. x = x_regime,
  667. n_perm = 10000L
  668. )
  669. key <- sprintf("Mouse_L23_Vertex_%s_%d_%d", vertex_label, mouse_xmin, mouse_xmax)
  670. shuffle_results_mouse[[key]] <- res_shuffle
  671. cat(key, " | obs r =", round(res_shuffle$obs_r, 3),
  672. " | shuffle p =", signif(res_shuffle$p_emp, 3), "\n")
  673. }
  674. }
  675. ```
  676. ```{r shuffle_control_opossum}
  677. # Opossum shuffle control
  678. cat("\n=== Opossum Shuffle Control (Distance Randomization) ===\n")
  679. opossum_subclass <- "IT_A"
  680. opossum.rgb <- read.csv(paste0(dir.list$fig3$data, "opossum_integrated_PC_colors.csv"),
  681. row.names = 1)
  682. for (vertex_label in vertices) {
  683. vertex_col <- paste0("Euclidean_to_Vertex_", vertex_label)
  684. opossum_cells <- colnames(obj.i.opossum.IT)[
  685. !is.na(obj.i.opossum.IT$subclass_nn) &
  686. obj.i.opossum.IT$subclass_nn == opossum_subclass
  687. ]
  688. opossum_coords <- obj.i.opossum.IT@images[[1]]$centroids@coords[
  689. obj.i.opossum.IT$subclass_nn[!is.na(obj.i.opossum.IT$subclass_nn)] == opossum_subclass,
  690. ]
  691. rownames(opossum_coords) <- opossum_cells
  692. opossum_y_positions <- opossum_coords[opossum_cells, "x"]
  693. opossum_distance <- opossum.rgb[opossum_cells, vertex_col]
  694. for (regime in regimes) {
  695. opossum_xmin <- regime$opossum[1]
  696. opossum_xmax <- regime$opossum[2]
  697. idx <- opossum_y_positions >= opossum_xmin & opossum_y_positions < opossum_xmax
  698. y_regime <- 1 - (opossum_y_positions[idx] - opossum_xmin) / (opossum_xmax - opossum_xmin)
  699. x_regime <- opossum_distance[idx]
  700. res_shuffle <- shuffle_distance_test(
  701. y = y_regime,
  702. x = x_regime,
  703. n_perm = 10000L
  704. )
  705. key <- sprintf("Opossum_ITA_Vertex_%s_%d_%d", vertex_label, opossum_xmin, opossum_xmax)
  706. shuffle_results_opossum[[key]] <- res_shuffle
  707. cat(key, " | obs r =", round(res_shuffle$obs_r, 3),
  708. " | shuffle p =", signif(res_shuffle$p_emp, 3), "\n")
  709. }
  710. }
  711. ```
  712. ```{r partial_correlation_setup}
  713. # Partial correlation: depth vs Vertex C controlling for Vertex B
  714. # Tests if relationship between depth and one vertex is independent of the other
  715. library(ppcor)
  716. mouse_subclass <- "L2/3"
  717. opossum_subclass <- "IT_A"
  718. regimes <- list(list(mouse = c(1000, 1550), opossum = c(1000, 1550)))
  719. mouse.rgb <- read.csv(paste0(dir.list$fig3$data, "mouse_integrated_PC_colors.csv"),
  720. row.names = 1)
  721. opossum.rgb <- read.csv(paste0(dir.list$fig3$data, "opossum_integrated_PC_colors.csv"),
  722. row.names = 1)
  723. ```
  724. ```{r partial_correlation_mouse}
  725. # Mouse partial correlations
  726. cat("=== Mouse Partial Correlations ===\n")
  727. mouse_cells <- colnames(obj.i.mouse.IT)[
  728. !is.na(obj.i.mouse.IT$subclass_nn) &
  729. obj.i.mouse.IT$subclass_nn == mouse_subclass
  730. ]
  731. mouse_coords <- obj.i.mouse.IT@images[[1]]$centroids@coords[
  732. obj.i.mouse.IT$subclass_nn[!is.na(obj.i.mouse.IT$subclass_nn)] == mouse_subclass,
  733. ]
  734. rownames(mouse_coords) <- mouse_cells
  735. mouse_y <- mouse_coords[mouse_cells, "x"]
  736. mouse_dB <- mouse.rgb[mouse_cells, "Euclidean_to_Vertex_B"]
  737. mouse_dC <- mouse.rgb[mouse_cells, "Euclidean_to_Vertex_C"]
  738. for (regime in regimes) {
  739. mouse_xmin <- regime$mouse[1]
  740. mouse_xmax <- regime$mouse[2]
  741. idx <- mouse_y >= mouse_xmin & mouse_y < mouse_xmax
  742. df_mouse <- data.frame(
  743. Y = 1 - (mouse_y[idx] - mouse_xmin) / (mouse_xmax - mouse_xmin),
  744. dB = mouse_dB[idx],
  745. dC = mouse_dC[idx]
  746. )
  747. # Ordinary Spearman correlations
  748. cor_Y_dB <- cor(df_mouse$Y, df_mouse$dB, method = "spearman")
  749. cor_Y_dC <- cor(df_mouse$Y, df_mouse$dC, method = "spearman")
  750. cor_dB_dC <- cor(df_mouse$dB, df_mouse$dC, method = "spearman")
  751. cat(sprintf("\nMouse [%d-%d]:\n", mouse_xmin, mouse_xmax))
  752. cat("Spearman correlations:\n")
  753. cat(" Y vs dB =", round(cor_Y_dB, 3), "\n")
  754. cat(" Y vs dC =", round(cor_Y_dC, 3), "\n")
  755. cat(" dB vs dC =", round(cor_dB_dC, 3), "\n")
  756. # Partial correlations
  757. pcor_C_given_B <- pcor.test(
  758. x = df_mouse$Y,
  759. y = df_mouse$dC,
  760. z = df_mouse$dB,
  761. method = "spearman"
  762. )
  763. pcor_B_given_C <- pcor.test(
  764. x = df_mouse$Y,
  765. y = df_mouse$dB,
  766. z = df_mouse$dC,
  767. method = "spearman"
  768. )
  769. cat("Partial correlations:\n")
  770. cat(" Y ~ dC | dB: r =", round(pcor_C_given_B$estimate, 3),
  771. " p =", signif(pcor_C_given_B$p.value, 3), "\n")
  772. cat(" Y ~ dB | dC: r =", round(pcor_B_given_C$estimate, 3),
  773. " p =", signif(pcor_B_given_C$p.value, 3), "\n")
  774. }
  775. ```
  776. ```{r partial_correlation_opossum}
  777. # Opossum partial correlations
  778. cat("\n=== Opossum Partial Correlations ===\n")
  779. opossum_cells <- colnames(obj.i.opossum.IT)[
  780. !is.na(obj.i.opossum.IT$subclass_nn) &
  781. obj.i.opossum.IT$subclass_nn == opossum_subclass
  782. ]
  783. opossum_coords <- obj.i.opossum.IT@images[[1]]$centroids@coords[
  784. obj.i.opossum.IT$subclass_nn[!is.na(obj.i.opossum.IT$subclass_nn)] == opossum_subclass,
  785. ]
  786. rownames(opossum_coords) <- opossum_cells
  787. opossum_y <- opossum_coords[opossum_cells, "x"]
  788. opossum_dB <- opossum.rgb[opossum_cells, "Euclidean_to_Vertex_B"]
  789. opossum_dC <- opossum.rgb[opossum_cells, "Euclidean_to_Vertex_C"]
  790. for (regime in regimes) {
  791. opossum_xmin <- regime$opossum[1]
  792. opossum_xmax <- regime$opossum[2]
  793. idx <- opossum_y >= opossum_xmin & opossum_y < opossum_xmax
  794. df_opossum <- data.frame(
  795. Y = 1 - (opossum_y[idx] - opossum_xmin) / (opossum_xmax - opossum_xmin),
  796. dB = opossum_dB[idx],
  797. dC = opossum_dC[idx]
  798. )
  799. # Ordinary Spearman correlations
  800. cor_Y_dB <- cor(df_opossum$Y, df_opossum$dB, method = "spearman")
  801. cor_Y_dC <- cor(df_opossum$Y, df_opossum$dC, method = "spearman")
  802. cor_dB_dC <- cor(df_opossum$dB, df_opossum$dC, method = "spearman")
  803. cat(sprintf("\nOpossum [%d-%d]:\n", opossum_xmin, opossum_xmax))
  804. cat("Spearman correlations:\n")
  805. cat(" Y vs dB =", round(cor_Y_dB, 3), "\n")
  806. cat(" Y vs dC =", round(cor_Y_dC, 3), "\n")
  807. cat(" dB vs dC =", round(cor_dB_dC, 3), "\n")
  808. # Partial correlations
  809. pcor_C_given_B <- pcor.test(
  810. x = df_opossum$Y,
  811. y = df_opossum$dC,
  812. z = df_opossum$dB,
  813. method = "spearman"
  814. )
  815. pcor_B_given_C <- pcor.test(
  816. x = df_opossum$Y,
  817. y = df_opossum$dB,
  818. z = df_opossum$dC,
  819. method = "spearman"
  820. )
  821. cat("Partial correlations:\n")
  822. cat(" Y ~ dC | dB: r =", round(pcor_C_given_B$estimate, 3),
  823. " p =", signif(pcor_C_given_B$p.value, 3), "\n")
  824. cat(" Y ~ dB | dC: r =", round(pcor_B_given_C$estimate, 3),
  825. " p =", signif(pcor_B_given_C$p.value, 3), "\n")
  826. }
  827. ```
  828. ```{r partial_correlation_permutation}
  829. partial_cor_permutation <- function(y, x, z, n_perm = 10000, method = "spearman") {
  830. obs_pcor <- ppcor::pcor.test(y, x, z, method = method)$estimate
  831. r_perm <- replicate(n_perm, {
  832. y_shuf <- sample(y)
  833. ppcor::pcor.test(y_shuf, x, z, method = method)$estimate
  834. })
  835. p_emp <- mean(abs(r_perm) >= abs(obs_pcor))
  836. list(obs_r = obs_pcor, r_perm = r_perm, p_emp = p_emp)
  837. }
  838. mouse_subclass <- "L2/3"
  839. opossum_subclass <- "IT_A"
  840. regimes <- list(list(mouse = c(1000, 1550), opossum = c(1000, 1550)))
  841. # Mouse
  842. cat("=== Mouse Partial Correlations (Permutation) ===\n")
  843. mouse_cells <- colnames(obj.i.mouse.IT)[
  844. !is.na(obj.i.mouse.IT$subclass_nn) &
  845. obj.i.mouse.IT$subclass_nn == mouse_subclass
  846. ]
  847. mouse_coords <- obj.i.mouse.IT@images[[1]]$centroids@coords[
  848. obj.i.mouse.IT$subclass_nn[!is.na(obj.i.mouse.IT$subclass_nn)] == mouse_subclass,
  849. ]
  850. rownames(mouse_coords) <- mouse_cells
  851. mouse_y <- mouse_coords[mouse_cells, "x"]
  852. mouse_dB <- mouse.rgb[mouse_cells, "Euclidean_to_Vertex_B"]
  853. mouse_dC <- mouse.rgb[mouse_cells, "Euclidean_to_Vertex_C"]
  854. for (regime in regimes) {
  855. idx <- mouse_y >= regime$mouse[1] & mouse_y < regime$mouse[2]
  856. df_mouse <- data.frame(
  857. Y = 1 - (mouse_y[idx] - regime$mouse[1]) / (regime$mouse[2] - regime$mouse[1]),
  858. dB = mouse_dB[idx],
  859. dC = mouse_dC[idx]
  860. )
  861. set.seed(42)
  862. pcor_C_given_B <- partial_cor_permutation(df_mouse$Y, df_mouse$dC, df_mouse$dB)
  863. pcor_B_given_C <- partial_cor_permutation(df_mouse$Y, df_mouse$dB, df_mouse$dC)
  864. cat(sprintf("\nMouse [%d-%d] (n = %d cells):\n", regime$mouse[1], regime$mouse[2], nrow(df_mouse)))
  865. cat(" Y ~ dC | dB: r =", round(pcor_C_given_B$obs_r, 3),
  866. " p =", signif(pcor_C_given_B$p_emp, 3), "\n")
  867. cat(" Y ~ dB | dC: r =", round(pcor_B_given_C$obs_r, 3),
  868. " p =", signif(pcor_B_given_C$p_emp, 3), "\n")
  869. }
  870. # Opossum
  871. cat("\n=== Opossum Partial Correlations (Permutation) ===\n")
  872. opossum_cells <- colnames(obj.i.opossum.IT)[
  873. !is.na(obj.i.opossum.IT$subclass_nn) &
  874. obj.i.opossum.IT$subclass_nn == opossum_subclass
  875. ]
  876. opossum_coords <- obj.i.opossum.IT@images[[1]]$centroids@coords[
  877. obj.i.opossum.IT$subclass_nn[!is.na(obj.i.opossum.IT$subclass_nn)] == opossum_subclass,
  878. ]
  879. rownames(opossum_coords) <- opossum_cells
  880. opossum_y <- opossum_coords[opossum_cells, "x"]
  881. opossum_dB <- opossum.rgb[opossum_cells, "Euclidean_to_Vertex_B"]
  882. opossum_dC <- opossum.rgb[opossum_cells, "Euclidean_to_Vertex_C"]
  883. for (regime in regimes) {
  884. idx <- opossum_y >= regime$opossum[1] & opossum_y < regime$opossum[2]
  885. df_opossum <- data.frame(
  886. Y = 1 - (opossum_y[idx] - regime$opossum[1]) / (regime$opossum[2] - regime$opossum[1]),
  887. dB = opossum_dB[idx],
  888. dC = opossum_dC[idx]
  889. )
  890. set.seed(42)
  891. pcor_C_given_B <- partial_cor_permutation(df_opossum$Y, df_opossum$dC, df_opossum$dB)
  892. pcor_B_given_C <- partial_cor_permutation(df_opossum$Y, df_opossum$dB, df_opossum$dC)
  893. cat(sprintf("\nOpossum [%d-%d] (n = %d cells):\n", regime$opossum[1], regime$opossum[2], nrow(df_opossum)))
  894. cat(" Y ~ dC | dB: r =", round(pcor_C_given_B$obs_r, 3),
  895. " p =", signif(pcor_C_given_B$p_emp, 3), "\n")
  896. cat(" Y ~ dB | dC: r =", round(pcor_B_given_C$obs_r, 3),
  897. " p =", signif(pcor_B_given_C$p_emp, 3), "\n")
  898. }
  899. ```
  900. ```{r}
  901. # Set the Python path back for Seurat (restart R)
  902. Sys.setenv(RETICULATE_PYTHON = "C:/Users/TLab/AppData/Local/Programs/Python/Python311/python.exe")
  903. ```

3FGHIJ_OpossumMouse_PCGradients.Rmd at commit 8c490f6, under MIT · at the source

Overview

Authors: Ryan Gorzek1, Joshua T Trachtenberg1
  1. Department of Neurobiology, David Geffen School of Medicine, University of California, Los Angeles, Los Angeles, CA 90095, USA
Institutions: University of California, Los Angeles (United States)
Journal: PNAS nexus, volume 5, issue 4, article pgag055
Dates: received 13 October 2025; accepted 19 February 2026; published online 16 April 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1093/pnasnexus/pgag055 · PMID 42005962 · PMCID PMC13089494 · OpenAlex W7154582350
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: genetics / omics (modality), mouse (organism), cellular / molecular (subfield)
Methods: Connectivity, Statistics, Smoothing, state filtering, decompositions, Preprocessing, fMRI & imaging
Keywords: neocortex, transcriptomics, comparative, evolution, column
Journal subjects: Biological, Health, and Medical Sciences, Neuroscience
Topic: Neural dynamics and brain function (Cognitive Neuroscience, Neuroscience), according to OpenAlex
Funding: NIH (R01 EY023871)
Citations: not cited yet (Europe PMC); 62 references in the paper

Abstract

The neocortex, a layered structure unique to mammals, supports higher-order functions, including perception, learning, and decision-making. While its laminar architecture is broadly conserved, the cell type–specific organization of the cortical column has not been compared across species that diverged early in mammalian evolution. To address this, we used single-nucleus RNA sequencing and spatial transcriptomics to compare gene expression, cell types, and laminar architecture in the primary visual cortex (V1) of metatherian (Monodelphis domestica) and eutherian (Mus musculus) mammals. We show that spatio-transcriptomic distinctions between supragranular (layer 2/3) and infragranular (layer 5) intratelencephalic neurons are more pronounced in mice, consistent with lineage-specific specialization. Mouse cortex also exhibits a lower relative density of parvalbumin-positive GABAergic neurons and redistributed perineuronal nets, consistent with altered constraints on plasticity. Together, these findings demonstrate substantial variation in the cellular and spatial organization of the cortical column across deeply diverged mammals, challenging the view that local cortical architecture is uniformly conserved.

Reproduced under the paper's license (CC BY), from the paper cited above.

Repositories

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

shekharlab/mouseVC

License: none: the authors keep all their rights
State: the link answers, verified on 29 September 2026
Evidence: files inventoried
Commit: ce19e14782295577364850ffa5c91d346e4500af, 2 September 2024
Languages: Jupyter (50)
Size: 51 files, 50 scripts
Software Heritage: not archived
Found in: “Data Availability”
Holds: README, 50 notebooks
Not found: license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: Matplotlib (4 files), NumPy (4 files), pandas (4 files), Scanpy (4 files), SciPy (4 files), seaborn (2 files), scikit-learn (1 file)
Availability: 1 check, the latest on 29 September 2026: the link answers
  • 29 September 2026: the link answers
4 files

ryan-gorzek/opossum-V1-omics

License: MIT
State: the link answers, verified on 29 September 2026
Evidence: files inventoried
Commit: 8c490f6ef5d283fb52fcd1caf94be2381b94b983, 20 January 2026
Languages: R (32), Jupyter (3), MATLAB (1), Shell (1)
Size: 182 files, 37 scripts
Software Heritage: not archived
Found in: “Data Availability”
Holds: README, license file, 34 notebooks
Not found: CITATION.cff, environment file, tests, continuous integration, documentation
Tools: tidyverse (31 files), ggplot2 (30 files), Seurat (29 files), patchwork (10 files), data.table (8 files), reticulate (8 files), reshape2 (6 files), NumPy (4 files), pandas (4 files), SciPy (4 files), Scanpy (3 files), Matplotlib (2 files), Plotly (2 files), seaborn (2 files), NetworkX (1 file), SAMtools (1 file), scikit-learn (1 file), WGCNA (1 file)
Availability: 1 check, the latest on 29 September 2026: the link answers
  • 29 September 2026: the link answers
39 files

The paper's code and data availability statement is in the Data section.

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;
  • 41 scripts, each with its path and the digest of its content;
  • 14 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

Data Availability

Code is available on GitHub (github.com/ryan-gorzek/opossum-V1-omics). Raw and processed opossum snRNA-seq (GSE299387) and Stereo-seq (GSE299386) data are available on NCBI Gene Expression Omnibus (GEO). Raw mouse snRNA-seq data from our previous study (36) are available on GEO (GSE190940; P38 normally reared samples GSM5754081-3), and processed/labeled data are available by request (github.com/shekharlab/mouseVC). Immunofluorescence images are available on Figshare (doi.org/10.6084/m9.figshare.31427822 (https://doi.org/10.6084/m9.figshare.31427822)).

Reproduced under the paper's license (CC BY), from the paper cited above.

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

Recorded: type, language, journal, volume, issue, pages, dates, 2 authors, 5 keywords, 1 funder, 62 references.

Cite

This paper

Gorzek, R., & Trachtenberg, J. T. (2026). Comparative transcriptomics reveals differences in cortical cell type organization between metatherian and eutherian mammals. PNAS nexus, 5(4), pgag055. https://doi.org/10.1093/pnasnexus/pgag055

BibTeX

@article{gorzek2026comparative,
author = {Gorzek, Ryan and Trachtenberg, Joshua T},
title = {{Comparative transcriptomics reveals differences in cortical cell type organization between metatherian and eutherian mammals}},
journal = {PNAS nexus},
year = {2026},
month = apr,
volume = {5},
number = {4},
pages = {pgag055},
publisher = {Oxford University Press},
issn = {2752-6542},
doi = {10.1093/pnasnexus/pgag055},
url = {https://doi.org/10.1093/pnasnexus/pgag055},
pmid = {42005962},
pmcid = {PMC13089494}
}

RIS

TY - JOUR
AU - Gorzek, Ryan
AU - Trachtenberg, Joshua T
TI - Comparative transcriptomics reveals differences in cortical cell type organization between metatherian and eutherian mammals
T2 - PNAS nexus
J2 - PNAS Nexus
PY - 2026
DA - 2026/04/16
VL - 5
IS - 4
SP - pgag055
SN - 2752-6542
PB - Oxford University Press
DO - 10.1093/pnasnexus/pgag055
UR - https://doi.org/10.1093/pnasnexus/pgag055
LA - en
ER -

CSL-JSON

{
"id": "10.1093/pnasnexus/pgag055",
"type": "article-journal",
"title": "Comparative transcriptomics reveals differences in cortical cell type organization between metatherian and eutherian mammals",
"container-title": "PNAS nexus",
"author": [
{
"family": "Gorzek",
"given": "Ryan"
},
{
"family": "Trachtenberg",
"given": "Joshua T"
}
],
"container-title-short": "PNAS Nexus",
"volume": "5",
"issue": "4",
"page": "pgag055",
"DOI": "10.1093/pnasnexus/pgag055",
"PMID": "42005962",
"PMCID": "PMC13089494",
"ISSN": "2752-6542",
"publisher": "Oxford University Press",
"URL": "https://doi.org/10.1093/pnasnexus/pgag055",
"language": "en",
"issued": {
"date-parts": [
[
2026,
4,
16
]
]
}
}

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.1186/s13059-026-04177-w [code]
Genomic sequence evolution underlying human neocortical interareal diversification.
Journal: Genome biology
In common: SAMtools, reticulate, Scanpy, 12 other tools, genetics / omics, mouse, cellular / molecular, 4 references
[2] doi:10.1038/s41586-026-10629-x [code]
Whole-genome duplication shaped cell-type evolution in the vertebrate brain.
Journal: Nature
In common: reticulate, Scanpy, NetworkX, 11 other tools, genetics / omics, mouse, cellular / molecular, 4 references
[3] doi:10.1126/sciadv.aeg3223 [code]
The extreme diversity of retinal amacrine cells has deep evolutionary roots.
Journal: Science advances
In common: WGCNA, reticulate, Scanpy, 13 other tools, genetics / omics, cellular / molecular, 2 references
[4] doi:10.1038/s42003-026-10957-8 [code]
Brain defence by the extracellular matrix protein Cochlin.
Journal: Communications biology
In common: WGCNA, SAMtools, reticulate, 14 other tools, mouse, cellular / molecular
[5] 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: WGCNA, Scanpy, NetworkX, 13 other tools, genetics / omics, cellular / molecular, 2 references
[6] doi:10.1093/bioinformatics/btag592 [code]
Network-based stratification of allele-specific expression reveals patient subgroups in Huntington's disease.
Journal: Bioinformatics (Oxford, England)
In common: WGCNA, SAMtools, reticulate, 13 other tools, genetics / omics
[7] doi:10.1038/s41467-026-76675-1 [code]
Long-read proteogenomic atlas of human neuronal differentiation reveals isoform diversity informing neurodevelopmental risk mechanisms.
Journal: Nature communications
In common: WGCNA, SAMtools, reticulate, 13 other tools, genetics / omics
[8] doi:10.1038/s41586-026-10512-9 [code]
Astrocyte glucocorticoid receptor signalling restricts neuronal plasticity.
Journal: Nature
In common: SAMtools, Seurat, reshape2, 7 other tools, mouse, cellular / molecular, 6 references
[9] doi:10.1038/s41467-026-72935-2 [code]
Spindle neurons in human cortex possess distinctive firing properties and transcriptomic signatures.
Journal: Nature communications
In common: WGCNA, Scanpy, Seurat, 10 other tools, genetics / omics, cellular / molecular, 4 references
[10] 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: SAMtools, reticulate, Scanpy, 12 other tools, genetics / omics, mouse, cellular / molecular

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.