OSCR

Sex specific effects of adoptive Tregs transfer on the brain and periphery in maternal immune activation offspring rescuing immune dysregulation.

Code ↔ Paper

8 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 8 matches
  1. [1] § Materials and methods › RNA-sequencing preparation and analysis ↔ Master_QuantSeqAnalysis.sh, lines 166–206 · score 0.98 · alignIntronMax, alignMatesGapMax, alignSJDBoverhangMin, outFilterMismatchNmax, STAR, mm10
  2. [2] § Materials and methods › RNA-sequencing preparation and analysis ↔ LimmaVoom_DE_RNAseq_FC_sexlitter_removeP30.R, lines 300–346 · score 0.88 · calcNormFactors, contrasts.fit, library composition, eBayes, design matrix, Voom
  3. [3] § Materials and methods › RNA-sequencing preparation and analysis ↔ LimmaVoom_DE_RNAseq_CB_sexlitter.R, lines 341–387 · score 0.88 · calcNormFactors, contrasts.fit, library composition, eBayes, design matrix, Voom
  4. [4] § Materials and methods › Weighted gene co-expression network analysis ↔ WGCNA_allconditions.R, lines 423–478 · score 0.79 · soft thresholding power, co expression, TOM, adjacency, topological, fit
  5. [5] § Materials and methods › Weighted gene co-expression network analysis ↔ WGCNA_allconditions.R, lines 1436–1475 · score 0.70 · Gene module membership, Hub gene, log2RPKM, WGCNA
  6. [6] § Materials and methods › RNA-sequencing preparation and analysis ↔ DEGcomparisons.R, lines 476–522 · score 0.55 · GO term enrichments, compareCluster, cutoff, ClusterProfiler, genes
  7. [7] § Materials and methods › RNA-sequencing preparation and analysis ↔ LimmaVoom_DE_RNAseq_CB_sexlitter.R, lines 1039–1085 · score 0.55 · GO term enrichments, compareCluster, cutoff, ClusterProfiler, genes
  8. [8] § Materials and methods › Weighted gene co-expression network analysis ↔ WGCNA_allconditions.R, lines 326–328 · score 0.51 · median absolute deviation, WGCNA

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 · 2,181 lines · 83 KB · no license · 3 matches

  1. #####################################################################################
  2. # Gene expression from human brain across development: brainspan
  3. ####################################################################################
  4. #BiocManager::install("edgeR")
  5. library(edgeR)
  6. #source("https://bioconductor.org/biocLite.R")
  7. #biocLite("limma")
  8. library(limma)
  9. library(dplyr)
  10. library(tidyr)
  11. library(ggplot2)
  12. library(cowplot)
  13. library(gplots)
  14. #source("http://bioconductor.org/biocLite.R")
  15. #biocLite("biomaRt")
  16. library(biomaRt)
  17. library(WGCNA);
  18. # The following setting is important, do not omit.
  19. options(stringsAsFactors = FALSE)
  20. ######################################################################
  21. # Basic function to convert mouse to human gene names
  22. human = useMart(biomart="ENSEMBL_MART_ENSEMBL", dataset="hsapiens_gene_ensembl")
  23. mouse = useMart("ensembl", dataset = "mmusculus_gene_ensembl")
  24. # convertMouseGeneList <- function(x){
  25. # #for hg38:
  26. # genesV2 = getLDS(attributes = c("mgi_symbol","ensembl_gene_id"), filters = "mgi_symbol", values = x , mart = mouse, attributesL = c("hgnc_symbol","ensembl_gene_id","entrezgene"), martL = human, uniqueRows=T)
  27. # humanx <- unique(genesV2[,])
  28. #
  29. # # Print the first 6 genes found to the screen
  30. # print(head(humanx))
  31. # return(humanx)
  32. # }
  33. ######################################################################
  34. #Change to your working directory
  35. setwd("/Users/aciernia/Sync/collaborations/Ashwood/MIATcellRNAseq/")
  36. ######################################################################
  37. ############################################################################################################################
  38. ############################################################################################################################
  39. ############################################################################################################################
  40. #Initial data processing, sample cleaning and differential expression analysis
  41. ############################################################################################################################
  42. ############################################################################################################################
  43. ############################################################################################################################
  44. ############################################################################################################################
  45. #make RPKM data
  46. ############################################################################################################################
  47. #loop for combining GeneID and counts for each txt file
  48. path ="/Users/aciernia/Sync/collaborations/Ashwood/MIATcellRNAseq/counts"
  49. setwd(path)
  50. # out.file<-""
  51. # group<-""
  52. # file.names <- dir(path, pattern ='*collapsedUMI.counts.txt')
  53. # for(i in 1:length(file.names)){
  54. # file <- read.table(file.names[i],skip=1, header=TRUE, sep="\t", stringsAsFactors=FALSE)
  55. # counts <- data.frame(file$Geneid,file[,7])
  56. # #extract file name without count.txt
  57. # m <- as.data.frame(file.names[i])
  58. # names(m) <- c("split")
  59. # m$split <- as.character(m$split)
  60. # m <-tidyr::separate(m,split,into= c("name","stuff","stuff2","stuff3"),sep="\\.")
  61. #
  62. # print(m$name)
  63. # #replace column headings with names
  64. # names(counts) <- c("Geneid",m$name)
  65. #
  66. # #write to output file
  67. # out.file <- counts
  68. # write.table(out.file, file =paste(m$name, ".out.txt", sep=""), sep="\t",quote=F)
  69. # }
  70. #take files from loop above as new input
  71. input.files <-dir(path, pattern ='*out.txt')
  72. input.files <- as.data.frame(input.files)
  73. names(input.files) <- c("filenames")
  74. #get treatments names
  75. input.files$Sample.ID <- gsub(".out.txt","",input.files$filenames)
  76. #read in info
  77. Info3 <- read.csv("/Users/aciernia/Sync/collaborations/Ashwood/MIATcellRNAseq/MasterExperimentInfo.csv")
  78. #remove PA92FC30 based on MSDS
  79. Info3 <- Info3 %>% filter(Sample.ID !="PA92FC30")
  80. setwd("/Users/aciernia/Sync/collaborations/Ashwood/MIATcellRNAseq/counts")
  81. path <- c("/Users/aciernia/Sync/collaborations/Ashwood/MIATcellRNAseq/counts")
  82. RG <- readDGE(Info3$filenames, group=Info3$Group)
  83. colnames(RG$counts) <- gsub(".out","",colnames(RG$counts))
  84. #save
  85. path ="/Users/aciernia/Sync/collaborations/Ashwood/MIATcellRNAseq/WGCNA"
  86. setwd(path)
  87. save(RG,Info3, file="RNAseqDEGlist.RData")
  88. # number of unique transcripts
  89. dim(RG)
  90. #53801 177
  91. ###########################################################
  92. # Filter for one count per million in at least 1/4 of libraries = 130/4 = 32
  93. allsamples <- table(Info3$Dam.Treatment.Group,Info3$Pup.Treatment.Group,Info3$Sex.x, Info3$Brain.Region)
  94. allsamples
  95. #smallest group is n=6
  96. keep <- rowSums(cpm(RG)>1)>=6
  97. RGcpm <- RG[keep,]
  98. dim(RGcpm)
  99. # 21283 177
  100. geneid <- rownames(RGcpm) #ensemble IDs for biomart
  101. ##################################################################################
  102. #read in gene info
  103. ##################################################################################
  104. #source("http://bioconductor.org/biocLite.R")
  105. #biocLite("biomaRt")
  106. library(biomaRt)
  107. #mouse = useMart("ensembl", dataset = "mmusculus_gene_ensembl")
  108. #us_mart <- useEnsembl(biomart = "ensembl", mirror = "uswest")
  109. us_mart <- useEnsembl(biomart = "ensembl", mirror = "uswest",dataset = "mmusculus_gene_ensembl")
  110. #head(listAttributes(human),100)
  111. #attributes <- listAttributes(us_mart)
  112. #attributes[grep("exon", attributes$name),]
  113. genes <- getBM(attributes = c("ensembl_gene_id","chromosome_name","start_position","end_position","mgi_symbol","external_gene_name","description"),
  114. filter= "ensembl_gene_id",
  115. values = rownames(RGcpm),
  116. mart = us_mart)
  117. genes$genelength <- abs(genes$end_position - genes$start_position)
  118. #remove duplicates:keeps only first entry
  119. genes <- genes[!duplicated(genes$ensembl_gene_id),]
  120. #match order: df[match(target, df$name),]
  121. genes <- genes[match(rownames(RGcpm),genes$ensembl_gene_id),]
  122. ##########################################################################
  123. #add gene info to DEGlist object
  124. ##########################################################################
  125. #add into DEGlist
  126. RGcpm$genes <- genes
  127. #save
  128. save(RG,RGcpm,genes, file="DEGlist.RData")
  129. ###########################################################
  130. #filtering plot
  131. ###########################################################
  132. library(RColorBrewer)
  133. nsamples <- ncol(RGcpm)
  134. colourCount = nsamples
  135. getPalette = colorRampPalette(brewer.pal(9, "Set1"))
  136. fill=getPalette(colourCount)
  137. #plot:
  138. pdf('FilteringCPM_plots.pdf')
  139. par(mfrow=c(1,2))
  140. #prefilter:
  141. lcpm <- cpm(RG, log=TRUE, prior.count=2)
  142. plot(density(lcpm[,1]), col=fill[1], lwd=2, ylim=c(0,0.5), las=2,
  143. main="", xlab="")
  144. title(main="A. Raw data", xlab="Log-cpm")
  145. abline(v=0, lty=3)
  146. for (i in 2:nsamples){
  147. den <- density(lcpm[,i])
  148. lines(den$x, den$y, col=fill[i], lwd=2)
  149. }
  150. #legend("topright", Samples, text.col=fill, bty="n")
  151. #filtered data
  152. #og-CPM of zero threshold (equivalent to a CPM value of 1) used in the filtering ste
  153. lcpm <- cpm(RGcpm, log=TRUE, prior.count=2)
  154. plot(density(lcpm[,1]), col=fill[1], lwd=2, ylim=c(0,0.5), las=2,
  155. main="", xlab="")
  156. title(main="B. Filtered data", xlab="Log-cpm")
  157. abline(v=0, lty=3)
  158. for (i in 2:nsamples){
  159. den <- density(lcpm[,i])
  160. lines(den$x, den$y, col=fill[i], lwd=2)
  161. }
  162. #legend("topright", Samples, text.col=fill, bty="n")
  163. dev.off()
  164. ###########################################################
  165. ###########################################################
  166. #reset library sizes
  167. RGcpm$samples$lib.size <- colSums(RGcpm$counts)
  168. #plot library sizes
  169. pdf('LibrarySizes.pdf',w=30,h=8)
  170. barplot(RGcpm$samples$lib.size,names=colnames(RGcpm),las=2)
  171. # Add a title to the plot
  172. title("Barplot of library sizes")
  173. dev.off()
  174. # Get log2 counts per million
  175. logcounts <- cpm(RGcpm,log=TRUE)
  176. # Check distributions of samples using boxplots
  177. pdf('NonNormalizedLogCPM.pdf',w=30,h=10)
  178. boxplot(logcounts, xlab="", ylab="Log2 counts per million",las=2)
  179. # Let's add a blue horizontal line that corresponds to the median logCPM
  180. abline(h=median(logcounts),col="blue")
  181. title("Boxplots of logCPMs (unnormalised)")
  182. dev.off()
  183. ##########################################################################
  184. #Diagnosis * treatment + sex with subjects correlation removed
  185. ##################################################################################
  186. #make design matrix
  187. Info3$Sex <- factor(Info3$Sex.x, levels=c("M","F"))
  188. Info3$Dam.Treatment.Group <- factor(Info3$Dam.Treatment.Group,levels = c("Saline","PolyIC"))
  189. Info3$Pup.Treatment.Group <- factor(Info3$Pup.Treatment.Group,levels = c("Saline","Treg"))
  190. Info3$Brain.Region <- factor(Info3$Brain.Region)
  191. Info3$Group <- factor(Info3$Group)
  192. #set design matrix
  193. design <- model.matrix(~0+Group, data=Info3) #if using a 0 intercept must set up contrasts
  194. colnames(design)
  195. ##################################################################################
  196. #Normalization TMM and Voom
  197. ##################################################################################
  198. #The two steps refer to different aspects of normalization. CPM "normalization" accounts for library size differences between samples, and produces normalized values that can be compared on an absolute scale (e.g., for filtering). TMM normalization accounts for composition bias, and computes normalization factors for comparing between libraries on a relative scale. CPM normalization doesn't account for composition bias, and TMM normalization doesn't produce normalized values. Thus, you need both steps in the analysis pipeline. This isn't a problem, as the two steps aren't really redundant.
  199. #TMM normalization for library composition
  200. DGE=calcNormFactors(RGcpm,method =c("TMM"))
  201. pdf('VoomTrend.pdf',w=6,h=4)
  202. v=voom(DGE,design,plot=T)
  203. dev.off()
  204. corfit <- duplicateCorrelation(v, design, block=Info3$Mouse.Number)
  205. fit <- lmFit(v, design, block = Info3$Mouse.Number, correlation = corfit$consensus)
  206. #compute RPKM off adjusted library sizes
  207. RPKM <- rpkm(DGE,gene.length =DGE$genes$genelength,normalized.lib.sizes = TRUE, log=F)
  208. #save
  209. save(RG,RGcpm,Info3,design,genes, RPKM,v,file="DEGlist.RData")
  210. ############################################################################################################################
  211. ############################################################################################################################
  212. ############################################################################################################################
  213. #WGCNA
  214. ############################################################################################################################
  215. ############################################################################################################################
  216. ############################################################################################################################
  217. #make WGCNA table
  218. #remove extra columns:
  219. DF <- RPKM
  220. #make gene matrix with genes as columns and rows as samples
  221. DF2 <- t(DF)
  222. DF2 <- as.data.frame(DF2)
  223. write.csv(DF2,"WGCNA_RPKMinputmatrix.csv")
  224. ################## process data ########################
  225. #detect genes with missing values or samples with missing values
  226. gsg = goodSamplesGenes(DF2, verbose = 3);
  227. gsg$allOK # TRUE
  228. #remove the genes with too many missing values
  229. if (!gsg$allOK)
  230. {
  231. # Optionally, print the gene and sample names that were removed:
  232. if (sum(!gsg$goodGenes)>0)
  233. printFlush(paste("Removing genes:", paste(names(DF2)[!gsg$goodGenes], collapse = ", ")));
  234. if (sum(!gsg$goodSamples)>0)
  235. printFlush(paste("Removing samples:", paste(rownames(DF2)[!gsg$goodSamples], collapse = ", ")));
  236. # Remove the offending genes and samples from the data:
  237. DF2 = DF2[gsg$goodSamples, gsg$goodGenes]
  238. }
  239. gsg = goodSamplesGenes(DF2, verbose = 3);
  240. gsg$allOK # TRUE
  241. #gene with RPKM value of 2 or higher in at least one sample.
  242. #max(col)>=2
  243. #https://stackoverflow.com/questions/24212739/how-to-find-the-highest-value-of-a-column-in-a-data-frame-in-r/24212879
  244. colMax <- function(data) sapply(data, max, na.rm = TRUE)
  245. DF3 <- DF2[, colMax(DF2) >= 2]
  246. dim(DF2)
  247. dim(DF3)
  248. #log2 transform:
  249. Log2DF3 <- log2(DF3+1)
  250. # median absolute deviation
  251. #remove if = 0 https://support.bioconductor.org/p/65124/
  252. colMad <- function(data) sapply(data, mad, na.rm = TRUE)
  253. DF4 = Log2DF3[, colMad(Log2DF3) != 0]
  254. dim(DF4) #6464 genes left
  255. write.csv(DF4,"WGCNA_log2RPKMinputmatrix.csv")
  256. #=====================================================================================
  257. #Next we cluster the samples (in contrast to clustering genes that will come later) to see if there are any obvious outliers.
  258. sampleTree = hclust(dist(DF4), method = "average");
  259. # Plot the sample tree: Open a graphic output window of size 12 by 9 inches
  260. # The user should change the dimensions if the window is too large or too small.
  261. sizeGrWindow(12,9)
  262. pdf(file = "sampleClustering_preCut.pdf", width = 12, height = 9);
  263. par(cex = 0.6);
  264. par(mar = c(0,4,2,0))
  265. plot(sampleTree, main = "Sample clustering to detect outliers", sub="", xlab="", cex.lab = 1.5,
  266. cex.axis = 1.5, cex.main = 2)
  267. # Plot a line to show the cut
  268. #remove two samples E18 tube 8 and P60 tube 50
  269. abline(h = 160, col = "red");
  270. dev.off()
  271. # Determine cluster under the line
  272. clust = cutreeStatic(sampleTree, cutHeight = 160, minSize = 10)
  273. table(clust)
  274. # clust 1 contains the samples we want to keep. > all in this case
  275. keepSamples = (clust==1)
  276. datExpr = DF4[keepSamples, ]
  277. nGenes = ncol(datExpr)
  278. nSamples = nrow(datExpr)
  279. #=====================================================================================
  280. #phenotype data:
  281. #Read in experient information sheet
  282. names(Info3)
  283. info <- Info3
  284. #filter to include only seq files:
  285. info$Sample.ID <- as.character(info$Sample.ID)
  286. infowt <- info[which(info$Sample.ID %in% rownames(datExpr)),]
  287. table(infowt$Sample.ID %in% rownames(datExpr)) #177 samples
  288. #match sample names and trait data:
  289. Samples = rownames(datExpr)
  290. traitRows = match(Samples, infowt$Sample.ID)
  291. datTraits = infowt[traitRows, ]
  292. datTraits<- as.data.frame(datTraits)
  293. datTraits$Sample.ID
  294. #change to numeric: sex #F =2 = red, M= 1 = white
  295. datTraits$sex2 <- as.numeric(as.factor(datTraits$Sex))
  296. #change to numeric: dam treatment 1=saline, 2=polyIC
  297. datTraits$Dam.Treatment.Group2 <- as.numeric(datTraits$Dam.Treatment.Group)
  298. #change to numeric: pup treatment 1=saline, 2=treg
  299. datTraits$Pup.Treatment.Group2 <- as.numeric(datTraits$Pup.Treatment.Group)
  300. #change to numeric: 1=Cerebellum, 2= Frontal, 3= Cortex Hippocampus
  301. datTraits$Brain.Region2 <- as.numeric(datTraits$Brain.Region)
  302. #numeric traits only
  303. numerictraits <- datTraits[,c(20,21,19,22)]
  304. rownames(numerictraits) <- datTraits$Sample.ID
  305. #We now have the expression data in the variable datExpr, and the corresponding clinical traits in the variable datTraits. Before we continue with network construction and module detection, we visualize how the clinical traits relate to the sample dendrogram.
  306. # Re-cluster samples
  307. sampleTree2 = hclust(dist(datExpr), method = "average")
  308. # Convert traits to a color representation: white means low, red means high, grey means missing entry
  309. traitColors1 = numbers2colors(numerictraits$Dam.Treatment.Group2,signed = FALSE);
  310. traitColors2 = numbers2colors(numerictraits$Pup.Treatment.Group2,signed = FALSE);
  311. traitColors3 = numbers2colors(numerictraits$sex2,signed = FALSE);
  312. traitColors <-cbind(traitColors1,traitColors2,traitColors3)
  313. colnames(traitColors) <- c("Dam treatment","Pup treatment","sex")
  314. # Plot the sample dendrogram and the colors underneath.
  315. pdf(file = "sampleClustering_withtraits.pdf", width = 12, height = 9)
  316. plotDendroAndColors(sampleTree2, traitColors, groupLabels = colnames(traitColors),
  317. main = "Sample dendrogram and trait heatmap")
  318. dev.off()
  319. save(numerictraits,datTraits,datExpr, file = "WTWGCNAnetworkConstruction-inputdata.RData")
  320. #=====================================================================================
  321. #choice of the soft thresholding power β to which co-expression similarity is raised to calculate adjacency
  322. # Choose a set of soft-thresholding powers
  323. powers = c(c(1:30))
  324. # Call the network topology analysis function
  325. sft = pickSoftThreshold(datExpr, powerVector = powers, networkType = "signed",corFnc="bicor" ,verbose = 5)
  326. # Plot the results:
  327. sizeGrWindow(9, 5)
  328. par(mfrow = c(1,2));
  329. cex1 = 0.9;
  330. # Scale-free topology fit index as a function of the soft-thresholding power
  331. plot(sft$fitIndices[,1], -sign(sft$fitIndices[,3])*sft$fitIndices[,2],
  332. xlab="Soft Threshold (power)",ylab="Scale Free Topology Model Fit,signed R^2",type="n",
  333. main = paste("Scale independence"));
  334. text(sft$fitIndices[,1], -sign(sft$fitIndices[,3])*sft$fitIndices[,2],
  335. labels=powers,cex=cex1,col="blue");
  336. # this line corresponds to using an R^2 cut-off of h
  337. abline(h=0.80,col="black")
  338. # Mean connectivity as a function of the soft-thresholding power
  339. plot(sft$fitIndices[,1], sft$fitIndices[,5],
  340. xlab="Soft Threshold (power)",ylab="Mean Connectivity", type="n",
  341. main = paste("Mean connectivity"))
  342. text(sft$fitIndices[,1], sft$fitIndices[,5], labels=powers, cex=cex1,col="blue")
  343. write.csv(sft, "SoftThresholding_powercalc.csv")
  344. #lowest power for which the scale-free topology fit index of > 0.8 ->5
  345. #=====================================================================================
  346. #Run this section on an external server, save the network data and load into R studio
  347. #=====================================================================================
  348. #Co-expression similarity and adjacency
  349. library(WGCNA)
  350. allowWGCNAThreads()
  351. # The following setting is important, do not omit.
  352. options(stringsAsFactors = FALSE)
  353. #load data
  354. Allnet = blockwiseModules(datExpr, maxBlockSize = 50000,
  355. power = 5, TOMType = "signed", minModuleSize = 20,
  356. networkType = "signed",
  357. corType = "bicor", #biweight midcorrelation
  358. maxPOutliers = 0.05, #forces bicor to never regard more than the specified proportion of samples as outliers.
  359. reassignThreshold = 0,
  360. numericLabels = TRUE,
  361. saveTOMs = FALSE,
  362. nThreads = 12,
  363. #saveTOMFileBase = "TOM-BilboMGExpression",
  364. verbose = 3)
  365. save(Allnet, file = "NetworkConstruction-auto_WTWGCNA.RData")
  366. #=====================================================================================
  367. table(Allnet$colors)
  368. # Convert labels to colors for plotting
  369. AllnetModuleColors = labels2colors(Allnet$colors)
  370. AllnetTree = Allnet$dendrograms[[1]]
  371. #plot the gene dendrogram and the corresponding module colors
  372. sizeGrWindow(8,6);
  373. pdf(file = "AllnetDendrogram_allsamples.pdf", wi = 8, he = 6)
  374. plotDendroAndColors(AllnetTree, AllnetModuleColors,
  375. "Module colors",
  376. dendroLabels = FALSE, hang = 0.03,
  377. addGuide = TRUE, guideHang = 0.05,
  378. main = "All Samples Cluster Dendrogram")
  379. dev.off()
  380. #=====================================================================================
  381. # Calculate eigengenes
  382. MEList = moduleEigengenes(datExpr, colors = AllnetModuleColors)
  383. MEs = MEList$eigengenes
  384. # Calculate dissimilarity of module eigengenes
  385. MEDiss = 1-cor(MEs);
  386. # Cluster module eigengenes
  387. METree = hclust(as.dist(MEDiss), method = "average");
  388. # Plot the result
  389. sizeGrWindow(7, 6)
  390. pdf(file = "Pretrim_allnet_dendrogram.pdf", wi = 9, he = 6)
  391. plot(METree, main = "Clustering of module eigengenes",
  392. xlab = "", sub = "")
  393. # Plot the cut line into the dendrogram
  394. abline(h=0.6, col = "red")
  395. dev.off()
  396. #=====================================================================================
  397. #merge down to fewer modules based on plot height
  398. MEDissThres = 0.1
  399. # Call an automatic merging function
  400. merge = mergeCloseModules(datExpr, AllnetModuleColors, cutHeight = MEDissThres, verbose = 3)
  401. # The merged module colors
  402. mColors = merge$colors;
  403. # Eigengenes of the new merged modules:
  404. mergedMEs = merge$newMEs;
  405. #replot
  406. sizeGrWindow(12, 9)
  407. pdf(file = "Allnet_postmerg.1MEClustering.pdf", wi = 9, he = 6)
  408. plotDendroAndColors(AllnetTree, mColors,
  409. "Module colors",
  410. dendroLabels = FALSE, hang = 0.03,
  411. addGuide = TRUE, guideHang = 0.05,
  412. main = "All Samples Cluster Dendrogram")
  413. dev.off()
  414. #=====================================================================================
  415. # Rename to moduleColors
  416. moduleColors = mColors
  417. # Construct numerical labels corresponding to the colors
  418. colorOrder = c("grey", standardColors(50));
  419. moduleLabels = match(moduleColors, colorOrder)-1;
  420. MEs = mergedMEs;
  421. # Save module colors and labels for use in subsequent parts
  422. save(MEs, moduleLabels, moduleColors, AllnetTree, datTraits, numerictraits,datExpr,Allnet,file = "allsamplesWTMGtimecourse-networkpostmerge.1.RData")
  423. #load("allsamplesbilboMGtimecourse-networkpostmerge.25.RData")
  424. #=====================================================================================
  425. #repeat clustering of new MEs
  426. # Calculate dissimilarity of module eigengenes
  427. MEDiss = 1-cor(MEs);
  428. # Cluster module eigengenes
  429. METree = hclust(as.dist(MEDiss), method = "average");
  430. # Plot the result
  431. sizeGrWindow(7, 6)
  432. pdf(file = "Pretrim_allnet_dendrogram_postmerge.pdf", wi = 9, he = 6)
  433. plot(METree, main = "Clustering of module eigengenes after merging modules",
  434. xlab = "", sub = "")
  435. dev.off()
  436. #=====================================================================================
  437. #=====================================================================================
  438. #correlate eigengenes with external traits and look for the most signi cant associations
  439. # Define numbers of genes and samples
  440. nGenes = ncol(datExpr);
  441. nSamples = nrow(datExpr);
  442. # Recalculate MEs with color labels
  443. MEs0 = moduleEigengenes(datExpr, moduleColors)$eigengenes
  444. MEs = orderMEs(MEs0)
  445. moduleTraitCor = cor(MEs, numerictraits, use = "p");
  446. moduleTraitPvalue = corPvalueStudent(moduleTraitCor, nSamples)
  447. #FDR correct the pvalues
  448. #sapply(pval,p.adjust,method="fdr") #per column
  449. #FDR correction on entire matrix
  450. FDR <- matrix(p.adjust(as.vector(moduleTraitPvalue), method='fdr'),ncol=ncol(moduleTraitPvalue))
  451. colnames(FDR) <- colnames(moduleTraitPvalue)
  452. rownames(FDR) <- rownames(moduleTraitPvalue)
  453. corout <- cbind(moduleTraitCor,FDR)
  454. write.csv(corout, "PearsonsCorrelations_mod-trait.csv",row.names = T)
  455. #We color code each association by the correlation value:
  456. sizeGrWindow(10,6)
  457. pdf(file = "module-traitrelationshipsFDRcorrected.pdf", wi = 8.5, he = 11)
  458. # Will display correlations and their p-values
  459. textMatrix = paste(signif(moduleTraitCor, 2), "\ (", #pearson correlation coefficient, space, (FDR corrected pvalue)
  460. signif(FDR, 4), ")", sep = "");
  461. dim(textMatrix) = dim(moduleTraitCor)
  462. par(mar = c(6, 8.5, 3, 3));
  463. # Display the correlation values within a heatmap plot
  464. labeledHeatmap(Matrix = moduleTraitCor,
  465. xLabels = names(numerictraits),
  466. yLabels = names(MEs),
  467. ySymbols = names(MEs),
  468. colorLabels = FALSE,
  469. colors = blueWhiteRed(50),
  470. textMatrix = textMatrix,
  471. setStdMargins = FALSE,
  472. cex.text = 0.9,
  473. zlim = c(-1,1),
  474. main = paste("Module-trait relationships"))
  475. dev.off()
  476. #=====================================================================================
  477. #ANOVA for trait associations
  478. #=====================================================================================
  479. library(nlme)
  480. library(lsmeans)
  481. datTraits <- as.data.frame(datTraits)
  482. datTraits$sex <- factor(datTraits$sex)
  483. datTraits$Dam.Treatment.Group <- factor(datTraits$Dam.Treatment.Group)
  484. datTraits$Pup.Treatment.Group <- factor(datTraits$Pup.Treatment.Group)
  485. datTraits$Brain.Region <- factor(datTraits$Brain.Region)
  486. datTraits$subject <- datTraits$Sample.ID
  487. MEs$Sample.ID <- rownames(MEs)
  488. datComb <- merge(datTraits,MEs, by = "Sample.ID")
  489. datComb2 <- datComb %>% gather(module, ME, 25:ncol(datComb))
  490. write.csv(datComb2,"Moduel-ME_dataforANOVA.csv")
  491. mod <- unique(datComb2$module)
  492. #remove grey
  493. mod <- head(mod, -1)
  494. anova_out <- NULL
  495. for (i in mod) {
  496. print(i)
  497. #select data
  498. dattmp <- datComb2 %>% dplyr::filter(module == i)
  499. #model
  500. tmp <- lme(ME ~ Dam.Treatment.Group*Pup.Treatment.Group*sex*Brain.Region, ~1|Sample.ID, data = dattmp)
  501. #model indcludes random effects subject ID
  502. anova <- anova(tmp, type = "marginal") #marginal gives Type 3 SS for ANOVA
  503. #write anova to output file
  504. anova <- as.data.frame(anova)
  505. anova$condition <- rownames(anova)
  506. anova <- anova[-1,]
  507. anova2 <- anova %>% gather(stats,values,1:4) %>%
  508. mutate(col = paste(condition,stats, sep="_")) %>%
  509. dplyr::select(col,values) %>%
  510. spread(col,values)
  511. anova2$module <- paste(i)
  512. #save to loop
  513. anova_out <- rbind(anova_out,anova2)
  514. }
  515. write.csv(anova_out,"MixedModelAnova_moudle-traits.csv")
  516. #include post hocs
  517. anova_out <- NULL
  518. ME_posthoc <- NULL
  519. for (i in mod) {
  520. print(i)
  521. #select data
  522. dattmp <- datComb2 %>% dplyr::filter(module == i)
  523. #model
  524. tmp <- lme(ME ~ Dam.Treatment.Group*Pup.Treatment.Group*sex*Brain.Region, ~1|Sample.ID, data = dattmp)
  525. #model indcludes random effects subject ID
  526. anova <- anova(tmp, type = "marginal") #marginal gives Type 3 SS for ANOVA
  527. #write anova to output file
  528. anova <- as.data.frame(anova)
  529. anova$condition <- rownames(anova)
  530. anova <- anova[-1,]
  531. anova2 <- anova %>% gather(stats,values,1:4) %>%
  532. mutate(col = paste(condition,stats, sep="_")) %>%
  533. dplyr::select(col,values) %>%
  534. spread(col,values)
  535. anova2$module <- paste(i)
  536. #save to loop
  537. anova_out <- rbind(anova_out,anova2)
  538. ## POSTHOC starts here ##
  539. #create a reference grid model object
  540. ME_refgrid <- ref.grid(tmp)
  541. #creates a fitted model using the reference grid, based on treatment and brain region interactions
  542. ME_lsmeans <- lsmeans(ME_refgrid, ~Dam.Treatment.Group*Pup.Treatment.Group|sex*Brain.Region)
  543. #summarize paired comparisons
  544. ME_lsmeans_summary <- summary(pairs(ME_lsmeans, adjust = "none"))
  545. ME_lsmeans_summary <- as.data.frame(ME_lsmeans_summary)
  546. #posthocHSD = contrast(refgrid, method = "pairwise",adjust = "none")
  547. #outsum <- as.data.frame(summary(posthocHSD))
  548. #get only control vs LPS
  549. # outsum <- outsum[grepl("CONTROL", outsum$contrast),]
  550. #correct for multiple comparisons
  551. ME_lsmeans_summary$padjust <- p.adjust(ME_lsmeans_summary$p.value, method = "BH")
  552. #paste module information
  553. ME_lsmeans_summary$module <- paste(i)
  554. #save to output
  555. ME_posthoc <- rbind(ME_posthoc,ME_lsmeans_summary)
  556. }
  557. write.csv(ME_posthoc,"BHposthocs_moudle-traits.csv")
  558. #graph MEs
  559. pdf(file = "boxplot_MEs.pdf", wi = 22, he = 30)
  560. #
  561. p <- ggplot(datComb2, aes(x=Dam.Treatment.Group, y=ME), group = Pup.Treatment.Group) +
  562. facet_wrap(~module*Brain.Region*Sex.x,ncol = 6, scales = "free") +
  563. stat_summary(geom = "boxplot",
  564. fun.data = function(x) setNames(quantile(x, c(0.05, 0.25, 0.5, 0.75, 0.95)), c("ymin", "lower", "middle", "upper", "ymax")),
  565. position = "dodge", aes(fill=Pup.Treatment.Group))+ #gives line as median, top of box and bottom of box as 25th and 75th quartile, line = 5th and 9th percentile
  566. geom_point(position = position_dodge(width = 0.90),aes(group=Pup.Treatment.Group, colour=Sex.x)) +
  567. scale_fill_manual(values = cbPalette) +
  568. theme_cowplot(font_size = 15)+
  569. theme(axis.text.x = element_text(angle=45, vjust=0.5),
  570. strip.background = element_rect(fill="#B0C4DE"),
  571. # legend.position="none",
  572. strip.text.x = element_text(size = 20))+
  573. xlab(label = c("Dam Treatment")) +
  574. ylab(label = c("ME"))
  575. p
  576. dev.off()
  577. #
  578. #graph MEs Cerebellum ME blue
  579. pdf(file = "boxplot_MEs_CB_blue.pdf", wi = 6, he = 4)
  580. #
  581. CBblue <- datComb2 %>% filter(module == "MEblue") %>% filter(Brain.Region == "Cerebellum")
  582. p <- ggplot(CBblue, aes(x=Dam.Treatment.Group, y=ME), group = Pup.Treatment.Group) +
  583. facet_wrap(~Sex.x,ncol = 2) +
  584. stat_summary(geom = "boxplot",
  585. fun.data = function(x) setNames(quantile(x, c(0.05, 0.25, 0.5, 0.75, 0.95)), c("ymin", "lower", "middle", "upper", "ymax")),
  586. position = "dodge", aes(fill=Pup.Treatment.Group))+ #gives line as median, top of box and bottom of box as 25th and 75th quartile, line = 5th and 9th percentile
  587. geom_point(position = position_dodge(width = 0.90),aes(group=Pup.Treatment.Group)) +
  588. scale_fill_manual(values = cbPalette) +
  589. theme_cowplot(font_size = 15)+
  590. theme(axis.text.x = element_text(angle=45, vjust=0.5),
  591. strip.background = element_rect(fill="#B0C4DE"),
  592. # legend.position="none",
  593. strip.text.x = element_text(size = 20))+
  594. xlab(label = c("Dam Treatment")) +
  595. ylab(label = c("ME"))
  596. p
  597. dev.off()
  598. #
  599. #graph MEs Cerebellum ME turquoise
  600. pdf(file = "boxplot_MEs_CB_turquoise.pdf", wi = 6, he = 4)
  601. #
  602. CBturquoise <- datComb2 %>% filter(module == "MEturquoise") %>% filter(Brain.Region == "Cerebellum")
  603. p <- ggplot(CBturquoise, aes(x=Dam.Treatment.Group, y=ME), group = Pup.Treatment.Group) +
  604. facet_wrap(~Sex.x,ncol = 2) +
  605. stat_summary(geom = "boxplot",
  606. fun.data = function(x) setNames(quantile(x, c(0.05, 0.25, 0.5, 0.75, 0.95)), c("ymin", "lower", "middle", "upper", "ymax")),
  607. position = "dodge", aes(fill=Pup.Treatment.Group))+ #gives line as median, top of box and bottom of box as 25th and 75th quartile, line = 5th and 9th percentile
  608. geom_point(position = position_dodge(width = 0.90),aes(group=Pup.Treatment.Group)) +
  609. scale_fill_manual(values = cbPalette) +
  610. theme_cowplot(font_size = 15)+
  611. theme(axis.text.x = element_text(angle=45, vjust=0.5),
  612. strip.background = element_rect(fill="#B0C4DE"),
  613. # legend.position="none",
  614. strip.text.x = element_text(size = 20))+
  615. xlab(label = c("Dam Treatment")) +
  616. ylab(label = c("ME"))
  617. p
  618. dev.off()
  619. #
  620. #graph MEs HC ME turquoise
  621. pdf(file = "boxplot_MEs_HC_turquoise.pdf", wi = 6, he = 4)
  622. #
  623. HCturquoise <- datComb2 %>% filter(module == "MEturquoise") %>% filter(Brain.Region == "Hippocampus")
  624. p <- ggplot(HCturquoise, aes(x=Dam.Treatment.Group, y=ME), group = Pup.Treatment.Group) +
  625. facet_wrap(~Sex.x,ncol = 2) +
  626. stat_summary(geom = "boxplot",
  627. fun.data = function(x) setNames(quantile(x, c(0.05, 0.25, 0.5, 0.75, 0.95)), c("ymin", "lower", "middle", "upper", "ymax")),
  628. position = "dodge", aes(fill=Pup.Treatment.Group))+ #gives line as median, top of box and bottom of box as 25th and 75th quartile, line = 5th and 9th percentile
  629. geom_point(position = position_dodge(width = 0.90),aes(group=Pup.Treatment.Group)) +
  630. scale_fill_manual(values = cbPalette) +
  631. theme_cowplot(font_size = 15)+
  632. theme(axis.text.x = element_text(angle=45, vjust=0.5),
  633. strip.background = element_rect(fill="#B0C4DE"),
  634. # legend.position="none",
  635. strip.text.x = element_text(size = 20))+
  636. xlab(label = c("Dam Treatment")) +
  637. ylab(label = c("ME"))
  638. p
  639. dev.off()
  640. #
  641. #graph MEs Cerebellum ME turquoise
  642. pdf(file = "boxplot_MEs_FC_green.pdf",wi = 6, he = 4)
  643. #
  644. FCgreen <- datComb2 %>% filter(module == "MEgreen") %>% filter(Brain.Region == "Frontal Cortex")
  645. p <- ggplot(FCgreen, aes(x=Dam.Treatment.Group, y=ME), group = Pup.Treatment.Group) +
  646. facet_wrap(~Sex.x,ncol = 2) +
  647. stat_summary(geom = "boxplot",
  648. fun.data = function(x) setNames(quantile(x, c(0.05, 0.25, 0.5, 0.75, 0.95)), c("ymin", "lower", "middle", "upper", "ymax")),
  649. position = "dodge", aes(fill=Pup.Treatment.Group))+ #gives line as median, top of box and bottom of box as 25th and 75th quartile, line = 5th and 9th percentile
  650. geom_point(position = position_dodge(width = 0.90),aes(group=Pup.Treatment.Group)) +
  651. scale_fill_manual(values = cbPalette) +
  652. theme_cowplot(font_size = 15)+
  653. theme(axis.text.x = element_text(angle=45, vjust=0.5),
  654. strip.background = element_rect(fill="#B0C4DE"),
  655. # legend.position="none",
  656. strip.text.x = element_text(size = 20))+
  657. xlab(label = c("Dam Treatment")) +
  658. ylab(label = c("ME"))
  659. p
  660. dev.off()
  661. #
  662. pdf(file = "boxplot_MEs_FC_yellow.pdf", wi = 6, he = 4)
  663. #
  664. FCyellow <- datComb2 %>% filter(module == "MEyellow") %>% filter(Brain.Region == "Frontal Cortex")
  665. p <- ggplot(FCyellow, aes(x=Dam.Treatment.Group, y=ME), group = Pup.Treatment.Group) +
  666. facet_wrap(~Sex.x,ncol = 2) +
  667. stat_summary(geom = "boxplot",
  668. fun.data = function(x) setNames(quantile(x, c(0.05, 0.25, 0.5, 0.75, 0.95)), c("ymin", "lower", "middle", "upper", "ymax")),
  669. position = "dodge", aes(fill=Pup.Treatment.Group))+ #gives line as median, top of box and bottom of box as 25th and 75th quartile, line = 5th and 9th percentile
  670. geom_point(position = position_dodge(width = 0.90),aes(group=Pup.Treatment.Group)) +
  671. scale_fill_manual(values = cbPalette) +
  672. theme_cowplot(font_size = 15)+
  673. theme(axis.text.x = element_text(angle=45, vjust=0.5),
  674. strip.background = element_rect(fill="#B0C4DE"),
  675. # legend.position="none",
  676. strip.text.x = element_text(size = 20))+
  677. xlab(label = c("Dam Treatment")) +
  678. ylab(label = c("ME"))
  679. p
  680. dev.off()
  681. #
  682. datComb2 <- read.csv("/Users/aciernia/Sync/collaborations/Ashwood/MIATcellRNAseq/WGCNA/Moduel-ME_dataforANOVA.csv")
  683. #graph MEs
  684. datComb2$Pup.Treatment.Group <- gsub("Treg","Tregs",datComb2$Pup.Treatment.Group)
  685. datComb2$Treatment <- paste(datComb2$Dam.Treatment.Group, datComb2$Pup.Treatment.Group, sep="-")
  686. datComb2$Treatment <- factor(datComb2$Treatment,levels=c("Saline-Saline","Saline-Tregs","PolyIC-Saline","PolyIC-Tregs"))
  687. #Saline–Saline (dark blue) — #777787
  688. #Saline–Treg (light blue) — #747788
  689. #Poly I:C–Saline (red) — #b15b53
  690. #Poly I:C–Treg (light red/pink) — #b2817f
  691. cbPalette <- c("#5756f9","#92bffa","#fe0100","#fe8080")
  692. #graph MEs Cerebellum ME blue
  693. pdf(file = "boxplot_MEs_CB_blue_wide.pdf", wi = 8, he = 6)
  694. #
  695. CBblue <- datComb2 %>% filter(module == "MEblue") %>% filter(Brain.Region == "Cerebellum")
  696. p <- ggplot(CBblue, aes(x = Treatment, y = ME, fill = Treatment)) +
  697. facet_wrap(~ Sex.x, ncol = 2) +
  698. stat_summary(
  699. geom = "boxplot",
  700. fun.data = function(x) {
  701. qs <- quantile(x, c(0.05, 0.25, 0.5, 0.75, 0.95), na.rm = TRUE)
  702. setNames(qs, c("ymin", "lower", "middle", "upper", "ymax"))
  703. },
  704. position = position_dodge2(width = 0.9, preserve = "single")
  705. ) +
  706. geom_point(position = position_dodge(width = 0.9), aes(group = Treatment), alpha = 0.8) +
  707. scale_fill_manual(values = cbPalette) +
  708. # two-line x labels: keep "-" on the top line
  709. scale_x_discrete(labels = function(x) {
  710. parts <- strsplit(x, "\\s*[\\-–—]\\s*", perl = TRUE)
  711. sapply(seq_along(parts), function(i) {
  712. if (length(parts[[i]]) >= 2) paste0(parts[[i]][1], " -\n", parts[[i]][2]) else x[i]
  713. })
  714. }) +
  715. theme_cowplot(font_size = 15) +
  716. theme(
  717. axis.text.x = element_text(angle = 0, hjust = 0.5, lineheight = 0.9),
  718. strip.background = element_rect(fill = "#B0C4DE"),
  719. strip.text.x = element_text(size = 20),
  720. legend.position = "none"
  721. ) +
  722. xlab("Treatment") +
  723. ylab("ME")
  724. p
  725. dev.off()
  726. #
  727. #graph MEs Cerebellum ME turquoise
  728. pdf(file = "boxplot_MEs_CB_turquoise_wide.pdf", wi = 8, he = 6)
  729. #
  730. CBturquoise <- datComb2 %>% filter(module == "MEturquoise") %>% filter(Brain.Region == "Cerebellum")
  731. p <- ggplot(CBturquoise, aes(x = Treatment, y = ME, fill = Treatment)) +
  732. facet_wrap(~ Sex.x, ncol = 2) +
  733. stat_summary(
  734. geom = "boxplot",
  735. fun.data = function(x) {
  736. qs <- quantile(x, c(0.05, 0.25, 0.5, 0.75, 0.95), na.rm = TRUE)
  737. setNames(qs, c("ymin", "lower", "middle", "upper", "ymax"))
  738. },
  739. position = position_dodge2(width = 0.9, preserve = "single")
  740. ) +
  741. geom_point(position = position_dodge(width = 0.9), aes(group = Treatment), alpha = 0.8) +
  742. scale_fill_manual(values = cbPalette) +
  743. # two-line x labels: keep "-" on the top line
  744. scale_x_discrete(labels = function(x) {
  745. parts <- strsplit(x, "\\s*[\\-–—]\\s*", perl = TRUE)
  746. sapply(seq_along(parts), function(i) {
  747. if (length(parts[[i]]) >= 2) paste0(parts[[i]][1], " -\n", parts[[i]][2]) else x[i]
  748. })
  749. }) +
  750. theme_cowplot(font_size = 15) +
  751. theme(
  752. axis.text.x = element_text(angle = 0, hjust = 0.5, lineheight = 0.9),
  753. strip.background = element_rect(fill = "#B0C4DE"),
  754. strip.text.x = element_text(size = 20),
  755. legend.position = "none"
  756. ) +
  757. xlab("Treatment") +
  758. ylab("ME")
  759. p
  760. dev.off()
  761. #
  762. #graph MEs HC ME turquoise
  763. pdf(file = "boxplot_MEs_HC_turquoise_wide.pdf", wi = 8, he = 6)
  764. #
  765. HCturquoise <- datComb2 %>% filter(module == "MEturquoise") %>% filter(Brain.Region == "Hippocampus")
  766. p <- ggplot(HCturquoise, aes(x = Treatment, y = ME, fill = Treatment)) +
  767. facet_wrap(~ Sex.x, ncol = 2) +
  768. stat_summary(
  769. geom = "boxplot",
  770. fun.data = function(x) {
  771. qs <- quantile(x, c(0.05, 0.25, 0.5, 0.75, 0.95), na.rm = TRUE)
  772. setNames(qs, c("ymin", "lower", "middle", "upper", "ymax"))
  773. },
  774. position = position_dodge2(width = 0.9, preserve = "single")
  775. ) +
  776. geom_point(position = position_dodge(width = 0.9), aes(group = Treatment), alpha = 0.8) +
  777. scale_fill_manual(values = cbPalette) +
  778. # two-line x labels: keep "-" on the top line
  779. scale_x_discrete(labels = function(x) {
  780. parts <- strsplit(x, "\\s*[\\-–—]\\s*", perl = TRUE)
  781. sapply(seq_along(parts), function(i) {
  782. if (length(parts[[i]]) >= 2) paste0(parts[[i]][1], " -\n", parts[[i]][2]) else x[i]
  783. })
  784. }) +
  785. theme_cowplot(font_size = 15) +
  786. theme(
  787. axis.text.x = element_text(angle = 0, hjust = 0.5, lineheight = 0.9),
  788. strip.background = element_rect(fill = "#B0C4DE"),
  789. strip.text.x = element_text(size = 20),
  790. legend.position = "none"
  791. ) +
  792. xlab("Treatment") +
  793. ylab("ME")
  794. p
  795. dev.off()
  796. #
  797. #graph MEs Cerebellum ME turquoise
  798. pdf(file = "boxplot_MEs_FC_green_wide.pdf",wi = 8, he = 6)
  799. #
  800. FCgreen <- datComb2 %>% filter(module == "MEgreen") %>% filter(Brain.Region == "Frontal Cortex")
  801. p <- ggplot(FCgreen, aes(x = Treatment, y = ME, fill = Treatment)) +
  802. facet_wrap(~ Sex.x, ncol = 2) +
  803. stat_summary(
  804. geom = "boxplot",
  805. fun.data = function(x) {
  806. qs <- quantile(x, c(0.05, 0.25, 0.5, 0.75, 0.95), na.rm = TRUE)
  807. setNames(qs, c("ymin", "lower", "middle", "upper", "ymax"))
  808. },
  809. position = position_dodge2(width = 0.9, preserve = "single")
  810. ) +
  811. geom_point(position = position_dodge(width = 0.9), aes(group = Treatment), alpha = 0.8) +
  812. scale_fill_manual(values = cbPalette) +
  813. # two-line x labels: keep "-" on the top line
  814. scale_x_discrete(labels = function(x) {
  815. parts <- strsplit(x, "\\s*[\\-–—]\\s*", perl = TRUE)
  816. sapply(seq_along(parts), function(i) {
  817. if (length(parts[[i]]) >= 2) paste0(parts[[i]][1], " -\n", parts[[i]][2]) else x[i]
  818. })
  819. }) +
  820. theme_cowplot(font_size = 15) +
  821. theme(
  822. axis.text.x = element_text(angle = 0, hjust = 0.5, lineheight = 0.9),
  823. strip.background = element_rect(fill = "#B0C4DE"),
  824. strip.text.x = element_text(size = 20),
  825. legend.position = "none"
  826. ) +
  827. xlab("Treatment") +
  828. ylab("ME")
  829. p
  830. dev.off()
  831. #
  832. pdf(file = "boxplot_MEs_FC_yellow_wide.pdf", wi = 8, he = 6)
  833. #
  834. FCyellow <- datComb2 %>% filter(module == "MEyellow") %>% filter(Brain.Region == "Frontal Cortex")
  835. p <- ggplot(FCyellow, aes(x = Treatment, y = ME, fill = Treatment)) +
  836. facet_wrap(~ Sex.x, ncol = 2) +
  837. stat_summary(
  838. geom = "boxplot",
  839. fun.data = function(x) {
  840. qs <- quantile(x, c(0.05, 0.25, 0.5, 0.75, 0.95), na.rm = TRUE)
  841. setNames(qs, c("ymin", "lower", "middle", "upper", "ymax"))
  842. },
  843. position = position_dodge2(width = 0.9, preserve = "single")
  844. ) +
  845. geom_point(position = position_dodge(width = 0.9), aes(group = Treatment), alpha = 0.8) +
  846. scale_fill_manual(values = cbPalette) +
  847. # two-line x labels: keep "-" on the top line
  848. scale_x_discrete(labels = function(x) {
  849. parts <- strsplit(x, "\\s*[\\-–—]\\s*", perl = TRUE)
  850. sapply(seq_along(parts), function(i) {
  851. if (length(parts[[i]]) >= 2) paste0(parts[[i]][1], " -\n", parts[[i]][2]) else x[i]
  852. })
  853. }) +
  854. theme_cowplot(font_size = 15) +
  855. theme(
  856. axis.text.x = element_text(angle = 0, hjust = 0.5, lineheight = 0.9),
  857. strip.background = element_rect(fill = "#B0C4DE"),
  858. strip.text.x = element_text(size = 20),
  859. legend.position = "none"
  860. ) +
  861. xlab("Treatment") +
  862. ylab("ME")
  863. p
  864. dev.off()
  865. #
  866. pdf(file = "boxplot_MEs_FC_brown_wide.pdf", wi = 8, he = 6)
  867. #
  868. FCbrown <- datComb2 %>% filter(module == "MEbrown") %>% filter(Brain.Region == "Frontal Cortex")
  869. p <- ggplot(FCbrown, aes(x = Treatment, y = ME, fill = Treatment)) +
  870. facet_wrap(~ Sex.x, ncol = 2) +
  871. stat_summary(
  872. geom = "boxplot",
  873. fun.data = function(x) {
  874. qs <- quantile(x, c(0.05, 0.25, 0.5, 0.75, 0.95), na.rm = TRUE)
  875. setNames(qs, c("ymin", "lower", "middle", "upper", "ymax"))
  876. },
  877. position = position_dodge2(width = 0.9, preserve = "single")
  878. ) +
  879. geom_point(position = position_dodge(width = 0.9), aes(group = Treatment), alpha = 0.8) +
  880. scale_fill_manual(values = cbPalette) +
  881. # two-line x labels: keep "-" on the top line
  882. scale_x_discrete(labels = function(x) {
  883. parts <- strsplit(x, "\\s*[\\-–—]\\s*", perl = TRUE)
  884. sapply(seq_along(parts), function(i) {
  885. if (length(parts[[i]]) >= 2) paste0(parts[[i]][1], " -\n", parts[[i]][2]) else x[i]
  886. })
  887. }) +
  888. theme_cowplot(font_size = 15) +
  889. theme(
  890. axis.text.x = element_text(angle = 0, hjust = 0.5, lineheight = 0.9),
  891. strip.background = element_rect(fill = "#B0C4DE"),
  892. strip.text.x = element_text(size = 20),
  893. legend.position = "none"
  894. ) +
  895. xlab("Treatment") +
  896. ylab("ME")
  897. p
  898. dev.off()
  899. #
  900. #save.image(file = "AllFiles.RData")
  901. #load(file = "/Users/aciernia/Sync/collaborations/Ashwood/MIATcellRNAseq/WGCNA/AllFiles.RData")
  902. #quantify associations of individual genes with our trait of interest (years) by de ning Gene Signi cance GS as
  903. #(the absolute value of) the correlation between the gene and the trait
  904. #For each module, we also de ne a quantitative
  905. #measure of module membership MM as the correlation of the module eigengene and the gene expression pro le. This
  906. #allows us to quantify the similarity of all genes on the array to every module.
  907. ##module membership MM
  908. #correlation between expression of each gene and MEs (uncorrected p values)
  909. MEs <- MEs %>% dplyr::select(-Sample.ID)
  910. # names (colors) of the modules
  911. modNames = substring(names(MEs), 3)
  912. geneModuleMembership = as.data.frame(cor(datExpr, MEs, use = "p"));
  913. MMPvalue = as.data.frame(corPvalueStudent(as.matrix(geneModuleMembership), nSamples));
  914. names(geneModuleMembership) = paste("MM", modNames, sep="");
  915. names(MMPvalue) = paste("p.MM", modNames, sep="");
  916. #or
  917. # calculate the module membership values (aka. module eigengene based
  918. # connectivity kME):
  919. #datKME = signedKME(PFCdatExpr, MEs)
  920. #correlate each gene expression with variable of interest
  921. # Define variable age containing the years column of datTrait
  922. #dam
  923. Dam.Treatment = as.data.frame(numerictraits$Dam.Treatment.Group2);
  924. names(Dam.Treatment) = "Dam.Treatment"
  925. Dam_geneTraitSignificance = as.data.frame(cor(datExpr, Dam.Treatment, use = "p"));
  926. Dam_GSPvalue = as.data.frame(corPvalueStudent(as.matrix(Dam_geneTraitSignificance), nSamples));
  927. names(Dam_geneTraitSignificance) = paste("GS.", names(Dam.Treatment), sep="");
  928. names(Dam_GSPvalue) = paste("p.GS.", names(Dam.Treatment), sep="")
  929. #pups
  930. Pup.Treatment = as.data.frame(numerictraits$Pup.Treatment.Group2);
  931. names(Pup.Treatment) = "Pup.Treatment"
  932. Pup_geneTraitSignificance = as.data.frame(cor(datExpr, Pup.Treatment, use = "p"));
  933. Pup_GSPvalue = as.data.frame(corPvalueStudent(as.matrix(Pup_geneTraitSignificance), nSamples));
  934. names(Pup_geneTraitSignificance) = paste("GS.", names(Pup.Treatment), sep="");
  935. names(Pup_GSPvalue) = paste("p.GS.", names(Pup.Treatment), sep="")
  936. #Regions
  937. Region = as.data.frame(numerictraits$Brain.Region2);
  938. names(Region) = "Brain Region"
  939. Region_geneTraitSignificance = as.data.frame(cor(datExpr, Region, use = "p"));
  940. Region_GSPvalue = as.data.frame(corPvalueStudent(as.matrix(Region_geneTraitSignificance), nSamples));
  941. names(Region_geneTraitSignificance) = paste("GS.", names(Region), sep="");
  942. names(Region_GSPvalue) = paste("p.GS.", names(Region), sep="")
  943. #=====================================================================================
  944. #Intramodular analysis: identifying genes with high GS and MM
  945. #Using the GS and MM measures, we can identify genes that have a high signi cance for weight as well as high module
  946. #membership in interesting modules.
  947. #As an example, we look at the brown module that has the highest association with age.
  948. pdf(file = "Damtreatment_geneModuleMembershipvsGeneSignificanceAGE.pdf", wi = 10, he = 10)
  949. par(mfrow = c(2,2));
  950. module = "blue"
  951. column = match(module, modNames);
  952. moduleGenes = moduleColors==module;
  953. verboseScatterplot(abs(geneModuleMembership[moduleGenes, column]),
  954. abs(Dam_geneTraitSignificance[moduleGenes, 1]),
  955. xlab = paste("Module Membership in", module, "module"),
  956. ylab = "Dam Treatment Gene significance for age",
  957. main = paste("Module membership vs. Dam treatment gene significance\n"),
  958. cex.main = 1.2, cex.lab = 1.2, cex.axis = 1.2, col = module)
  959. module = "brown"
  960. column = match(module, modNames);
  961. moduleGenes = moduleColors==module;
  962. verboseScatterplot(abs(geneModuleMembership[moduleGenes, column]),
  963. abs(Dam_geneTraitSignificance[moduleGenes, 1]),
  964. xlab = paste("Module Membership in", module, "module"),
  965. ylab = "Dam Treatment Gene significance for age",
  966. main = paste("Module membership vs. Dam treatment gene significance\n"),
  967. cex.main = 1.2, cex.lab = 1.2, cex.axis = 1.2, col = module)
  968. module = "turquoise"
  969. column = match(module, modNames);
  970. moduleGenes = moduleColors==module;
  971. verboseScatterplot(abs(geneModuleMembership[moduleGenes, column]),
  972. abs(Dam_geneTraitSignificance[moduleGenes, 1]),
  973. xlab = paste("Module Membership in", module, "module"),
  974. ylab = "Dam Treatment Gene significance for age",
  975. main = paste("Module membership vs. Dam treatment gene significance\n"),
  976. cex.main = 1.2, cex.lab = 1.2, cex.axis = 1.2, col = module)
  977. module = "green"
  978. column = match(module, modNames);
  979. moduleGenes = moduleColors==module;
  980. verboseScatterplot(abs(geneModuleMembership[moduleGenes, column]),
  981. abs(Dam_geneTraitSignificance[moduleGenes, 1]),
  982. xlab = paste("Module Membership in", module, "module"),
  983. ylab = "Dam Treatment Gene significance for age",
  984. main = paste("Module membership vs. Dam treatment gene significance\n"),
  985. cex.main = 1.2, cex.lab = 1.2, cex.axis = 1.2, col = module)
  986. module = "yellow"
  987. column = match(module, modNames);
  988. moduleGenes = moduleColors==module;
  989. verboseScatterplot(abs(geneModuleMembership[moduleGenes, column]),
  990. abs(Dam_geneTraitSignificance[moduleGenes, 1]),
  991. xlab = paste("Module Membership in", module, "module"),
  992. ylab = "Dam Treatment Gene significance for age",
  993. main = paste("Module membership vs. Dam treatment gene significance\n"),
  994. cex.main = 1.2, cex.lab = 1.2, cex.axis = 1.2, col = module)
  995. module = "grey"
  996. column = match(module, modNames);
  997. moduleGenes = moduleColors==module;
  998. verboseScatterplot(abs(geneModuleMembership[moduleGenes, column]),
  999. abs(Dam_geneTraitSignificance[moduleGenes, 1]),
  1000. xlab = paste("Module Membership in", module, "module"),
  1001. ylab = "Dam Treatment Gene significance for age",
  1002. main = paste("Module membership vs. Dam treatment gene significance\n"),
  1003. cex.main = 1.2, cex.lab = 1.2, cex.axis = 1.2, col = module)
  1004. dev.off()
  1005. pdf(file = "Puptreatment_geneModuleMembershipvsGeneSignificanceAGE.pdf", wi = 10, he = 10)
  1006. par(mfrow = c(2,2));
  1007. module = "blue"
  1008. column = match(module, modNames);
  1009. moduleGenes = moduleColors==module;
  1010. verboseScatterplot(abs(geneModuleMembership[moduleGenes, column]),
  1011. abs(Pup_geneTraitSignificance[moduleGenes, 1]),
  1012. xlab = paste("Module Membership in", module, "module"),
  1013. ylab = "Pup Treatment Gene significance for age",
  1014. main = paste("Module membership vs. Pup treatment gene significance\n"),
  1015. cex.main = 1.2, cex.lab = 1.2, cex.axis = 1.2, col = module)
  1016. module = "brown"
  1017. column = match(module, modNames);
  1018. moduleGenes = moduleColors==module;
  1019. verboseScatterplot(abs(geneModuleMembership[moduleGenes, column]),
  1020. abs(Pup_geneTraitSignificance[moduleGenes, 1]),
  1021. xlab = paste("Module Membership in", module, "module"),
  1022. ylab = "Pup Treatment Gene significance for age",
  1023. main = paste("Module membership vs. Pup treatment gene significance\n"),
  1024. cex.main = 1.2, cex.lab = 1.2, cex.axis = 1.2, col = module)
  1025. module = "turquoise"
  1026. column = match(module, modNames);
  1027. moduleGenes = moduleColors==module;
  1028. verboseScatterplot(abs(geneModuleMembership[moduleGenes, column]),
  1029. abs(Pup_geneTraitSignificance[moduleGenes, 1]),
  1030. xlab = paste("Module Membership in", module, "module"),
  1031. ylab = "Pup Treatment Gene significance for age",
  1032. main = paste("Module membership vs. Pup treatment gene significance\n"),
  1033. cex.main = 1.2, cex.lab = 1.2, cex.axis = 1.2, col = module)
  1034. module = "green"
  1035. column = match(module, modNames);
  1036. moduleGenes = moduleColors==module;
  1037. verboseScatterplot(abs(geneModuleMembership[moduleGenes, column]),
  1038. abs(Pup_geneTraitSignificance[moduleGenes, 1]),
  1039. xlab = paste("Module Membership in", module, "module"),
  1040. ylab = "Pup Treatment Gene significance for age",
  1041. main = paste("Module membership vs. Pup treatment gene significance\n"),
  1042. cex.main = 1.2, cex.lab = 1.2, cex.axis = 1.2, col = module)
  1043. module = "yellow"
  1044. column = match(module, modNames);
  1045. moduleGenes = moduleColors==module;
  1046. verboseScatterplot(abs(geneModuleMembership[moduleGenes, column]),
  1047. abs(Pup_geneTraitSignificance[moduleGenes, 1]),
  1048. xlab = paste("Module Membership in", module, "module"),
  1049. ylab = "Pup Treatment Gene significance for age",
  1050. main = paste("Module membership vs. Pup treatment gene significance\n"),
  1051. cex.main = 1.2, cex.lab = 1.2, cex.axis = 1.2, col = module)
  1052. module = "grey"
  1053. column = match(module, modNames);
  1054. moduleGenes = moduleColors==module;
  1055. verboseScatterplot(abs(geneModuleMembership[moduleGenes, column]),
  1056. abs(Pup_geneTraitSignificance[moduleGenes, 1]),
  1057. xlab = paste("Module Membership in", module, "module"),
  1058. ylab = "Pup Treatment Gene significance for age",
  1059. main = paste("Module membership vs. Pup treatment gene significance\n"),
  1060. cex.main = 1.2, cex.lab = 1.2, cex.axis = 1.2, col = module)
  1061. dev.off()
  1062. pdf(file = "Region_geneModuleMembershipvsGeneSignificance.pdf", wi = 10, he = 10)
  1063. par(mfrow = c(2,2));
  1064. module = "blue"
  1065. column = match(module, modNames);
  1066. moduleGenes = moduleColors==module;
  1067. verboseScatterplot(abs(geneModuleMembership[moduleGenes, column]),
  1068. abs(Region_geneTraitSignificance[moduleGenes, 1]),
  1069. xlab = paste("Module Membership in", module, "module"),
  1070. ylab = "Region Treatment Gene significance for Region",
  1071. main = paste("Module membership vs. Region treatment gene significance\n"),
  1072. cex.main = 1.2, cex.lab = 1.2, cex.axis = 1.2, col = module)
  1073. module = "brown"
  1074. column = match(module, modNames);
  1075. moduleGenes = moduleColors==module;
  1076. verboseScatterplot(abs(geneModuleMembership[moduleGenes, column]),
  1077. abs(Region_geneTraitSignificance[moduleGenes, 1]),
  1078. xlab = paste("Module Membership in", module, "module"),
  1079. ylab = "Region Treatment Gene significance for Region",
  1080. main = paste("Module membership vs. Region treatment gene significance\n"),
  1081. cex.main = 1.2, cex.lab = 1.2, cex.axis = 1.2, col = module)
  1082. module = "turquoise"
  1083. column = match(module, modNames);
  1084. moduleGenes = moduleColors==module;
  1085. verboseScatterplot(abs(geneModuleMembership[moduleGenes, column]),
  1086. abs(Region_geneTraitSignificance[moduleGenes, 1]),
  1087. xlab = paste("Module Membership in", module, "module"),
  1088. ylab = "Region Treatment Gene significance for Region",
  1089. main = paste("Module membership vs. Region treatment gene significance\n"),
  1090. cex.main = 1.2, cex.lab = 1.2, cex.axis = 1.2, col = module)
  1091. module = "green"
  1092. column = match(module, modNames);
  1093. moduleGenes = moduleColors==module;
  1094. verboseScatterplot(abs(geneModuleMembership[moduleGenes, column]),
  1095. abs(Region_geneTraitSignificance[moduleGenes, 1]),
  1096. xlab = paste("Module Membership in", module, "module"),
  1097. ylab = "Region Treatment Gene significance for Region",
  1098. main = paste("Module membership vs. Region treatment gene significance\n"),
  1099. cex.main = 1.2, cex.lab = 1.2, cex.axis = 1.2, col = module)
  1100. module = "yellow"
  1101. column = match(module, modNames);
  1102. moduleGenes = moduleColors==module;
  1103. verboseScatterplot(abs(geneModuleMembership[moduleGenes, column]),
  1104. abs(Region_geneTraitSignificance[moduleGenes, 1]),
  1105. xlab = paste("Module Membership in", module, "module"),
  1106. ylab = "Region Treatment Gene significance for Region",
  1107. main = paste("Module membership vs. Region treatment gene significance\n"),
  1108. cex.main = 1.2, cex.lab = 1.2, cex.axis = 1.2, col = module)
  1109. module = "grey"
  1110. column = match(module, modNames);
  1111. moduleGenes = moduleColors==module;
  1112. verboseScatterplot(abs(geneModuleMembership[moduleGenes, column]),
  1113. abs(Region_geneTraitSignificance[moduleGenes, 1]),
  1114. xlab = paste("Module Membership in", module, "module"),
  1115. ylab = "Region Treatment Gene significance for Region",
  1116. main = paste("Module membership vs. Region treatment gene significance\n"),
  1117. cex.main = 1.2, cex.lab = 1.2, cex.axis = 1.2, col = module)
  1118. dev.off()
  1119. #Clearly, GS and MM are highly correlated, illustrating that genes highly significantly associated with a trait are
  1120. #often also the most important (central) elements of modules associated with the trait.
  1121. #=====================================================================================
  1122. #We have found modules with high association with our trait of interest, and have identified their central players by the Module Membership measure.
  1123. #We now merge this statistical information with gene annotation and write out a file that summarizes the most important results and can be inspected in standard spreadsheet software
  1124. # Create the starting data frame
  1125. Ensemble = colnames(datExpr)
  1126. #df <- nc %>% dplyr::select(ensembl_gene_id,mgi_symbol,description,genelength) %>% distinct()
  1127. #get matching data for each ensemble id from the row data from Brainspain input
  1128. ids <- genes[which(genes$ensembl_gene_id %in% Ensemble),]
  1129. #match order
  1130. idRows = match(Ensemble, ids$ensembl_gene_id)
  1131. ids2 = ids[idRows, ]
  1132. geneInfo0 = data.frame(ensembl_gene_id = colnames(datExpr),
  1133. geneSymbol = ids2$mgi_symbol,
  1134. description = ids2$description,
  1135. genelength = ids2$genelength,
  1136. moduleColor = moduleColors,
  1137. Dam_geneTraitSignificance,
  1138. Dam_GSPvalue,
  1139. Pup_geneTraitSignificance,
  1140. Pup_GSPvalue,
  1141. Region_geneTraitSignificance,
  1142. Region_GSPvalue,
  1143. t(datExpr))
  1144. # Order modules by their significance for age
  1145. modOrder = order(-abs(cor(MEs, Dam.Treatment, use = "p")));
  1146. # Add module membership information in the chosen order
  1147. for (mod in 1:ncol(geneModuleMembership))
  1148. {
  1149. oldNames = names(geneInfo0)
  1150. geneInfo0 = data.frame(geneInfo0, geneModuleMembership[, modOrder[mod]],
  1151. MMPvalue[, modOrder[mod]]);
  1152. names(geneInfo0) = c(oldNames, paste("MM.", modNames[modOrder[mod]], sep=""),
  1153. paste("p.MM.", modNames[modOrder[mod]], sep=""))
  1154. }
  1155. write.csv(geneInfo0, file = "geneInfo_Master_WGCNA.csv")
  1156. #geneInfo0 <- read.csv("geneInfo_BilboMGtimecourse.csv")
  1157. #=====================================================================================
  1158. #output a character vector of genes, where the genes are the hub gene picked for each module,
  1159. #and the names correspond to the module in which each gene is a hub.
  1160. hubs <- chooseTopHubInEachModule(datExpr,moduleColors, type = "signed",power =10) #https://support.bioconductor.org/p/46342/
  1161. #power of 2 for unsigned, 4 for signed
  1162. write.csv(hubs,"TopHubInEachModule.csv")
  1163. #These genes represent the top 10 genes per module based on kME
  1164. topGenesKME = NULL
  1165. for (i in 1:length(colnames(geneModuleMembership))){
  1166. KMErank = geneModuleMembership[(order(-geneModuleMembership[,i])),] #order by column, - decreasing
  1167. KMErank$Ensemble <- rownames(KMErank)
  1168. GenesKME = KMErank[c(1:10),c(i,7)] #where column 7 is the ensemble id
  1169. #get gene info
  1170. topKMEinfo <- ids2[which(ids2$ensembl_gene_id %in% rownames(GenesKME)),]
  1171. #get kME
  1172. merge <- merge(topKMEinfo,GenesKME,by.x="ensembl_gene_id", by.y = "Ensemble")
  1173. colnames(merge)[9] <- c("kME") #module column
  1174. merge$module <- substr(colnames(geneModuleMembership[i]),3,nchar(colnames(geneModuleMembership[i])))
  1175. topGenesKME = rbind(topGenesKME,merge)
  1176. }
  1177. write.csv(topGenesKME,"Top10HubInEachModule_KME.csv")
  1178. #topGenesKME <- read.csv("TopHubInEachModule.csv")
  1179. #=====================================================================================
  1180. #Extract modules
  1181. module_colors = setdiff(unique(moduleColors), "grey")
  1182. # for (color in module_colors){
  1183. # module=datExpr[,moduleColors==module_colors]
  1184. # write.table(module, paste("module_",color, "log2RPKM+1expression_DLPFC.txt",sep=""), sep="\t", row.names=T, col.names=T,quote=FALSE)
  1185. #
  1186. # }
  1187. #Look at expression patterns of these genes, as they are clustered
  1188. #heatmap colors:
  1189. #install.packages("RColorBrewer")
  1190. library("RColorBrewer")
  1191. library(gplots)
  1192. #gene-module info
  1193. heatDF <- geneInfo0 %>% filter(moduleColor != "grey") %>% arrange(moduleColor)
  1194. heatDF$moduleColor <- factor(heatDF$moduleColor)
  1195. data <- as.matrix(heatDF[,12:188]) #RPKM values
  1196. rownames(data) <- heatDF$ensembl_gene_id
  1197. #data <- t(m)
  1198. library(pheatmap)
  1199. my_palette <- colorRampPalette(c("blue", "white", "red"))(n = 299)
  1200. #define column groups:
  1201. annotation_col <- data.frame(
  1202. #Sample = factor(d$donor_name),
  1203. Dam.Treatment = factor(numerictraits$Dam.Treatment.Group2, levels = unique(numerictraits$Dam.Treatment.Group2)),
  1204. Pup.Treatment = factor(numerictraits$Pup.Treatment.Group2, levels = unique(numerictraits$Pup.Treatment.Group2)),
  1205. Region = factor(numerictraits$Brain.Region2, levels = unique(numerictraits$Brain.Region2)),
  1206. Sex = factor(numerictraits$sex2))
  1207. rownames(annotation_col) = colnames(data)
  1208. head(annotation_col)
  1209. annotation_row <- data.frame(heatDF$moduleColor)
  1210. rownames(annotation_row) = rownames(data)
  1211. colnames(annotation_row) <- c("module")
  1212. head(annotation_row)
  1213. # Specify colors
  1214. #https://stackoverflow.com/questions/15282580/how-to-generate-a-number-of-most-distinctive-colors-in-r
  1215. library(RColorBrewer)
  1216. n <- 27
  1217. qual_col_pals = brewer.pal.info[brewer.pal.info$category == 'qual',]
  1218. col_vector = unlist(mapply(brewer.pal, qual_col_pals$maxcolors, rownames(qual_col_pals)))
  1219. #pie(rep(1,n), col=sample(col_vector, n))
  1220. # change the color of annotation to what you want: (eg: "navy", "darkgreen")
  1221. Var1 <- sample(col_vector, 2)
  1222. names(Var1) <- unique(annotation_col$Dam.Treatment)
  1223. Var2 <- sample(col_vector, 2)
  1224. names(Var2) <- unique(annotation_col$Pup.Treatment)
  1225. Var3 <- c("cornflowerblue","darksalmon")
  1226. names(Var3) <- unique(annotation_col$Sex)
  1227. Var4 <- sample(col_vector, 3)
  1228. names(Var4) <- unique(annotation_col$Region)
  1229. Var5 <- as.character(unique(heatDF$moduleColor))
  1230. names(Var5) <- unique(heatDF$moduleColor)
  1231. anno_colors <- list(Dam.Treatment = Var1, Pup.Treatment = Var2, Sex = Var3, Brain.Region = Var4, moduleColor = Var5)
  1232. pdf(file = "module-Heatmap_log2RPKM_zscore.pdf", wi = 20, he = 16)
  1233. pheatmap::pheatmap(data,
  1234. cluster_row = F,
  1235. cluster_cols = T,
  1236. annotation_col = annotation_col,
  1237. annotation_row = annotation_row,
  1238. color = my_palette,
  1239. fontsize = 10,
  1240. fontsize_row=6,
  1241. show_rownames = F,
  1242. fontsize_col = 10,
  1243. annotation_colors = anno_colors,
  1244. scale = c("row"),
  1245. main = "Gene Expression Modules")
  1246. dev.off()
  1247. #=====================================================================================
  1248. #average heatmap by condition
  1249. heatDF2 <- heatDF[,c(1,5,12:188)] #ensembl ID, modulecolour, log2PRKM values
  1250. heatDF2 <- heatDF2 %>% gather(Sample.ID, log2RPKM, 3:ncol(heatDF2))
  1251. headDF3 <- merge(heatDF2,datTraits, by = "Sample.ID", all.x=T)
  1252. heatDF4 <- headDF3 %>% group_by(moduleColor,ensembl_gene_id,Group) %>% summarize(meanlog2RPKM= mean(log2RPKM)) %>%
  1253. spread(Group,meanlog2RPKM)%>% arrange(moduleColor)
  1254. matrix <- as.matrix(heatDF4[,3:ncol(heatDF4)])
  1255. rownames(matrix) <- heatDF4$ensembl_gene_id
  1256. #order columns
  1257. colnames(matrix)
  1258. #newcolorder <- c( "7 F" , "7 M" ,"15 F", "15 M", "35 F" ,"35 M" , "84 F", "84 M")
  1259. #matrix <- matrix[,newcolorder]
  1260. #colnames(matrix)
  1261. my_palette <- colorRampPalette(c("blue", "white", "red"))(n = 299)
  1262. #define column groups:
  1263. Dam.Treatment <- substr(colnames(matrix),1,6)
  1264. tmp <- as.data.frame(colnames(matrix))
  1265. colnames(tmp) <- c("group")
  1266. tmp <- tmp %>% separate(group,into=c("Dam","Pup","sex","region"),sep="_")
  1267. sex <- substr(colnames(matrix),(nchar(colnames(matrix))+1)-1,nchar(colnames(matrix)))
  1268. annotation_col <- tmp
  1269. rownames(annotation_col) = colnames(matrix)
  1270. head(annotation_col)
  1271. annotation_row <- data.frame(heatDF4$moduleColor)
  1272. rownames(annotation_row) = rownames(matrix)
  1273. colnames(annotation_row) <- c("moduleColor")
  1274. head(annotation_row)
  1275. # Specify colors
  1276. #https://stackoverflow.com/questions/15282580/how-to-generate-a-number-of-most-distinctive-colors-in-r
  1277. library(RColorBrewer)
  1278. n <- 27
  1279. qual_col_pals = brewer.pal.info[brewer.pal.info$category == 'qual',]
  1280. col_vector = unlist(mapply(brewer.pal, qual_col_pals$maxcolors, rownames(qual_col_pals)))
  1281. #pie(rep(1,n), col=sample(col_vector, n))
  1282. # change the color of annotation to what you want: (eg: "navy", "darkgreen")
  1283. Var1 <- sample(col_vector, 2)
  1284. names(Var1) <- unique(annotation_col$Dam)
  1285. Var2 <- sample(col_vector, 2)
  1286. names(Var2) <- unique(annotation_col$Pup)
  1287. Var3 <- c("cornflowerblue","darksalmon")
  1288. names(Var3) <- unique(annotation_col$sex)
  1289. Var4 <- sample(col_vector, 3)
  1290. names(Var4) <- unique(annotation_col$region)
  1291. Var5 <- as.character(unique(heatDF4$moduleColor))
  1292. names(Var5) <- unique(heatDF4$moduleColor)
  1293. anno_colors <- list(DamTreatment = Var1, PupTreatment = Var2, Sex = Var3, BrainRegion = Var4, moduleColor = Var5)
  1294. pdf(file = "Heatmap_log2RPKM_zscore_noReplicates.pdf", wi = 11, he = 8.5)
  1295. pheatmap::pheatmap(matrix,
  1296. cluster_row = F,
  1297. cluster_cols = T,
  1298. annotation_col = annotation_col,
  1299. annotation_row = annotation_row,
  1300. color = my_palette,
  1301. show_rownames = F,
  1302. fontsize = 12,
  1303. fontsize_row=6,
  1304. fontsize_col = 12,
  1305. annotation_colors = anno_colors,
  1306. scale = c("row"),
  1307. main = "Gene Expression Modules")
  1308. dev.off()
  1309. #=====================================================================================
  1310. #split by brain region
  1311. # #=====================================================================================
  1312. ##############Cerebellum###################
  1313. CB <- headDF3 %>% filter(Brain.Region == "Cerebellum")
  1314. heatDF4 <- CB %>% group_by(moduleColor,ensembl_gene_id,Group) %>% summarize(meanlog2RPKM= mean(log2RPKM)) %>%
  1315. spread(Group,meanlog2RPKM)%>% arrange(moduleColor)
  1316. matrix <- as.matrix(heatDF4[,3:ncol(heatDF4)])
  1317. rownames(matrix) <- heatDF4$ensembl_gene_id
  1318. #order columns
  1319. colnames(matrix)
  1320. newcolorder <- c("Saline_Saline_M_Cerebellum", "Saline_Saline_F_Cerebellum",
  1321. "Saline_Treg_M_Cerebellum","Saline_Treg_F_Cerebellum",
  1322. "PolyIC_Saline_M_Cerebellum","PolyIC_Saline_F_Cerebellum",
  1323. "PolyIC_Treg_M_Cerebellum", "PolyIC_Treg_F_Cerebellum")
  1324. matrix <- matrix[,newcolorder]
  1325. colnames(matrix)
  1326. my_palette <- colorRampPalette(c("blue", "white", "red"))(n = 299)
  1327. #define column groups:
  1328. tmp <- as.data.frame(colnames(matrix))
  1329. colnames(tmp) <- c("group")
  1330. tmp <- tmp %>% separate(group,into=c("Dam","Pup","sex","region"),sep="_")
  1331. sex <- substr(colnames(matrix),(nchar(colnames(matrix))+1)-1,nchar(colnames(matrix)))
  1332. annotation_col <- tmp
  1333. rownames(annotation_col) = colnames(matrix)
  1334. head(annotation_col)
  1335. annotation_row <- data.frame(heatDF4$moduleColor)
  1336. rownames(annotation_row) = rownames(matrix)
  1337. colnames(annotation_row) <- c("moduleColor")
  1338. head(annotation_row)
  1339. # Specify colors
  1340. #https://stackoverflow.com/questions/15282580/how-to-generate-a-number-of-most-distinctive-colors-in-r
  1341. library(RColorBrewer)
  1342. n <- 27
  1343. qual_col_pals = brewer.pal.info[brewer.pal.info$category == 'qual',]
  1344. col_vector = unlist(mapply(brewer.pal, qual_col_pals$maxcolors, rownames(qual_col_pals)))
  1345. #pie(rep(1,n), col=sample(col_vector, n))
  1346. # change the color of annotation to what you want: (eg: "navy", "darkgreen")
  1347. Var1 <- sample(col_vector, 2)
  1348. names(Var1) <- unique(annotation_col$Dam)
  1349. Var2 <- sample(col_vector, 2)
  1350. names(Var2) <- unique(annotation_col$Pup)
  1351. Var3 <- c("cornflowerblue","darksalmon")
  1352. names(Var3) <- unique(annotation_col$sex)
  1353. Var4 <- sample(col_vector, 3)
  1354. names(Var4) <- unique(annotation_col$region)
  1355. Var5 <- as.character(unique(heatDF4$moduleColor))
  1356. names(Var5) <- unique(heatDF4$moduleColor)
  1357. anno_colors <- list(DamTreatment = Var1, PupTreatment = Var2, Sex = Var3, BrainRegion = Var4, moduleColor = Var5)
  1358. pdf(file = "CB_Heatmap_log2RPKM_zscore_noReplicates.pdf", wi = 11, he = 8.5)
  1359. pheatmap::pheatmap(matrix,
  1360. cluster_row = F,
  1361. cluster_cols = F,
  1362. annotation_col = annotation_col,
  1363. annotation_row = annotation_row,
  1364. color = my_palette,
  1365. show_rownames = F,
  1366. fontsize = 12,
  1367. fontsize_row=6,
  1368. fontsize_col = 12,
  1369. annotation_colors = anno_colors,
  1370. scale = c("row"),
  1371. main = "Gene Expression Modules")
  1372. dev.off()
  1373. ##############Frontal Cortex###################
  1374. FC <- headDF3 %>% filter(Brain.Region == "Frontal Cortex")
  1375. heatDF4 <- FC %>% group_by(moduleColor,ensembl_gene_id,Group) %>% summarize(meanlog2RPKM= mean(log2RPKM)) %>%
  1376. spread(Group,meanlog2RPKM)%>% arrange(moduleColor)
  1377. matrix <- as.matrix(heatDF4[,3:ncol(heatDF4)])
  1378. rownames(matrix) <- heatDF4$ensembl_gene_id
  1379. #order columns
  1380. #order columns
  1381. colnames(matrix)
  1382. newcolorder <- c("Saline_Saline_M_Frontal Cortex", "Saline_Saline_F_Frontal Cortex",
  1383. "Saline_Treg_M_Frontal Cortex","Saline_Treg_F_Frontal Cortex",
  1384. "PolyIC_Saline_M_Frontal Cortex","PolyIC_Saline_F_Frontal Cortex",
  1385. "PolyIC_Treg_M_Frontal Cortex", "PolyIC_Treg_F_Frontal Cortex")
  1386. matrix <- matrix[,newcolorder]
  1387. colnames(matrix)
  1388. my_palette <- colorRampPalette(c("blue", "white", "red"))(n = 299)
  1389. #define column groups:
  1390. tmp <- as.data.frame(colnames(matrix))
  1391. colnames(tmp) <- c("group")
  1392. tmp <- tmp %>% separate(group,into=c("Dam","Pup","sex","region"),sep="_")
  1393. sex <- substr(colnames(matrix),(nchar(colnames(matrix))+1)-1,nchar(colnames(matrix)))
  1394. annotation_col <- tmp
  1395. rownames(annotation_col) = colnames(matrix)
  1396. head(annotation_col)
  1397. annotation_row <- data.frame(heatDF4$moduleColor)
  1398. rownames(annotation_row) = rownames(matrix)
  1399. colnames(annotation_row) <- c("moduleColor")
  1400. head(annotation_row)
  1401. # Specify colors
  1402. #https://stackoverflow.com/questions/15282580/how-to-generate-a-number-of-most-distinctive-colors-in-r
  1403. library(RColorBrewer)
  1404. n <- 27
  1405. qual_col_pals = brewer.pal.info[brewer.pal.info$category == 'qual',]
  1406. col_vector = unlist(mapply(brewer.pal, qual_col_pals$maxcolors, rownames(qual_col_pals)))
  1407. #pie(rep(1,n), col=sample(col_vector, n))
  1408. # change the color of annotation to what you want: (eg: "navy", "darkgreen")
  1409. Var1 <- sample(col_vector, 2)
  1410. names(Var1) <- unique(annotation_col$Dam)
  1411. Var2 <- sample(col_vector, 2)
  1412. names(Var2) <- unique(annotation_col$Pup)
  1413. Var3 <- c("cornflowerblue","darksalmon")
  1414. names(Var3) <- unique(annotation_col$sex)
  1415. Var4 <- sample(col_vector, 3)
  1416. names(Var4) <- unique(annotation_col$region)
  1417. Var5 <- as.character(unique(heatDF4$moduleColor))
  1418. names(Var5) <- unique(heatDF4$moduleColor)
  1419. anno_colors <- list(DamTreatment = Var1, PupTreatment = Var2, Sex = Var3, BrainRegion = Var4, moduleColor = Var5)
  1420. pdf(file = "FC_Heatmap_log2RPKM_zscore_noReplicates.pdf", wi = 11, he = 8.5)
  1421. pheatmap::pheatmap(matrix,
  1422. cluster_row = F,
  1423. cluster_cols = F,
  1424. annotation_col = annotation_col,
  1425. annotation_row = annotation_row,
  1426. color = my_palette,
  1427. show_rownames = F,
  1428. fontsize = 12,
  1429. fontsize_row=6,
  1430. fontsize_col = 12,
  1431. annotation_colors = anno_colors,
  1432. scale = c("row"),
  1433. main = "Gene Expression Modules")
  1434. dev.off()
  1435. ##############FHippocampus###################
  1436. HC <- headDF3 %>% filter(Brain.Region == "Hippocampus")
  1437. heatDF4 <- HC %>% group_by(moduleColor,ensembl_gene_id,Group) %>% summarize(meanlog2RPKM= mean(log2RPKM)) %>%
  1438. spread(Group,meanlog2RPKM)%>% arrange(moduleColor)
  1439. matrix <- as.matrix(heatDF4[,3:ncol(heatDF4)])
  1440. rownames(matrix) <- heatDF4$ensembl_gene_id
  1441. #order columns
  1442. colnames(matrix)
  1443. newcolorder <- c("Saline_Saline_M_Hippocampus", "Saline_Saline_F_Hippocampus",
  1444. "Saline_Treg_M_Hippocampus","Saline_Treg_F_Hippocampus",
  1445. "PolyIC_Saline_M_Hippocampus","PolyIC_Saline_F_Hippocampus",
  1446. "PolyIC_Treg_M_Hippocampus", "PolyIC_Treg_F_Hippocampus")
  1447. matrix <- matrix[,newcolorder]
  1448. colnames(matrix)
  1449. my_palette <- colorRampPalette(c("blue", "white", "red"))(n = 299)
  1450. #define column groups:
  1451. tmp <- as.data.frame(colnames(matrix))
  1452. colnames(tmp) <- c("group")
  1453. tmp <- tmp %>% separate(group,into=c("Dam","Pup","sex","region"),sep="_")
  1454. annotation_col <- tmp
  1455. rownames(annotation_col) = colnames(matrix)
  1456. head(annotation_col)
  1457. annotation_row <- data.frame(heatDF4$moduleColor)
  1458. rownames(annotation_row) = rownames(matrix)
  1459. colnames(annotation_row) <- c("moduleColor")
  1460. head(annotation_row)
  1461. # Specify colors
  1462. #https://stackoverflow.com/questions/15282580/how-to-generate-a-number-of-most-distinctive-colors-in-r
  1463. library(RColorBrewer)
  1464. n <- 27
  1465. qual_col_pals = brewer.pal.info[brewer.pal.info$category == 'qual',]
  1466. col_vector = unlist(mapply(brewer.pal, qual_col_pals$maxcolors, rownames(qual_col_pals)))
  1467. #pie(rep(1,n), col=sample(col_vector, n))
  1468. # change the color of annotation to what you want: (eg: "navy", "darkgreen")
  1469. Var1 <- sample(col_vector, 2)
  1470. names(Var1) <- unique(annotation_col$Dam)
  1471. Var2 <- sample(col_vector, 2)
  1472. names(Var2) <- unique(annotation_col$Pup)
  1473. Var3 <- c("cornflowerblue","darksalmon")
  1474. names(Var3) <- unique(annotation_col$sex)
  1475. Var4 <- sample(col_vector, 3)
  1476. names(Var4) <- unique(annotation_col$region)
  1477. Var5 <- as.character(unique(heatDF4$moduleColor))
  1478. names(Var5) <- unique(heatDF4$moduleColor)
  1479. anno_colors <- list(DamTreatment = Var1, PupTreatment = Var2, Sex = Var3, BrainRegion = Var4, moduleColor = Var5)
  1480. pdf(file = "HC_Heatmap_log2RPKM_zscore_noReplicates.pdf", wi = 11, he = 8.5)
  1481. pheatmap::pheatmap(matrix,
  1482. cluster_row = F,
  1483. cluster_cols = F,
  1484. annotation_col = annotation_col,
  1485. annotation_row = annotation_row,
  1486. color = my_palette,
  1487. show_rownames = F,
  1488. fontsize = 12,
  1489. fontsize_row=6,
  1490. fontsize_col = 12,
  1491. annotation_colors = anno_colors,
  1492. scale = c("row"),
  1493. main = "Gene Expression Modules")
  1494. dev.off()
  1495. #=====================================================================================
  1496. #line plots
  1497. # #=====================================================================================
  1498. # # #scale data same as pheatmap: subtract mean and divide by std. dev
  1499. # # #https://www.biostars.org/p/223532/
  1500. # scale_rows = function(x){
  1501. # m = apply(x, 1, mean, na.rm = T)
  1502. # s = apply(x, 1, sd, na.rm = T)
  1503. # return((x - m) / s)
  1504. # }
  1505. # #
  1506. # scale_mat = function(mat, scale){
  1507. # if(!(scale %in% c("none", "row", "column"))){
  1508. # stop("scale argument shoud take values: 'none', 'row' or 'column'")
  1509. # }
  1510. # mat = switch(scale, none = mat, row = scale_rows(mat), column = t(scale_rows(t(mat))))
  1511. # return(mat)
  1512. # }
  1513. # #
  1514. # # #data:
  1515. # heatDF4 <- headDF3 %>% group_by(moduleColor,ensembl_gene_id,Group) %>% summarize(meanlog2exp = mean(log2RPKM)) %>%
  1516. # spread(Group,meanlog2exp)%>% arrange(moduleColor)
  1517. # #
  1518. # matrix <- as.matrix(heatDF4[,3:ncol(heatDF4)])
  1519. # rownames(matrix) <- heatDF4$ensembl_gene_id
  1520. # #
  1521. # #
  1522. # # #scale by row:
  1523. # merPFCmatrix <- scale_mat(matrix, scale = "row")
  1524. # merPFCmatrix <- as.data.frame(merPFCmatrix)
  1525. # #
  1526. # merPFCmatrix$module <- heatDF4$moduleColor
  1527. # #
  1528. # merPFCDF <- merPFCmatrix %>% gather(group, scaled_expression, 1:(ncol(merPFCmatrix)-1)) %>%
  1529. # group_by(module,group)
  1530. #%>%
  1531. # # summarize(meanscaled_expression = mean(scaled_expression))
  1532. # #
  1533. # merPFCDF <- as.data.frame(merPFCDF)
  1534. # #
  1535. # # #arrange
  1536. # # newcolorder <- c( "7 F" , "7 M" ,"15 F", "15 M", "35 F" ,"35 M" , "84 F", "84 M")
  1537. # #
  1538. # # merPFCDF$age <- factor(merPFCDF$age,levels = newcolorder)
  1539. # #
  1540. # # #set colors:
  1541. # my_palette2 <- unique(merPFCDF$module)
  1542. # #
  1543. # my_palette2 <- col2hex(my_palette2)
  1544. # #
  1545. # library(cowplot)
  1546. # pdf(file = "lineplot_log2RPKM_scaled_noReplicates.pdf", wi = 11, he = 8.5)
  1547. # #
  1548. # p <- ggplot(merPFCDF, aes(x=group, y=meanscaled_expression, group=module,colour=module)) +
  1549. # geom_line(size=2) +
  1550. # scale_color_manual(values = my_palette2)+
  1551. # theme(axis.text.x = element_text(angle=45, vjust=0.5))+
  1552. # xlab(label = c("Treatment")) +
  1553. # ylab(label = c("Scaled log2(RPKM+1)"))
  1554. # #
  1555. # p
  1556. # #
  1557. # dev.off()
  1558. #
  1559. # #facet by module
  1560. merPFCDF2 <- merPFCDF %>% separate(group, into=c("DamTreatment","PupTreatment","sex","region"), sep="_")
  1561. merPFCDF2$DamTreatment <- factor( merPFCDF2$DamTreatment,levels =c("Saline","PolyIC" ))
  1562. theme_set(theme_classic(base_size = 24))
  1563. cbPalette <- c("lightblue","pink")
  1564. pdf(file = "boxplot_log2RPKM+1_scaled_noReplicates_facet.pdf", wi = 18, he = 30)
  1565. #
  1566. p <- ggplot(merPFCDF2, aes(x=DamTreatment, y=scaled_expression), group = PupTreatment) +
  1567. facet_wrap(~region*module*sex,ncol = 5) +
  1568. stat_summary(geom = "boxplot",
  1569. fun.data = function(x) setNames(quantile(x, c(0.05, 0.25, 0.5, 0.75, 0.95)), c("ymin", "lower", "middle", "upper", "ymax")),
  1570. position = "dodge", aes(fill=PupTreatment))+ #gives line as median, top of box and bottom of box as 25th and 75th quartile, line = 5th and 9th percentile
  1571. # geom_point(position = position_dodge(width = 0.90),aes(group=PupTreatment, colour=sex)) +
  1572. scale_fill_manual(values = cbPalette) +
  1573. theme_cowplot(font_size = 15)+
  1574. theme(axis.text.x = element_text(angle=45, vjust=0.5),
  1575. strip.background = element_rect(fill="#B0C4DE"),
  1576. # legend.position="none",
  1577. strip.text.x = element_text(size = 30))+
  1578. xlab(label = c("Dam Treatment")) +
  1579. ylab(label = c("Scaled log2(RPKM)"))
  1580. p
  1581. dev.off()
  1582. #
  1583. pdf(file = "boxplot_log2RPKM+1_scaled_noReplicates_facet2.pdf", wi = 22, he = 30)
  1584. #
  1585. p <- ggplot(merPFCDF2, aes(x=DamTreatment, y=scaled_expression), group = PupTreatment) +
  1586. facet_wrap(~module*region*sex,ncol = 6) +
  1587. stat_summary(geom = "boxplot",
  1588. fun.data = function(x) setNames(quantile(x, c(0.05, 0.25, 0.5, 0.75, 0.95)), c("ymin", "lower", "middle", "upper", "ymax")),
  1589. position = "dodge", aes(fill=PupTreatment))+ #gives line as median, top of box and bottom of box as 25th and 75th quartile, line = 5th and 9th percentile
  1590. #geom_point(position = position_dodge(width = 0.90),aes(group=PupTreatment, colour=sex)) +
  1591. scale_fill_manual(values = cbPalette) +
  1592. theme_cowplot(font_size = 15)+
  1593. theme(axis.text.x = element_text(angle=45, vjust=0.5),
  1594. strip.background = element_rect(fill="#B0C4DE"),
  1595. # legend.position="none",
  1596. strip.text.x = element_text(size = 20))+
  1597. xlab(label = c("Dam Treatment")) +
  1598. ylab(label = c("Scaled log2(RPKM)"))
  1599. p
  1600. dev.off()
  1601. #
  1602. pdf(file = "boxplot_log2RPKM+1_scaled_CB_bluemodule.pdf", wi = 6, he = 4)
  1603. #
  1604. CBblueRPKM <- merPFCDF2 %>% filter(module == "blue") %>% filter(region == "Cerebellum")
  1605. p <- ggplot( CBblueRPKM, aes(x=DamTreatment, y=scaled_expression), group = PupTreatment) +
  1606. facet_wrap(~sex,ncol = 2) +
  1607. stat_summary(geom = "boxplot",
  1608. fun.data = function(x) setNames(quantile(x, c(0.05, 0.25, 0.5, 0.75, 0.95)), c("ymin", "lower", "middle", "upper", "ymax")),
  1609. position = "dodge", aes(fill=PupTreatment))+ #gives line as median, top of box and bottom of box as 25th and 75th quartile, line = 5th and 9th percentile
  1610. #geom_point(position = position_dodge(width = 0.90),aes(group=PupTreatment, colour=sex)) +
  1611. scale_fill_manual(values = cbPalette) +
  1612. theme_cowplot(font_size = 15)+
  1613. theme(axis.text.x = element_text(angle=45, vjust=0.5),
  1614. strip.background = element_rect(fill="#B0C4DE"),
  1615. # legend.position="none",
  1616. strip.text.x = element_text(size = 20))+
  1617. xlab(label = c("Dam Treatment")) +
  1618. ylab(label = c("Scaled log2(RPKM)"))
  1619. p
  1620. dev.off()
  1621. pdf(file = "boxplot_log2RPKM+1_scaled_CB_turquoisemodule.pdf", wi = 6, he = 4)
  1622. #
  1623. CBturquoiseRPKM <- merPFCDF2 %>% filter(module == "turquoise") %>% filter(region == "Cerebellum")
  1624. p <- ggplot( CBturquoiseRPKM, aes(x=DamTreatment, y=scaled_expression), group = PupTreatment) +
  1625. facet_wrap(~sex,ncol = 2) +
  1626. stat_summary(geom = "boxplot",
  1627. fun.data = function(x) setNames(quantile(x, c(0.05, 0.25, 0.5, 0.75, 0.95)), c("ymin", "lower", "middle", "upper", "ymax")),
  1628. position = "dodge", aes(fill=PupTreatment))+ #gives line as median, top of box and bottom of box as 25th and 75th quartile, line = 5th and 9th percentile
  1629. #geom_point(position = position_dodge(width = 0.90),aes(group=PupTreatment, colour=sex)) +
  1630. scale_fill_manual(values = cbPalette) +
  1631. theme_cowplot(font_size = 15)+
  1632. theme(axis.text.x = element_text(angle=45, vjust=0.5),
  1633. strip.background = element_rect(fill="#B0C4DE"),
  1634. # legend.position="none",
  1635. strip.text.x = element_text(size = 20))+
  1636. xlab(label = c("Dam Treatment")) +
  1637. ylab(label = c("Scaled log2(RPKM)"))
  1638. p
  1639. dev.off()
  1640. pdf(file = "boxplot_log2RPKM+1_scaled_HC_turquoisemodule.pdf", wi = 6, he = 4)
  1641. #
  1642. HCturquoiseRPKM <- merPFCDF2 %>% filter(module == "turquoise") %>% filter(region == "Hippocampus")
  1643. p <- ggplot( HCturquoiseRPKM, aes(x=DamTreatment, y=scaled_expression), group = PupTreatment) +
  1644. facet_wrap(~sex,ncol = 2) +
  1645. stat_summary(geom = "boxplot",
  1646. fun.data = function(x) setNames(quantile(x, c(0.05, 0.25, 0.5, 0.75, 0.95)), c("ymin", "lower", "middle", "upper", "ymax")),
  1647. position = "dodge", aes(fill=PupTreatment))+ #gives line as median, top of box and bottom of box as 25th and 75th quartile, line = 5th and 9th percentile
  1648. #geom_point(position = position_dodge(width = 0.90),aes(group=PupTreatment, colour=sex)) +
  1649. scale_fill_manual(values = cbPalette) +
  1650. theme_cowplot(font_size = 15)+
  1651. theme(axis.text.x = element_text(angle=45, vjust=0.5),
  1652. strip.background = element_rect(fill="#B0C4DE"),
  1653. # legend.position="none",
  1654. strip.text.x = element_text(size = 20))+
  1655. xlab(label = c("Dam Treatment")) +
  1656. ylab(label = c("Scaled log2(RPKM)"))
  1657. p
  1658. dev.off()
  1659. pdf(file = "boxplot_log2RPKM+1_scaled_FC_Greenmodule.pdf", wi = 6, he = 4)
  1660. #
  1661. FCgreenRPKM <- merPFCDF2 %>% filter(module == "green") %>% filter(region == "Frontal Cortex")
  1662. p <- ggplot(FCgreenRPKM, aes(x=DamTreatment, y=scaled_expression), group = PupTreatment) +
  1663. facet_wrap(~sex,ncol = 2) +
  1664. stat_summary(geom = "boxplot",
  1665. fun.data = function(x) setNames(quantile(x, c(0.05, 0.25, 0.5, 0.75, 0.95)), c("ymin", "lower", "middle", "upper", "ymax")),
  1666. position = "dodge", aes(fill=PupTreatment))+ #gives line as median, top of box and bottom of box as 25th and 75th quartile, line = 5th and 9th percentile
  1667. #geom_point(position = position_dodge(width = 0.90),aes(group=PupTreatment, colour=sex)) +
  1668. scale_fill_manual(values = cbPalette) +
  1669. theme_cowplot(font_size = 15)+
  1670. theme(axis.text.x = element_text(angle=45, vjust=0.5),
  1671. strip.background = element_rect(fill="#B0C4DE"),
  1672. # legend.position="none",
  1673. strip.text.x = element_text(size = 20))+
  1674. xlab(label = c("Dam Treatment")) +
  1675. ylab(label = c("Scaled log2(RPKM)"))
  1676. p
  1677. dev.off()
  1678. pdf(file = "boxplot_log2RPKM+1_scaled_FC_yellowmodule.pdf", wi = 6, he = 4)
  1679. #
  1680. FCyellowRPKM <- merPFCDF2 %>% filter(module == "yellow") %>% filter(region == "Frontal Cortex")
  1681. p <- ggplot(FCyellowRPKM, aes(x=DamTreatment, y=scaled_expression), group = PupTreatment) +
  1682. facet_wrap(~sex,ncol = 2) +
  1683. stat_summary(geom = "boxplot",
  1684. fun.data = function(x) setNames(quantile(x, c(0.05, 0.25, 0.5, 0.75, 0.95)), c("ymin", "lower", "middle", "upper", "ymax")),
  1685. position = "dodge", aes(fill=PupTreatment))+ #gives line as median, top of box and bottom of box as 25th and 75th quartile, line = 5th and 9th percentile
  1686. #geom_point(position = position_dodge(width = 0.90),aes(group=PupTreatment, colour=sex)) +
  1687. scale_fill_manual(values = cbPalette) +
  1688. theme_cowplot(font_size = 15)+
  1689. theme(axis.text.x = element_text(angle=45, vjust=0.5),
  1690. strip.background = element_rect(fill="#B0C4DE"),
  1691. # legend.position="none",
  1692. strip.text.x = element_text(size = 20))+
  1693. xlab(label = c("Dam Treatment")) +
  1694. ylab(label = c("Scaled log2(RPKM)"))
  1695. p
  1696. dev.off()
  1697. #=====================================================================================
  1698. #GO term enrichment:https://labs.genetics.ucla.edu/horvath/htdocs/CoexpressionNetwork/GeneAnnotation/
  1699. #source("http://bioconductor.org/biocLite.R");
  1700. #biocLite(c("impute", "AnnotationDBI", "GO.db", "org.Hs.eg.db", "org.Mm.eg.db"))
  1701. #install.packages("anRichment_1.01-2.tar.gz")
  1702. #source("https://horvath.genetics.ucla.edu/html/CoexpressionNetwork/GeneAnnotation/installAnRichment.R");
  1703. # installAnRichment();
  1704. library(anRichment)
  1705. options(stringsAsFactors = FALSE)
  1706. ###################################################################
  1707. GOcollection = buildGOcollection(organism = "mouse")
  1708. #get entrez IDs:
  1709. entrez <- getBM(attributes = c("ensembl_gene_id", "entrezgene_id"),
  1710. filter= "ensembl_gene_id",
  1711. values = geneInfo0$ensembl_gene_id,
  1712. mart = mouse)
  1713. geneInfo <- merge(geneInfo0, entrez, by="ensembl_gene_id")
  1714. # evaluates the enrichment of the gene modules in the collection of GO terms
  1715. GOenrichment = enrichmentAnalysis(
  1716. classLabels = geneInfo$moduleColor, identifiers = geneInfo$entrezgene_id,
  1717. refCollection = GOcollection,
  1718. useBackground = "intersection", #intersection of genes in identifiers and the organism database
  1719. threshold = 0.05,
  1720. thresholdType = "FDR",
  1721. getOverlapEntrez = FALSE,
  1722. getOverlapSymbols = TRUE,
  1723. entrySeparator = ",",
  1724. maxReportedOverlapGenes = 1000,
  1725. ignoreLabels = "grey") #ignore genes not assigned to modules (grey)
  1726. #
  1727. collectGarbage()
  1728. #
  1729. names(GOenrichment)
  1730. #
  1731. #enrichment results are summarized in the component enrichmentTable:
  1732. names(GOenrichment$enrichmentTable)
  1733. #
  1734. write.csv(GOenrichment$enrichmentTable, file = "GOenrichment-enrichmentTable.csv")
  1735. #
  1736. #

