OSCR

Ischemic injury triggers a protective microglial phenotype in models of Aβ pathology.

Code ↔ Paper

3 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 3 matches
  1. [1] § Results › Augmentation of Apoe expression is a defining feature of microglial stroke response in comorbidity ↔ analysis/scRNA_Analyses_Candlishetal.Rmd, lines 416–441 · score 0.93 · Cx3cr1, P2ry12, H2 Aa, H2 Ab1, Clec7a, response microglia
  2. [2] § Results › Augmentation of Apoe expression is a defining feature of microglial stroke response in comorbidity ↔ analysis/scRNA_Analyses_Candlishetal.Rmd, lines 416–441 · score 0.80 · H2 Aa, H2 Ab1, Clec7a, response microglia, Oasl2, Ifit3
  3. [3] § Results › Augmentation of Apoe expression is a defining feature of microglial stroke response in comorbidity ↔ analysis/scRNA_Analyses_Candlishetal.Rmd, lines 3766–3820 · score 0.58 · H2 D1, Siglech, Ccl6, B2m, Lipe, Cst7

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 · 3,920 lines · 127 KB · no license · 3 matches

  1. ---
  2. title: "Analyses for Publication"
  3. author: "AGC"
  4. date: "2023-09-27"
  5. output:
  6. #pdf_document: default
  7. html_document: default
  8. ---
  9. ```{r setup, include=FALSE}
  10. #options(Seurat.object.assay.version = "v5")
  11. outputdir="./output/Res_202602/"
  12. if(!dir.exists(outputdir)) dir.create(outputdir, recursive = T)
  13. ## don't update matrixStats
  14. knitr::opts_chunk$set(
  15. echo = FALSE,
  16. warning = FALSE,
  17. message = FALSE)
  18. #library(limma)
  19. #library(DESeq2)
  20. library(tidyverse)
  21. library(scCustomize)
  22. library(Seurat)
  23. library(harmony)
  24. library(SingleR)
  25. library(data.table)
  26. library(compareGroups)
  27. library(openxlsx)
  28. library(viridis)
  29. library(DT)
  30. library(slingshot)
  31. library(SingleCellExperiment)
  32. library(ggpubr)
  33. library(clustree)
  34. library(RCurl)
  35. library(AnnotationHub)
  36. library(WGCNA)
  37. library(plotly)
  38. library(org.Mm.eg.db)
  39. library(knitr)
  40. library(ggrepel)
  41. set.seed(1324567)
  42. getwd()
  43. ```
  44. ```{r load_annotations, cache=F, include=FALSE}
  45. source ("./code/custom_functions.R")
  46. cc_file <- getURL("https://raw.githubusercontent.com/hbc/tinyatlas/master/cell_cycle/Mus_musculus.csv")
  47. cell_cycle_genes <- read.csv(text = cc_file)
  48. ah <- AnnotationHub::AnnotationHub()
  49. # Access the Ensembl database for organism
  50. ahDb <- query(ah,
  51. pattern = c("Mus musculus", "EnsDb"),
  52. ignore.case = TRUE)
  53. # Acquire the latest annotation files
  54. id <- ahDb %>%
  55. mcols() %>%
  56. rownames() %>%
  57. tail(n = 1)
  58. # Download the appropriate Ensembldb database
  59. edb <- ah[[id]]
  60. # Extract gene-level information from database
  61. annotations <- genes(edb,
  62. return.type = "data.frame")
  63. # Select annotations of interest
  64. annotations <- annotations %>%
  65. dplyr::select(gene_id, gene_name, seq_name, gene_biotype, description)
  66. ```
  67. # Load batch 2026
  68. ## Metadata additional samples
  69. ```{r load_add_meta, cache=F}
  70. # Read Sheet2
  71. df_raw <- read.xlsx("/files/scSeq_Hefendehl/data/20260126/534_plates_wSexAge.xlsx", sheet = "Sheet2")
  72. # Clean column names
  73. colnames(df_raw) <- c("User_Sample_Name", "Plate", "Container_Type",
  74. "Well_Location", "Protocol", "Species", "Mouse_ID",
  75. "Tissue_or_Organ", "Cell_Type", "Genotype", "Treatment",
  76. "Gender", "Age")
  77. # Filter to actual sample entries (remove header rows / template rows)
  78. df <- df_raw %>%
  79. dplyr::filter(!is.na(User_Sample_Name),
  80. !grepl("^<", User_Sample_Name), # remove <TABLE HEADER> etc.
  81. Container_Type == "386 well plate") # keep only plate entries
  82. # Function to expand a well range like "A1 - P12" into all individual wells
  83. expand_wells <- function(well_range) {
  84. # Parse "A1 - P12" format
  85. parts <- trimws(strsplit(well_range, "-")[[1]])
  86. start <- trimws(parts[1])
  87. end <- trimws(parts[2])
  88. # Extract row letters and column numbers
  89. start_row <- substr(start, 1, 1)
  90. start_col <- as.integer(substring(start, 2))
  91. end_row <- substr(end, 1, 1)
  92. end_col <- as.integer(substring(end, 2))
  93. rows <- LETTERS[which(LETTERS == start_row):which(LETTERS == end_row)]
  94. cols <- start_col:end_col
  95. # Generate all combinations
  96. expand.grid(Row = rows, Col = cols, stringsAsFactors = FALSE) %>%
  97. mutate(Well = paste0(Row, Col)) %>%
  98. pull(Well)
  99. }
  100. # Expand each sample entry to individual well positions
  101. df_expanded <- df %>%
  102. rowwise() %>%
  103. mutate(Well = list(expand_wells(Well_Location))) %>%
  104. unnest(Well) %>%
  105. dplyr::select(Plate,
  106. Well,
  107. Species,
  108. Mouse_ID,
  109. Tissue_or_Organ,
  110. Cell_Type,
  111. Genotype,
  112. Treatment,
  113. Age, Gender)
  114. df_expanded <- df_expanded %>%
  115. mutate(
  116. Plate = gsub("_011", "_11", Plate),
  117. Plate = gsub("_012", "_12", Plate),
  118. Cell_ID = paste0(Plate, "_", Well),
  119. Gender = ifelse(Gender=="female", "f", "m"),
  120. Genotype_Treatment = paste0(Genotype, "_", Treatment),
  121. ) %>%
  122. dplyr::select(
  123. Plate,
  124. Cell_ID,
  125. Mouse_ID,
  126. Genotype,
  127. Treatment,
  128. Genotype_Treatment,
  129. Age,
  130. Gender) %>% as.data.frame()
  131. rownames(df_expanded) <- df_expanded$Cell_ID
  132. # View result
  133. display_tab(df_expanded)
  134. # Optional: save to CSV
  135. write.csv(df_expanded,
  136. "/files/scSeq_Hefendehl/data/20260126/534_Plate_positions_all.csv",
  137. row.names = FALSE)
  138. ```
  139. ## load additional samples second GT
  140. ```{r load_add_samples 2nd, cache=F, dependson="load_add_meta"}
  141. files <- list.files("/files/scSeq_Hefendehl/data/20260126/",
  142. pattern = ".*Kallisto.*.csv",
  143. full.names = T)
  144. countlist = list()
  145. for(f in files){
  146. counts <- read.csv(f, row.names = 1, header = TRUE)
  147. matched <- annotations$gene_name[match(
  148. gsub("\\.[0-9]+", "", rownames(counts)),
  149. annotations$gene_id)]
  150. gene_names <- ifelse(is.na(matched), rownames(counts), matched)
  151. dups <- duplicated(gene_names) | duplicated(gene_names, fromLast = TRUE)
  152. dup_counts <- counts[dups, ] %>%
  153. as.data.frame() %>%
  154. mutate(gene = matched[dups]) %>%
  155. group_by(gene) %>%
  156. summarise(across(everything(), sum)) %>%
  157. column_to_rownames("gene")
  158. rownames(counts)[!dups] <- gene_names[!dups]
  159. counts <- rbind(counts[!dups, ], dup_counts)
  160. counts <- counts[rownames(counts) != "", ]
  161. counts <- as((as.matrix(counts)), "sparseMatrix")
  162. meta_counts <- df_expanded[colnames(counts), ]
  163. counts <- CreateSeuratObject(counts = counts,
  164. project = unique(meta_counts$Plate),
  165. min.cells = 3,
  166. min.features = 150,
  167. meta.data =meta_counts)
  168. Notannotgenes <- grepl("^ENSMUSG", rownames(counts))
  169. counts <- counts[!Notannotgenes,]
  170. print(unique(counts$Plate))
  171. counts[["orig.ident"]] <- counts$Cell_ID
  172. countlist[[unique(counts$Plate)]] <- counts
  173. }
  174. ```
  175. # Load batch 2025
  176. ```{r load_add_samples, cache=F, dependson="load_add_samples 2nd"}
  177. Sample_files <- list.files("/files/scSeq_Hefendehl/data/20230203/Sample_Tables/",
  178. pattern = "Sample.*.csv",
  179. full.names = T)
  180. counts_run1 <- read.csv("/files/scSeq_Hefendehl/data/20230203/Alignments/Run1/Kallisto/counts.csv", row.names = 1, header = TRUE) %>% rownames_to_column(var="GENE")
  181. counts_run2 <- read.csv("/files/scSeq_Hefendehl/data/20230203/Alignments/Run2/Kallisto/counts.csv", row.names = 1, header = TRUE) %>% rownames_to_column(var="GENE")
  182. counts <- counts_run1 %>% full_join(counts_run2, by = "GENE")
  183. Platenames= c("025"="SS2_20_025_9",
  184. "022"="SS2_20_022_7",
  185. "024"="SS2_20_024_8",
  186. "048"="SS2_21_048_6")
  187. Samples_meta = data.frame()
  188. for(s in Sample_files){
  189. P = substr(basename(s), 14,16)
  190. P = Platenames[P]
  191. Samples <- read.csv(s, header = TRUE) %>%
  192. mutate(
  193. Plate=as.character(P),
  194. Genotype = ifelse(Genotype=="WT", "WT", "APPPS1"),
  195. Genotype_Treatment = paste0(Genotype, "_", Treatment),
  196. Cell_ID=paste0(P,"_", Cell_ID),
  197. Age = as.numeric(gsub(" weeks", "", Age))) %>%
  198. dplyr::select(
  199. "Plate",
  200. "Cell_ID",
  201. "Mouse_ID",
  202. "Genotype",
  203. "Treatment",
  204. "Genotype_Treatment",
  205. "Gender",
  206. "Age")
  207. Samples_meta <- rbind(Samples_meta, Samples)
  208. }
  209. counts_sel <- counts %>% dplyr::select(any_of(Samples_meta$Cell_ID), "GENE") %>% as.data.frame() %>% column_to_rownames("GENE")
  210. counts_sel[is.na(counts_sel)]<-0
  211. matched <- annotations$gene_name[match(
  212. gsub("\\.[0-9]+", "", rownames(counts_sel)),
  213. annotations$gene_id)]
  214. gene_names <- ifelse(is.na(matched), rownames(counts_sel), matched)
  215. dups <- duplicated(gene_names) | duplicated(gene_names, fromLast = TRUE)
  216. dup_counts <- counts_sel[dups, ] %>%
  217. as.data.frame() %>%
  218. mutate(gene = matched[dups]) %>%
  219. group_by(gene) %>%
  220. summarise(across(everything(), sum)) %>%
  221. column_to_rownames("gene")
  222. rownames(counts_sel)[!dups] <- gene_names[!dups]
  223. counts_sel <- rbind(counts_sel[!dups, ], dup_counts)
  224. counts_sel <- counts_sel[rownames(counts_sel) != "", ]
  225. counts_sel <- as((as.matrix(counts_sel)), "sparseMatrix")
  226. Cells <- intersect(colnames(counts_sel), Samples_meta$Cell_ID)
  227. counts_sel <- counts_sel[,Cells]
  228. rownames(Samples_meta) <- Samples_meta$Cell_ID
  229. Samples_meta <- Samples_meta[Cells,]
  230. counts <- CreateSeuratObject(counts = counts_sel,
  231. project = "Batch1",
  232. min.cells = 3,
  233. min.features = 150,
  234. meta.data =Samples_meta)
  235. Notannotgenes <- grepl("^ENSMUSG", rownames(counts))
  236. counts <- counts[!Notannotgenes,]
  237. counts_list_firstbatch <- SplitObject(counts, split.by = "Plate")
  238. ```
  239. ```{r}
  240. seurat_list = c(counts_list_firstbatch, countlist)
  241. seurat_obj <- merge(
  242. seurat_list[[1]],
  243. y = seurat_list[-1],
  244. add.cell.ids = names(seurat_list))
  245. # Exclusde not gene_name annotated genes
  246. ```
  247. ```{r}
  248. rm(list=c("meta_counts",
  249. "samples.integrated",
  250. "seurat_list",
  251. "tmp_counts",
  252. "tmp_meta",
  253. "tmp_seurat",
  254. "ah",
  255. "ahDb",
  256. "countlist",
  257. "counts",
  258. "counts_list_firstbatch",
  259. "edb",
  260. "df", "df_expanded",
  261. "df_raw",
  262. "dup_counts"))
  263. gc()
  264. ```
  265. ```{r, fig.width=18, fig.height=5}
  266. Idents(seurat_obj) <- "Plate"
  267. DefaultAssay(seurat_obj) <- "RNA"
  268. seurat_obj[["percent.mt"]] <- PercentageFeatureSet(seurat_obj, pattern = "^mt-")
  269. seurat_obj <- JoinLayers(seurat_obj)
  270. seurat_obj[["RNA"]] <- JoinLayers(seurat_obj[["RNA"]])
  271. seurat_obj <- seurat_obj %>%
  272. NormalizeData() %>%
  273. FindVariableFeatures() %>%
  274. ScaleData() %>%
  275. RunPCA() %>%
  276. FindNeighbors(dims = 1:30, reduction = "pca") %>%
  277. FindClusters(cluster.name = "unintegrated_clusters") %>%
  278. RunUMAP(dims = 1:30, reduction = "pca", reduction.name = "umap.unintegrated")
  279. p <- DimPlot(seurat_obj, reduction = "umap.unintegrated", group.by = c("Plate", "Mouse_ID", "unintegrated_clusters"))
  280. p
  281. ggsave(paste0(outputdir, "DataLoad_umap.unintegrated.pdf"), p, width = 18, height=5)
  282. ```
  283. ```{r fig.width=12, fig.height=4}
  284. VlnPlot(seurat_obj, features = c("nCount_RNA", "nFeature_RNA", "percent.mt"),
  285. group.by = "Plate")
  286. seurat.obj.filt <- subset(seurat_obj,
  287. subset = nFeature_RNA > 100 &
  288. nFeature_RNA < 7000 &
  289. nCount_RNA <3e6 &
  290. nCount_RNA > 400 &
  291. percent.mt < 5)
  292. counts <- JoinLayers(seurat.obj.filt, assay = "RNA") %>% GetAssayData(assay = "RNA", layer="data")
  293. genes.percent.expression <- rowMeans(counts > 0)
  294. keep.genes <- names(genes.percent.expression[genes.percent.expression >= 0.005])
  295. # filter for expression in at least 0.5% of cells
  296. seurat.obj.filt <- seurat.obj.filt[keep.genes, ]
  297. VlnPlot(seurat.obj.filt, features = c("nCount_RNA", "nFeature_RNA", "percent.mt"),
  298. group.by = "Plate")
  299. # 7000 or less than 150 and cells with >7% mitochondrial counts.
  300. samples.integrated <- seurat.obj.filt
  301. ```
  302. ```{r}
  303. #samples.integrated = readRDS("/files/scSeq_Hefendehl/data/20230203/seu-SCT-harmony_02-02-23.rds")
  304. samples.integrated[["Genotype_Treatment"]] = factor(samples.integrated$Genotype_Treatment,
  305. levels = c("WT_Ctrl",
  306. "WT_Stroke",
  307. "APPPS1_Ctrl",
  308. "APPPS1_Stroke"))
  309. [email hidden] %>%
  310. dplyr::select(Mouse_ID, Genotype_Treatment, Gender, Age) %>%
  311. group_by(Mouse_ID) %>% mutate(
  312. nCells = n()
  313. ) %>% ungroup() %>%
  314. dplyr::distinct() -> Samplelist
  315. openxlsx::write.xlsx(Samplelist, "/files/scSeq_Hefendehl/data/Samplelist.xlsx",rowNames = TRUE)
  316. display_tab(Samplelist)
  317. ```
  318. ## Reclustering of datasets
  319. ### Define Gene lists
  320. ```{r}
  321. DAM_up <- c("Itgax","Cst7","Ccl4","Clec7a","Lpl","Siglec1","Spp1","Axl","Apoe","Trem2","Csf1","Lyz2","H2-D1","Tyrobp","Cd74","Gpnmb","B2m","Cd9","Ctsb","Ctsd") # genes up regulated in DAMs versus homestatics
  322. # additions
  323. DAM1_up <- c("Tyrobp", "Ctsb", "Ctsd", "Apoe", "B2m", "Fth1", "Lyz2") # genes up regulated in DAM1 vs Homeostasis
  324. DAM1_down <- c("Cx3cr1", "P2ry12", "Tmem119")# genes down regulated in DAM1 vs homeostasis
  325. DAM2_up <- c("Trem2", "Axl", "Cst7", "Ctsl", "Lpl", "Cd9", "Csf1", "Ccl6", "Itgax", "Clec7a", "Lilrb4", "Timp2")
  326. DAM1vsDAM2 = c("Trem2", "Cst7", "Spp1", "Lpl", "Itgax", "Ctsl", "Ctsz", "Cd68", "Axl", "Cd9", "Ccl6", "Csf1")
  327. homeostat.genes=c("P2ry12","P2ry13","Tmem119","Cx3cr1","Selplg","Cd33")
  328. INF_resp_microglia <- c("Ifit2", "Ifit3", "Ifitm3", "Irf7", "Oasl2")
  329. Cycling_microglia <- c("Top2a", "Mcm2", "Tubb5", "Mki67", "Cdk1")
  330. Act_resp_microglia <- c("Cd74", "H2-Ab1", "H2-Aa", "Ctsb", "Ctsd")
  331. Axon_tract_microglia <- c("Spp1", "Gpnmb", "Igf1", "Lgals3", "Fabp5", "Lpl", "Lgals1", "Ctsl", "Anxa5")
  332. cluster.genes=unique(c(DAM_up, DAM1vsDAM2, homeostat.genes))
  333. ```
  334. ```{r}
  335. ngenes = 50
  336. distal_dat = openxlsx::read.xlsx(
  337. "/files/scSeq_Hefendehl/data/Copy of DEG_control_vs_stroke_vs_distal_original.xlsx",
  338. sheet = 1)
  339. distal_dat <- distal_dat[order(distal_dat$score, decreasing = T)[1:ngenes],]
  340. distal_genes <- distal_dat$X1
  341. control_dat = openxlsx::read.xlsx("/files/scSeq_Hefendehl/data/Copy of DEG_control_vs_stroke_vs_distal_original.xlsx",sheet = 2)
  342. control_dat <- control_dat[order(control_dat$score, decreasing = T)[1:ngenes],]
  343. control_genes <- control_dat$X1
  344. Stroke_dat = openxlsx::read.xlsx("/files/scSeq_Hefendehl/data/Copy of DEG_control_vs_stroke_vs_distal_original.xlsx",sheet = 3)
  345. Stroke_dat <- Stroke_dat[order(Stroke_dat$score, decreasing = T)[1:ngenes],]
  346. Stroke_genes <- Stroke_dat$X1
  347. ```
  348. ## inspect data
  349. ### SCT CCA integration all cells
  350. ```{r, fig.width=8,fig.height=4}
  351. DefaultAssay(samples.integrated) = "RNA"
  352. samples.integrated <- UpdateSeuratObject(samples.integrated)
  353. samples.integrated$Run <-substr(samples.integrated$Plate, 1, 6)
  354. samples.integrated[["RNA"]] <- split(samples.integrated[["RNA"]], f= samples.integrated$Run)
  355. samples.integrated <- SCTransform(samples.integrated, vst.flavor = "v2")
  356. samples.integrated <- RunPCA(samples.integrated, npcs = 30, verbose = FALSE)
  357. # one-liner to run Integration
  358. DefaultAssay(samples.integrated) <- "RNA"
  359. samples.integrated <- IntegrateLayers(object = samples.integrated, method = CCAIntegration,
  360. orig.reduction = "pca", new.reduction = 'integrated.cca')
  361. samples.integrated <- FindNeighbors(samples.integrated, reduction = "integrated.cca", dims = 1:30)
  362. samples.integrated <- FindClusters(samples.integrated, resolution = 0.6)
  363. samples.integrated <- RunUMAP(samples.integrated, reduction = "integrated.cca", dims = 1:30, reduction.name = "umap.integrated.cca")
  364. a = DimPlot(samples.integrated, reduction = "umap.integrated.cca", group.by = "Plate")
  365. b = FeaturePlot_scCustom(samples.integrated, reduction = "umap.integrated.cca", features = "Aif1", colors_use = viridis_dark_high)
  366. b2 = FeaturePlot_scCustom(samples.integrated, reduction = "umap.integrated.cca", features = "Ptprc", colors_use = viridis_dark_high)
  367. c = RidgePlot(samples.integrated, features = "Aif1", group.by = "Mouse_ID")
  368. c2 = RidgePlot(samples.integrated, features = "Ptprc", group.by = "Mouse_ID")
  369. d = DimPlot(samples.integrated, reduction = "umap.integrated.cca", split.by = "Genotype_Treatment", pt.size = 1)
  370. e = FeaturePlot_scCustom(samples.integrated, reduction = "umap.integrated.cca", features = "Aif1", split.by = "Genotype_Treatment", colors_use = viridis_dark_high)
  371. e2 = FeaturePlot_scCustom(samples.integrated, reduction = "umap.integrated.cca", features = "Ptprc", split.by = "Genotype_Treatment", colors_use = viridis_dark_high)
  372. ```
  373. ```{r, fig.width=12,fig.height=5}
  374. a|b|b2
  375. ggarrange(c,c2, common.legend=T, legend = "none")
  376. ggsave(paste0(outputdir,"cluster_cca_integrated_nofilter.pdf"), a)
  377. ```
  378. ```{r, fig.width=12,fig.height=4}
  379. d
  380. e
  381. e2
  382. ```
  383. ### Sex specific genes
  384. ```{r, fig.width=12,fig.height=4}
  385. Idents(samples.integrated) <- "Mouse_ID"
  386. Sexgenes = c("Ddx3y", #y linked and microglia expressed
  387. "Xist") #X inactivation
  388. # cluster all cells for visualization purpose prior to exclusion
  389. a = DimPlot(samples.integrated, reduction = "umap.integrated.cca")
  390. b = FeaturePlot_scCustom(samples.integrated, reduction = "umap.integrated.cca",
  391. features = "Xist",
  392. colors_use = viridis_dark_high)
  393. c = RidgePlot(samples.integrated, features = Sexgenes)
  394. d = DimPlot(samples.integrated,
  395. reduction = "umap.integrated.cca",
  396. group.by = "Plate",
  397. split.by = "Mouse_ID",
  398. pt.size = 1)
  399. e = FeaturePlot_scCustom(samples.integrated,
  400. reduction = "umap.integrated.cca",
  401. features = Sexgenes,
  402. split.by = "Mouse_ID",
  403. colors_use = viridis_dark_high)
  404. ```
  405. ```{r, fig.width=10,fig.height=4}
  406. a|b
  407. c
  408. ggsave(paste0(outputdir, "cluster_Xist_harmony_integrated_nofilter.pdf"), a|b)
  409. ggsave(paste0(outputdir, "cluster_Xist_Ridge_integrated_nofilter.pdf"), c)
  410. ```
  411. ```{r, fig.width=30,fig.height=4}
  412. d
  413. ```
  414. ```{r fig.width=6, fig.height=6}
  415. DimPlot(samples.integrated, reduction="umap.integrated.cca", group.by = "Genotype_Treatment")
  416. ```
  417. ```{r fig.width=80, fig.height=15}
  418. e
  419. ggsave(paste0(outputdir, "cluster_Sexgenes_integrated_nofilter.pdf"), e, limitsize = F)
  420. ```
  421. ```{r, include=FALSE}
  422. reads = JoinLayers(samples.integrated, assay = "RNA") %>% GetAssayData(assay = "RNA", layer="data")
  423. reads = t(reads) %>% as.data.frame()
  424. metadata <- [email hidden]
  425. metadata$Aif1neg = NA
  426. metadata$Aif1neg <- paste0("Aif1neg_",as.character(reads$Aif1 ==0))
  427. metadata -> [email hidden]
  428. ```
  429. ```{r}
  430. rm( list=c("reads", "seurat_obj", "seurat.obj.filt"))
  431. ```
  432. ### remove sex specific and not-annotated genes
  433. ```{r, fig.width=4,fig.height=4}
  434. samples.integrated.filt <- samples.integrated
  435. sex.genes <- rownames(samples.integrated.filt) %in% annotations$gene_name[grepl("X|Y", annotations$seq_name)]
  436. Gmgenes <- grepl("^Gm", rownames(samples.integrated.filt))
  437. Rikgenes <- grepl(".*Rik$", rownames(samples.integrated.filt))
  438. samples.integrated.filt<- samples.integrated.filt[!(sex.genes|Gmgenes|Rikgenes),]
  439. ```
  440. # Clean integration
  441. ## Pre cell filtering integration
  442. ```{r, fig.width=4,fig.height=4}
  443. DefaultAssay(samples.integrated.filt)<- "RNA"
  444. samples.integrated.filt <- samples.integrated.filt %>% RunHarmony("Run")
  445. SDs=Stdev(object = samples.integrated.filt, reduction = "pca")
  446. varexpl <- SDs/sum(SDs)
  447. ndims <- which(cumsum(varexpl)>0.75)[1]
  448. ElbowPlot(samples.integrated.filt, reduction = "pca", ndims = 30) + geom_vline(xintercept =ndims)
  449. samples.integrated.filt <- samples.integrated.filt %>%
  450. FindNeighbors(reduction = "integrated.cca", dims = 1:ndims) %>%
  451. FindClusters(cluster.name = "integrated_clusters") %>%
  452. RunUMAP(dims = 1:ndims, reduction = "integrated.cca")
  453. ```
  454. ```{r, fig.width=12,fig.height=6}
  455. DimPlot(samples.integrated.filt, reduction = "umap",
  456. group.by = c("Plate", "Mouse_ID", "integrated_clusters", "Genotype_Treatment"))
  457. ```
  458. ## map cell types
  459. ```{r}
  460. ref.sce.mm <- celldex::MouseRNAseqData()
  461. sce.filt<- as.SingleCellExperiment(JoinLayers(samples.integrated.filt, assay = "RNA"), assay = "RNA")
  462. pred.mouseRNA <- SingleR(test =sce.filt, ref = ref.sce.mm, assay.type.test=1,
  463. labels = ref.sce.mm$label.fine)
  464. table(pred.mouseRNA$labels) #fine tuned cell types
  465. #table(pred.mouseRNA$pruned.labels) #cell type after pruning
  466. samples.integrated.filt$Immgen_sc_labels_agc <- NA
  467. samples.integrated.filt$Immgen_sc_labels_agc <- pred.mouseRNA$labels
  468. ```
  469. ```{r}
  470. pheat=plotScoreHeatmap(pred.mouseRNA, show.labels = TRUE,
  471. annotation_col=data.frame(cluster=samples.integrated.filt$seurat_clusters,
  472. row.names=rownames(pred.mouseRNA)))
  473. Idents(samples.integrated.filt)<- "seurat.integrated"
  474. a<- DimPlot(samples.integrated.filt, reduction="umap", group.by="Immgen_sc_labels_agc",
  475. label = F)
  476. b<- DimPlot(samples.integrated.filt, reduction="umap", group.by="Immgen_sc_labels_agc",
  477. label = F, split.by = "Plate")
  478. c<- DimPlot(samples.integrated.filt, reduction="umap", group.by="Immgen_sc_labels_agc", split.by = "Genotype_Treatment",
  479. label = F)
  480. ```
  481. ```{r}
  482. print(pheat)
  483. ggsave(filename = paste0(outputdir, "CelltypesHeatmap_Opt_All_genes_all_cells_Clusters_integrated.pdf"), pheat)
  484. ```
  485. ```{r}
  486. a
  487. ggsave(filename = paste0(outputdir, "Celltypes_Opt_All_genes_all_cells_Clusters_integrated.pdf"), a)
  488. ```
  489. ```{r, fig.width=18, fig.height=4}
  490. b
  491. ggsave(filename = paste0(outputdir, "Celltypes_Opt_All_genes_all_cells_Clusters_byPlate_integrated.pdf"), b)
  492. ```
  493. ```{r, fig.width=12, fig.height=4}
  494. c
  495. ggsave(filename = paste0(outputdir, "Celltypes_Opt_All_genes_all_cells_Clusters_byCondition_integrated.pdf"), c)
  496. ```
  497. ## filter and recluster only Microglia
  498. ### Re-optimize clustering
  499. ```{r}
  500. samples.integrated.filt <- samples.integrated.filt[,grepl("Microglia",samples.integrated.filt$Immgen_sc_labels_agc)]
  501. DefaultAssay(samples.integrated.filt)<- "RNA"
  502. samples.integrated.filt <- samples.integrated.filt %>%
  503. NormalizeData() %>%
  504. ScaleData() %>%
  505. RunPCA() %>%
  506. RunHarmony("Run")
  507. ```
  508. #### Layer integration across Runs using CCA Integration
  509. ```{r}
  510. reslist= seq(0.2,1.2,0.2)
  511. samples.integrated.filt <- samples.integrated.filt %>%
  512. IntegrateLayers(method = CCAIntegration,
  513. orig.reduction = "pca",
  514. new.reduction = 'integrated.cca') %>%
  515. FindNeighbors(reduction = "integrated.cca", dims = 1:ndims) %>%
  516. FindClusters(resolution = reslist) %>%
  517. RunUMAP(reduction = "integrated.cca", min.dist = 0.1, spread = 1, dims=1:ndims)
  518. clustreeplot<-clustree(samples.integrated.filt, prefix = "RNA_snn_res.")
  519. samples.integrated.filt <- samples.integrated.filt %>% RunUMAP(reduction = "integrated.cca", min.dist = 0.1, spread = 1, dims=1:ndims, reduction.name = "umap")
  520. ```
  521. ### Define resoultion for clustering
  522. ```{r, fig.width=15, fig.height=12}
  523. plotlist=list()
  524. for( cl in (grep("RNA_snn", colnames([email hidden]), value=T))){
  525. plotlist[[cl]] <- DimPlot(samples.integrated.filt, reduction="umap", group.by = cl)
  526. }
  527. plotlist <- plotlist[sort(names(plotlist))]
  528. ggarrange(plotlist=plotlist)
  529. ```
  530. ```{r, fig.width=5, fig.height=6}
  531. clustreeplot
  532. ggsave(filename = paste0(outputdir, "All_genes_Clustertree_integrated.pdf"), clustreeplot)
  533. ```
  534. ```{r}
  535. library(mclust)
  536. samples.integrated.filt.meta <- [email hidden]
  537. res_cols <- sort(grep("RNA_snn_res", colnames(samples.integrated.filt.meta), value = TRUE))
  538. ari_results <- data.frame()
  539. for (i in 1:(length(res_cols) - 1)) {
  540. col1 <- res_cols[i]
  541. col2 <- res_cols[i + 1]
  542. ari <- adjustedRandIndex(samples.integrated.filt.meta[[col1]],
  543. samples.integrated.filt.meta[[col2]])
  544. ari_results <- rbind(ari_results, data.frame(res1 = col1, res2 = col2, ARI = ari))
  545. }
  546. best_res <- ari_results$res1[which.max(ari_results$ARI)]
  547. best_res <- as.numeric(gsub("RNA_snn_res.", "", best_res))
  548. ari_results
  549. best_res <- 0.6
  550. ```
  551. clustering resolultion was set to `r best_res`
  552. ```{r, warning=F, }
  553. DefaultAssay(samples.integrated.filt) <- "RNA"
  554. samples.integrated.filt <- samples.integrated.filt %>%
  555. FindNeighbors(reduction = "integrated.cca", dims = 1:ndims) %>%
  556. FindClusters(resolution = best_res, cluster.name = "seurat.integrated") %>%
  557. RunUMAP(reduction = "integrated.cca", min.dist = 0.1, spread = 1, dims=1:ndims)
  558. n = length(unique(samples.integrated.filt$seurat.integrated))
  559. Idents(samples.integrated.filt) <- "seurat.integrated"
  560. samples.integrated.filt$labels<- factor(Idents(samples.integrated.filt),
  561. levels = c(0:(n-1)), labels=paste0("Microglia", 0:(n-1))
  562. )
  563. Idents(samples.integrated.filt) = "labels"
  564. DefaultAssay(samples.integrated.filt) <- "RNA"
  565. samples.integrated.filt[["RNA"]] <- samples.integrated.filt[["RNA"]] %>% JoinLayers()
  566. samples.integrated.filt[["RNA"]]$scale.data <- NULL
  567. samples.integrated.filt<- samples.integrated.filt %>% NormalizeData() %>% ScaleData()
  568. a<-DimPlot(samples.integrated.filt, , reduction = "umap",
  569. group.by = "seurat.integrated", pt.size =1, label = T) + NoLegend()
  570. b<-DimPlot(samples.integrated.filt, reduction = "umap", split.by = "Plate", pt.size = 1)
  571. c<-DimPlot(samples.integrated.filt, reduction = "umap", split.by = "Genotype_Treatment", pt.size =1)
  572. d <- DimPlot(samples.integrated.filt, reduction = "umap", split.by = "Mouse_ID", pt.size =1)
  573. e<-FeaturePlot_scCustom(samples.integrated.filt,reduction = "umap", layer = "scale.data",
  574. features = homeostat.genes, colors_use = viridis_dark_high)
  575. ```
  576. ```{r, fig.width=5, fig.height=5}
  577. a
  578. ggsave(filename =
  579. paste0(outputdir,
  580. "Opt_All_genes_all_cells_Clusters_integrated.pdf"), a)
  581. ```
  582. ```{r, fig.width=30, fig.height=5}
  583. b
  584. ggsave(filename =
  585. paste0(outputdir,
  586. "Opt_All_genes_all_cells_Clusters_byPlate_integrated.pdf"),
  587. b)
  588. ```
  589. ```{r, fig.width=12, fig.height=4}
  590. c
  591. ggsave(filename = paste0(
  592. outputdir,
  593. "Opt_All_genes_all_cells_Clusters_byCondition_integrated.pdf"),
  594. c)
  595. ```
  596. ```{r, fig.width=30, fig.height=3}
  597. d
  598. ggsave(filename = paste0(
  599. outputdir,
  600. "Opt_All_genes_all_cells_Clusters_byMouseID_integrated.pdf"),
  601. d)
  602. ```
  603. ```{r, fig.width=8, fig.height=12}
  604. e
  605. ggsave(filename = paste0(outputdir,
  606. "All_genes_Clusters_byHomeostatgenes_integrated.pdf"), e)
  607. ```
  608. ```{r}
  609. a <- DimPlot(samples.integrated.filt, reduction="umap", label = T)
  610. b <- DimPlot(samples.integrated.filt, reduction="umap", split.by = "Plate", label = F)
  611. c <- DimPlot(samples.integrated.filt, reduction="umap", split.by = "Genotype_Treatment", label = F)
  612. d <- DimPlot(samples.integrated.filt, reduction = "umap", group.by = "Genotype_Treatment")
  613. e <- DimPlot(samples.integrated.filt, reduction = "umap", group.by = "Gender")
  614. g <- DimPlot(samples.integrated.filt, reduction = "umap", group.by = "Aif1neg")
  615. h <- DimPlot(samples.integrated.filt, reduction = "umap", group.by = "Immgen_sc_labels_agc")
  616. samples.integrated.filt[["Immgen_sc_label_short"]] <- ifelse(
  617. grepl("Microglia", samples.integrated.filt$Immgen_sc_labels_agc),
  618. "Microglia", NA)
  619. i <- DimPlot(samples.integrated.filt, reduction = "umap", group.by = "Immgen_sc_label_short")
  620. ```
  621. ```{r, fig.width=8, fig.height=7}
  622. a
  623. ggsave(filename = paste0(outputdir, "Microglia_Opt_All_genes_Clusters_integrated.pdf"), a)
  624. d
  625. ggsave(filename = paste0(outputdir, "Microglia_Opt_All_genes_Condition_integrated.pdf"), d)
  626. e
  627. ggsave(filename = paste0(outputdir, "Microglia_Opt_All_genes_Gender_integrated.pdf"), e)
  628. g
  629. ggsave(filename = paste0(outputdir, "Microglia_Opt_All_genes_Aif1neg_integrated.pdf"), g)
  630. h
  631. ggsave(filename = paste0(outputdir, "Microglia_Opt_All_genes_Immgen_sc_labels_agc_integrated.pdf"), h)
  632. i
  633. ggsave(filename = paste0(outputdir, "Microglia_Opt_All_genes_Immgen_sc_labels_summed_integrated.pdf"), i)
  634. ```
  635. ```{r, fig.width=12, fig.height=4}
  636. c
  637. ggsave(filename = paste0(outputdir, "Microglia_Opt_All_genes_Clusters_byCondition.pdf"), c)
  638. ```
  639. ```{r, fig.width=18, fig.height=3}
  640. b
  641. ggsave(filename = paste0(outputdir, "Microglia_Opt_All_genes_Clusters_byPlate_integrated.pdf"), b)
  642. ```
  643. ```{r, fig.height=18, fig.width=10}
  644. f <- FeaturePlot_scCustom(samples.integrated.filt, reduction ="umap",
  645. features = sort(cluster.genes),order =T,
  646. colors_use = viridis_dark_high)
  647. f
  648. ggsave(filename = paste0(outputdir, "Microglia_Opt_all_genes_MicrogliaGenesintegrated.pdf"), f)
  649. ```
  650. ```{r, fig.width=8, fig.height=8}
  651. genelist <- c("Alpk1", "Mmp12", "Igf1", "S100a6", "Apoc4", "Dock10", "Nanog", "Olfr344")
  652. f <- FeaturePlot_scCustom(samples.integrated.filt, reduction = "umap",
  653. layer = "scale.data",
  654. features = sort(genelist),order =T,
  655. colors_use = viridis_dark_high)
  656. f
  657. ggsave(filename = paste0(outputdir, "Microglia_Opt_all_genes_AddGenelistintegrated.pdf"), f)
  658. ```
  659. # Map initial clusters batch 1
  660. ```{r, fig.width=8, fig.height=7}
  661. samples.integrated.filt_batch1 <- readRDS("./output/SeuratObjectafterProcessing.rds")
  662. meta <- [email hidden]
  663. meta_B1 <- [email hidden]
  664. lkup <- c(SS2_20_22="SS2_20_022",
  665. SS2_20_24="SS2_20_024",
  666. SS2_20_25="SS2_20_025",
  667. SS2_21_48="SS2_21_048")
  668. meta_B1$plate_new <- lkup[meta_B1$Plate]
  669. meta$label_B1<- meta_B1[match(meta$Cell_ID, paste0(meta_B1$plate_new, "_",meta_B1$Cell_ID)), "labels"]
  670. [email hidden] <- meta
  671. p<- DimPlot(samples.integrated.filt,
  672. group.by = "label_B1",
  673. reduction = "umap", order = T) + scale_color_discrete(na.value = "#F1F1F1")
  674. ggsave(paste0(outputdir, "Overlay_Initital_clusters.pdf"), p)
  675. p
  676. table(samples.integrated.filt$labels, samples.integrated.filt$label_B1)
  677. ggsave(filename = paste0(outputdir, "Microglia_Opt_all_genes_Batch1_Old_labels_integrated.pdf"), p)
  678. rm("samples.integrated.filt_batch1")
  679. ```
  680. ```{r, fig.width=7, fig.height=7}
  681. DefaultAssay(samples.integrated.filt) <- "RNA"
  682. FeaturePlot_scCustom(samples.integrated.filt, reduction="umap", features = "P2ry1", colors_use = viridis_dark_high, layer = "scale.data")
  683. ```
  684. # Markers for Clusters
  685. ```{r}
  686. metadata<[email hidden]
  687. res = compareGroups(Genotype_Treatment~labels, data = metadata)
  688. compareGroups::createTable(res, show.p.mul = T)
  689. compareGroups::createTable(res, show.p.mul = T) %>% export2xls(paste0(outputdir, "Cluster_distribution_genotype.xlsx"))
  690. res = compareGroups(Genotype_Treatment~Mouse_ID, data = metadata, max.xlev = 70, max.ylev = 20)
  691. compareGroups::createTable(res, show.p.mul = T)
  692. compareGroups::createTable(res, show.p.mul = T) %>% export2xls(paste0(outputdir, "Cellcount_distribution_MouseBygenotype.xlsx"))
  693. res = compareGroups(labels~Mouse_ID, data = metadata, max.xlev = 70, max.ylev = 20)
  694. compareGroups::createTable(res, show.p.mul = T)
  695. compareGroups::createTable(res, show.p.mul = T) %>% export2xls(paste0(outputdir, "Cellcount_distribution_MouseByCluster.xlsx"))
  696. ```
  697. ```{r, fig.height=18, fig.width=24}
  698. DefaultAssay(samples.integrated.filt) <- "RNA"
  699. f <- RidgePlot(samples.integrated.filt,
  700. features = sort(cluster.genes),
  701. assay = "RNA",
  702. layer = "data", combine = F)
  703. f <- ggarrange(plotlist = f, common.legend = T, legend = "right")
  704. f
  705. ggsave(filename = paste0(outputdir, "Microglia_Opt_all_genes_MicrogliaGenesRidgePlotintegrated.pdf"), f)
  706. ```
  707. ### all clusters
  708. ```{r}
  709. Idents(samples.integrated.filt) <- "labels"
  710. DefaultAssay(samples.integrated.filt)<- "RNA"
  711. #samples.integrated.filt <- PrepSCTFindMarkers(samples.integrated.filt)
  712. # remove not annotated genes
  713. geneunivers<-rownames(samples.integrated.filt)
  714. Markers=FindAllMarkers(samples.integrated.filt,
  715. logfc.threshold = 1,
  716. assay = "RNA", slot = "data",
  717. features = geneunivers,
  718. only.pos = T)
  719. display_tab(Markers)
  720. openxlsx::write.xlsx(Markers, paste0(outputdir, "Clusters_Markers_all.xlsx"),rowNames = TRUE)
  721. genelist = list()
  722. for ( i in unique(Markers$cluster)) genelist[[i]] <- Markers$gene[Markers$cluster==i]
  723. GOterm=getGOresults(genelist, genereference = geneunivers, organism = "mmusculus")
  724. display_tab(GOterm$result)
  725. openxlsx::write.xlsx(GOterm$result, paste0(outputdir, "Clusters_GOterms_Markers_all.xlsx"),rowNames = TRUE)
  726. ```
  727. ```{r}
  728. metadata=[email hidden]
  729. restab = table(GT_Treat = metadata$Genotype_Treatment, DAMs=metadata$labels)
  730. restab
  731. prop.table(restab, margin = 1)
  732. chisq.test(restab)
  733. proplot <- ggplot(as.data.frame(restab),
  734. aes(fill=DAMs, x=GT_Treat, y=Freq))+
  735. geom_bar(position="fill", stat="identity", color="black", linewidth=0.5)+theme_classic()+ggtitle("Micorglia cluster proportions")
  736. proplot
  737. ggsave(filename = paste0(outputdir, "Microglia_Clusterproportions_per_condition_all_integrated.pdf"), proplot)
  738. library(chisq.posthoc.test)
  739. chisq.posthoc.test(restab)
  740. #To Do Pairwise
  741. ```
  742. ```{r, fig.width=10, fig.height=12}
  743. plotlist = list()
  744. mat <- GetAssayData(samples.integrated.filt, assay = "RNA", slot = "data")
  745. temp_obj <- samples.integrated.filt
  746. for (m in names(genelist)){
  747. #reads = rowSums(samples.integrated.filt@assays$RNA$counts)
  748. targets <- Markers[Markers$cluster==m, ] %>% arrange(desc(pct.1))
  749. targets <- targets$gene[1:10]
  750. mat_sel <- mat[targets, , drop = FALSE]
  751. mat_norm <- t(apply(mat_sel, 1, function(x) (x - min(x)) / (max(x) - min(x) + 1e-9))) %>% as.matrix()
  752. temp_obj@assays$RNA@layers$data[match(targets, rownames(temp_obj)), ] <- mat_norm[targets, colnames(temp_obj)]
  753. p<-DoHeatmap(temp_obj, features = targets, disp.max = 1,
  754. group.by = "labels", assay = "RNA", slot = "data",
  755. label = F, combine=F)
  756. p <- p[[1]] + scale_fill_viridis()
  757. ggsave(p, file=paste0(outputdir, "Top10GenesByExpr_",m,"_Heatmaps_byCluster_integrated.pdf"))
  758. plotlist[[m]]<-p
  759. }
  760. p<- ggarrange(plotlist = plotlist, labels = names(genelist), common.legend = T)
  761. p
  762. ggsave(file=paste0(outputdir, "Top10Genes_Heatmaps_byCluster_Row_Scaled_integrated.pdf"), p)
  763. ```
  764. ```{r, fig.width=15, fig.height=12}
  765. plotlist = list()
  766. mat <- GetAssayData(samples.integrated.filt, assay = "RNA", slot = "data")
  767. for (m in names(genelist)){
  768. #reads = rowSums(samples.integrated.filt@assays$RNA$counts)
  769. targets <- Markers[Markers$cluster==m, ] %>% arrange(desc(pct.1))
  770. targets <- targets$gene[1:10]
  771. mat_sel <- mat[targets, , drop = FALSE]
  772. max_plot <- mean(mat_sel)+2*sd(mat_sel)
  773. p<-DoHeatmap(samples.integrated.filt, features = targets, disp.max = ceiling(max_plot),
  774. group.by = "labels", assay = "RNA", slot = "data",
  775. label = F, combine=F)
  776. p <- p[[1]] + scale_fill_viridis()
  777. ggsave(p, file=paste0(outputdir, "Top10GenesByExpr_",m,"_Heatmaps_byCluster_integrated.pdf"))
  778. plotlist[[m]]<-p
  779. }
  780. p<- ggarrange(plotlist = plotlist, labels = names(genelist), common.legend = F)
  781. p
  782. ggsave(file=paste0(outputdir, "Top10Genes_Heatmaps_byCluster_integrated.pdf"), p)
  783. ```
  784. ```{r, fig.width=14, fig.height=7}
  785. FeaturePlot_scCustom(samples.integrated.filt, features = c("Lipe1", "Rfx7", "Olfr344", "S100a8"),
  786. layer="data", colors_use = viridis_dark_high, , reduction = "umap")
  787. ```
  788. ```{r, fig.width=7, fig.height=7}
  789. DimPlot(samples.integrated.filt, reduction = "umap")
  790. ```
  791. ## Comparison of DEGs in DAMs between treatments/genotypes
  792. ### define DAM
  793. DAM profiles based on Cell. 2017 Jun 15;169(7):1276-1290.e17. doi: 10.1016/j.cell.2017.05.018)
  794. ##### DAM1
  795. ```{r, fig.width=12, fig.height=4}
  796. #load("./data/DAM_genelists.RData")
  797. DefaultAssay(samples.integrated.filt) = "RNA"
  798. samples.integrated.filt<- AddModuleScore(object = samples.integrated.filt,
  799. assay="RNA", slot="data",
  800. features = list(DAM1_up), name = "DAM_score")
  801. #FeaturePlot_scCustom(samples.integrated.filt, features = "DAM_score1")+scale_color_viridis_c()
  802. samples.integrated.filt <- AddModuleScore(object = samples.integrated.filt,
  803. assay="RNA", slot="data",
  804. features = list(DAM_up), name = "DAM_score")
  805. p4 <- FeaturePlot_scCustom(seurat_object = samples.integrated.filt, reduction = "umap",
  806. features = "DAM_score1", colors_use = viridis_dark_high)
  807. p4a <- DimPlot(object = samples.integrated.filt, reduction = "umap")
  808. DAMcutoff = 1.5
  809. phist = ggplot(data = [email hidden], aes(x=DAM_score1))+
  810. geom_density()+geom_vline(xintercept = DAMcutoff)+
  811. theme_classic()
  812. samples.integrated.filt$DAM_binary = as.factor(samples.integrated.filt$DAM_score1>=DAMcutoff)
  813. pbin <- DimPlot(object = samples.integrated.filt, group.by = "DAM_binary", reduction = "umap")
  814. comb = phist | p4 | pbin| p4a
  815. comb
  816. prop.table(table(DAMs=samples.integrated.filt$DAM_binary, Clusters=samples.integrated.filt$labels), margin = 2)
  817. dam_GT_p <-DimPlot(object = samples.integrated.filt, group.by = "DAM_binary", split.by = "Genotype_Treatment")
  818. ggsave(filename = paste0(outputdir, "Microglia_DAM1_callingintegrated.pdf"), comb)
  819. ggsave(filename = paste0(outputdir, "Microglia_DAM1_bygenotype_integrated.pdf"), dam_GT_p)
  820. ```
  821. ```{r}
  822. phist
  823. p4
  824. pbin
  825. ggsave(filename = paste0(outputdir, "Microglia_DAM1_thresholding_integrated.pdf"), phist)
  826. ggsave(filename = paste0(outputdir, "Microglia_DAM1_scoring_integrated.pdf"), p4)
  827. ggsave(filename = paste0(outputdir, "Microglia_DAM1_binary_integrated.pdf"), pbin)
  828. ```
  829. ##### DAM2
  830. ```{r, fig.width=12, fig.height=4}
  831. samples.integrated.filt <- AddModuleScore(object = samples.integrated.filt,
  832. features = list(DAM2_up), name = "DAM2_score")
  833. p4 <- FeaturePlot_scCustom(seurat_object = samples.integrated.filt, reduction = "umap",
  834. features = "DAM2_score1", colors_use = viridis_dark_high)
  835. p4a <- DimPlot(object = samples.integrated.filt, reduction = "umap")
  836. DAM2cutoff = 1.0
  837. phist = ggplot(data = [email hidden], aes(x=DAM2_score1))+
  838. geom_density()+geom_vline(xintercept = DAM2cutoff)+
  839. theme_classic()
  840. samples.integrated.filt$DAM2_binary = as.factor(samples.integrated.filt$DAM2_score1>=DAM2cutoff)
  841. pbin <- DimPlot(object = samples.integrated.filt, reduction = "umap",
  842. group.by = "DAM2_binary")
  843. comb = phist | p4 | pbin| p4a
  844. dam_GT_p <-DimPlot(object = samples.integrated.filt,reduction = "umap", group.by = "DAM2_binary", split.by = "Genotype_Treatment")
  845. comb
  846. dam_GT_p
  847. ggsave(filename = paste0(outputdir, "Microglia_DAM2_calling_integrated.pdf"), comb)
  848. ggsave(filename = paste0(outputdir, "Microglia_DAM2_bygenotype_integrated.pdf"), dam_GT_p)
  849. prop.table(table(DAM2=samples.integrated.filt$DAM2_binary, Clusters=samples.integrated.filt$labels), margin = 2)
  850. prop.table(table(DAM2=samples.integrated.filt$DAM2_binary, DAMs=samples.integrated.filt$DAM_binary), margin = 2)
  851. ```
  852. ```{r, fig.width=12}
  853. a <- ggplot([email hidden], aes(x=DAM2_score1, y=DAM_score1))+
  854. geom_density_2d_filled()+geom_point(col="#FFFFFF55")+theme_classic()+ggtitle("all cells")
  855. b<- ggplot([email hidden][samples.integrated.filt$DAM_binary==TRUE,], aes(x=DAM2_score1, y=DAM_score1))+geom_density_2d_filled()+geom_point(col="#FFFFFF55")+theme_classic()+ggtitle("DAMs only")
  856. combo <- a|b
  857. combo
  858. ggsave(filename = paste0(outputdir, "Microglia_DAMvsDAM2_contourplot_integrated.pdf"), combo)
  859. ```
  860. ```{r}
  861. metadata=[email hidden]
  862. restab = table(GT_Treat = metadata$Genotype_Treatment, DAMs=metadata$DAM_binary)
  863. restab
  864. prop.table(restab, margin = 1)
  865. chisq.test(restab)
  866. proplot <- ggplot(as.data.frame(restab),
  867. aes(fill=DAMs, x=GT_Treat, y=Freq))+
  868. geom_bar(position="fill", color="black",stat="identity")+theme_classic()+ggtitle("DAM proportions")
  869. proplot
  870. ggsave(filename = paste0(outputdir, "Microglia_DAMproportions_per_condition_all_integrated.pdf"), proplot)
  871. library(chisq.posthoc.test)
  872. chisq.posthoc.test(restab)
  873. #To Do Pairwise
  874. ```
  875. #### DAMs in APPPS1 vs. DAMs in APPPS1 + Stroke
  876. ```{r}
  877. metadata=[email hidden][samples.integrated.filt$Genotype == "APPPS1", ]
  878. restab = table(GT_Treat = as.character(metadata$Genotype_Treatment), DAMs=metadata$DAM_binary)
  879. restab
  880. prop.table(restab, margin = 1)
  881. fisher.test(restab)
  882. proplot<-ggplot(as.data.frame(restab),
  883. aes(fill=DAMs, x=GT_Treat, y=Freq))+
  884. geom_bar(position="fill", color="black",stat="identity")+theme_classic()
  885. proplot
  886. ggsave(filename = paste0(outputdir, "Microglia_DAMproportions_per_condition_APPPS1_integrated.pdf"), proplot)
  887. ```
  888. #### DAMs in WT vs. DAMs in WT + Stroke
  889. ```{r}
  890. metadata=[email hidden][samples.integrated.filt$Genotype == "WT", ]
  891. restab = table(GT_Treat = as.character(metadata$Genotype_Treatment), DAMs=metadata$DAM_binary)
  892. restab
  893. prop.table(restab, margin = 1)
  894. fisher.test(restab)
  895. proplot<-ggplot(as.data.frame(restab),
  896. aes(fill=DAMs, x=GT_Treat, y=Freq))+
  897. geom_bar(position="fill", color="black",stat="identity")+theme_classic()
  898. proplot
  899. ggsave(filename = paste0(outputdir, "Microglia_DAMproportions_per_condition_WT_integrated.pdf"), proplot)
  900. ```
  901. #### DAM1 vs DAM2
  902. ```{r}
  903. metadata=[email hidden][samples.integrated.filt$DAM_binary==TRUE,]
  904. restab = table(GT_Treat = metadata$Genotype_Treatment, DAM2=metadata$DAM2_binary)
  905. restab
  906. prop.table(restab, margin = 1)
  907. chisq.test(restab)
  908. proplot<-ggplot(as.data.frame(restab),
  909. aes(fill=DAM2, x=GT_Treat, y=Freq))+
  910. geom_bar(position="fill", color="black",stat="identity")+theme_classic()
  911. chisq.posthoc.test(restab)
  912. proplot
  913. ggsave(filename = paste0(outputdir, "Microglia_DAM2proportionsofDAM1_per_condition_integrated.pdf"), proplot)
  914. ```
  915. ```{r}
  916. metadata=[email hidden][(samples.integrated.filt$DAM_binary==TRUE) & (samples.integrated.filt$Genotype=="APPPS1"),]
  917. restab = table(GT_Treat = as.character(metadata$Genotype_Treatment), DAM2=metadata$DAM2_binary)
  918. restab
  919. prop.table(restab, margin = 1)
  920. chisq.test(restab)
  921. proplot<- ggplot(as.data.frame(restab),
  922. aes(fill=DAM2, x=GT_Treat, y=Freq))+
  923. geom_bar(position="fill", color="black",stat="identity")+theme_classic()
  924. proplot
  925. ggsave(filename = paste0(outputdir, "Microglia_DAM2proportionsofDAM1_per_condition_APPPS1_integrated.pdf"), proplot)
  926. ```
  927. ```{r}
  928. metadata=[email hidden][(samples.integrated.filt$DAM_binary==TRUE) & (samples.integrated.filt$Genotype=="WT"),]
  929. restab = table(GT_Treat = as.character(metadata$Genotype_Treatment), DAM2=metadata$DAM2_binary)
  930. restab
  931. prop.table(restab, margin = 1)
  932. chisq.test(restab)
  933. proplot<-ggplot(as.data.frame(restab),
  934. aes(fill=DAM2, x=GT_Treat, y=Freq))+
  935. geom_bar(position="fill", color="black",stat="identity")+theme_classic()
  936. proplot
  937. ggsave(filename = paste0(outputdir, "Microglia_DAM2proportionsofDAM1_per_condition_WT_integrated.pdf"), proplot)
  938. ```
  939. #### Homeostatic Cells
  940. ```{r fig.width=9, fig.height=15}
  941. # list from Jan Hofmann
  942. a <- RidgePlot(samples.integrated.filt, features = homeostat.genes, ncol = 2)
  943. a
  944. b<- FeaturePlot_scCustom(samples.integrated.filt, reduction="umap",
  945. features = homeostat.genes, colors_use = viridis_dark_high)
  946. b
  947. ggsave(filename = paste0(outputdir, "Microglia_HomeostatGenes_Cluster_Ridgeplot_integrated.pdf"), a)
  948. ggsave(filename = paste0(outputdir, "Microglia_HomeostatGenes_Featureplot_integrated.pdf"), a)
  949. ```
  950. ```{r, fig.width=14, fig.height=4}
  951. samples.integrated.filt <- AddModuleScore(object = samples.integrated.filt, layer ="scaled.data",
  952. features = list(homeostat.genes), name = "Homeo_score")
  953. p4 <- FeaturePlot_scCustom(seurat_object = samples.integrated.filt,
  954. reduction = "umap",
  955. features = "Homeo_score1",
  956. colors_use = viridis_dark_high)
  957. p4a <- DimPlot(object = samples.integrated.filt, reduction = "umap")
  958. Homeocutff = 1.5
  959. phist = ggplot(data = [email hidden], aes(x=Homeo_score1))+
  960. geom_density()+geom_vline(xintercept = Homeocutff)+theme_classic()
  961. samples.integrated.filt$Homeo_binary = as.factor(samples.integrated.filt$Homeo_score1>=Homeocutff)
  962. pbin <- DimPlot(object = samples.integrated.filt, reduction = "umap", group.by = "Homeo_binary")
  963. comb = phist | p4 | pbin| p4a
  964. Hom_GT_p <-DimPlot(object = samples.integrated.filt, reduction = "umap",
  965. group.by = "Homeo_binary", split.by = "Genotype_Treatment")
  966. comb
  967. Hom_GT_p
  968. prop.table(table(Homeo=samples.integrated.filt$Homeo_binary,
  969. Clusters=samples.integrated.filt$labels), margin = 2)
  970. ggsave(filename = paste0(outputdir, "Microglia_Homeo_calling_integrated.pdf"), comb)
  971. ggsave(filename = paste0(outputdir, "Microglia_Homeo_bygenotype_integrated.pdf"), Hom_GT_p)
  972. ```
  973. ```{r}
  974. phist
  975. p4
  976. pbin
  977. ggsave(filename = paste0(outputdir, "Microglia_Homeo_thresholding_integrated.pdf"), phist)
  978. ggsave(filename = paste0(outputdir, "Microglia_Homeo_scoring_integrated.pdf"), p4)
  979. ggsave(filename = paste0(outputdir, "Microglia_Homeo_binary_integrated.pdf"), pbin)
  980. ```
  981. #### Homeo vs DAM
  982. ```{r}
  983. metadata = [email hidden]
  984. metadata$Homeo_DAM <- factor(1*as.logical(metadata$Homeo_binary) + 2*as.logical(metadata$DAM_binary), levels = c(0,1,2,3), labels = c("Neither", "Homeo", "DAM", "Unknown"))
  985. [email hidden] <- metadata
  986. a = DimPlot(samples.integrated.filt, reduction="umap", group.by = "Homeo_DAM")
  987. a
  988. ggsave(filename = paste0(outputdir, "Microglia_Homeo_DAM_integrated.pdf"), a)
  989. ```
  990. ```{r}
  991. restab = table(GT_Treat = metadata$Genotype_Treatment, Homeo=metadata$Homeo_DAM)
  992. restab
  993. prop.table(restab, margin = 1)
  994. chisq.test(restab)
  995. proplot<-ggplot(as.data.frame(restab),
  996. aes(fill=Homeo, x=GT_Treat, y=Freq))+
  997. geom_bar(position="fill", color="black",stat="identity")+theme_classic()
  998. chisq.posthoc.test(restab)
  999. proplot
  1000. ggsave(filename = paste0(outputdir, "Microglia_HomeoDAMproportions_per_condition_integrated.pdf"), proplot)
  1001. ```
  1002. ```{r}
  1003. restab = table(Clust = metadata$labels, Homeo=metadata$Homeo_DAM)
  1004. restab
  1005. prop.table(restab, margin = 1)
  1006. chisq.test(restab)
  1007. proplot<-ggplot(as.data.frame(restab),
  1008. aes(fill=Homeo, x=Clust, y=Freq))+
  1009. geom_bar(position="fill", color="black",stat="identity")+theme_classic()
  1010. chisq.posthoc.test(restab)
  1011. proplot
  1012. ggsave(filename = paste0(outputdir, "Microglia_HomeoDAMproportions_per_ckuster_integrated.pdf"), proplot)
  1013. ```
  1014. ```{r}
  1015. restab = table(Clust = metadata$labels, Celltype=metadata$Mouse_ID)
  1016. restab
  1017. prop.table(restab, margin = 1)
  1018. chisq.test(restab)
  1019. proplot<-ggplot(as.data.frame(restab),
  1020. aes(fill=Clust, x=Celltype, y=Freq))+
  1021. geom_bar(position="fill", color="black",stat="identity")+theme_classic()
  1022. chisq.posthoc.test(restab)
  1023. proplot <- proplot + theme(axis.text.x = element_text(angle=90))
  1024. proplot
  1025. ggsave(filename = paste0(outputdir, "Microglia_celltype_labels_integrated.pdf"), proplot)
  1026. ```
  1027. ```{r}
  1028. restab = table(gender=metadata$Gender, Clust = metadata$labels)
  1029. restab
  1030. prop.table(restab, margin = 1)
  1031. chisq.test(restab)
  1032. proplot<-ggplot(as.data.frame(restab),
  1033. aes(fill=gender, x=Clust, y=Freq))+
  1034. geom_bar(position="fill", color="black",stat="identity")+theme_classic()
  1035. chisq.posthoc.test(restab)
  1036. proplot
  1037. ggsave(filename = paste0(outputdir, "Microglia_HomeoDAMproportions_per_gender_integrated.pdf"), proplot)
  1038. ```
  1039. ```{r, fig.width=12}
  1040. a <- ggplot([email hidden], aes(x=Homeo_score1, y=DAM_score1))+
  1041. geom_density_2d_filled()+geom_point(col="#FFFFFF55")+theme_classic()+ggtitle("all cells")
  1042. b<- ggplot([email hidden][samples.integrated.filt$DAM_binary==TRUE,], aes(x=Homeo_score1, y=DAM_score1))+geom_density_2d_filled()+geom_point(col="#FFFFFF55")+theme_classic()+ggtitle("DAMs only")
  1043. a|b
  1044. ggsave(filename = paste0(outputdir, "Microglia_DAMvsHomeo_integrated.pdf"), a|b)
  1045. ```
  1046. #### Homeo in Genotype Treatment
  1047. proportion tables show percentages of Homeostatic cells per condition
  1048. ```{r}
  1049. metadata=[email hidden]
  1050. restab = table(GT_Treat = metadata$Genotype_Treatment, Homeo=metadata$Homeo_binary)
  1051. restab
  1052. prop.table(restab, margin = 1)
  1053. chisq.test(restab)
  1054. proplot<-ggplot(as.data.frame(restab),
  1055. aes(fill=Homeo, x=GT_Treat, y=Freq))+
  1056. geom_bar(position="fill", color="black",stat="identity")+theme_classic()
  1057. chisq.posthoc.test(restab)
  1058. proplot
  1059. ggsave(filename = paste0(outputdir, "Microglia_Homeoproportions_per_condition_integrated.pdf"), proplot)
  1060. ```
  1061. ```{r}
  1062. metadata=[email hidden][samples.integrated.filt$Genotype=="APPPS1",]
  1063. restab = table(GT_Treat = as.character(metadata$Genotype_Treatment), Homeo=metadata$Homeo_binary)
  1064. restab
  1065. prop.table(restab, margin = 1)
  1066. chisq.test(restab)
  1067. proplot<- ggplot(as.data.frame(restab),
  1068. aes(fill=Homeo, x=GT_Treat, y=Freq))+
  1069. geom_bar(position="fill", color="black",stat="identity")+theme_classic()
  1070. proplot
  1071. ggsave(filename = paste0(outputdir, "Microglia_Homeoproportions_per_condition_APPPS1_integrated.pdf"), proplot)
  1072. ```
  1073. ```{r}
  1074. metadata=[email hidden][samples.integrated.filt$Genotype=="WT",]
  1075. restab = table(GT_Treat = as.character(metadata$Genotype_Treatment), Homeo=metadata$Homeo_binary)
  1076. restab
  1077. prop.table(restab, margin = 1)
  1078. chisq.test(restab)
  1079. proplot<-ggplot(as.data.frame(restab),
  1080. aes(fill=Homeo, x=GT_Treat, y=Freq))+
  1081. geom_bar(position="fill", color="black",stat="identity")+theme_classic()
  1082. proplot
  1083. ggsave(filename = paste0(outputdir, "Microglia_Homeoproportions_per_condition_WT_integrated.pdf"), proplot)
  1084. ```
  1085. ### Spatial cell types
  1086. ```{r, fig.height=12,fig.width=5}
  1087. Idents(samples.integrated.filt) = "Genotype_Treatment"
  1088. DoHeatmap(samples.integrated.filt, slot = "data", features = c(distal_genes, control_genes, Stroke_genes))+ggtitle("spatial genes all")
  1089. DoHeatmap(samples.integrated.filt, slot = "data",features = c(distal_genes))+ggtitle("spatial genes distal")
  1090. DoHeatmap(samples.integrated.filt, slot = "data",features = c(control_genes))+ggtitle("spatial genes control")
  1091. DoHeatmap(samples.integrated.filt, slot = "data",features = c(Stroke_genes))+ggtitle("spatial genes peri-ictus")
  1092. ```
  1093. #### Distal Cell types
  1094. ```{r, fig.width=12, fig.height=4}
  1095. #load("./data/DAM_genelists.RData")
  1096. DefaultAssay(samples.integrated.filt) = "RNA"
  1097. samples.integrated.filt <- AddModuleScore(object = samples.integrated.filt,
  1098. features = list(distal_genes), name = "Distal")
  1099. p4 <- FeaturePlot_scCustom(seurat_object = samples.integrated.filt, reduction = "umap",
  1100. features = "Distal1", colors_use = viridis_dark_high)
  1101. p4a <- DimPlot(object = samples.integrated.filt, reduction = "umap")
  1102. Distalcutoff = 0.125
  1103. phist = ggplot(data = [email hidden], aes(x=Distal1))+
  1104. geom_density()+geom_vline(xintercept = Distalcutoff)+
  1105. theme_classic()
  1106. samples.integrated.filt$Distal_binary = as.factor(samples.integrated.filt$Distal1>=Distalcutoff)
  1107. pbin <- DimPlot(object = samples.integrated.filt, reduction = "umap",group.by = "Distal_binary")
  1108. phist | p4 | pbin| p4a
  1109. prop.table(table(Distals=samples.integrated.filt$Distal_binary, Clusters=samples.integrated.filt$labels), margin = 2)
  1110. DimPlot(object = samples.integrated.filt, group.by = "Distal_binary", reduction = "umap", split.by = "Genotype_Treatment")
  1111. ```
  1112. #### Control Cell types
  1113. ```{r, fig.width=12, fig.height=4}
  1114. #load("./data/DAM_genelists.RData")
  1115. DefaultAssay(samples.integrated.filt) = "RNA"
  1116. samples.integrated.filt <- AddModuleScore(object = samples.integrated.filt,
  1117. features = list(control_genes), name = "Control")
  1118. p4 <- FeaturePlot_scCustom(seurat_object = samples.integrated.filt, reduction = "umap",
  1119. features = "Control1", colors_use = viridis_dark_high)
  1120. p4a <- DimPlot(object = samples.integrated.filt, reduction = "umap")
  1121. Controlcutoff = 0.1
  1122. phist = ggplot(data = [email hidden], aes(x=Control1))+
  1123. geom_density()+geom_vline(xintercept = Controlcutoff)+
  1124. theme_classic()
  1125. samples.integrated.filt$Control_binary = as.factor(samples.integrated.filt$Control1>=Controlcutoff)
  1126. pbin <- DimPlot(object = samples.integrated.filt, reduction = "umap",
  1127. group.by = "Control_binary")
  1128. phist | p4 | pbin| p4a
  1129. prop.table(table(Controls=samples.integrated.filt$Control_binary, Clusters=samples.integrated.filt$labels), margin = 2)
  1130. DimPlot(object = samples.integrated.filt, group.by = "Control_binary", reduction = "umap",
  1131. split.by = "Genotype_Treatment")
  1132. ```
  1133. #### Peri_ictus Cell types
  1134. ```{r, fig.width=12, fig.height=4}
  1135. #load("./data/DAM_genelists.RData")
  1136. DefaultAssay(samples.integrated.filt) = "RNA"
  1137. samples.integrated.filt <- AddModuleScore(object = samples.integrated.filt,
  1138. features = list(Stroke_genes), name = "Peri_ictus")
  1139. p4 <- FeaturePlot_scCustom(seurat_object = samples.integrated.filt, reduction = "umap",features = "Peri_ictus1", colors_use = viridis_dark_high)
  1140. p4a <- DimPlot(object = samples.integrated.filt, reduction = "umap")
  1141. Strokecutoff = 1.75
  1142. phist = ggplot(data = [email hidden], aes(x=Peri_ictus1))+
  1143. geom_density()+geom_vline(xintercept = Strokecutoff)+
  1144. theme_classic()+ggtitle("Peri_ictus")
  1145. samples.integrated.filt$Peri_ictus_binary = as.factor(samples.integrated.filt$Peri_ictus1>=Strokecutoff)
  1146. pbin <- DimPlot(object = samples.integrated.filt, reduction = "umap",group.by = "Peri_ictus_binary")
  1147. phist | p4 | pbin| p4a
  1148. prop.table(table(Strokes=samples.integrated.filt$Peri_ictus_binary, Clusters=samples.integrated.filt$labels), margin = 2)
  1149. DimPlot(object = samples.integrated.filt, reduction = "umap",group.by = "Peri_ictus_binary", split.by = "Genotype_Treatment")
  1150. ```
  1151. ```{r}
  1152. ggplot([email hidden], aes(x=Peri_ictus1, y=Control1))+
  1153. geom_density_2d_filled()+geom_point(col="#FFFFFF55")+theme_classic()+ggtitle("all cells")
  1154. ggplot([email hidden][samples.integrated.filt$Peri_ictus_binary==TRUE,], aes(x=Peri_ictus1, y=Control1))+geom_density_2d_filled()+geom_point(col="#FFFFFF55")+theme_classic()+ggtitle("Peri_ictus only")
  1155. ```
  1156. proportion tables show percebtages of DAM cells per condition
  1157. #### Distals binary proportions
  1158. ```{r}
  1159. metadata=[email hidden]
  1160. restab = table(GT_Treat = metadata$Genotype_Treatment, Distals=metadata$Distal_binary)
  1161. restab
  1162. prop.table(restab, margin = 1)
  1163. chisq.test(restab)
  1164. ggplot(as.data.frame(restab),
  1165. aes(fill=Distals, x=GT_Treat, y=Freq))+
  1166. geom_bar(position="fill", color="black",stat="identity")+theme_classic()
  1167. library(chisq.posthoc.test)
  1168. chisq.posthoc.test(restab)
  1169. #To Do Pairwise
  1170. ```
  1171. #### Distals in APPPS1
  1172. ```{r}
  1173. metadata=[email hidden][samples.integrated.filt$Genotype == "APPPS1", ]
  1174. restab = table(GT_Treat = as.character(metadata$Genotype_Treatment), Distals=metadata$Distal_binary)
  1175. restab
  1176. prop.table(restab, margin = 1)
  1177. fisher.test(restab)
  1178. ggplot(as.data.frame(restab),
  1179. aes(fill=Distals, x=GT_Treat, y=Freq))+
  1180. geom_bar(position="fill", color="black",stat="identity")+theme_classic()
  1181. ```
  1182. #### Distals in WT
  1183. ```{r}
  1184. metadata=[email hidden][samples.integrated.filt$Genotype == "WT", ]
  1185. restab = table(GT_Treat = as.character(metadata$Genotype_Treatment), Distals=metadata$Distal_binary)
  1186. restab
  1187. prop.table(restab, margin = 1)
  1188. fisher.test(restab)
  1189. ggplot(as.data.frame(restab),
  1190. aes(fill=Distals, x=GT_Treat, y=Freq))+
  1191. geom_bar(position="fill", color="black",stat="identity")+theme_classic()
  1192. ```
  1193. #### Controls binary proportions
  1194. ```{r}
  1195. metadata=[email hidden]
  1196. restab = table(GT_Treat = metadata$Genotype_Treatment, Controls=metadata$Control_binary)
  1197. restab
  1198. prop.table(restab, margin = 1)
  1199. chisq.test(restab)
  1200. ggplot(as.data.frame(restab),
  1201. aes(fill=Controls, x=GT_Treat, y=Freq))+
  1202. geom_bar(position="fill", color="black",stat="identity")+theme_classic()
  1203. library(chisq.posthoc.test)
  1204. chisq.posthoc.test(restab)
  1205. #To Do Pairwise
  1206. ```
  1207. #### Controls in APPPS1
  1208. ```{r}
  1209. metadata=[email hidden][samples.integrated.filt$Genotype == "APPPS1", ]
  1210. restab = table(GT_Treat = as.character(metadata$Genotype_Treatment), Controls=metadata$Control_binary)
  1211. restab
  1212. prop.table(restab, margin = 1)
  1213. fisher.test(restab)
  1214. ggplot(as.data.frame(restab),
  1215. aes(fill=Controls, x=GT_Treat, y=Freq))+
  1216. geom_bar(position="fill", color="black",stat="identity")+theme_classic()
  1217. ```
  1218. #### Controls in WT
  1219. ```{r}
  1220. metadata=[email hidden][samples.integrated.filt$Genotype == "WT", ]
  1221. restab = table(GT_Treat = as.character(metadata$Genotype_Treatment), Controls=metadata$Control_binary)
  1222. restab
  1223. prop.table(restab, margin = 1)
  1224. fisher.test(restab)
  1225. ggplot(as.data.frame(restab),
  1226. aes(fill=Controls, x=GT_Treat, y=Freq))+
  1227. geom_bar(position="fill", color="black",stat="identity")+theme_classic()
  1228. ```
  1229. #### Peri_ictus binary proportions
  1230. ```{r}
  1231. metadata=[email hidden]
  1232. restab = table(GT_Treat = metadata$Genotype_Treatment, Peri_Ictal=metadata$Peri_ictus_binary)
  1233. restab
  1234. prop.table(restab, margin = 1)
  1235. chisq.test(restab)
  1236. ggplot(as.data.frame(restab),
  1237. aes(fill=Peri_Ictal, x=GT_Treat, y=Freq))+
  1238. geom_bar(position="fill", color="black",stat="identity")+theme_classic()
  1239. library(chisq.posthoc.test)
  1240. chisq.posthoc.test(restab)
  1241. #To Do Pairwise
  1242. ```
  1243. #### Peri_ictus in APPPS1
  1244. ```{r}
  1245. metadata=[email hidden][samples.integrated.filt$Genotype == "APPPS1", ]
  1246. restab = table(GT_Treat = as.character(metadata$Genotype_Treatment), Peri_Ictal=metadata$Peri_ictus_binary)
  1247. restab
  1248. prop.table(restab, margin = 1)
  1249. fisher.test(restab)
  1250. ggplot(as.data.frame(restab),
  1251. aes(fill=Peri_Ictal, x=GT_Treat, y=Freq))+
  1252. geom_bar(position="fill", color="black",stat="identity")+theme_classic()
  1253. ```
  1254. #### Peri_ictus WT
  1255. ```{r}
  1256. metadata=[email hidden][samples.integrated.filt$Genotype == "WT", ]
  1257. restab = table(GT_Treat = as.character(metadata$Genotype_Treatment), Peri_Ictal=metadata$Peri_ictus_binary)
  1258. restab
  1259. prop.table(restab, margin = 1)
  1260. fisher.test(restab)
  1261. ggplot(as.data.frame(restab),
  1262. aes(fill=Peri_Ictal, x=GT_Treat, y=Freq))+
  1263. geom_bar(position="fill", color="black",stat="identity")+theme_classic()
  1264. ```
  1265. # DEG comparing conditions overall
  1266. ## WT Stroke vs no Stroke
  1267. avg_logFC: log fold-chage of the average expression between the two groups. Positive values indicate that the gene is more highly expressed in the first group
  1268. ```{r, fig.width=6, fig.height=6}
  1269. genes_to_label <- openxlsx::read.xlsx("/files/scSeq_Hefendehl/data/Volcano pot labels on graph.xlsx",
  1270. sheet = "Wildtype control vs Wildtype st")
  1271. genes_to_label <- c(genes_to_label$Up, genes_to_label$Down)
  1272. Idents(samples.integrated.filt) <- "Genotype_Treatment"
  1273. DimPlot(samples.integrated.filt, reduction="umap")
  1274. DEG_Wt_CtrlvsStroke <-FindMarkers(samples.integrated.filt,
  1275. ident.1 = "WT_Stroke", ident.2 = "WT_Ctrl",
  1276. assay = "RNA", slot = "data",
  1277. test.use = "wilcox", logfc.threshold = 0)
  1278. genes_to_label[!genes_to_label %in% rownames(DEG_Wt_CtrlvsStroke)]
  1279. ```
  1280. ```{r, fig.width=6, fig.height=6}
  1281. p = EnhancedVolcano::EnhancedVolcano(DEG_Wt_CtrlvsStroke,
  1282. x = "avg_log2FC",
  1283. y = "p_val_adj",
  1284. pCutoff=0.05,
  1285. lab=rownames(DEG_Wt_CtrlvsStroke),
  1286. selectLab = genes_to_label,
  1287. title = "WT_Ctrl vs WT_Stroke")
  1288. display_tab(DEG_Wt_CtrlvsStroke)
  1289. p
  1290. write.xlsx(DEG_Wt_CtrlvsStroke, file = paste0(outputdir, "Microglia_DEX_WTCtrlvsWTStroke_integrated.xlsx"),rowNames = TRUE)
  1291. ggsave(filename = paste0(outputdir, "Microglia_Volcano_WTCtrlvsWTStroke_integrated.pdf"), p)
  1292. ```
  1293. ## APPPS1 Stroke vs APPPS1 no Stroke
  1294. avg_logFC: log fold-chage of the average expression between the two groups. Positive values indicate that the gene is more highly expressed in the first group
  1295. ```{r fig.width=6, fig.height=6}
  1296. genes_to_label <- openxlsx::read.xlsx("/files/scSeq_Hefendehl/data/Volcano pot labels on graph.xlsx",
  1297. sheet = "APPPS1 control Vs APPPS1 stroke")
  1298. genes_to_label <- c(genes_to_label$Up, genes_to_label$Down)
  1299. DEG_APPPS1_CtrlvsStroke <-FindMarkers(samples.integrated.filt,
  1300. ident.1 = "APPPS1_Stroke", ident.2 = "APPPS1_Ctrl",
  1301. assay = "RNA", slot = "data",
  1302. test.use = "wilcox", logfc.threshold = 0)
  1303. display_tab(DEG_APPPS1_CtrlvsStroke)
  1304. genes_to_label[!genes_to_label %in% rownames(DEG_APPPS1_CtrlvsStroke)]
  1305. p<- EnhancedVolcano::EnhancedVolcano(DEG_APPPS1_CtrlvsStroke,
  1306. x = "avg_log2FC",
  1307. y = "p_val_adj",
  1308. lab=rownames(DEG_APPPS1_CtrlvsStroke),
  1309. selectLab = genes_to_label,
  1310. pCutoff = 0.05,
  1311. title = "APPPS1_Ctrl vs APPPS1_Stroke")
  1312. p
  1313. write.xlsx(DEG_APPPS1_CtrlvsStroke, file = paste0(outputdir, "Microglia_DEX_APPPS1CtrlvsAPPPS1Stroke_integrated.xlsx"),rowNames = TRUE)
  1314. ggsave(filename = paste0(outputdir, "Microglia_Volcano_APPPS1CtrlvsAPPPS1Stroke_integrated.pdf"), p)
  1315. ```
  1316. ## WT Stroke vs APPPS1Stroke
  1317. ```{r fig.width=6, fig.height=6}
  1318. # plot here only DAM markers
  1319. genes_to_label <- unique(c(DAM_up, DAM1_down, DAM1_up, DAM1vsDAM2, DAM2_up))
  1320. DEG_Stroke_APPPS1vsWT <-FindMarkers(samples.integrated.filt,
  1321. ident.1 = "APPPS1_Stroke", ident.2 = "WT_Stroke",
  1322. assay = "RNA", slot = "data",
  1323. test.use = "wilcox", logfc.threshold = 0)
  1324. display_tab(DEG_Stroke_APPPS1vsWT)
  1325. genes_to_label[!genes_to_label %in% rownames(DEG_Stroke_APPPS1vsWT)]
  1326. p<- EnhancedVolcano::EnhancedVolcano(DEG_Stroke_APPPS1vsWT,
  1327. x = "avg_log2FC",
  1328. y = "p_val_adj",
  1329. lab=rownames(DEG_Stroke_APPPS1vsWT),
  1330. selectLab = genes_to_label,
  1331. pCutoff = 0.05,
  1332. title = "WT_stroke vs APPPS1_Stroke")
  1333. p
  1334. write.xlsx(DEG_Stroke_APPPS1vsWT, file = paste0(outputdir, "Microglia_DEX_Stroke_APPPS1vsWT_integrated.xlsx"),rowNames = TRUE)
  1335. ggsave(filename = paste0(outputdir, "Microglia_Volcano_WTstrokevsAPPPS1StrokeDAMgenes_integrated.pdf"), p)
  1336. ```
  1337. ## WT ctr; vs APPPS1 ctrl
  1338. avg_logFC: log fold-chage of the average expression between the two groups. Positive values indicate that the gene is more highly expressed in the first group
  1339. ```{r fig.width=6, fig.height=6}
  1340. genes_to_label <- openxlsx::read.xlsx("/files/scSeq_Hefendehl/data/Volcano pot labels on graph.xlsx",
  1341. sheet = "Wild type control Vs APPPS1 con")
  1342. genes_to_label <- c(genes_to_label$Up, genes_to_label$Down)
  1343. DEG_APPPS1_CtrlvsWT_Ctrl <-FindMarkers(samples.integrated.filt,
  1344. ident.1 = "APPPS1_Ctrl", ident.2 = "WT_Ctrl",
  1345. assay = "RNA", slot = "data",
  1346. test.use = "wilcox", logfc.threshold = 0)
  1347. display_tab(DEG_APPPS1_CtrlvsWT_Ctrl)
  1348. genes_to_label[!genes_to_label %in% rownames(DEG_APPPS1_CtrlvsWT_Ctrl)]
  1349. p<- EnhancedVolcano::EnhancedVolcano(DEG_APPPS1_CtrlvsWT_Ctrl,
  1350. x = "avg_log2FC",
  1351. y = "p_val_adj",
  1352. lab=rownames(DEG_APPPS1_CtrlvsWT_Ctrl),
  1353. selectLab = genes_to_label,
  1354. pCutoff = 0.05,
  1355. title = "WT_Ctrl vs APPPS1_Ctrl")
  1356. p
  1357. write.xlsx(DEG_APPPS1_CtrlvsWT_Ctrl, file = paste0(outputdir, "Microglia_DEX_APPPS1_CtrlvsWT_Ctrl_integrated.xlsx"),rowNames = TRUE)
  1358. ggsave(filename = paste0(outputdir, "Microglia_Volcano_WTCtrlvsAPPPS1ctrl_integrated.pdf"), p)
  1359. ```
  1360. ## Scatterplot of DEGs of all four conditions
  1361. ```{r}
  1362. genelist_both= intersect(rownames(DEG_Wt_CtrlvsStroke), rownames(DEG_APPPS1_CtrlvsStroke))
  1363. plotdata=data.frame(log2FC_WTCtrl_vs_WTStroke=DEG_Wt_CtrlvsStroke[genelist_both,]$avg_log2FC,
  1364. padj_WTCtrl_vs_WTStroke=DEG_Wt_CtrlvsStroke[genelist_both,]$p_val,
  1365. log2FC_APPPS1Ctrl_vs_APPPS1Stroke = DEG_APPPS1_CtrlvsStroke[genelist_both,]$avg_log2FC,
  1366. padj_APPPS1Ctrl_vs_APPPS1Stroke = DEG_APPPS1_CtrlvsStroke[genelist_both,]$p_val) %>%
  1367. mutate(
  1368. collab=ifelse((padj_WTCtrl_vs_WTStroke < 0.05) & (padj_APPPS1Ctrl_vs_APPPS1Stroke < 0.05), "Both",
  1369. ifelse((padj_WTCtrl_vs_WTStroke > 0.05) & (padj_APPPS1Ctrl_vs_APPPS1Stroke < 0.05), "APPPS1Stroke",
  1370. ifelse((padj_WTCtrl_vs_WTStroke < 0.05) & (padj_APPPS1Ctrl_vs_APPPS1Stroke > 0.05), "WTStroke", NA)))
  1371. )
  1372. rownames(plotdata) = genelist_both
  1373. plotdata$label = rownames(plotdata)
  1374. # the next lines plot the top 20 genes of either analyses
  1375. n=20
  1376. plotdata$label[! c(1:nrow(plotdata)) %in% c(
  1377. order(abs(plotdata$log2FC_WTCtrl_vs_WTStroke), decreasing = T)[1:n],
  1378. order(abs(plotdata$log2FC_APPPS1Ctrl_vs_APPPS1Stroke), decreasing = T)[1:n])]=""
  1379. #if you execute the next two lines the labels you choose will be plotted
  1380. # to execute set FALSE to TRUE and change the list of gene names
  1381. if(TRUE){
  1382. genestoplot = c("S100a6", "Apoc4", "C4b", "Atp1a2", "Apoc1", "Fn1","Ntrk2")
  1383. print(paste0(genestoplot[! genestoplot %in% rownames(plotdata)], " cannot be found"))
  1384. plotdata$label[! rownames(plotdata) %in% genestoplot] = ""
  1385. }
  1386. ```
  1387. ```{r}
  1388. plotdata <- plotdata %>%
  1389. arrange(desc(is.na(collab)))
  1390. p <- ggplot(plotdata, aes(x=log2FC_WTCtrl_vs_WTStroke, y=log2FC_APPPS1Ctrl_vs_APPPS1Stroke, label=label))+
  1391. geom_point(aes(colour = collab), alpha=0.7)+
  1392. geom_text_repel(box.padding = 0.5, max.overlaps = Inf, color="black")+
  1393. scale_color_discrete(palette=c( "#56B4E9", "#009E73","#F0E442"))+
  1394. #geom_abline(slope=-1, intercept=0, lty=2)+geom_abline(slope=1, intercept=0, lty=2)+
  1395. theme_classic()+ggtitle("log_FC")
  1396. p
  1397. ggsave(filename = paste0(outputdir, "Microglia_logFCCtrlvsStroke_APPPS1vsWT_all_integrated.pdf"), p)
  1398. ```
  1399. ```{r, fig.width=9, fig.height=7}
  1400. # sig only
  1401. genelist_both=
  1402. unique(c(rownames(DEG_Wt_CtrlvsStroke %>% dplyr::filter(p_val<0.05 & abs(avg_log2FC)>0.5)),
  1403. rownames(DEG_APPPS1_CtrlvsStroke%>% dplyr::filter(p_val<0.05 & abs(avg_log2FC)>0.5))))
  1404. plotdata=data.frame(log2FC_WTCtrl_vs_WTStroke=DEG_Wt_CtrlvsStroke[genelist_both,]$avg_log2FC,
  1405. padj_WTCtrl_vs_WTStroke=DEG_Wt_CtrlvsStroke[genelist_both,]$p_val,
  1406. log2FC_APPPS1Ctrl_vs_APPPS1Stroke = DEG_APPPS1_CtrlvsStroke[genelist_both,]$avg_log2FC,
  1407. padj_APPPS1Ctrl_vs_APPPS1Stroke = DEG_APPPS1_CtrlvsStroke[genelist_both,]$p_val) %>%
  1408. mutate(
  1409. collab=ifelse((padj_WTCtrl_vs_WTStroke < 0.05) & (padj_APPPS1Ctrl_vs_APPPS1Stroke < 0.05), "Both",
  1410. ifelse((padj_WTCtrl_vs_WTStroke > 0.05) & (padj_APPPS1Ctrl_vs_APPPS1Stroke < 0.05), "APPPS1Stroke",
  1411. ifelse((padj_WTCtrl_vs_WTStroke < 0.05) & (padj_APPPS1Ctrl_vs_APPPS1Stroke > 0.05), "WTStroke", NA)))
  1412. )
  1413. rownames(plotdata) = genelist_both
  1414. plotdata$label = rownames(plotdata)
  1415. #if you execute the next lines the labels you choose will be plotted
  1416. # if set to TRUE, change the list of gene names and they will be plotted
  1417. # if set to FALSE the top n=15 of both will be plotted
  1418. mode = "both" # alternative "selected" or "topN" or "both"
  1419. genestoplot = c("S100a6", "Apoc4", "C4b", "Atp1a2", "Apoc1", "Fn1","Ntrk2") # name here your gene of interest
  1420. topn = 15 # name the top number of genes to be plotted
  1421. ### don't change anything below the line here
  1422. plotdata$label = rownames(plotdata)
  1423. if(mode=="selected"){
  1424. print(paste0(genestoplot[! genestoplot %in% rownames(plotdata)], " cannot be found"))
  1425. plotdata$label[which(! rownames(plotdata) %in% genestoplot)] = ""
  1426. } else if (mode=="topN"){
  1427. n=topn
  1428. genestoplotn15 <-c(1:nrow(plotdata)) %in%
  1429. c(
  1430. order(abs(plotdata$log2FC_WTCtrl_vs_WTStroke), decreasing = T)[1:n],
  1431. order(abs(plotdata$log2FC_APPPS1Ctrl_vs_APPPS1Stroke), decreasing = T)[1:n])
  1432. plotdata$label[!genestoplotn15]=""
  1433. } else if (mode =="both") {
  1434. print(paste0(genestoplot[! genestoplot %in% rownames(plotdata)], " cannot be found"))
  1435. genestoplotcmbn <-(c(1:nrow(plotdata)) %in%
  1436. c(
  1437. order(abs(plotdata$log2FC_WTCtrl_vs_WTStroke), decreasing = T)[1:n],
  1438. order(abs(plotdata$log2FC_APPPS1Ctrl_vs_APPPS1Stroke), decreasing = T)[1:n])) | (rownames(plotdata) %in% genestoplot)
  1439. plotdata$label[which(! genestoplotcmbn)] = ""
  1440. }
  1441. ```
  1442. ```{r, fig.width=9, fig.height=7}
  1443. p <- ggplot(plotdata, aes(x=log2FC_WTCtrl_vs_WTStroke, y=log2FC_APPPS1Ctrl_vs_APPPS1Stroke, label=label))+
  1444. geom_point(aes(colour = collab), alpha=0.7)+
  1445. geom_text_repel(box.padding = 0.5, max.overlaps = Inf,
  1446. color="black")+
  1447. scale_color_discrete(palette=c( "#56B4E9", "#009E73","#F0E442"))+
  1448. #geom_abline(slope=-1, intercept=0, lty=2)+geom_abline(slope=1, intercept=0, lty=2)+
  1449. theme_classic()+ggtitle("log_FC")
  1450. p
  1451. ggsave(filename = paste0(outputdir, "Microglia_logFCCtrlvsStroke_APPPS1vsWT_sig_only_integrated.pdf"), p)
  1452. ```
  1453. ```{r fig.width=8, fig.height=8}
  1454. reads_data = JoinLayers(samples.integrated.filt, assay = "RNA") %>%
  1455. GetAssayData(assay = "RNA", layer="data") # loaded data as used above
  1456. #reads_data = samples.integrated.filt@assays$RNA@counts # Raw counts/reads
  1457. #reads_data = samples.integrated.filt@assays$[email hidden] #scaled/reads
  1458. barplot_genes = function(gene, split.by =T){
  1459. require(ggbeeswarm)
  1460. plotdata = data.frame(log2Reads = log2(reads_data[gene,]+1),
  1461. Genotype_Treatment = [email hidden]$Genotype_Treatment,
  1462. Cluster = [email hidden]$labels)
  1463. if(split.by=="none" | split.by=="cluster") {
  1464. p=ggplot(plotdata, aes(x=Genotype_Treatment, y=log2Reads, fill=Genotype_Treatment))+
  1465. geom_violin()+
  1466. geom_beeswarm(alpha=0.4, method = "hex")+ggtitle(gene)+theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
  1467. if(split.by=="cluster"){p=p+facet_wrap(~Cluster)}
  1468. } else if (split.by=="Microglia") {
  1469. p=ggplot(plotdata, aes(x=Cluster, y=log2Reads, fill=Cluster))+
  1470. geom_violin()+
  1471. geom_beeswarm(alpha=0.4, method = "hex")+
  1472. ggtitle(gene)+
  1473. theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
  1474. }
  1475. p
  1476. }
  1477. barplot_genes(gene="Ptprc", split.by ="cluster") # alternative split.by = "none" oder " Micorglia
  1478. barplot_genes(gene="Ptprc", split.by ="none") # just across the genotype_treatments
  1479. barplot_genes(gene="Ptprc", split.by ="Microglia") # add +coord_cartesian(ylim=c(0, 7)) if you want to change the ylims
  1480. barplot_genes(gene="Ptprc", split.by ="Microglia")+coord_cartesian(ylim=c(0, 2))
  1481. barplot_genes(gene="Ptprc", split.by ="Microglia") + facet_wrap(~Genotype_Treatment)
  1482. FeaturePlot_scCustom(samples.integrated.filt, features = sort(genestoplot), reduction="umap", colors_use = viridis_dark_high)
  1483. ```
  1484. ## DEG Stroke Cells only
  1485. ```{r, eval=FALSE}
  1486. DEG_Strokebins_Wt_CtrlvsStroke <-FindMarkers(samples.integrated.filt, subset.ident = "Stroke_bin", subset="TRUE",
  1487. assay = "RNA", slot = "data",
  1488. ident.1 = "WT_Stroke", ident.2 = "WT_Ctrl",
  1489. test.use = "wilcox", logfc.threshold = 0)
  1490. display_tab(DEG_Strokebins_Wt_CtrlvsStroke)
  1491. DEG_Strokebins_Appps1_CtrlvsStroke <-FindMarkers(samples.integrated.filt, subset.ident = "Stroke_bin", subset="TRUE",
  1492. assay = "RNA", slot = "data",
  1493. ident.1 = "APPPS1_Stroke", ident.2 = "APPPS1_Ctrl",
  1494. test.use = "wilcox", logfc.threshold = 0)
  1495. display_tab(DEG_Strokebins_Appps1_CtrlvsStroke)
  1496. genelist_both= intersect(rownames(DEG_Strokebins_Appps1_CtrlvsStroke), rownames(DEG_Strokebins_Wt_CtrlvsStroke))
  1497. plotdata=data.frame(WT=DEG_Strokebins_Wt_CtrlvsStroke[genelist_both,]$avg_log2FC, APPPS1 = DEG_Strokebins_Appps1_CtrlvsStroke[genelist_both,]$avg_log2FC)
  1498. rownames(plotdata) = genelist_both
  1499. plotdata$label = rownames(plotdata)
  1500. n=5
  1501. plotdata$label[! c(1:nrow(plotdata)) %in%
  1502. c(
  1503. order(abs(plotdata$WT), decreasing = T)[1:n],
  1504. order(abs(plotdata$APPPS1), decreasing = T)[1:n])]=""
  1505. plotdata$col="WT"
  1506. apps1=abs(plotdata$APPPS1)>abs(plotdata$WT)
  1507. plotdata$col[ apps1]="APPPS1"
  1508. plotdata$col[(abs(plotdata$APPPS1)<0.25) & (abs(plotdata$WT)<0.25)] <- NA
  1509. ggplot(plotdata, aes(x=WT, y=APPPS1, color=col, label=label))+geom_point(alpha=0.7)+
  1510. geom_text(vjust=-0.7, color="black")+geom_abline(slope=-1, intercept=0, lty=2)+geom_abline(slope=1, intercept=0, lty=2)+theme_classic()+ggtitle("log_FC_Stroke_bins")
  1511. ```
  1512. ## DEG comparing Cluster
  1513. All Clusters versus All Genes versus all Conditions
  1514. ### Define Main analysis pipeline
  1515. ```{r}
  1516. compareCluster <- function(
  1517. ClusterA = "Microglia6",
  1518. ClusterB = "Microglia0",
  1519. seuratObject = samples.integrated.filt,
  1520. output = "./",
  1521. genelist = NULL,
  1522. FCcutoff = 1,
  1523. comorbid = FALSE,
  1524. evgenecode=F
  1525. ) {
  1526. # ensure output exists
  1527. if (!dir.exists(output)) dir.create(outputdir, recursive = TRUE)
  1528. # name + logfile ALWAYS defined
  1529. resname <- if (isTRUE(comorbid)) {
  1530. paste0(ClusterA, "vs", ClusterB, "_comorbid")
  1531. } else {
  1532. paste0(ClusterA, "vs", ClusterB)
  1533. }
  1534. logfile <- file.path(output, paste0("log_", resname, ".txt"))
  1535. if (file.exists(logfile)) file.remove(logfile)
  1536. # helper to append to log
  1537. log_line <- function(level, msg) {
  1538. cat(
  1539. paste0(
  1540. format(Sys.time(), "%Y-%m-%d %H:%M:%S"),
  1541. " | ", level,
  1542. " | ", ClusterA, " vs ", ClusterB,
  1543. " | ", msg, "\n"
  1544. ),
  1545. file = logfile,
  1546. append = TRUE
  1547. )
  1548. }
  1549. # FindMarkers call (different args if comorbid)
  1550. DEG_tmp <- tryCatch(
  1551. withCallingHandlers(
  1552. {
  1553. if (isTRUE(comorbid)) {
  1554. FindMarkers(
  1555. seuratObject,
  1556. assay = "RNA",
  1557. subset.ident = "Genotype_Treatment",
  1558. subset = "APPPS1_Stroke",
  1559. layer = "data",
  1560. ident.1 = ClusterA, ident.2 = ClusterB,
  1561. test.use = "wilcox", logfc.threshold = 0
  1562. )
  1563. } else {
  1564. FindMarkers(
  1565. seuratObject,
  1566. assay = "RNA",
  1567. layer = "data",
  1568. ident.1 = ClusterA, ident.2 = ClusterB,
  1569. test.use = "wilcox", logfc.threshold = 0
  1570. )
  1571. }
  1572. },
  1573. warning = function(w) {
  1574. log_line("WARNING", conditionMessage(w))
  1575. invokeRestart("muffleWarning")
  1576. }
  1577. ),
  1578. error = function(e) {
  1579. log_line("ERROR", conditionMessage(e))
  1580. return(NULL)
  1581. }
  1582. )
  1583. # If FindMarkers failed, still return log + empty slots
  1584. if (is.null(DEG_tmp)) {
  1585. return(list(
  1586. Markers = NULL,
  1587. VulcanoPlot = NULL,
  1588. qqplot = NULL,
  1589. Goresults = NULL,
  1590. GOplots = NULL,
  1591. log = logfile
  1592. ))
  1593. }
  1594. openxlsx::write.xlsx(
  1595. DEG_tmp %>% dplyr::filter(p_val_adj<0.1),
  1596. file = file.path(output, paste0("DEG_Gene_list_", resname, ".xlsx")),
  1597. rowNames = TRUE
  1598. )
  1599. # label genes that actually exist in DEG table
  1600. genes_to_label2 <- intersect(genelist, rownames(DEG_tmp))
  1601. q <- gg_qqplot(DEG_tmp$p_val)
  1602. p <- EnhancedVolcano::EnhancedVolcano(
  1603. DEG_tmp,
  1604. x = "avg_log2FC",
  1605. y = "p_val_adj",
  1606. lab = rownames(DEG_tmp),
  1607. selectLab = genes_to_label2,
  1608. pCutoff = 0.05,
  1609. title = resname
  1610. )
  1611. ggsave(
  1612. filename = file.path(output, paste0("DEG_Vulcano_", resname, "_integrated.pdf")),
  1613. plot = (p | q),
  1614. width = 10, height = 5
  1615. )
  1616. gene_univers <- rownames(seuratObject)
  1617. gogenes <- list(
  1618. genesigall = rownames(DEG_tmp)[DEG_tmp$p_val_adj < 0.05 & abs(DEG_tmp$avg_log2FC) > FCcutoff],
  1619. genesigup = rownames(DEG_tmp)[DEG_tmp$p_val_adj < 0.05 & DEG_tmp$avg_log2FC > FCcutoff],
  1620. genesigdown = rownames(DEG_tmp)[DEG_tmp$p_val_adj < 0.05 & DEG_tmp$avg_log2FC < -FCcutoff]
  1621. )
  1622. Gores <- getGOresults(
  1623. geneset = gogenes,
  1624. domain_scope = "known",
  1625. genereference = gene_univers,
  1626. return_genelist = evgenecode,
  1627. organism = "mmusculus"
  1628. )
  1629. openxlsx::write.xlsx(
  1630. Gores$result %>% dplyr::select(-parents),
  1631. file = file.path(output, paste0("DEG_GOlist_", resname, ".xlsx")),
  1632. rowNames = TRUE
  1633. )
  1634. plotlist <- list()
  1635. for (m in unique(Gores$result$query)) {
  1636. idx <- Gores$result$query == m & grepl("GO", Gores$result$source)
  1637. if (sum(idx) >= 1) {
  1638. plotlist[[m]] <- GOplot(Gores$result[idx, ], N = 10, Title = m)
  1639. } else {
  1640. plotlist[[m]] <- ggplot() +
  1641. annotate(
  1642. "text", x = 10, y = 10, size = 6,
  1643. label = "no significant GO term\ncheck excel sheet for other enrichments"
  1644. ) +
  1645. theme_void() +
  1646. ggtitle(m)
  1647. }
  1648. }
  1649. ggsave(
  1650. filename = file.path(output, paste0("DEG_GO_plots_", resname, ".pdf")),
  1651. plot = ggarrange(plotlist = plotlist),
  1652. width = 10, height = 5
  1653. )
  1654. return(list(
  1655. Markers = DEG_tmp,
  1656. VulcanoPlot = p,
  1657. qqplot = q,
  1658. Goresults = Gores$result,
  1659. GOplots = plotlist,
  1660. log = logfile
  1661. ))
  1662. }
  1663. ```
  1664. ### DEG run for each combination
  1665. ```{r, warning=FALSE, message=FALSE}
  1666. if(T){
  1667. Idents(samples.integrated.filt) <- "labels"
  1668. labels_unique = sort(unique(samples.integrated.filt$labels))
  1669. label_pairs <- combn(labels_unique, 2, simplify = FALSE)
  1670. results_list <- list()
  1671. for (pair in label_pairs) {
  1672. print(paste(pair, collapse = "_vs_"))
  1673. print("all")
  1674. res <- compareCluster(
  1675. ClusterA = pair[1],
  1676. ClusterB = pair[2],
  1677. FCcutoff = 0.5,
  1678. output = outputdir,
  1679. genelist = genes_to_label
  1680. )
  1681. print("comorbid")
  1682. res_comorbid <- compareCluster(
  1683. ClusterA = pair[1],
  1684. ClusterB = pair[2],
  1685. FCcutoff = 0.5,
  1686. output = outputdir,
  1687. genelist = genes_to_label,
  1688. comorbid=T
  1689. )
  1690. results_list[[paste(pair, collapse = "_vs_")]] <- res
  1691. results_list[[paste0(paste(pair, collapse = "_vs_"),
  1692. "_comorbid")]] <- res_comorbid
  1693. }
  1694. }
  1695. ```
  1696. ```{r, results='asis', message=FALSE, warning=FALSE, fig.width=10, fig.height=5}
  1697. # results_list: named list where each element is res from compareCluster()
  1698. for (nm in names(results_list)) {
  1699. res <- results_list[[nm]]
  1700. cat("\n\n## ", nm, "\n\n", sep = "")
  1701. # --- 1) Volcano + QQ (patchwork-style)
  1702. # If you're using patchwork, this should work:
  1703. if (!is.null(res$VulcanoPlot) && !is.null(res$qqplot)) {
  1704. p1 <- res$VulcanoPlot | res$qqplot
  1705. print(p1)
  1706. } else {
  1707. cat("*No VulcanoPlot and/or qqplot found for this comparison.*\n\n")
  1708. }
  1709. # --- 2) GO plots (arranged)
  1710. if (!is.null(res$GOplots) && length(res$GOplots) > 0) {
  1711. p2 <- ggarrange(plotlist = res$GOplots, ncol = 2)
  1712. print(p2)
  1713. } else {
  1714. cat("*No GOplots found for this comparison.*\n\n")
  1715. }
  1716. # --- 3) Markers table
  1717. cat("\n\n### Markers\n\n")
  1718. if (!is.null(res$Markers) && nrow(res$Markers) > 0) {
  1719. print(kable(res$Markers %>% arrange(p_val) %>% slice_head(n = 100), format = "markdown"))
  1720. } else {
  1721. cat("*No markers found for this comparison.*\n\n")
  1722. }
  1723. }
  1724. ```
  1725. ### within cluster Wt vs WT Stroke
  1726. ```{r, results='asis', message=FALSE, warning=FALSE, fig.width=10, fig.height=5}
  1727. Idents(samples.integrated.filt) <- "Genotype_Treatment"
  1728. for(clust in unique(samples.integrated.filt$labels)){
  1729. print(clust)
  1730. FCcutoff = 0.5
  1731. resname=paste0(clust, "_WT_Ctrl_vs_WT_Stroke_")
  1732. DEG_tmp<- FindMarkers(samples.integrated.filt[,samples.integrated.filt$labels==clust],
  1733. assay = "RNA",
  1734. layer = "data",
  1735. ident.1 = "WT_Ctrl",
  1736. ident.2 = "WT_Stroke",
  1737. test.use = "wilcox", logfc.threshold = 0
  1738. )
  1739. res_sig <- DEG_tmp %>% dplyr::filter(p_val<0.05)
  1740. openxlsx::write.xlsx(res_sig,
  1741. file = file.path(outputdir, paste0("DEG_Gene_list_", resname, ".xlsx")),
  1742. rowNames = TRUE
  1743. )
  1744. q <- gg_qqplot(DEG_tmp$p_val)
  1745. p <- EnhancedVolcano::EnhancedVolcano(
  1746. DEG_tmp,
  1747. x = "avg_log2FC",
  1748. y = "p_val_adj",
  1749. lab = rownames(DEG_tmp),
  1750. selectLab = genes_to_label,
  1751. pCutoff = 0.05,
  1752. title = resname
  1753. )
  1754. ggsave(
  1755. filename = file.path(outputdir, paste0("DEG_Vulcano_", resname, "integrated.pdf")),
  1756. plot = (p | q),
  1757. width = 10, height = 5
  1758. )
  1759. gene_univers <- rownames(samples.integrated.filt)
  1760. gogenes <- list(
  1761. genesigall = rownames(DEG_tmp)[DEG_tmp$p_val_adj < 0.05 & abs(DEG_tmp$avg_log2FC) > FCcutoff],
  1762. genesigup = rownames(DEG_tmp)[DEG_tmp$p_val_adj < 0.05 & DEG_tmp$avg_log2FC > FCcutoff],
  1763. genesigdown = rownames(DEG_tmp)[DEG_tmp$p_val_adj < 0.05 & DEG_tmp$avg_log2FC < -FCcutoff]
  1764. )
  1765. if(any(lapply(gogenes, length)>0)){
  1766. Gores <- getGOresults(
  1767. geneset = gogenes,
  1768. domain_scope = "known",
  1769. genereference = gene_univers,
  1770. return_genelist = F,
  1771. organism = "mmusculus"
  1772. )
  1773. } else {
  1774. print("no significant genes identified")
  1775. Gores <- NULL
  1776. }
  1777. if(length(Gores)!=0){
  1778. openxlsx::write.xlsx(
  1779. Gores$result %>% dplyr::select(-parents),
  1780. file = file.path(outputdir, paste0("DEG_GOlist_", resname, ".xlsx")),
  1781. rowNames = TRUE
  1782. )
  1783. plotlist <- list()
  1784. for (m in unique(Gores$result$query)) {
  1785. idx <- Gores$result$query == m & grepl("GO", Gores$result$source)
  1786. if (sum(idx) >= 1) {
  1787. plotlist[[m]] <- GOplot(Gores$result[idx, ], N = 10, Title = m)
  1788. } else {
  1789. plotlist[[m]] <- ggplot() +
  1790. annotate(
  1791. "text", x = 10, y = 10, size = 6,
  1792. label = "no significant GO term\ncheck excel sheet for other enrichments"
  1793. ) +
  1794. theme_void() +
  1795. ggtitle(m)
  1796. }
  1797. }
  1798. ggsave(
  1799. filename = file.path(outputdir, paste0("DEG_GO_plots_", resname, ".pdf")),
  1800. plot = ggarrange(plotlist = plotlist),
  1801. width = 10, height = 5
  1802. ) } else {
  1803. openxlsx::write.xlsx(data.frame(resname="No results identified"),
  1804. file = file.path(outputdir, paste0("DEG_GOlist_", resname, ".xlsx")))
  1805. p <- ggplot() +
  1806. annotate(
  1807. "text", x = 10, y = 10, size = 6,
  1808. label = "no significant enrichments"
  1809. ) +
  1810. theme_void()
  1811. ggsave(
  1812. filename = file.path(outputdir, paste0("DEG_GO_plots_", resname, ".pdf")),
  1813. plot = p,
  1814. width = 10, height = 5
  1815. )
  1816. }
  1817. }
  1818. Idents(samples.integrated.filt) <- "labels"
  1819. ```
  1820. ### within cluster APPPS1_Stroke vs WT Stroke
  1821. ```{r, results='asis', message=FALSE, warning=FALSE, fig.width=10, fig.height=5}
  1822. Idents(samples.integrated.filt) <- "Genotype_Treatment"
  1823. for(clust in unique(samples.integrated.filt$labels)){
  1824. print(clust)
  1825. FCcutoff = 0.5
  1826. resname=paste0(clust, "_WT_stroke_vs_APPPS1_Stroke_")
  1827. DEG_tmp<- FindMarkers(samples.integrated.filt[,samples.integrated.filt$labels==clust],
  1828. assay = "RNA",
  1829. layer = "data",
  1830. ident.1 = "APPPS1_Stroke",
  1831. ident.2 = "WT_Stroke",
  1832. test.use = "wilcox", logfc.threshold = 0
  1833. )
  1834. res_sig <- DEG_tmp %>% dplyr::filter(p_val<0.05)
  1835. openxlsx::write.xlsx(res_sig,
  1836. file = file.path(outputdir, paste0("DEG_Gene_list_", resname, ".xlsx")),
  1837. rowNames = TRUE
  1838. )
  1839. q <- gg_qqplot(DEG_tmp$p_val)
  1840. p <- EnhancedVolcano::EnhancedVolcano(
  1841. DEG_tmp,
  1842. x = "avg_log2FC",
  1843. y = "p_val_adj",
  1844. lab = rownames(DEG_tmp),
  1845. selectLab = genes_to_label,
  1846. pCutoff = 0.05,
  1847. title = resname
  1848. )
  1849. ggsave(
  1850. filename = file.path(outputdir, paste0("DEG_Vulcano_", resname, "integrated.pdf")),
  1851. plot = (p | q),
  1852. width = 10, height = 5
  1853. )
  1854. gene_univers <- rownames(samples.integrated.filt)
  1855. gogenes <- list(
  1856. genesigall = rownames(DEG_tmp)[DEG_tmp$p_val_adj < 0.05 & abs(DEG_tmp$avg_log2FC) > FCcutoff],
  1857. genesigup = rownames(DEG_tmp)[DEG_tmp$p_val_adj < 0.05 & DEG_tmp$avg_log2FC > FCcutoff],
  1858. genesigdown = rownames(DEG_tmp)[DEG_tmp$p_val_adj < 0.05 & DEG_tmp$avg_log2FC < -FCcutoff]
  1859. )
  1860. if(any(lapply(gogenes, length)>0)){
  1861. Gores <- getGOresults(
  1862. geneset = gogenes,
  1863. domain_scope = "known",
  1864. genereference = gene_univers,
  1865. return_genelist = F,
  1866. organism = "mmusculus"
  1867. )
  1868. } else {
  1869. print("no significant genes identified")
  1870. Gores <- NULL
  1871. }
  1872. if(length(Gores)!=0){
  1873. openxlsx::write.xlsx(
  1874. Gores$result %>% dplyr::select(-parents),
  1875. file = file.path(outputdir, paste0("DEG_GOlist_", resname, ".xlsx")),
  1876. rowNames = TRUE
  1877. )
  1878. plotlist <- list()
  1879. for (m in unique(Gores$result$query)) {
  1880. idx <- Gores$result$query == m & grepl("GO", Gores$result$source)
  1881. if (sum(idx) >= 1) {
  1882. plotlist[[m]] <- GOplot(Gores$result[idx, ], N = 10, Title = m)
  1883. } else {
  1884. plotlist[[m]] <- ggplot() +
  1885. annotate(
  1886. "text", x = 10, y = 10, size = 6,
  1887. label = "no significant GO term\ncheck excel sheet for other enrichments"
  1888. ) +
  1889. theme_void() +
  1890. ggtitle(m)
  1891. }
  1892. }
  1893. ggsave(
  1894. filename = file.path(outputdir, paste0("DEG_GO_plots_", resname, ".pdf")),
  1895. plot = ggarrange(plotlist = plotlist),
  1896. width = 10, height = 5
  1897. ) } else {
  1898. openxlsx::write.xlsx(data.frame(resname="No results identified"),
  1899. file = file.path(outputdir, paste0("DEG_GOlist_", resname, ".xlsx")))
  1900. p <- ggplot() +
  1901. annotate(
  1902. "text", x = 10, y = 10, size = 6,
  1903. label = "no significant enrichments"
  1904. ) +
  1905. theme_void()
  1906. ggsave(
  1907. filename = file.path(outputdir, paste0("DEG_GO_plots_", resname, ".pdf")),
  1908. plot = p,
  1909. width = 10, height = 5
  1910. )
  1911. }
  1912. }
  1913. Idents(samples.integrated.filt) <- "labels"
  1914. ```
  1915. ### within cluster APPPS1 vs APPPS1 Stroke
  1916. ```{r, results='asis', message=FALSE, warning=FALSE, fig.width=10, fig.height=5}
  1917. Idents(samples.integrated.filt) <- "Genotype_Treatment"
  1918. for(clust in unique(samples.integrated.filt$labels)){
  1919. print(clust)
  1920. FCcutoff = 0.5
  1921. resname=paste0(clust, "_APPPS1_Stroke_vs_APPPS1_Ctrl_")
  1922. DEG_tmp<- FindMarkers(samples.integrated.filt[,samples.integrated.filt$labels==clust],
  1923. assay = "RNA",
  1924. subset.ident = "labels",
  1925. subset = clust,
  1926. layer = "data",
  1927. ident.1 = "APPPS1_Stroke", ident.2 = "APPPS1_Ctrl",
  1928. test.use = "wilcox", logfc.threshold = 0
  1929. )
  1930. res_sig <- DEG_tmp %>% dplyr::filter(p_val<0.05)
  1931. openxlsx::write.xlsx(res_sig,
  1932. file = file.path(outputdir, paste0("DEG_Gene_list_", resname, ".xlsx")),
  1933. rowNames = TRUE
  1934. )
  1935. q <- gg_qqplot(DEG_tmp$p_val)
  1936. p <- EnhancedVolcano::EnhancedVolcano(
  1937. DEG_tmp,
  1938. x = "avg_log2FC",
  1939. y = "p_val_adj",
  1940. lab = rownames(DEG_tmp),
  1941. selectLab = genes_to_label,
  1942. pCutoff = 0.05,
  1943. title = resname
  1944. )
  1945. ggsave(
  1946. filename = file.path(outputdir, paste0("DEG_Vulcano_", resname, "integrated.pdf")),
  1947. plot = (p | q),
  1948. width = 10, height = 5
  1949. )
  1950. gene_univers <- rownames(samples.integrated.filt)
  1951. gogenes <- list(
  1952. genesigall = rownames(DEG_tmp)[DEG_tmp$p_val_adj < 0.05 & abs(DEG_tmp$avg_log2FC) > FCcutoff],
  1953. genesigup = rownames(DEG_tmp)[DEG_tmp$p_val_adj < 0.05 & DEG_tmp$avg_log2FC > FCcutoff],
  1954. genesigdown = rownames(DEG_tmp)[DEG_tmp$p_val_adj < 0.05 & DEG_tmp$avg_log2FC < -FCcutoff]
  1955. )
  1956. if(any(lapply(gogenes, length)>0)){
  1957. Gores <- getGOresults(
  1958. geneset = gogenes,
  1959. domain_scope = "known",
  1960. genereference = gene_univers,
  1961. return_genelist = F,
  1962. organism = "mmusculus"
  1963. )
  1964. } else {
  1965. print("no significant genes identified")
  1966. Gores <- NULL
  1967. }
  1968. if(length(Gores)!=0){
  1969. openxlsx::write.xlsx(
  1970. Gores$result %>% dplyr::select(-parents),
  1971. file = file.path(outputdir, paste0("DEG_GOlist_", resname, ".xlsx")),
  1972. rowNames = TRUE
  1973. )
  1974. plotlist <- list()
  1975. for (m in unique(Gores$result$query)) {
  1976. idx <- Gores$result$query == m & grepl("GO", Gores$result$source)
  1977. if (sum(idx) >= 1) {
  1978. plotlist[[m]] <- GOplot(Gores$result[idx, ], N = 10, Title = m)
  1979. } else {
  1980. plotlist[[m]] <- ggplot() +
  1981. annotate(
  1982. "text", x = 10, y = 10, size = 6,
  1983. label = "no significant GO term\ncheck excel sheet for other enrichments"
  1984. ) +
  1985. theme_void() +
  1986. ggtitle(m)
  1987. }
  1988. }
  1989. ggsave(
  1990. filename = file.path(outputdir, paste0("DEG_GO_plots_", resname, ".pdf")),
  1991. plot = ggarrange(plotlist = plotlist),
  1992. width = 10, height = 5
  1993. ) } else {
  1994. openxlsx::write.xlsx(data.frame(resname="No results identified"),
  1995. file = file.path(outputdir, paste0("DEG_GOlist_", resname, ".xlsx")))
  1996. p <- ggplot() +
  1997. annotate(
  1998. "text", x = 10, y = 10, size = 6,
  1999. label = "no significant enrichments"
  2000. ) +
  2001. theme_void()
  2002. ggsave(
  2003. filename = file.path(outputdir, paste0("DEG_GO_plots_", resname, ".pdf")),
  2004. plot = p,
  2005. width = 10, height = 5
  2006. )
  2007. }
  2008. }
  2009. Idents(samples.integrated.filt) <- "labels"
  2010. ```
  2011. ```{r}
  2012. rm(list=c("seuratObject", "sce.filt", "reads", "reads_data", "comb",
  2013. "ref.sce.mm",
  2014. "e2",
  2015. "res",
  2016. "res_comorbid",
  2017. "samples.integrated"))
  2018. gc()
  2019. ```
  2020. # Pseudotime analysis
  2021. ## slinghsot starting Microglia 0
  2022. ```{r, fig.width==7, fig.height=7}
  2023. samples.integrated.filt.meta = [email hidden] %>% dplyr::select(- contains("Pseudo"))
  2024. [email hidden] <- samples.integrated.filt.meta
  2025. sce.microglia <- as.SingleCellExperiment(samples.integrated.filt, assay = "RNA")
  2026. sce.microglia <- slingshot(sce.microglia,
  2027. clusterLabels = 'labels',
  2028. reducedDim = 'UMAP',
  2029. start.clus="Microglia0",
  2030. end.clus=c("Microglia3", "Microglia4", "Microglia5"),
  2031. omega=T,
  2032. omega_scale=4,
  2033. extend="n")
  2034. pt_col <- grep("slingPseudotime", names(colData(sce.microglia)), value = TRUE)
  2035. metasce <- data.frame(colData(sce.microglia)[,pt_col],
  2036. row.names = rownames(colData(sce.microglia)))
  2037. colnames(metasce) <- pt_col
  2038. samples.integrated.filt.meta <- cbind(samples.integrated.filt.meta,metasce)
  2039. samples.integrated.filt.meta -> [email hidden]
  2040. dataset = data.frame(reducedDim(sce.microglia, "UMAP"),
  2041. cluster = as.character(sce.microglia$labels),
  2042. DAMs = as.character(sce.microglia$DAM_binary))
  2043. curves <- slingCurves(sce.microglia, as.df=T)
  2044. p = ggplot(dataset, aes(x=umap_1, y=umap_2))+
  2045. geom_point(aes(col = cluster), size=2)+
  2046. geom_point(data=subset(dataset, dataset$DAMs==T), aes(fill=DAMs), pch=21, size=0.7)+
  2047. scale_fill_manual(values="black")
  2048. curves = curves %>% arrange(Lineage, Order)
  2049. p = p + geom_path(data = curves, aes(group = Lineage), lwd=1, lineend = "butt",)+theme_classic()
  2050. curves_arrows = curves %>% group_by(Lineage) %>% mutate(xend = lead(umap_1), yend = lead(umap_2))
  2051. curves_arrows = curves_arrows[curves_arrows$Order %in% seq(10,150, by=floor((150-10)/10)),]
  2052. p = p + geom_segment(data = curves_arrows,
  2053. aes(x = umap_1, y = umap_2, xend = xend, yend = yend),
  2054. linewidth=0.5,
  2055. arrow = arrow(length=unit(0.3, "cm"), type="closed"))
  2056. p
  2057. ggsave(filename = paste0(outputdir, "Pseudotime_linages_startMicroglia0_integrated.pdf"), p)
  2058. write_rds(p, paste0(outputdir, "Pseudotime_linages_startMicroglia0_integrated.rds"))
  2059. ```
  2060. ```{r}
  2061. library(TSCAN)
  2062. n.top.gene = 10
  2063. tscan_res <- list()
  2064. for (pt in pt_col){
  2065. print(pt)
  2066. tscan_res [[pt]]<- testPseudotime(sce.microglia, pseudotime = sce.microglia[[pt]])
  2067. }
  2068. ```
  2069. Look for genes that are up/down-regulated along pseudotime, for the re-clustered cells (Same paper Fig 2G/H)
  2070. ## Trajectory genes
  2071. By default, estimates of the spline coefficients are not returned as they are difficult to interpret. Rather, a log-fold change of expression along each path is estimated to provide some indication of the overall magnitude and direction of any change.
  2072. ```{r}
  2073. reslist <- list()
  2074. reslist_feat <- list()
  2075. for (pt in names(tscan_res)){
  2076. scePT <- tscan_res[[pt]]
  2077. scePT<- scePT[order(scePT$FDR, decreasing = F),]
  2078. display_tab(as.data.frame(scePT)[1:20,])
  2079. reslist_feat[[pt]] <- FeaturePlot_scCustom(samples.integrated.filt, features = pt, reduction = "umap", colors_use = viridis_dark_high)
  2080. write.xlsx(as.data.frame(scePT), rowNames = TRUE,
  2081. file = paste0(outputdir, pt, "_genes.xslx"))
  2082. PT1_up = scePT[scePT$logFC>0,]
  2083. PT1_low = scePT[scePT$logFC<0,]
  2084. p <- scater::plotExpression(sce.microglia, features=rownames(PT1_up)[1:n.top.gene], x=pt, colour_by="labels")+scale_color_hue() + ggtitle(paste(pt, "up reg"))
  2085. p2 <- scater::plotExpression(sce.microglia, features=rownames(PT1_low)[1:n.top.gene], x=pt, colour_by="labels")+scale_color_hue()+ ggtitle(paste(pt, "down reg"))
  2086. reslist[[pt]]=p|p2
  2087. }
  2088. ```
  2089. ```{r, fig.height=15, fig.width=36}
  2090. a <- ggarrange(plotlist = reslist)
  2091. a
  2092. ggsave(filename = paste0(outputdir, "Pseudotime_Top10up_down_reg_Genes-correct_integrated.pdf"), a)
  2093. ```
  2094. ```{r, fig.height=8, fig.width=10}
  2095. a <- ggarrange(plotlist = reslist_feat)
  2096. a
  2097. ggsave(filename = paste0(outputdir, "Pseudotime_Umap_Genes-correct_integrated.pdf"), a)
  2098. ```
  2099. # WGCNA
  2100. In the paper <https://www.nature.com/articles/s41586-018-0023-4> this analysis was used to generate different modules of gene lists that can then be mapped onto different treatment/genotypes within one experiment (see Figure 4). This is an analysis that can be done in Seurat <https://smorabit.github.io/tutorials/9_scWGCNA_tutorial/> Which could be very cool for our data. In the paper they also have 3 different conditions in 2 genotypes.
  2101. avoid running this section as it takes very long
  2102. ```{r}
  2103. nclusters <- length(unique(samples.integrated.filt$labels))
  2104. genes.use <- rownames(samples.integrated.filt)
  2105. targets <- [email hidden]
  2106. group <- as.factor(samples.integrated.filt$Genotype_Treatment)
  2107. ```
  2108. ```{r fig.width=8, fig.height=6}
  2109. force.recalc = T
  2110. powers = c(seq(1,10,by=1), seq(12,20, by=2));
  2111. # skips recalculation of net object as it takes long...
  2112. reads <- JoinLayers(samples.integrated.filt, assay = "RNA") %>% GetAssayData(assay = "RNA", layer="data")
  2113. datExpr <- as.data.frame(reads[genes.use,])
  2114. rm("reads")
  2115. datExpr <- as.data.frame(t(datExpr))
  2116. datExpr <- datExpr[,goodGenes(datExpr)]
  2117. # expressed in more than 10% of cells
  2118. exprgenes = colSums(datExpr>0)>nrow(datExpr)*0.1
  2119. datExpr <- datExpr[,exprgenes]
  2120. #annotated only
  2121. mmacc=as.list(org.Mm.egALIAS2EG)
  2122. annotatedgenes = colnames(datExpr) %in% names(mmacc)
  2123. datExpr <- datExpr[,annotatedgenes]
  2124. powers = c(seq(1,10,by=1), seq(12,20, by=2));
  2125. enableWGCNAThreads(nThreads = 7)
  2126. if(force.recalc | (! file.exists(file=paste0(outputdir, "powertable.rds")))){
  2127. # Call the network topology analysis function for each set in turn
  2128. powerTable = list(
  2129. data = pickSoftThreshold(
  2130. datExpr,
  2131. powerVector=powers,
  2132. verbose = 100,
  2133. networkType="unsigned",
  2134. corFnc="cor"
  2135. )[[2]]
  2136. );
  2137. saveRDS(powerTable, file=paste0(outputdir, "powertable.rds"))
  2138. } else {
  2139. powerTable = readRDS(file=paste0(outputdir, "powertable.rds"))
  2140. }
  2141. colors = c("blue", "red","black")
  2142. # Will plot these columns of the returned scale free analysis tables
  2143. plotCols = c(2,5,6,7)
  2144. colNames = c("Scale Free Topology Model Fit", "Mean connectivity", "mean connectivity",
  2145. "Max connectivity");
  2146. # Get the minima and maxima of the plotted points
  2147. ylim = matrix(NA, nrow = 2, ncol = 4);
  2148. for (col in 1:length(plotCols)){
  2149. ylim[1, col] = min(ylim[1, col], powerTable$data[, plotCols[col]], na.rm = TRUE);
  2150. ylim[2, col] = max(ylim[2, col], powerTable$data[, plotCols[col]], na.rm = TRUE);
  2151. }
  2152. # Plot the quantities in the chosen columns vs. the soft thresholding power
  2153. par(mfcol = c(2,2));
  2154. par(mar = c(4.2, 4.2 , 2.2, 0.5))
  2155. cex1 = 0.7;
  2156. for (col in 1:length(plotCols)){
  2157. plot(powerTable$data[,1], -sign(powerTable$data[,3])*powerTable$data[,2],
  2158. xlab="Soft Threshold (power)",ylab=colNames[col],type="n", ylim = ylim[, col],
  2159. main = colNames[col]);
  2160. addGrid();
  2161. if (col==1){
  2162. text(powerTable$data[,1], -sign(powerTable$data[,3])*powerTable$data[,2],
  2163. labels=powers,cex=cex1,col=colors[1]);
  2164. } else
  2165. text(powerTable$data[,1], powerTable$data[,plotCols[col]],
  2166. labels=powers,cex=cex1,col=colors[1]);
  2167. if (col==1){
  2168. legend("bottomright", legend = 'Metacells', col = colors, pch = 20) ;
  2169. } else
  2170. legend("topright", legend = 'Metacells', col = colors, pch = 20) ;
  2171. }
  2172. softPower=3
  2173. nSets = 1
  2174. setLabels = 'OCS'
  2175. shortLabels = setLabels
  2176. multiExpr <- list()
  2177. multiExpr[['ODC']] <- list(data=datExpr)
  2178. checkSets(multiExpr) # check data size
  2179. # construct network
  2180. if(force.recalc | (! file.exists(file=paste0(outputdir, "net.rds")))){
  2181. net=blockwiseConsensusModules(multiExpr, blocks = NULL,
  2182. maxBlockSize = 30000, ## This should be set to a smaller size if the user has limited RAM
  2183. randomSeed = 12345,
  2184. corType = "pearson",
  2185. power = softPower,
  2186. consensusQuantile = 0.3,
  2187. networkType = "unsigned",
  2188. TOMType = "signed",
  2189. TOMDenom = "min",
  2190. scaleTOMs = TRUE, scaleQuantile = 0.8,
  2191. sampleForScaling = TRUE, sampleForScalingFactor = 1000,
  2192. useDiskCache = TRUE, chunkSize = NULL,
  2193. deepSplit = 4,
  2194. pamStage=FALSE,
  2195. detectCutHeight = 0.995, minModuleSize = 50,
  2196. mergeCutHeight = 0.2,
  2197. saveConsensusTOMs = TRUE,
  2198. consensusTOMFilePattern = paste0(outputdir,"ConsensusTOM-block.%b.rda"))
  2199. saveRDS(net, file=paste0(outputdir, "net.rds"))
  2200. } else {
  2201. net = readRDS(file=paste0(outputdir, "net.rds"))
  2202. }
  2203. consMEs = net$multiMEs;
  2204. moduleLabels = net$colors;
  2205. # Convert the numeric labels to color labels
  2206. moduleColors = as.character(moduleLabels)
  2207. consTree = net$dendrograms[[1]];
  2208. # module eigengenes
  2209. MEs=moduleEigengenes(multiExpr[[1]]$data, colors = moduleColors, nPC=1)$eigengenes
  2210. MEs=orderMEs(MEs)
  2211. meInfo<-data.frame(rownames(datExpr), MEs)
  2212. colnames(meInfo)[1]= "SampleID"
  2213. # intramodular connectivity
  2214. KMEs<-signedKME(datExpr, MEs,outputColumnName = "kME",corFnc = "bicor")
  2215. # compile into a module metadata table
  2216. geneInfo=as.data.frame(cbind(colnames(datExpr),moduleColors, KMEs))
  2217. # how many modules did we get?
  2218. nmodules <- length(unique(moduleColors))
  2219. # merged gene symbol column
  2220. colnames(geneInfo)[1]= "GeneSymbol"
  2221. colnames(geneInfo)[2]= "Initially.Assigned.Module.Color"
  2222. # save info
  2223. write.csv(geneInfo,file=paste0(outputdir,'/geneInfoSigned.csv'))
  2224. PCvalues=MEs
  2225. ```
  2226. ```{r}
  2227. p = WGCNA::plotDendroAndColors(consTree, moduleColors[net$goodGenes], "Module colors", dendroLabels = FALSE, hang = 0.03, addGuide = TRUE, guideHang = 0.05,
  2228. main = paste0("Microglia gene dendrogram and module colors"))
  2229. ggsave(file=paste0(outputdir, "Microglia_WGCNA_Dendrocolplot_integrated.pdf"))
  2230. ```
  2231. ## WGCNA by Genotype_treatment
  2232. ```{r, fig.width=7, fig.height=4}
  2233. plot_df <- cbind(dplyr::select(targets, c(Genotype, Treatment, labels)), PCvalues)
  2234. plot_df <- reshape2::melt(plot_df, id.vars = c('Genotype', 'Treatment', "labels"))
  2235. plot_df$Genotype <- factor(plot_df$Genotype, levels=c('WT','APPPS1'))
  2236. plot_df$Genotype_Treatment <- paste0(plot_df$Genotype, "_", plot_df$Treatment)
  2237. plot_df$Genotype_Treatment <- factor(plot_df$Genotype_Treatment, levels=c('WT_Ctrl','WT_Stroke', "APPPS1_Ctrl", "APPPS1_Stroke"))
  2238. colors <- sub('ME', '', as.character(levels(plot_df$variable)))
  2239. p <- ggplot(plot_df, aes(x=variable, y=value, fill=Treatment)) +
  2240. geom_boxplot(notch=FALSE) +
  2241. RotatedAxis() + ylab('Module Eigengene') + xlab('') +
  2242. theme(
  2243. axis.text.x=element_blank(),
  2244. axis.ticks.x=element_blank(),
  2245. )
  2246. p <- p + facet_wrap(~variable+Genotype, scales='free_x', ncol=nmodules)+theme_classic()
  2247. p
  2248. ggsave(file=paste0(outputdir, "Microgila_WGCNA_Eigenscore_byGenotype_integrated.pdf"), p)
  2249. ```
  2250. ## WGCNA violin by condition
  2251. ```{r, fig.height=2, fig.width=8}
  2252. p2 <- ggplot(plot_df, aes(x=variable, y=value, fill=Genotype_Treatment)) +
  2253. geom_violin() +
  2254. # RotatedAxis() +
  2255. ylab('Module Eigengene') + xlab('') +
  2256. theme(
  2257. axis.text.x=element_blank(),
  2258. axis.ticks.x=element_blank(),
  2259. )
  2260. p2 <- p2 + facet_wrap(~variable, scales='free', ncol=nmodules)+theme_classic()
  2261. p2
  2262. ggsave(file=paste0(outputdir, "Microgila_WGCNA_Eigenscore_byGenotypeTreatment_integrated.pdf"), p2)
  2263. ```
  2264. ## WGCNA violin by cluster
  2265. ```{r, fig.height=2, fig.width=10}
  2266. p2 <- ggplot(plot_df, aes(x=variable, y=value, fill=labels)) +
  2267. geom_violin() +
  2268. # RotatedAxis() +
  2269. ylab('Module Eigengene') + xlab('') +
  2270. theme(
  2271. axis.text.x=element_blank(),
  2272. axis.ticks.x=element_blank(),
  2273. )
  2274. p2 <- p2 + facet_wrap(~variable, scales='free', ncol=nmodules)+theme_classic()
  2275. p2
  2276. ggsave(file=paste0(outputdir, "Microgila_WGCNA_Eigenscore_byCluster_integrated.pdf"), p2)
  2277. ```
  2278. ## WGCNA Heatmap by condition
  2279. ```{r, fig.width=6, fig.height=4}
  2280. reslist = list()
  2281. for(M in unique(plot_df$variable)){
  2282. Mdata = plot_df[plot_df$variable==M,]
  2283. fit= lm(value~Genotype*Treatment, data = Mdata)
  2284. resfit = summary(fit)
  2285. reslist[[M]] <- c(Genotype_Treatment = resfit$coefficients["GenotypeAPPPS1:TreatmentStroke", "Pr(>|t|)"])
  2286. }
  2287. ME_avg <- plot_df %>% dplyr::group_by(variable, Treatment, Genotype) %>% summarise(avg_Eigenmodule = mean(value),
  2288. sd_Eigenvalue = sd(value),
  2289. med_Eigenvalue=median(value))
  2290. ME_avg$pval=unlist(reslist[ME_avg$variable])
  2291. ME_avg$pval_ast=convertpvaltostars(ME_avg$pval)
  2292. ME_avg$Genotype_Treatment = paste0(ME_avg$Genotype, "_",ME_avg$Treatment)
  2293. ME_avg$Genotype_Treatment <- factor(ME_avg$Genotype_Treatment, levels=c('WT_Ctrl','WT_Stroke', "APPPS1_Ctrl", "APPPS1_Stroke"))
  2294. ME_avg$Module = paste0(ME_avg$pval_ast, ME_avg$variable)
  2295. ME_avg
  2296. openxlsx::write.xlsx(ME_avg, file=paste0(outputdir, "WGCNA_LinModStat_GTxTreatm.xlsx"),rowNames = TRUE)
  2297. ```
  2298. ```{r, fig.width=8, fig.height=5}
  2299. Meandata = MEs %>% group_by(samples.integrated.filt$Genotype_Treatment) %>% summarise_all(mean) %>% column_to_rownames("samples.integrated.filt$Genotype_Treatment") %>% t()
  2300. SDdata = MEs %>% group_by(samples.integrated.filt$Genotype_Treatment) %>% summarise_all(sd)%>% column_to_rownames("samples.integrated.filt$Genotype_Treatment") %>% t()
  2301. colLabels=colnames(Meandata)
  2302. rowLabels=rownames(Meandata)
  2303. rowLabels=paste0(convertpvaltostars(unlist(reslist[rowLabels])), " ",rowLabels=rownames(Meandata))
  2304. textlab = paste0(signif(Meandata,2), "\n", "(", signif(SDdata, 2), ")")
  2305. pdf(paste0(outputdir, "WGCNA_labeled_Heatmap_integrated.pdf"))
  2306. par(mar=c(5,8,5,5))
  2307. labeledHeatmap(Meandata, xLabels = colLabels,
  2308. yLabels = rowLabels,
  2309. yColorLabels = T,
  2310. colors = viridis(50),
  2311. setStdMargins = FALSE, textMatrix = textlab,
  2312. main = "Mean(SD) Eigengene-expression");
  2313. dev.off()
  2314. par(mar=c(5,8,5,5))
  2315. labeledHeatmap(Meandata, xLabels = colLabels,
  2316. yLabels = rowLabels,
  2317. yColorLabels = T,
  2318. colors = viridis(50),
  2319. setStdMargins = FALSE, textMatrix = textlab,
  2320. main = "Mean(SD) Eigengene-expression");
  2321. ```
  2322. ## WGCNA Heatmap by cluster
  2323. ```{r, fig.width=6, fig.height=4}
  2324. reslist = list()
  2325. for(M in unique(plot_df$variable)){
  2326. Mdata = plot_df[plot_df$variable==M,]
  2327. fit= aov(value~labels, data = Mdata)
  2328. resfit = summary(fit)
  2329. reslist[[M]] <- c(Clusters = resfit[[1]]["labels", "Pr(>F)"])
  2330. }
  2331. ME_avg <- plot_df %>% dplyr::group_by(variable, labels) %>% summarise(avg_Eigenmodule = mean(value),
  2332. sd_Eigenvalue = sd(value),
  2333. med_Eigenvalue=median(value))
  2334. ME_avg$pval=unlist(reslist[ME_avg$variable])
  2335. ME_avg$pval_ast=convertpvaltostars(ME_avg$pval)
  2336. ME_avg$Module = paste0(ME_avg$pval_ast, ME_avg$variable)
  2337. ME_avg
  2338. openxlsx::write.xlsx(ME_avg, file=paste0(outputdir, "WGCNA_LinModStat_ByCluster.xlsx"),rowNames = TRUE)
  2339. ```
  2340. ```{r, fig.width=10, fig.height=5}
  2341. Meandata = MEs %>% group_by(samples.integrated.filt$labels) %>% summarise_all(mean) %>% column_to_rownames("samples.integrated.filt$labels") %>% t()
  2342. SDdata = MEs %>% group_by(samples.integrated.filt$labels) %>% summarise_all(sd)%>% column_to_rownames("samples.integrated.filt$labels") %>% t()
  2343. colLabels=colnames(Meandata)
  2344. rowLabels=rownames(Meandata)
  2345. rowLabels=rownames(Meandata)
  2346. rowLabels=paste0(convertpvaltostars(unlist(reslist[rowLabels])), " ",rowLabels=rownames(Meandata))
  2347. textlab = paste0(signif(Meandata,2), "\n", "(", signif(SDdata, 2), ")")
  2348. pdf(paste0(outputdir, "WGCNA_labeled_Heatmap_byCluster_integrated.pdf"))
  2349. par(mar=c(5,8,5,5))
  2350. labeledHeatmap(Meandata, xLabels = colLabels,
  2351. yLabels = rowLabels,
  2352. colorLabels = TRUE,
  2353. colors = viridis(50),
  2354. setStdMargins = FALSE, textMatrix = textlab,
  2355. main = "Mean(SD) Eigengene-expression");
  2356. dev.off()
  2357. par(mar=c(5,8,5,5))
  2358. labeledHeatmap(Meandata, xLabels = colLabels,
  2359. yLabels = rowLabels,
  2360. colorLabels = TRUE,
  2361. colors = viridis(50),
  2362. setStdMargins = FALSE, textMatrix = textlab,
  2363. main = "Mean(SD) Eigengene-expression");
  2364. ```
  2365. ## Heatmaps Genewise per module
  2366. ```{r}
  2367. Modules = unique(moduleColors)
  2368. Modules = Modules[! Modules %in% "grey"] # drop grey one
  2369. for(m in Modules){
  2370. p = DoHeatmap(samples.integrated.filt, features = rownames(samples.integrated.filt)[moduleColors==m], slot="data",
  2371. group.by = "Genotype_Treatment")+scale_fill_viridis()
  2372. ggsave(paste0(paste0(outputdir, "WGCNAGeneWise_ExpressionModule", m, "_integrated.pdf")), p)
  2373. }
  2374. ```
  2375. ## Heatmpas top 50 genes per module Conditions wise
  2376. ```{r, fig.width=14, fig.height=14}
  2377. genelist = split(names(net$colors), net$colors)
  2378. gene_univers = names(net$colors)
  2379. plotlist = list()
  2380. reads = rowSums(JoinLayers(samples.integrated.filt, assay = "RNA") %>% GetAssayData(assay = "RNA", layer="data") )
  2381. for (m in names(genelist)){
  2382. targets = genelist[[m]]
  2383. targets <- reads[targets] %>% sort(., decreasing = T)
  2384. targets <- names(targets)[1:50]
  2385. p<-DoHeatmap(samples.integrated.filt,features = targets,
  2386. group.by = "Genotype_Treatment", slot = "data")
  2387. ggsave(p, file=paste0(outputdir, "WGCNA_Module_",m,"_allgenes_Heatmaps_integrated.pdf"))
  2388. plotlist[[m]]<-p
  2389. }
  2390. p<- ggarrange(plotlist = plotlist, labels = names(genelist))
  2391. p
  2392. ggsave(file=paste0(outputdir, "WGCNA_Module_Heatmaps_integrated.pdf"), p)
  2393. names(plotlist)
  2394. ```
  2395. ```{r, fig.width=5, fig.height=5}
  2396. module = "green"
  2397. featureslist=c("Apoe", "Axl", "Cst7", "Tyrobp","Cd63", "Clec7a", "H2-D1", "Lyz2", "Npc2")
  2398. pdf(paste0(outputdir, "WGCNA_", module, "selectedgenes_heatmap_integrated.pdf"))
  2399. DoHeatmap(samples.integrated.filt,features = featureslist,
  2400. group.by = "Genotype_Treatment", slot = "data")
  2401. dev.off()
  2402. ```
  2403. ```{r, fig.width=5, fig.height=5}
  2404. module = "yellow"
  2405. featureslist=c("Trem2", "Csf1r", "C1qa", "C1qb", "C1qc", "Ctss",
  2406. "Ctsl", "Ctsh", "Cyba", "Lamp1")
  2407. pdf(paste0(outputdir, "WGCNA_", module, "selectedgenes_heatmap_integrated.pdf"))
  2408. DoHeatmap(samples.integrated.filt,features = featureslist,
  2409. group.by = "Genotype_Treatment", slot = "data")
  2410. dev.off()
  2411. ```
  2412. ```{r, fig.width=5, fig.height=5}
  2413. module = "turqouise"
  2414. featureslist=c("Olfr1307", "Olfr635", "Olfr1336", "Olfr46",
  2415. "Olfr344", "Fgd4", "Pkib", "Shisa5", "Senp7", "Snhg14")
  2416. pdf(paste0(outputdir, "WGCNA_", module, "selectedgenes_heatmap_integrated.pdf"))
  2417. DoHeatmap(samples.integrated.filt,features = featureslist,
  2418. group.by = "Genotype_Treatment", slot = "data")
  2419. dev.off()
  2420. ```
  2421. ```{r, fig.width=5, fig.height=5}
  2422. module = "grey"
  2423. featureslist=c("Adam10", "Abca1", "CD74","Arpc1b", "Eef2",
  2424. "Itgb2", "Pdia3", "Aldoa", "Cfh", "Ssh2")
  2425. pdf(paste0(outputdir, "WGCNA_", module, "selectedgenes_heatmap_integrated.pdf"))
  2426. DoHeatmap(samples.integrated.filt,features = featureslist,
  2427. group.by = "Genotype_Treatment", slot = "data")
  2428. dev.off()
  2429. ```
  2430. ## Heatmpas top 50 genes per module Cluster wise
  2431. ```{r, fig.width=14, fig.height=14}
  2432. plotlist = list()
  2433. reads = rowSums(JoinLayers(samples.integrated.filt, assay = "RNA") %>% GetAssayData(assay = "RNA", layer="data") )
  2434. for (m in names(genelist)){
  2435. targets = genelist[[m]]
  2436. targets <- reads[targets] %>% sort(., decreasing = T)
  2437. targets <- names(targets)[1:50]
  2438. p<-DoHeatmap(samples.integrated.filt, features = targets,
  2439. group.by = "labels", slot = "data")
  2440. ggsave(p, file=paste0(outputdir, "WGCNA_Module_",m,"_Heatmaps_byCluster_integrated.pdf"))
  2441. plotlist[[m]]<-p
  2442. }
  2443. p<- ggarrange(plotlist = plotlist, labels = names(genelist))
  2444. p
  2445. ggsave(file=paste0(outputdir,"WGCNA_Module_Heatmaps_byCluster_integrated.pdf"), p)
  2446. names(plotlist)
  2447. ```
  2448. ```{r, fig.width=5, fig.height=5}
  2449. module = "green"
  2450. featureslist=c("Apoe", "Axl", "Cst7", "Tyrobp","Cd63", "Clec7a", "H2-D1", "Lyz2", "Npc2")
  2451. pdf(paste0(outputdir, "WGCNA_", module, "selectedgenes_heatmap_byCluster_integrated.pdf"))
  2452. DoHeatmap(samples.integrated.filt,features = featureslist,
  2453. group.by = "labels", slot = "data")
  2454. dev.off()
  2455. ```
  2456. ```{r, fig.width=5, fig.height=5}
  2457. module = "yellow"
  2458. featureslist=c("Trem2", "Csf1r", "C1qa", "C1qb", "C1qc", "Ctss",
  2459. "Ctsl", "Ctsh", "Cyba", "Lamp1")
  2460. pdf(paste0(outputdir, "WGCNA_", module, "selectedgenes_heatmap_byCluster_integrated.pdf"))
  2461. DoHeatmap(samples.integrated.filt,features = featureslist,
  2462. group.by = "labels", slot = "data")
  2463. dev.off()
  2464. ```
  2465. ```{r, fig.width=5, fig.height=5}
  2466. module = "turqouise"
  2467. featureslist=c("Olfr1307", "Olfr635", "Olfr1336", "Olfr46",
  2468. "Olfr344", "Fgd4", "Pkib", "Shisa5", "Senp7", "Snhg14")
  2469. pdf(paste0(outputdir, "WGCNA_", module, "selectedgenes_heatmap_byCluster_integrated.pdf"))
  2470. DoHeatmap(samples.integrated.filt,features = featureslist,
  2471. group.by = "labels", slot = "data")
  2472. dev.off()
  2473. ```
  2474. ```{r, fig.width=5, fig.height=5}
  2475. module = "grey"
  2476. featureslist=c("Adam10", "Abca1", "CD74","Arpc1b", "Eef2",
  2477. "Itgb2", "Pdia3", "Aldoa", "Cfh", "Ssh2")
  2478. pdf(paste0(outputdir, "WGCNA_", module, "selectedgenes_heatmap_byCluster_integrated.pdf"))
  2479. DoHeatmap(samples.integrated.filt,features = featureslist,
  2480. group.by = "labels", slot = "data")
  2481. dev.off()
  2482. ```
  2483. ## WGCNA GO terms
  2484. ```{r, out.width='130%',out.height='100%'}
  2485. pvallist = unlist(reslist)
  2486. MOI = gsub("ME", "", names(pvallist)) %>% gsub(".Clusters", "", .)
  2487. # MOI = MOI[pvallist<0.05]
  2488. MOI <- MOI[MOI != "grey"]
  2489. # if you want to have the affected genes set return_genelist = T; this takes roughly 4-8 hours
  2490. Gores = getGOresults(geneset = genelist[MOI], domain_scope = "known",
  2491. genereference = gene_univers,
  2492. return_genelist = T,
  2493. organism = "mmusculus")
  2494. display_tab(Gores$result)
  2495. openxlsx::write.xlsx(Gores$result%>% dplyr::select(-parents), file=paste0(outputdir, "WGCNA_GO_terms.xlsx"),rowNames = TRUE)
  2496. plotlist <- list()
  2497. for(m in unique(Gores$result$query)){
  2498. p <- GOplot(Gores$result[Gores$result$query ==m,], N = 10, Title = m)
  2499. plotlist[[m]] <- p
  2500. }
  2501. ```
  2502. ```{r, fig.width=15, fig.height=6}
  2503. p<- ggarrange(plotlist = plotlist)
  2504. p
  2505. ggsave(file=paste0(outputdir,"WGCNA_GO_terms.pdf"), p)
  2506. ```
  2507. # Exdendet Plots and DAta inspection
  2508. ## Dot plot showing top markers for condition clusters, same paper Fig 2f
  2509. ### MG related genes
  2510. ```{r, fig.width=18, fig.height=5}
  2511. reads = JoinLayers(samples.integrated.filt, assay = "RNA") %>%
  2512. GetAssayData(assay = "RNA", layer="data")
  2513. reads.filt= reads[cluster.genes,]
  2514. datatoplot_mean = aggregate(t(reads.filt),
  2515. list(paste0(samples.integrated.filt$labels, "/",samples.integrated.filt$Genotype_Treatment)),
  2516. mean, na.rm=T) %>%
  2517. as.data.frame() %>%
  2518. column_to_rownames("Group.1") %>% scale()
  2519. datatoplot_mean <- datatoplot_mean %>% as.data.frame() %>%
  2520. rownames_to_column("Var1") %>%
  2521. pivot_longer(cols = -Var1,
  2522. names_to = "Genes",
  2523. values_to = "value")
  2524. datatoplot_mean$Microglia = factor(gsub("/.*", "", datatoplot_mean$Var1), levels=rev(levels(samples.integrated.filt$labels)))
  2525. datatoplot_mean$Genotype_Treatment = factor(gsub(".*/", "", datatoplot_mean$Var1), levels=c("WT_Ctrl", "WT_Stroke", "APPPS1_Ctrl","APPPS1_Stroke") )
  2526. colnames(datatoplot_mean) = c("Cluster_Condition", "Gene", "Scaled_mean", "Microglia", "Genotype_Treatment")
  2527. datatoplot_perc = aggregate(t(reads.filt), list(paste0(samples.integrated.filt$labels, "/",samples.integrated.filt$Genotype_Treatment)),
  2528. function(x){length(which(x>0))/length(x)})
  2529. datatoplot_perc <- datatoplot_perc %>% as.data.frame() %>%
  2530. pivot_longer(cols = -Group.1,
  2531. names_to = "Genes",
  2532. values_to = "perc")
  2533. datatoplot = cbind(datatoplot_mean, perc=datatoplot_perc$perc)
  2534. p <- ggplot(datatoplot, aes(x=Gene, y=Microglia, col=Scaled_mean, size=perc))+geom_point()+scale_size_continuous(range = c(0,3))+
  2535. theme_classic()+theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))+facet_grid(~Genotype_Treatment)
  2536. p
  2537. ggsave(filename = paste0(outputdir, "Microglia_Dotplot_ClsuterCondition_Genelists_integrated.pdf"), p)
  2538. ```
  2539. ### Spatial_mutual genes
  2540. ```{r}
  2541. Spatial_mutual <- c("S100a6", "Apoc4", "C4b", "Atp1a2", "Apoc1", "Fn1", "Ntrk2") # genes up in both spatial and APPPS1_stroke vs APPPS1
  2542. ### Dot plot showing top markers for condition clusters, same paper Fig 2f
  2543. reads = JoinLayers(samples.integrated.filt, assay = "RNA") %>%
  2544. GetAssayData(assay = "RNA", layer="data")
  2545. reads.filt= reads[Spatial_mutual,]
  2546. datatoplot_mean = aggregate(t(reads.filt),
  2547. list(paste0(samples.integrated.filt$labels, "/",samples.integrated.filt$Genotype_Treatment)),
  2548. mean, na.rm=T) %>%
  2549. as.data.frame() %>%
  2550. column_to_rownames("Group.1") %>% scale() %>% as.data.frame() %>%
  2551. rownames_to_column("Var1")
  2552. datatoplot_mean=datatoplot_mean %>% pivot_longer(cols = -Var1, names_to = "Gene", values_to = "value")
  2553. datatoplot_mean$Microglia = factor(gsub("/.*", "", datatoplot_mean$Var1), levels=rev(levels(samples.integrated.filt$labels)))
  2554. datatoplot_mean$Genotype_Treatment = factor(gsub(".*/", "", datatoplot_mean$Var1), levels=c("WT_Ctrl", "WT_Stroke", "APPPS1_Ctrl","APPPS1_Stroke") )
  2555. colnames(datatoplot_mean) = c("Cluster_Condition", "Gene", "Scaled_mean", "Microglia", "Genotype_Treatment")
  2556. datatoplot_perc = aggregate(t(reads.filt), list(paste0(samples.integrated.filt$labels, "/",samples.integrated.filt$Genotype_Treatment)),
  2557. function(x){length(which(x>0))/length(x)})
  2558. datatoplot_perc=datatoplot_perc %>% pivot_longer(cols=-Group.1,
  2559. values_to = "perc",
  2560. names_to = "Gene")
  2561. datatoplot = cbind(datatoplot_mean, perc=datatoplot_perc$perc)
  2562. p <- ggplot(datatoplot, aes(x=Gene, y=Microglia, col=Scaled_mean, size=perc))+geom_point()+scale_size_continuous(range = c(0,3))+
  2563. theme_classic()+theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))+facet_grid(~Genotype_Treatment)
  2564. p
  2565. ggsave(filename = paste0(outputdir, "Microglia_Dotplot_Up_spatial_and_APPPS1vsAPPPS1stroke_integrated.pdf"), p)
  2566. ```
  2567. ### Custom Genes
  2568. ```{r}
  2569. Test_genes <- c("S100a6", "S100a9", "S100a8", "S100a10", "S100a11", "S100b", "S100a7a") # genes up in both spatial and APPPS1_stroke vs APPPS1
  2570. ### Dot plot showing top markers for condition clusters, same paper Fig 2f
  2571. reads = JoinLayers(samples.integrated.filt, assay = "RNA") %>%
  2572. GetAssayData(assay = "RNA", layer="data")
  2573. reads.filt= reads[Test_genes,]
  2574. datatoplot_mean = aggregate(t(reads.filt),
  2575. list(paste0(samples.integrated.filt$labels, "/",samples.integrated.filt$Genotype_Treatment)),
  2576. mean, na.rm=T) %>%
  2577. as.data.frame() %>%
  2578. column_to_rownames("Group.1") %>% scale() %>% as.data.frame() %>%
  2579. rownames_to_column("Var1")
  2580. datatoplot_mean=datatoplot_mean %>% pivot_longer(cols=-Var1,
  2581. names_to = "Gene",
  2582. values_to = "value")
  2583. datatoplot_mean$Microglia = factor(gsub("/.*", "", datatoplot_mean$Var1), levels=rev(levels(samples.integrated.filt$labels)))
  2584. datatoplot_mean$Genotype_Treatment = factor(gsub(".*/", "", datatoplot_mean$Var1), levels=c("WT_Ctrl", "WT_Stroke", "APPPS1_Ctrl","APPPS1_Stroke") )
  2585. colnames(datatoplot_mean) = c("Cluster_Condition", "Gene", "Scaled_mean", "Microglia", "Genotype_Treatment")
  2586. datatoplot_perc = aggregate(t(reads.filt), list(paste0(samples.integrated.filt$labels, "/",samples.integrated.filt$Genotype_Treatment)),
  2587. function(x){length(which(x>0))/length(x)})
  2588. datatoplot_perc=datatoplot_perc %>% pivot_longer(
  2589. cols=-Group.1, values_to = "perc", names_to = "Gene")
  2590. datatoplot = cbind(datatoplot_mean, perc=datatoplot_perc$perc)
  2591. p <- ggplot(datatoplot, aes(x=Gene, y=Microglia, col=Scaled_mean, size=perc))+geom_point()+scale_size_continuous(range = c(0,3))+
  2592. theme_classic()+theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))+facet_grid(~Genotype_Treatment)
  2593. p
  2594. ggsave(filename = paste0(outputdir, "Microglia_Dotplot_test_integrated.pdf"), p)
  2595. ```
  2596. ## cell cylce scoring plots
  2597. ```{r}
  2598. cell_cycle_markers <- dplyr::left_join(cell_cycle_genes, annotations, by = c("geneID" = "gene_id"))
  2599. # Acquire the S phase genes
  2600. s_genes <- cell_cycle_markers %>%
  2601. dplyr::filter(phase == "S") %>%
  2602. pull("gene_name")
  2603. # Acquire the G2M phase genes
  2604. g2m_genes <- cell_cycle_markers %>%
  2605. dplyr::filter(phase == "G2/M") %>%
  2606. pull("gene_name")
  2607. samples.integrated.filt<-
  2608. CellCycleScoring(samples.integrated.filt, layer="scaled.data",
  2609. s.features = s_genes,
  2610. g2m.features = g2m_genes)
  2611. a<-DimPlot(samples.integrated.filt, reduction = "umap", group.by = "Phase", pt.size =1)
  2612. b<-DimPlot(samples.integrated.filt, reduction = "umap", group.by = "Phase", split.by = "Plate", pt.size =1)
  2613. c<-DimPlot(samples.integrated.filt, reduction = "umap", group.by = "Phase", split.by = "Genotype_Treatment", pt.size =1)
  2614. a
  2615. ggsave(filename = paste0(outputdir, "G2M_Opt_All_genes_all_cells_Clusters_integrated.pdf"), a)
  2616. ```
  2617. ```{r, fig.width=18, fig.height=4}
  2618. b
  2619. ggsave(filename = paste0(outputdir, "G2M_Opt_All_genes_all_cells_Clusters_byPlate_integrated.pdf"), b)
  2620. ```
  2621. ```{r fig.width=10, fig.height=4}
  2622. c
  2623. ggsave(filename = paste0(outputdir, "G2M_Opt_All_genes_all_cells_Clusters_byCondition_integrated.pdf"), c)
  2624. ```
  2625. ```{r, fig.width=7, fig.height=7}
  2626. p <- DimPlot(samples.integrated.filt, reduction = "umap", group.by = "Phase")
  2627. p
  2628. ggsave(file=paste0(outputdir,"CClustering_CellPhase.pdf_integrated.pdf"), p)
  2629. p <- FeaturePlot_scCustom(samples.integrated.filt,
  2630. reduction = "umap",
  2631. features = "S.Score",
  2632. colors_use = viridis_dark_high)
  2633. p
  2634. ggsave(file=paste0(outputdir,"CClustering_CellPhaseScore.pdf"), p)
  2635. p <- FeaturePlot_scCustom(samples.integrated.filt, reduction = "umap",features = "G2M.Score", colors_use = viridis_dark_high)
  2636. p
  2637. ggsave(file=paste0(outputdir,"CClustering_CellPhaseG2MScore.pdf"), p)
  2638. metadata <- [email hidden]
  2639. p<- ggplot(metadata, aes(x=labels, y= S.Score))+geom_violin(aes(fill=labels))+geom_boxplot(aes(alpha=1))+theme_classic()
  2640. p
  2641. ggsave(file=paste0(outputdir,"CClustering_CellPhaseScoreViolin.pdf"), p)
  2642. p<- ggplot(metadata, aes(x=labels, y= G2M.Score))+geom_violin(aes(fill=labels))+geom_boxplot(aes(alpha=1))+theme_classic()
  2643. p
  2644. ggsave(file=paste0(outputdir,"CClustering_CellPhaseG2MScoreViolin.pdf"), p)
  2645. pairwise.t.test(metadata$S.Score, metadata$labels)
  2646. pairwise.t.test(metadata$G2M.Score, metadata$labels)
  2647. ```
  2648. ## Additonal Microglia subtype scores
  2649. ```{r, fig.width=6, fig.height=6}
  2650. DefaultAssay(samples.integrated.filt) <- "RNA"
  2651. BAM = c("Cd36", "Cd38","Lyve1","Cd206","Cd163", "Cd169")
  2652. CAM = c("Emilin2", "Pf4", "Msa4a", "Hp","F5","Mki67")
  2653. Lipid = c("Lipe", "Acnat1", "Lratd1", "Or8b44", "Vmn1r13")
  2654. samples.integrated.filt<- AddModuleScore(object = samples.integrated.filt,
  2655. assay="RNA", slot="data",
  2656. features = list(INF_resp_microglia),
  2657. name = "MG_score_INF_resp_microglia")
  2658. samples.integrated.filt<- AddModuleScore(object = samples.integrated.filt,
  2659. assay="RNA", slot="data",
  2660. features = list(Cycling_microglia),
  2661. name = "MG_score_Cycling_microglia")
  2662. samples.integrated.filt<- AddModuleScore(object = samples.integrated.filt,
  2663. assay="RNA", slot="data",
  2664. features = list(Act_resp_microglia),
  2665. name = "MG_score_Act_resp_microglia")
  2666. samples.integrated.filt<- AddModuleScore(object = samples.integrated.filt,
  2667. assay="RNA", slot="data",
  2668. features = list(Axon_tract_microglia),
  2669. name = "MG_score_Axon_tract_microglia")
  2670. samples.integrated.filt <- AddModuleScore(object = samples.integrated.filt,
  2671. assay = "RNA", layer="data",
  2672. features = list(BAM), name = "BAM_score")
  2673. samples.integrated.filt <- AddModuleScore(object = samples.integrated.filt,
  2674. assay = "RNA", layer="data",
  2675. features = list(CAM), name = "CAM_score")
  2676. samples.integrated.filt <- AddModuleScore(object = samples.integrated.filt,
  2677. assay = "RNA", layer="data",
  2678. features = list(Lipid), name = "Lipid_score")
  2679. featlist=c("MG_score_Axon_tract_microglia1",
  2680. "MG_score_Act_resp_microglia1",
  2681. "MG_score_Cycling_microglia1",
  2682. "MG_score_INF_resp_microglia1",
  2683. "BAM_score1",
  2684. "CAM_score1",
  2685. "Lipid_score1"
  2686. )
  2687. p <- FeaturePlot_scCustom(samples.integrated.filt,
  2688. na_cutoff = 0, reduction="umap",
  2689. features = featlist,
  2690. colors_use = viridis_dark_high)
  2691. ```
  2692. ```{r, fig.width=18, fig.height=14}
  2693. p
  2694. ggsave(paste0(outputdir, "DimPlots_MGSubtypes_Genes_integrated.pdf"), p)
  2695. ```
  2696. ```{r, fig.width=12, fig.height=16}
  2697. p <- RidgePlot(samples.integrated.filt,
  2698. features = c("MG_score_Axon_tract_microglia1",
  2699. "MG_score_Act_resp_microglia1",
  2700. "MG_score_Cycling_microglia1",
  2701. "MG_score_INF_resp_microglia1",
  2702. "BAM_score1",
  2703. "CAM_score1",
  2704. "Lipid_score1") ,
  2705. group.by = "labels", ncol = 2)
  2706. p
  2707. ggsave(paste0(outputdir, "Ridge_MGSubtypes_Genes_integrated.pdf"), p)
  2708. ```
  2709. ## Additional QC plots final dataset
  2710. ```{r fig.width=12, fig.height=4}
  2711. DefaultAssay(samples.integrated.filt) <- "RNA"
  2712. metadata <- [email hidden]
  2713. metadata$nCount_RNA_finset <- colSums(samples.integrated.filt)
  2714. metadata$nFeature_RNA_finset <- colSums((JoinLayers(samples.integrated.filt, assay = "RNA") %>% GetAssayData(assay = "RNA", layer="data")) >0)
  2715. metadata -> [email hidden]
  2716. p <- VlnPlot(samples.integrated.filt, features = c("nCount_RNA_finset") , group.by = "labels") +geom_hline(yintercept = 200)
  2717. p
  2718. p2 <- VlnPlot(samples.integrated.filt, features = c("nFeature_RNA_finset") , group.by = "labels") +geom_hline(yintercept = 150)
  2719. p2
  2720. p3 <- VlnPlot(samples.integrated.filt, features = "percent.mt" , group.by = "labels") + ylim(c(0,10)) +geom_hline(yintercept = 5)
  2721. p3
  2722. pcomb <- ggarrange(p,p2,p3, common.legend = T, ncol = 3, legend = "right")
  2723. pcomb
  2724. ggsave(paste0(outputdir, "Qualityplots_integrated.pdf"), pcomb)
  2725. ```
  2726. ## Additional Plots DEX
  2727. ```{r, fig.width=4, fig.height=6}
  2728. genes_to_label_dwn <- c("Siglech", "Ccl6" , "Cst7", "Tyrobp")
  2729. genes_to_label_up <- c("H2-D1", "B2m" , "C4b", "Lipe", "Apoe")
  2730. all_genes <- c(genes_to_label_up, genes_to_label_dwn)
  2731. all_genes <- c(genes_to_label_up, genes_to_label_dwn)
  2732. # Get remaining genes not in all_genes
  2733. rest_genes <- rownames(DEG_APPPS1_CtrlvsStroke)[!rownames(DEG_APPPS1_CtrlvsStroke) %in% all_genes]
  2734. # Combine: labeled genes first, then the rest
  2735. df_res <- DEG_APPPS1_CtrlvsStroke[rev(c(all_genes, rest_genes)), ]
  2736. df_res <- df_res %>%
  2737. mutate(sign = ifelse(df_res$avg_log2FC < 0, "down",
  2738. ifelse(df_res$avg_log2FC > 0, "up", "no.reg")),
  2739. sign = ifelse(df_res$p_val_adj > 0.05, "no.reg", sign),
  2740. sign = ifelse(rownames(df_res) %in% genes_to_label_up, "up", sign),
  2741. sign = ifelse(rownames(df_res) %in% genes_to_label_dwn, "down", sign),
  2742. goi = ifelse(rownames(df_res) %in% all_genes, 1, 0))
  2743. library(ggrepel)
  2744. panelA <- ggplot(df_res, aes(x=avg_log2FC, y=-log10(p_val_adj),
  2745. col=sign, alpha=goi, size=as.factor(goi))) +
  2746. geom_point() +
  2747. theme_minimal() +
  2748. geom_hline(yintercept = -log10(0.05), lwd=0.3, linetype="dashed") +
  2749. geom_vline(xintercept = 0, lwd=0.3, linetype="dashed") +
  2750. scale_color_manual(name = "",
  2751. values = c("up" = "red3", "no.reg" = "gray60", "down" = "royalblue")) +
  2752. guides(alpha = "none", size = "none") +
  2753. geom_label_repel(data = df_res[all_genes, ],
  2754. aes(label = rownames(df_res[all_genes, ])),
  2755. size = 3,
  2756. max.overlaps = Inf,
  2757. box.padding = 0.5,
  2758. point.padding = 0.3,
  2759. segment.color = "gray40",
  2760. segment.size = 0.3,
  2761. min.segment.length = 0,
  2762. force = 2,
  2763. show.legend = FALSE) +
  2764. theme(legend.position = "top",
  2765. legend.justification = "left") +
  2766. ggtitle("Bulk differential expression \nall micorglia integrated")
  2767. panelA
  2768. ```
  2769. ```{r}
  2770. reads = JoinLayers(samples.integrated.filt, assay = "RNA") %>%
  2771. GetAssayData(assay = "RNA", layer="data")
  2772. subset = samples.integrated.filt$Genotype =="APPPS1"
  2773. reads.filt= reads[all_genes, subset]
  2774. datatoplot_mean = aggregate(t(reads.filt),
  2775. list(paste0(samples.integrated.filt$labels[subset], "/",samples.integrated.filt$Genotype_Treatment[subset])),
  2776. mean, na.rm=T) %>%
  2777. as.data.frame() %>%
  2778. column_to_rownames("Group.1")
  2779. datatoplot_mean <- datatoplot_mean %>% as.data.frame() %>%
  2780. rownames_to_column("Var1") %>%
  2781. pivot_longer(cols = -Var1,
  2782. names_to = "Genes",
  2783. values_to = "value")
  2784. datatoplot_mean$Microglia = factor(gsub("/.*", "", datatoplot_mean$Var1), levels=rev(levels(samples.integrated.filt$labels)))
  2785. datatoplot_mean$Genotype_Treatment = factor(gsub(".*/", "", datatoplot_mean$Var1), levels=c("WT_Ctrl", "WT_Stroke", "APPPS1_Ctrl","APPPS1_Stroke") )
  2786. colnames(datatoplot_mean) = c("Cluster_Condition", "Gene", "Scaled_mean", "Microglia", "Genotype_Treatment")
  2787. datatoplot_perc = aggregate(t(reads.filt), list(paste0(samples.integrated.filt$labels[subset], "/",samples.integrated.filt$Genotype_Treatment[subset])),
  2788. function(x){length(which(x>0))/length(x)})
  2789. datatoplot_perc <- datatoplot_perc %>% as.data.frame() %>%
  2790. pivot_longer(cols = -Group.1,
  2791. names_to = "Genes",
  2792. values_to = "perc")
  2793. datatoplot = cbind(datatoplot_mean, perc=datatoplot_perc$perc)
  2794. datatoplot$Microglia <- as.character(datatoplot$Microglia)
  2795. datatoplot$Gene <- factor(datatoplot$Gene, levels=all_genes, labels=all_genes)
  2796. datatoplot <- datatoplot %>%
  2797. group_by(Microglia, Gene) %>%
  2798. mutate(Scaled_Diff = Scaled_mean - mean(Scaled_mean)) %>%
  2799. ungroup()
  2800. library(ggh4x)
  2801. Microglia_color_palette <- scales::hue_pal()(nlevels(factor(datatoplot$Microglia)))
  2802. # Define colors for each Microglia level
  2803. strip_colors <- setNames(Microglia_color_palette, levels(factor(datatoplot$Microglia)))
  2804. strip <- strip_themed(background_x = elem_list_rect(fill = strip_colors))
  2805. panelB <- ggplot(datatoplot, aes(x=Genotype_Treatment, y=Gene, col=Scaled_Diff, size=perc)) +
  2806. geom_point() +
  2807. scale_size_continuous(range = c(1,7)) +
  2808. theme_classic() +
  2809. geom_hline(yintercept = 5.5, lwd=0.5, linetype="dashed", color="gray40")+
  2810. theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1),
  2811. strip.text = element_text(face = "bold", color = "white")) +
  2812. facet_grid2(~Microglia, strip = strip) +
  2813. scale_color_continuous(palette = colorRampPalette(rev(RColorBrewer::brewer.pal(5,"RdBu")))(100))+
  2814. ggtitle("Per cluster difference in expression \n normlaized to within cluster mean")
  2815. ```
  2816. ```{r, fig.width=15, fig.height=6}
  2817. p<- ggarrange(panelA,panelB, widths = c(1.2,4), labels = c("A", "B"))
  2818. ggsave(filename = paste0(outputdir, "APPPS1_Bulk_vs_Microglia_Dotplot_ClusterCondition_Genelists_integrated.pdf"), p, width = 15, height = 6)
  2819. ```
  2820. ```{r}
  2821. rm(list=c("reads", "counts", "counts_run2", "counts_run1",
  2822. "counts_sel", "results_list", "sce.microglia"))
  2823. gc()
  2824. ```
  2825. ```{r}
  2826. saveRDS(samples.integrated.filt, paste0(outputdir, "SeuratObjectafterProcessing.rds"))
  2827. # samples.integrated.filt <- readRDS( paste0(outputdir, "SeuratObjectafterProcessing.rds"))
  2828. ```

