/
shimmer.pl
executable file
·1638 lines (1413 loc) · 48.8 KB
/
shimmer.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 -w
#########################################################
# Author: Nancy F. Hansen
# Program: "Shimmer"
# Function: shimmer
# Program to use hypothesis testing to
# predict single-nucleotide somatic
# mutations using Fisher's Exact Test with
# multiple testing correction.
##########################################################
use strict;
use Getopt::Long;
#use Pod::Usage;
use File::Temp qw /tempfile tempdir /;
use vars qw($VERSION);
our %Opt;
our $R_EXE = 'R';
our $ANNOVAR_EXE = 'annotate_variation.pl';
our @SOM_COLORS = ( {'power' => 0.0, 'color' => '255,0,0'}, # red
{'power' => 0.4, 'color' => '255,100,0'}, # orange
{'power' => 0.6, 'color' => '255,255,0'}, # yellow
{'power' => 0.8, 'color' => '0,255,0'}, # green
{'power' => 0.9, 'color' => '0,0,255'} ); # blue
$| = 1; # let's see output right away!
my $Id = q$Id:$;
$VERSION = sprintf "%.4f", substr(q$Rev:10000$, 4)/10000;
my $program_name = $0;
if ($program_name !~ /^\//) { # add path
my $path = `pwd`;
chomp $path;
$program_name = "$path/$program_name";
}
my $short_program_name = $program_name;
$short_program_name =~ s:.*/::; # without path
my $Usage = "Usage: $short_program_name <--region chr1:1000-2000> <--bedfile bed file of regions> <--ref reference fasta> <bam file from normal sample> <bam file from mutated sample>\nFor more information, type \"perldoc $short_program_name\".";
my $printcounts_exe = "printCompCounts";
process_commandline();
($#ARGV == 1)
or die "$Usage";
my $bam1 = $ARGV[0];
my $bam2 = $ARGV[1];
my $ref_fasta = $Opt{'ref'};
my $region = $Opt{'region'};
my $bedfile = $Opt{'bedfile'};
my $minqual = $Opt{'minqual'}; # disregard any base with quality lower than minqual
my $mapqual = $Opt{'mapqual'}; # disregard any read with mapping quality lower than mapqual
my $min_indel_reads = $Opt{'minindel'}; # disregard any indel without this total number of reads' coverage (in both samples)
if ($Opt{'counts'}) {
# check files:
foreach my $file ($ref_fasta, $bam1, $bam2) {
if (!(-r $file)) {
die "Can\'t read file $file!\n";
}
}
my $som_file = $Opt{'som_file'};
my $het_file = $Opt{'het_file'};
my $indel_file = $Opt{'indel_file'};
if (!$som_file || !$het_file || !(-e $som_file) || !(-e $het_file)) { # need to generate count files
# print counts of different alleles at all interesting positions
print_counts($ref_fasta, $bam1, $bam2, $region, $bedfile, $minqual, $mapqual, $som_file, $het_file, $indel_file, $printcounts_exe);
}
# test counts for significance with Fisher's exact test (without mult testing corr)
test_counts($som_file, $het_file, $indel_file);
}
elsif ($Opt{'bh'}) {
# apply Benjamini-Hochberg to determine cutoff for significance
my $max_q = $Opt{'max_q'};
my $test_fof = $Opt{'test_fof'};
my $outfile = $Opt{'outfile'};
my $vsfile = $Opt{'vs_file'};
my $vcffile = $Opt{'vcf_file'};
if (!(-r $test_fof)) {
die "Cannot read file $test_fof to apply B-H correction!\n";
}
bh_correct_tests($test_fof, $max_q, $outfile);
write_vs_file($outfile, $vsfile) if ($vsfile);
write_vcf_file($outfile, $vcffile) if ($vcffile);
}
elsif ($Opt{'annotate'}) {
my $annovar_db = $Opt{'annovardb'};
my $vs_file = $Opt{'vs_file'};
my $ann_vs_file = $Opt{'outfile'};
my $buildver = $Opt{'buildver'};
annotate_variants($annovar_db, $buildver, $vs_file, $ann_vs_file);
}
elsif ($Opt{'covg'}) {
my $input_file = $Opt{'input'}
or die "Must specify input file with --input option when running $0 -covg\n";
my $outdir = $Opt{'outdir'}
or die "Must specify output directory with --outdir option when running $0 --covg\n";
calc_power_file($input_file, $outdir, $bam1, $bam2, $ref_fasta, $printcounts_exe);
}
else {
run_shimmer($program_name, $ref_fasta, $bam1, $bam2, $region, $bedfile, $minqual);
}
## Subroutine to run all of the steps of Shimmer
sub run_shimmer {
my $shimmer = shift;
my $ref_fasta = shift;
my $bam1 = shift;
my $bam2 = shift;
my $region = shift;
my $bedfile = shift;
my $minqual = shift;
if ($Opt{'outdir'} && !(-e $Opt{'outdir'})) {
mkdir $Opt{'outdir'}
or die "Couldn\'t create $Opt{'outdir'}: $!\n";
}
my $tmpdir = $Opt{'outdir'} || tempdir( "run_shimmer_XXXXXX", DIR => '.' );
if ($tmpdir !~ /^\//) {
my $pwd = `pwd`;
chomp $pwd;
$tmpdir = "$pwd/$tmpdir";
}
if ((!$Opt{'som_file'}) || (!$Opt{'het_file'})) {
my $command = "$shimmer --counts --ref $ref_fasta $bam1 $bam2 --min_som_reads $Opt{min_som_reads} --som_file $tmpdir/som_counts.txt --het_file $tmpdir/het_counts.txt --indel_file $tmpdir/indel_counts.txt";
$command .= " --region $region" if ($region);
$command .= " --bedfile $bedfile" if ($bedfile);
$command .= " --minqual $minqual" if ($minqual);
$command .= " --mapqual $mapqual" if ($mapqual);
$command .= " --minindel $min_indel_reads" if ($min_indel_reads);
$command .= " --testall" if ($Opt{'testall'});
print "$command\n";
system($command) == 0
or die "Failed to run $shimmer --counts!\n";
}
if (!$Opt{'skip_tests'}) {
my $max_q = $Opt{'max_q'};
open SOMFOF, ">$tmpdir/som_counts.fof"
or die "Couldn\'t open $tmpdir/som_counts.fof for writing: $!\n";
my $test_output = $Opt{'som_file'} || "$tmpdir/som_counts.txt";
$test_output =~ s/\.txt$//;
$test_output .= '.tests.txt';
print SOMFOF "$test_output\n";
close SOMFOF;
my $command = "$shimmer --max_q $max_q --test_fof $tmpdir/som_counts.fof --bh --vs_file $tmpdir/somatic_diffs.vs --vcf_file $tmpdir/somatic_diffs.vcf --outfile $tmpdir/som_counts.bh.txt $bam1 $bam2";
$command .= " --testall" if ($Opt{'testall'});
print "$command\n";
(system("$command") == 0)
or die "Failed to run $command!\n";
open INDELFOF, ">$tmpdir/indel_counts.fof"
or die "Couldn\'t open $tmpdir/indel_counts.fof for writing: $!\n";
my $indel_test_output = $Opt{'indel_file'} || "$tmpdir/indel_counts.txt";
$indel_test_output =~ s/\.txt$//;
$indel_test_output .= '.tests.txt';
print INDELFOF "$indel_test_output\n";
close INDELFOF;
(system("$shimmer --max_q $max_q --test_fof $tmpdir/indel_counts.fof --bh --vs_file $tmpdir/somatic_indels.vs --outfile $tmpdir/indel_counts.bh.txt $bam1 $bam2") == 0)
or die "Failed to run $shimmer --test_fof $tmpdir/indel_counts.fof!\n";
if ($Opt{'annovardb'}) {
my $annovardb = $Opt{'annovardb'};
my $buildver = $Opt{'buildver'};
(system("$shimmer --annotate --buildver $buildver --annovardb $annovardb --annovar $ANNOVAR_EXE --vs_file $tmpdir/somatic_diffs.vs --outfile $tmpdir/somatic_diffs.ANN.vs $bam1 $bam2")==0)
or die "Failed to run $shimmer --annotate --buildver $buildver --annovardb $annovardb --annovar $ANNOVAR_EXE --vs_file $tmpdir/somatic_diffs.vs --outfile $tmpdir/somatic_diffs.ANN.vs $bam1 $bam2: $!\n";
(system("$shimmer --annotate --buildver $buildver --annovardb $annovardb --annovar $ANNOVAR_EXE --vs_file $tmpdir/somatic_indels.vs --outfile $tmpdir/somatic_indels.ANN.vs $bam1 $bam2")==0)
or die "Failed to run $shimmer --annotate --buildver $buildver --annovardb $annovardb --annovar $ANNOVAR_EXE --vs_file $tmpdir/somatic_indels.vs --outfile $tmpdir/somatic_indels.ANN.vs $bam1 $bam2: $!\n";
}
}
if ($Opt{'power'}) {
my $run_string = "$shimmer --input $tmpdir/som_counts.bh.txt --outdir $tmpdir --covg --ref $ref_fasta $bam1 $bam2";
system("$run_string") == 0
or die "Couldn\'t run $run_string\n";
}
} ## end run_shimmer
sub print_counts {
my $ref_fasta = shift;
my $bam1 = shift;
my $bam2 = shift;
my $region = shift;
my $bedfile = shift;
my $minqual = shift;
my $mapqual = shift;
my $som_file = shift;
my $het_file = shift;
my $indel_file = shift;
my $printcounts_exe = shift;
my $insert = $Opt{'insert'};
my $min_tumor_reads = $Opt{'min_som_reads'};
my $ra_het_count_limits = read_min_max_data(); # store limits of different genotypes
# call mpileup (via the c-script "printCompCounts"), and select sites that are independent, but have enough coverage/diversity to be informative
my $printcounts_call = "$printcounts_exe -bam1 $bam1 -bam2 $bam2 -fasta $ref_fasta";
$printcounts_call .= " -region $region" if ($region);
$printcounts_call .= " -bedfile $bedfile" if ($bedfile);
$printcounts_call .= " -minqual $minqual" if ($minqual);
$printcounts_call .= " -mapqual $mapqual" if ($mapqual);
print "Calling $printcounts_call\n";
open COUNTS, "$printcounts_call | "
or die "Couldn\'t execute $printcounts_call!\n";
open SOM, ">$som_file"
or die "Couldn\'t open $som_file for writing: $!\n";
open INDELS, ">$indel_file"
or die "Couldn\'t open $indel_file for writing: $!\n";
open CNV, ">$het_file"
or die "Couldn\'t open $het_file for writing: $!\n";
my ($cur_chr, $cur_pos, $cur_win_start, $cur_win_end, $best_geno, $best_cov, $best_string);
while (<COUNTS>) {
chomp;
if (/^#Indels/) {
my ($indel, $chr, $pos, $ref, $total1, $total2, $indel_string, $indel1, $indel2) = split /\t/, $_;
my $nonindel1 = $total1 - $indel1;
my $nonindel2 = $total2 - $indel2;
next if ($nonindel1 < 0 || $nonindel2 < 0); # skip ugly regions for now
my $geno = call_genotype($indel1, $total1, $ra_het_count_limits);
if (($total1 >= $min_indel_reads) && ($indel1 + $indel2 >= $min_indel_reads)) {
print INDELS "$indel\t$chr\t$pos\t$ref\t$nonindel1\t$nonindel2\t$indel_string\t$indel1\t$indel2\t$geno\n";
}
next;
}
my ($chr, $pos, $ref_base, $base1, $normal1_count, $tumor1_count, $base2, $normal2_count, $tumor2_count) = split /\t/, $_;
$ref_base = uc $ref_base;
my $total_norm = $normal1_count + $normal2_count;
my $total_tumor = $tumor1_count + $tumor2_count;
my $total_alt = ($base2 eq $ref_base) ? $normal1_count + $tumor1_count : $normal2_count + $tumor2_count;
my $normal_ref = ($base2 eq $ref_base) ? $normal2_count : $normal1_count;
my $tumor_ref = ($base2 eq $ref_base) ? $tumor2_count : $tumor1_count;
my $normal_alt = ($base2 eq $ref_base) ? $normal1_count : $normal2_count;
my $tumor_alt = ($base2 eq $ref_base) ? $tumor1_count : $tumor2_count;
my $alt_base = ($base2 eq $ref_base) ? $base1 : $base2;
my $first_base = ($base2 eq $ref_base) ? $base2 : $base1;
my $geno = call_genotype($normal_alt, $total_norm, $ra_het_count_limits);
# first check for potential somatic alterations:
if (($total_norm >= $min_tumor_reads) && ($total_tumor >= $min_tumor_reads) && ($total_alt >= $min_tumor_reads)) {
print SOM "$chr\t$pos\t$ref_base\t$first_base\t$normal_ref\t$tumor_ref\t$alt_base\t$normal_alt\t$tumor_alt\t$geno\n";
}
next if ($geno eq 'und');
# then check if this position is a potential "best position" in its window:
if (!$cur_win_start) {
$cur_chr = $chr;
$cur_win_start = $pos;
$cur_win_end = $pos + $insert;
}
if (($chr ne $cur_chr) || ($pos > $cur_win_end)) { # process old window, create new
print CNV "$best_string";
$best_string = '';
$best_geno = '';
$best_cov = '';
$cur_chr = $chr;
$cur_win_start = $pos;
$cur_win_end = $pos + $insert;
}
# replace best string, if appropriate:
if ((!$best_string) || ($geno eq $best_geno && $total_norm > $best_cov) || ($best_geno ne 'het' && $geno eq 'het')) {
$best_string = "$chr\t$pos\t$ref_base\t$first_base\t$normal_ref\t$tumor_ref\t$alt_base\t$normal_alt\t$tumor_alt\t$geno\n";
$best_geno = $geno;
$best_cov = $total_norm;
}
}
# print final window:
print CNV "$best_string";
close COUNTS;
close CNV;
close SOM;
close INDELS;
}
sub read_min_max_data {
my $ra_min_max = [];
while (<DATA>) {
next if ((/^#/) || (/^COV/));
chomp;
if (/^(\d+)\s(\d+)\s(\d+)\s(\d+)\s(\d+)$/) {
my ($cov, $max_hom, $min_het, $max_het, $min_hnr) = ($1, $2, $3, $4, $5);
$ra_min_max->[$cov] = { 'max_hom' => $max_hom,
'min_het' => $min_het,
'max_het' => $max_het,
'min_hnr' => $min_hnr };
}
}
return $ra_min_max;
}
sub call_genotype {
my $alt_count = shift;
my $total_count = shift;
my $ra_count_limits = shift;
my $rh_limits;
if ($total_count > $#{$ra_count_limits}) {
$rh_limits = {'max_hom' => 17,
'min_het' => 0.20*$total_count,
'max_het' => 0.80*$total_count };
}
else {
$rh_limits = $ra_count_limits->[$total_count];
}
if ($rh_limits) {
if ($alt_count <= $rh_limits->{'max_hom'}) {
return 'hom';
}
elsif ($alt_count >= $rh_limits->{'min_het'} &&
$alt_count <= $rh_limits->{'max_het'}) {
return 'het';
}
}
return 'und';
}
sub test_counts {
# test counts for significance with Fisher's exact test (without mult testing corr)
my $som_file = shift;
my $het_file = shift;
my $indel_file = shift;
my $test_opt = ($Opt{'testall'}) ? 'all' : 'hom';
foreach my $file ($som_file, $het_file, $indel_file) {
my $type = ($file eq $som_file) ? 'som' :
($file eq $het_file) ? 'het' : 'indel';
my $r_command_file = "$file.r";
open COM, ">$r_command_file"
or die "Couldn\'t open $r_command_file for writing: $!\n";
print COM <<"DOC";
library("statmod");
con <- file("$file", "r");
while (length(input <- readLines(con, n=1000)) > 0) {
for (i in 1:length(input)) {
line <- input[i];
linevec <- strsplit(line, split="\\t");
allele_counts <- c(linevec[[1]][[5]], linevec[[1]][[6]], linevec[[1]][[8]], linevec[[1]][[9]]);
allele_counts <- as.numeric(allele_counts);
geno <- linevec[[1]][[10]];
dim(allele_counts) <- c(2,2);
if ((("$type" == "som") && ((geno == "hom") || (geno == "und"))) || (("$type"=="som") && ("$test_opt"=="all")) || (("$type" == "het") && (geno == "het")) || (("$type" == "indel") && (geno == "hom"))) {
exact_result <- fisher.test(allele_counts);
pvalue <- exact_result["p.value"];
output <- paste(linevec[[1]][[1]], linevec[[1]][[2]], linevec[[1]][[3]], linevec[[1]][[4]], linevec[[1]][[5]], linevec[[1]][[6]], linevec[[1]][[7]], linevec[[1]][[8]], linevec[[1]][[9]], linevec[[1]][[10]], pvalue, sep=":");
}
else {
output <- paste(linevec[[1]][[1]], linevec[[1]][[2]], linevec[[1]][[3]], linevec[[1]][[4]], linevec[[1]][[5]], linevec[[1]][[6]], linevec[[1]][[7]], linevec[[1]][[8]], linevec[[1]][[9]], linevec[[1]][[10]], "NA", sep=":");
}
print(output, quote=FALSE, max.levels=0);
}
}
DOC
close COM
or die "Couldn\'t close file $r_command_file: $!\n";
my $r_pipe = "$R_EXE --file=$r_command_file | ";
open ROUTPUT, "$r_pipe"
or die "Couldn\'t open pipe to $r_pipe!\n";
my $test_output = $file;
$test_output =~ s/\.txt$//;
$test_output .= '.tests.txt';
open TEST, ">$test_output"
or die "Couldn\'t open $test_output for writing: $!\n";
my $last = 0;
my @vals = ();
while (<ROUTPUT>) {
if (/^\[1\]\s(.+)$/) {
my $output = $1;
$output =~ s/:\s*/\t/g;
print TEST "$output\n";
}
}
while (<ROUTPUT>) {
next;
}
close TEST;
close ROUTPUT;
}
}
# subroutine to apply Benjamini-Hochberg procedure to p-values to obtain q values
sub bh_correct_tests {
my $test_fof = shift;
my $max_q = shift;
my $outfile = shift;
my @files = ();
open FILES, "$test_fof"
or die "Couldn\'t open $test_fof for reading: $!\n";
while (<FILES>) {
chomp;
push @files, $_;
}
close FILES;
my @lines = ();
my @pvalues = ();
my $no_tests = 0;
my $line_index = 0;
foreach my $test_file (@files) {
open TESTS, $test_file
or die "Couldn\'t open $test_file for reading: $!\n";
while (<TESTS>) {
my $line = $_;
push @lines, $line;
chomp $line;
my @fields = split /\s/, $line;
my $geno = $fields[$#fields - 1];
my $pvalue = $fields[$#fields];
$no_tests++ if (($pvalue ne 'NA') || ($geno eq 'und') || ($Opt{'acctests'}));
if (($pvalue ne 'NA') && ((!$max_q) || ($pvalue <= $max_q))) {
push @pvalues, {'pvalue' => $pvalue, 'line_index' => $line_index};
}
$line_index++;
}
close TESTS;
}
print "Applying Benjamini-Hochberg correction to somatic change predictions with $no_tests tests. Results in $outfile.\n";
# now order and assign q-values:
my $index = 1;
my @lines_to_print = ();
my @sorted_pvalues = sort bypthenna @pvalues;
foreach my $rh_line (@sorted_pvalues) {
my $pvalue = $rh_line->{'pvalue'};
my $qvalue = ($pvalue eq "NA") ? "NA" : $no_tests*$rh_line->{'pvalue'}/$index;
$qvalue = 1.0 if ($qvalue > 1.0);
last if (($max_q) && ($qvalue ne "NA") && ($qvalue > $max_q));
$index++;
$lines[$rh_line->{'line_index'}] =~ s/\n/\t$qvalue\n/;
my $this_line = $lines[$rh_line->{'line_index'}];
push @lines_to_print, {'line_index' => $rh_line->{'line_index'}, 'line' => $lines[$rh_line->{'line_index'}]};
}
sub bypthenna {
my $avalue = $a->{'pvalue'};
my $bvalue = $b->{'pvalue'};
if ($avalue eq "NA") {
return 1;
}
elsif ($bvalue eq "NA") {
return -1;
}
else {
return $avalue <=> $bvalue;
}
}
# and write out the lines to stdout:
open OUT, ">$outfile"
or die "Couldn\'t open $outfile for writing: $!\n";
foreach my $line (sort {$a->{'line_index'} <=> $b->{'line_index'}} @lines_to_print) {
print OUT $line->{'line'};
}
close OUT;
} # end bh_correct_tests
sub write_vs_file {
my $outfile = shift;
my $vsfile = shift;
my $indel_flag = ($vsfile =~ /somatic_indels/) ? 1 : 0;
open SOM, "$outfile"
or die "Couldn\'t open $outfile for reading: $!\n";
open VS, ">$vsfile"
or die "Couldn\'t open $vsfile for writing: $!\n";
print VS "Index\tChr\tLeftFlank\tRightFlank\tref_allele\tvar_allele\tmuttype\tnormal_covg\ttumor_covg\tnormal_ratio\ttumor_ratio\tq_value\n";
my $index = 1;
while (<SOM>) {
chomp;
if (!$indel_flag) {
my ($chr, $pos, $ref, $allele1, $norm1_count, $tumor1_count, $allele2, $norm2_count, $tumor2_count, $gen, $pvalue, $qvalue) = split /\t/, $_;
$ref = uc $ref;
my $normal_covg = $norm1_count + $norm2_count;
my $tumor_covg = $tumor1_count + $tumor2_count;
my $normal_ratio = $norm2_count/$normal_covg;
my $tumor_ratio = $tumor2_count/$tumor_covg;
my $lfe = $pos - 1;
my $rfs = $pos + 1;
print VS "$index\t$chr\t$lfe\t$rfs\t$ref\t$allele2\tSNP\t$normal_covg\t$tumor_covg\t$normal_ratio\t$tumor_ratio\t$qvalue\n";
$index++;
}
else { # indel file has different format
my ($indels, $chr, $pos, $ref, $normref_count, $tumorref_count, $indel_string, $normdiv_count, $tumordiv_count, $geno, $pvalue, $qvalue) = split /\t/, $_;
my $indel_type = ($indel_string =~ /^\+/) ? 'ins' : 'del';
$indel_string =~ s/^[+-]\d+//;
my $indel_length = length($indel_string);
#my $lfe = ($indel_type eq 'ins') ? $pos : $pos - 1;
my $lfe = $pos;
my $rfs = ($indel_type eq 'ins') ? $pos + 1 : $pos + $indel_length + 1;
my $alt_string = ($indel_type =~ 'del') ? '*' : $indel_string;
my $ref_string = ($indel_type =~ 'del') ? $indel_string : '*';
my $normal_covg = $normref_count + $normdiv_count;
my $tumor_covg = $tumorref_count + $tumordiv_count;
my $normal_ratio = $normdiv_count/$normal_covg;
my $tumor_ratio = $tumordiv_count/$tumor_covg;
print VS "$index\t$chr\t$lfe\t$rfs\t$ref_string\t$alt_string\tINDEL\t$normal_covg\t$tumor_covg\t$normal_ratio\t$tumor_ratio\t$qvalue\n";
$index++;
}
}
close SOM;
close VS;
} ## end write_vs_file
sub write_vcf_file {
my $outfile = shift;
my $vcffile = shift;
open SOM, "$outfile"
or die "Couldn\'t open $outfile for reading: $!\n";
open VCF, ">$vcffile"
or die "Couldn\'t open $vcffile for writing: $!\n";
print VCF "##fileformat=VCFv4.1\n";
my ($sec, $min, $hour, $mday, $mon, $year ) = localtime();
$mon++;
$year += 1900;
printf VCF "##fileDate=%d%02d%02d\n", $year, $mon, $mday;
print VCF "##source=Shimmer\n";
# include info for RM flag for repeat-masked sequence:
print VCF "##INFO=<ID=RM,Number=0,Type=Flag,Description=\"Lower-case reference (probably masked for repeat)\">\n";
# included genotype id's:
print VCF "##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">\n";
#print VCF "##FORMAT=<ID=GQ,Number=1,Type=Integer,Description=\"Genotype Quality\">\n";
print VCF "##FORMAT=<ID=DP,Number=1,Type=Integer,Description=\"Read Depth\">\n";
# print required eight fields:
print VCF "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tNORMAL\tTUMOR\n";
my $index = 1;
while (<SOM>) {
chomp;
my ($chr, $pos, $ref, $allele1, $norm1_count, $tumor1_count, $allele2, $norm2_count, $tumor2_count, $gen, $pvalue, $qvalue) = split /\t/, $_;
my $normal_covg = $norm1_count + $norm2_count;
my $tumor_covg = $tumor1_count + $tumor2_count;
my $normal_ratio = $norm2_count/$normal_covg;
my $tumor_ratio = $tumor2_count/$normal_covg;
my $info_flag = ($ref eq uc $ref) ? '.' : 'RM';
my $qual_score = ($qvalue == 0) ? 999 : int(-10.0*log($qvalue)/log(10.0));
$qual_score = 0 if ($qual_score < 0);
$ref = uc $ref;
print VCF "$chr\t$pos\t\.\t$ref\t$allele2\t$qual_score\t.\t$info_flag\tGT:DP\t0/0:$normal_covg\t0/1:$tumor_covg\n";
$index++;
}
close SOM;
close VCF;
} ## end write_vcf_file
sub annotate_variants {
my $annovar_db = shift;
my $buildver = shift;
my $vs_file = shift;
my $ann_vs_file = shift;
# write Annovar input file:
open VS, "$vs_file"
or die "Couldn\'t open $vs_file: $!\n";
my $anv = "$vs_file.annovar.txt";
open ANV, ">$anv"
or die "Couldn\'t open $anv for writing: $!\n";
while (<VS>) {
chomp;
my ($index, $chr, $lfe, $rfs, $ref, $var, $muttype, $rest) = split /\t/, $_;
next if ($index eq 'Index');
my $pos = $lfe + 1;
if ($muttype eq 'SNP') {
print ANV "$chr\t$pos\t$pos\t$ref\t$var\t$index\n";
}
elsif ($muttype eq 'INDEL') {
$ref =~ s/\*/\-/;
$var =~ s/\*/\-/;
my ($left, $right);
if ($ref eq '-' && ($lfe == $rfs - 1)) {
$left = $lfe + 1;
$right = $left;
}
else {
$left = $lfe + 1;
$right = $rfs - 1;
}
print ANV "$chr\t$left\t$right\t$ref\t$var\t$index\n";
}
}
close ANV;
close VS;
my $annovar_cmd = "$ANNOVAR_EXE --buildver $buildver --geneanno --dbtype knowngene --hgvs $anv $annovar_db";
(system("$annovar_cmd") == 0)
or die "Some problem running $ANNOVAR_EXE!\n";
# parse output, add columns to VS file:
my $rh_function = {};
open VAR, "$anv.variant_function"
or die "Couldn\'t open $anv.variant_function: $!\n";
while (<VAR>) {
chomp;
my @fields = split /\t/;
$rh_function->{$fields[7]} = {'loc_type' => $fields[0], 'gene' => $fields[1]};
}
close VAR;
my $rh_cons = {};
open EXON, "$anv.exonic_variant_function"
or die "Couldn\'t open $anv.exonic_function: $!\n";
while (<EXON>) {
chomp;
my @fields = split /\t/;
my $type = $fields[1];
$type =~ s/\s/_/g;
$rh_cons->{$fields[8]} = {'type' => $type, 'cons' => $fields[2]};
}
close EXON;
print "About to write annotated file $vs_file!\n";
# now write annotated VS file with extra columns:
open VS, "$vs_file"
or die "Couldn\'t open $vs_file: $!\n";
open ANN, ">$ann_vs_file"
or die "Couldn\'t open $ann_vs_file for writing: $!\n";
while (<VS>) {
chomp;
my @fields = split /\t/, $_;
my @new_fields = @fields[0..6];
if ($new_fields[0] eq 'Index') {
push @new_fields, qw( type Gene_name loc_type consequence );
}
else {
my $index = $new_fields[0];
my $type = $rh_cons->{$index}->{'type'} || $rh_function->{$index}->{'loc_type'} || 'NA';
my $gene = $rh_function->{$index}->{'gene'} || 'NA';
my $loc_type = $rh_function->{$index}->{'loc_type'} || 'NA';
my $consequence = $rh_cons->{$index}->{'cons'} || 'NA';
push @new_fields, ($type, $gene, $loc_type, $consequence);
}
push @new_fields, @fields[7..$#fields];
my $annotated_string = join "\t", @new_fields;
print ANN "$annotated_string\n";
}
close ANN;
close VS;
} ## end annotate_variants
sub calc_power_file {
my $input_file = shift;
my $outdir = shift;
my $bam1 = shift;
my $bam2 = shift;
my $ref_fasta = shift;
my $printcounts_exe = shift;
# call mpileup (via the c-script "printCompCounts"), and record bed regions for somatic and CNA power values.
my $printcounts_call = "$printcounts_exe -bam1 $bam1 -bam2 $bam2 -fasta $ref_fasta";
my $perc_sum = 0;
my $perc_no = 0;
open SOM, "$input_file"
or die "Couldn\'t open $input_file: $!\n";
while (<SOM>) {
chomp;
my ($chr, $pos, $ref, $base1, $norm1, $tumor1, $base2, $norm2, $tumor2, $geno) = split /\t/, $_;
$perc_sum += ($norm1 + $norm2)/($norm1 + $tumor1 + $norm2 + $tumor2);
$perc_no++;
}
close SOM;
my $tumor_perc_estimate = ($perc_no) ? int(100*$perc_sum/$perc_no*2) : 100;
$tumor_perc_estimate = 100 if ($tumor_perc_estimate > 100);
my $purity = int($perc_sum/$perc_no*100);
my $rh_somatic_power = read_somatic_power($purity);
open COUNTS, "$printcounts_call | "
or die "Couldn\'t execute $printcounts_call!\n";
my ($current_chr, $current_start, $current_pos, $current_color);
open SOMBED, ">$outdir/somatic_power.bed"
or die "Couldn\'t open $outdir/somatic_power.bed for writing: $!\n";
while (<COUNTS>) {
my ($chr, $pos, $ref_base, $base1, $normal1_count, $tumor1_count, $base2, $normal2_count, $tumor2_count) = split /\t/, $_;
my $total_norm = $normal1_count + $normal2_count;
my $total_tumor = $tumor1_count + $tumor2_count;
my $power_color = power_color($rh_somatic_power, $total_norm, $total_tumor);
if (!$current_color || !$current_chr || $chr ne $current_chr || $pos != $current_pos + 1 || $power_color ne $current_color) {
# write out old entry:
if ($current_color) {
print SOMBED "$current_chr\t$current_start\t$current_pos\t-\t-\t-\t-\t-\t$current_color\n";
}
$current_start = $pos - 1;
$current_color = $power_color;
}
$current_chr = $chr;
$current_pos = $pos;
}
close COUNTS;
if ($current_color) {
print SOMBED "$current_chr\t$current_start\t$current_pos\t-\t-\t-\t-\t-\t$current_color\n";
}
close SOMBED;
close COUNTS;
} # end calc_power_file
sub read_somatic_power {
my $purity = shift;
my $som_power_file = "/home/nhansen/projects/shimmer/power_graphs/somatic_power_table.txt";
open SOM, $som_power_file
or die "Couldn\'t open $som_power_file: $!\n";
my $rh_som_power = {};
my $best_purity;
while (<SOM>) {
chomp;
my ($perc_tumor, $normal_reads, $tumor_reads, $power) = split;
next if ($perc_tumor > $purity);
if (!$best_purity) {
$best_purity = $perc_tumor;
}
elsif ($perc_tumor != $best_purity) {
last;
}
$rh_som_power->{$normal_reads}->{$tumor_reads} = $power;
$rh_som_power->{$normal_reads}->{'max'} = $tumor_reads;
$rh_som_power->{'max'} = $normal_reads;
}
close SOM;
return $rh_som_power;
}
sub power_color {
my $rh_power = shift;
my $normal_total = shift;
my $tumor_total = shift;
my $normal_tens = 10*int($normal_total/10);
my $tumor_tens = 10*int($tumor_total/10);
$normal_tens = $rh_power->{'max'} if ($normal_tens > $rh_power->{'max'});
my $power = 0;
if ($rh_power->{$normal_tens} && $rh_power->{$normal_tens}->{$tumor_tens}) {
$power = $rh_power->{$normal_tens}->{$tumor_tens};
}
elsif ($rh_power->{$normal_tens}) {
if ($tumor_tens > $rh_power->{$normal_tens}->{'max'}) {
$power = $rh_power->{$normal_tens}->{'max'};
}
}
my $power_color;
for (my $i=0; $i<= $#SOM_COLORS; $i++) {
if ($power >= $SOM_COLORS[$i]->{'power'}) {
$power_color = $SOM_COLORS[$i]->{'color'};
}
}
return $power_color;
}
sub calculate_depth_norm {
my $file = shift;
open DIFFS, $file
or die "Couldn\'t open $file: $!\n";
my $sum_ratio = 0;
my $sumsq_ratio = 0;
my $total_points = 0;
my @norm_ratios = ();
while (<DIFFS>) {
chomp;
my @fields = split /\t/, $_;
my $line = $_;
my $no_fields = @fields;
if ($no_fields == 12) { # data line
my $pvalue = $fields[10];
if (($pvalue eq 'NA') || ($pvalue < 0.5)) {
next;
}
my $normal_a = $fields[4];
my $tumor_a = $fields[5];
my $normal_b = $fields[7];
my $tumor_b = $fields[8];
#next if (!($normal_a + $normal_b)); # need some tumor reads to assess anything
next if (($normal_a + $normal_b) < 100 || ($tumor_a + $tumor_b) < 100); # need some reads to assess anything
my $this_ratio = ($normal_a + $normal_b) / ($tumor_a + $tumor_b);
$sum_ratio += $this_ratio;
$sumsq_ratio += $this_ratio**2;
push @norm_ratios, $this_ratio;
$total_points++;
}
}
close DIFFS;
if (!$total_points) {
die "Unable to calculate a normalization ratio for depths--too few \"normal\" points!\n";
}
my @sorted_norm_ratios = sort {$a <=> $b} @norm_ratios;
my $median_ratio = $sorted_norm_ratios[int($#sorted_norm_ratios/2)];
my $avg_ratio = $sum_ratio/$total_points;
print "Calculated average read depth ratio of $avg_ratio, median $median_ratio (normal divided by tumor).\n";
return $avg_ratio;
} # end calculate_depth_norm
sub process_commandline {
# Set defaults here
%Opt = (
max_q => 0.05, insert => 300, min_som_reads => 10, minindel => 10
);
GetOptions(\%Opt, qw(
region=s bedfile=s ref=s counts som_file=s indel_file=s
het_file=s bh vs_file=s vcf_file=s max_q=f test_fof=s
outfile=s outdir=s input=s plots power covg minqual=i
min_som_reads=i minindel=i mapqual=i acctests testall
insert=i annovar=s annovardb=s buildver=s skip_tests
annotate help+ version verbose
)) || pod2usage(0);
if ($Opt{help}) { pod2usage(verbose => $Opt{help}); }
if ($Opt{version}) { die "$0, ", q$Revision: $, "\n"; }
# argument checking:
if ($Opt{'annovardb'}) {
$ANNOVAR_EXE = $Opt{'annovar'} || `which $ANNOVAR_EXE`;
chomp $ANNOVAR_EXE;
if (!$ANNOVAR_EXE || !(-e $ANNOVAR_EXE)) {
die "Cannot find $ANNOVAR_EXE--ignoring opt --annovardb!\n";
}
if (!$Opt{'buildver'}) {
die "Must specify a build version (e.g., hg18) for annovar with --buildver\n";
}
}
}
=pod
=head1 NAME
shimmer.pl - call somatic single base changes from matched tumor and normal
next generation sequences.
=head1 SYNOPSIS
Tally counts of alleles in two BAM files, and write out data for sites with
unexpectedly large deviations in allele frequencies, controlling the false
discovery rate (FDR) using the Benjamini-Hochberg procedure:
shimmer.pl [options] <normal_bam_file> <tumor_bam_file> --ref <ref_fasta_file>
Run shimmer.pl -man for a detailed description of options and the output files.
=head1 DESCRIPTION
The script creates a randomly named directory (run_shimmer_XXXXXX) in the
user's current working directory, and reads through the two BAM files
provided as options with samtools mpileup, recording the normal sample's
genotype, as well as the counts of the two most frequently seen alleles at
each site. It then uses the R "statmod" library to calculate p-values with
the Fisher's exact test on each site where a minimum threshold of alternate
allele copies are seen (see --min_som_reads option).
Once all p-values have been calculated, shimmer.pl uses the Benjamini-Hochberg
procedure to report only changes with a false discovery rate below
the specified maximum FDR (see --max_q option). The single-nucleotide
variants are reported in VarSifter and VCF formats in the files
"somatic_diffs.vs" and "somatic_diffs.vcf", respectively.
=head1 INPUT
The first and second arguments to shimmer are the paths of two BAM-formatted
files of aligned sequencing reads. These files must be sorted
using samtools prior to running shimmer, and indexed if the --region option
wil be used.
The path of a valid, fasta-formatted file for the reference sequence must
be passed with the option --ref. This fasta file must have a corresponding
samtools index file with the same name except for an appended ".fai" if the
--region option will be used.
=head1 OPTIONS
=over 5
=item B<--region> I<chr> or
=item B<--region> I<chr:start-end>
This option specifies a region as a reference entry (chromosome), optionally
followed by a position range, and causes the program to limit somatic call to
only that region. By default, the program calls variants in all regions
that covered by reads in both BAM files.
=item B<--bedfile> I<bedfilename>
This option specifies the path of a BED formatted file containing regions to
be tested for somatic variants. Limiting regions with this option can increase
power to detect somatic variation by reducing the number of tests performed.
=item B<--ref> I<reference_fasta_file>
This option specifies the reference file to which the reads in the BAM files
were aligned. It is a required option.
=item B<--minqual> I<min_base_quality_score>
This option specifies a minimum phred quality score to be required for
read bases to be included in the counts for the Fisher's exact tests. By
default, all bases are included.
=item B<--mapqual> I<min_mapping_quality_score>
This option specifies a minimum read mapping quality score to be required for
a read's bases to be included in the counts for the Fisher's exact tests. By
default, all reads' bases are included.
=item B<--max_q> I<max_acceptable_FDR>
This option specifies the maximum FDR level to be set for the
Benjamini-Hochberg procedure for multiple testing correction. A value of 0
will cause shimmer to report all tests including those with q values equal to