WGCNA_allconditions.R at commit 432ab07, no license · at the source

Overview

Authors: Destanie Rose1,2, Rachel J Moreno1,2, Hadley Osman1,2, Megan E Rowland3,4, Jill Silverman2,5, Annie Ciernia3,4, Paul Ashwood1,2
  1. Department of Microbiology and Immunology, UC Davis, 50th Street Sacramento, Davis, CA 95817 USA
  2. The M.I.N.D. Institute, University of California at Davis, Davis, CA USA
  3. Department of Biochemistry and Molecular Biology, University of British Columbia, Vancouver, BC Canada
  4. Djavad Mowafaghian Centre for Brain Health, University of British Columbia, Vancouver, BC Canada
  5. Deperatment of Psychiatry and Behavioral Sciences, University of California at Davis, Davis, CA USA
Journal: Journal of neuroinflammation, volume 23, issue 1, article 133
Dates: received 20 December 2025; accepted 12 February 2026; published online 12 March 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1186/s12974-026-03739-w · PMID 41821031 · PMCID PMC13097898 · OpenAlex W7135079076
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: mouse (organism), autism (population), schizophrenia / psychosis (population), cellular / molecular (subfield)
Methods: Statistics, Smoothing, state filtering, decompositions, Machine learning
Keywords: Maternal immune activation (MIA), Autism, Schizophrenia, Immune regulation, Regulatory T cells (Tregs), Inflammation, Behavior, TH17 cells, Sex, Gene expression
MeSH: Adoptive Transfer*, Autism Spectrum Disorder*, Brain*, Prenatal Exposure Delayed Effects*, Sex Characteristics*, T-Lymphocytes, Regulatory*, Animals, Cytokines, Disease Models, Animal, Female, Male, Mice, Mice, Inbred C57BL, Pregnancy (* major topic)
Topic: Autism Spectrum Disorder Research (Cognitive Neuroscience, Neuroscience), according to OpenAlex
Funding: National Institute of Child Health and Human Development
Citations: cited by 1 paper (Europe PMC); 67 references in the paper