scRNA_Analyses_Candlishetal.Rmd at commit e83d217, no license · at the source

Overview

Authors: Michael Candlish1, Jan Hofmann1, Desirée Brösamle2,3,4,5, Annika Haessler6, Murphy DeMeglio1, Angelos Skodras2, Georgi Tushev7, Eloah S De Biasi1, Stefan Günther8, René Wiegandt8, Heidi Theis9, Elena De Domenico9, Nina Sofia Hermann2,3,4,5, Peter Breunig1, Christina Sauerland1, K Peter R Nilsson10, Marc D Beyer9,11, Mario Looso8, Maike Windbergs6, Sigrun Roeber12, Jochen Herms13, Jonas J Neher2,3,4,5, Andreas G Chiocchetti14, Jasmin K Hefendehl1
14 affiliations
  1. Neurovascular Disorders, Institute of Cell Biology and Neuroscience, Biologicum, Goethe University Frankfurt, Max-von-Laue Str. 13, Frankfurt am Main, Germany
  2. Department of Cellular Neurology, Hertie Institute for Clinical Brain Research, University of Tübingen, Tübingen, Germany
  3. Biomedical Center (BMC), Biochemistry, Faculty of Medicine, LMU Munich, Munich, Germany
  4. Neuroimmunology and Neurodegenerative Diseases, German Center for Neurodegenerative Diseases (DZNE), Munich, Germany
  5. Munich Cluster for Systems Neurology (SyNergy), Munich, Germany
  6. Institute of Pharmaceutical Technology, Goethe University Frankfurt, Max-von- Laue-Str. 9, Frankfurt am Main, Germany
  7. Max Planck Institute for Brain Research, Max-von-Laue-Str. 4, Frankfurt am Main, Germany
  8. Max Planck Institute for Heart and Lung Research, Member of the German Center for Lung Research (DZL), Member of the Cardio-Pulmonary Institute (CPI), Bad Nauheim, Germany
  9. Platform for Single Cell Genomics and Epigenomics (PRECISE) at the German Center for Neurodegenerative Diseases (DZNE), Bonn, Germany
  10. Department of Physics, Chemistry and Biology, Linköping University, Linköping, SE-581 83 Sweden
  11. Immunogenomics & Neurodegeneration, German Center for Neurodegenerative Diseases (DZNE), Bonn, Germany
  12. Center of Neuropathology and Prion Research, Faculty of Medicine, LMU Munich, Munich, Germany
  13. Center for Neuropathology, Ludwig-Maximilians-University Munich, Munich, Germany
  14. Department of Child and Adolescent Psychiatry, Psychosomatics and Psychotherapy, University Hospital, Goethe University Frankfurt, Frankfurt am Main, Germany
