-
Notifications
You must be signed in to change notification settings - Fork 2
/
bb.coverage
executable file
·1643 lines (1487 loc) · 67.6 KB
/
bb.coverage
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
#----------------------------------------------------------#
# Author: Douglas Senalik [email protected] #
#----------------------------------------------------------#
# "Black Box" program series
=bb
Create a plot of coverage of raw reads on a reference sequence
=cut bb
use strict;
use warnings;
use Getopt::Long; # for getting command line parameters
use Unix::Processors; # for default number of cpu cores to use
use File::Temp qw/ tempfile /;
# version 1.0 July 14, 2016
# version 1.1 Jan 19, 2017 - update because of changes to coverageBed parameters as of
# v2.24.0 (27-May-2015) i.e. "We have changed the behavior
# of the coverage tool such that it is consistent with the
# other tools. Specifically, coverage is now computed for
# the intervals in the A file based on the overlaps with
# the B file, rather than vice versa"
# version 1.2 Dec 8, 2019 - Sys::CPU no longer in CPAN, replaced with Unix::Processors,
# and add --noenhanced and --oneplot flags
############################################################
# configuration variables
############################################################
my $sffinfocmd = "/opt/454/bin/sffinfo"; # Roche program to extract FASTA from sff
my $makeblastdbcmd = "makeblastdb"; # program to compile BLAST database, can add path here if necessary
my $blastcmd = "blastn"; # program to perform BLAST search, can add path here if necessary
my $gnuplotcmd = "gnuplot"; # program to create plot
my $resizecmd = "convert"; # program to rescale image, convert is part of imagemagick
my $defaultdbname = "tmp.db"; # default blast database name
my $dbnamewithpath = ""; # blast database name including cache path
my $maxalignments = 2000000; # maximum number of alignments
my $defaultevalue = 0.01; # defaults for blastn
my $defaultlenmin = 200; # "
my $defaultpctmin = 90; # "
my $defaultgc = 101; # for optional gc plot, window size to calculate gc ratio
my $defaultformat = "png"; # graph image file format (for gnuplot)
my $defaultxlabel = 'Reference Sequence in b.p.';
my $defaultylabel = 'Coverage Depth';
my $defaultxsize = 1600; # default plot width
my $defaultysize = 600; # default plot height
my $tempfiletemplate = "bb.coverage.tmp.XXXX";
my $plotareabg = '#FFFFFF'; # color of plot area, currently hard coded to white
my $defaultmarkerlabelstagger = 5; # this many y positions for successive marker labels, set to 0 to disable
my $updateinterval = 10000; # progress update interval
my $defaultshown = 10; # default for --shown if no other value specified
my $procs = new Unix::Processors;
my $defaultnumcpu = int ($procs->max_physical * 0.75 + 0.26); # number of processors for blast step, defaults to approx 3/4 of processors
my $defaultshoworfs = 0.95; # fraction of Y axis for orfs plot
# colors for orf reading frames, order is -3 -2 -1 notused 1 2 3
my @orfcolor = ( '#377EB8', '#4DAF4A', '#984EA3', '#808080', '#FF7F00', '#A65628', '#E41A1C' );
my $defaultbowtiemode = "sensitive";
my $defaultfill = "#B0E0E6"; # fill color B0E0E6=powder blue
my $samtoolssortmem = "10000000000"; # 10 GBytes, default is 500000000 which is 500 MBytes
my $defaultmarkercolor = '#B0C4DE'; # LightSteelBlue
my $fontpath = "/usr/share/fonts/:/usr/share/fonts/dejavu:/usr/share/fonts/truetype/dejavu";
my $defaultpngfont = "DejaVuSans,9";
my $defaultpsfont = "Arial";
my $defaultmarkerlabelheight = '0.95';
############################################################
# global variables
############################################################
my $ansiup = "\033[1A"; # terminal control
(my $prognopath = $0) =~ s/^.*[\/\\]//;
my @reffullheaders = (); # reference FASTA headers
my @refsequences = (); # reference FASTA sequence ( used only for gc ratio )
my @reflengths = (); # lengths of reference sequences
my @refhdrkeys = (); # list of reference FASTA headers up to first space
my %refhdrhash = (); # hash of @refhdrkeys to find index, and to check for duplicates
my $tmpdir = "/tmp"; # becomes $cachename if a cache directory is specified
my @coverage = (); # array of arrays
my @greps; # to limit to only certain sequences in an input bam
my $calccoverage = 0; # 1 if need to calculate coverage by blast. 0 if using BED files
my %persequencemarkers; # from --parse procesing
my $orfdata = ""; # gnuplot commands for displaying orfs, insert into command file directly
my $permanentdb = 0; # true when using precompiled blast database
my @mergedlabels; # labels when using --oneplot
my $coverageby;
my $objcounter = 0;
############################################################
# command line parameters
############################################################
my @sffnames = (); # one or more sff files of raw reads
my $dbname = ""; # name of blast database
my @fastanames = (); # one or more FASTA files of raw reads
my @fastqnames = (); # one or more FASTQ files of raw reads
my @referencenames = (); # reference sequences in FASTA format
my @bamnames = (); # coverage from .bam files
my @bednames = (); # coverage already calculated in BED format
my @rochenames = (); # coverage to be extracted from 454PairAlign.txt from Roche mapper
my $outpath = ""; # graph image file output directory
my $image = ""; # image file name
my $noimage; # inhibit image creation
my $shown; # show tracts of this many consecutive N's on plot
my $cachename = ""; # directory name to save BLAST output
my $numcpu = $defaultnumcpu; # number of processors for blast step
my $htmlname = ""; # append some HTML code to this page
my $build = 0; # recalculate everything flag
my $wspacing = 0; # wiggle file flag and spacing
my $wname; # optional wiggle file name
my $whname; # optional wiggle name in header of wiggle file
my $lenmin = $defaultlenmin; # minimum blast hit total length
my $pctmin = $defaultpctmin; # minimum blast hit percent match
my $evalue = $defaultevalue; # e-value used for blast search
my $font = $defaultpngfont;
my $format = $defaultformat; # graph file format, e.g. "png"
my $noenhanced; # toggle for gnuplot noenhanced vs. enhanced
my $xsize = $defaultxsize; # plot width
my $ysize = $defaultysize; # plot height
my $xlabel = $defaultxlabel;
my $ylabel = $defaultylabel;
my $title;
my $xscale;
my $xtics;
my $mxtics;
my $xmin = 1; # plot x axis minimum
my $xmax; # plot x axis maximum, undefined = use auto scaling
my $ymin = 0; # plot y axis minimum
my $ymax; # plot y axis maximum, undefined = use auto scaling
my $nointlabel; # no internal label
my $nolegend; # no legend
my $leftcrop = 0;
my $rightcrop = 0;
my $thumbnail = 0; # make a thumbnail at this scale
my $oneplot; # all sequences on one plot
my $gc; # plot percent gc if defined, if value use that window size
my $transform; # experimental
my $fill;
my $showorfs; # plot orfs
my @markers;
my $markerlabelstagger = $defaultmarkerlabelstagger;
my $markerlabelheight = $defaultmarkerlabelheight;
my $bowtiemode = $defaultbowtiemode;
my $parse = 0; # parse header from bb.fastareorder --annotate
my $help = 0; # print help and exit
my $quiet = 0; # only show errors
my $debug = 0; # print extra debugging information
GetOptions (
"sff=s" => \@sffnames, # string
"fasta=s" => \@fastanames, # string
"fastq=s" => \@fastqnames, # string
"reference=s" => \@referencenames, # string
"grep=s" => \@greps, # string
"bam=s" => \@bamnames, # string
"bed=s" => \@bednames, # string
"roche=s" => \@rochenames, # string
"outpath=s" => \$outpath, # string
"image=s" => \$image, # string
"noimage" => \$noimage, # flag
"wiggle=i" => \$wspacing, # integer
"wigname=s" => \$wname, # string
"wigheadername=s"=> \$whname, # string
"shown|showN:i" => \$shown, # flag/integer
"orfs|showorfs:s"=> \$showorfs, # flag/real
"dbname=s" => \$dbname, # string
"cache=s" => \$cachename, # string
"cpu=i" => \$numcpu, # integer
"html=s" => \$htmlname, # string
"format=s" => \$format, # string
"noenhanced" => \$noenhanced, # flag
"oneplot" => \$oneplot, # flag
"font=s" => \$font, # string
"xsize=s" => \$xsize, # string (real)
"xtics=s" => \$xtics, # string (real)
"mxtics=s" => \$mxtics, # string (real)
"ysize=s" => \$ysize, # string (real)
"xscale=s" => \$xscale, # string (real)
"xmin=s" => \$xmin, # string (real)
"xmax=s" => \$xmax, # string (real)
"ymin=s" => \$ymin, # string (real)
"ymax=s" => \$ymax, # string (real)
"thumbnail=s" => \$thumbnail, # string (real)
"build" => \$build, # flag
"gc:i" => \$gc, # flag or value
"transform=s" => \$transform, # string (real)
"markers=s" => \@markers, # string array
"labelheight=s" => \$markerlabelheight, # string (real)
"stagger=i" => \$markerlabelstagger,# integer
"fill:s" => \$fill, # flag or color
"lenmin=s" => \$lenmin, # string (real)
"pctmin=s" => \$pctmin, # string (real)
"nointernallabel"=> \$nointlabel, # flag
"nolegend" => \$nolegend, # flag
"title=s" => \$title, # flag
"parse" => \$parse, # flag
"leftcrop=i" => \$leftcrop, # integer
"rightcrop=i" => \$rightcrop, # integer
"mode=s" => \$bowtiemode, # string
"xlabel=s" => \$xlabel, # string
"ylabel=s" => \$ylabel, # string
"help" => \$help, # flag
"quiet" => \$quiet, # flag
"debug" => \$debug); # flag
############################################################
# parameter checking and some initialization
############################################################
# debug implies not quiet
if ( $debug ) { $quiet = 0; }
# check for required parameters
if ( ( -s $dbname.".nin" ) or ( -s $dbname.".00.nin" ) ) { $permanentdb = 1; }
unless ( ( @sffnames ) or ( @fastanames ) or ( @fastqnames ) or ( @bamnames ) or ( @bednames )
or ( @rochenames ) or ( $permanentdb ) ) { $help = 1; }
if ( ( @sffnames ) or ( @fastanames ) or ( @fastqnames ) or ( $permanentdb ) ) { $calccoverage = 1; }
unless ( @referencenames ) { $help = 1; }
if ( ( defined $gc ) and ( $gc < 1 ) ) { $gc = $defaultgc; }
if ( $cachename )
{
unless ( -d $cachename )
{
unless ( $help )
{ mkdir $cachename or die "Could not create cache directory \"$cachename\": $!\n"; }
}
}
else
{
unless ( -d $tmpdir )
{ die "Configuration error, temporary directory \"$tmpdir\" is invalid\n"; }
$cachename = $tmpdir;
}
unless ( $outpath ) { $outpath = "." }
unless ( $outpath =~ m/\/$/ ) { $outpath .= "/"; }
if ( ( defined $shown ) and ( ! $shown ) ) { $shown = $defaultshown; }
if ( defined $showorfs )
{
unless ( $showorfs ) { $showorfs = $defaultshoworfs; }
if ( ( $showorfs < 0 ) or ( $showorfs > 1 ) ) { die "Error, --orfs parameter must be between 0 and 1, you specified \"$showorfs\"\n"; }
}
if ( @bamnames )
{ $coverageby = "bowtie2"; }
else
{ $coverageby = "blastn minlen=$lenmin minpct=$pctmin"; }
if ( ( defined $fill ) and ( ! $fill ) )
{ $fill = $defaultfill }
############################################################
# print help screen
############################################################
if ( $help )
{
print "$prognopath
Generates a plot of raw read coverage for one or more
reference sequences, as determined by NCBI's blast program,
or use coverage already calculated and saved in BED or bam format
Required parameters:
one of the following is required
| --sff=xxx name of sff file with raw reads,
| multiple instances allowed
| --fasta=xxx name of fasta file with raw reads,
| multiple instances allowed, can be gzipped
| --fastq=xxx name of fastq file with raw reads,
| multiple instances allowed, can be gzipped
| --dbname=xxx name of precompiled blast database
| --bed=xxx name of BED file with coverage data from
| output of coverageBed with -d parameter,
| multiple instances allowed
| --bam=xxx create this bam file if it does not already
| exist, and use it to create the above --bed
| file using --fasta or --fastq or --sff
| If --bed not specified, stop after
| creating bam file. This provides a nice
| wrapper for Bowtie2. Multiple allowed
| --roche=xxx name of 454PairAlign.txt which will be
|__ used to calculate coverage
--reference=xxx reference sequences FASTA file,
multiple instances allowed, or multiple
sequences per file are allowed
Optional parameters:
--outpath=xxx directory for graph image files.
If not specified, will be same directory
as the reference sequences
--grep=xxx only plot this sequence, multiple allowed
--image=xxx output image name template, don't include
path or extension. This is the part after \".vs.\"
--noimage do not create the image file or the data file,
useful if you just want to convert .bam to .bed
--cpu=xxx number of processors to use for blast, default=$defaultnumcpu
--showN[=xxx] mark tracts of N's in image of this length or
longer; if length is not specified, $defaultshown is used
--showorfs[=xxx] plot ORFs in all 6 reading frames, optional value
is Y position as percent of Y axis, default is $defaultshoworfs
--cache=xxx save BLAST files in this directory.
If not specified, results are not saved
--dbname=xxx a name for the BLAST database, required if
you want to cache it
--wiggle=xxx entering an integer value here will trigger
creation of an optional wiggle file in the
directory specified by --outpath, with the
supplied spacing value, e.g. --wiggle=50
--wigname=xxx use to override default wiggle file name, --wiggle still
required. If contains no path, --outpath is prepended
--wigheadername=xxx This is the name used in the wiggle file header
--oneplot concatenate all sequences onto one plot
--format=xxx image file format for graphs, default=\"$defaultformat\"
--noenhanced disable the gnuplot interpretation of underscore as subscript
--xsize=xxx plot width, default=$xsize
--ysize=xxx plot height, default=$ysize
--xscale=xxx alternative to xsize, to make image
width proportional to sequence length.
Units are pixels per kbp, e.g.
--xscale=100 for 3,000 bp sequence =
--xsize=300 (bug: but ignores margins)
--xtics=xxx set major tic mark interval, default is auto
--mxtics=xxx divisor for minor tic mark interval, default is auto
--xmin=xxx X axis minimum, default is 1
--xmax=xxx X axis maximum, default is sequence length
--ymin=xxx Y axis minimum, default is 0
--ymax=xxx Y axis maximum, default is autoscale
--xlabel=xxx X axis label, default \"$defaultxlabel\"
--ylabel=xxx Y axis label, default \"$defaultylabel\"
--fill[=xxx] fill in the area under the curve with solid color
default fill color is \"$defaultfill\"
--font=xxx default is \"$defaultpngfont\"
--parse parse FASTA header generated by bb.fastareorder --annotate
and put a marker at contig borders
--html=xxx append HTML code to display the graph to
this page. --thumbnail is recommended also
--lenmin=xxx minimum blast hit length, default=$lenmin
--pctmin=xxx minimum blast hit percent match, default=$pctmin
--evalue=xxx e-value for blast, default=$evalue
--thumbnail=xxx make a thumbnail of graph at the specified
percentage scaling, e.g. --thumbnail=20
--build regenerate all intermediate files and
cached files even if they already exist
--gc[=xxx] include a plot of gc percentage. Optional parameter
is window size, default is $defaultgc
--transform experimental, adjust coverage based on gc content
--markers=xxx[..xxx][,yyy][,ccc] draw a marker at this coordinate or range,
with optional label yyy, color(hex) (default $defaultmarkercolor).
Multiple allowed, or prefix with \"\@\" to read from a file
--stagger=xxx stagger labels for above markers, number of
different y positions, default=$defaultmarkerlabelstagger, 0 disables
--labelheight=xxx percent of graph height to put --markers labels at, default = $defaultmarkerlabelheight
--title=xxx override default graph title, or use --title=0 to disable title
--nointernallabel do not add the label inside the plot
--nolegend do not add a legend
--leftcrop=xxx remove the first xxx data points
--rightcrop=xxx remove the last xxx data points
--mode=xxx mapping mode for bowtie2, default is \"$defaultbowtiemode\",
some options are \"very-sensitive\" \"fast\" \"very-fast\"
\"very-sensitive-local\" \"sensitive-local\" \"fast-local\"
\"very-fast-local\" - see
http://bowtie-bio.sourceforge.net/bowtie2/manual.shtml#reporting-options
--help print this screen
--quiet only print error messages
--debug print extra debugging information
";
exit 1;
} # if ( $help )
############################################################
# read markers file(s) if present
############################################################
{
my @newmarkers;
foreach my $marker ( @markers )
{
if ( $marker =~ m/^\@(.*)$/ )
{
my $infile = $1;
my $INF = stdopen ( "<", $infile );
while ( my $aline = <$INF> )
{
$aline =~ s/[\r\n]//g;
$aline =~ s/\s+$//;
$aline =~ s/^\s+//;
next unless ( $aline );
push ( @newmarkers, $aline );
}
stdclose ( $INF );
}
else # normal entry
{ push ( @newmarkers, $marker ); }
}
@markers = @newmarkers;
}
############################################################
# parse reference files to get sequence names and lengths
############################################################
{
my $seqnum = -1;
unless ( $quiet ) { print "Parsing reference files\n"; }
foreach my $aref ( @referencenames )
{
debugmsg ( "Reading reference file \"$aref\"" );
my $INF = stdopen ( "<", $aref );
my $linenum = 0;
while ( my $aline = <$INF> )
{
$linenum++;
if ( $aline =~ m/^>(.*)$/ )
{
$seqnum++;
my $fullhdr = $1;
$fullhdr =~ s/[\r\n]//g; # remove return
( my $hdr = $fullhdr ) =~ s/ .*$//; # keep only up to first space
push ( @refhdrkeys, $hdr );
if ( defined $refhdrhash{$hdr} )
{ die "Error, file \"$aref\" line $linenum, duplicate header for sequence $aline"; } # still a return on $aline
$refhdrhash{$hdr} = $seqnum;
# parse headers from bb.fastareorder, e.g.
#>1.C040C14_F 2 sequences: contig2269(646nt@1-646)+-contig3162(337nt@647-983)
if ( $parse )
{
( my $list = $fullhdr ) =~ s/^.*://;
my @parts = split ( /\+/, $list );
foreach my $apart ( @parts )
{
unless ( $apart =~ m/([^\(]+)\(\d+nt\@(\d+)/ ) { die "Error parsing \"$apart\" from header \"$fullhdr\"\n"; }
my $contig = $1;
my $start = $2;
push ( @{$persequencemarkers{$hdr}}, "$start,$contig" );
}
}
} # if header
else # sequence line
{
# length of sequence, ignore non-letters
$aline =~ s/[^A-Za-z]//g;
$reflengths[$seqnum] += length($aline);
# only save sequence in memory if we will need it later
if ( ( $gc ) or ( $shown ) ) { $refsequences[$seqnum] .= $aline; }
} # if sequence line
} # while <$INF>
stdclose ( $INF );
} # foreach my $aref ( @referencenames )
unless ( $quiet ) { print "Read in ".scalar(@refhdrkeys)." reference sequences\n"; }
}
############################################################
# convert each sff file to a FASTA file
############################################################
foreach my $asff ( @sffnames )
{
my $fastaversion = $asff;
$fastaversion =~ s/\.sff$/.fasta/i;
if ( ( ! -s $fastaversion ) or ( $build ) )
{
unless ( $quiet ) { print "Converting \"$asff\" to FASTA format\n"; }
my $cmd = $sffinfocmd . " -seq \"$asff\" > \"$fastaversion\"";
unless ( $quiet ) { print "COMMAND: $cmd\n"; }
my $result = system ( $cmd );
if ( $result ) { die "Error $result executing command \"$cmd\"\n"; }
}
else # already exists
{
unless ( $quiet ) { print "FASTA file \"$fastaversion\" already exists, skipping conversion\n"; }
}
# add this to the --fasta list
push ( @fastanames, $fastaversion );
} # foreach my $asff ( @sffnames )
############################################################
# create a concatenated raw read FASTA file
############################################################
unless ( @bamnames )
{
unless ( $dbname ) { $dbname = $defaultdbname }
if ( ( -s $dbname . '.nin' ) or ( -s $dbname . '.00.nin' ) )
{ $dbnamewithpath = $dbname; } # e.g. pre-compiled blast database used
else
{ $dbnamewithpath = $cachename . "/" . $dbname; }
if ( $calccoverage )
{
if ( ( ( -s "${dbnamewithpath}.nin" ) or ( -s "${dbnamewithpath}.00.nin" ) ) and ( ! $build ) )
{
unless ( $quiet ) { print "BLAST database input file already made, skipping this step\n"; }
}
elsif ( @fastanames or @fastqnames ) # file does not exist, need to create it
{
my @allnames = ( @fastanames, @fastqnames );
if ( ( ( scalar @allnames ) <= 1 )
and ( ( ( scalar @fastqnames ) == 0 ) or ( scalar @bamnames > 0 ) ) )
{
# can just make symbolic link
unless ( $quiet ) { print "Linking to raw read file\n"; }
# @@@@ bug: need full path for this to work
symlink ( $allnames[0], $dbnamewithpath ) or die "Error creating symlink \"$allnames[0]\" to \"$dbnamewithpath\": $!\n";
}
else # more than one read file
{
unless ( $quiet ) { print "Concatenating raw read files\n"; }
my $OUTF = stdopen ( ">", $dbnamewithpath );
foreach my $afile ( @fastanames )
{
debugmsg ( "Concatenating file \"$afile\"" );
my $INF = stdopen ( "<", $afile );
while ( my $aline = <$INF> )
{
$aline =~ s/[\r]//g; # remove DOS returns, just to be safe
print $OUTF $aline;
}
stdclose ( $INF );
} # foreach my $afile ( @fastanames )
foreach my $afile ( @fastqnames )
{
debugmsg ( "Concatenating file \"$afile\"" );
my $INF = stdopen ( "<", $afile );
my $linenum = 0;
while ( my $aline = <$INF> )
{
$linenum++;
my $mod = ( $linenum % 4 );
$aline =~ s/[\r]//g; # remove DOS returns, just to be safe
if ( $mod == 1 )
{
$aline =~ s/^\@/>/;
print $OUTF $aline;
}
elsif ( $mod == 2 )
{ print $OUTF $aline; }
}
stdclose ( $INF );
} # foreach my $afile ( @fastqnames )
stdclose ( $OUTF );
} # else more than one read file
} # else does not exist
else
{ die "Neither reads nor database \"$dbnamewithpath\" found\n"; }
} # if ( $calccoverage )
} # unless ( @bamnames )
############################################################
# compile BLAST database
############################################################
if ( ( $calccoverage ) and ( ! @bamnames ) )
{
if ( ( ( -s "${dbnamewithpath}.nin" ) or ( -s "${dbnamewithpath}.00.nin" ) ) and ( ! $build ) )
{
unless ( $quiet ) { print "BLAST database already compiled, skipping this step\n"; }
}
else # file does not exist, need to create it
{
unless ( $quiet ) { print "Compiling BLAST database of raw reads\n"; }
my $cmd = $makeblastdbcmd;
$cmd .= " -in \"${dbnamewithpath}\"";
$cmd .= " -dbtype nucl";
unless ( $quiet ) { print "COMMAND: $cmd\n"; }
my $result = system ( $cmd );
if ( $result ) { die "Error $result returned from command \"$cmd\"\n"; }
} # else does not exist
} # if ( $calccoverage )
############################################################
# perform BLAST search for each reference file
############################################################
if ( ( $calccoverage ) and ( ! @bamnames ) )
{
foreach my $aref ( @referencenames )
{
my $blastoutfile = $aref;
$blastoutfile =~ s/^.*\///; # remove path
( my $shortdb = $dbname ) =~ s/^.*\///;
$blastoutfile = $cachename . "/" . $blastoutfile . ".vs." . $shortdb . ".blast"; # put blast results in cache directory
if ( ( ! -s $blastoutfile ) or ( $build ) )
{
unless ( $quiet ) { print "Performing blastn search on reference file \"$aref\"\n"; }
my $cmd = $blastcmd;
$cmd .= " -query \"$aref\"";
$cmd .= " -task blastn";
$cmd .= " -db \"$dbnamewithpath\"";
$cmd .= " -out \"$blastoutfile\"";
$cmd .= " -evalue $evalue";
$cmd .= " -perc_identity $pctmin";
$cmd .= " -outfmt 6";
$cmd .= " -num_alignments $maxalignments";
$cmd .= " -num_descriptions $maxalignments";
$cmd .= " -dust no";
$cmd .= " -num_threads $numcpu";
unless ( $quiet ) { print "COMMAND: $cmd\n"; }
my $result = system ( $cmd );
if ( $result )
{
unlink $blastoutfile;
die "Error $result returned from blast command \"$cmd\"\n";
}
}
else
{ unless ( $quiet ) { print "Blast result file \"$blastoutfile\" already exists, skipping blast\n"; } }
} # foreach my $aref ( @referencenames )
} # if ( $calccoverage )
############################################################
# run bowtie2 if bam files do not exist
############################################################
foreach my $bam ( @bamnames )
{
unless ( -s $bam )
{
bowtie2($bam);
} # if bam file does not exist
} # foreach my $bam ( @bamnames )
# if specified bam files and no bed files, stop here
if ( ( @bamnames ) and ( ! @bednames ) )
{
unless ( $quiet ) { print "All bam files generated, no bed files specified, this program is done\n"; }
exit 0;
}
############################################################
# make BED file if bam file specified
############################################################
if ( @bamnames )
{
# make a BED file for references if not already present
foreach my $ref ( @referencenames )
{
my $refbed = $ref . ".bed";
if ( ! -s $refbed )
{
unless ( $quiet ) { print "Creating reference BED file \"$refbed\"\n"; }
my $cmd = "bb.fastalen --in=\"$ref\" --each --bed --out=\"$refbed\"";
unless ( $quiet ) { print "COMMAND: $cmd\n"; }
my $result = system ( $cmd );
if ( $result ) { die "Error $result running command \"$cmd\"\n"; }
}
} # foreach $ref
my $i = 0;
foreach my $bam ( @bamnames )
{
if ( @bednames )
{
unless ( $bednames[$i] ) { die "Error, no --bed file name specified for --bam file \"$bam\"\n"; }
my $j = 0;
foreach my $ref ( @referencenames )
{
$j++;
my $refbed = $ref . ".bed";
my $thisbed = $bednames[$i];
# when multiple references, insert index in front of
# extension, or if no extension, append it
if ( ( scalar @referencenames ) > 1 )
{
unless ( $thisbed =~ s/(\.[^\.]*)$/\.$j$1/ )
{ $thisbed .= "." . $j; }
}
# skip if --bed file already exists
if ( ! -s $thisbed )
{
unless ( $quiet ) { print "Creating BED file \"$thisbed\" from \"$bam\" + \"$refbed\"\n"; }
# changed Jan. 19, 2017 for change in bedtools coverageBed, see version notes
# at top of this program. used to be --abam xxx -b xxx here
my $cmd = "coverageBed -b \"$bam\" -a \"$refbed\" -d -split -sorted > \"$thisbed\"";
unless ( $quiet ) { print "COMMAND: $cmd\n"; }
my $result = system ( $cmd );
if ( $result ) { die "Error $result running command \"$cmd\"\n"; }
} # if not already exists
else
{
unless ( $quiet )
{ print "Skipping generation of BED file \"$thisbed\", file already exists\n"; }
}
} # foreach reference
} # if ( @bednames )
$i++;
}
} # if ( @bamnames )
############################################################
# parse BLAST output files or BED files and store coverage data in memory
############################################################
if ( ( $calccoverage ) and ( ! @bednames ) )
{
foreach my $aref ( @referencenames )
{
my $blastoutfile = $aref;
$blastoutfile =~ s/^.*\///; # remove path
( my $shortdb = $dbname ) =~ s/^.*\///;
$blastoutfile = $cachename . "/" . $blastoutfile . ".vs." . $shortdb . ".blast"; # put blast results in cache directory
unless ( $quiet ) { print "Parsing blast search results for reference \"$aref\"\n"; }
my $linenum = 0;
my %goodblasthits;
my %allblasthits;
my $debugcounter = 10;
my $INF = stdopen ( "<", $blastoutfile );
while ( my $aline = <$INF> )
{
$linenum++;
$aline =~ s/[\r\n]//g;
my @cols = split ( /\t/, $aline );
$allblasthits{$cols[1]}++;
if ( $debugcounter ) { debugmsg ( "parsing blast hit from query \"$cols[0]\" to \"$cols[1]\"" ); }
# minimum length
if ( $cols[3] < $lenmin )
{
if ( $debugcounter ) { debugmsg ( "length \"$cols[3]\" below minimum \"$lenmin\"" ); }
next;
}
# minimum percent match
if ( $cols[2] < $pctmin )
{
if ( $debugcounter ) { debugmsg ( "match percent \"$cols[2]\" below minimum \"$pctmin\"" ); }
next;
}
# this is a mapped read
$goodblasthits{$cols[1]}++;
if ( $debugcounter ) { debugmsg ( "good mapped read \"$cols[1]\"" ); }
# get sequence index
my $idx = $refhdrhash{$cols[0]};
unless ( defined $idx ) { die "Failed index lookup for reference \"$cols[0]\", blast output file \"$blastoutfile\" line $linenum\n"; }
for my $i ( $cols[6] .. $cols[7] )
{ $coverage[$idx]->[$i]++; }
if ( $debugcounter ) { $debugcounter--; }
} # while <$INF>
stdclose ( $INF );
if ( $linenum >= $maxalignments )
{ print "WARNING, results may be incomplete, reached the maximum number of alignments which is ".commify($maxalignments)."\n"; }
unless ( $quiet )
{ print "Mapped ".commify(scalar keys %goodblasthits)." reads out of ".commify(scalar keys %allblasthits)." blast hits to reference $aref\n"; }
} # foreach my $aref ( @referencenames )
} # if ( $calccoverage )
elsif ( @bednames ) # parse BED files
{
unless ( $quiet ) { print "Reading BED features\n"; }
foreach my $bedfile ( @bednames )
{
debugmsg ( "Processing BED file \"$bedfile\"" );
my $linenum = 0;
my $INF = stdopen ( "<", $bedfile );
while ( my $aline = <$INF> )
{
$linenum++;
$aline =~ s/[\r\n]//g;
my @cols = split ( /\t/, $aline );
# non -d BED columns are [0]=seqid [1]=start(0-bases) [2]=end(1-based)
# [3]=The number of features in A that overlapped (by at least one base pair) the B interval
# [4]=The number of bases in B that had non-zero coverage from features in A
# [5]=The length of the entry in B
# [6]=The fraction of bases in B that had non-zero coverage from features in A
# but columns with -d option are
# non -d BED columns are [0]=seqid [1]=start(0-bases) [2]=end(1-based)
# [3]=base(1-based)
# [4]=coverage
# get sequence index
my $idx = $refhdrhash{$cols[0]};
unless ( defined $idx ) { die "Failed index lookup for reference \"$cols[0]\", BED file \"$bedfile\" line $linenum\n"; }
# store coverage data
$coverage[$idx]->[$cols[3]] = $cols[4];
} # while ( my $aline = <$INF> )
stdclose ( $INF );
unless ( $quiet ) { print "BED file \"$bedfile\" contained ".commify($linenum)." features\n"; }
} # foreach my $bedfile ( @bednames )
} # else parse BED files
elsif ( @rochenames ) # parse Roche gsMapper 454PairAlign.txt files
{
unless ( $quiet ) { print "Reading Roche 454PairAlign.txt to determine coverage\n"; }
foreach my $rochefile ( @rochenames )
{
debugmsg ( "Processing Roche file \"$rochefile\"" );
my $linenum = 0;
my $nreads = 0;
my $part = -1; # 0, 1, or 2
my $INF = stdopen ( "<", $rochefile );
my @lines;
while ( my $aline = <$INF> )
{
# each read occupies three lines, e.g.:
#>FCD05TCACXX:6:1101:1298:2085#ATCACGAT/2, 48..90 of 90 and GY14Scaffold00998, 101926..101968 of 563336 (41/44 ident)
# 48 TTCCACGGGTTAGGATCCAACCG-TTACAATATGTTGAAGTTTT 90
# 101926 TTCCACGGGTTAGGATCCAACA-ATTACAATATGTTGAAGTTTT 101968
$linenum++;
$part = ( ( $part + 1 ) % 3 );
unless ( $part ) { @lines = (); } # reset
$aline =~ s/[\r\n]//g;
$lines[$part] = $aline;
if ( $part == 0 )
{
unless ( $aline =~ m/^>/ ) { die "Error, line $linenum does not start with \">\": \"$aline\"\n"; }
}
elsif ( $part == 2 )
{
$nreads++;
if ( ( ! $quiet ) and ( ( $nreads % $updateinterval ) == 0 ) )
{ print commify($nreads)." reads\n".$ansiup; }
# sequence will end up in column [2]
my @refcols = split ( /\s+/, $lines[2] );
my @readcols = split ( /\s+/, $lines[1] );
my $refid;
if ( $lines[0] =~ m/ and ([^,]+)/ )
{ $refid = $1; }
else
{ die "Error parsing line ".commify($linenum-2).", \"$lines[0]\"\n"; }
# get sequence index
my $idx = $refhdrhash{$refid};
unless ( defined $idx ) { die "Failed index lookup for reference \"$refid\", line ".commify($linenum)."\n"; }
# store coverage data. I will ignore SNPs and just add 1 to coverage for entire reference range
for my $i ( $refcols[1] .. $refcols[3] )
{ $coverage[$idx]->[$i]++; }
} # $part == 2
} # while ( my $aline = <$INF> )
stdclose ( $INF );
unless ( $quiet ) { print "Roche file \"$rochefile\" contained ".commify($nreads)." reads\n"; }
} # foreach my $rochefile ( @rochenames )
} # else parse Roche gsMapper files
############################################################
# optional wiggle file
############################################################
# http://genome.ucsc.edu/goldenPath/help/wiggle.html
if ( $wspacing )
{
unless ( $quiet ) { print "Creating wiggle files at a spacing of $wspacing\n"; }
for my $i ( 0 .. $#refhdrkeys )
{
( my $shortdb = $dbname ) =~ s/^.*\///;
my $wigglefile = $outpath . "/" . $refhdrkeys[$i] . ".vs." . $shortdb . ".wig";
if ( $wname )
{
if ( $wname =~ m/\// )
{ $wigglefile = $wname; }
else
{ $wigglefile = $outpath . "/" . $wname; }
}
debugmsg ( "Creating wiggle file \"$wigglefile\"" );
my $OUTF = stdopen ( ">", $wigglefile );
my $headername = $refhdrkeys[$i] . "_vs_" . $shortdb; # default name
if ( $whname ) { $headername = $whname; }
print $OUTF "track type=wiggle_0 name=\"$headername\" description=\"Coverage by $coverageby\"\n";
print $OUTF "fixedStep chrom=\"$refhdrkeys[$i]\" start=1 step=$wspacing span=$wspacing\n";
my $cumul = 0;
my $tot = 0;
for my $j ( 1 .. $reflengths[$i] )
{
my $datum = $coverage[$i]->[$j];
unless ( defined $datum ) { $datum = 0 }
$tot += $datum;
$cumul++;
if ( $cumul >= $wspacing )
{
my $mean = sprintf ( "%0.3f", ( $tot / $cumul ) );
print $OUTF $mean, "\n";
$tot = 0;
$cumul = 0;
}
} # for $j
# include any left over data from a fractional increment at the end
if ( $cumul )
{
my $mean = sprintf ( "%0.3f", ( $tot / $cumul ) );
print $OUTF $mean, "\n";
}
stdclose ( $OUTF );
} # for $i
} # if ( $wspacing )
############################################################
# calculate optional gc ratio from reference sequences
############################################################
my @gcratio;
if ( $gc )
{
# if $gc is not odd, then one more base will be in the window
# on the left side than the right side
my $leftwindow = int ( $gc / 2 );
my $rightwindow = ( $gc - 1 - $leftwindow );
for my $i ( 0 .. $#refhdrkeys )
{
my $nnt = 0;
# convert sequence string to array
my @bases = split ( //, $refsequences[$i] );
debugmsg ( "Reference $i $refhdrkeys[$i] has ".$#bases." bases, reflength=$reflengths[$i]" );
# make temporary cumulative total of gc count in an array
my $ngc = 0;
my @tmptotalgc;
for my $j ( 0 .. $#bases )
{
if ( $bases[$j-1] =~ m/[CGScgs]/ )
{ $ngc++; }
elsif ( $bases[$j-1] =~ m/[KMNRYkmnry]/ )
{ $ngc += 0.5; }
elsif ( $bases[$j-1] =~ m/[BVbv]/ )
{ $ngc += (2/3); }
elsif ( $bases[$j-1] =~ m/[DHdh]/ )
{ $ngc += (1/3); }
# and [ATWatw] count as zero
$tmptotalgc[$j] = $ngc;
} # for $j
# window is centered on base position
for my $j ( 0 .. $#bases )
{
my $start = ( $j - $leftwindow );
if ( $start < 0 ) { $start = 0; }
my $end = ( $j + $rightwindow );
if ( $end > $#bases ) { $end = $#bases; }
$gcratio[$i]->[$j+1] = ( ( $tmptotalgc[$end] - $tmptotalgc[$start] ) / ( $end - $start + 1 ) );
} # for $j
} # for $i
} # if ( $gc )
############################################################
# find tracts of N's
############################################################
my @Ncoords;
if ( $shown )
{
for my $i ( 0 .. $#refhdrkeys )
{
while ( $refsequences[$i] =~ m/(N{$shown,})/ig )
{
my $end = pos($refsequences[$i]);
my $start = $end - length($1) + 1;
debugmsg ( "Tract of N's in reference $i $refhdrkeys[$i]: Start=$start end=$end" );
push ( @{$Ncoords[$i]}, $start, $end ); # two elements per span, start and end, 1-based
}
} # for $i
} # if $shown
############################################################
# optional ORFs detection
############################################################
if ( $showorfs )
{
unless ( $quiet ) { print "Detecting ORFs\n"; }
# generate table of orfs using bb.orffinder
foreach my $aref ( @referencenames )
{
my ($TMPORF, $tmporf) = tempfile($tempfiletemplate, TMPDIR=>1, UNLINK=>1);
debugmsg ( "Caculating ORFs in reference file \"$aref\", output=\"$tmporf\"" );
my $cmd = "bb.orffinder --infile=\"$aref\" --outfile=\"$tmporf\"";
unless ( $quiet ) { print "COMMAND: $cmd\n"; }
my $result = system ( $cmd );
if ( $result ) { die "Error $result running command \"$cmd\"\n"; }
# parse orfs file and create gnuplot data
while ( my $aline = <$TMPORF> )
{
$aline =~ s/[\r\n]//g;
next if ( $aline =~ m/^#/ );
my @cols = split ( /\t/, $aline );
# [0]#ID [1]orf [2]Frame [3]Start [4]Codon [5]Stop [6]Codon [7]Length