-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlacer.pl
executable file
·1576 lines (1500 loc) · 52.2 KB
/
lacer.pl
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
#
my $lacer_version = 0.426;
# version 0.426
# Update recal file (no_standard_covs false) to track GATK4
# Add a new verbosity level to prevent SVD fits for covariates by default
# Cosmetic updates to progress tracker
# Enable correct progress when stopbases is set
#
# version 0.425
# Replicate rows prior to svd to make sure we have more rows than columns
# This appears to be a new check in PDL somewhere between 2.007 and 2.018
#
# version 0.424
# change -dump to a flag instead of requiring an integer argument
# add percentage to # of recalibration bases on status display
# change default $MINCOV to 5 to prevent lots of coverage=1 bases taking up
# too many recalibration bases, particularly a problem when using -stopbases
#
# version 0.423
# clean up verbose vs. dump, default thread_debug is 0
# fixed bug with reporting reverse complement base when mapped to negative
# strand - context was ok, just the base at that position was revcomped when it
# shouldn't have been
#
# version 0.422
# add bed file input for regions
#
# version 0.421
# add some extra output for figures, quality control, etc.
#
# version 0.42
# fix up read group handling
# change defaults - no coverage limit
#
# version 0.41
# separate out GLOBALS - 0.5 experiment with consolidating made it slower
# don't use single anymore, use actual counts
# alter sort order to capture minor nonconsensus bases
#
# version 0.4
# start cleaning up a bit
# add a better progress indicator
#
# version 0.3
# thread enabled
# batch together pdl calls instead of doing one per base
#
# version 0.2
# change default range span to 0.8 instead of 0.5
# also make this a parameter
# add in context and cycle covariates
# switch histogram keying to enable this
#
use warnings;
use strict;
use Data::Dumper;
use threads;
use threads::shared;
use Thread::Queue;
use Bio::DB::Sam;
use PDL;
use PDL::NiceSlice;
use PDL::MatrixOps;
use PDL::Parallel::threads ("retrieve_pdls", "share_pdls", "free_pdls");
$PDL::BIGPDL = 1;
$PDL::BIGPDL = 1; # so Perl doesn't warn
use Memory::Usage;
use Term::ProgressBar;
use Getopt::Long;
Getopt::Long::Configure("pass_through");
$SIG{INT} = \&sigint_handler; # so we can stop a little early
# shared globals
my $ALLHIST = {}; share($ALLHIST);
my $VCFPOS = {}; share($VCFPOS);
my @RG_LIST = (); share(@RG_LIST);
my @THREADSTATUS = (); share(@THREADSTATUS); # started, data, goaway, interrupt
my @DUMPDATA = (); share(@DUMPDATA);
my ($CONSENSUS_TO_PRINT,
$MAXCOV,
$MINCOV,
$MINMAPQ,
$MINQ,
$INCLUDEVCF,
$MAXQUAL,
$MINQUAL,
$MINOR_FREQ,
$DUMP,
$ABORT,
$CALIBRATION_BASES,
$TOTAL_BASES,
$USE_READGROUPS) :shared;
$CONSENSUS_TO_PRINT = 1; # 0 means all
$MAXCOV = 0; # max coverage at a given position - skip if greater
$MINCOV = 5; # min coverage at a given position - skip if less
$MINMAPQ = 30; # minimum mapping quality to consider
$MINQ = 6; # minimum base quality to consider
$INCLUDEVCF = 0; # 0 is skip vcf positions, 1 is only use vcf positions
$MAXQUAL = 0;
$MINQUAL = 0;
$MINOR_FREQ = 0.05; # we'll try to print these bases - generalized "single"
$DUMP = 0;
$ABORT = 0; # second control-C we really quit
$CALIBRATION_BASES = 0; # these are for dynamic updates
$TOTAL_BASES = 0;
$USE_READGROUPS = 1; # if it's 0 we put everything together
# other variables - shouldn't be needed in threads
my $original_command = join (" ", $0, @ARGV);
my $mu = Memory::Usage->new();
my $starttime = time();
my $bamfile = "";
my $ref_fasta = "";
my $windowsize = 10000; # windows size of coordinates to look at
my $region = ""; # look only in this region
my $outfile = "-";
my $vcf = "";
my $vcfoffset = 1000;
my $svd_bin = 3000;
my $covariate_binsize = 1000;
my $min_span = 0.8;
my $do_covariates = 1;
my $gatk = 1; # whether to output gatk recal file
my $rg = "";
my $verbose = 1;
my $num_threads = 4;
my $rgfield = "ID";
my $randomize_regions = 0;
my $stop_bases = 0;
my $thread_debug = 0;
GetOptions (
'bam=s' => \$bamfile,
'reference=s' => \$ref_fasta,
'consensus=i' => \$CONSENSUS_TO_PRINT,
'window=i' => \$windowsize,
'svdbin=i' => \$svd_bin,
'covariatebin=i' => \$covariate_binsize,
'coverage=i' => \$MAXCOV,
'mincoverage=i' => \$MINCOV,
'span=f' => \$min_span,
'mapq=i' => \$MINMAPQ,
'minq=i' => \$MINQ,
'region=s' => \$region,
'vcf=s' => \$vcf,
'includevcf=i' => \$INCLUDEVCF,
'gatk!' => \$gatk,
'outfile=s' => \$outfile,
'randomize!' => \$randomize_regions,
'stopbases=i' => \$stop_bases,
'verbose=i' => \$verbose,
'covariates!' => \$do_covariates,
'threads=i' => \$num_threads,
'minor=f' => \$MINOR_FREQ,
'dump!' => \$DUMP,
'readgroups!' => \$USE_READGROUPS,
'rgfield=s' => \$rgfield
);
if (!-f $bamfile || !-f $ref_fasta) {
print "Usage: $0 -bam <bam file> -reference <ref fasta> [ parameters ]\n";
print <<__USAGE__;
Required arguments
-bam <bam file> : make sure it's *sorted* and *indexed*
make sure the index file is named the same as
your .bam file but with a .bai index
-reference <ref fasta> : the reference fasta file
General data parameters (mostly similar to GATK)
-vcf <vcf file> : vcf file marking known variants - generally not
needed (no default)
-includevcf <0|1> : 0 = skip vcf positions (like GATK)
1 = use only vcf positions
-coverage <int> : if coverage at a position is greater than this,
don't pick single/nonconsensus bases here
(0 = no limit) (default $MAXCOV)
-mincoverage <int> : if coverage at a position is less than this,
don't pick single/nonconsensus bases here
(0 = no minimum) (default $MINCOV)
-minq <int> : minimum base quality to use, lower ones ignored
(default $MINQ)
-mapq <int> : minimum mapping quality - discard read otherwise
(default $MINMAPQ)
-region <chrom:first-last> : region to focus on for pileups and recalibration
can also specify a BED file (chrom first last)
BED format is whitespace delimited
(default all chromosomes, all positions)
-covariates|nocovariates : whether to do context and cycle covariates
(default covariates)
-gatk|nogatk : whether to output GATK-style recalibration table
(default gatk)
-readgroups|noreadgroups : whether to use readgroups - if noreadgroups,
all data in the bam file will be combined
(default readgroups)
-rgfield : specifies whether to use read group ID (ID),
platform unit (PU), library (LB), or sample
name (SM) from the \@RG line (later versions of
GATK require PU) (default $rgfield)
General running parameters
-outfile <filename> : output filename; default is STDOUT
-threads <int> : # of threads to use (default $num_threads)
-window <int> : window size (work unit) for pileups ($windowsize)
-randomize|norandomize : randomize order of windows for pileups
(default norandomize)
-stopbases <int> : stop pileups and recalibrate when we reach this
many recalibration bases (0 = no limit)
(default $stop_bases)
Technical SVD/recalibration parameters
-consensus <int> : # of consensus bases to use
every time we see a nonconsensus base, we take
this many consensus bases from that same pos
(0 = use all) (default $CONSENSUS_TO_PRINT)
-svdbin <int> : # of bases to bin into quality histogram when
making matrix that we end up doing SVD on ($svd_bin)
-covariatebin <int> : # of bases to bin when doing covariate SVDs
covariates generally have less data so make this
smaller than svdbin ($covariate_binsize)
-span <float> : between 0 and 1, technical parameter for how much
of eigenvalue 1 range to require when predicting
error and correct quality dists (default $min_span)
-minor <float> : between 0 and 1, realistically less than 0.1
defines frequency of minor bases in a pileup
(default $MINOR_FREQ)
-verbose <0|1|2|3> : 0 = totally silent
1 = progress meter, overall SVD fit (default)
2 = progress meter with all SVD fits
3 = noisy (memory usage, timing, etc on STDOUT)
-dump|nodump : dump all the data to STDOUT (warning it's a lot)
__USAGE__
exit;
}
# set up variables and files and such
if (!length($outfile) || $outfile eq "-") {
*OUT = *STDOUT;
} elsif (-f $outfile) {
die "Output file $outfile exists, will not overwrite. Aborting...\n";
} else {
open(OUT, ">$outfile");
}
my $sam = Bio::DB::Sam->new(-fasta => $ref_fasta, -bam => $bamfile, -autoindex => 1, -expand_flags => 1);
my $bam = $sam->bam;
my $header = $bam->header();
my $bam_comments = $header->text;
my @seqs = $sam->seq_ids;
my $i = 0;
my $first = 0;
my $last = 0;
my $single = ();
my $alldata = {};
my $threaddata = [];
my $tempdata;
my $temphist;
my @h = ();
my @regions = ();
my @out;
my %context_code = (
"AA" => 1, "AC" => 2, "AG" => 3, "AT" => 4,
"CA" => 5, "CC" => 6, "CG" => 7, "CT" => 8,
"GA" => 9, "GC" => 10, "GG" => 11, "GT" => 12,
"TA" => 13, "TC" => 14, "TG" => 15, "TT" => 16,
".A" => -1, ".C" => -2, ".G" => -3, ".T" => -4,
"A." => -5, "C." => -6, "G." => -7, "T." => -8,
".." => -9
);
my %code_context = reverse %context_code;
my $align;
my @f;
my $j;
my $time;
my $end;
my $last_count;
my $matrix;
my $recalibrated;
my $scale;
my $range;
my $chrom;
my @data;
my $p;
my $ix;
my $start;
my $consensus_base;
my $svd_hist;
my $covariate;
my $covariate_hist;
my $covariate_recalibrated;
my $queue;
my $number_regions;
my @threadlist;
my $temppdl;
my $pending;
my $waiting;
my $wait_interval;
my $progress;
my @table;
my $max_bases;
my $rginfo;
my $left_fields;
$verbose = 3 if $verbose > 3;
if ($verbose == 3) {
print STDOUT "# Start time: $starttime\n";
print STDOUT "# Original command line: ", $original_command, "\n";
print STDOUT "# windowsize (for pileups): $windowsize\n";
print STDOUT "# SVD binsize (for quality histograms): $svd_bin\n";
print STDOUT "# Maxcov $MAXCOV, Min mapping $MINMAPQ, Min base $MINQ\n";
print STDOUT "# vcf mode $INCLUDEVCF\n";
$mu->record("Start");
}
#
# figure out what regions we're looking at
#
if (length $region && -f $region) {
open REG, $region;
while ($j = <REG>) {
next if $j =~ /^#/;
next if $j =~ /^$/;
chomp;
($chrom, $start, $end) = split /\s+/, $j;
# bed file is 0-based so correct range, but only need start
$start++;
for ($i = $start; $i <= $end; $i += $windowsize) {
$first = $i;
$last = $i+$windowsize-1;
$last = $end if $end < $last;
push @regions, "$chrom:$first-$last";
}
}
} elsif (length $region) {
($chrom, $range) = split /:/, $region;
($start, $end) = split /-/, $range;
if (!$start || !$end) {
$start = 1;
$end = $sam->length($chrom);
}
for ($i = $start; $i <= $end; $i += $windowsize) {
$first = $i;
$last = $i+$windowsize-1;
$last = $end if $end < $last;
push @regions, "$chrom:$first-$last";
}
}
if (!scalar @regions) {
foreach $chrom (@seqs) {
$start = 1;
$end = $sam->length($chrom);
for ($i = $start; $i <= $end; $i += $windowsize) {
$first = $i;
$last = $i+$windowsize-1;
$last = $end if $end < $last;
push @regions, "$chrom:$first-$last";
}
}
}
if ($randomize_regions) {
my @temp = @regions;
@regions = ();
my @index = ();
foreach $i (0..$#temp) {
$index[$i] = rand();
}
foreach $i (sort { $index[$a] <=> $index[$b] } (0..$#temp)) {
push @regions, $temp[$i];
}
}
#
# hope the read groups are all listed in the bam comments at the top
# use this to initialize the pdls for $alldata
#
if ($USE_READGROUPS) {
undef $rginfo;
@f = split /\n/, $bam_comments;
foreach $i (@f) {
if ($i =~ /^\@RG/) {
$i =~ /ID:(\S+)/;
$rg = $1;
$rg = "NULL" if !defined $rg;
push(@RG_LIST, $rg);
foreach $j (qw(ID PL PU LB SM)) {
if ($i =~ /$j:(\S+)/) {
$rginfo->{$rg}->{$j} = $1;
} else {
$rginfo->{$rg}->{$j} = "NULL";
}
}
}
}
if (!defined $rginfo) {
@RG_LIST = ("NULL");
foreach $j (qw(ID PL PU LB SM)) {
$rginfo->{"NULL"}->{$j} = "NULL";
}
}
}
if (!scalar @RG_LIST) {
@RG_LIST = ("NULL");
}
foreach $rg (@RG_LIST) {
foreach $j (1..$num_threads) {
$threaddata->[$j]->{$rg} = zeroes(6,1);
share_pdls($j . "__" . $rg => $threaddata->[$j]->{$rg});
}
$alldata->{$rg} = null;
}
#
# generate pileups and collect info
#
if (-f $vcf) {
open V, $vcf;
while (<V>) {
next if /^#/;
chomp;
@f = split /\t/, $_;
if (!defined $VCFPOS->{$f[0]}) {
my %anon :shared;
$VCFPOS->{$f[0]} = \%anon;
}
$VCFPOS->{$f[0]}->{$f[1]} = 1;
}
close V;
}
$queue = Thread::Queue->new;
$queue->enqueue(@regions);
$number_regions = scalar @regions;
$num_threads = scalar @regions if scalar @regions < $num_threads;
foreach $i (1..$num_threads) {
threads->create(\&worker, $queue, $i, $i . "__");
$THREADSTATUS[$i] = "started";
}
sub worker {
my $q = shift;
my $thread = shift;
my $prefix = shift;
my $region = "";
my $time;
my $tempdata;
my $temphist;
my $rg;
my $first;
my $last;
my $alldata = {};
foreach $rg (@RG_LIST) {
$alldata->{$rg} = retrieve_pdls($prefix . $rg);
}
my $map_consensus = sub {
my ($seqid, $pos, $pileup, $sam) = @_;
my @a;
my $aln;
my @nt;
my @rg;
my $cov = 0;
my $max = 0;
my @con = ();
my $num = 0;
my $tempq;
my $temppos;
my @index;
my $left;
my $left2;
my $right;
my $printed_consensus;
my $printed_nonminor;
my @context;
my $i;
my $n;
my $base = { "G" => 0, "A" => 0, "T" => 0, "C" => 0 };
my $have_minor = 0;
# first pass - call consensus
return if ($pos < $first || $pos > $last);
if ($INCLUDEVCF) {
return if !defined $VCFPOS->{$seqid}->{$pos};
} else {
return if defined $VCFPOS->{$seqid} && defined $VCFPOS->{$seqid}->{$pos};
}
# keep track of indices in original @$pileup
# only want to run alignments once
# also need to keep track if we skipped this element of @$pileup
# so initialize to 0
@a = (0) x scalar(@$pileup);
# do reverse so we can splice
foreach $i (reverse (0..$#{$pileup})) {
$p = $pileup->[$i];
next if !defined($p);
# if we don't want this read then don't look at it again
next if ($p->is_refskip || $p->indel);
$a[$i] = $p->alignment;
$aln = $a[$i];
next if !$aln->qual || $aln->qual < $MINMAPQ;
$tempq = unpack("x". ($p->qpos) . "C", $aln->_qscore);
next if $tempq < $MINQ;
$cov++;
if ($USE_READGROUPS) {
$rg[$i] = $aln->aux;
if ($rg[$i] =~ /RG:Z:(\S+)/) {
$rg[$i] = $1;
} else {
$rg[$i] = "NULL";
}
} else {
$rg[$i] = "NULL";
}
$temphist->{$rg[$i]}->{0}->[$tempq]++; # overall histogram
if ($aln->strand > 0) {
# note qpos returns 0-based coordinate
# context should be reverse complemented already if negative strand
# base returned should be positive strand regardless - to compare with ref
$temppos = $p->qpos+1;
# ($context[$i], $nt[$i]) = get_context($aln->qseq, $p->qpos, 1);
($context[$i], $nt[$i]) = get_2base($aln->qseq, $p->qpos, 1);
} else {
$temppos = $aln->l_qseq - $p->qpos;
# ($context[$i], $nt[$i]) = get_context($aln->qseq, $p->qpos, -1);
($context[$i], $nt[$i]) = get_2base($aln->qseq, $p->qpos, -1);
}
$temppos = -$temppos if $aln->get_tag_values("SECOND_MATE");
$temphist->{$rg[$i]}->{$temppos}->[$tempq]++; # position specific
$temphist->{$rg[$i]}->{$context[$i]}->[$tempq]++;
if (!$MAXQUAL) {
$MAXQUAL = $tempq;
}
if (!$MINQUAL) {
$MINQUAL = $tempq;
}
if ($tempq > $MAXQUAL) { $MAXQUAL = $tempq; }
if ($tempq < $MINQUAL) { $MINQUAL = $tempq; }
$base->{$nt[$i]}++;
}
# if we're high coverage, we still need the histograms, but don't use these
# bases for recalibration - they set this in GATK but unclear it affects us
return if $MAXCOV && $cov > $MAXCOV;
return if $MINCOV && $cov < $MINCOV;
$have_minor = 0;
foreach $n (qw(G A T C)) {
$num++ if $base->{$n} > 0;
if ($base->{$n} > $max) {
@con = ($n);
$max = $base->{$n};
} elsif ($base->{$n} == $max) {
push @con, $n;
}
if ($base->{$n} == 1 ||
($base->{$n} > 0 && $cov > 0 && $base->{$n}/$cov < $MINOR_FREQ)
) {
$have_minor = 1;
}
} # done with first pass
# actually only go on if we have minor bases
if ($have_minor) {
if (scalar @con) {
$consensus_base = $con[int(rand(scalar(@con)))];
} else {
$consensus_base = ".";
}
# randomize the order in case we're not printing all consensus
$printed_consensus = 0;
$printed_nonminor = 0;
@index = ();
foreach $i (0..$#$pileup) {
$index[$i] = rand();
}
foreach $i (sort { $index[$a] <=> $index[$b] } (0..$#$pileup)) {
next if !$a[$i];
$p = $pileup->[$i];
next if ($p->is_refskip || $p->indel);
$aln = $a[$i];
next if !$aln->qual || $aln->qual < $MINMAPQ;
next if $aln->qscore->[$p->qpos] < $MINQ;
@data = ();
push @data, $aln->qscore->[$p->qpos];
# Consensus or not
if ($consensus_base eq $nt[$i]) {
next if ($CONSENSUS_TO_PRINT && $printed_consensus >= $CONSENSUS_TO_PRINT);
push @data, 1; # consensus
$printed_consensus++;
} else {
push @data, 0; # nonconsensus
if ($cov > 0 && $base->{$nt[$i]} > 1 && $base->{$nt[$i]}/$cov > $MINOR_FREQ) {
# test coverage for divide by zero (shouldn't happen)
# we want all singles to get printed regardless of coverage
# otherwise, limit only when it's not a minor base
next if ($CONSENSUS_TO_PRINT && $printed_nonminor >= $CONSENSUS_TO_PRINT);
$printed_nonminor++;
}
}
# "vote" for this nucleotide at this position
push @data, $base->{$nt[$i]};
# Coverage at this coordinate
push @data, $cov;
# Position - in read
if ($aln->strand > 0) {
$temppos = $p->qpos+1;
} else {
$temppos = $aln->l_qseq - $p->qpos;
}
$temppos = -$temppos if $aln->get_tag_values("SECOND_MATE");
push @data, $temppos;
# context - encoded as integer
push @data, $context_code{$context[$i]};
if ($DUMP) {
lock(@DUMPDATA);
push @DUMPDATA, join ("\t", $seqid, $pos, $nt[$i], $aln->qual, $aln->strand, @data);
}
$tempdata->{$rg[$i]} = null if !defined $tempdata->{$rg[$i]};
$tempdata->{$rg[$i]} = $tempdata->{$rg[$i]}->glue(1,pdl(\@data));
}
}
}; # sub map_consensus
$sam->clone;
while ($region = $q->dequeue_nb) {
last if ($THREADSTATUS[$thread] eq "interrupt");
print STDERR "$THREADSTATUS[$thread]\n" if $THREADSTATUS[$thread] ne "started";
$tempdata = {};
$temphist = {};
if ($region =~ /:(\d+)-(\d+)/) {
($first, $last) = ($1, $2);
} else {
($first, $last) = (0, 0); # we should never really hit this else clause
}
if ($thread_debug) { print STDERR "About to do pileup for $region, thread $thread, status $THREADSTATUS[$thread]\n"; }
$sam->fast_pileup($region, $map_consensus);
if ($thread_debug) { print STDERR "Return from pileup for $region, thread $thread, status $THREADSTATUS[$thread]\n"; }
foreach $rg (keys %$tempdata) {
if (!defined $alldata->{$rg}) {
# actually if there are no read groups we should have defined
# a default "NULL" read group and set $alldata->{NULL}
# so the second check here shouldn't really be necessary
if ($rg eq "NULL" && $RG_LIST[0] ne "NULL") {
print STDERR "Error, we found some reads not marked by read groups. Ignoring these...\n";
} else {
print STDERR "Error, we found some reads marked by a read group ($rg) not in the SAM header. Ignoring these...\n";
}
next;
}
if ($alldata->{$rg}->at(0,0) == 0) {
$alldata->{$rg} = $tempdata->{$rg}->copy;
} else {
$alldata->{$rg} = $alldata->{$rg}->glue(1, $tempdata->{$rg});
}
}
{
lock($ALLHIST);
&add_hist($temphist);
}
{
lock($CALIBRATION_BASES);
lock($TOTAL_BASES);
foreach $rg (keys %$tempdata) {
$CALIBRATION_BASES += $tempdata->{$rg}->getdim(1);
}
foreach $rg (keys %$temphist) {
foreach my $j (0..$#{$temphist->{$rg}->{0}}) {
$TOTAL_BASES += $temphist->{$rg}->{0}->[$j] if defined $temphist->{$rg}->{0}->[$j];
}
}
}
}
# samtools module crashes on thread exit
# just detach and sleep a long time
foreach $rg (@RG_LIST) {
share_pdls($thread . "final" . $rg => $alldata->{$rg}->sever);
}
{
lock @THREADSTATUS;
$THREADSTATUS[$thread] = "data";
}
while (1) {
sleep 5;
if ($THREADSTATUS[$thread] eq "goaway") {
threads->detach;
last;
}
}
foreach $rg (keys %$alldata) {
free_pdls($thread . "__" . $rg);
free_pdls($thread . "final" . $rg);
}
while (1) {
sleep 600;
}
}
@threadlist = threads->list;
$waiting = 1;
$wait_interval = 60;
if ($verbose) {
if ($stop_bases > 0) {
$progress = Term::ProgressBar->new({ name => "Cal bases", count => $stop_bases, remove => 0, ETA => 'linear' });
} else {
$progress = Term::ProgressBar->new({ name => "Pileups", count => $number_regions, remove => 0, ETA => 'linear' });
}
$progress->max_update_rate($wait_interval);
$progress->minor(0);
$progress->message("Lacer version $lacer_version running on $bamfile");
if ($stop_bases > 0) {
$progress->message("Will stop after finding at least $stop_bases calibration bases.");
}
$progress->message("Press Control-C *once* to finish current windows and recalibrate immediately.");
$progress->message("Numbers below for all read groups (expect calibration bases to be <2% total)");
$progress->message("0/0 (calibration/total; 0.00%) bases processed");
}
if ($DUMP) {
print STDOUT join ("\t", "# SeqID", "Position", "Base", "MapQ", "Strand", "Quality", "Consensus", "Vote", "Coverage", "Cycle", "ContextCode"), "\n";
}
my $message = "";
my $ml = 0;
while ($waiting) {
$waiting = 0;
sleep $wait_interval;
if ($DUMP && scalar @DUMPDATA) {
lock(@DUMPDATA);
print STDOUT join ("\n", @DUMPDATA), "\n";
@DUMPDATA = ();
}
foreach $i (1..$#THREADSTATUS) {
if ($THREADSTATUS[$i] eq "data") {
foreach $rg (@RG_LIST) {
$temppdl = retrieve_pdls($i . "final" . $rg);
if ($temppdl->at(0,0) > 0) {
$alldata->{$rg} = $alldata->{$rg}->glue(1, $temppdl);
$alldata->{$rg}->sever;
}
free_pdls($i . "__" . $rg);
}
{
lock @THREADSTATUS;
$THREADSTATUS[$i] = "goaway";
}
}
}
foreach $i (@threadlist) {
$waiting++ if !$i->is_detached;
}
if ($verbose) {
$pending = $queue->pending();
if (defined($pending)) {
if ($stop_bases > 0) {
if ($CALIBRATION_BASES > $stop_bases) {
$progress->update($stop_bases);
} else {
$progress->update($CALIBRATION_BASES);
}
} else {
$progress->update($number_regions - $pending - $num_threads);
}
}
if ($TOTAL_BASES > 0) {
$message = "\b\r$CALIBRATION_BASES/" . $TOTAL_BASES . " (calibration/total; " . sprintf("%.2f", $CALIBRATION_BASES/$TOTAL_BASES * 100) . "%) bases processed";
$ml = length($message) - $ml - 1;
$progress->message($message);
}
}
if ($thread_debug) {
print STDERR "Stop Bases: $stop_bases\n";
print STDERR "Calibration Bases: $CALIBRATION_BASES\n";
print STDERR "Threads:\n";
foreach $i (1..$#THREADSTATUS) {
print STDERR " Thread $i -- $THREADSTATUS[$i]\n";
}
print STDERR "Queue:\n";
if ($pending) {
print STDERR " Pending: $pending; Total: $number_regions\n";
print STDERR " Next in queue: ", $queue->peek(), "\n";
print STDERR " Last in queue: ", $queue->peek(-1), "\n";
}
}
if ($stop_bases > 0 && $CALIBRATION_BASES > $stop_bases) {
&quit_pileups;
}
}
# we should be done now
if (!defined $ALLHIST || ref($ALLHIST) ne "HASH") {
print STDERR "Uh oh, we don't seem to have any data\n";
exit;
}
if ($verbose) {
if ($stop_bases > 0) {
if ($CALIBRATION_BASES > $stop_bases) {
$progress->update($stop_bases);
} else {
$progress->update($CALIBRATION_BASES);
}
} else {
$progress->update($number_regions);
}
print STDERR "\nBeginning SVD-based recalibration...\n";
}
#
# do the recalibration
#
# first clean all the histograms
if ($DUMP) {
foreach $j ($MINQUAL..$MAXQUAL) {
foreach $rg (sort keys %$ALLHIST) {
@out = ("# Quality", "Read Group");
foreach $covariate (sort keys %{$ALLHIST->{$rg}}) {
push @out, $covariate;
}
print join ("\t", @out), "\n";
last;
}
}
}
foreach $j ($MINQUAL..$MAXQUAL) {
foreach $rg (sort keys %$ALLHIST) {
@out = ($j, $rg);
foreach $covariate (sort keys %{$ALLHIST->{$rg}}) {
if (!defined $ALLHIST->{$rg}->{$covariate}->[$j] ||
$ALLHIST->{$rg}->{$covariate}->[$j] < 0) {
$ALLHIST->{$rg}->{$covariate}->[$j] = 0;
}
if ($DUMP) {
push @out, $ALLHIST->{$rg}->{$covariate}->[$j];
}
}
if ($DUMP) {
print STDOUT join ("\t", @out), "\n";
}
}
}
my $pca1;
foreach $rg (keys %$alldata) {
# sanity check to make sure we have data
if (ref($alldata->{$rg}) ne "PDL" ||
$alldata->{$rg}->isnull ||
$alldata->{$rg}->at(0,0) == 0) {
print STDERR "Uh oh, seem to have no data for read group $rg\n";
next;
}
# first the overall recalibration
($matrix, $last_count) = make_matrix($alldata->{$rg}, $svd_bin);
# make the svd_hist here anyway so we can count bases even if we don't have
# enough data to recalibrate
# $svd_hist->{$rg} = long(@{$ALLHIST->{$rg}->{0}}[$MINQUAL..$MAXQUAL]);
# getting some odd type problem converting to pdl - so make the whole array int?
$svd_hist->{$rg} = pdl(to_int(@{$ALLHIST->{$rg}->{0}}[$MINQUAL..$MAXQUAL]));
if ($verbose == 3) {
$mu->record("After generating matrix");
print STDOUT "# Initial base data size for read group $rg: ", $alldata->{$rg}->shape, "\n";
}
if (!$matrix->isnull) {
($recalibrated->{$rg}, $pca1) = quality_svd($matrix, $svd_hist->{$rg}, $svd_bin, $last_count, $min_span);
if ($verbose) {
print STDOUT "# SVD fit (overall recalibration): $pca1\n";
}
$mu->record("After quality_svd");
}
if ($do_covariates) {
# now covariates - context
foreach $covariate (list($alldata->{$rg}->(5,)->uniq)) {
# next if !$covariate;
$ix = which($alldata->{$rg}->(5,)->flat == $covariate);
($matrix, $last_count) = make_matrix($alldata->{$rg}->(:,$ix), $covariate_binsize);
if (!$matrix->isnull) {
if (!$gatk) {
print OUT "# Covariate: $code_context{$covariate} ($covariate)\n";
}
$covariate_hist->{$rg}->{$code_context{$covariate}} = pdl(to_int(@{$ALLHIST->{$rg}->{$code_context{$covariate}}}[$MINQUAL..$MAXQUAL]));
($covariate_recalibrated->{$rg}->{$code_context{$covariate}}, $pca1) = quality_svd($matrix, $covariate_hist->{$rg}->{$code_context{$covariate}}, $covariate_binsize, $last_count, $min_span);
if ($verbose >= 2) {
print STDOUT "# SVD fit $code_context{$covariate} ($covariate): $pca1\n";
}
}
}
$mu->record("After context covariates");
# now covariates - position
foreach $covariate (list($alldata->{$rg}->(4,)->uniq)) {
$ix = which($alldata->{$rg}->(4,)->flat == $covariate);
($matrix, $last_count) = make_matrix($alldata->{$rg}->(:,$ix), $covariate_binsize);
if (!$matrix->isnull) {
if (!$gatk) {
print OUT "# Covariate: $covariate\n";
}
$covariate_hist->{$rg}->{$covariate} = pdl(to_int(@{$ALLHIST->{$rg}->{$covariate}}[$MINQUAL..$MAXQUAL]));
($covariate_recalibrated->{$rg}->{$covariate}, $pca1) = quality_svd($matrix, $covariate_hist->{$rg}->{$covariate}, $covariate_binsize, $last_count, $min_span);
if ($verbose >= 2) {
print STDOUT "# SVD fit (Position $covariate): $pca1\n";
}
}
}
$mu->record("After position covariates");
}
}
#
# output GATK formatted file
#
# first make sure we have something to output
@table = ();
$max_bases = 0;
foreach $rg (keys %$alldata) {
if (defined $svd_hist->{$rg} &&
defined $recalibrated->{$rg} &&
ref($recalibrated->{$rg}) eq "PDL" &&
ref($svd_hist->{$rg}) eq "PDL") {
push @table, $rg;
$max_bases = sum($svd_hist->{$rg}) if sum($svd_hist->{$rg}) > $max_bases;
if ($verbose == 3) {
print STDERR "Read group $rg recalibrated on ", $alldata->{$rg}->getdim(1), " nonconsensus and matched consensus bases out of ", sum($svd_hist->{$rg}), " total bases.\n";
}
} else {
print STDERR "== Error ==\n";
print STDERR "Didn't get recalibration results. This is most likely because we don't have enough data. We need usually at least 5 rows to do an SVD.\n";
if (defined $svd_hist->{$rg} && ref($svd_hist->{$rg}) eq "PDL") {
print STDERR " -- For readgroup $rg, we looked at ", sum($svd_hist->{$rg}), " bases total.\n";
print STDERR " We identified ", $alldata->{$rg}->getdim(1), " nonconsensus and matched consensus bases to\n";
print STDERR " recalibrate on. With an svdbin size of $svd_bin, this gives ", int($alldata->{$rg}->getdim(1)/$svd_bin), " rows for an SVD.\n";
}
print STDERR "\n";
print STDERR "If you don't have enough data, then you can try expanding the region parameter\n";
print STDERR "or reducing the -svdbin parameter. If you don't see read group specific\n";
print STDERR "information above, then we probably have a problem with your bam file.\n";
print STDERR "If you're sure your bam file is ok then please contact the authors.\n";
print STDERR "Also, if you do have enough data (5 rows) for at least one of the read groups\n";
print STDERR "above and you are still getting this error message, please contact the authors.\n";
}
}
exit if !scalar(@table);
$max_bases = length($max_bases);
if ($gatk) {
&gatk_header($svd_hist, $MAXQUAL, $do_covariates, $max_bases);
@table = ("ReadGroup EventType EmpiricalQuality EstimatedQReported Observations Errors \n");
foreach $rg (keys %$recalibrated) {
next if !defined $svd_hist->{$rg};
next if ref($recalibrated->{$rg}) ne "PDL";
next if ref($svd_hist->{$rg}) ne "PDL";
push @table, gatk_table0($rginfo->{$rg}->{$rgfield}, pdl($MINQUAL..$MAXQUAL), $recalibrated->{$rg}, $svd_hist->{$rg}, $max_bases);
}
$left_fields = { 0 => 1, # ReadGroup
1 => 1, # EventType
2 => 0, # EmpiricalQuality
3 => 0, # EstimatedQReported
4 => 0, # Observations
5 => 0 }; # Errors
&clean_gatk_table($left_fields, \@table);
# subtract 1 from number of lines in table - we added the header
print OUT '#:GATKTable:6:' . (scalar(@table)-1) . ':%s:%s:%.4f:%.4f:%d:%.2f:;', "\n";
print OUT '#:GATKTable:RecalTable0:', "\n";
print OUT @table;
print OUT "\n";
@table = ("ReadGroup QualityScore EventType EmpiricalQuality Observations Errors \n");
foreach $rg (keys %$recalibrated) {
next if !defined $svd_hist->{$rg};
next if ref($recalibrated->{$rg}) ne "PDL";
next if ref($svd_hist->{$rg}) ne "PDL";
push @table, gatk_table1($rginfo->{$rg}->{$rgfield}, pdl($MINQUAL..$MAXQUAL), $recalibrated->{$rg}, $svd_hist->{$rg}, $max_bases);
}
$left_fields = { 0 => 1, # ReadGroup
1 => 0, # QualityScore
2 => 1, # EventType
3 => 0, # EmpiricalQuality
4 => 0, # Observations
5 => 0 }; # Errors
&clean_gatk_table($left_fields, \@table);
# subtract 1 from number of lines in table - we added the header
print OUT '#:GATKTable:6:' . (scalar(@table)-1) . ':%s:%s:%s:%.4f:%d:%.2f:;', "\n";
print OUT '#:GATKTable:RecalTable1:', "\n";
print OUT @table;
print OUT "\n";
@table = ("ReadGroup QualityScore CovariateValue CovariateName EventType EmpiricalQuality Observations Errors \n");
foreach $rg (keys %$covariate_recalibrated) {
if ($do_covariates) {
foreach $covariate (sort keys %{$covariate_recalibrated->{$rg}}) {
next if ref($covariate_recalibrated->{$rg}->{$covariate}) ne "PDL";
next if !defined $covariate_hist->{$rg}->{$covariate};
next if ref($covariate_hist->{$rg}->{$covariate}) ne "PDL";
next if $covariate =~ /\./;
push @table, gatk_table2($rginfo->{$rg}->{$rgfield}, pdl($MINQUAL..$MAXQUAL), $covariate_recalibrated->{$rg}->{$covariate}, $covariate_hist->{$rg}->{$covariate}, $covariate, $max_bases);
}
}
}
$left_fields = { 0 => 1, # ReadGroup
1 => 0, # QualityScore