Journal: Journal of neuroinflammation, volume 23, issue 1, article 213
Dates: received 29 August 2025; accepted 29 May 2026; published online 9 June 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1186/s12974-026-03897-x · PMID 42265753 · PMCID PMC13292430 · OpenAlex W4417255812
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: human (organism), mouse (organism), Alzheimer's / dementia (population), stroke (population), cellular / molecular (subfield)
Methods: Statistics, Smoothing, state filtering, decompositions
Keywords: Alzheimer’s disease, Stroke, Microglia, Co-morbidity
MeSH: Amyloid beta-Peptides*, Brain Ischemia*, Microglia*, Alzheimer Disease, Amyloid beta-Protein Precursor, Animals, Apolipoproteins E, Disease Models, Animal, Humans, Mice, Mice, Inbred C57BL, Mice, Transgenic, Phenotype (* major topic)
Topic: Neuroinflammation and Neurodegeneration Mechanisms (Neurology, Neuroscience), according to OpenAlex
Funding: Johann Wolfgang Goethe-Universität, Frankfurt am Main
Citations: cited by 1 paper (Europe PMC); 39 references in the paper

Abstract

Microglia are highly plastic cells that are capable of integrating subsequent insults. As the majority of Alzheimer’s Disease (AD) patients also show cerebrovascular pathology, we here aimed to dissect the interactions between AD and ischemic brain injury on the microglial response to amyloid beta (Aβ) pathology. Unexpectedly, ischemic stroke in the context of cerebral β-amyloidosis drives the emergence of a neuroprotective microglial phenotype characterized by an ApoE-enriched transcriptional state and enhanced lipid handling. These microglia promote the rapid formation of highly compact Aβ plaques that are relatively inert and strikingly reminiscent of those observed in cognitively resilient AD patients. Our findings thus reveal that the microglial response to Aβ pathology is not a fixed trajectory toward dysfunction, but retains a capacity for beneficial reprogramming when engaged by the appropriate stimulus. Beyond characterizing this comorbid state, our data identify specific molecular pathways, centered on ApoE, complement activation, and lysosomal processing, that may be amenable to therapeutic targeting to promote protective microglial function in AD.

