-
Notifications
You must be signed in to change notification settings - Fork 11
/
rf-count-genome
executable file
·1346 lines (913 loc) · 52.5 KB
/
rf-count-genome
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 strict;
use Config;
use Fcntl qw(SEEK_SET);
use File::Basename;
use File::Copy;
use File::Path qw(mkpath);
use File::Spec;
use FindBin qw($Bin);
use Fcntl qw(:flock SEEK_SET SEEK_END);
use Getopt::Long qw(:config no_ignore_case);
use lib $Bin . "/lib";
use Core::Utils;
use Core::Mathematics qw(:all);
use Core::Process::Queue;
use Core::Statistics;
use Data::IO::Sequence;
use Data::Sequence::Utils;
use RF::Data::RC;
use RF::Data::IO::RC;
use Term::Table;
use Term::Progress;
use Term::Progress::Multiple;
use Term::Constants qw(:screen);
$|++;
die "\n [!] Error: This program requires ithreads." .
"\n Please recompile Perl with ithreads support and try again\n\n" unless(defined $Config{useithreads});
my ($tmpdir, $output, $wt, $samtoolsParams,
$samtools, $multifasta, $sam, $progressBar,
$multiBar, $help, $overwrite, $error, $bam_trim5,
$offset, $threads, $processmanager, $estimatedSize,
$table, $mutcount, $rcio, $covonly, $nodel, $baseRC,
$pp, $po, $nodiscarddup, $minqual, $maxdel, $maxmut,
$hashead, $mapqual, $noambiguous, $medianqual, $noins,
$collapse, $maxmutdist, $evalsurround, $leftalign,
$discardshorter, $leftdel, $rightdel, $rmconsecutive,
$primaryonly, $onlyMut, $blockSize, $libraryStrandAll,
@bam_trim5, @qcounter, %transcripts, %spacer,
%files, %realid, %onlyMut, %blockData, %allStats,
%allFreqs);
do {
local $SIG{__WARN__} = sub { };
GetOptions( "h|help" => \$help,
"br|baseRC=s" => \$baseRC,
"t|tmp-dir=s" => \$tmpdir,
"o|output-dir=s" => \$output,
"ow|overwrite" => \$overwrite,
"t5|trim-5prime=s" => \$bam_trim5,
"wt|working-threads=i" => \$wt,
"ls|library-strandedness=s" => \$libraryStrandAll,
"s|samtools=s" => \$samtools,
"p|processors=i" => \$threads,
"f|fasta=s" => \$multifasta,
"m|count-mutations" => \$mutcount,
"co|coverage-only" => \$covonly,
"nd|no-deletions" => \$nodel,
"ni|no-insertions" => \$noins,
"md|max-deletion-len=i" => \$maxdel,
"pp|properly-paired" => \$pp,
"po|paired-only" => \$po,
"q|min-quality=i" => \$minqual,
"mq|map-quality=i" => \$mapqual,
"me|max-edit-distance=s" => \$maxmut,
"na|no-ambiguous" => \$noambiguous,
"la|left-align" => \$leftalign,
"eq|median-quality=i" => \$medianqual,
"cc|collapse-consecutive" => \$collapse,
"mc|max-collapse-distance=i" => \$maxmutdist,
"es|eval-surrounding" => \$evalsurround,
"ds|discard-shorter=i" => \$discardshorter,
"ld|left-deletion" => \$leftdel,
"rd|right-deletion" => \$rightdel,
"dc|discard-consecutive=i" => \$rmconsecutive,
"pn|primary-only" => \$primaryonly,
"om|only-mut=s" => \$onlyMut,
"ndd|no-discard-duplicates" => \$nodiscarddup,
"bs|block-size=s" => \$blockSize,
"P|per-file-progress" => \$multiBar ) or help(1);
};
help() if ($help);
# Default values
$output ||= "rf_count_genome/";
$wt ||= 1;
$offset = 0;
$threads ||= 1;
$bam_trim5 //= 0;
$minqual //= 20;
$medianqual //= 20;
$mapqual //= 0;
$maxdel //= 10;
$maxmutdist //= 2;
$maxmut ||= 0.15;
$discardshorter //= 1;
$rmconsecutive //= 0;
$blockSize ||= 100000;
$samtools ||= which("samtools");
$output =~ s/\/?$/\//;
$tmpdir = $output . "tmp/";
$multiBar = 0 if (!-t STDOUT);
##
# Input validation
##
die "\n [!] Error: No sample SAM/BAM file provided\n\n" if (!@ARGV);
die "\n [!] Error: No FASTA nor base RC file provided\n\n" if (!defined $multifasta && !defined $baseRC);
die "\n [!] Error: Provided FASTA file doesn't exist\n\n" if (defined $multifasta && !-e $multifasta);
die "\n [!] Error: Provided base RC file does not exist\n\n" if (defined $baseRC && !-e $baseRC);
die "\n [!] Error: Parameters -co and -m are mutually exclusive\n\n" if ($mutcount && $covonly);
die "\n [!] Error: Working threads value must be an integer greater than 0\n\n" if (!isint($wt) || $wt < 1);
die "\n [!] Error: Invalid format for -t5 parameter's argument\n\n" if (defined $bam_trim5 && $bam_trim5 !~ m/^(\d+[;,]?)+$/);
die "\n [!] Error: Number of processors must be an integer greater than 0\n\n" if ($threads < 1);
die "\n [!] Error: Parameter -nd requires parameter -m\n\n" if ($nodel && !$mutcount);
die "\n [!] Error: Minimum quality score value must be and integer >= 0 and <= 41\n\n" if (!inrange($minqual, [0, 41]));
die "\n [!] Error: Median read's quality score value must be and integer >= 0 and <= 41\n\n" if (!inrange($medianqual, [0, 41]));
die "\n [!] Error: Maximum edit distance value must be > 0 and <= 1\n\n" if (!inrange($maxmut, [0, 1]) || !$maxmut);
die "\n [!] Error: Parameters -na and -la are mutually exclusive\n\n" if ($noambiguous && $leftalign);
die "\n [!] Error: Parameters -cc and -dc are mutually exclusive\n\n" if ($collapse && $rmconsecutive);
die "\n [!] Error: Discard shorter must be a positive INT >= 0\n\n" if (!isint($discardshorter) || !ispositive($discardshorter));
die "\n [!] Error: Invalid library strandedness\n\n" if (defined $libraryStrandAll && $libraryStrandAll !~ /^(?:1|f(?:irst)?(?:-strand)?)|(?:2|s(?:econd)?(?:-strand)?)|(?:0|u(?:nstranded)?)$/);
die "\n [!] Error: Block size must be a positive INT >= 1000\n\n" if (!isint($blockSize) || $blockSize < 1000);
warn "\n [!] Warning: Some input files are duplicates. Considering only unique files...\n" if (@ARGV != uniq(@ARGV));
if ($mutcount && $onlyMut) {
# Automatically disables counting indels
$nodel = 1;
$noins = 1;
%onlyMut = map { my $i = $_; map { $i . $_ => { count => 0,
take => 0 } } qw(A C G T) } qw(A C G T);
foreach my $mutation (split(/[,;]/, $onlyMut)) {
my @bases = split(/[:2>]/, $mutation);
die "\n [!] Error: Invalid format for -mo parameter's argument \"" . $mutation . "\"\n\n" if (@bases != 2);
die "\n [!] Error: Mutation in -mo parameter's argument \"" . $mutation . "\" contains a non-IUPAC character\n\n" if (!isiupac(join("", @bases)));
foreach my $base1 (split //, (iupac2nt($bases[0]))[0]) {
foreach my $base2 (split //, (iupac2nt($bases[1]))[0]) { $onlyMut{$base1 . $base2}->{take} = 1; }
}
}
}
if (!defined $samtools) { die "\n [!] Error: samtools is not in PATH\n\n"; }
elsif (!-e $samtools) { die "\n [!] Error: samtools doesn't exist\n\n"; }
elsif (!-x $samtools) { die "\n [!] Error: samtools is not executable\n\n"; }
else {
my $ret = `$samtools 2>&1`;
if ($ret =~ m/Version: ([\d\.]+)/) {
my $version = $1;
die "\n [!] Error: RF Count requires SAMTools v1 or greater (Detected: v" . $version . ")\n\n" if (substr($version, 0, 1) < 1);
}
else { warn "\n [!] Warning: Unable to detect SAMTools version\n"; }
my (@noFlags, @yesFlags);
@noFlags = qw(UNMAP QCFAIL);
push(@yesFlags, "PAIRED") if ($pp || $po);
push(@yesFlags, "PROPER_PAIR") if ($pp);
push(@noFlags, "REVERSE") if (!$mutcount && !$covonly);
push(@noFlags, "SECONDARY") if ($primaryonly);
push(@noFlags, "DUP") if (!$nodiscarddup);
$samtoolsParams = "-f " . join(",", uniq(@yesFlags)) . " " if (@yesFlags);
$samtoolsParams = "-F " . join(",", uniq(@noFlags)) . " -q $mapqual";
}
#$SIG{__DIE__} = \&cleanup;
print "\n[+] Making output directory...";
if (-e $output) {
if ($overwrite) {
my $error = rmtree($output);
die "\n\n [!] Error: " . $error . "\n\n" if ($error);
}
else { die "\n\n [!] Error: Output directory already exists." .
"\n Please use -ow (or --overwrite) to overwrite output directory\n\n"; }
}
mkpath($tmpdir, { mode => 0755,
error => \$error });
die "\n\n [!] Error: Unable to create output directory (" . $error->[0]->{each(%{$error->[0]})} . ")\n\n" if (@{$error});
mkpath($output . "frequencies/", { mode => 0755,
error => \$error }) if ($onlyMut && $mutcount);
##
# Prepare files
##
$table = Term::Table->new(indent => 2);
$table->head("Sample", "File format", "Sorted", "Indexed", "Library type", "5'-end trimming");
@bam_trim5 = split(/,/, $bam_trim5);
undef($bam_trim5);
$bam_trim5 = shift(@bam_trim5) if (@bam_trim5 == 1); # If only one value for 5' trimming in SAM/BAM files has been specified,
# this is applied to all the passed SAM/BAM files
print "\n[+] Checking files:\n\n";
foreach my $sample (uniq(@ARGV)) {
my ($file, $path, $extension, $format,
$sorted, $libraryType);
($sample, $libraryType) = split(":", $sample);
die " [!] Error: Specified sample file \"$sample\" doesn't exist\n\n" if (!-e $sample);
($file, $path, $extension) = fileparse($sample, qr/\.[^.]*/);
($format, $sorted) = guessTypeAndSorting($sample);
if (!$libraryType) {
if (!$libraryStrandAll) {
if ($mutcount || $covonly) { $libraryType = "unstranded"; }
else { $libraryType = "second-strand"; }
}
else { $libraryType = $libraryStrandAll; }
}
if ($libraryType =~ m/^(?:1|f(?:irst)?(?:-strand)?)$/i) { $libraryType = "first-strand"; }
elsif ($libraryType =~ m/^(?:2|s(?:econd)?(?:-strand)?)$/i) { $libraryType = "second-strand"; }
elsif ($libraryType =~ m/^(?:0|u(?:nstranded)?)$/i) { $libraryType = "unstranded"; }
else { die " [!] Error: Invalid library type for sample \"" . $file . "\"\n\n"; }
die " [!] Error: Library type for RT-stop experiments can only be second-strand\n\n" if ($libraryType ne "second-strand" &&
!$mutcount && !$covonly);
push(@qcounter, { path => $sample,
file => $file,
type => $format,
sorted => $sorted,
indexed => -e "$sample.bai" ? 1 : 0,
library => $libraryType,
trim5 => 0,
missingMD => 0 });
$files{$file} = $#qcounter;
$spacer{$file} = length($file);
# If only one value for 5' trimming in SAM/BAM files has been specified, this is applied to all the passed SAM/BAM files
$qcounter[-1]->{trim5} = isint($bam_trim5) && ispositive($bam_trim5) ? $bam_trim5 : shift(@bam_trim5);
die " [!] Error: Less 5'-end trimming values in -t5 list than provided SAM/BAM files\n\n" if (!defined $qcounter[-1]->{trim5});
die " [!] Error: 5'-end trimming value must be a positive integer\n\n" if (!ispositive($qcounter[-1]->{trim5}) ||
!isint($qcounter[-1]->{trim5}));
$table->row($qcounter[-1]->{file}, $qcounter[-1]->{type}, $sorted ? "Yes" : "No",
$qcounter[-1]->{indexed} ? "Yes" : "No", $libraryType, ($mutcount || $covonly) ? "Ignored" : $qcounter[-1]->{trim5} . " nt");
}
%spacer = map { $_ => 1 + max(values %spacer) - $spacer{$_} } (keys %spacer);
die " [!] Error: More 5'-end trimming values in -t5 list than provided SAM/BAM files\n\n" if (@bam_trim5);
$table->print();
print "\n";
# Starts the process manager
$processmanager = Core::Process::Queue->new( processors => $threads,
stderr => $output . "error.out",
tmpDir => $tmpdir,
verbosity => 1 );
##
# FASTA Parsing
##
print "\n[+] Importing chromosomes from reference, and building count table base structure...";
if (!defined $baseRC) {
my $seqio = Data::IO::Sequence->new(file => $multifasta);
$rcio = RF::Data::IO::RC->new( file => $tmpdir . "base.rc",
index => $output . "index.rci",
buildindex => 1,
mode => "w" );
while (my $entry = $seqio->read()) {
my ($rentry, $id);
$id = $entry->id();
$id =~ s/[^\w\.-]/_/g; # Fixes sequence ids that can cause errors at later stages
$entry->unmask(); # Makes sequence uppercase
$rentry = RF::Data::RC->new( id => $id,
sequence => $entry->sequence() );
$rcio->write($rentry);
# Store length for later steps
$transcripts{$id} = $entry->length();
$realid{$id} = $entry->id();
$realid{$entry->id()} = $id;
}
$baseRC = $tmpdir . "base.rc";
}
else {
$rcio = RF::Data::IO::RC->new(file => $baseRC);
for ($rcio->ids()) {
$transcripts{$_} = $rcio->length($_);
$realid{$_} = $_;
}
}
$rcio->close();
$estimatedSize = sum(map { 12 + ($transcripts{$_} + ($transcripts{$_} % 2)) / 2 + 4 * $transcripts{$_} * 2 } keys %transcripts);
$estimatedSize *= sum(map { $_->{library} eq "unstranded" ? 1 : 2 } @qcounter);
if (my $spaceLeft = spaceLeft($output)) { die "\n\n [!] Error: Insufficient space on disk (needed: " . bytesToHuman($estimatedSize) . ", available: " . bytesToHuman($spaceLeft) . ")\n\n" if ($estimatedSize > $spaceLeft); }
##
# SAM/BAM Header validation
##
print "\n[+] Inspecting SAM/BAM file headers...";
foreach my $sample (@qcounter) {
my $inheader = 0;
open(my $fh, "-|", $samtools . " view -H " . $sample->{path} . " 2>&1") or die "\n\n [!] Error: Unable to read SAM/BAM header from sample \"" . $sample->{file} . "\" (" . $! . ")\n\n";
while (my $row = <$fh>) {
chomp($row);
if ($row =~ m/^\@SQ\tSN:(.+?)\tLN:(\d+)$/) {
my ($id, $length) = ($1, $2);
$id =~ s/\//_/g;
if (exists $transcripts{$id}) {
die "\n\n [!] Error: Chromosome \"" . $id . "\" length from sample \"" . $sample->{file} . "\" header (" . $length . " nt) differs from reference (" . $transcripts{$id} . " nt)." .
"\n Please re-map your dataset using the same reference, and try again.\n\n" if ($transcripts{$id} != $length);
$inheader++;
}
}
}
close($fh);
die "\n\n [!] Error: All chromosomes in sample \"" . $sample->{file} . "\" header are absent in reference." .
"\n Please re-map your dataset using the same reference, or provide a different reference by the -f (or --fasta) parameter.\n\n" if (!$inheader);
warn "\n\n [!] Warning: Only " . $inheader . "/" . keys(%transcripts) . " reference chromosomes are present in sample \"" . $sample->{file} . "\" header." .
"\n All chromosomes absent in reference will be skipped.\n" if ($inheader != keys(%transcripts));
}
##
# Sorting BAM files (if needed)
##
if (my @unsorted = grep { !$_->{sorted} } @qcounter) {
print "\n[+] Sorting " . scalar(@unsorted) . " unsorted SAM/BAM file(s)...\n";
$processmanager->onstart(sub { print "\n [-] Sorting sample \"" . $_[0] . "\"" . (" " x $spacer{$_[0]}) . "(PID: " . $_[1] . ")"; });
foreach my $sample (@unsorted) {
my $path = $tmpdir . $sample->{file} . "_sorted.bam";
$processmanager->enqueue( command => "$samtools sort -@ $wt -O BAM -T \"" . $tmpdir . $sample->{file} . "\" -o \"$path\" \"" . $sample->{path} . "\"",
id => $sample->{file} );
$sample->{path} = $path;
$sample->{type} = "BAM";
}
$processmanager->start();
$processmanager->waitall();
while (my $sample = $processmanager->dequeue()) { die "\n\n [!] Error: Unable to sort sample \"" . $sample->id() . "\"\n\n" if ($sample->exitcode()->[0]); }
print "\n";
}
##
# Indexing BAM files (if needed)
##
if (my @toIndex = grep { !$_->{indexed} } @qcounter) {
print "\n[+] Indexing " . scalar(@toIndex) . " BAM file(s)...\n";
$processmanager->onstart(sub { print "\n [-] Indexing sample \"" . $_[0] . "\"" . (" " x $spacer{$_[0]}) . "(PID: " . $_[1] . ")"; });
foreach my $sample (@toIndex) {
$processmanager->enqueue( command => "$samtools index -@ $wt \"" . $sample->{path} . "\"",
id => $sample->{file} );
$sample->{indexed} = 1;
}
$processmanager->start();
$processmanager->waitall();
while (my $sample = $processmanager->dequeue()) { die "\n\n [!] Error: Unable to index sample \"" . $sample->id() . "\"\n\n" if ($sample->exitcode()->[0]); }
print "\n";
}
print "\n[+] Copying RC base structure...";
$processmanager->onstart(sub { });
foreach my $sample (@qcounter) {
$processmanager->enqueue( command => sub { copy($baseRC, $output . $sample->{file} . ".plus.rc") or die $!; return(); },
id => $sample->{file} . "_plus");
$processmanager->enqueue( command => sub { copy($baseRC, $output . $sample->{file} . ".minus.rc") or die $!; return(); },
id => $sample->{file} . "_minus" ) if ($sample->{library} ne "unstranded");
}
$processmanager->start();
$processmanager->waitall();
while (my $sample = $processmanager->dequeue()) { die "\n\n [!] Error: Unable to copy counts table structure for sample \"" . $sample->exitcode()->[0] . "\"\n\n" if ($sample->exitcode()->[0]); }
print "\n[+] Queuing jobs...";
foreach my $chromosome (keys %transcripts) {
foreach my $sample (@qcounter) {
$processmanager->enqueue( command => \&count,
arguments => [ $sample, $chromosome ],
id => $sample->{file} );
}
}
$processmanager->shuffleQueue();
print "\n[+] Calculating per-base " . ($covonly ? "coverage" : ($mutcount ? "mutation counts" : "RT-stops") . " and coverage") . ". This may take a while...\n\n";
if ($multiBar) {
$progressBar = Term::Progress::Multiple->new( sets => { map { $_->{file} => scalar($processmanager->listQueue($_->{file})) } @qcounter },
colored => 1 );
$progressBar->initAll();
}
else {
$progressBar = Term::Progress->new( max => $processmanager->queueSize(),
colored => 1 );
$progressBar->init();
}
$processmanager->processors(min(ncores(), $threads * $wt));
$processmanager->onstart(sub {});
$processmanager->onexit(sub {});
$processmanager->parentOnExit(sub {
# Here we retrieve the partials from each process and combine them
my ($sample, $pid, $stats);
($sample, $pid) = @_[0,1];
$stats = ($processmanager->dequeue($pid)->exitcode())[0];
if (ref($stats) ne "HASH") { $stats = { error => $stats }; }
$progressBar->update($multiBar ? $sample : 1) if (!defined $stats->{error});
if (defined $stats->{error} || defined $stats->{warning}) {
my $errMsg = $stats->{error} || $stats->{warning};
$progressBar->appendText($multiBar ? ($sample, $errMsg) : $errMsg);
if (defined $stats->{error}) {
$allStats{$sample}->{error} = $errMsg;
$processmanager->deleteQueue($sample);
$processmanager->killById($sample);
}
}
else {
$allStats{$sample}->{$_} += $stats->{$_} for (qw(A C G T mutated total totalPrimary));
$allStats{$sample}->{covered}++;
if ($mutcount && $onlyMut) { $allFreqs{$sample}->{$_}->{count} += $stats->{onlyMut}->{$_}->{count} for (keys %{$stats->{onlyMut}}); }
}
});
$processmanager->start();
$processmanager->waitall();
print "\n\n[+] Statistics:\n";
foreach my $sample (sort keys %allStats) {
my ($stats, @rc);
@rc = ($output . $sample . ".plus.rc");
push(@rc, $output . $sample . ".minus.rc") if (-e $output . $sample . ".minus.rc");
if (exists $allStats{$sample}->{error}) { $stats = " [!] Processing failed for sample \"$sample\" (" . $allStats{$sample}->{error} . ")"; }
else {
$stats = " [*] Sample \"$sample\":" . (" " x $spacer{$sample}) . ($allStats{$sample}->{covered} || 0) . " chromosomes covered";
if (!$covonly) {
my $total = sum(map { $allStats{$sample}->{$_} } qw(A C G T));
$stats .= " [" . join("; ", map { $_ . ": " . sprintf("%.2f", $allStats{$sample}->{$_} / $total * 100) } qw(A C G T)) . "]" if ($total);
$stats .= " - " . $allStats{$sample}->{mutated} . "/" . $allStats{$sample}->{total} .
" (" . sprintf("%.2f", $allStats{$sample}->{mutated} / $allStats{$sample}->{total} * 100) . "\%) mutated alignments" if ($mutcount && $allStats{$sample}->{total});
}
# Updates the read count in the RC file
foreach my $rc (@rc) {
$rcio = RF::Data::IO::RC->new( file => $rc,
mode => "w+",
noPreloadIndex => 1 );
$rcio->mappedreads($allStats{$sample}->{totalPrimary});
$rcio->close();
}
if ($mutcount && $onlyMut) {
my ($totMuts, $freqIO);
$totMuts = sum(map { $allFreqs{$sample}->{$_}->{count} } keys %{$allFreqs{$sample}});
$freqIO = Data::IO->new( file => $output . "frequencies/" . $sample . ".txt",
mode => "w+",
flush => 1 );
$freqIO->write(join("\n", map { join("\t", $_, $totMuts ? sprintf("%.6f", $allFreqs{$sample}->{$_}->{count} / $totMuts) : "NaN") } sort keys %{$allFreqs{$sample}}) . "\n");
}
}
print "\n$stats";
}
print "\n\n[+] Cleaning up temporary files...";
cleanup();
print "\n[+] All done.\n\n";
sub count {
my ($sample, $id) = @_;
undef($processmanager); # Free up memory cloned from parent
$id =~ s/[^\w\.-]/_/g;
my ($stats, %counts, %coverage, %stats,
%rcIO, %covered);
%stats = ( id => $id,
A => 0,
C => 0,
G => 0,
T => 0,
mutated => 0,
total => 0,
totalPrimary => 0,
warning => undef );
%counts = ( "+" => [],
"-" => [] );
%coverage = ( "+" => [],
"-" => [] );
$rcIO{"+"} = RF::Data::IO::RC->new( file => $output . $sample->{file} . ".plus.rc",
index => $output . "index.rci",
mode => "w+" );
$rcIO{"-"} = RF::Data::IO::RC->new( file => $output . $sample->{file} . ".minus.rc",
index => $output . "index.rci",
mode => "w+" ) if ($sample->{library} ne "unstranded");
# We need to fix some parameters in case the analysis is MaP and unstranded
if ($sample->{library} eq "unstranded" && $mutcount) {
$noambiguous = 1;
undef($_) for ($leftalign, $rightdel, $leftdel, $collapse, $onlyMut);
}
if (open(my $fh, "-|", $samtools . " view $samtoolsParams " . $sample->{path} . " $realid{$id} 2>&1")) {
while (!eof($fh)) {
my ($row, $cov, $ins,
$editdist, $truelen, $gaps,
$realStrand, $start, $covWithGaps, @row);
chomp($row = <$fh>);
if ($row =~ /Could not retrieve index file/) { return({ error => "Error: Missing BAM index" }); }
elsif ($row =~ /invalid region or unknown reference/) { return({ warning => "Warning: Chromosome \"$realid{$id}\" absent in BAM file" }); }
elsif ($row =~ /\[main_samview\] (.+)$/) {
$stats{"warning"} = "Warning: $1";
next;
}
@row = split(/\t/, $row);
next if ($row[5] eq "*"); # to avoid malformed lines missing a CIGAR string
if ($sample->{library} eq "unstranded") { $realStrand = "+"; }
else {
if ($sample->{library} eq "second-strand") { $realStrand = $row[1] & 16 ? ($row[1] & 1 ? ($row[1] & 64 ? "-" : "+") : "-") : ($row[1] & 1 ? ($row[1] & 64 ? "+" : "-") : "+"); }
else { $realStrand = $row[1] & 16 ? ($row[1] & 1 ? ($row[1] & 64 ? "+" : "-") : "+") : ($row[1] & 1 ? ($row[1] & 64 ? "-" : "+") : "-"); }
}
$start = ($mutcount || $covonly || $realStrand eq "-" ? $row[3] : $row[3] - $sample->{trim5}) - 1;
($cov, $truelen, $covWithGaps, $ins, $gaps) = parsecigar($row[5]);
@{$ins} = map { $_ + $start } @{$ins}; # Adjust insertion relative position to true position
$editdist = editdist($row) + @{$ins}; # Editing distance is calculated this way so that consecutively deleted/inserted bases are counted only once
next if ($start < 0 || (!$mutcount && !$covonly && $realStrand eq "+" && $start - 1 < 0));
next if ($mutcount && $truelen < $discardshorter);
next if ($mutcount && $editdist / $cov > $maxmut);
next if ($mutcount && median(map { unpack("C*", $_) - 33 } split(//, $row[10])) < $medianqual); # Check median read's quality
#next if ($po && $row[1] & 1 && $row[1] & 8); # Read is one of a pair, but one mate is unmapped
#next if ($pp && $row[1] & 1 && !($row[1] & 2)); # Read is one of a pair, but pair is not properly mapped
next if ((($row[5] =~ m/^\d+S/ && $realStrand eq "+") || ($row[5] =~ m/\d+S$/ && $realStrand eq "-")) && !$mutcount && !$covonly); # Discard read in RT-count mode, if it has soft/hard clipping at 5'-end
#next if ($row[4] < $mapqual); # Discard reads with too low mapping quality
#next if ($primaryonly && $row[1] & 256); # Discard secondary alignments
#next if ($row[1] & 512); # Discard reads that fail platform quality checks
#next if ($row[1] & 1024 && !$nodiscarddup); # Discard reads that are optical/PCR duplicates
if (!defined $blockData{"start"} || $start > $blockData{start} + $blockSize - 1) {
if (defined $blockData{"start"}) {
my $maxSize = max(scalar(@{$counts{"+"}}), scalar(@{$counts{"-"}}), scalar(@{$coverage{"+"}}), scalar(@{$coverage{"-"}}));
push(@{$counts{"+"}}, (0) x ($maxSize - scalar(@{$counts{"+"}})));
push(@{$coverage{"+"}}, (0) x ($maxSize - scalar(@{$coverage{"+"}})));
if ($sample->{library} ne "unstranded") {
push(@{$counts{"-"}}, (0) x ($maxSize - scalar(@{$counts{"-"}})));
push(@{$coverage{"-"}}, (0) x ($maxSize - scalar(@{$coverage{"-"}})));
}
if ($blockData{"start"} + $#{$counts{"+"}} <= $start) {
$rcIO{"+"}->writeBytewise($id, $blockData{"start"}, $counts{"+"}, $coverage{"+"});
$counts{"+"} = [];
$coverage{"+"} = [];
if ($sample->{library} ne "unstranded") {
$rcIO{"-"}->writeBytewise($id, $blockData{"start"}, $counts{"-"}, $coverage{"-"});
$counts{"-"} = [];
$coverage{"-"} = [];
}
}
else {
my (@counts, @coverage);
@counts = splice(@{$counts{"+"}}, 0, $start - $blockData{"start"});
@coverage = splice(@{$coverage{"+"}}, 0, $start - $blockData{"start"});
$rcIO{"+"}->writeBytewise($id, $blockData{"start"}, \@counts, \@coverage);
if ($sample->{library} ne "unstranded") {
@counts = splice(@{$counts{"-"}}, 0, $start - $blockData{"start"});
@coverage = splice(@{$coverage{"-"}}, 0, $start - $blockData{"start"});
$rcIO{"-"}->writeBytewise($id, $blockData{"start"}, \@counts, \@coverage);
}
}
}
$blockData{"start"} = $start;
undef($blockData{"sequence"});
}
$start -= $blockData{"start"};
if (!defined $blockData{"sequence"} || $start + $covWithGaps >= $blockData{"length"}) {
$blockData{"sequence"} = $rcIO{"+"}->sequence($id, $blockData{"start"}, min($transcripts{$id} - 1, $blockData{"start"} + $start + $covWithGaps + $blockSize));#max($blockSize, $start + $covWithGaps + $blockSize)));
$blockData{"length"} = length($blockData{"sequence"});
}
next if (($mutcount || $covonly || $realStrand eq "-") && $start < 0);
# This happens when we are at the beginning of the block and the rt-stop is before the
# beginning of the block, then we update directly on the file
if (!$mutcount && !$covonly && $realStrand eq "+" && $start - 1 < 0) { $rcIO{"+"}->updateBytewise($id, $blockData{"start"} - 1, [1], [1]); }
else {
if ($mutcount) { # Mutations count
# Parse the MD flag only when edit distance != 0
if ($row !~ m/NM:i:0/) {
my ($muts, $missingMD, @uniqmutations);
($muts, $missingMD) = parsemd(\@row, clonearrayref($gaps), $realStrand);
if ($missingMD) {
$stats{warning} = "Warning: Missing MD tag, run 'samtools calmd' to fix";
last;
}
@$muts = uniq(@$muts, @{$ins}) if (!$noins);
@$muts = rmconsecutive(@$muts) if ($rmconsecutive);
# Collapsing is done towards the 3' end of the RNA, but if the library is unstranded, we do not know where the 3' end is
@$muts = collapsemutations($muts, $realStrand) if ($collapse);
@$muts = map { $_ - $blockData{"start"} } @$muts;
if (@$muts) {
$stats{mutated}++;
for (@$muts) {
$counts{$realStrand}->[$_]++;
my $base = $realStrand eq "+" ? substr($blockData{"sequence"}, $_, 1) : dnarevcomp(substr($blockData{"sequence"}, $_, 1));
$stats{$base}++;
}
}
}
}
elsif (!$covonly) { # RT-stops count mode
if ($realStrand eq "+") {
$counts{$realStrand}->[$start - 1]++;
$coverage{$realStrand}->[$_]++ for ($start - 1 .. $start + $sample->{trim5} - 1);
$stats{substr($blockData{"sequence"}, $start - 1, 1)}++;
}
else {
my $rtStopPos = $start + $covWithGaps + $sample->{trim5};
# On the minus strand, if the read aligns to the end of the chromosome, the RT-stop would exceed the length
next if ($blockData{"start"} + $rtStopPos >= $transcripts{$id});
$counts{$realStrand}->[$rtStopPos]++;
$coverage{$realStrand}->[$_]++ for ($rtStopPos - $sample->{trim5} .. $rtStopPos);
$stats{dnarevcomp(substr($blockData{"sequence"}, $rtStopPos, 1))}++;
}
}
}
$stats{totalPrimary}++ unless ($row[1] & 256);
$stats{total}++;
if (@$gaps) {
my ($lastStart, $lastEnd);
$lastStart = $start;
$lastStart += $sample->{trim5} if (!$mutcount && !$covonly && $realStrand eq "+");
foreach my $gap (@$gaps) {
$lastEnd = $lastStart + $gap->[0];
map { $coverage{$realStrand}->[$_]++ } $lastStart .. $lastEnd;
$lastStart = $lastEnd + $gap->[1] + 1;
}
$lastEnd = $start + $covWithGaps - 1;
$lastEnd += $sample->{trim5} if (!$mutcount && !$covonly && $realStrand eq "+");
map { $coverage{$realStrand}->[$_]++ } $lastStart .. $lastEnd;
}
else { map { $coverage{$realStrand}->[$_]++ } $start .. $start + $cov - 1; }
}
close($fh);
# Only if there were reads processed from file
if (defined $blockData{"start"}) {
my $maxSize = max(scalar(@{$counts{"+"}}), scalar(@{$counts{"-"}}), scalar(@{$coverage{"+"}}), scalar(@{$coverage{"-"}}));
push(@{$counts{"+"}}, (0) x ($maxSize - scalar(@{$counts{"+"}})));
push(@{$coverage{"+"}}, (0) x ($maxSize - scalar(@{$coverage{"+"}})));
if ($sample->{library} ne "unstranded") {
push(@{$counts{"-"}}, (0) x ($maxSize - scalar(@{$counts{"-"}})));
push(@{$coverage{"-"}}, (0) x ($maxSize - scalar(@{$coverage{"-"}})));
}
$rcIO{"+"}->writeBytewise($id, $blockData{"start"}, $counts{"+"}, $coverage{"+"}, $stats{totalPrimary});
$counts{"+"} = [];
$coverage{"+"} = [];
if ($sample->{library} ne "unstranded") {
$rcIO{"-"}->writeBytewise($id, $blockData{"start"}, $counts{"-"}, $coverage{"-"}, $stats{totalPrimary});
$counts{"-"} = [];
$coverage{"-"} = [];
}
}
$stats{onlyMut} = \%onlyMut;
return(\%stats);
}
else { return({ error => "Error: Unable to read file \"" . $sample->{file} . "\"" }); }
}
sub cleanup {
unlink(glob($tmpdir . "*"));
if (!-s $output . "error.out") { unlink($output . "error.out"); }
else { print "\n\n [!] Warning: Execution completed with error(s)/warning(s). Please check the \"${output}/error.out\" file\n"; }
rmtree($tmpdir);
}
sub guessTypeAndSorting {
my $file = shift;
my ($type, $header, $eof, $sorted,
$i, $h, @data, %header);
$i = $h = 0;
$sorted = 1;
$header = "\x1f\x8b\x08\x04\x00\x00\x00\x00\x00\xff\x06\x00\x42\x43\x02\x00";
$eof = "\x1f\x8b\x08\x04\x00\x00\x00\x00\x00\xff\x06\x00\x42\x43\x02\x00\x1b\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00";
open(my $fh, "-|", "$samtools view -h $samtoolsParams $file 2>&1") or die "\n [!] Error: Unable to open sample \"$file\" ($!)\n\n";
while (<$fh>) {
if (substr($_, 0, 1) eq "@") {
if (substr($_, 1, 2) eq "SQ") {
my @row = split "\t";
$header{(split(":", $row[1]))[1]} = $h;
$h++;
}
}
else {
$i++;
my @row = split "\t";
die "\n [!] Error: Sample \"$file\" is not a valid SAM/BAM file\n\n" if (/(?:Failed to open file|fail to read the header)/ ||
@row < 12 || !isint($row[1]) || !isdna($row[9]));
$sorted = 0 if (@data && ($header{$row[2]} < $header{$data[0]} ||
($header{$row[2]} == $header{$data[0]} && $row[3] < $data[1])));
@data = ($row[2], $row[3]);
}
last if ($i == 100);
}
close($fh);
undef(@data);
open($fh , "<:raw", $file);
read($fh, $data[0], 16);
seek($fh, -28, SEEK_END);
read($fh, $data[1], 28);
close($fh);
if ($data[0] eq $header && $data[1] eq $eof) { $type = "BAM"; }
else { $type = "SAM"; }
return($type, $sorted);
}
sub parsemd { # SAM MD flag parser
my ($row, $gaps, $strand) = @_;
my ($md, $llen, $realStart, $lastGapEnd,
@pos, @quals, %posMap);
$realStart = $row->[3] - 1;
$llen = $realStart;
$lastGapEnd = $realStart;
return([], 1) if (@{$row} < 11);
for (10 .. $#{$row}) { if ($row->[$_] =~ m/^MD:Z:(.+)$/) { $md = $1; last; } }
return([], 1) if (!defined $md);
%posMap = ref2read($row);
@quals = split(//, $row->[10]);
$md = uc($md);
while($md =~ m/^(\d+)/) {
my ($len, $next);
$len = $1;
$md =~ s/^$len//;
if (@$gaps && $llen + $len > $lastGapEnd + $gaps->[0]->[0]) {
my $gap = shift(@$gaps);
$llen += $gap->[1];
$lastGapEnd += $gap->[0] + $gap->[1];
}
while($md =~ m/^(\D)/) {