forked from FelixKrueger/Bismark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bismark_methylation_extractor_bwasp
executable file
·6708 lines (5735 loc) · 324 KB
/
bismark_methylation_extractor_bwasp
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 perl
use warnings;
use strict;
$|++;
use Getopt::Long;
use Cwd;
use Carp;
use FindBin qw($RealBin);
use lib "$RealBin/../lib";
## This program is Copyright (C) 2010-18, Felix Krueger ([email protected])
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
my @filenames; # input files
my %counting;
my $parent_dir = getcwd();
my %fhs;
my $version = 'v0.19.1';
my (
$ignore, $genomic_fasta, $single, $paired, $full,
$report, $no_overlap, $merge_non_CpG, $vanilla, $output_dir,
$no_header, $bedGraph, $remove, $coverage_threshold, $counts,
$cytosine_report, $genome_folder, $zero, $CpG_only, $CX_context,
$split_by_chromosome, $sort_size, $samtools_path, $gzip, $ignore_r2,
$mbias_off, $mbias_only, $gazillion, $ample_mem, $maxrlgth,
$maxrlgth_r2, $multicore, $yacht
) = process_commandline();
### only needed for bedGraph output
my @sorting_files; # if files are to be written to bedGraph format, these are the methylation extractor output files
my @methylcalls = qw (0 0 0); # [0] = methylated, [1] = unmethylated, [2] = total
my @bedfiles;
### only needed for genome-wide cytosine methylation report
my %chromosomes;
my %mbias_1;
my %mbias_2;
my ( $ignore_3prime, $ignore_3prime_r2 );
##############################################################################################
### Summarising Run Parameters
##############################################################################################
### METHYLATION EXTRACTOR
warn "Summarising Bismark methylation extractor parameters:\n";
warn '=' x 63, "\n";
if ($single) {
if ($vanilla) {
warn "Bismark single-end vanilla format specified\n";
} else {
warn "Bismark single-end SAM format specified (default)\n"; # default
}
} elsif ($paired) {
if ($vanilla) {
warn "Bismark paired-end vanilla format specified\n";
} else {
warn "Bismark paired-end SAM format specified (default)\n"; # default
}
} ## end elsif ($paired)
warn "Number of cores to be used: $multicore\n";
if ($single) {
if ($ignore) {
warn "First $ignore bp will be disregarded when processing the methylation call string\n";
}
if ($maxrlgth) {
warn "Positions beyond $maxrlgth will be disregarded when processing the methylation call string\n";
}
} else { ## paired-end
if ($ignore) {
warn "First $ignore bp will be disregarded when processing the methylation call string of Read 1\n";
}
if ($ignore_r2) {
warn "First $ignore_r2 bp will be disregarded when processing the methylation call string of Read 2\n";
}
if ($maxrlgth) {
warn "Positions beyond $maxrlgth will be disregarded when processing the methylation call string of Read 1\n";
}
if ($maxrlgth_r2) {
warn "Positions beyond $maxrlgth_r2 will be disregarded when processing the methylation call string of Read 2\n";
}
} ## end else [ if ($single) ]
if ($full) {
warn
"Strand-specific outputs will be skipped. Separate output files for cytosines in CpG, CHG and CHH context will be generated\n";
}
if ($merge_non_CpG) {
warn "Merge CHG and CHH context to non-CpG context specified\n";
}
### output directory
if ( $output_dir eq '' ) {
warn "Output will be written to the current directory ('$parent_dir')\n";
} else {
warn "Output path specified as: $output_dir\n";
}
sleep(1);
### BEDGRAPH
if ($bedGraph) {
warn "\n\nSummarising bedGraph parameters:\n";
warn '=' x 63, "\n";
if ($counts) {
warn
"Generating additional output in bedGraph and coverage format\nbedGraph format:\t<Chromosome> <Start Position> <End Position> <Methylation Percentage>\ncoverage format:\t<Chromosome> <Start Position> <End Position> <Methylation Percentage> <count methylated> <count non-methylated>\n\n";
} else {
warn
"Generating additional sorted output in bedGraph format (output format: <Chromosome> <Start Position> <End Position> <Methylation Percentage>)\n";
}
### Zero-based coordinates
if ($zero) {
warn
"Writing out an additional coverage file (ending in zero.cov) with 0-based start and 1-based end genomic coordinates (zero-based, half-open; user-defined)\n";
}
warn "Using a cutoff of $coverage_threshold read(s) to report cytosine positions\n";
if ($CX_context) {
warn
"Reporting and sorting methylation information for all cytosine context (sorting may take a long time, you have been warned ...)\n";
} else { # default
$CpG_only = 1;
warn "Reporting and sorting cytosine methylation information in CpG context only (default)\n";
}
if ($remove) {
warn "White spaces in read ID names will be removed prior to sorting\n";
}
if ($ample_mem) {
warn "Sorting chromosomal postions for the bedGraph step using arrays instead of using UNIX sort\n";
} elsif ( defined $sort_size ) {
warn
"The bedGraph UNIX sort command will use the following memory setting:\t'$sort_size'. Temporary directory used for sorting is the output directory\n";
} else {
warn "Setting a default memory usage for the bedGraph UNIX sort command to 2GB\n";
}
sleep(1);
if ($cytosine_report) {
warn "\n\nSummarising genome-wide cytosine methylation report parameters:\n";
warn '=' x 63, "\n";
warn
"Generating comprehensive genome-wide cytosine report\n(output format: <Chromosome> <Position> <Strand> <count methylated> <count non-methylated> <C-context> <trinucleotide context> )\n";
if ($CX_context) {
warn "Reporting methylation for all cytosine contexts. Be aware that this will generate enormous files\n";
} else { # default
$CpG_only = 1;
warn "Reporting cytosine methylation in CpG context only (default)\n";
}
if ($split_by_chromosome) {
warn "Splitting the cytosine report output up into individual files for each chromosome\n";
}
### Zero-based coordinates
if ($zero) {
warn "Using zero-based start and 1-based end genomic coordinates (zero-based, half-open; user-defined)\n";
} else { # default, 1-based coords
warn "Using 1-based genomic coordinates (default)\n";
}
### GENOME folder
if ($genome_folder) {
unless ( $genome_folder =~ /\/$/ ) {
$genome_folder =~ s/$/\//;
}
unless ( -d $genome_folder ) {
die
"The specified genome folder does not appear to be a directory. Please respecify and try again!\n\n";
}
warn "Genome folder was specified as $genome_folder\n";
} else {
$genome_folder = '/data/public/Genomes/Mouse/NCBIM37/';
warn "Using the default genome folder /data/public/Genomes/Mouse/NCBIM37/\n";
}
sleep(1);
} ## end if ($cytosine_report)
} ## end if ($bedGraph)
warn "\n";
sleep(1);
######################################################
### PROCESSING FILES
######################################################
foreach my $filename (@filenames) {
# resetting counters and filehandles
%fhs = ();
%counting = (
total_meCHG_count => 0,
total_meCHH_count => 0,
total_meCpG_count => 0,
total_unmethylated_CHG_count => 0,
total_unmethylated_CHH_count => 0,
total_unmethylated_CpG_count => 0,
sequences_count => 0,
methylation_call_strings => 0,
);
@sorting_files = ();
@bedfiles = ();
%mbias_1 = ();
%mbias_2 = ();
unless ($vanilla) {
# Testing if the file appears to be truncated, in which case we bail with a big scary warning message
if ( $filename =~ /(\.bam$)/ ) {
bam_isTruncated($filename);
}
### performing a quick check to see if a paired-end SAM file has been sorted by positions which does interfere with the logic used by the extractor
if ($paired) {
test_positional_sorting($filename);
}
} ## end unless ($vanilla)
my ( $pid, $pids, $report_basename ) = process_Bismark_results_file($filename);
if ( $pid == 0 ) {
warn "Finished processing child process. Exiting..\n";
# ### Closing all filehandles of the child process so that the Bismark methylation extractor output doesn't get truncated due to buffering issues
# foreach my $fh (keys %fhs) {
# if ($fh =~ /^[1230]$/) {
# foreach my $context (keys %{$fhs{$fh}}) {
# $fhs{$fh}->{$context}->flush;
# }
# }
# else{
# $fhs{$fh}->flush;
# }
# }
exit 0;
} ## end if ( $pid == 0 )
###
if ( $pid and $multicore > 1 ) {
warn "Now waiting for all child processes to complete\n";
sleep(1);
### we need to ensure that we wait for all child processes to be finished before continuing
# warn "here are the child IDs: @$pids\n";
# warn "Looping through the child process IDs:\n";
foreach my $id (@$pids) {
# print "$id\t";
my $kid = waitpid( $id, 0 );
# print "Returned: $kid\nExit status: $?\n";
unless ( $? == 0 ) {
warn "\nChild process terminated with exit signal: '$?'\n\n";
}
} ## end foreach my $id (@$pids)
} ## end if ( $pid and $multicore...)
### Closing all filehandles so that the Bismark methylation extractor output doesn't get truncated due to buffering issues
foreach my $fh ( keys %fhs ) {
if ( $fh =~ /^[1230]$/ ) {
foreach my $context ( keys %{ $fhs{$fh} } ) {
close $fhs{$fh}->{$context} or die $!;
}
} else {
close $fhs{$fh} or die $!;
}
} ## end foreach my $fh ( keys %fhs )
### We need to stitch together a main splitting report from all individual parent/child processes
if ( $multicore > 1 ) {
merge_individual_splitting_reports($report_basename);
print_splitting_report();
merge_individual_mbias_reports($report_basename)
; # this updates the main %mbias_1 and %mbias_2 data structures so we can proceed normally
} ## end if ( $multicore > 1 )
unless ($mbias_off) {
### printing out all M-Bias data
produce_mbias_plots($filename);
}
unless ($mbias_only) {
delete_unused_files();
}
if ($bedGraph) {
my $out = ( split( /\//, $filename ) )[-1]; # extracting the filename if a full path was specified
$out =~ s/gz$//;
$out =~ s/sam$//;
$out =~ s/bam$//;
$out =~ s/txt$//;
$out =~ s/$/bedGraph/;
my $bedGraph_output = $out;
my @args;
if ($remove) {
push @args, '--remove';
}
if ($CX_context) {
push @args, '--CX_context';
}
if ($no_header) {
push @args, '--no_header';
}
if ($gazillion) {
push @args, '--gazillion';
}
if ($ample_mem) {
push @args, '--ample_memory';
}
if ($zero) {
push @args, "--zero";
}
# if ($counts){
# push @args, "--counts";
# }
push @args, "--buffer_size $sort_size";
push @args, "--cutoff $coverage_threshold";
push @args, "--output $bedGraph_output";
push @args, "--dir '$output_dir'";
### adding all files to be sorted to @args
foreach my $f (@sorting_files) {
push @args, $f;
}
# print join "\t",@args,"\n";
system("$RealBin/bismark2bedGraph @args");
warn "Finished BedGraph conversion ...\n\n";
sleep(1);
# open (OUT,'>',$output_dir.$bedGraph_output) or die "Problems with the bedGraph output filename detected: file path: '$output_dir'\tfile name: '$bedGraph_output' $!";
# warn "Writing bedGraph to file: $bedGraph_output\n";
# process_bedGraph_output();
# close OUT or die $!;
### genome-wide cytosine methylation report requires bedGraph processing anyway
if ($cytosine_report) {
@args = (); # resetting @args
my $cytosine_out = $out;
$cytosine_out =~ s/bedGraph$//;
if ($CX_context) {
$cytosine_out =~ s/$/CX_report.txt/;
} else {
$cytosine_out =~ s/$/CpG_report.txt/;
}
push @args, "--output $cytosine_out";
push @args, "--dir '$output_dir'";
push @args, "--genome '$genome_folder'";
push @args, "--parent_dir '$parent_dir'";
if ($zero) {
push @args, "--zero";
}
if ($CX_context) {
push @args, '--CX_context';
}
if ($split_by_chromosome) {
push @args, '--split_by_chromosome';
}
if ($gzip) {
push @args, '--gzip';
}
my $coverage_output = $bedGraph_output;
$coverage_output =~ s/bedGraph$/bismark.cov.gz/;
push @args, $coverage_output; # this will be the infile
# warn "Handing over the following infile: $coverage_output\n"; sleep (5);
system("$RealBin/coverage2cytosine @args");
warn "\n\nFinished generating genome-wide cytosine report\n\n";
} ## end if ($cytosine_report)
} ## end if ($bedGraph)
} ## end foreach my $filename (@filenames)
sub merge_individual_splitting_reports {
my $report_basename = shift;
my @splitting_reports; # only needed in multi-core mode to generate an overall report
foreach my $ext ( 1 .. $multicore ) {
push @splitting_reports, "$report_basename.$ext";
}
warn "\nMerging individual splitting reports into overall report: '$report_basename'\n";
warn "Merging from these individual files:\n";
print join( "\n", @splitting_reports ), "\n\n";
sleep(1);
##########
# resetting the counter first
%counting = (
total_meCHG_count => 0,
total_meCHH_count => 0,
total_meCpG_count => 0,
total_unmethylated_CHG_count => 0,
total_unmethylated_CHH_count => 0,
total_unmethylated_CpG_count => 0,
sequences_count => 0,
methylation_call_strings => 0,
);
# repopulating the merged counter
foreach my $file (@splitting_reports) {
open( IR, $file ) or die $!;
while (<IR>) {
chomp;
my ( $context, $count ) = ( split /\t/ );
if ($context) {
if ( $context =~ /^Total C to T conversions in CpG context/ ) {
# warn "context: $context\ncount: $count\n";
$counting{total_unmethylated_CpG_count} += $count;
} elsif ( $context =~ /^Total C to T conversions in CHG context/ ) {
# warn "context: $context\ncount: $count\n";
$counting{total_unmethylated_CHG_count} += $count;
} elsif ( $context =~ /^Total C to T conversions in CHH context/ ) {
# warn "context: $context\ncount: $count\n";
$counting{total_unmethylated_CHH_count} += $count;
} elsif ( $context =~ /^Total methylated C\'s in CpG context/ ) {
# warn "context: $context\ncount: $count\n";
$counting{total_meCpG_count} += $count;
} elsif ( $context =~ /^Total methylated C\'s in CHG context/ ) {
# warn "context: $context\ncount: $count\n";
$counting{total_meCHG_count} += $count;
} elsif ( $context =~ /^Total methylated C\'s in CHH context/ ) {
# warn "context: $context\ncount: $count\n";
$counting{total_meCHH_count} += $count;
} elsif ( $context =~ /^line count/ ) {
# warn "Line count\ncount: $count\n";
$counting{sequences_count} = $count; # always the same
} elsif ( $context =~ /^meth call strings/ ) {
# warn "Meth call strings\ncount: $count\n";
$counting{methylation_call_strings} += $count;
}
} ## end if ($context)
} ## end while (<IR>)
} ## end foreach my $file (@splitting_reports)
# deleting the individual reports afterwards
foreach my $file (@splitting_reports) {
unlink $file;
}
} ## end sub merge_individual_splitting_reports
sub merge_individual_mbias_reports {
my $report_basename = shift;
my @mbias_reports; # only needed in multi-core mode to generate an overall report
foreach my $ext ( 1 .. $multicore ) {
push @mbias_reports, "$report_basename.${ext}.mbias";
}
warn "\nMerging individual M-bias reports into overall M-bias statistics from these $multicore individual files:\n";
print join( "\n", @mbias_reports ), "\n\n";
##########
# resetting the counters first, then repopulating them
%mbias_1 = ();
%mbias_2 = ();
# repopulating the merged counter
foreach my $file (@mbias_reports) {
open( IR, $file ) or die $!;
my $context;
my $read;
while (<IR>) {
chomp;
# warn "$_\n"; sleep(1);
if ( $_ =~ /context/ ) {
$context = $1 if ( $_ =~ /(\D{3}) context/ );
# warn "Context set as $context\n";
if ( $_ =~ /R2/ ) {
$read = 'R2';
} else {
$read = 'R1';
}
# warn "Setting read identity to '$read'\n";
# reading in 2 additional lines (===========, and header line)
$_ = <IR>;
#warn "discarding line $_\n";
$_ = <IR>;
#warn "discarding line $_\n";
next;
} else {
if ( $_ eq '' ) {
# empty line, only occurs after a context has finished and before a new context starts
next;
}
my ( $pos, $meth, $unmeth ) = ( split /\t/ );
# warn "$pos\t$meth\t$unmeth\n"; sleep(1);
if ( $read eq 'R1' ) {
$mbias_1{$context}->{$pos}->{meth} += $meth;
$mbias_1{$context}->{$pos}->{un} += $unmeth;
} elsif ( $read eq 'R2' ) {
$mbias_2{$context}->{$pos}->{meth} += $meth;
$mbias_2{$context}->{$pos}->{un} += $unmeth;
}
} ## end else [ if ( $_ =~ /context/ )]
} ## end while (<IR>)
close IR or warn "Had trouble closing filehandle for $file: $!\n";
} ## end foreach my $file (@mbias_reports)
# deleting the individual reports afterwards
foreach my $file (@mbias_reports) {
unlink $file;
}
} ## end sub merge_individual_mbias_reports
sub delete_unused_files {
warn "Deleting unused files ...\n\n";
sleep(1);
my $index = 0;
while ( $index <= $#sorting_files ) {
if ( $sorting_files[$index] =~ /gz$/ ) {
open( USED, "gunzip -c $sorting_files[$index] |" )
or die "Failed to read from methylation extractor output file $sorting_files[$index]: $!\n";
} else {
open( USED, $sorting_files[$index] )
or die "Failed to read from methylation extractor output file $sorting_files[$index]: $!\n";
}
my $used = 0;
while (<USED>) {
next if (/^Bismark/);
if ($_) {
$used = 1;
last;
}
} ## end while (<USED>)
if ($used) {
warn "$sorting_files[$index] contains data ->\tkept\n";
++$index;
} else {
my $delete = unlink $sorting_files[$index];
if ($delete) {
warn "$sorting_files[$index] was empty ->\tdeleted\n";
} else {
warn "$sorting_files[$index] was empty, however deletion was unsuccessful: $!\n";
}
### we also need to remove the element from @sorting_files
splice @sorting_files, $index, 1;
} ## end else [ if ($used) ]
} ## end while ( $index <= $#sorting_files)
warn "\n\n"; ## can't close the piped filehandles at this point because it will die (unfortunately)
} ## end sub delete_unused_files
sub produce_mbias_plots {
my $filename = shift;
my $mbias = ( split( /\//, $filename ) )[-1]; # extracting the filename if a full path was specified
$mbias =~ s/gz$//;
$mbias =~ s/sam$//;
$mbias =~ s/bam$//;
$mbias =~ s/cram$//;
$mbias =~ s/txt$//;
my $mbias_graph_1 = my $mbias_graph_2 = $mbias;
$mbias_graph_1 = $output_dir . $mbias_graph_1 . 'M-bias_R1.png';
$mbias_graph_2 = $output_dir . $mbias_graph_2 . 'M-bias_R2.png';
$mbias =~ s/$/M-bias.txt/;
open( MBIAS, '>', "$output_dir$mbias" ) or die "Failed to open file for the M-bias data\n\n";
# determining maximum read length
my $max_length_1 = 0;
my $max_length_2 = 0;
foreach my $context ( keys %mbias_1 ) {
foreach my $pos ( sort { $a <=> $b } keys %{ $mbias_1{$context} } ) {
$max_length_1 = $pos unless ( $max_length_1 >= $pos );
}
}
if ($paired) {
foreach my $context ( keys %mbias_2 ) {
foreach my $pos ( sort { $a <=> $b } keys %{ $mbias_2{$context} } ) {
$max_length_2 = $pos unless ( $max_length_2 >= $pos );
}
}
} ## end if ($paired)
if ($single) {
warn "Determining maximum read length for M-Bias plot\n";
warn "Maximum read length of Read 1: $max_length_1\n\n";
} else {
warn "Determining maximum read lengths for M-Bias plots\n";
warn "Maximum read length of Read 1: $max_length_1\n";
warn "Maximum read length of Read 2: $max_length_2\n\n";
}
# sleep(3);
my @mbias_read1;
my @mbias_read2;
#Check whether the module GD::Graph:lines is installed
my $gd_graph_installed = 0;
eval {
require GD::Graph::lines;
GD::Graph::lines->import();
};
unless ($@) { # syntax or routine error variable, set if something goes wrong in the last eval{ require ...}
$gd_graph_installed = 1;
#Check whether the module GD::Graph::colour is installed
eval {
require GD::Graph::colour;
GD::Graph::colour->import(qw(:colours :lists :files :convert));
};
if ($@) {
warn
"Perl module GD::Graph::colour not found, skipping drawing M-bias plots (only writing out M-bias plot table)\n";
sleep(2);
$gd_graph_installed = 0;
} ## end if ($@)
} else {
warn
"Perl module GD::Graph::lines is not installed, skipping drawing M-bias plots (only writing out M-bias plot table)\n";
sleep(2);
}
my $graph_title;
my $graph1;
my $graph2;
if ($gd_graph_installed) {
$graph1 = GD::Graph::lines->new( 800, 600 );
if ($paired) {
$graph2 = GD::Graph::lines->new( 800, 600 );
}
} ## end if ($gd_graph_installed)
foreach my $context (qw(CpG CHG CHH)) {
@{ $mbias_read1[0] } = ();
if ($paired) {
print MBIAS "$context context (R1)\n================\n";
$graph_title = 'M-bias (Read 1)';
} else {
print MBIAS "$context context\n===========\n";
$graph_title = 'M-bias';
}
print MBIAS "position\tcount methylated\tcount unmethylated\t% methylation\tcoverage\n";
foreach my $pos ( 1 .. $max_length_1 ) {
unless ( defined $mbias_1{$context}->{$pos}->{meth} ) {
$mbias_1{$context}->{$pos}->{meth} = 0;
}
unless ( defined $mbias_1{$context}->{$pos}->{un} ) {
$mbias_1{$context}->{$pos}->{un} = 0;
}
my $percent = '';
if ( ( $mbias_1{$context}->{$pos}->{meth} + $mbias_1{$context}->{$pos}->{un} ) > 0 ) {
$percent = sprintf( "%.2f",
$mbias_1{$context}->{$pos}->{meth} * 100 /
( $mbias_1{$context}->{$pos}->{meth} + $mbias_1{$context}->{$pos}->{un} ) );
}
my $coverage = $mbias_1{$context}->{$pos}->{un} + $mbias_1{$context}->{$pos}->{meth};
print MBIAS
"$pos\t$mbias_1{$context}->{$pos}->{meth}\t$mbias_1{$context}->{$pos}->{un}\t$percent\t$coverage\n";
push @{ $mbias_read1[0] }, $pos;
if ( $context eq 'CpG' ) {
push @{ $mbias_read1[1] }, $percent;
push @{ $mbias_read1[4] }, $coverage;
} elsif ( $context eq 'CHG' ) {
push @{ $mbias_read1[2] }, $percent;
push @{ $mbias_read1[5] }, $coverage;
} elsif ( $context eq 'CHH' ) {
push @{ $mbias_read1[3] }, $percent;
push @{ $mbias_read1[6] }, $coverage;
}
} ## end foreach my $pos ( 1 .. $max_length_1)
print MBIAS "\n";
} ## end foreach my $context (qw(CpG CHG CHH))
if ($gd_graph_installed) {
add_colour( nice_blue => [ 31, 120, 180 ] );
add_colour( nice_orange => [ 255, 127, 0 ] );
add_colour( nice_green => [ 51, 160, 44 ] );
add_colour( pale_blue => [ 153, 206, 227 ] );
add_colour( pale_orange => [ 253, 204, 138 ] );
add_colour( pale_green => [ 191, 230, 207 ] );
$graph1->set(
x_label => 'position (bp)',
y1_label => '% methylation',
y2_label => '# methylation calls',
title => $graph_title,
line_width => 2,
x_max_value => $max_length_1,
x_min_value => 0,
y_tick_number => 10,
y_label_skip => 2,
y1_max_value => 100,
y1_min_value => 0,
y_label_skip => 2,
y2_min_value => 0,
x_label_skip => 5,
x_label_position => 0.5,
x_tick_offset => -1,
bgclr => 'white',
transparent => 0,
two_axes => 1,
use_axis => [ 1, 1, 1, 2, 2, 2 ],
legend_placement => 'RC',
legend_spacing => 6,
legend_marker_width => 24,
legend_marker_height => 18,
dclrs => [qw(nice_blue nice_orange nice_green pale_blue pale_orange pale_green)],
) or die $graph1->error;
$graph1->set_legend(
'CpG methylation',
'CHG methylation',
'CHH methylation',
'CpG total calls',
'CHG total calls',
'CHH total calls'
);
### Failure to plot the MBIAS graph will now generate a warning instead of dieing (previous version below. Suggested by Andrew DeiRossi, 05 June 2014)
if ( my $gd1 = $graph1->plot( \@mbias_read1 ) ) {
open( MBIAS_G1, '>', $mbias_graph_1 ) or die "Failed to write to file for M-bias plot 1: $!\n\n";
binmode MBIAS_G1;
print MBIAS_G1 $gd1->png;
} else {
warn "WARNING: Cannot generate read 1 M-bias plot: ", $graph1->error, "\n\n";
}
# my $gd1 = $graph1->plot(\@mbias_read1) or die $graph1->error;
# open (MBIAS_G1,'>',$mbias_graph_1) or die "Failed to write to file for M-bias plot 1: $!\n\n";
# binmode MBIAS_G1;
# print MBIAS_G1 $gd1->png;
} ## end if ($gd_graph_installed)
if ($paired) {
foreach my $context (qw(CpG CHG CHH)) {
@{ $mbias_read2[0] } = ();
print MBIAS "$context context (R2)\n================\n";
print MBIAS "position\tcount methylated\tcount unmethylated\t% methylation\tcoverage\n";
foreach my $pos ( 1 .. $max_length_2 ) {
unless ( defined $mbias_2{$context}->{$pos}->{meth} ) {
$mbias_2{$context}->{$pos}->{meth} = 0;
}
unless ( defined $mbias_2{$context}->{$pos}->{un} ) {
$mbias_2{$context}->{$pos}->{un} = 0;
}
my $percent = '';
if ( ( $mbias_2{$context}->{$pos}->{meth} + $mbias_2{$context}->{$pos}->{un} ) > 0 ) {
$percent = sprintf( "%.2f",
$mbias_2{$context}->{$pos}->{meth} * 100 /
( $mbias_2{$context}->{$pos}->{meth} + $mbias_2{$context}->{$pos}->{un} ) );
}
my $coverage = $mbias_2{$context}->{$pos}->{un} + $mbias_2{$context}->{$pos}->{meth};
print MBIAS
"$pos\t$mbias_2{$context}->{$pos}->{meth}\t$mbias_2{$context}->{$pos}->{un}\t$percent\t$coverage\n";
push @{ $mbias_read2[0] }, $pos;
if ( $context eq 'CpG' ) {
push @{ $mbias_read2[1] }, $percent;
push @{ $mbias_read2[4] }, $coverage;
} elsif ( $context eq 'CHG' ) {
push @{ $mbias_read2[2] }, $percent;
push @{ $mbias_read2[5] }, $coverage;
} elsif ( $context eq 'CHH' ) {
push @{ $mbias_read2[3] }, $percent;
push @{ $mbias_read2[6] }, $coverage;
}
} ## end foreach my $pos ( 1 .. $max_length_2)
print MBIAS "\n";
} ## end foreach my $context (qw(CpG CHG CHH))
if ($gd_graph_installed) {
add_colour( nice_blue => [ 31, 120, 180 ] );
add_colour( nice_orange => [ 255, 127, 0 ] );
add_colour( nice_green => [ 51, 160, 44 ] );
add_colour( pale_blue => [ 153, 206, 227 ] );
add_colour( pale_orange => [ 253, 204, 138 ] );
add_colour( pale_green => [ 191, 230, 207 ] );
$graph2->set(
x_label => 'position (bp)',
line_width => 2,
x_max_value => $max_length_1,
x_min_value => 0,
y_tick_number => 10,
y_label_skip => 2,
y1_max_value => 100,
y1_min_value => 0,
y_label_skip => 2,
y2_min_value => 0,
x_label_skip => 5,
x_label_position => 0.5,
x_tick_offset => -1,
bgclr => 'white',
transparent => 0,
two_axes => 1,
use_axis => [ 1, 1, 1, 2, 2, 2 ],
legend_placement => 'RC',
legend_spacing => 6,
legend_marker_width => 24,
legend_marker_height => 18,
dclrs => [qw(nice_blue nice_orange nice_green pale_blue pale_orange pale_green)],
x_label => 'position (bp)',
y1_label => '% methylation',
y2_label => '# calls',
title => 'M-bias (Read 2)',
) or die $graph2->error;
$graph2->set_legend(
'CpG methylation',
'CHG methylation',
'CHH methylation',
'CpG total calls',
'CHG total calls',
'CHH total calls'
);
### Failure to plot the MBIAS graph will now generate a warning instead of dieing (previous version below. Suggested by Andrew DeiRossi, 05 June 2014)
if ( my $gd2 = $graph2->plot( \@mbias_read2 ) ) {
open( MBIAS_G2, '>', $mbias_graph_2 ) or die "Failed to write to file for M-bias plot 2: $!\n\n";
binmode MBIAS_G2;
print MBIAS_G2 $gd2->png;
} else {
warn "WARNING: Cannot generate Read 2 M-bias plot: ", $graph2->error, "\n\n";
}
# my $gd2 = $graph2->plot(\@mbias_read2) or die $graph2->error;
# open (MBIAS_G2,'>',$mbias_graph_2) or die "Failed to write to file for M-bias plot 2: $!\n\n";
# binmode MBIAS_G2;
# print MBIAS_G2 $gd2->png;
} ## end if ($gd_graph_installed)
} ## end if ($paired)
} ## end sub produce_mbias_plots
sub process_commandline {
my $help;
my $single_end;
my $paired_end;
my $ignore;
my $ignore_r2;
my $genomic_fasta;
my $full;
my $report;
my $extractor_version;
my $no_overlap;
my $merge_non_CpG;
my $vanilla;
my $output_dir;
my $no_header;
my $bedGraph;
my $coverage_threshold = 1; # Minimum number of reads covering before calling methylation status
my $remove;
my $counts;
my $cytosine_report;
my $genome_folder;
my $zero;
my $CpG_only;
my $CX_context;
my $split_by_chromosome;
my $sort_size;
my $samtools_path;
my $gzip;
my $mbias_only;
my $mbias_off;
my $gazillion;
my $ample_mem;
my $include_overlap;
my $maxrlgth;
my $maxrlgth_r2;
my $multicore;
my $yacht;
my $command_line = GetOptions(
'help|man' => \$help,
'p|paired-end' => \$paired_end,
's|single-end' => \$single_end,
'fasta' => \$genomic_fasta,
'ignore=i' => \$ignore,
'ignore_r2=i' => \$ignore_r2,
'comprehensive' => \$full,
'report' => \$report,
'version' => \$extractor_version,
'no_overlap' => \$no_overlap,
'merge_non_CpG' => \$merge_non_CpG,
'vanilla' => \$vanilla,
'o|output=s' => \$output_dir,
'no_header' => \$no_header,
'bedGraph' => \$bedGraph,
"cutoff=i" => \$coverage_threshold,
"remove_spaces" => \$remove,
"counts" => \$counts,
"cytosine_report" => \$cytosine_report,
'g|genome_folder=s' => \$genome_folder,
"zero_based" => \$zero,
"CX|CX_context" => \$CX_context,
"split_by_chromosome" => \$split_by_chromosome,
"buffer_size=s" => \$sort_size,
'samtools_path=s' => \$samtools_path,
'gzip' => \$gzip,
'mbias_only' => \$mbias_only,
'mbias_off' => \$mbias_off,
'gazillion|scaffolds' => \$gazillion,
'ample_memory' => \$ample_mem,
'include_overlap' => \$include_overlap,
'maxrlgth=i' => \$maxrlgth,
'maxrlgth_r2=i' => \$maxrlgth_r2,
'parallel|multicore=i' => \$multicore,
'yacht' => \$yacht,
);
### EXIT ON ERROR if there were errors with any of the supplied options