Supplementary Information: The online version contains supplementary material available at 10.1186/s12974-026-03897-x.

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 3 matches between paragraphs and lines of code.

KJPMolgenLab/scSeq_Hefendehl

License: none: the authors keep all their rights
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Commit: e83d21755cf398796bb6dc512bcd7bc3548688da, 28 May 2026
Languages: JavaScript (27), R (7), Shell (1)
Size: 345 files, 35 scripts
Software Heritage: not archived
Found in: “Data availability”
Holds: README, documentation, 4 notebooks
Not found: license file, CITATION.cff, environment file, tests, continuous integration
Tools: tidyverse (2 files), data.table (1 file), DESeq2 (1 file), ggpubr (1 file), Harmony (1 file), limma (1 file), pheatmap (1 file), Plotly (1 file), reshape2 (1 file), Seurat (1 file), SingleCellExperiment (1 file), WGCNA (1 file)
Availability: 1 check, the latest on 27 September 2026: the link answers
  • 27 September 2026: the link answers
36 files

gitlab.mpcdf.mpg.de/mpibr/scic/roioverstack

License: none: the authors keep all their rights
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Commit: c86198d87dcd2f6dea1896e12a607be5cf2be609, 6 May 2024
Languages: MATLAB (1)
Size: 4 files, 1 script
Software Heritage: not archived
Found in: “Code availability”
Holds: README, tests
Not found: license file, CITATION.cff, environment file, continuous integration, documentation
Availability: 1 check, the latest on 27 September 2026: the link answers
  • 27 September 2026: the link answers