Abstract

Autism spectrum disorder (ASD) is characterized by atypical communication, social interactions, and restricted interests. In ASD, there are dysfunctional immune regulatory control mechanisms that can lead to immune activation. Notably lower frequencies of regulatory T cells (Tregs) and reduced immunosuppressive cytokines are reported and associated with more impaired behaviors impacting both individuals with autism and their families. Therefore, therapeutic approaches that enhance immune regulation may offer substantial benefits. Using the maternal immune activation (MIA) model, we investigated whether adoptive transfer of wildtype Tregs into MIA offspring recipients could rescue immune activation, brain transcriptome changes and behaviors exhibited in adult MIA offspring. We also aimed to explore potential sex-differences in responses. In male but not female MIA offspring, Tregs transfer reduced the frequency of T helper (TH)-17 (RORγT⁺ CD4⁺) T cells in both the mesenteric lymph node (MLN) and spleen. Moreover, the frequency of CD25⁺Foxp3⁺ T cells was increased in the MLN and spleen of male but not female MIA offspring following Tregs transfer. Splenocytes from male MIA offspring receiving Tregs showed reduced production of inflammatory cytokines (e.g., IL-6 and TNFα) following PMA/Ionomycin stimulations. In contrast, female MIA offspring that received Tregs exhibited different cytokine profiles characterized by increased production of cytokines, including GM-CSF, IFNγ, and IL-10. In the brain, bulk mRNA sequencing in the cerebellum, frontal cortex, and hippocampus revealed that Tregs-treated male MIA offspring had differentially expressed genes involved in neurodevelopmental disorders, synaptic function, and epigenetic regulation. Minimal gene expression differences were observed in female counterparts. There was significant improvement in self-grooming behaviors in males MIA offspring that received Tregs. In females, social novelty improved after Tregs treatment. In summary, adoptive Tregs transfer reduced systemic inflammation, brain transcription and behavior alterations in a sex dependent manner in the context of MIA. These findings suggest that adoptive Tregs transfer may represent a viable therapeutic avenue for mitigating systemic inflammation and comorbidities associated with MIA and neurodevelopmental disorders such as ASD.

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

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

