MethylAnalysis_bulk_v3.R 11.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304

MethylAnalysis_bulk_v3 <- function(methcall.folder = NULL, # input folder with .cov files (bismark)
                           outfolder = NULL, # output folder (if not exist it will be created)
                           proj.id = "myproject", # project id to prefix in putput files
                           samplesheet = NULL,
                           sheetnum = 1,
                           design.var = "Disease", # variable to subset samplesheet
                           case.var = "Case", # 1 in treatment vector
                           control.var = "Control", # 0 in treatment vector
                           idcol = "SampleID",
                           mincoverage = 10,
                           lowperc = 5,
                           lowcount = 10,
                           assem="hg38",
                           do.subset = T,
                           chr.subset = "chr9",
                           start.subset = 136668000,
                           end.subset = 136671000,
                           pipeline.meth = "bismarkCoverage",
                           plot.covariates = c("Condition","Batch","MRD",
                                               "Torelapse","Chemorefractory",
                                               "Sex","CytoA","Tissue"),
                           idstoremove = NULL,
                           delta.meth = 10,
                           plot.categorical.vars = c("Condition","Batch","MRD","Torelapse","Chemorefractory","Sex","CytoA"),
                           plot.continuous.vars = c("miR-126","egfl7"),
                           plot.height = 9,
                           plot.width = 12,
                           cellw = 15, 
                           cellh = 15,
                           fontnumsize = 5,
                           fontsize = 8
                           ){
  
  # load libraries
  
  require(methylKit)
  require(ggplot2)
  require(reshape2)
  require(plyr)
  require(ggrepel)
  library(GenomicRanges)
  library(openxlsx)
  library(pheatmap)
  
  # check vars
  
  if(is.null(methcall.folder)){
    stop("Please set methcall.folder")
  }
  
  if(is.null(outfolder)){
    stop("Please set outfolder")
  }
  
  if(is.null(samplesheet)){
    stop("Please set samplesheet")
  }
  
  # Setup variables
  
  infolder = paste0(methcall.folder, "/")
  dir.create(infolder, showWarnings = F)
  
  outfolder = paste0(outfolder, "/")
  dir.create(outfolder, showWarnings = F)
  
  qcfolder <- paste0(outfolder, "QC/")
  dir.create(qcfolder, showWarnings = F)
  
  
  # reading sample sheet with metadata
  ssheet <- read.xlsx(samplesheet, sheet = sheetnum)
  
  if(!is.null(idstoremove)){
    ssheet <- subset.data.frame(x = ssheet, subset = !ssheet[[idcol]] %in% idstoremove)
  }

  # defining design vector according to variable
  
  ssheet <- subset.data.frame(x = ssheet, subset = ssheet[[design.var]] %in% c(case.var, control.var))
  
  d.vec <- ssheet[[design.var]]
  d.vector <- ifelse(d.vec == case.var, 1, 0)
  
  # initialzing coverage .cov files list
  covs <- list()
  sampleids <- as.list(ssheet[[idcol]])
  names(sampleids) <- ssheet[[idcol]]
  
  for (i in ssheet[[idcol]]) {
    covs[[i]] <- paste0(infolder, "/", i, ".bismark.cov")
  }
  
  saveRDS(object = covs, file = "covs_object.rds")
  
  # creating object 
  
  myobj <- methRead(location = covs,
                    sample.id = sampleids,
                    assembly = assem,
                    pipeline = pipeline.meth,
                    treatment = d.vector,
                    context="CpG", 
                    mincov = mincoverage)
  
  saveRDS(myobj, file = "Myobject.rds")
  
  names(myobj) <- ssheet[[idcol]]
  
  saveRDS(myobj, file = "Myobject_with_names.rds")

  # subsetting if declared
  
  if(isTRUE(do.subset)){
    my.win = GRanges(seqnames = chr.subset, ranges = IRanges(start = start.subset, end = end.subset))
    myobj <- selectByOverlap(myobj,my.win)
  }

  
  saveRDS(myobj, file = "Myobject_with_names_aftersubset.rds")
  
  # filtering on minimum coverage 
  myobj <- filterByCoverage(methylObj = myobj, lo.count=lowcount, lo.perc = lowperc)
  
  # Normalization
  myobj <- normalizeCoverage(obj = myobj)
  
 # saveRDS(object = myobj, file = "Initial_object.rds")
  
  # Calculate basic stats and PCs

  metricsfolder <- paste0(qcfolder, "Metrics/")
  dir.create(path = metricsfolder, showWarnings = F)
    
  for (id in ssheet[[idcol]]) {
    
    png(filename = paste0(metricsfolder,proj.id,"_CpG_pct_methylation_sample_", id, ".png"), 
        width = 9, height = 6, units = "in", res = 96)
    print(getMethylationStats(myobj[[id]],plot=TRUE,both.strands=FALSE))
    dev.off()
    png(filename = paste0(metricsfolder, proj.id,"_Coverage_stats_sample_", id, ".png"), 
        width = 9, height = 6, units = "in", res = 96)
    print(getCoverageStats(myobj[[id]],plot=TRUE,both.strands=FALSE))
    dev.off()
  }
  
  # create meth obj 
  
  #meth <- unite(object = myobj, destrand=FALSE)
  meth <- unite(object = myobj, destrand=FALSE) # for debugging
  saveRDS(meth, "savemeth.tmp.rds")
  # Perform correlation
  
  sink(paste0(qcfolder, proj.id, "_Correlations.txt"))
  getCorrelation(meth,plot=FALSE)
  sink()
  
  if(length(ssheet[[idcol]]) < 15){
    png(filename = paste0(qcfolder,proj.id, "_Correlations_pearson_pairwise.png"), 
        width = 9, height = 6, units = "in", res = 96)
    print(getCorrelation(meth,plot=TRUE))
    dev.off()
  }
  
  png(filename = paste0(qcfolder, proj.id, "_Clustering.png"), 
      width = 9, height = 6, units = "in", res = 96)
  clusterSamples(meth, dist="euclidean", plot=TRUE, method = "ward.D2")
  dev.off()
  
  # Re-plotting PCs (custom chart)
  
  # compute PCs and store in object
  
  pca_compt <- PCASamples(meth, obj.return = T, screeplot = F)
  
  # extract PCs components
  
  pcafolder <- paste0(qcfolder, "PCA/")
  dir.create(path = pcafolder, showWarnings = F)
  
  pca_pc1_2 <- as.data.frame(x = pca_compt$x[,1:2])
  
  for(myvars in plot.covariates){
    pca_pc1_2$condition <- as.factor(ssheet[[myvars]])
    png(filename = paste0(pcafolder, proj.id, "_PCA_",myvars,".png"), 
        width = 9, height = 6, units = "in",res=96)
    print(ggplot(data = pca_pc1_2, 
                 mapping = aes(x = PC1, y=PC2, col=condition, label=rownames(pca_pc1_2))) + 
            geom_point(size=3) + geom_text_repel(size=3) + ggtitle(label = "Principal component analysis", subtitle = myvars) + 
            theme(plot.title = element_text(size = 16, face = "bold", hjust = 0.5)) +
            theme(plot.subtitle=element_text(size=12, hjust=0.5, face="italic", color="black")) +
            theme(axis.title = element_text(size=12, hjust=0.5, face="bold", color="black")) +
            theme(legend.text = element_text(size=8, hjust=0.5)) +
            theme(legend.title = element_blank()) +
            theme(axis.text = element_text(size=12, hjust=0.5, color="black")))
    dev.off()
    
  }
  
  # retrieve and store % of methylation 
  
  perc.meth <- percMethylation(meth)
  
  saveRDS(perc.meth,"pctmethly.rds")
  
  base::rownames(perc.meth) <- paste0(meth$chr, "_", meth$start)
  
  # Perform diff methylation
  
  myDiff=calculateDiffMeth(meth)
  
  write.table(myDiff,paste0(outfolder,proj.id,"_DiffMeth_single_CpG.txt"), row.names = F)
  difftest <- read.table(paste0(outfolder,proj.id,"_DiffMeth_single_CpG.txt"), header = T)

  difftest$comparison <- proj.id
  difftest$qvalue_r <- as.character(cut(x = difftest$qvalue,
                                        breaks = c(-1, 1e-100, 1e-10, 1e-02, 1),
                                        labels = c("***","**","*","ns")))
  
  myindex <- abs(difftest$meth.diff) < delta.meth
  difftest$meth.diff <- abs(difftest$meth.diff)
  difftest$qvalue_r[myindex] <- "ns"
  write.table(difftest,paste0(outfolder,proj.id,"_DiffMeth_single_CpG.txt"), row.names = F)
  

  # Adding color list and annotations

  library(RColorBrewer)

  color_list <- list()
  annrows <- NULL
  anncols <- subset.data.frame(difftest, select = c("qvalue_r","meth.diff"))
  base::rownames(anncols) <- difftest$start
  
  rows.annot.vars.cat = plot.categorical.vars
  rows.annot.vars.con = plot.continuous.vars

  # if(!is.null(rows.annot.vars.cat) | !is.null(rows.annot.vars.con)){
  #   rownames(ssheet) <- ssheet$SampleID
  #   annrows <- subset.data.frame(x = ssheet, select = c(rows.annot.vars.cat, rows.annot.vars.con))
  #   concolors <- RColorBrewer::brewer.pal(n = 9, name = "Set1")
  #   catcolors <- NULL
  #   for (varcon in 1:length(rows.annot.vars.con)) {
  #     color_list[[rows.annot.vars.con[varcon]]] <- colorRampPalette(c("lightgrey", concolors[varcon]))(10)
  #   }
  #   for (varcat in 1:length(rows.annot.vars.cat)) {
  #     ncolor <- 1
  #     for (val in unique(ssheet[[rows.annot.vars.cat[varcat]]])[order(unique(ssheet[[rows.annot.vars.cat[varcat]]]))]){
  #       if(length(unique(ssheet[[rows.annot.vars.cat[varcat]]])) > 9){
  #         catcolors <- colorRampPalette(RColorBrewer::brewer.pal(n = 9, name = "Set3"))(length(unique(ssheet[[rows.annot.vars.cat[varcat]]])))
  #       }
  #       else{
  #         catcolors <- RColorBrewer::brewer.pal(n = 9, name = "Set3")
  #       }
  #       color_list[[rows.annot.vars.cat[varcat]]][[val]] <- catcolors[ncolor]
  #       ncolor <- ncolor + 1
  #     }
  #   }
  # }
  
  color_list[["qvalue_r"]] = c("*" = "#6497b1", "**" = "#03396c", "***" = "#011f4b", ns= "#c4cacf")
  color_list[["meth.diff"]] = colorRampPalette(brewer.pal(n = 11, "Reds"))(100)
  color_list[["miR-126"]] <- brewer.pal(n = 9, "PuRd")
  
  # Heatmap
  
  pctmeth_matrix <- t(perc.meth)
  base::colnames(pctmeth_matrix) <- gsub(x = base::colnames(pctmeth_matrix), pattern = "chr[0-9]+_", replacement = "")
  
  pheatmap(mat = pctmeth_matrix, main = gsub(x = proj.id, pattern = "_", replacement = " "), 
           filename = paste0(outfolder, proj.id,"_CpG_percent_methylation_matrix_pheatmap.pdf"), width = plot.width, height = plot.height,
           na_col = "black", 
           cluster_cols = FALSE, 
           cluster_rows = TRUE, 
           annotation_row = annrows, 
           cellwidth = cellw, 
           cellheight = cellh, 
           display_numbers = T, 
           fontsize = fontsize,
           fontsize_number = fontnumsize, 
           number_format = "%.0f",
           #border_color = "#CBBEB5", 
           annotation_col = anncols, 
           #labels_row = lrow,
           #labels_col = lcol,
           #gaps_row = gaps.row,
           gaps_col = c(8),
           annotation_colors = color_list,
           color = c("#F5F5F5","#EEEEEE","#CCCCCC","#999999", "#666666","#333333","#000000"), breaks = c(0,10,20,30,50,70,90,100)
  )
  
  saveRDS(object = pctmeth_matrix, paste0(outfolder, proj.id,"_CpG_percent_methylation_matrix_pheatmap.rds"))
  saveRDS(object = list(anncol = anncols, annrow = annrows, anncolors = color_list), paste0(outfolder, proj.id,"_annotations_matrix_pheatmap.rds"))
  saveRDS(object = difftest, paste0(outfolder, proj.id,"_CpG_differential_methylation.rds"))
  saveRDS(object = perc.meth, paste0(outfolder, proj.id,"_CpG_percent_methylation.rds"))
  
  write.table(x = perc.meth, file = paste0(outfolder, proj.id,"_CpG_percent_methylation.txt"))
  write.table(x = difftest, file = paste0(outfolder, proj.id,"_CpG_differential_methylation.txt"))

  saveRDS(myobj, file = paste0(outfolder,proj.id,"_methylkit.rds"))
  saveRDS(myobj, file = paste0(outfolder,proj.id,"_methylkit_meth.rds"))

}