2 files

Code availability

The code for segmentation of qFTAA- and hFTAA- labelled Aβ plaques can be found here: https://gitlab.mpcdf.mpg.de/mpibr/scic/roioverstack. Any additional requests for code should be addressed to Prof. Jasmin Hefendehl.

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

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

Any additional requests for data should be addressed to Prof. Jasmin Hefendehl. Details regarding scRNAseq analysis and data can be found at the following websites respectively. https://github.com/KJPMolgenLab/scSeq_Hefendehl/ and https://kjpmolgenlab.github.io/scSeq_Hefendehl/.

The code for segmentation of qFTAA- and hFTAA- labelled Aβ plaques can be found here: https://gitlab.mpcdf.mpg.de/mpibr/scic/roioverstack. Any additional requests for code should be addressed to Prof. Jasmin Hefendehl.

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

Recorded: type, language, journal, volume, issue, pages, dates, 24 authors, 4 keywords, 13 MeSH terms, 1 funder, 39 references.

Cite

This paper

Candlish, M., Hofmann, J., Brösamle, D., Haessler, A., DeMeglio, M., Skodras, A., Tushev, G., De Biasi, E. S., Günther, S., Wiegandt, R., Theis, H., De Domenico, E., Hermann, N. S., Breunig, P., Sauerland, C., Nilsson, K. P. R., Beyer, M. D., Looso, M., Windbergs, M., . . . Hefendehl, J. K. (2026). Ischemic injury triggers a protective microglial phenotype in models of Aβ pathology. Journal of neuroinflammation, 23(1), 213. https://doi.org/10.1186/s12974-026-03897-x

