-
Notifications
You must be signed in to change notification settings - Fork 0
/
8a-non_CG_methylation.R
2776 lines (2216 loc) · 208 KB
/
8a-non_CG_methylation.R
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env Rscript
# 8-non_CG_methylation.R
#
# Jay Moore, John Innes Centre, Norwich
# jonathan.moore@jic.ac.uk
#
# 05/11/2019
#
# Version 1 - 1001 methylomes data analysis, adapted from Schmitz/Becker project - load non-CG methylation and call status for each sample
#
# Change log
#
# Data source (project_id)
# .methratio2 files from bsmap
# Summary of functions
#
# Done:
# Read GFF files output from bs_sequel for each sample in a project - each file contains C and T calls at all sites in a meth_context
# Align and merge the C and T calls at sites across samples
# Plot summary data about samples, sites
# Assign methylation status at each site in each sample
#
# This script calls methylation status of a C site based on:
# Fisher's exact test -> "I" (identify sites where coverage is too low to make a clear distinction between methylated and unmethylated status given the conversion efficiency and sequencing and alignment errors for the sample)
# Binomial test with B-H FDH adjusted p-values >= 0.01 -> "U" (identify sites where the number of "C" calls is too few to make a call of methylated for the sample)
# #C >= #T -> differentiate between "M" and "P" (impose an expectation that methylated sites will be represented by at least half of aligned reads being converted, else call Partial methylation)
# Coverage < 5 sigma -> "I" (assume coverage is approxinmately Gaussian distribution, and ignore sites where coverage is too high to be meaningful for the sample)
#
# Once all sites have been called, the script combines adjacent C and G sites identified from the reference and addresses the concordance of calls in adjacent CG dinucleotides.
#
# Bring CG site combined calls into same structure as CHG/CHH calls
#
# Underway:
#
#
# To do:
#
#
#
# Results:
#
#
if(!require(optparse)){
install.packages("optparse")
library(optparse)
}
library("optparse")
option_list = list(
make_option(c("-p", "--project"), action="store", default="m1001", type='character',
help="project code for location of mapping output"),
make_option(c("-s", "--sample"), action="store", default=NA, type='character',
help="project code for location of mapping output"),
make_option(c("-c", "--context"), action="store", default=NA, type='character',
help="methylation context (CG, CHG or CHH)"),
make_option(c("-a", "--action"), action="store", default="all", type='character',
help="actions to perform (load, plot, call, merge, analyse or all)"),
make_option(c("-v", "--verbose"), action="store_true", default=TRUE,
help="Should the program print extra stuff out? [default %default]"),
make_option(c("-q", "--quiet"), action="store_false", dest="verbose",
help="Make the program not be verbose.")
)
opt = parse_args(OptionParser(option_list=option_list))
if (opt$verbose) {
# show the user which options were chosen
cat("Project: ")
cat(opt$project)
cat("\n")
cat("Sample: ")
cat(opt$sample)
cat("\n")
cat("Context: ")
cat(opt$context)
cat("\n")
cat("Action: ")
cat(opt$action)
cat("\n")
}
# project_id, sample_id and meth_context together are used for finding raw data and naming output files
project_id=NULL
if (is.na(opt$project)) {
# No project defined - set a default
project_id="Mp1"
#project_id="memory_line_2"
} else {
project_id=opt$project
}
sample_id=NULL
if (is.na(opt$sample)) {
# No sample defined - quit
stop("No sample specified")
#project_id="memory_line_2"
} else {
sample_id=opt$sample
}
meth_context=NULL
if (is.na(opt$context)) {
# No context defined - set a default
meth_context="NONCG"
#meth_context="CHG"
#meth_context="CHH"
} else {
meth_context=opt$context
}
action=NULL
if (is.na(opt$action)) {
# No action defined - set a default
action="all"
#action="load"
#action="plot"
#action="call"
#action="merge"
#action="analyse"
} else {
action=opt$action
}
#### This part installs packages so will be slow the first time per platform
# Sometimes rlang is needed for bioconductor to instal. This problem seems to have gone away now...
#if(!require(rlang)){
# install.packages("rlang")
# library(rlang)
#}
#### This part sets up libraries and contextual information and metadata about the project
# Platform-specific stuff:
# Base of path to project
# Where to find bioconductor (packages need to be pre-installed in R using singularity if running on the cluster)
on_cluster = FALSE
pathroot = ""
if (.Platform$OS.type=="windows") {
pathroot="X:/Daniel-Zilberman/"
source("http://bioconductor.org/biocLite.R")
} else if (.Platform$OS.type=="unix") {
if(substr(getwd(),1,20)=="/jic/scratch/groups/") {
# assume we are running on cluster
pathroot="/jic/scratch/groups/Daniel-Zilberman"
on_cluster = TRUE
} else {
# assume we are running in Virtualbox with shared folder /media/sf_D_DRIVE
pathroot="/media/sf_D_DRIVE"
source("http://bioconductor.org/biocLite.R")
}
}
if (!on_cluster) {
# Assume that if we are on the cluster, then we are running in a VM with all relevant packages pre-installed
#biocLite(c("GenomicRanges", "BSgenome", "BSgenome.Athaliana.TAIR.TAIR9", "MethylSeekR", "karyoploteR"))
BiocManager::install(c("GenomicRanges", "BSgenome", "BSgenome.Athaliana.TAIR.TAIR9", "MethylSeekR", "karyoploteR", "ggtree"))
}
#### This part installs packages so will be slow the first time per platform
if(!require(data.table)){
install.packages("data.table")
library(data.table)
}
if(!require(stringr)){
install.packages("stringr")
library(stringr)
}
if(!require(ggplot2)){
install.packages("ggplot2")
library(ggplot2)
}
#if(!require(mixtools)){
# install.packages("mixtools")
# library(mixtools)
#}
if(!require(rootSolve)){
install.packages("rootSolve")
library(rootSolve)
}
#if(!require(ggpubr)){
# install.packages("ggpubr")
# library(ggpubr)
#}
library(data.table)
library(stringr)
library(ggplot2)
library(plyr)
#library(ggpubr)
# Source directory containing alignments from bs_sequel
source_dir = paste0(pathroot,"/Projects/Jay-1001_methylomes/3-alignments/")
# Working directory where outputs will be directed to
setwd(dir = paste0(pathroot,"/Projects/Jay-1001_methylomes/5-analysis/",sample_id))
raw_data_dir = "../../0-raw_data/"
reference_dir = "../../0-reference/"
reference_fasta = paste0(pathroot,"/Reference_data/Genomes/Arabidopsis/TAIR10/TAIR10_Chr.all.fasta") # TAIR10 genome assembly This never gets used at the moment
reference_CG_sites = paste0(pathroot,"/Reference_data/Genomes/Arabidopsis/TAIR10/TAIR10_Chr.all.CG_sites.tsv") # We prepared this earlier using a perl script to parse the TAIR10 genome assembly
reference_gff = paste0(pathroot,"/Reference_data/Genomes/Arabidopsis/Araport11/Araport11_GFF3_genes_transposons.201606.gff") # AraPort11 annotation
reference_exons = paste0(pathroot,"/Reference_data/Genomes/Arabidopsis/Araport11/GFF/Araport11_GFF3_genes_transposons.201606-exon.gff") # Prepared from AraPort11 annotation by a script in bs_sequel
reference_introns = paste0(pathroot,"/Reference_data/Genomes/Arabidopsis/Araport11/GFF/Araport11_GFF3_genes_transposons.201606-intron.gff") # Prepared from AraPort11 annotation by a script in bs_sequel
reference_5UTR = paste0(pathroot,"/Reference_data/Genomes/Arabidopsis/Araport11/GFF/Araport11_GFF3_genes_transposons.201606-five_prime_UTR.gff") # Prepared from AraPort11 annotation by a script in bs_sequel
reference_3UTR = paste0(pathroot,"/Reference_data/Genomes/Arabidopsis/Araport11/GFF/Araport11_GFF3_genes_transposons.201606-three_prime_UTR.gff") # Prepared from AraPort11 annotation by a script in bs_sequel
### SNP_loci.txt - we need to import a list of all known SNPs between lines considered for analysis, so SNP loci can inform site exclusion criteria
reference_chromatin_states = paste0(pathroot,"/Reference_data/Genomes/Arabidopsis/Chromatin_states/Sequeira-Mendes_et_al_2014_tpc124578_SupplementalIDS2.txt") # genomic ranges assigning each segment of the nuclear genome to one of 9 chromatin states
reference_DHS_loci = paste0(pathroot,"/Reference_data/Genomes/Arabidopsis/DHS_scores/TAIR10_DHSs.gff") # DNase-hypersensitivity sites (indicative of open chromatin)
# Nucleosomes position data from http://plantdhs.org/Download (Jiming Jiang lab) Originally described in Wu Y.F. Zhang W.L. Jiang J.M. Genome-wide nucleosome positioning is orchestrated by genomic regions associated with DNase I hypersensitivity in rice PLoS Genet. 2014 10 e1004378
# For nucleosome positioning data need to first read in from BigWig file, but Windows can't do this so did it using VM, then exported resulting genomicranges object.
# This is the code to run in R in the VM:
#source("http://www.bioconductor.org/biocLite.R")
#biocLite("rtracklayer")
#library(rtracklayer)
#saveRDS(import("/media/sf_D_DRIVE/Reference_data/Genomes/Arabidopsis/Nucleosomes/Ath_leaf_NPS.bw", format="BigWig"), "/media/sf_D_DRIVE/Reference_data/Genomes/Arabidopsis/Nucleosomes/Ath_leaf_NPS.RDS")
#reference_nucleosomes = paste0(pathroot,"/Reference_data/Genomes/Arabidopsis/Nucleosomes/Ath_leaf_NPS.RDS")
# Nucleosomes position data from https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSM2807196
# Lyons DB, Zilberman D. DDM1 and Lsh remodelers allow methylation of DNA wrapped in nucleosomes. Elife 2017 Nov 15;6. PMID: 29140247
# GSE96994 wt.rep1.mnase_seq results
# GSM2807196_wt.rep1.nucleosomes.bed is all nucleosome calls
# GSM2807196_wt.group_1.bed is well-positioned nucleosome calls
#reference_nucleosomes = paste0(pathroot,"/Reference_data/Genomes/Arabidopsis/Nucleosomes/GSM2807196_wt.rep1.nucleosomes.bed")
reference_nucleosomes = paste0(pathroot,"/Reference_data/Genomes/Arabidopsis/Nucleosomes/GSM2807196_wt.group_1.bed")
# H3K9me2 normalised WT data from Dave Lyons
# For H3K9me2 data need to first read in from BigWig file, but Windows can't do this so did it using VM, then exported resulting genomicranges object.
# This is the code to run in R in the VM:
#source("http://www.bioconductor.org/biocLite.R")
#biocLite("rtracklayer")
#library(rtracklayer)
#saveRDS(import("/media/sf_D_DRIVE/Reference_data/Genomes/Arabidopsis/Histone_modifications/dk9.jacobsen.normalized.bw", format="BigWig"), "/media/sf_D_DRIVE/Reference_data/Genomes/Arabidopsis/Histone_modifications/dk9.jacobsen.normalized.RDS")
reference_H3K9me2 = paste0(pathroot,"/Reference_data/Genomes/Arabidopsis/Histone_modifications/dk9.jacobsen.normalized.RDS")
# H3K9me1 Plant DNase I hypersensitivity data. Downloaded from http://plantdhs.org/Download (Jiming Jiang lab) on 05/12/2017
# For H3K4me1 data need to first read in from BigWig file, but Windows can't do this so did it using VM, then exported resulting genomicranges object.
# This is the code to run in R in the VM:
#source("http://www.bioconductor.org/biocLite.R")
#biocLite("rtracklayer")
#library(rtracklayer)
#saveRDS(import("/media/sf_D_DRIVE/Reference_data/Genomes/Arabidopsis/Histone_modifications/Ath_buds_H3K4me1.bw", format="BigWig"), "/media/sf_D_DRIVE/Reference_data/Genomes/Arabidopsis/Histone_modifications/Ath_buds_H3K4me1.RDS")
reference_H3K4me1 = paste0(pathroot,"/Reference_data/Genomes/Arabidopsis/Histone_modifications/Ath_buds_H3K4me1.RDS")
# H3K9me1 Plant DNase I hypersensitivity data. Downloaded from http://plantdhs.org/Download (Jiming Jiang lab) on 05/12/2017
# For H3K27me3 data need to first read in from BigWig file, but Windows can't do this so did it using VM, then exported resulting genomicranges object.
# This is the code to run in R in the VM:
#source("http://www.bioconductor.org/biocLite.R")
#biocLite("rtracklayer")
#library(rtracklayer)
#saveRDS(import("/media/sf_D_DRIVE/Reference_data/Genomes/Arabidopsis/Histone_modifications/Ath_leaf_H3K27me3.bw", format="BigWig"), "/media/sf_D_DRIVE/Reference_data/Genomes/Arabidopsis/Histone_modifications/Ath_leaf_H3K27me3.RDS")
reference_H3K27me3 = paste0(pathroot,"/Reference_data/Genomes/Arabidopsis/Histone_modifications/Ath_leaf_H3K27me3.RDS")
# H2AW data from Jaemyung
reference_H2AW = paste0(pathroot,"/Reference_data/Genomes/Arabidopsis/Histone_modifications/h2aw.w50.gff")
# Started with global Arabidopsis accessions from Ecker study (927 of)
sample_list1 = read.table(paste0(raw_data_dir,"GSE43857.txt"), sep="\t", header=TRUE) # from https://www.ncbi.nlm.nih.gov/geo/browse/?view=samples&series=43857
fastq_list1 = read.table(paste0(raw_data_dir,"ENA_SRA065807.txt"), sep="\t", header=TRUE) # from https://www.ebi.ac.uk/ena/data/view/SRA065807
# Swedish Arabidopsis accessions from separate study (284 of)
sample_list2 = read.table(paste0(raw_data_dir,"GSE54292.txt"), sep="\t", header=TRUE) # from https://www.ncbi.nlm.nih.gov/geo/browse/?view=samples&series=54292
fastq_list2 = read.table(paste0(raw_data_dir,"ENA_SRP035593.txt"), sep="\t", header=TRUE) # from https://www.ebi.ac.uk/ena/data/view/PRJNA236110
sample_list = rbind.data.frame(sample_list1, sample_list2)
fastq_list = rbind.data.frame(fastq_list1, fastq_list2)
# The above sample_list routine was somewhat unsatisfactory. Instead, we will read in the synthesis created manually in Excel, using the above resources as a starting point:
sample_list = read.table(paste0(raw_data_dir,"sample_info_synthesis.txt"), sep="\t", header=TRUE)
sample_list$Name = str_split_fixed(sample_list$Title, "\\(",2)[,1]
#sample_list1$Ecotype_id = as.numeric(str_split_fixed(str_split_fixed(sample_list1$Title, "\\(",2)[,2], "\\)", 2)[,1])
sample_list$Ecotype_id = as.numeric(str_split_fixed(sample_list$Sample, "_", 2)[,1])
sample_files = data.frame()
for (this_accession in sample_list$SRA.Accession) {
these_files = fastq_list[fastq_list$experiment_accession == this_accession,"fastq_ftp"]
for (this_file in these_files) {
some_files=strsplit(this_file,";")
sample_files = rbind.data.frame(sample_files, c("Accession" = as.character(sample_list[sample_list$SRA.Accession==this_accession,"Accession"]), "Title" = as.character(sample_list[sample_list$SRA.Accession==this_accession,"Title"]), "SRA_Accession" = this_accession, "FASTQ_file" = some_files[[1]][[1]]), stringsAsFactors=FALSE)
if (length(some_files[[1]]) > 1) {
sample_files = rbind.data.frame(sample_files, c("Accession" = as.character(sample_list[sample_list$SRA.Accession==this_accession,"Accession"]), "Title" = as.character(sample_list[sample_list$SRA.Accession==this_accession,"Title"]), "SRA_Accession" = this_accession, "FASTQ_file" = some_files[[1]][[2]]), stringsAsFactors=FALSE)
# it looks like a lot of the paired-end files are represented as 'SINGLE' but should be 'PAIRED' - replace where necessary
if (fastq_list[fastq_list$fastq_ftp == this_file,"library_layout"] == "SINGLE") {
fastq_list[fastq_list$fastq_ftp == this_file,"library_layout"] = "PAIRED"
}
} else {
#cat(fastq_list[fastq_list$experiment_accession == this_accession,"library_layout"])
}
}
}
colnames(sample_files) = c("Accession", "Title", "SRA_Accession", "FASTQ_file")
# get the list of runs for the sample
# concatenate the methylation data for the runs
all_samples_ct=NA
run_no = 0
for (this_run in fastq_list[fastq_list$experiment_accession==sample_id,"run_accession"]) {
run_no = run_no + 1
if(opt$verbose) {cat(paste0("Loading ",this_run,"\n"))}
x=read.table(file=paste0(source_dir, this_run, "_TAIR10.non-cg.methratio2"), header=TRUE, sep="\t")
# needs sep="\t" because some entries (e.g. first two in mitochondria) have no entry in context string for some reason
# merge the data for this sample with the accumulated data
colnames(x)[7]=paste0(this_run,"_C")
x$T_count = x[,6]-x[,7]
colnames(x)[10]=paste0(this_run,"_T")
# Added in the context column for meth_context=NONCG because we need to split out CHG and CHH later
if (run_no==1) {
all_samples_ct=x[c("chr","pos","strand","context",paste0(this_run,"_C"),paste0(this_run,"_T"))]
} else {
all_samples_ct=merge(x[c("chr","pos","strand","context",paste0(this_run,"_C"),paste0(this_run,"_T"))], all_samples_ct, by=c("chr","pos","strand","context"), all=TRUE)
}
rm(x)
}
# make new columns for the totals
all_samples_ct[,paste0(sample_id,"_C")] = rep(0, nrow(all_samples_ct))
all_samples_ct[,paste0(sample_id,"_T")] = rep(0, nrow(all_samples_ct))
#colnames(all_samples_ct)[4 + run_no*2]=paste0(sample_id,"_C")
#colnames(all_samples_ct)[4 + run_no*2]=paste0(sample_id,"_T")
# accumulate the totals for all runs
run_no = 0
for (this_run in fastq_list[fastq_list$experiment_accession==sample_id,"run_accession"]) {
run_no = run_no + 1
if(opt$verbose) {cat(paste0("Accumulating ",this_run,"\n"))}
all_samples_ct[,paste0(sample_id,"_C")] = all_samples_ct[,paste0(sample_id,"_C")] + ifelse(is.na(all_samples_ct[,paste0(this_run,"_C")]),0,all_samples_ct[,paste0(this_run,"_C")])
all_samples_ct[,paste0(sample_id,"_T")] = all_samples_ct[,paste0(sample_id,"_T")] + ifelse(is.na(all_samples_ct[,paste0(this_run,"_T")]),0,all_samples_ct[,paste0(this_run,"_T")])
}
colnames(all_samples_ct)[1]="Chromosome"
colnames(all_samples_ct)[2]="Locus"
colnames(all_samples_ct)[3]="Strand"
all_samples_ct = all_samples_ct[,c(1, 2, 3, 4, 5 + run_no*2, 6 + run_no*2)]
#all_samples_ct = data.table(all_samples_ct,key=c("Chromosome", "Locus","Strand"))
# Dump the data table to file for a convenience cache
saveRDS(all_samples_ct, file=paste0(project_id,"_",meth_context,"_",sample_id,"_all_samples_ct.rds"))
# Load the reference genome annotation, and anotate each gene and transposon based on the CG methylome
library(GenomicRanges)
#gff.genes=readRDS(paste0(reference_dir,"SRA035939_CG_gff.genes.rds"))
#gff.transposons=readRDS(paste0(reference_dir,"SRA035939_CG_gff.transposons.rds"))
# Load the annotation
annot_gff = read.delim(reference_gff, header=F, comment.char="#")
#gff.exons = read.delim(reference_exons, header=F, comment.char="#")
#gff.introns = read.delim(reference_introns, header=F, comment.char="#")
#gff.5UTR = read.delim(reference_5UTR, header=F, comment.char="#")
#gff.3UTR = read.delim(reference_3UTR, header=F, comment.char="#")
# Grab the portion relating to genes
gff.genes = annot_gff[annot_gff[,3]=="gene",]
# Grab the portion relating to transposons
gff.transposons = annot_gff[annot_gff[,3]=="transposable_element",]
rm(annot_gff)
# Convert chromosome names to uppercase to match previous objects
#gff.genes$V1=toupper(gff.genes$V1)
#gff.transposons$V1=toupper(gff.transposons$V1)
#gff.exons$V1=toupper(gff.exons$V1)
#gff.introns$V1=toupper(gff.introns$V1)
#gff.5UTR$V1=toupper(gff.5UTR$V1)
#gff.3UTR$V1=toupper(gff.3UTR$V1)
# The following line sometimes fails if stringi has not been installed correctly. Not sure why. Fix is to install.packages("stringi") and to allow RStudio to restart R.
# Grab gene IDs from descriptive field
gff.genes$gene_ID=str_split_fixed(str_split_fixed(gff.genes$V9, ';',3)[,1],"=",2)[,2]
gff.transposons$gene_ID=str_split_fixed(str_split_fixed(gff.transposons$V9, ';',3)[,1],"=",2)[,2]
#gff.exons$gene_ID=str_split_fixed(str_split_fixed(gff.exons$V9, ';',3)[,1],"=",2)[,2]
#gff.introns$gene_ID=str_split_fixed(str_split_fixed(gff.introns$V9, ';',3)[,1],"=",2)[,2]
#gff.5UTR$gene_ID=str_split_fixed(str_split_fixed(gff.5UTR$V9, ';',3)[,1],"=",2)[,2]
#gff.3UTR$gene_ID=str_split_fixed(str_split_fixed(gff.3UTR$V9, ';',3)[,1],"=",2)[,2]
#Gene names are tricky - need to find the element containing "symbol="
gff.genes=within(gff.genes, {gene_name=str_split_fixed(str_split_fixed(V9, ';',3)[,2],"=",2)[,2]})
gff.transposons=within(gff.transposons, {gene_name=str_split_fixed(str_split_fixed(V9, ';',3)[,3],"=",2)[,2]})
# Fix the gene names in exon, intron and UTRs
#gff.exons$exon_ID = gff.exons$gene_ID
#gff.exons$gene_ID = substr(gff.exons$gene_ID,1,9)
#gff.introns$intron_ID = gff.introns$gene_ID
#gff.introns$gene_ID = substr(gff.introns$gene_ID,1,9)
#gff.5UTR$UTR_ID = gff.5UTR$gene_ID
#gff.5UTR$gene_ID = substr(gff.5UTR$gene_ID,1,9)
#gff.3UTR$UTR_ID = gff.3UTR$gene_ID
#gff.3UTR$gene_ID = substr(gff.3UTR$gene_ID,1,9)
# Add the exon and intron numbers
#gff.exons$exon_no = as.numeric(str_split_fixed(gff.exons$exon_ID, ':',3)[,3])
#gff.introns$exon_no = as.numeric(str_split_fixed(gff.introns$intron_ID, ':',3)[,3])
# Find out how many exons each gene has
#install.packages("sqldf")
#library(sqldf)
#gff.genes=merge(gff.genes, sqldf('SELECT genes.gene_id, MAX(exon_no) AS no_exons FROM [gff.exons] exons, [gff.genes] genes WHERE genes.gene_ID=exons.gene_ID GROUP BY genes.gene_id'), by="gene_ID", all=TRUE)
# Find how many variable sites each gene has
#gene_info = gff.genes
#varloc_genes = NULL
# Make a GRanges for gene space
gene_ranges=makeGRangesFromDataFrame(df = gff.genes, start.field = "V4", end.field = "V5",seqnames.field = "V1")
# Make a GRanges for transposon space
transposon_ranges=makeGRangesFromDataFrame(df = gff.transposons, start.field = "V4", end.field = "V5",seqnames.field = "V1")
# Load the BSGenome version of the reference
library(BSgenome)
# List the available genome assemblies
#available.genomes()
# TAIR9 and TAIR10 correspond to the same genome assembly so there is no need for a BSgenome pkg for TAIR10 :-)
# https://stat.ethz.ch/pipermail/bioconductor/2010-December/036938.html
library(BSgenome.Athaliana.TAIR.TAIR9)
# Find the sequence lengths for each chromosome
sLengths=seqlengths(Athaliana)
# Use the MethylSeekR package to segment the methylome
library(MethylSeekR)
# MethylSeekR expects an input file with 4 columns: Chrom, Locus, T and M. T is total reads, M is methylated reads.
# Create an input file for MethylSeekR based on the merged methylomes of all valid samples
# Sum the M (Cov_C) and T (Cov_C+Cov_T) counts for all valid samples
# Create empty tables to accumulate each of the 'across samples' columns data
#across_samples_TM=matrix(0, nrow=nrow(all_samples_meth_status), ncol=2)
# We are only dealing with one sample at a time so:
#valid_samples = sample_id
#for(sample_name in valid_samples) {
# if(opt$verbose) {cat(paste0("Adding methylation read counts to across-samples per-site table: ",sample_name,"\n"))}
# Merge each of the sample counts into the relevant accumulation table, accounting for possible NA values
# across_samples_TM[,1]=ifelse(is.na(coverage_data[coverage_data$Sample==sample_name,]$Cov_C+coverage_data[coverage_data$Sample==sample_name,]$Cov_T),across_samples_TM[,1],across_samples_TM[,1]+coverage_data[coverage_data$Sample==sample_name,]$Cov_C+coverage_data[coverage_data$Sample==sample_name,]$Cov_T)
# across_samples_TM[,2]=ifelse(is.na(coverage_data[coverage_data$Sample==sample_name,]$Cov_C),across_samples_TM[,2],across_samples_TM[,2]+coverage_data[coverage_data$Sample==sample_name,]$Cov_C)
#} # end for each sample
### Read in the SNPs data
#snps.gr <- readSNPTable(FileName=snpFname, seqLengths=sLengths)
# We will set sample_C and sample_T to 0 for all C loci where there is an annotated mutation
# Find the ecotype corresponding to this sample
this_ecotype = sample_list[sample_list$SRA.Accession==sample_id, "Ecotype_id"]
this_snp_file = paste0(reference_dir,this_ecotype,"_C_vars.txt")
if (file.exists(this_snp_file)) {
if(opt$verbose) {cat(paste0("Loading ",this_ecotype," SNPs\n"))}
#no_ecotypes = no_ecotypes + 1
#samples_with_genomes=c(samples_with_genomes, this_sample)
# read in the known C sites with SNPs for this sample. Use unique to deduplicate cases where the same site is listed more than once
this_sample_snps = unique(read.table(this_snp_file, header=FALSE, sep="\t"))
colnames(this_sample_snps) = c("Chromosome", "Locus")
#merge snps and sample to get rid of any rows exclusively from snp file, then replace sample values with 0 where a SNP was found
mutant_sites = merge(all_samples_ct[,c("Chromosome", "Locus")], cbind(this_sample_snps, "mutation"=rep(1,nrow(this_sample_snps))), by = c("Chromosome", "Locus"), all.x=TRUE, all.y=FALSE)
all_samples_ct[, paste0(sample_id,"_C")] = ifelse(is.na(mutant_sites$mutation), as.character(all_samples_ct[, paste0(sample_id,"_C")]), 0)
all_samples_ct[, paste0(sample_id,"_T")] = ifelse(is.na(mutant_sites$mutation), as.character(all_samples_ct[, paste0(sample_id,"_T")]), 0)
}
# Write out a copy of the SNP-masked methylome in the format that MethylSeekR likes to read in (Cov_C+Cov_T, Cov_C)
#write.table(cbind(paste0(substr(as.character(all_samples_meth_status$Chromosome),1,1),tolower(substr(as.character(all_samples_meth_status$Chromosome),2,3)),substr(as.character(all_samples_meth_status$Chromosome),4,4)),all_reps_meth_status$Locus,across_samples_TM),file=paste0(project_id,"_",meth_context,"_TM_read_counts_across_samples.tsv"),sep="\t",col.names=FALSE,row.names=FALSE,quote=FALSE)
#all_samples_ct = data.frame(all_samples_ct)
write.table(cbind(as.character(all_samples_ct$Chromosome), format(all_samples_ct$Locus, scientific=FALSE), as.numeric(all_samples_ct[,paste0(sample_id,"_C")])+as.numeric(all_samples_ct[,paste0(sample_id,"_T")]), as.numeric(all_samples_ct[,paste0(sample_id,"_C")])),file=paste0(project_id,"_",meth_context,"_",sample_id,"_TM_read_counts_across_samples.tsv"),sep="\t",col.names=FALSE,row.names=FALSE,quote=FALSE)
# Also write out separate files containing the SNP-masked CHG and CHH methylomes
# First make a vector defining the context of each site
noncg_context = ifelse((substr(all_samples_ct$context,3,3)=="C" & substr(all_samples_ct$context,5,5)=="G") | (substr(all_samples_ct$context,3,3)=="G" & substr(all_samples_ct$context,1,1)=="C"), "CHG", "CHH")
write.table(cbind(as.character(all_samples_ct[noncg_context=="CHG","Chromosome"]), format(all_samples_ct[noncg_context=="CHG","Locus"], scientific=FALSE), as.numeric(all_samples_ct[noncg_context=="CHG",paste0(sample_id,"_C")])+as.numeric(all_samples_ct[noncg_context=="CHG",paste0(sample_id,"_T")]), as.numeric(all_samples_ct[noncg_context=="CHG",paste0(sample_id,"_C")])),file=paste0(project_id,"_CHG_",sample_id,"_TM_read_counts_across_samples.tsv"),sep="\t",col.names=FALSE,row.names=FALSE,quote=FALSE)
write.table(cbind(as.character(all_samples_ct[noncg_context=="CHH","Chromosome"]), format(all_samples_ct[noncg_context=="CHH","Locus"], scientific=FALSE), as.numeric(all_samples_ct[noncg_context=="CHH",paste0(sample_id,"_C")])+as.numeric(all_samples_ct[noncg_context=="CHH",paste0(sample_id,"_T")]), as.numeric(all_samples_ct[noncg_context=="CHH",paste0(sample_id,"_C")])),file=paste0(project_id,"_CHH_",sample_id,"_TM_read_counts_across_samples.tsv"),sep="\t",col.names=FALSE,row.names=FALSE,quote=FALSE)
# Write out a copy of the SNP-masked methylome in Bismark .cov format for visualising in SeqMonk
#write.table(cbind(as.character(all_reps_meth_status$Chromosome),all_reps_meth_status$Locus,ifelse(meth_context=="CG",1,0)+all_reps_meth_status$Locus,across_samples_TM[,2]/across_samples_TM[,1],across_samples_TM[,2],across_samples_TM[,1]-across_samples_TM[,2]),file=paste0(project_id,"_",meth_context,"_CT_read_counts_across_samples.cov"),sep="\t",col.names=FALSE,row.names=FALSE,quote=FALSE)
write.table(cbind(toupper(as.character(all_samples_ct$Chromosome)), str_trim(format(all_samples_ct$Locus, scientific=FALSE)), str_trim(format(all_samples_ct$Locus + ifelse(meth_context=="CG",1,0), scientific=FALSE)), as.numeric(all_samples_ct[,paste0(sample_id,"_C")])/(as.numeric(all_samples_ct[,paste0(sample_id,"_C")])+as.numeric(all_samples_ct[,paste0(sample_id,"_T")])), as.numeric(all_samples_ct[,paste0(sample_id,"_C")]), as.numeric(all_samples_ct[,paste0(sample_id,"_T")])),file=paste0(project_id,"_",meth_context,"_",sample_id,"_CT_read_counts_across_samples.cov"),sep="\t",col.names=FALSE,row.names=FALSE,quote=FALSE)
# Read the methylome data in as a Granges object
#meth.gr <- readMethylome(FileName=paste0(project_id,"_",meth_context,"_",sample_id,"_TM_read_counts_across_samples.tsv"), seqLengths=sLengths)
### Remove the CpG sites from the SNP loci
#meth.gr <- removeSNPs(meth.gr, snps.gr)
#plotAlphaDistributionOneChr(m=meth.gr, chr.sel="Chr1", num.cores=1)
#plotAlphaDistributionOneChr(m=meth.gr, chr.sel="Chr2", num.cores=1)
#plotAlphaDistributionOneChr(m=meth.gr, chr.sel="Chr3", num.cores=1)
#plotAlphaDistributionOneChr(m=meth.gr, chr.sel="Chr4", num.cores=1)
#plotAlphaDistributionOneChr(m=meth.gr, chr.sel="Chr5", num.cores=1)
#plotAlphaDistributionOneChr(m=meth.gr, chr.sel="ChrM", num.cores=1)
#plotAlphaDistributionOneChr(m=meth.gr, chr.sel="ChrC", num.cores=1)
# Posterior means of alpha<1 indicate a bias towards very low or very high methylation. Only ChrM has a bimodal distribution, with significant density above 1.0, indicative of likely presence of partially methylated domains (PMDs) (although in our case it is more likely due to multiple copies of differently methylated mitochondrial genomes being analysed together). Accoringly we skip the next part.
# Define some loci to mask out from the genome (mitochondria, chloroplast, genes found previously to have coverage anomalies)
mask_loci=data.frame(Chromosome=character(), start_site=integer(), end_site=integer())
mask_loci=rbind(mask_loci,list(Chromosome="ChrM",start_site=1,end_site=sLengths[6]),list(Chromosome="ChrC",start_site=1,end_site=sLengths[7]))
mask_loci.gr=makeGRangesFromDataFrame(df=mask_loci, start.field="start_site", end.field="end_site", seqnames.field="Chromosome")
# Define genomicranges representing the whole genome
genome_loci=data.frame(Chromosome=character(), start_site=integer(), end_site=integer())
levels(genome_loci$Chromosome)=c("CHR1","CHR2","CHR3","CHR4","CHR5","CHRM","CHRC")
for (chrom_no in 1:length(sLengths)) {
genome_loci[chrom_no,]=list(Chromosome=toupper(names(sLengths[chrom_no])),start_site=1,end_site=sLengths[chrom_no])
}
genome_loci.gr=makeGRangesFromDataFrame(df=genome_loci, start.field="start_site", end.field="end_site", seqnames.field="Chromosome")
# The following function is from the package MethylSeekR
# The following changes have been made:
# nCG.classification threshold on no CG sites to differentiate between LMR and UMR segments replaced by an array of 'median methylation' cutoff levels (may want to change this to use pmeth instead)
# This was done because in Arabidopsis, there is not a clear separation in segment size between unmethylated and low-methylated segments, but there is a clear separation in methylation level, in contrast to mammals.
# In Arabidopsis, CG sites tend to be fully methylated, or unmethylated, so using the median values introduces sampling artefacts
# median.meth replaced by pmeth in scatterplot
# nCG replaced by nSites for generality across contexts
segmentUMRsLMRs <- function (m, meth.cutoff = 0.5, nCpG.cutoff = 3, PMDs = NA, pdfFilename = NULL,
num.cores = 1, myGenomeSeq, seqLengths, nCpG.smoothing = 3,
minCover = 5)
{
#nCG.classification <- 30
#mMeth.classification=c(0.2,0.4,0.75)
mMeth.classification=c(0.2)
message("identifying UMRs and LMRs")
m = m[values(m)[, 1] >= minCover]
nCGsPerChr = table(as.character(seqnames(m)))
chrs = names(nCGsPerChr)[nCGsPerChr >= nCpG.smoothing]
res <- mclapply(chrs, function(chr) {
sel <- which(as.character(seqnames(m)) == chr)
mean.meth <- runmean(Rle(values(m)[sel, 2]/values(m)[sel,1]), k = nCpG.smoothing, endrule = "constant")
indx <- mean.meth < meth.cutoff
runValue(indx)[runLength(indx) < nCpG.cutoff & runValue(indx) == TRUE] = FALSE
runValue(indx)[runLength(indx) < nCpG.cutoff & runValue(indx) == FALSE] = TRUE
tmp.ids <- rep(1:length(runLength(indx)), runLength(indx))
tmp <- split(1:length(sel), tmp.ids)
tmp <- tmp[runValue(indx) == TRUE]
if (length(tmp) > 0) {
coords <- cbind(sapply(tmp, min), sapply(tmp, max))
starts <- round((start(m)[sel[pmax(1, coords[, 1] - 1)]] + start(m)[sel[coords[, 1]]])/2)
ends <- round((start(m)[sel[coords[, 2]]] + start(m)[sel[pmin(length(sel), coords[, 2] + 1)]])/2)
hmr.gr = GRanges(seqnames = unique(seqnames(m[sel])),
strand = "*", ranges = IRanges(starts, ends),
seqlengths = seqLengths)
}
else {
hmr.gr = GRanges(, seqlengths = seqLengths)
}
hmr.gr
}, mc.cores = num.cores)
segments.gr = do.call(c, unname(res))
if (class(PMDs) == "GRanges") {
segments.gr = subsetByOverlaps(segments.gr, PMDs[values(PMDs)$type == "notPMD"])
}
nSites = vcountPattern("CG", getSeq(myGenomeSeq, resize(segments.gr, width(segments.gr), fix = "start"), as.character = FALSE))
ov <- findOverlaps(m, segments.gr)
T = tapply(values(m[queryHits(ov)])[, 1], subjectHits(ov), sum)
M = tapply(values(m[queryHits(ov)])[, 2], subjectHits(ov), sum)
nSites.segmentation = tapply(values(m[queryHits(ov)])[, 1], subjectHits(ov), length)
median.meth = tapply(as.vector(runmean(Rle(values(m[queryHits(ov)])[,2]/values(m[queryHits(ov)])[, 1]), nCpG.smoothing, endrule = "constant")), subjectHits(ov), median)
median.meth = pmax(0, median.meth)
if (!all.equal(as.numeric(names(T)), 1:length(segments.gr))) {
message("error in calculating methylation levels for PMDs")
}
type=ifelse(median.meth<mMeth.classification[1],"UMR", "LMR")
#type=ifelse(median.meth<mMeth.classification[1],0,ifelse(median.meth<mMeth.classification[2],1,ifelse(median.meth<mMeth.classification[3],2,3)))
#type = c("UMR", "LMR")[as.integer(nCG < nCG.classification) + 1]
values(segments.gr) = DataFrame(nSites.segmentation, nSites, T, M, pmeth = M/T, median.meth = median.meth, type)
jet.colors <- colorRampPalette(c("#00007F", "blue", "#007FFF", "cyan", "#7FFF7F", "yellow", "#FF7F00", "red", "#7F0000"))
if (!is.null(pdfFilename)) {
pdf(pdfFilename, height = 5, width = 5)
}
smoothScatter(log2(values(segments.gr)$nSites), 100 * values(segments.gr)$pmeth,
colramp = jet.colors, xlab = "log2 number of sites in segment",
ylab = "mean methylation (%)")
#abline(v = log2(nCG.classification), lty = 5)
abline(h = 100 * mMeth.classification[1], lty = 5)
abline(h = 100 * mMeth.classification[2], lty = 5)
abline(h = 100 * mMeth.classification[3], lty = 5)
if (!is.null(pdfFilename))
dev.off()
segments.gr
}
meth_by_segment <- function (m, segment_model, meth_context, num.cores = 1, myGenomeSeq, seqLengths, nSite.smoothing = 3, mMeth.classification=c(0.7), mMeth.classes=c("LMR","FMR"))
{
# Replaced nCG with nSites for generality
# m is a genomic ranges object representing a methylome
# segment_model is an arbitrary genomic ranges object representing a set of query segments of interest
# Count CG sites in each segment
# Added fixed=FALSE so that ambiguity codes will work properly
nSites = vcountPattern(meth_context, getSeq(Athaliana, resize(segment_model, width(segment_model), fix = "start"), as.character = FALSE), fixed=FALSE)
# Overlap the methylome with the segments
ov <- findOverlaps(m, segment_model)
# Count Ts and Ms per segment
T = tapply(values(m[queryHits(ov)])[, 1], subjectHits(ov), sum)
M = tapply(values(m[queryHits(ov)])[, 2], subjectHits(ov), sum)
nSites.segmentation = tapply(values(m[queryHits(ov)])[, 1], subjectHits(ov), length)
# The next step carries out a robust smoothing of the methylation values across the segment. It takes k adjacent sites (default=3) and calculates M/T for a sliding window of that size, then takes the median value of this proportion across the segment. k=3 give 'minimal' robust smoothing eliminating isolated outliers.
# This might be problematic for us, as in cases where each site is either fully methylated or unmethylated, it will tend to generate sequences like this for a window size of 3:
# 0,0,0,1/3,1/3,1/3,1/3,2/3,2/3,2/3,1,1,1,1,1 - this will lead to clusters of median methylation at 1/3 or 2/3 except for mostly unmethylated or methylated segments.
median.meth = tapply(as.vector(runmean(Rle(values(m[queryHits(ov)])[,2]/values(m[queryHits(ov)])[, 1]), nSite.smoothing, endrule = "constant")), subjectHits(ov), median)
median.meth = pmax(0, median.meth)
if (!all.equal(as.numeric(names(T)), 1:length(segment_model))) {
message("error in calculating methylation levels for PMDs")
}
# Original code used median.meth to make a 'type' determination for the segment. We will use pmeth instead
#type=ifelse(median.meth<mMeth.classification[1],mMeth.classes[1], mMeth.classes[2])
type=ifelse(M/T<mMeth.classification[1],mMeth.classes[1], mMeth.classes[2])
#type=ifelse(median.meth<mMeth.classification[1],0,ifelse(median.meth<mMeth.classification[2],1,ifelse(median.meth<mMeth.classification[3],2,3)))
#type = c("UMR", "LMR")[as.integer(nCG < nCG.classification) + 1]
DataFrame(nSites.segmentation, nSites, T, M, pmeth = M/T, median.meth = median.meth, type)
}
# Function to return NAs for cases where segmentation model doen's overlap any sites in the given context
NA_by_segment <- function (segment_model)
{
segment_count = length(segment_model)
nSites.segmentation = rep(as.integer(NA),segment_count)
nSites = rep(as.integer(NA),segment_count)
T = array(NA,segment_count)
M = array(NA,segment_count)
pmeth = array(NA,segment_count)
median.meth = rep(as.numeric(NA),segment_count)
type = array(NA,segment_count)
DataFrame(nSites.segmentation, nSites, T, M, pmeth = M/T, median.meth = median.meth, type)
}
# Define a corresponding convenience function to save an annotated genomic ranges object
# Function adapted from MethylSeekR package
saveUMRLMRSegments <- function (segs, GRangesFilename = NULL, TableFilename = NULL)
{
# Replaced nCG with nSites for generality
if (!is.null(GRangesFilename))
saveRDS(segs, GRangesFilename)
if (!is.null(TableFilename)) {
D = data.frame(chr = as.character(seqnames(segs)), start = start(segs),
end = end(segs), type = values(segs)$type, nSites.segmentation = values(segs)$nSites.segmentation,
nSites.seq = values(segs)$nSites, mean.meth = 100 * values(segs)$pmeth,
median.meth = 100 * values(segs)$median.meth)
write.table(D, file = TableFilename, quote = FALSE, sep = "\t",
row.names = FALSE)
}
}
# Define a convenience function to convert chromosome names to mixed-case (e.g. Chr9, ChrC)
mixedCaseChr <- function(s, strict = FALSE) {
paste0(toupper(substr(s,1,1)),tolower(substr(s,2,3)),toupper(substr(s,4,4)))
}
fixGRChomCase <- function(gr, strict = FALSE) {
#mixedCaseChr <- function(s, strict = FALSE) {
# paste0(toupper(substr(s,1,1)),tolower(substr(s,2,3)),toupper(substr(s,4,4)))
#}
levels(gr@seqnames@values) = mixedCaseChr(as.character(levels(gr@seqnames@values)))
gr@seqinfo@seqnames = levels(gr@seqnames@values)
gr
}
# Set chromosome names to mixed case in genome segments object
levels(genome_loci.gr@seqnames@values) = mixedCaseChr(as.character(levels(genome_loci.gr@seqnames@values)))
genome_loci.gr@seqinfo@seqnames = levels(genome_loci.gr@seqnames@values)
levels(mask_loci.gr@seqnames@values) = mixedCaseChr(as.character(levels(mask_loci.gr@seqnames@values)))
mask_loci.gr@seqinfo@seqnames = levels(mask_loci.gr@seqnames@values)
#methylated_loci.gr=reduce(makeGRangesFromDataFrame(df=rbind(gff.transposons[,c("V1","V4","V5")],gff.genes[gff.genes$m_class=="Heterochromatic",c("V1","V4","V5")]), start.field="V4", end.field="V5", seqnames.field="V1"))
#gene_body_loci.gr=reduce(makeGRangesFromDataFrame(df=gff.genes[gff.genes$m_class=="Gene-body Methylated",c("V1","V4","V5")], start.field="V4", end.field="V5", seqnames.field="V1"))
#unmethylated_loci.gr=reduce(makeGRangesFromDataFrame(df=gff.genes[gff.genes$m_class=="Unmethylated",c("V1","V4","V5")], start.field="V4", end.field="V5", seqnames.field="V1"))
# Concatenate the CHG and CHH methylomes (already done), and sort them, by position and chromosome
# CHG and CHH are already concatenated in our NONCG context file, so we just load it. Left in sort, sortseqlevels and c in case they do anything useful
meth_CHG_CHH.gr <- sort(sortSeqlevels(c(readMethylome(FileName=paste0(project_id,"_",meth_context,"_",sample_id,"_TM_read_counts_across_samples.tsv"), seqLengths=sLengths))))
#methylated_loci.gr=reduce(makeGRangesFromDataFrame(df=rbind(gff.transposons[,c("V1","V4","V5")],gff.genes[gff.genes$m_class=="Heterochromatic",c("V1","V4","V5")]), start.field="V4", end.field="V5", seqnames.field="V1"))
#gene_body_loci.gr=reduce(makeGRangesFromDataFrame(df=gff.genes[gff.genes$m_class=="Gene-body Methylated",c("V1","V4","V5")], start.field="V4", end.field="V5", seqnames.field="V1"))
#unmethylated_loci.gr=reduce(makeGRangesFromDataFrame(df=gff.genes[gff.genes$m_class=="Unmethylated",c("V1","V4","V5")], start.field="V4", end.field="V5", seqnames.field="V1"))
# m_n_non_CG_optimisation=data.frame(m=numeric(), n=numeric(), UMR=integer(), LMR=integer(), fp=numeric(), tp=numeric())
# Loop through values for m and n parameters
#m_CHG.seq=seq(0.002,0.1, by=0.002)
# m_non_CG.seq=seq(0.05,0.5, by=0.05)
#n_CHG.seq=seq(1,20, by=1)
# n_non_CG.seq=seq(50,500, by=50)
# for (m_non_CG.sel in m_non_CG.seq) {
# for (n_non_CG.sel in n_non_CG.seq) {
# #n.sel=4
# #UMRLMRsegments_CHG.gr <- segmentUMRsLMRs(m=meth_CHG.gr, meth.cutoff=m_CHG.sel, nCpG.cutoff=n_CHG.sel, num.cores=1, myGenomeSeq=Athaliana, seqLengths=sLengths)
# #UMRLMRsegments_CHG.gr <- segmentUMRsLMRs(m=meth_CHH.gr, meth.cutoff=m_CHG.sel, nCpG.cutoff=n_CHG.sel, num.cores=1, myGenomeSeq=Athaliana, seqLengths=sLengths)
# UMRLMRsegments_non_CG.gr <- segmentUMRsLMRs(m=meth_CHG_CHH.gr, meth.cutoff=m_non_CG.sel, nCpG.cutoff=n_non_CG.sel, num.cores=1, myGenomeSeq=Athaliana, seqLengths=sLengths)
#
# # Capitalise chromosome names in segmentation object
# levels(UMRLMRsegments_non_CG.gr@seqnames)=c("CHR1","CHR2","CHR3","CHR4","CHR5","CHRM","CHRC")
# UMRLMRsegments_non_CG.gr@seqinfo@seqnames=c("CHR1","CHR2","CHR3","CHR4","CHR5","CHRM","CHRC")
#
# # Find overlaps between segments and positive and negative 'control' loci (annotated genes and transposons)
# fp_hits=findOverlaps(methylated_loci.gr, UMRLMRsegments_non_CG.gr)
# fp_overlaps <- pintersect(methylated_loci.gr[queryHits(fp_hits)], UMRLMRsegments_non_CG.gr[subjectHits(fp_hits)])
# fp_overlap_prop <- sum(width(fp_overlaps)) / sum(width(methylated_loci.gr))
# tp_hits=findOverlaps(unmethylated_loci.gr, UMRLMRsegments_non_CG.gr)
# tp_overlaps <- pintersect(unmethylated_loci.gr[queryHits(tp_hits)], UMRLMRsegments_non_CG.gr[subjectHits(tp_hits)])
# tp_overlap_prop <- sum(width(tp_overlaps)) / sum(width(unmethylated_loci.gr))
#
# # Find overlaps between segments and variable loci
# #variable_sites_UMR_olaps = findOverlaps(variant_call_ranges, UMRLMRsegments_CHG.gr[UMRLMRsegments_CHG.gr@elementMetadata$type=="UMR"])
# #variable_sites_LMR_olaps = findOverlaps(variant_call_ranges, UMRLMRsegments_CHG.gr[UMRLMRsegments_CHG.gr@elementMetadata$type=="LMR"])
# m_n_non_CG_optimisation=rbind(m_n_non_CG_optimisation, list(m=m_non_CG.sel, n=n_non_CG.sel, UMR=0, LMR=0, fp=fp_overlap_prop, tp=tp_overlap_prop))
# # How many variable sites were captured?
# #cat(paste0("m.sel=",m_CHG.sel," n.sel=",n_CHG.sel," Variable sites in UMRs: ",length(variable_sites_UMR_olaps@from)," LMRs: ",length(variable_sites_LMR_olaps@from),"\n"))
# }
# }
# m_n_non_CG_optimisation$variable_sites_captured=m_n_non_CG_optimisation$UMR+m_n_non_CG_optimisation$LMR
# # Plot ROC curves for each value of n, and estimate AUC
# pdf(paste0(project_id,"_",meth_context,"_",sample_id,"_MethylSeekR_m_n_non_CG_optimisation_ROC.pdf"))
# print(ggplot(m_n_non_CG_optimisation, aes(x=fp, y=tp)) + geom_point() +geom_text(aes(label=paste0(m)),hjust=0, vjust=0) +geom_line() +facet_wrap(~ n))
# dev.off()
# # Estimate AUC from trapezium approximation
# cat(paste0("Estimated AUC values from ROC curves generated by varying m parameter for each value of n in MethylSeekR:\n"))
# best_n_non_CG = 0
# prev_best_auc_non_CG = 0
# for (n_non_CG.sel in n_non_CG.seq) {
# m_n_non_CG_optimisation_auc=0
# prev_tp=0
# prev_fp=0
# for (m_non_CG.sel in m_non_CG.seq) {
# m_n_non_CG_optimisation_auc = m_n_non_CG_optimisation_auc + (1-m_n_non_CG_optimisation[(m_n_non_CG_optimisation$m==m_non_CG.sel) & (m_n_non_CG_optimisation$n==n_non_CG.sel),]$fp)*(m_n_non_CG_optimisation[(m_n_non_CG_optimisation$m==m_non_CG.sel) & (m_n_non_CG_optimisation$n==n_non_CG.sel),]$tp-prev_tp) + ((m_n_non_CG_optimisation[(m_n_non_CG_optimisation$m==m_non_CG.sel) & (m_n_non_CG_optimisation$n==n_non_CG.sel),]$tp-prev_tp)*(m_n_non_CG_optimisation[(m_n_non_CG_optimisation$m==m_non_CG.sel) & (m_n_non_CG_optimisation$n==n_non_CG.sel),]$fp-prev_fp))/2
# prev_tp=m_n_non_CG_optimisation[(m_n_non_CG_optimisation$m==m_non_CG.sel) & (m_n_non_CG_optimisation$n==n_non_CG.sel),]$tp
# prev_fp=m_n_non_CG_optimisation[(m_n_non_CG_optimisation$m==m_non_CG.sel) & (m_n_non_CG_optimisation$n==n_non_CG.sel),]$fp
# }
# if (m_n_non_CG_optimisation_auc > prev_best_auc_non_CG) {
# best_n_non_CG = n_non_CG.sel
# prev_best_auc_non_CG = m_n_non_CG_optimisation_auc
# }
# cat(paste0(" n=",n_non_CG.sel," AUC=",m_n_non_CG_optimisation_auc,"\n"))
# }
# cat(paste0("n=",best_n_non_CG," maximises AUC (",prev_best_auc_non_CG,").\n"))
# n=50 AUC=0.855976191899861
# n=100 AUC=0.869442588656929
# n=150 AUC=0.874541502003507
# n=200 AUC=0.876019948216069
# n=250 AUC=0.874809539568385
# n=300 AUC=0.873804294288875
# n=350 AUC=0.87223443141152
# n=400 AUC=0.868125233054618
# n=450 AUC=0.866712745995736
# n=500 AUC=0.864528135434016
#n=200 maximises AUC (0.876019948216069).
# Inspection of curve for n=200 (and all the rest) show that around m=0.15 maxes out tp whilst minimising fp
# From Schmitz:
#n=50 AUC=0.853405558876841
#n=100 AUC=0.880384843230491
#n=150 AUC=0.890148958302221
#n=200 AUC=0.896297635230469
#n=250 AUC=0.90066653773841
#n=300 AUC=0.904636365469396
#n=350 AUC=0.907922263804411
#n=400 AUC=0.910975041031063
#n=450 AUC=0.913507235932189
#n=500 AUC=0.916029402508772
#n=500 maximises AUC (0.916029402508772).
# best_n_non_CG = 500
# Inspection of ROC curves indicates that tp rate maxes out (~1.0) around m=0.15, with fp rate minimised at .25 for n=500.
# Segment using best_n and m=0.7 to find appropriate cutoff for m.sel (0.9 gave weird results - almost no segments)
# UMRLMRsegments_non_CG.gr <- segmentUMRsLMRs(m=meth_CHG_CHH.gr, meth.cutoff=0.7, nCpG.cutoff=best_n_non_CG, num.cores=1, myGenomeSeq=Athaliana, seqLengths=sLengths, pdfFilename=paste0(project_id,"_",meth_context,"_", sample_id, "_MethylSeekR_non_CG_segmentation_landscape_",best_n_non_CG,"_0_7.pdf"))
# saveUMRLMRSegments(segs=UMRLMRsegments_non_CG.gr, GRangesFilename=paste0("UMRsLMRs_non_CG_0.7_",best_n_non_CG,".gr.rds"), TableFilename=paste0(project_id,"_",meth_context,"_", sample_id, "_MethylSeekR_segments_non_CG_0.7_",best_n_non_CG,".tsv"))
# UMRLMRsegments_non_CG.gr <- readRDS(paste0("UMRsLMRs_non_CG_0.7_",best_n_non_CG,".gr.rds"))
# More formally:
# Plot density distribution of segment mCH*
# pdf(paste0(project_id,"_",meth_context,"_", sample_id, "_MethylSeekR_non_CG_segmentation_landscape_",best_n_non_CG,"_0_7_density.pdf"))
# print(ggplot(as.data.frame(UMRLMRsegments_non_CG.gr@elementMetadata@listData), aes(x=pmeth)) + geom_histogram(binwidth=0.01))
# dev.off()
# Visual inspection of m1001_NONCG_SRX445897_MethylSeekR_non_CG_segmentation_landscape_200_0_7.pdf shows at least two seperate populations - unmethylated segments with n>2^10 and m<0.05; and methylation segments with 1<n<2^12 and m>=0.05
#From Schmitz: Visual inspection of SRA035939_CHH_MethylSeekR_non_CG_segmentation_landscape_500_0_9.pdf shows three clear populations of segments. Short methylated segments (n<2^5, m>0.15), and longer unmethylated and low-methylated segments (n>2^10, m<0.1; m>0.1).
# Fit mixture of Gaussians to nonCG density to identify cutoff
# Initially tried fitting 3 Gaussians to whole data set, but third Gaussian was used to cover the scattering of high-pMeth sgments (m>0.3). Accordingly, fit to segments with m<0.3 only
#install.packages("MASS") # for fitting negative binomial models to data
#library(MASS)
# install.packages("mixtools")
# library(mixtools)
# m_non_CG_mixmdl = normalmixEM(as.data.frame(UMRLMRsegments_non_CG.gr)[(!is.na(as.data.frame(UMRLMRsegments_non_CG.gr)$pmeth)) & (as.data.frame(UMRLMRsegments_non_CG.gr)$pmeth<0.3),]$pmeth, k=3)
# Had to exclude sites with NA CHG methylation or the fitting algorithm exploded
# Print the characteristics of the fit curves
# cat(paste0("Fit lambda values (mixture proportions):\n"))
# m_non_CG_mixmdl$lambda
# Schmitz data:
# Becker data:
# cat(paste0("Fit mu values (means):\n"))
# m_non_CG_mixmdl$mu
# Schmitz data:
# Becker data:
# cat(paste0("Fit sigma values (st.devs):\n"))
# m_non_CG_mixmdl$sigma
# Schmitz data:
# Becker data:
# Find the intersection of the two larger components in the mixture - here we cut off
#packages were installed and mixfn defined earlier
#install.packages("rootSolve")
# library(rootSolve)
# mixfn <- function(x, m1, sd1, m2, sd2, p1, p2){
# dnorm(x, m1, sd1) * p1 - dnorm(x, m2, sd2) * p2 }
# m_non_CG_low_model=2
# m_non_CG_high_model=m_non_CG_low_model+1
# segment_m_non_CG_cutoff=uniroot.all(mixfn, lower=0, upper=1, m1=m_non_CG_mixmdl$mu[m_non_CG_low_model], sd1=m_non_CG_mixmdl$sigma[m_non_CG_low_model], m2=m_non_CG_mixmdl$mu[m_non_CG_high_model], sd2=m_non_CG_mixmdl$sigma[m_non_CG_high_model], p1=m_non_CG_mixmdl$lambda[m_non_CG_low_model], p2=m_non_CG_mixmdl$lambda[m_non_CG_high_model])
# segment_m_non_CG_cutoff
# Most heavily methylated accession SRX445897 0.045130730 but 3 Gaussians doesn't look like great fit
# Schmitz data: 0.05920002 but 3 Gaussians doesn't look like a great fit
# Becker data:
# pdf(paste0(project_id,"_",meth_context,"_", sample_id, "_m_non_CG_segmentation_m_non_CG_cutoff_density_fitted.pdf"))
# print(plot(m_non_CG_mixmdl,which=2, breaks=seq(0,1,0.001)))
# dev.off()
# m_non_CG.sel = segment_m_non_CG_cutoff[length(segment_m_non_CG_cutoff)]
# Run optimised segmentation
# UMRLMRsegments_non_CG.gr <- segmentUMRsLMRs(m=meth_CHG_CHH.gr, meth.cutoff=m_non_CG.sel, nCpG.cutoff=best_n_non_CG, num.cores=1, myGenomeSeq=Athaliana, seqLengths=sLengths)
# Save segmentation
# saveUMRLMRSegments(segs=UMRLMRsegments_non_CG.gr, GRangesFilename=paste0(sample_id,"UMRsLMRs_non_CG_",m_non_CG.sel,"_",best_n_non_CG,".gr.rds"), TableFilename=paste0(project_id,"_",meth_context,"_",sample_id,"_MethylSeekR_segments_non_CG_",m_non_CG.sel,"_",best_n_non_CG,".tsv"))
# Fitting Gaussians to separate the components of the pmeth distribution was generally unsuccessful. It was able to identify the cutoff around pmeth=0.067, but this led to highly fragmented unmethylated regions, with very many very short methylated segments that were unconvincing. Manually setting the cutoff to pmeth=0.15 in the segmentation, on the basis of visual inspection of the methylation landscape, produced a much better segmentation result. We will manually set best_n_non_CG=200
m_non_CG.sel=0.15
best_n_non_CG=200
# Clean up memory space
# rm(UMRLMRsegments_non_CG.gr)
# gc()
UMRLMRsegments_non_CG.gr <- segmentUMRsLMRs(m=meth_CHG_CHH.gr, meth.cutoff=m_non_CG.sel, nCpG.cutoff=best_n_non_CG, num.cores=1, myGenomeSeq=Athaliana, seqLengths=sLengths, pdfFilename=paste0(project_id,"_",meth_context,"_",sample_id,"_MethylSeekR_non_CG_segmentation_landscape_",best_n_non_CG,"_",m_non_CG.sel,".pdf"))
pdf(paste0(project_id,"_",meth_context,"_",sample_id,"_MethylSeekR_CG_segmentation_landscape_",best_n_non_CG,"_",m_non_CG.sel,"_density.pdf"))
print(ggplot(as.data.frame(UMRLMRsegments_non_CG.gr@elementMetadata@listData), aes(x=pmeth)) + geom_histogram(binwidth=0.01))
dev.off()
# Save segmentation
saveUMRLMRSegments(segs=UMRLMRsegments_non_CG.gr, GRangesFilename=paste0(sample_id,"UMRsLMRs_non_CG_",m_non_CG.sel,"_",best_n_non_CG,".gr.rds"), TableFilename=paste0(project_id,"_",meth_context,"_",sample_id,"_MethylSeekR_segments_non_CG_",m_non_CG.sel,"_",best_n_non_CG,".tsv"))
#MG_segments.gr = setdiff(genome_loci.gr, mask_loci.gr)
m_non_CG_segments.gr = setdiff(setdiff(genome_loci.gr, UMRLMRsegments_non_CG.gr), mask_loci.gr)
UMR_non_CG_segments.gr = setdiff(UMRLMRsegments_non_CG.gr, mask_loci.gr)
# Switch to CG context to complete the segmentation
meth_context="CG"
# Free up some space
rm(meth_CHG_CHH.gr)
gc()
# get the list of runs for the sample
# concatenate the methylation data for the runs
all_samples_ct=NA
run_no = 0
for (this_run in fastq_list[fastq_list$experiment_accession==sample_id,"run_accession"]) {
run_no = run_no + 1
if(opt$verbose) {cat(paste0("Loading ",this_run,"\n"))}
x=read.table(file=paste0(source_dir, this_run, "_TAIR10.cg.methratio2"), header=TRUE, sep="\t")
# needs sep="\t" because some entries (e.g. first two in mitochondria) have no entry in context string for some reason
# merge the data for this sample with the accumulated data
colnames(x)[7]=paste0(this_run,"_C")
x$T_count = x[,6]-x[,7]
colnames(x)[10]=paste0(this_run,"_T")
if (run_no==1) {
all_samples_ct=x[c("chr","pos","strand",paste0(this_run,"_C"),paste0(this_run,"_T"))]
} else {
all_samples_ct=merge(x[c("chr","pos","strand",paste0(this_run,"_C"),paste0(this_run,"_T"))], all_samples_ct, by=c("chr","pos","strand"), all=TRUE)
}
rm(x)
}
# make new columns for the totals
all_samples_ct[,paste0(sample_id,"_C")] = rep(0, nrow(all_samples_ct))
all_samples_ct[,paste0(sample_id,"_T")] = rep(0, nrow(all_samples_ct))
#colnames(all_samples_ct)[4 + run_no*2]=paste0(sample_id,"_C")
#colnames(all_samples_ct)[4 + run_no*2]=paste0(sample_id,"_T")
# accumulate the totals for all runs
run_no = 0
for (this_run in fastq_list[fastq_list$experiment_accession==sample_id,"run_accession"]) {
run_no = run_no + 1
if(opt$verbose) {cat(paste0("Accumulating ",this_run,"\n"))}
all_samples_ct[,paste0(sample_id,"_C")] = all_samples_ct[,paste0(sample_id,"_C")] + ifelse(is.na(all_samples_ct[,paste0(this_run,"_C")]),0,all_samples_ct[,paste0(this_run,"_C")])
all_samples_ct[,paste0(sample_id,"_T")] = all_samples_ct[,paste0(sample_id,"_T")] + ifelse(is.na(all_samples_ct[,paste0(this_run,"_T")]),0,all_samples_ct[,paste0(this_run,"_T")])
}
colnames(all_samples_ct)[1]="Chromosome"
colnames(all_samples_ct)[2]="Locus"
colnames(all_samples_ct)[3]="Strand"
all_samples_ct = all_samples_ct[,c(1, 2, 3, 4 + run_no*2, 5 + run_no*2)]
#all_samples_ct = data.table(all_samples_ct,key=c("Chromosome", "Locus","Strand"))
# Dump the data table to file for a convenience cache
saveRDS(all_samples_ct, file=paste0(project_id,"_",meth_context,"_",sample_id,"_all_samples_ct.rds"))
### Read in the SNPs data
#snps.gr <- readSNPTable(FileName=snpFname, seqLengths=sLengths)
# We will set sample_C and sample_T to 0 for all CG loci where there is an annotated mutation
# Find the ecotype corresponding to this sample
this_ecotype = sample_list[sample_list$SRA.Accession==sample_id, "Ecotype_id"]
this_snp_file = paste0(reference_dir,this_ecotype,"_CG_vars.txt")
if (file.exists(this_snp_file)) {
if(opt$verbose) {cat(paste0("Loading ",this_ecotype," SNPs\n"))}
#no_ecotypes = no_ecotypes + 1
#samples_with_genomes=c(samples_with_genomes, this_sample)
# read in the known C sites with SNPs for this sample. Use unique to deduplicate cases where the same site is listed more than once
this_sample_snps = unique(read.table(this_snp_file, header=FALSE, sep="\t"))
colnames(this_sample_snps) = c("Chromosome", "Locus")
#merge snps and sample to get rid of any rows exclusively from snp file, then replace sample values with 0 where a SNP was found
mutant_sites = merge(all_samples_ct[,c("Chromosome", "Locus")], cbind(this_sample_snps, "mutation"=rep(1,nrow(this_sample_snps))), by = c("Chromosome", "Locus"), all.x=TRUE, all.y=FALSE)
all_samples_ct[, paste0(sample_id,"_C")] = ifelse(is.na(mutant_sites$mutation), all_samples_ct[, paste0(sample_id,"_C")], 0)
all_samples_ct[, paste0(sample_id,"_T")] = ifelse(is.na(mutant_sites$mutation), all_samples_ct[, paste0(sample_id,"_T")], 0)
}
# Write out a copy of the SNP-masked methylome in the format that MethylSeekR likes to read in (Cov_C+Cov_T, Cov_C)
#all_samples_ct = data.frame(all_samples_ct)
write.table(cbind(as.character(all_samples_ct$Chromosome), format(all_samples_ct$Locus, scientific=FALSE), as.numeric(all_samples_ct[,paste0(sample_id,"_C")])+as.numeric(all_samples_ct[,paste0(sample_id,"_T")]), as.numeric(all_samples_ct[,paste0(sample_id,"_C")])),file=paste0(project_id,"_",meth_context,"_",sample_id,"_TM_read_counts_across_samples.tsv"),sep="\t",col.names=FALSE,row.names=FALSE,quote=FALSE)