-
Notifications
You must be signed in to change notification settings - Fork 103
/
coverage2cytosine
executable file
·2248 lines (1873 loc) · 76.4 KB
/
coverage2cytosine
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;
## This program is Copyright (C) 2010-23, 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 %chromosomes; # storing sequence information of all chromosomes/scaffolds
my %processed; # keeping a record of which chromosomes have been processed
my %context_summary; # storing methylation values for all contexts for NOMe-seq or scNMT-experiments
my $coverage2cytosine_version = 'v0.24.2';
my ($output_dir,$genome_folder,$zero,$CpG_only,$CX_context,$split_by_chromosome,$parent_dir,$coverage_infile,$cytosine_out,$merge_CpGs,$gc_context,$gzip,$tetra,$nome,$disco,$threshold,$drach) = process_commandline();
on_screen_summary();
read_genome_into_memory();
warn "Stored sequence information of ",scalar keys %chromosomes," chromosomes/scaffolds in total\n\n";
my $global_cyt_report;
### 18 August 2015. Update 12 Jan 2017: Additional restrictions for NOMe-Seq
# The following section reprocessed the genome to generate cytosine methylation output in GC context (e.g. when a GpC methylase had been deployed
if ($drach){
warn "Applying DRACH motif filtering to $coverage_infile. Exiting afterwards\n";
generate_DRACH_report($coverage_infile);
exit 0;
}
generate_genome_wide_cytosine_report($coverage_infile);
### 25 March 2020 (COVID19 lockdown)
# Trying to add context specific methylation summaries for NOMe-seq data https://github.com/FelixKrueger/Bismark/issues/321
print_context_summary();
### 11 December 2014
# The following optional section re-reads the genome-wide report and merges methylation evidence of both top and bottom strand
# into a single CpG dinucleotide entity. This significantly simplifies downstream processing, e.g. by the bsseq R-/Bioconductor package
# which recommends this merging process to increase coverage per CpG and reduce the memory burden for its processing
# Merge CpGs does not work in conjuction with --nome-seq (since some positions are filtered out).
if ($merge_CpGs) {
# we only allow this operation if the report is limited to CpG context, and for a single report for the entire genome for the time being
combine_CpGs_to_single_CG_entity($global_cyt_report);
}
sub print_context_summary{
print CONTEXTSUMMARY "upstream\tC-context\tfull context\tcount methylated\tcount unmethylated\tpercent methylation\n";
foreach my $context (sort keys %context_summary){
foreach my $ubase (sort keys %{$context_summary{$context}}){
my $perc;
if ( ($context_summary{$context}->{$ubase}->{u} + $context_summary{$context}->{$ubase}->{m}) > 0){
$perc = sprintf("%.2f", $context_summary{$context}->{$ubase}->{m} / ($context_summary{$context}->{$ubase}->{u} + $context_summary{$context}->{$ubase}->{m}) * 100);
}
else{
$perc = "N/A";
}
print CONTEXTSUMMARY "$ubase\t$context\t$ubase$context\t$context_summary{$context}->{$ubase}->{m}\t$context_summary{$context}->{$ubase}->{u}\t$perc\n";
}
}
}
### 18 August 2015. Update 12 Jan 2017: Additional restrictions for NOMe-Seq
# The following section reprocessed the genome to generate cytosine methylation output in GC context (e.g. when a GpC methylase had been deployed
if ($gc_context){
generate_GC_context_report($coverage_infile);
}
# function to handle file names and options. Assume $cytosine_out has been cleaned from unwanted suffixes
# First arg is optional chromosome number. Takes $cytosine_out, $split_by_chromosome, $nome, $gzip from outer scope.
sub handle_filehandles{
my $my_chr = shift;
if (defined $my_chr){
# warn "Working with chromosome in '--split_by_chromosome' mode\n";
}
my $cytosine_coverage_file = $cytosine_out;
my $cytosine_report_file;
if (defined $my_chr and $split_by_chromosome) {
## writing output to 1 file per chromosome
$cytosine_coverage_file =~ s/$/.chr${my_chr}/;
}
$cytosine_report_file = $cytosine_coverage_file; # required in any case
# if the data came from the methylation extractor it will already end in .CX_report.txt or .CpG_report.txt
if ($CX_context){
$cytosine_report_file =~ s/\.CX_report.txt$//; # removing to avoid duplication
}
else{
$cytosine_report_file =~ s/\.CpG_report.txt$//; # removing to avoid duplication
}
# 28 April 2020 - context summary will now always be printed
my $context_summary_file = $cytosine_report_file;
$context_summary_file .= '.cytosine_context_summary.txt';
open (CONTEXTSUMMARY,'>',"${output_dir}$context_summary_file") or die "Failed to write to file ${output_dir}$context_summary_file: $!\n";
if ($nome) {
$cytosine_report_file .= '.NOMe.CpG_report.txt';
$cytosine_coverage_file .= '.NOMe.CpG.cov';
if ($gzip) {
$cytosine_coverage_file .= '.gz';
$cytosine_report_file .= '.gz';
}
}
else {
if ($CX_context){
$cytosine_report_file .= $gzip ? '.CX_report.txt.gz' : '.CX_report.txt';
$cytosine_coverage_file .= $gzip ? '.CX.cov.gz' : '.CX.cov';
}
else{
$cytosine_report_file .= $gzip ? '.CpG_report.txt.gz' : '.CpG_report.txt';
$cytosine_coverage_file .= $gzip ? '.CpG.cov.gz' : '.CpG.cov';
}
}
if ($gzip) {
open (CYT,"| gzip -c - > ${output_dir}$cytosine_report_file") or die "Failed to write to file ${output_dir}$cytosine_report_file: $!\n";
if ($nome) {
open (CYTCOV,"| gzip -c - > ${output_dir}$cytosine_coverage_file") or die "Failed to write to file ${output_dir}$cytosine_coverage_file: $!\n";
}
}
else {
open (CYT,'>',"${output_dir}$cytosine_report_file") or die "Failed to open uncompressed file ${output_dir}$cytosine_report_file: $!\n";
if ($nome) {
open (CYTCOV,'>',"${output_dir}$cytosine_coverage_file") or die "Failed to open uncompressed file ${output_dir}$cytosine_coverage_file: $!\n";
}
}
$global_cyt_report = $cytosine_report_file; # needed for --merge_CpG option later on
if ($nome){
warn ">>> Writing genome-wide cytosine report to: $cytosine_report_file <<<\n";
warn ">>> Writing genome-wide cytosine coverage file to: $cytosine_coverage_file <<<\n\n";
}
else{
warn ">>> Writing genome-wide cytosine report to: $cytosine_report_file <<<\n\n";
}
warn ">>> Writing all cytosine context summary file to: $context_summary_file <<<\n\n";
return(defined $my_chr ? $my_chr : ''); # returning chromosome in --split_by_chromosome mode
}
sub generate_genome_wide_cytosine_report {
warn "="x78,"\n";
warn "Methylation information will now be written into a genome-wide cytosine report\n";
warn "="x78,"\n\n";
sleep (2);
my $number_processed = 0;
my $current_out_chr = '';
### changing to the output directory again
#unless ($output_dir eq ''){ # default
# chdir $output_dir or die "Failed to change directory to $output_dir\n";
# warn "Changed directory to $output_dir\n";
# }
my $in = shift;
# infiles handed over by the methylation extractor will be just the filename on their own. The directory should have been handed over with --dir
if ($in =~ /gz$/){
open (IN,"gunzip -c $in |") or die "Failed to read from gzipped file $in: $!\n"; # changed from gunzip -c to gunzip -c 08 04 16
}
else{
open (IN,"$in") or die "Failed to read from file $in: $!\n";
}
### 25 March/ 28 April 2020 (COVID-19 lockdown)
# Trying to add context specific methylation summaries for NOMe-seq data https://github.com/FelixKrueger/Bismark/issues/321
warn "Adding context-specific methylation summaries\n\n";
reset_context_summary();
# opening global output files unless --split_by_chromosome was specified
handle_filehandles() unless ($split_by_chromosome); ### writing all output to a single file (default)
my $last_chr;
my %chr; # storing reads for one chromosome at a time
my $count = 0;
while (<IN>){
chomp;
++$count;
my ($chr,$start,$end,undef,$meth,$nonmeth) = (split /\t/);
# defining the first chromosome
unless (defined $last_chr){
$last_chr = $chr;
++$number_processed;
warn "Storing all covered cytosine positions for chromosome: $chr\n";
if ($split_by_chromosome){
$current_out_chr = handle_filehandles($chr);
# warn "Returned the following current out chr: >>>$current_out_chr<<<\n";
}
}
### As of version 0.9.1 the start positions are 1-based!
if ($chr eq $last_chr){
$chr{$chr}->{$start}->{meth} = $meth;
$chr{$chr}->{$start}->{nonmeth} = $nonmeth;
}
else{
warn "Writing cytosine report for chromosome $last_chr (stored ",scalar keys %{$chr{$last_chr}}," different covered positions)\n";
++$number_processed;
my $tri_nt;
my $tetra_nt;
my $penta_nt;
my $context;
my $upstream_context; # for NOMe-Seq
$processed{$last_chr} = 1;
while ( $chromosomes{$last_chr} =~ /([CG])/g){ # C or G
$tri_nt = '';
$context = '';
if ($tetra){
$tetra_nt = ''; # clearing
$penta_nt = '';
}
$upstream_context = '';
my $pos = pos$chromosomes{$last_chr};
my $strand;
my $meth = 0;
my $nonmeth = 0;
if ($1 eq 'C'){ # C on forward strand
$tri_nt = substr ($chromosomes{$last_chr},($pos-1),3); # positions are 0-based!
if ($tetra){
if ( length($chromosomes{$last_chr}) >= ($pos - 1 + 4) ){
$tetra_nt = substr ($chromosomes{$last_chr},($pos-1),4);
}
else{
$tetra_nt = '';
}
if ( length($chromosomes{$last_chr}) >= ($pos - 1 + 5) ){
$penta_nt = substr ($chromosomes{$last_chr},($pos-1),5);
}
else{
$penta_nt = '';
}
}
# Extended this to any run 28 April 2020
$upstream_context = substr ($chromosomes{$last_chr},($pos-2),3);
# warn "$1\t$upstream_context\n"; sleep(1);
$strand = '+';
}
elsif ($1 eq 'G'){ # C on reverse strand
if ($pos-3 < 0) { # VB 28 09 2017 ; also, it would be more efficient to put this out of the loop...
$tri_nt = substr ($chromosomes{$last_chr},0,$pos);
}
else{
$tri_nt = substr ($chromosomes{$last_chr},($pos-3),3); # positions are 0-based!
}
$tri_nt = reverse $tri_nt;
$tri_nt =~ tr/ACTG/TGAC/;
if ($tetra){
if ( $pos - 4 >= 0 ){
$tetra_nt = substr ($chromosomes{$last_chr},($pos-4),4);
$tetra_nt = reverse $tetra_nt;
$tetra_nt =~ tr/ACTG/TGAC/;
}
else{
$tetra_nt = '';
}
if ( $pos - 5 >= 0 ){
$penta_nt = substr ($chromosomes{$last_chr},($pos-5),5);
$penta_nt = reverse $penta_nt;
$penta_nt =~ tr/ACTG/TGAC/;
}
else{
$penta_nt = '';
}
}
# Extended this to any run 28 April 2020
$upstream_context = substr ($chromosomes{$last_chr},($pos-2),3);
$upstream_context = reverse $upstream_context;
$upstream_context =~ tr/ACTG/TGAC/;
# warn "$1\t$upstream_context\n"; sleep(1);
$strand = '-';
}
next if (length$tri_nt < 3); # trinucleotide sequence could not be extracted
### If the very last position is a C in CpG context on the bottom strand we need to exclude it because its top strand equivalent
### will have been rejected due to insufficient length for $tri_nt
if ( (length($chromosomes{$last_chr}) - $pos) == 0){
next;
}
# if (length$penta_nt < 5){
# warn "$tri_nt\t$tetra_nt\t$penta_nt\n"; sleep(1);
# }
if (exists $chr{$last_chr}->{($pos)}){ # stored positions are 1-based! (as of v0.9.1)
$meth = $chr{$last_chr}->{$pos}->{meth};
$nonmeth = $chr{$last_chr}->{$pos}->{nonmeth};
}
# added this on 28 June 2019
next unless ($meth + $nonmeth >= $threshold); # if the position was not covered well enough it won't be reported
### determining cytosine context
if ($tri_nt =~ /^CG/){
$context = 'CG';
}
elsif ($tri_nt =~ /^C.{1}G$/){
$context = 'CHG';
}
elsif ($tri_nt =~ /^C.{2}$/){
$context = 'CHH';
}
else{ # if the context can't be determined the positions will not be printed (it will equally not have been reported by Bismark)
warn "The sequence context could not be determined (found: '$tri_nt'). Skipping.\n";
next;
}
# warn "Context: $context\tTRI-cont: $tri_nt\tUpstream: $upstream_context\n"; sleep(1);
# this is merely for reporting # Added 25 March 2020
context_reporting($tri_nt, $upstream_context, $meth, $nonmeth);
# warn "$tri_nt, $upstream_context, $meth, $nonmeth\n"; sleep(1);
if ($CpG_only){
if ($tri_nt =~ /^CG/){ # CpG context is the default
if ($nome){ # NOMe-Seq is CpG context only
if ( ($upstream_context eq 'ACG') or ($upstream_context eq 'TCG') ){
# fine
}
else{
next; # skipping this base
}
}
if ($zero){ # zero based coordinates
$pos -= 1;
if ($tetra){
print CYT join ("\t",$last_chr,$pos,$strand,$meth,$nonmeth,$context,$tri_nt,$tetra_nt,$penta_nt),"\n";
}
else{
if ($nome){ # added 20 Sept 2017
my $percentage = sprintf ("%.6f",$meth/ ($meth + $nonmeth) *100);
print CYT join ("\t",$last_chr,$pos,$strand,$meth,$nonmeth,$context,$tri_nt),"\n";
print CYTCOV join ("\t",$last_chr,$pos,$pos,$percentage,$meth,$nonmeth),"\n";
}
else{
print CYT join ("\t",$last_chr,$pos,$strand,$meth,$nonmeth,$context,$tri_nt),"\n";
}
}
}
else{ # default 1-based coordinates
if ($tetra){
print CYT join ("\t",$last_chr,$pos,$strand,$meth,$nonmeth,$context,$tri_nt,$tetra_nt,$penta_nt),"\n";
}
else{
if ($nome){ # added 20 Sept 2017
my $percentage = sprintf ("%.6f",$meth/ ($meth + $nonmeth) *100);
print CYT join ("\t",$last_chr,$pos,$strand,$meth,$nonmeth,$context,$tri_nt),"\n";
print CYTCOV join ("\t",$last_chr,$pos,$pos,$percentage,$meth,$nonmeth),"\n";
}
else{
print CYT join ("\t",$last_chr,$pos,$strand,$meth,$nonmeth,$context,$tri_nt),"\n";
}
}
}
}
}
else{ ## all cytosines, specified with --CX
if ($zero){ # zero based coordinates
$pos -= 1;
if ($tetra){
print CYT join ("\t",$last_chr,$pos,$strand,$meth,$nonmeth,$context,$tri_nt,$tetra_nt,$penta_nt),"\n";
}
else{
print CYT join ("\t",$last_chr,$pos,$strand,$meth,$nonmeth,$context,$tri_nt),"\n"
}
}
else{ # default
if ($tetra){
print CYT join ("\t",$last_chr,$pos,$strand,$meth,$nonmeth,$context,$tri_nt,$tetra_nt,$penta_nt),"\n";
}
else{
print CYT join ("\t",$last_chr,$pos,$strand,$meth,$nonmeth,$context,$tri_nt),"\n";
}
}
}
}
%chr = (); # resetting the hash
# new first entry
$last_chr = $chr;
$chr{$chr}->{$start}->{meth} = $meth;
$chr{$chr}->{$start}->{nonmeth} = $nonmeth;
if ($split_by_chromosome and $current_out_chr ne $last_chr){
# closing old filehandle(s)
close CYT or warn $!;
if ($nome){
close CYTCOV or warn $!;
}
# opening new filehandle
$current_out_chr = handle_filehandles($last_chr);
}
}
}
# Last found chromosome
# If there never was a last chromosome then something must have gone wrong with reading the data in
unless (defined $last_chr){
die "No last chromosome was defined, something must have gone wrong while reading the data in (e.g. specified wrong file path for a gzipped coverage file?). Please check your command!\n\n";
}
warn "Writing cytosine report for last chromosome $last_chr (stored ",scalar keys %{$chr{$last_chr}}," different covered positions)\n";
$processed{$last_chr} = 1;
my $tri_nt;
my $tetra_nt;
my $penta_nt;
my $context;
my $upstream_context;
while ( $chromosomes{$last_chr} =~ /([CG])/g){
$tri_nt = ''; # clearing
$context = '';
if ($tetra){
$tetra_nt = '';
$penta_nt = '';
}
$upstream_context = ''; # clearing
my $pos = pos$chromosomes{$last_chr};
my $strand;
my $meth = 0;
my $nonmeth = 0;
if ($1 eq 'C'){ # C on forward strand
$tri_nt = substr ($chromosomes{$last_chr},($pos-1),3); # positions are 0-based!
$strand = '+';
if ($tetra){
if ( length($chromosomes{$last_chr}) >= ($pos - 1 + 4) ){
$tetra_nt = substr ($chromosomes{$last_chr},($pos-1),4);
}
else{
$tetra_nt = '';
}
if ( length($chromosomes{$last_chr}) >= ($pos - 1 + 5) ){
$penta_nt = substr ($chromosomes{$last_chr},($pos-1),5);
}
else{
$penta_nt = '';
}
}
# 28 April 2020: using this metric for any context
$upstream_context = substr ($chromosomes{$last_chr},($pos-2),3);
# warn "$1\t$upstream_context\n"; sleep(1);
}
elsif ($1 eq 'G'){ # C on reverse strand
if ($pos-3 < 0) { # VB: 28 09 2017
$tri_nt = substr ($chromosomes{$last_chr},0,$pos);
}
else{
$tri_nt = substr ($chromosomes{$last_chr},($pos-3),3); # positions are 0-based!
}
$tri_nt = reverse $tri_nt;
$tri_nt =~ tr/ACTG/TGAC/;
$strand = '-';
if ($tetra){
if ( $pos - 4 >= 0 ){
$tetra_nt = substr ($chromosomes{$last_chr},($pos-4),4);
$tetra_nt = reverse $tetra_nt;
$tetra_nt =~ tr/ACTG/TGAC/;
}
else{
$tetra_nt = '';
}
if ( $pos - 5 >= 0 ){
$penta_nt = substr ($chromosomes{$last_chr},($pos-5),5);
$penta_nt = reverse $penta_nt;
$penta_nt =~ tr/ACTG/TGAC/;
}
else{
$penta_nt = '';
}
}
# 28 April 2020: using this metric for any context
$upstream_context = substr ($chromosomes{$last_chr},($pos-2),3);
$upstream_context = reverse $upstream_context;
$upstream_context =~ tr/ACTG/TGAC/;
# warn "$1\t$upstream_context\n"; sleep(1);
}
if (exists $chr{$last_chr}->{($pos)}){ # stored positions are 1-based! as of v0.9.1
$meth = $chr{$last_chr}->{$pos}->{meth};
$nonmeth = $chr{$last_chr}->{$pos}->{nonmeth};
}
# added this on 28 June 2019
next unless ($meth + $nonmeth >= $threshold); # if the position was not covered well enough it won't be reported
next if (length$tri_nt < 3); # trinucleotide sequence could not be extracted
### If the very last position is a C in CpG context on the bottom strand we need to exclude it because its top strand equivalent
### will have been rejected due to insufficient length for $tri_nt
if ( (length($chromosomes{$last_chr}) - $pos) == 0){
next;
}
# if (length$penta_nt < 5){
# warn "$tri_nt\t$tetra_nt\t$penta_nt\n"; sleep(1);
# }
### determining cytosine context
if ($tri_nt =~ /^CG/){
$context = 'CG';
}
elsif ($tri_nt =~ /^C.{1}G$/){
$context = 'CHG';
}
elsif ($tri_nt =~ /^C.{2}$/){
$context = 'CHH';
}
else{ # if the context can't be determined the positions will not be printed (it will equally not have been reported by Bismark)
warn "The cytosine context could not be determined (found: '$tri_nt'). Skipping.\n";
next;
}
# this is merely for reporting # Added 25 March 2020, modified 28 April 2020
context_reporting($tri_nt, $upstream_context, $meth, $nonmeth);
# warn ("$tri_nt, $upstream_context, $meth, $nonmeth\n"); sleep(1);
if ($CpG_only){
if ($tri_nt =~ /^CG/){ # CpG context is the default
if ($nome){
if ( ($upstream_context eq 'ACG') or ($upstream_context eq 'TCG') ){
# fine
}
else{
next; # skipping this base
}
}
if ($zero){ # zero-based coordinates
$pos -= 1;
if ($tetra){
print CYT join ("\t",$last_chr,$pos,$strand,$meth,$nonmeth,$context,$tri_nt,$tetra_nt,$penta_nt),"\n";
}
else{
if ($nome){ # added 20 Sept 2017
my $percentage = sprintf ("%.6f",$meth/ ($meth + $nonmeth) *100);
print CYT join ("\t",$last_chr,$pos,$strand,$meth,$nonmeth,$context,$tri_nt),"\n";
print CYTCOV join ("\t",$last_chr,$pos,$pos,$percentage,$meth,$nonmeth),"\n";
}
else{
print CYT join ("\t",$last_chr,$pos,$strand,$meth,$nonmeth,$context,$tri_nt),"\n";
}
}
}
else{ # default
if ($tetra){
print CYT join ("\t",$last_chr,$pos,$strand,$meth,$nonmeth,$context,$tri_nt,$tetra_nt,$penta_nt),"\n";
}
else{
if ($nome){ # added 20 Sept 2017
my $percentage = sprintf ("%.6f",$meth/ ($meth + $nonmeth) *100);
print CYT join ("\t",$last_chr,$pos,$strand,$meth,$nonmeth,$context,$tri_nt),"\n";
print CYTCOV join ("\t",$last_chr,$pos,$pos,$percentage,$meth,$nonmeth),"\n";
}
else{
print CYT join ("\t",$last_chr,$pos,$strand,$meth,$nonmeth,$context,$tri_nt),"\n";
}
}
}
}
}
else{ ## all cytosines, specified with --CX
if ($zero){ # zero based coordinates
$pos -= 1;
if ($tetra){
print CYT join ("\t",$last_chr,$pos,$strand,$meth,$nonmeth,$context,$tri_nt,$tetra_nt,$penta_nt),"\n";
}
else{
print CYT join ("\t",$last_chr,$pos,$strand,$meth,$nonmeth,$context,$tri_nt),"\n";
}
}
else{ # default
if ($tetra){
print CYT join ("\t",$last_chr,$pos,$strand,$meth,$nonmeth,$context,$tri_nt,$tetra_nt,$penta_nt),"\n";
}
else{
print CYT join ("\t",$last_chr,$pos,$strand,$meth,$nonmeth,$context,$tri_nt),"\n";
}
}
}
}
if ($nome){
warn "Finished writing out NOMe-Seq specific cytosine report for covered chromosomes (only reporting CGs in ACG and TCG context; processed $number_processed chromosomes/scaffolds in total)\n\n";
}
else{
warn "Finished writing out cytosine report for covered chromosomes (processed $number_processed chromosomes/scaffolds in total)\n\n";
}
if ($split_by_chromosome){
close CYT or warn $!;
if ($nome){
close CYTCOV or warn $!;
}
}
### Now processing chromosomes that were not covered in the coverage file
if($nome){
# 22 Sepember update: We have changed the NOMe-Seq processing process so that only positions that are
# actually covered are getting reported, both for the CpG report as well as for the coverage file
warn "NOMe-Seq processing only reports covered positions, so chromosomes that were not covered by any methylation calls in the coverage file are simply skipped...\nGenome-wide cytosine report processing complete\n\n";
}
elsif($threshold > 0){
warn "Coverage threshold was set to >$threshold<, so chromosomes that were not covered by any methylation calls in the coverage file are simply skipped...\nGenome-wide cytosine report processing complete\n\n";
}
else{
warn "Now processing chromosomes that were not covered by any methylation calls in the coverage file...\n";
my $unprocessed = 0;
foreach my $chr (sort keys %processed) {
unless ( $processed{$chr} ) {
++$unprocessed;
++$number_processed;
process_unprocessed_chromosomes($chr);
}
}
if ($unprocessed == 0) {
warn "All chromosomes in the genome were covered by at least some reads. coverage2cytosine processing complete.\n\n";
}
else{
warn "Finished writing out cytosine report (processed $number_processed chromosomes/scaffolds in total). coverage2cytosine processing complete.\n\n";
}
}
unless ($split_by_chromosome){
close CYT or warn $!;
if ($nome){
close CYTCOV or warn $!;
}
}
}
#### GC CONTEXT - optional
####
sub generate_GC_context_report {
warn "="x82,"\n";
warn "Methylation information for GC context will now be written to a GpC-context report\n";
warn "="x82,"\n\n";
warn "For the GC report, positions need to have coverage of at least 1 call. The threshold currently is: $threshold\n";
if ($threshold == 0){
warn "Setting threshold to 1\n";
$threshold = 1;
}
sleep (2);
my $number_processed = 0;
my $current_out_chr = '';
### changing to the output directory again
# unless ($output_dir eq ''){ # default
# chdir $output_dir or die "Failed to change directory to $output_dir\n";
# # warn "Changed directory to $output_dir\n";
# }
my $in = shift;
if ($in =~ /gz$/){
open (IN,"gunzip -c $in |") or die "Failed to read from gzipped file $in: $!\n";
}
else{
open (IN,"$in") or die "Failed to read from file $in: $!\n";
}
### for NOMe-Seq (nucleosome occupancy and methylome sequencing) we limit the reporting of
# 1. CpGs to A-C-G and T-C-G
# 2. GpC report files / cov files that only include G-C-A, G-C-C and G-C-T
# Local function to handle file names and options, similar to function in generate_genome_wide_cytosine_report().
# Assume $cytosine_out has been cleaned from unwanted suffixes
# First arg is optional chromosome number. Takes $cytosine_out, $split_by_chromosome, $nome, $gzip from outer scope.
my $filehandles_func = sub {
my $my_chr = shift;
if (defined $my_chr){
# warn "working on chromosome $my_chr in --split_by_chromosome mode\n"; sleep(3);
}
my $partial_name = $cytosine_out;
$partial_name =~ s/$/.chr${my_chr}/ if (defined $my_chr and $split_by_chromosome);
$partial_name .= '.NOMe' if ($nome);
my $gc_out = $partial_name.'.GpC_report.txt';
my $gc_cov = $partial_name.'.GpC.cov';
if ($gzip) {
$gc_out .= '.gz';
$gc_cov .= '.gz';
open (GC, "| gzip -c - > ${output_dir}$gc_out") or die "Failed to write to GpC file ${output_dir}$gc_out: !\n\n";
open (GCCOV, "| gzip -c - > ${output_dir}$gc_cov") or die "Failed to write to GpC coverage file ${output_dir}$gc_cov: !\n\n";
}
else {
open (GC, '>', "${output_dir}$gc_out") or die "Failed to write to GpC file ${output_dir}$gc_out: !\n\n";
open (GCCOV, '>', "${output_dir}$gc_cov") or die "Failed to write to GpC coverage file ${output_dir}$gc_cov: !\n\n";
}
warn ">>> Writing genome-wide GpC cytosine report to: $gc_out <<<\n";
warn ">>> Writing genome-wide GpC coverage file to: $gc_cov <<<\n\n";
return(defined $my_chr ? $my_chr : '');
};
$current_out_chr = ${filehandles_func}->() unless ($split_by_chromosome); ### writing all output to a single file (default)
my $last_chr;
my %chr; # storing reads for one chromosome at a time
my $count = 0;
while (<IN>){
chomp;
++$count;
my ($chr,$start,$end,undef,$meth,$nonmeth) = (split /\t/);
# defining the first chromosome
unless (defined $last_chr){
$last_chr = $chr;
++$number_processed;
warn "Storing all covered cytosine positions for chromosome: $chr\n";
if ($split_by_chromosome){
$current_out_chr = ${filehandles_func}->($chr);
}
}
### start positions are 1-based
if ($chr eq $last_chr){
$chr{$chr}->{$start}->{meth} = $meth;
$chr{$chr}->{$start}->{nonmeth} = $nonmeth;
}
else{
warn "Writing cytosine report for chromosome $last_chr (stored ",scalar keys %{$chr{$last_chr}}," different covered positions)\n";
++$number_processed;
$processed{$last_chr} = 1;
my $enough = 0;
while ( $chromosomes{$last_chr} =~ /(GC)/g){
# a GC on the top strand automatically means that there is a GC on the bottom strand as well, so we can process both at the same time
my $context_top = '';
my $context_bottom = '';
my $pos = pos$chromosomes{$last_chr};
my $meth_top = 0;
my $meth_bottom = 0;
my $nonmeth_top = 0;
my $nonmeth_bottom = 0;
#warn "$1\n"; sleep(1);
# C on forward strand
my $tri_nt_top = substr ($chromosomes{$last_chr},($pos-1),3); # positions are 0-based!
my $strand_top = '+';
# C on reverse strand
my $tri_nt_bottom = substr ($chromosomes{$last_chr},($pos-4),3); # positions are 0-based!
$tri_nt_bottom = reverse $tri_nt_bottom;
$tri_nt_bottom =~ tr/ACTG/TGAC/;
my $strand_bottom = '-';
next if (length $tri_nt_top < 3); # trinucleotide sequence could not be extracted for the top strand
next if (length $tri_nt_bottom < 3); # trinucleotide sequence could not be extracted for the reverse strand
# top strand
if (exists $chr{$last_chr}->{($pos)}){ # stored positions are 1-based!
$meth_top = $chr{$last_chr}->{$pos}->{meth};
$nonmeth_top = $chr{$last_chr}->{$pos}->{nonmeth};
}
# bottom strand
if (exists $chr{$last_chr}->{($pos-1)}){ # stored positions are 1-based! -1 for bottom strand Cs
$meth_bottom = $chr{$last_chr}->{$pos-1}->{meth};
$nonmeth_bottom = $chr{$last_chr}->{$pos-1}->{nonmeth};
}
### determining cytosine context top strand
if ($tri_nt_top =~ /^CG/){
$context_top = 'CG';
}
elsif ($tri_nt_top =~ /^C.{1}G$/){
$context_top = 'CHG';
}
elsif ($tri_nt_top =~ /^C.{2}$/){
$context_top = 'CHH';
}
else{ # if the context can't be determined the positions will not be printed (it will equally not have been reported by Bismark)
warn "The sequence context could not be determined for the top strand (found: '$tri_nt_top'). Skipping.\n";
next;
}
### determining cytosine context bottom strand
if ($tri_nt_bottom =~ /^CG/){
$context_bottom = 'CG';
}
elsif ($tri_nt_bottom =~ /^C.{1}G$/){
$context_bottom = 'CHG';
}
elsif ($tri_nt_bottom =~ /^C.{2}$/){
$context_bottom = 'CHH';
}
else{ # if the context can't be determined the positions will not be printed
warn "The sequence context could not be determined for the bottom strand (found: '$tri_nt_bottom'). Skipping.\n";
next;
}
# if Cs were not covered at all they are not written out
if ($meth_bottom + $nonmeth_bottom >= $threshold){
my $percentage = sprintf ("%.6f",$meth_bottom/ ($meth_bottom + $nonmeth_bottom) *100);
if ($nome and ($context_bottom eq 'CG') ){
# not reporting these (see point 2. above)
# print join ("\t",$last_chr,$pos-1,$strand_bottom,$meth_bottom,$nonmeth_bottom,$context_bottom,$tri_nt_bottom)," (skipping)\n";sleep(1);
}
else{
print GCCOV join ("\t",$last_chr,$pos-1,$pos-1,$percentage,$meth_bottom,$nonmeth_bottom),"\n";
print GC join ("\t",$last_chr,$pos-1,$strand_bottom,$meth_bottom,$nonmeth_bottom,$context_bottom,$tri_nt_bottom),"\n";
}
}
if ($meth_top + $nonmeth_top >= $threshold){
my $percentage = sprintf ("%.6f",$meth_top/ ($meth_top + $nonmeth_top) *100);
if ($nome and ($context_top eq 'CG') ){
# not reporting these (see point 2. above)
# print join ("\t",$last_chr,$pos,$strand_top,$meth_top,$nonmeth_top,$context_top,$tri_nt_top),"\n"; sleep(1);
}
else{
print GCCOV join ("\t",$last_chr,$pos,$pos,$percentage,$meth_top,$nonmeth_top),"\n";
print GC join ("\t",$last_chr,$pos,$strand_top,$meth_top,$nonmeth_top,$context_top,$tri_nt_top),"\n";
}
}
}
%chr = (); # resetting the hash
# new first entry
$last_chr = $chr;
$chr{$chr}->{$start}->{meth} = $meth;
$chr{$chr}->{$start}->{nonmeth} = $nonmeth;
if ($split_by_chromosome and $current_out_chr ne $last_chr){
# closing old filehandle(s)
close GC or warn $!;
if ($nome){
close GCCOV or warn $!;
}
# opening new filehandle
$current_out_chr = ${filehandles_func}->($last_chr);
}
}
}
# Last found chromosome
warn "Writing cytosine GpC report for last chromosome $last_chr (stored ",scalar keys %{$chr{$last_chr}}," different covered positions)\n";
$processed{$last_chr} = 1;
while ( $chromosomes{$last_chr} =~ /(GC)/g){
# a GC on the top strand automatically means that there is a GC on the bottom strand as well, so we can process both at the same time
my $context_top = '';
my $context_bottom = '';
my $pos = pos$chromosomes{$last_chr};
my $meth_top = 0;
my $meth_bottom = 0;
my $nonmeth_top = 0;
my $nonmeth_bottom = 0;
# C on forward strand
my $tri_nt_top = substr ($chromosomes{$last_chr},($pos-1),3); # positions are 0-based!
my $strand_top = '+';
# C on reverse strand
my $tri_nt_bottom = substr ($chromosomes{$last_chr},($pos-4),3); # positions are 0-based!
$tri_nt_bottom = reverse $tri_nt_bottom;
$tri_nt_bottom =~ tr/ACTG/TGAC/;
my $strand_bottom = '-';
next if (length $tri_nt_top < 3); # trinucleotide sequence could not be extracted for the top strand
next if (length $tri_nt_bottom < 3); # trinucleotide sequence could not be extracted for the bottom strand
### determining cytosine context top strand
if ($tri_nt_top =~ /^CG/){
$context_top = 'CG';
}
elsif ($tri_nt_top =~ /^C.{1}G$/){
$context_top = 'CHG';
}
elsif ($tri_nt_top =~ /^C.{2}$/){
$context_top = 'CHH';
}
else{ # if the context can't be determined the positions will not be printed
warn "The sequence context could not be determined for the top strand (found: '$tri_nt_top'). Skipping.\n";
next;
}
### determining cytosine context bottom strand
if ($tri_nt_bottom =~ /^CG/){
$context_bottom = 'CG';
}
elsif ($tri_nt_bottom =~ /^C.{1}G$/){
$context_bottom = 'CHG';
}
elsif ($tri_nt_bottom =~ /^C.{2}$/){
$context_bottom = 'CHH';
}
else{ # if the context can't be determined the positions will not be printed
warn "The sequence context could not be determined for the bottom strand (found: '$tri_nt_bottom'). Skipping.\n";
next;
}
# top strand
if (exists $chr{$last_chr}->{($pos)}){ # stored positions are 1-based!
$meth_top = $chr{$last_chr}->{$pos}->{meth};
$nonmeth_top = $chr{$last_chr}->{$pos}->{nonmeth};
}
# bottom strand
if (exists $chr{$last_chr}->{($pos-1)}){ # stored positions are 1-based! -1 for bottom strand Cs
$meth_bottom = $chr{$last_chr}->{$pos-1}->{meth};
$nonmeth_bottom = $chr{$last_chr}->{$pos-1}->{nonmeth};
}
# if Cs were not covered at all they are not written out
if ($meth_bottom + $nonmeth_bottom >= $threshold){
# warn ("methylation bottom strand: $meth_bottom\nnon-methylation bottom strand: $nonmeth_bottom\nThreshold: $threshold\n\n"); sleep (1);
my $percentage = sprintf ("%.6f",$meth_bottom/ ($meth_bottom + $nonmeth_bottom) *100);
if ($nome and ($context_bottom eq 'CG') ){
# not reporting these (see point 2. above)
# print join ("\t",$last_chr,$pos-1,$strand_bottom,$meth_bottom,$nonmeth_bottom,$context_bottom,$tri_nt_bottom)," (skipping)\n";
}
else{
$current_out_chr = ${filehandles_func}->($last_chr) if ($split_by_chromosome and $current_out_chr ne $last_chr);
print GCCOV join ("\t",$last_chr,$pos-1,$pos-1,$percentage,$meth_bottom,$nonmeth_bottom),"\n";
print GC join ("\t",$last_chr,$pos-1,$strand_bottom,$meth_bottom,$nonmeth_bottom,$context_bottom,$tri_nt_bottom),"\n";