BibTeX

@article{candlish2026ischemic,
author = {Candlish, Michael and Hofmann, Jan and Brösamle, Desirée and Haessler, Annika and DeMeglio, Murphy and Skodras, Angelos and Tushev, Georgi and De Biasi, Eloah S and Günther, Stefan and Wiegandt, René and Theis, Heidi and De Domenico, Elena and Hermann, Nina Sofia and Breunig, Peter and Sauerland, Christina and Nilsson, K Peter R and Beyer, Marc D and Looso, Mario and Windbergs, Maike and Roeber, Sigrun and Herms, Jochen and Neher, Jonas J and Chiocchetti, Andreas G and Hefendehl, Jasmin K},
title = {{Ischemic injury triggers a protective microglial phenotype in models of Aβ pathology}},
journal = {Journal of neuroinflammation},
year = {2026},
month = jun,
volume = {23},
number = {1},
pages = {213},
publisher = {BMC},
issn = {1742-2094},
doi = {10.1186/s12974-026-03897-x},
url = {https://doi.org/10.1186/s12974-026-03897-x},
pmid = {42265753},
pmcid = {PMC13292430}
}

RIS

TY - JOUR
AU - Candlish, Michael
AU - Hofmann, Jan
AU - Brösamle, Desirée
AU - Haessler, Annika
AU - DeMeglio, Murphy
AU - Skodras, Angelos
AU - Tushev, Georgi
AU - De Biasi, Eloah S
AU - Günther, Stefan
AU - Wiegandt, René
AU - Theis, Heidi
AU - De Domenico, Elena
AU - Hermann, Nina Sofia
AU - Breunig, Peter
AU - Sauerland, Christina
AU - Nilsson, K Peter R
AU - Beyer, Marc D
AU - Looso, Mario
AU - Windbergs, Maike
AU - Roeber, Sigrun
AU - Herms, Jochen
AU - Neher, Jonas J
AU - Chiocchetti, Andreas G
AU - Hefendehl, Jasmin K
TI - Ischemic injury triggers a protective microglial phenotype in models of Aβ pathology
T2 - Journal of neuroinflammation
J2 - J Neuroinflammation
PY - 2026
DA - 2026/06/09
VL - 23
IS - 1
SP - 213
SN - 1742-2094
PB - BMC
DO - 10.1186/s12974-026-03897-x
UR - https://doi.org/10.1186/s12974-026-03897-x
LA - en
ER -

CSL-JSON

{
"id": "10.1186/s12974-026-03897-x",
"type": "article-journal",
"title": "Ischemic injury triggers a protective microglial phenotype in models of Aβ pathology",
"container-title": "Journal of neuroinflammation",
"author": [
{
"family": "Candlish",
"given": "Michael"
},
{
"family": "Hofmann",
"given": "Jan"
},
{
"family": "Brösamle",
"given": "Desirée"
},
{
"family": "Haessler",
"given": "Annika"
},
{
"family": "DeMeglio",
"given": "Murphy"
},
{
"family": "Skodras",
"given": "Angelos"
},
{
"family": "Tushev",
"given": "Georgi"
},
{
"family": "De Biasi",
"given": "Eloah S"
},
{
"family": "Günther",
"given": "Stefan"
},
{
"family": "Wiegandt",
"given": "René"
},
{
"family": "Theis",
"given": "Heidi"
},
{
"family": "De Domenico",
"given": "Elena"
},
{
"family": "Hermann",
"given": "Nina Sofia"
},
{
"family": "Breunig",
"given": "Peter"
},
{
"family": "Sauerland",
"given": "Christina"
},
{
"family": "Nilsson",
"given": "K Peter R"
},
{
"family": "Beyer",
"given": "Marc D"
},
{
"family": "Looso",
"given": "Mario"
},
{
"family": "Windbergs",
"given": "Maike"
},
{
"family": "Roeber",
"given": "Sigrun"
},
{
"family": "Herms",
"given": "Jochen"
},
{
"family": "Neher",
"given": "Jonas J"
},
{
"family": "Chiocchetti",
"given": "Andreas G"
},
{
"family": "Hefendehl",
"given": "Jasmin K"
}
],
"container-title-short": "J Neuroinflammation",
"volume": "23",
"issue": "1",
"page": "213",
"DOI": "10.1186/s12974-026-03897-x",
"PMID": "42265753",
"PMCID": "PMC13292430",
"ISSN": "1742-2094",
"publisher": "BMC",
"URL": "https://doi.org/10.1186/s12974-026-03897-x",
"language": "en",
"issued": {
"date-parts": [
[
2026,
6,
9
]
]
}
}

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.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, Harmony, SingleCellExperiment, 9 other tools, cellular / molecular
[2] doi:10.1002/imt2.70163 [code]
Spatial multi-omics unveils sphingolipid metabolic reprogramming within the retinal pathological niche.
Journal: iMeta
In common: Harmony, SingleCellExperiment, limma, 8 other tools, mouse, cellular / molecular, 1 reference
[3] doi:10.1038/s41593-026-02367-0 [code]
A reproducible three-dimensional model of human brain tissue to investigate physiological and disease-associated microglia phenotypes.
Journal: Nature neuroscience
In common: WGCNA, Harmony, SingleCellExperiment, 8 other tools, Alzheimer's / dementia, cellular / molecular
[4] doi:10.1038/s41467-026-73305-8 [code]
Comparative analysis of the cellular landscape in mammalian striatum.
Journal: Nature communications
In common: WGCNA, Harmony, SingleCellExperiment, 7 other tools, mouse, cellular / molecular
[5] doi:10.1038/s41467-026-70232-6 [code]
Gene expression dynamics of human and mouse craniofacial development at the single-cell level.
Journal: Nature communications
In common: Harmony, SingleCellExperiment, limma, 7 other tools, mouse, cellular / molecular
[6] doi:10.1038/s41586-026-10414-w [code]
Focal white matter lesions drive grey matter inflammation and synapse loss.
Journal: Nature
In common: Harmony, SingleCellExperiment, DESeq2, 4 other tools, Alzheimer's / dementia, mouse, cellular / molecular, 3 references
[7] doi:10.1038/s42003-026-10957-8 [code]
Brain defence by the extracellular matrix protein Cochlin.
Journal: Communications biology
In common: WGCNA, limma, DESeq2, 7 other tools, mouse, cellular / molecular
[8] doi:10.1038/s41514-026-00397-3 [code]
Nasal administration of Protollin enhances monocyte phagocytosis and decreases CD8&lt;sup&gt;+&lt;/sup&gt; T cell cytotoxicity in subjects with early Alzheimer's disease: a Phase 1 clinical trial.
Journal: npj aging
In common: Harmony, limma, DESeq2, 7 other tools, Alzheimer's / dementia
[9] doi:10.1016/j.isci.2026.115657 [code]
Integration of machine learning to develop a disulfidptosis model for predicting glioma prognosis, immunotherapy response, and drug.
Journal: iScience
In common: WGCNA, Harmony, limma, 7 other tools
[10] doi:10.1016/j.isci.2026.115196 [code]
Transcriptional and cellular maturation of the chick spinal cord in the context of distinct neuromuscular circuits.
Journal: iScience
In common: WGCNA, SingleCellExperiment, limma, 7 other tools

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.