Repository

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

ciernialab/Rose-et-al.-2026

License: none: the authors keep all their rights
State: the link answers, verified on 30 September 2026
Evidence: files inventoried
Commit: 432ab0775a42fb94f6fff3bff53ab2574a85dc4a, 16 November 2025
Languages: R (6), Shell (2)
Size: 10 files, 8 scripts
Software Heritage: not archived
Found in: “Data availability”
Holds: README
Not found: license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: cowplot (6 files), ggplot2 (6 files), tidyverse (6 files), clusterProfiler (5 files), edgeR (5 files), limma (5 files), pheatmap (5 files), SAMtools (2 files), FastQC (1 file), nlme (1 file), STAR (1 file), Subread (featureCounts) (1 file), WGCNA (1 file)
Availability: 1 check, the latest on 30 September 2026: the link answers
  • 30 September 2026: the link answers
9 files

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

Tracing map

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

What the map holds:

  • 1 repository of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 8 scripts, each with its path and the digest of its content;
  • 8 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

All processed gene lists and statistics are available in Supplementary Tables. Raw fastq files and counts matrix for the RNA-seq are available on NCBI GEO at X. Analysis code is on our lab github ( [https://github.com/ciernialab/Rose-et-al.-2026](https://github.com/ciernialab/Rose-et-al.-2026).

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

Recorded: type, language, journal, volume, issue, pages, dates, 7 authors, 10 keywords, 14 MeSH terms, 1 funder, 65 references.

Cite

This paper

Rose, D., Moreno, R. J., Osman, H., Rowland, M. E., Silverman, J., Ciernia, A., & Ashwood, P. (2026). Sex specific effects of adoptive Tregs transfer on the brain and periphery in maternal immune activation offspring rescuing immune dysregulation. Journal of neuroinflammation, 23(1), 133. https://doi.org/10.1186/s12974-026-03739-w

BibTeX

@article{rose2026sex,
author = {Rose, Destanie and Moreno, Rachel J and Osman, Hadley and Rowland, Megan E and Silverman, Jill and Ciernia, Annie and Ashwood, Paul},
title = {{Sex specific effects of adoptive Tregs transfer on the brain and periphery in maternal immune activation offspring rescuing immune dysregulation}},
journal = {Journal of neuroinflammation},
year = {2026},
month = mar,
volume = {23},
number = {1},
pages = {133},
publisher = {BMC},
issn = {1742-2094},
doi = {10.1186/s12974-026-03739-w},
url = {https://doi.org/10.1186/s12974-026-03739-w},
pmid = {41821031},
pmcid = {PMC13097898}
}

RIS

TY - JOUR
AU - Rose, Destanie
AU - Moreno, Rachel J
AU - Osman, Hadley
AU - Rowland, Megan E
AU - Silverman, Jill
AU - Ciernia, Annie
AU - Ashwood, Paul
TI - Sex specific effects of adoptive Tregs transfer on the brain and periphery in maternal immune activation offspring rescuing immune dysregulation
T2 - Journal of neuroinflammation
J2 - J Neuroinflammation
PY - 2026
DA - 2026/03/12
VL - 23
IS - 1
SP - 133
SN - 1742-2094
PB - BMC
DO - 10.1186/s12974-026-03739-w
UR - https://doi.org/10.1186/s12974-026-03739-w
LA - en
ER -

CSL-JSON

{
"id": "10.1186/s12974-026-03739-w",
"type": "article-journal",
"title": "Sex specific effects of adoptive Tregs transfer on the brain and periphery in maternal immune activation offspring rescuing immune dysregulation",
"container-title": "Journal of neuroinflammation",
"author": [
{
"family": "Rose",
"given": "Destanie"
},
{
"family": "Moreno",
"given": "Rachel J"
},
{
"family": "Osman",
"given": "Hadley"
},
{
"family": "Rowland",
"given": "Megan E"
},
{
"family": "Silverman",
"given": "Jill"
},
{
"family": "Ciernia",
"given": "Annie"
},
{
"family": "Ashwood",
"given": "Paul"
}
],
"container-title-short": "J Neuroinflammation",
"volume": "23",
"issue": "1",
"page": "133",
"DOI": "10.1186/s12974-026-03739-w",
"PMID": "41821031",
"PMCID": "PMC13097898",
"ISSN": "1742-2094",
"publisher": "BMC",
"URL": "https://doi.org/10.1186/s12974-026-03739-w",
"language": "en",
"issued": {
"date-parts": [
[
2026,
3,
12
]
]
}
}

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.1093/bioinformatics/btag592 [code]
Network-based stratification of allele-specific expression reveals patient subgroups in Huntington's disease.
Journal: Bioinformatics (Oxford, England)
In common: FastQC, Subread (featureCounts), STAR, 9 other tools
[2] doi:10.1038/s42003-026-10957-8 [code]
Brain defence by the extracellular matrix protein Cochlin.
Journal: Communications biology
In common: Subread (featureCounts), nlme, WGCNA, 7 other tools, mouse, cellular / molecular
[3] doi:10.21203/rs.3.rs-9927928/v1 [code]
Genome-wide and allele-resolved maps of the radial architecture of the mouse genome
Journal: Research Square (preprint)
In common: FastQC, Subread (featureCounts), STAR, 6 other tools, mouse
[4] doi:10.1038/s41586-026-10512-9 [code]
Astrocyte glucocorticoid receptor signalling restricts neuronal plasticity.
Journal: Nature
In common: Subread (featureCounts), STAR, SAMtools, 6 other tools, mouse, cellular / molecular
[5] doi:10.1038/s42003-026-10059-5 [code]
Transcriptomic analysis in autism spectrum disorder suggests three molecular subtypes with distinct phenotypic profiles and functional pathways.
Journal: Communications biology
In common: FastQC, STAR, WGCNA, 4 other tools, autism, cellular / molecular, 1 reference
[6] doi:10.1038/s41467-026-76675-1 [code]
Long-read proteogenomic atlas of human neuronal differentiation reveals isoform diversity informing neurodevelopmental risk mechanisms.
Journal: Nature communications
In common: STAR, WGCNA, SAMtools, 6 other tools, autism
[7] doi:10.7554/elife.109104 [code]
Complementary vertebrate &lt;i&gt;Wac&lt;/i&gt; models exhibit phenotypes relevant to DeSanto-Shinawi Syndrome.
Journal: eLife
In common: FastQC, Subread (featureCounts), STAR, 5 other tools, mouse, cellular / molecular
[8] doi:10.1038/s41467-026-71432-w [code]
MeCP2 gene dosage-dependent neurodevelopmentally restricted defects arise by aberrant activation of cell fate-determining bivalent genes.
Journal: Nature communications
In common: FastQC, Subread (featureCounts), STAR, 5 other tools, mouse, cellular / molecular
[9] 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: Subread (featureCounts), WGCNA, edgeR, 6 other tools, cellular / molecular
[10] doi:10.1038/s41386-026-02406-1 [code]
Functional genomic profiling of schizophrenia-associated genes reveals key microglial regulators.
Journal: Neuropsychopharmacology : official publication of the American College of Neuropsychopharmacology
In common: FastQC, STAR, SAMtools, 5 other tools, schizophrenia / psychosis, cellular / molecular

Contribute

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

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

Request its removal

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

Discussion, reproductions, activity

Discussion: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.

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

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