-
Notifications
You must be signed in to change notification settings - Fork 0
/
damidseq_pipeline
executable file
·1532 lines (1249 loc) · 41.5 KB
/
damidseq_pipeline
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/perl -w
# Copyright © 2013-17, Owen Marshall
# 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 2 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
use strict;
use File::Copy;
use File::Basename;
use IPC::Cmd qw[can_run run];
use 5.010;
$|++;
my $version = "1.4.4";
print STDERR "\ndamidseq_pipeline v$version\nCopyright 2013-17, Owen Marshall\n\n";
# Global options
my %vars = (
'bowtie' => 1,
'bamfiles' => 0,
'extend_reads' => 1,
'extension_method' => 'gatc',
'len' => 300,
'q' => 30,
'bowtie2_path' => '',
'samtools_path' => '',
'bedtools_path' => '',
'gatc_frag_file' => '',
'kde_plot' => 0,
'bowtie2_genome_dir' => '',
'threads' => 7,
'full_data_files' => 0,
'qscore1min' => 0.4,
'qscore1max' => 1.0,
'qscore2max' => 0.9,
'norm_override'=> 0,
'output_format'=>'bedgraph',
'method_subtract' => 0,
'pseudocounts' => 0,
'ps_factor' => 10,
'min_norm_value' => -5,
'max_norm_value' => 5,
'norm_steps' => 300,
'just_align' => 0,
'norm_method' => 'kde',
'save_defaults' => 0,
'load_defaults' => '',
'reset_defaults' => 0,
'bins' => '75',
#'filter' => 0,
'dam' => '',
'out_name' => '',
'no_file_filters' => '',
'keep_sam' => 0,
'only_sam' => 0
);
my %vars_details = (
'bowtie' => 'Perform bowtie2 alignment [1/0]',
'bamfiles' => 'Only process BAM files',
'extend_reads' => 'Perform read extension [1/0]',
'extension_method' => "Read extension method to use; options are:\n\rfull: Method used by version 1.3 and earlier. Extends all reads to the value set with --len.\n\rgatc: Default for version 1.4 and above. Extends reads to --len or to the next GATC site, whichever is shorter. Using this option increases peak resolution.",
'len' => 'Length to extend reads to',
'q' => 'Cutoff average Q score for aligned reads',
'bowtie2_path' => 'path to bowtie2 executable (leave blank if in path)',
'samtools_path' => 'path to samtools executable (leave blank if in path)',
'bedtools_path' => 'path to BEDTools executable (leave blank if in path)',
'gatc_frag_file' => 'GFF file containing all instances of the sequence GATC',
'kde_plot' => 'create an Rplot of the kernel density fit for normalisation (requires R)',
'bowtie2_genome_dir' => 'Directory and basename for bowtie2 .bt2 indices',
'threads' => 'threads for bowtie2 to use',
'full_data_files' => 'Output full binned ratio files (not only GATC array)',
'qscore1min' => 'min decile for normalising from Dam array',
'qscore1max' => 'max decile for normalising from Dam array',
'qscore2max' => 'max decile for normalising from fusion-protein array',
'norm_override'=> 'Normalise by this amount instead',
'output_format' => 'Output tracks in this format [gff/bedgraph]',
'method_subtract' => 'Output values are (Dam_fusion - Dam) instead of log2(Dam_fusion/Dam) (not recommended)',
'pseudocounts' => 'Add this value of psuedocounts instead (default: optimal number of pseudocounts determined algorithmically)',
'ps_factor' => 'Value of c in c*(reads/bins) formula for calculating pseudocounts (default = 10)',
'min_norm_value' => 'Minimum log2 value to limit normalisation search at (default = -5)',
'max_norm_value' => 'Maximum log2 value to limit normalisation search at (default = +5)',
'norm_steps' => 'Number of points in normalisation routine (default = 300)',
'just_align' => 'Just align the FASTQ files, generate BAM files, and exit',
'norm_method' => "Normalisation method to use; options are:\n\rkde: use kernel density estimation of log2 GATC fragment ratio (default)\n\rrpm: use readcounts per million reads (not recommended for most use cases)",
'save_defaults' => "Save runtime parameters as default\n\r(provide a name to differentiate different genomes -- these can be loaded with 'load_defaults')",
'load_defaults' => "Load this saved set of defaults\n\r(use 'list' to list current saved options)",
'reset_defaults' => 'Delete user-defined parameters',
'bins' => 'Width of bins to use for mapping reads',
#'filter' => 'Apply filtering to fastq files before alignment and processing',
'dam' => 'Specify file to use as Dam control',
'out_name' => 'Use this as the fusion-protein name when saving the final ratio',
'no_file_filters' => 'Do not trim filenames for output',
'keep_sam' => 'Do not delete .sam file',
'only_sam' => 'Do not generate bam file'
);
my @vars_unsaved = (
'save_defaults',
'reset_defaults',
'load_defaults',
'dam',
'out_name'
);
# Global variables
my @gatc_simple;
my @cli;
my @in_files;
my %ampnorm;
my %files;
my %index;
my %ar;
my %array;
my %bowtie_output;
my %gatc;
my %gatc_reverse_hash;
my %gatc_chr;
my %gatc_frags;
my %gatc_frag_score;
my %gatc_index;
my %prot_hash;
my %norm_factors;
my %seg;
my %full_tracks;
my %counts;
my %bins;
my $HOME = (getpwuid($<))[7];
my $pi = 3.1415926536;
my $gatc_fragments;
my $denom;
my $damname;
my $frags;
my $no_paths;
my $windows_file;
my $samtools_version;
# Read parameters if exist
process_cli(0);
read_defaults();
parameter_check();
process_cli(1);
# CLI processing
check_paths();
save_defaults();
# Log file
init_log_file();
# Read input files
process_input_files();
# Check executables are present in path
executable_check();
#############################
### Pipeline workflow
###
align_sequences();
load_gatc_frags() unless ($vars{'extension_method'} eq 'full' && $vars{'just_align'});
if ($vars{'extension_method'} eq 'full') {
extend_reads_full();
} else {
extend_reads_gatc();
}
calc_bins();
exit 0 if $vars{'just_align'};
if ($vars{'norm_method'} eq 'kde') {
find_quants();
find_norm_factor();
}
normalize();
generate_ratio();
printout("\nAll done.\n\n");
exit 0;
#############################
### Subroutines start here
###
sub check_paths {
# Check paths
if ($vars{'gatc_frag_file'} && !(-e "$vars{'gatc_frag_file'}")) {
print STDERR "WARTNING: --gatc_frag_file option specified but file does not appear to exist.\n";
if ($no_paths) {
print STDERR "*** not saving file paths automatically (use --save_defaults=1 to override)\n\n";
$no_paths=0;
}
exit 1;
}
if ($vars{'bowtie2_genome_dir'} && !(-e "$vars{'bowtie2_genome_dir'}.1.bt2")) {
print STDERR "WARTNING: --bowtie2_genome_dir option specified but files with basename does not appear to exist.\n\n(Please ensure you specify both the directory and the basename of the .bt2 index files -- i.e. if files are dmel_r5.57.1.bt2 dmel_r5.57.2.bt2 etc, located inside the directory Dm_r5.57, use '[path to]/Dm_r5.57/dmel_r5.57' as the option value ...\n\n";
if ($no_paths) {
print STDERR "*** not saving file paths automatically (use --save_defaults to override)\n\n";
$no_paths=0;
}
exit 1;
}
# Parameter checks:
for my $p ('gatc_frag_file','bowtie2_genome_dir') {
unless ($vars{$p}) {
die("Please use the --$p option to specifiy the $vars_details{$p} ...\n\n");
}
}
# Save file paths if they haven't been set before
if ($no_paths) {
print STDOUT "All external files correctly located. Paths will be saved as defaults and be used from now on.\n";
$vars{'save_defaults'}=1;
}
}
sub executable_check {
# Check for bowtie2 and samtools:
unless ($vars{"bamfiles"} || can_run("$vars{'bowtie2_path'}bowtie2")) {
printout("\nError: cannot find bowtie2 executable. Please install bowtie2 or specify the path to bowtie2 with --bowtie2_path.\n\n");
exit 1;
}
unless (can_run("$vars{'samtools_path'}samtools")) {
printout("\nError: cannot find samtools executable. Please install samtools or specify the path to samtools with --samtools_path.\n\n");
exit 1;
} else {
# find samtools version
my @temp = `$vars{'samtools_path'}samtools 2>&1`;
foreach (@temp) {
next unless my ($v) = /^version: (\d+\.\d+)/i;
$samtools_version = $v;
print LOG "\nUsing samtools version $v\n";
}
}
unless ($samtools_version) {
printout("\nWarning: samtools executable found but unable to determine the version. We'll assume it's v1.2 or greater and hope for the best ...\n");
$samtools_version = 1.2;
}
}
sub process_cli {
# CLI processing
my $order = shift;
foreach (@ARGV) {
if (/--(.*)=(.*)/) {
unless (defined($vars{$1})) {
print STDERR "Did not understand $_ ...\n";
help();
}
my ($v, $opt) = ($1,$2);
$opt =~ s/~/$HOME/;
$vars{$v} = $opt;
push @cli, "$v=$opt" if $order;
next;
} elsif (/--h[elp]*/) {
help() if $order;
} elsif (/--(.*)/) {
# if no parameter is specified we assume it's a switch ...
# (could be a bit nicer and check this is ok with a hash representing data type ...)
if (defined($vars{$1})) {
$vars{$1} = 1;
} else {
print STDERR "Did not understand $_ ...\n";
help();
}
push @cli, "$1" if $order;
next;
}
push @in_files, $_ if $order;
}
}
sub process_input_files {
# Check for user-specified dam control
if ($vars{'dam'}) {
push @in_files, $vars{'dam'}
}
# Get unique list of infiles
@in_files = uniq(@in_files);
# Index file
my $index_file = "index.txt";
# CLI files
# if no files specified, process all .gz files in directory.
unless (@in_files) {
@in_files = glob("*.fastq.gz");
@in_files = glob("*.gz") unless scalar(@in_files);
@in_files = glob("*.fastq") unless scalar(@in_files);
@in_files = glob("*.bam") unless scalar(@in_files);
if ($vars{'bamfiles'}) {
@in_files = glob("*.bam");
}
}
unless (@in_files) {
printout("ERROR: no FASTQ or BAM files found (and no files specified on the command-line).\n(Use --help to see command-line options ...)\n\n");
exit 1;
}
printout("*** Reading data files ***\n");
my $index_txt_error = <<EOT;
The pipeline script requires a single tab-delimited file named index.txt that lists sequencing adaptors with sample names -- for e.g.:
A6 Dam
A12 polII
Adaptors are taken from the .fastq file name (e.g. the file name for the Dam sample above should contain 'A006') and do not need to match the actual adaptors used.
EOT
if ($vars{'bamfiles'}) {
# Bamfiles
foreach my $l (@in_files) {
my ($name,$dir,$ext) = fileparse($l, qr/\.[^.]*/);
next unless $ext =~ m/bam/;
$name =~ s/-ext\d+//; # remove extensions from the name
print STDOUT "$name\t$l\n";
$files{$name}[0]=$l;
check_dam_name($name, $l);
}
} elsif (@in_files && !(-e $index_file)) {
foreach my $l (@in_files) {
my ($name,$dir,$ext) = fileparse($l, qr/\.[^.]*/);
($name) = $name =~ m/(.*?)(_|-ext|\.)/i unless $vars{'no_file_filters'};
$vars{'bamfiles'} = 1 if $ext =~ /bam/;
if ($files{$name}) {
#same name already in use
my $i = 1;
while ($files{"$name.$i"}) {
$i++;
}
$name = "$name.$i";
}
print STDOUT "$name\t$l\n";
$files{$name}[0]=$l;
unless ($vars{'just_align'}) {
check_dam_name($name, $l);
}
}
} elsif (-e $index_file) {
open (NORM, "<$index_file") || die "Unable to open index file for reading: $!\n";
my @norm = <NORM>;
close NORM;
chomp(@norm);
printout("\nIndex\tName\n");
foreach my $l (@norm) {
next if $l =~ m/^$/; # skip new lines
next if $l =~ m/^#/; # skip comments
my ($i, $name) = split(/\s+/,$l);
unless (($name) && ($i =~ m/.*?(?:0*)+\d+/i)) {
die("\nERROR: misformatted index.txt file.\n\n$index_txt_error\n")
}
printout("$i\t$name\n");
my ($i_num) = ($i =~ m/.*?(?:0*)+(\d+)/i);
$index{$i_num}=$name;
}
printout("\n*** Matching adaptors ***\n");
foreach my $l (@in_files) {
print "$l\n";
## Change this next line's regexp to match your sequencing format (currently matches, e.g. "Index6" or "A006")
my ($i) = $l =~ m/.*?(?:index|a)(?:0*)(\d+)/i;
if ($index{$i}) {
printout("$index{$i}: Index $i\n");
$files{$index{$i}}[0]=$l;
unless ($vars{'just_align'}) {
if ($index{$i} =~ m/^dam/i) {
die("\nERROR: more than one Dam sample detected. Please only use one Dam control per run -- specify the files to process on the command-line\n\n") if $damname;
$damname = $index{$i}
}
}
} else {
die ("\nERROR: cannot find adaptor reference in fastq files.\n\n$index_txt_error\n");
}
}
} else {
help();
}
# Check that there's a Dam control sample ...
unless ($vars{'just_align'}) {
unless ($damname) {
printout("\nError: no Dam control sample detected!\nPlease use include a filename starting with 'Dam', or specify the Dam control file to use with the --dam=[filename] switch\n");
exit 1;
} else {
printout(" Using $damname as Dam control.\n") if $vars{'dam'};
}
}
# If we're only processing .bam files, we won't need to do an alignment or extend reads...
if ($vars{'bamfiles'}) {
$vars{'bowtie'} = 0;
$vars{'extend_reads'} = 0;
}
}
sub check_dam_name {
my ($name, $file) = @_;
if ($vars{'dam'}) {
$damname = $name if $vars{'dam'} eq $file;
} elsif ($name =~ m/^dam/i) {
die("\nERROR: more than one Dam sample detected. Please only use one Dam control per run -- specify the files to process on the command-line\n\n") if $damname;
$damname = $name;
}
}
sub read_defaults {
# Create config directory if it doesn't exist
unless (-d "$HOME/.config") {
mkdir("$HOME/.config");
}
unless (-d "$HOME/.config/damid_pipeline") {
mkdir("$HOME/.config/damid_pipeline");
}
# Migration for version 1.0
if (-e "$HOME/.config/damid_pipeline_defaults") {
move("$HOME/.config/damid_pipeline_defaults","$HOME/.config/damid_pipeline/defaults")
}
if ($vars{'load_defaults'}) {
if ($vars{'load_defaults'} eq 'list') {
print_defaults_files();
} else {
unless (-e "$HOME/.config/damid_pipeline/defaults.$vars{'load_defaults'}") {
print STDERR "Error: cannot find saved defaults file for '$vars{'load_defaults'}'\n\n";
print_defaults_files();
}
# load the defaults
print STDERR "Loading saved defaults for '$vars{'load_defaults'}' ...\n\n";
read_defaults_file("$HOME/.config/damid_pipeline/defaults.$vars{'load_defaults'}");
}
} elsif (-e "$HOME/.config/damid_pipeline/defaults") {
# read default parameters if exist
read_defaults_file("$HOME/.config/damid_pipeline/defaults");
}
}
sub print_defaults_files {
my @defaults_files = glob("$HOME/.config/damid_pipeline/defaults.*");
print STDOUT "Available defaults:\n";
if (@defaults_files) {
foreach (@defaults_files) {
my ($name) = m#$HOME/\.config/damid_pipeline/defaults\.(.*)$#;
print STDOUT " $name\n";
}
} else {
print STDOUT " No genome-specific defaults files found\n (Use --save_defaults=[name] to save them)\n";
}
print STDOUT "\n";
exit 0;
}
sub read_defaults_file {
my $file = shift;
open(DEFAULTS, "<$file") || die("Cannot open defaults file for writing: $!\n\n");
while (<DEFAULTS>) {
chomp;
my ($p,$v) = split;
$vars{$p} = $v;
}
close DEFAULTS;
}
sub save_defaults {
# Save parameters if requested
if ($vars{'save_defaults'}) {
my %donotsave = map {$_ => 1} @vars_unsaved;
my $name;
if ($vars{'save_defaults'} eq '1') {
$name = '';
} else {
$name = ".$vars{'save_defaults'}";
}
print STDERR "Writing defaults to file ...\n";
open(DEFAULTS,">$HOME/.config/damid_pipeline/defaults$name") || die("Cannot open defaults file for writing: $!\n\n");
for my $p (keys %vars) {
next if $donotsave{$p};
next unless $vars{$p};
print DEFAULTS "$p\t$vars{$p}\n";
}
print STDERR "Done.\n\n";
close DEFAULTS;
exit 0;
}
# reset defaults
if ($vars{'reset_defaults'}) {
my $name;
if ($vars{'reset_defaults'} eq '1') {
$name = '';
} else {
$name = ".$vars{'reset_defaults'}";
}
unlink("$HOME/.config/damid_pipeline/defaults$name") if -e "$HOME/.config/damid_pipeline/defaults$name";
print STDERR "Defaults reset ... please restart.\n\n";
exit 0;
}
}
sub parameter_check {
# Parameter check -- first run:
for my $p ('gatc_frag_file','bowtie2_genome_dir') {
unless ($vars{$p}) {
$no_paths = 1;
}
}
}
sub align_sequences {
if ($vars{'bowtie'}) {
printout("\n*** Aligning files with bowtie2 ***\n");
foreach my $fn (keys %files) {
my $pair1 = $files{$fn}[0];
printout("Now working on $fn ...\n");
if ($vars{'bowtie'}) {
$bowtie_output{$fn} = `$vars{'bowtie2_path'}bowtie2 -p $vars{'threads'} -x $vars{'bowtie2_genome_dir'} -U $pair1 -S $fn.sam 2>&1`;
unless ($bowtie_output{$fn}) {
printout("Error: no data returned from bowtie2. Exiting.\n\n");
exit 1;
}
printout("$bowtie_output{$fn}\n");
}
}
}
}
sub extend_reads_full {
# Extend reads
if ($vars{'extend_reads'}) {
printout("*** Extending reads to $vars{'len'} bases (full extension) ***\n");
foreach my $fn (keys %files) {
printout("Reading input file: $fn ...\n");
open (IN, "<$fn.sam") || die "Unable to read $fn: $!\n";
printout(" Processing data ...\n");
open (OUT, ">$fn-ext$vars{'len'}.sam");
my $c=0;
my $seqs;
while (<IN>) {
chomp;
my ($qname, $flag, $chr, $pos, $mapq, $cigar, $rnext, $pnext, $tlen, $seq, $qual) = split('\s+');
$c++;
unless ($c%100000) {
print " $c lines processed ...\r";
}
unless ($seq) {
print OUT "$_\n";
next;
}
next unless $mapq>=$vars{'q'};
$seqs++;
my $readlen;
foreach my $cig ($cigar =~ m/(\d+)[M|I|S|=|X]/g) {
$readlen += $cig;
}
$cigar="$vars{'len'}M";
if ($flag == 16) {
# minus strand
$pos -= $vars{'len'} - $readlen;
$pos = max(1,$pos);
}
$seq = "*"; # We're extending reads and we have no sequence information for the extension ...
$qual= "*"; # ... ditto for quality. Thankfully the SAMfile spec allows for no sequence or quality information.
print OUT join("\t", $qname, $flag, $chr, $pos, $mapq, $cigar, $rnext, $pnext, $tlen, $seq, $qual), "\n";
}
close IN;
close OUT;
# the original SAM files are huge, so we nuke them
unlink("$fn.sam") unless $vars{'keep_sam'};
printout(" Seqs extended (>q".$vars{'q'}.") = $seqs\n");
}
}
}
sub extend_reads_gatc {
# Extend reads
if ($vars{'extend_reads'}) {
printout("*** Extending reads up to $vars{'len'} bases ***\n");
foreach my $fn (keys %files) {
printout("Reading input file: $fn ...\n");
open (IN, "<$fn.sam") || die "Unable to read $fn: $!\n";
printout(" Processing data ...\n");
open (OUT, ">$fn-ext$vars{'len'}.sam");
my $c=0;
my $seqs;
my @non_chrs;
while (<IN>) {
if (/^\@/) {
print OUT;
next;
}
chomp;
my ($qname, $flag, $chr, $pos, $mapq, $cigar, $rnext, $pnext, $tlen, $seq, $qual) = split('\s+');
$c++;
unless ($c%100000) {
my $lp = sprintf("%0.2f",$c / 1000000);
print " $lp"."M lines processed ...\r";
}
next unless $seq;
next unless $mapq>=$vars{'q'};
unless ($gatc{$chr}) {
# We do the missing chromosome check here if we're extending to GATCs
push @non_chrs, $chr;
next;
}
$seqs++;
my $readlen;
foreach my $cig ($cigar =~ m/(\d+)[M|I|S|=|X]/g) {
$readlen += $cig;
}
$cigar="$vars{'len'}M";
# find next GATC after reads
# It takes far too long to grep an entire chromosome's worth of GATC fragments for GATC sites internal to the extension length. The following is an inelegant but very effective solution for speeding the process up: essentially, GATC fragments are binned into a hash when read in, and the hash is used as a lookup table. There may be issues with long extension lengths, but it's fairly versatile.
if ($flag == 16) {
### minus strand
my $fiveprime_search = $pos - ($vars{'len'} - $readlen);
my $threeprime_search = $pos;
my $fp_bin = int($fiveprime_search/200)+1;
my $tp_bin = int($threeprime_search/200)+2;
my $fp_index = $gatc_index{$chr}{$fp_bin} || $#{ $gatc{$chr}}-2;
my $tp_index = $gatc_index{$chr}{$tp_bin} || $#{ $gatc{$chr}}-2;
my @search_slice = @{ $gatc{$chr}}[$fp_index .. $tp_index];
my @hits = grep {$_ > $fiveprime_search && $_ < $threeprime_search} @search_slice;
if (@hits) {
# an intervening GATC
my $closest = (sort {$a <=> $b} @hits)[$#hits];
my $revised_len = int($pos+$readlen - $closest);
$cigar = $revised_len."M";
$pos = int($closest);
} else {
# no Great GATC
$pos -= int($vars{'len'} - $readlen);
$pos = max(1,$pos);
}
} else {
### plus strand
my $fiveprime_search = $pos + $readlen;
my $threeprime_search = $pos + $vars{'len'};
my $fp_bin = int($fiveprime_search/200)+1;
my $tp_bin = int($threeprime_search/200)+2;
my $fp_index = $gatc_index{$chr}{$fp_bin} || $#{ $gatc{$chr}}-2;
my $tp_index = $gatc_index{$chr}{$tp_bin} || $#{ $gatc{$chr}}-2;
my @search_slice = @{ $gatc{$chr}}[$fp_index .. $tp_index];
my @hits = grep {$_ > $fiveprime_search && $_ < $threeprime_search} @search_slice;
if (@hits) {
# an intervening GATC
my $closest = (sort {$a <=> $b} @hits)[0];
my $revised_len = int($closest - $pos);
$cigar = $revised_len."M";
} else {
# no Great GATC
$pos = max(1,$pos);
}
}
$seq = "*"; # We're extending reads and we have no sequence information for the extension ...
$qual= "*"; # ... ditto for quality. Thankfully the SAMfile spec allows for no sequence or quality information.
print OUT join("\t", $qname, $flag, $chr, $pos, $mapq, $cigar, $rnext, $pnext, $tlen, $seq, $qual), "\n";
}
close IN;
close OUT;
if (@non_chrs) {
my $missing = join("\n ", sort(uniq(@non_chrs)));
print STDERR " Warning: alignment contains chromosome identities not found in GATC file (see log file for details; this is normal if unmapped assemblies and the mitochondrial genome have been excluded from the GATC file.)\n";
print LOG " Warning: alignment contains chromosome identities not found in GATC file:\n $missing\n\n";
}
# the original SAM files are huge, so we nuke them
unlink("$fn.sam") unless $vars{'keep_sam'};
printout(" Seqs extended (>q".$vars{'q'}.") = $seqs\n\n");
}
}
}
sub calc_bins {
printout("*** Calculating bins ***");
foreach my $n (keys %files) {
my $fn = $vars{'bamfiles'} ? $files{$n}[0] :
$vars{'extend_reads'} ? "$n-ext$vars{'len'}" : $n;
$fn =~ s/\.bam$//;
printout("\nNow working on $fn ...\n");
unless ($vars{'bamfiles'}) {
printout("Generating .bam file ...\n");
`$vars{'samtools_path'}samtools view -Sb $fn.sam > $fn.unsort.bam`;
unlink("$fn.sam") unless $vars{'keep_sam'};
# sort the bam file ...
printout(" sorting ...\n");
if ($samtools_version < 1.3) {
`$vars{'samtools_path'}samtools sort $fn.unsort.bam $fn`;
} else {
`$vars{'samtools_path'}samtools sort -T . -o $fn.bam $fn.unsort.bam`;
}
unlink("$fn.unsort.bam");
}
# Obtain readcounts via samtools ...
my $seqs = `$vars{'samtools_path'}samtools view -c $fn.bam`;
chomp($seqs);
if ($seqs == 0) {
printout("Error: no reads obtained from bamfile ... exiting.\n\n");
exit 1;
}
$counts{$n}=$seqs;
printout(" $seqs reads\n");
# short-circuit for just_align option
next if $vars{'just_align'};
if ($n eq $damname) {
$denom = $counts{$n};
}
printout(" Generating bins from $fn.bam ...\n");
my %cov;
my %gff;
my %bases;
my $lines;
# We now manually calculate coverage, rather than using bedtools' -coverage option, for both memory considerations and ease of use.
# (bedtools' -coverage memory consumption is pretty crazy, getting up to 8Gb for ~25M reads ... this implementation uses about 1/10th of that memory.)
# Speed considerations are similar (this seems to be slightly faster ...)
open(COV, "$vars{'samtools_path'}samtools view -h $fn.bam |") || die ("Error: unable to open bamfile $!\n");
my $paired_flag = 0;
while (<COV>) {
chomp();
$lines++;
my ($qname, $flag, $chr, $pos, $mapq, $cigar, $rnext, $pnext, $tlen, $seq, $qual) = split(/\t/);
unless ($cigar) {
if (m/\@SQ\s+SN:([\d|\w]+)\s+LN:(\d+)/) {
# Grab chromosome sizes from BAM file
my ($chr, $size) = ($1, $2);
$bases{$chr} = $size;
}
next;
}
next if $cigar eq "*";
my ($pstart, $pend);
if ($pnext) {
# paired ends
$paired_flag = 1;
next unless $tlen && abs($tlen) < 1500;
next unless $rnext eq '=';
($pstart, $pend) = sort($pos, $pos + $tlen);
} else {
# single ends
my $readlen;
foreach my $cig ($cigar =~ m/(\d+)[M|I|S|=|X]/g) {
$readlen += $cig;
}
$pstart = $pos;
$pend = $pos+$readlen;
}
if ($lines % 20000 == 0) {
my $pc = sprintf("%0.1f", ($lines*100 / $counts{$n}));
print STDERR " $pc% processed ...\r"
}
# break into bins
my $start = int($pstart/$vars{'bins'});
my $end = int($pend/$vars{'bins'});
foreach my $bin ($start .. $end) {
$cov{$chr}{$bin*$vars{'bins'}}++;
}
}
close COV;
if ($paired_flag) {
printout(" Warning: paired-end reads detected. Support for paired-end reads is experimental ...\n Please report any bugs encountered at owenjm.github.io/damidseq_pipeline\n\n");
}
# sanity check on coverage
unless (keys(%cov)) {
printout(" Error: no coverage was found. Exiting ...\n\n");
exit 1;
}
# sanity check on chromosome names
unless ( map {my $t = $_; grep {$_ eq $t} keys(%cov)} keys(%gatc) ) {
if ( map {s/chr//gi; my $t = $_; grep {s/chr//gi; $_ eq $t} keys(%cov)} keys(%gatc) ) {
printout(" Warning: chromosome name mismatch detected -- removing 'chr' from definitions and continuing ...\n");
if (grep {m/chr/} keys %cov) {
my %new_cov;
@new_cov{ map {s/chr//; $_} keys %cov} = values %cov;
%cov = %new_cov;
my %new_bases;
@new_bases{ map {s/chr//; $_} keys %bases} = values %bases;
%bases = %new_bases;
} elsif (grep {m/chr/} keys %gatc) {
my %new_gatc;
@new_gatc{ map {s/chr//; $_} keys %gatc} = values %gatc;
%gatc = %new_gatc;
} else {
printout(" Error: can't find a 'chr' key definition in either hash (please contact the author for support)\n");
exit 1;
}
} else {
printout(" Error: chromsome definitions between bam and GATC file do not match!\n");
}
}
my $read_bins=0;
foreach my $chr (keys %cov) {
next unless $bases{$chr};
for (my $bin = 0; $bin < $bases{$chr}+$vars{'bins'}; $bin += $vars{'bins'}) {
# need to fill every bin ...
$read_bins++;
my $end = $bin+($vars{'bins'}-1);
my $score = $cov{$chr}{$bin} || 0;
push @{$gff{$chr}}, [$bin, $end, $score];
if ($vars{'full_data_files'}) {
$full_tracks{$chr}{$bin}{$n} = $score;
$full_tracks{$chr}{$bin}{'end'} = $end unless $full_tracks{$chr}{$bin}{'end'};
}
}
}
$bins{$n} = $read_bins;
my $gatc_nonhits = 0;
my $index = 0;
my @non_chrs;
printout(" Converting to GATC resolution ... \n");
foreach my $chr (keys %gff) {
unless ($gatc{$chr}) {
push @non_chrs, $chr;
next;
}
my $last_input=0;
foreach my $i (0 .. @{$gatc{$chr}}-2) {
$index++;
# Get two adjacent GATC sites
my ($mida) = @{$gatc{$chr}}[$i];
my ($midb) = @{$gatc{$chr}}[$i+1];
if ($index%100 == 0) {
my $pc = sprintf("%0.0f",($index*100)/$#gatc_simple);
print STDOUT " $pc\% processed ...\r";
}
my $sum;
my @data;
my $count;
# Run through the probe array to find the probes that lie within the fragment
foreach my $l ($last_input .. @{$gff{$chr}}-2) {
# Takes way too long to scan through the entire array for each GATC fragment, and is in theory unnecessary
# This proceedure uses $last_input to store the last probe found within an array, and start the next search from there
# (relies on an ordered array of data, hence the sorting above)
my ($start, $end, $score) = @{$gff{$chr}[$l]};
my ($startn, $endn, $scoren) = @{$gff{$chr}[$l+1]};
$last_input= ($l-1 > 0 ? $l-1 : 0);
if ($start > $midb) {
last;
}
next if $end < $mida;
if (($end > $mida) && ($start < $midb)) {
push @data, $score;
}
}
unless (@data) {
$gatc_nonhits++;
next;
}
my $mean = mean(@data);
push(@{$gatc_frags{"$chr-$mida-$midb"}}, $n);
$gatc_frag_score{"$chr-$mida-$midb"}{$n}=$mean;
$array{$chr}{$mida}{$n} = $mean;
$array{$chr}{$mida}{'end'} = $midb unless $array{$chr}{$mida}{'end'};
}
}
if (@non_chrs) {
my $missing = join(', ', @non_chrs);
print STDERR " Warning: alignment contains chromosome identities not found in GATC file (see log file for details; this is normal if unmapped assemblies and the mitochondrial genome have been excluded from the GATC file.)";
print LOG " Warning: alignment contains chromosome identities not found in GATC file:\n $missing\n";
}
printout("\n");
}
}
sub normalize {
printout("\n*** Normalising ***\n");