-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathribosensor
executable file
·2655 lines (2390 loc) · 125 KB
/
ribosensor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env perl
use strict;
use warnings;
use Getopt::Long;
use Time::HiRes qw(gettimeofday);
# ribosensor :: analyze ribosomal RNA sequences with profile HMMs and BLASTN
# Usage: ribosensor [-options] <fasta file to annotate> <output directory>\n";
require "ribo.pm";
# make sure required environment variables are set
my $env_riboscripts_dir = utl_DirEnvVarValid("RIBOSCRIPTSDIR");
my $env_rrnasensor_dir = utl_DirEnvVarValid("RRNASENSORDIR");
my $env_riboinfernal_dir = utl_DirEnvVarValid("RIBOINFERNALDIR");
my $env_riboeasel_dir = utl_DirEnvVarValid("RIBOEASELDIR");
my $env_riboblast_dir = utl_DirEnvVarValid("RIBOBLASTDIR");
my $df_model_dir = $env_riboscripts_dir . "/models/";
my %execs_H = (); # hash with paths to all required executables
$execs_H{"ribo"} = $env_riboscripts_dir . "/ribotyper";
$execs_H{"rRNA_sensor_script"} = $env_rrnasensor_dir . "/rRNA_sensor_script";
$execs_H{"esl-seqstat"} = $env_riboeasel_dir . "/esl-seqstat";
$execs_H{"esl-sfetch"} = $env_riboeasel_dir . "/esl-sfetch";
$execs_H{"blastn"} = $env_riboblast_dir . "/blastn";
$execs_H{"blastdbcmd"} = $env_riboblast_dir . "/blastdbcmd";
# deal with 'time' differently because we can deal if it doesn't exist and
# we only use it if it does exist and -p is used
my $env_ribotime_dir = ribo_CheckForTimeExecutable(); # this will return undef if time doesn't exist or is undef
if(defined $env_ribotime_dir) {
$execs_H{"time"} = $env_ribotime_dir . "/time";
}
utl_ExecHValidate(\%execs_H, undef);
#########################################################
# Command line and option processing using sqp_opts.pm
#
# opt_HH: 2D hash:
# 1D key: option name (e.g. "-h")
# 2D key: string denoting type of information
# (one of "type", "default", "group", "requires", "incompatible", "preamble", "help")
# value: string explaining 2D key:
# "type": "boolean", "string", "integer" or "real"
# "default": default value for option
# "group": integer denoting group number this option belongs to
# "requires": string of 0 or more other options this option requires to work, each separated by a ','
# "incompatible": string of 0 or more other options this option is incompatible with, each separated by a ','
# "preamble": string describing option for preamble section (beginning of output from script)
# "help": string describing option for help section (printed if -h used)
# "setby": '1' if option set by user, else 'undef'
# "value": value for option, can be undef if default is undef
#
# opt_order_A: array of options in the order they should be processed
#
# opt_group_desc_H: key: group number (integer), value: description of group for help output
my %opt_HH = ();
my @opt_order_A = ();
my %opt_group_desc_H = ();
# Add all options to %opt_HH and @opt_order_A.
# Group 2 optional arguments are passed directly to sensor and are irrelevant to ribotyper
# Group 1 and group 3 optional arguments are not specific to sensor or ribotyper
# This section needs to be kept in sync (manually) with the &GetOptions call below
$opt_group_desc_H{"1"} = "basic options";
# option type default group requires incompat preamble-output help-output
opt_Add("-h", "boolean", 0, 0, undef, undef, undef, "display this help", \%opt_HH, \@opt_order_A);
opt_Add("-f", "boolean", 0, 1, undef, undef, "forcing directory overwrite", "force; if <output directory> exists, overwrite it", \%opt_HH, \@opt_order_A);
opt_Add("-m", "string", "16S", 1, undef, undef, "set mode to <s>", "set mode to <s>, possible <s> values are \"16S\" and \"18S\"", \%opt_HH, \@opt_order_A);
opt_Add("-c", "boolean", 0, 1, undef, undef, "assert that sequences are from cultured organisms", "assert that sequences are from cultured organisms", \%opt_HH, \@opt_order_A);
opt_Add("-n", "integer", 0, 1, undef, "-p", "use <n> CPUs", "use <n> CPUs", \%opt_HH, \@opt_order_A);
opt_Add("-v", "boolean", 0, 1, undef, undef, "be verbose", "be verbose; output commands to stdout as they're run", \%opt_HH, \@opt_order_A);
opt_Add("-i", "string", undef, 1, undef, undef, "use model info file <s> instead of default", "use model info file <s> instead of default", \%opt_HH, \@opt_order_A);
opt_Add("--keep", "boolean", 0, 1, undef, undef, "keep all intermediate files", "keep all intermediate files that are removed by default", \%opt_HH, \@opt_order_A);
opt_Add("--skipsearch", "boolean", 0, 1, undef, "-f", "skip search stages, use results from earlier run", "skip search stages, use results from earlier run", \%opt_HH, \@opt_order_A);
$opt_group_desc_H{"2"} = "rRNA_sensor related options";
opt_Add("--Sminlen", "integer", 100, 2, undef, undef, "set rRNA_sensor minimum seq length to <n>", "set rRNA_sensor minimum sequence length to <n>", \%opt_HH, \@opt_order_A);
opt_Add("--Smaxlen", "integer", 2000, 2, undef, undef, "set rRNA_sensor maximum seq length to <n>", "set rRNA_sensor minimum sequence length to <n>", \%opt_HH, \@opt_order_A);
opt_Add("--Smaxevalue", "real", 1e-40, 2, undef, undef, "set rRNA_sensor maximum E-value to <x>", "set rRNA_sensor maximum E-value to <x>", \%opt_HH, \@opt_order_A);
opt_Add("--Sminid1", "integer", 75, 2, undef, undef, "set rRNA_sensor min percent id for seqs <= 350 nt to <n>", "set rRNA_sensor minimum percent id for seqs <= 350 nt to <n>", \%opt_HH, \@opt_order_A);
opt_Add("--Sminid2", "integer", 80, 2, undef, undef, "set rRNA_sensor min percent id for seqs [351..600] nt to <n>", "set rRNA_sensor minimum percent id for seqs [351..600] nt to <n>", \%opt_HH, \@opt_order_A);
opt_Add("--Sminid3", "integer", 86, 2, undef, undef, "set rRNA_sensor min percent id for seqs > 600 nt to <n>", "set rRNA_sensor minimum percent id for seqs > 600 nt to <n>", \%opt_HH, \@opt_order_A);
opt_Add("--Smincovall", "integer", 10, 2, undef, undef, "set rRNA_sensor min percent coverage for all sequences to <n>", "set rRNA_sensor minimum coverage for all sequences to <n>", \%opt_HH, \@opt_order_A);
opt_Add("--Smincov1", "integer", 80, 2, undef, undef, "set rRNA_sensor min percent coverage for seqs <= 350 nt to <n>", "set rRNA_sensor minimum coverage for seqs <= 350 nt to <n>", \%opt_HH, \@opt_order_A);
opt_Add("--Smincov2", "integer", 86, 2, undef, undef, "set rRNA_sensor min percent coverage for seqs > 350 nt to <n>", "set rRNA_sensor minimum coverage for seqs > 350 nt to <n>", \%opt_HH, \@opt_order_A);
$opt_group_desc_H{"3"} = "options for saving sequence subsets to files";
opt_Add("--psave", "boolean",0, 3, undef, undef, "save passing sequences to a file", "save passing sequences to a file", \%opt_HH, \@opt_order_A);
$opt_group_desc_H{"4"} = "options for parallelizing cmsearch on a compute farm";
# option type default group requires incompat preamble-output help-output
opt_Add("-p", "boolean", 0, 4, undef, undef, "parallelize ribotyper and rRNA_sensor on a compute farm", "parallelize ribotyper and rRNA_sensor on a compute farm", \%opt_HH, \@opt_order_A);
opt_Add("-q", "string", undef, 4, "-p", undef, "use qsub info file <s> instead of default", "use qsub info file <s> instead of default", \%opt_HH, \@opt_order_A);
opt_Add("-s", "integer", 181, 4, "-p", undef, "seed for random number generator is <n>", "seed for random number generator is <n>", \%opt_HH, \@opt_order_A);
opt_Add("--nkb", "integer", 100, 4, "-p", undef, "number of KB of seq for each farm job is <n>", "number of KB of sequence for each farm job is <n>", \%opt_HH, \@opt_order_A);
opt_Add("--wait", "integer", 500, 4, "-p", undef, "allow <n> minutes for jobs on farm", "allow <n> wall-clock minutes for jobs on farm to finish, including queueing time", \%opt_HH, \@opt_order_A);
opt_Add("--errcheck", "boolean", 0, 4, "-p", undef, "consider any farm stderr output as indicating a job failure", "consider any farm stderr output as indicating a job failure", \%opt_HH, \@opt_order_A);
# This section needs to be kept in sync (manually) with the opt_Add() section above
my %GetOptions_H = ();
my $usage = "Usage: ribosensor [-options] <fasta file to annotate> <output directory>\n";
my $synopsis = "ribosensor :: analyze ribosomal RNA sequences with profile HMMs and BLASTN";
my $options_okay =
&GetOptions('h' => \$GetOptions_H{"-h"},
'f' => \$GetOptions_H{"-f"},
'm=s' => \$GetOptions_H{"-m"},
'c' => \$GetOptions_H{"-c"},
'n=s' => \$GetOptions_H{"-n"},
'v' => \$GetOptions_H{"-v"},
'i=s' => \$GetOptions_H{"-i"},
'keep' => \$GetOptions_H{"--keep"},
'skipsearch' => \$GetOptions_H{"--skipsearch"},
'Sminlen=s' => \$GetOptions_H{"--Sminlen"},
'Smaxlen=s' => \$GetOptions_H{"--Smaxlen"},
'Smaxevalue=s' => \$GetOptions_H{"--Smaxevalue"},
'Sminid1=s' => \$GetOptions_H{"--Sminid1"},
'Sminid2=s' => \$GetOptions_H{"--Sminid2"},
'Sminid3=s' => \$GetOptions_H{"--Sminid3"},
'Smincovall=s' => \$GetOptions_H{"--Smincovall"},
'Smincov1=s' => \$GetOptions_H{"--Smincov1"},
'Smincov2=s' => \$GetOptions_H{"--Smincov2"},
'psave' => \$GetOptions_H{"--psave"},
# options for parallelization
'p' => \$GetOptions_H{"-p"},
'q=s' => \$GetOptions_H{"-q"},
's=s' => \$GetOptions_H{"-s"},
'nkb=s' => \$GetOptions_H{"--nkb"},
'wait=s' => \$GetOptions_H{"--wait"},
'errcheck' => \$GetOptions_H{"--errcheck"});
my $total_seconds = -1 * ofile_SecondsSinceEpoch(); # by multiplying by -1, we can just add another ofile_SecondsSinceEpoch call at end to get total time
my $executable = $0;
my $date = scalar localtime();
my $version = "1.0.5";
my $releasedate = "Sep 2023";
my $package_name = "Ribovore";
# make *STDOUT file handle 'hot' so it automatically flushes whenever we print to it
select *STDOUT;
$| = 1;
# print help and exit if necessary
if((! $options_okay) || ($GetOptions_H{"-h"})) {
ofile_OutputBanner(*STDOUT, $package_name, $version, $releasedate, $synopsis, $date, undef);
opt_OutputHelp(*STDOUT, $usage, \%opt_HH, \@opt_order_A, \%opt_group_desc_H);
if(! $options_okay) { die "ERROR, unrecognized option;"; }
else { exit 0; } # -h, exit with 0 status
}
# check that number of command line args is correct
if(scalar(@ARGV) != 2) {
print "Incorrect number of command line arguments.\n";
print $usage;
print "\nTo see more help on available options, do ribosensor -h\n\n";
exit(1);
}
my ($seq_file, $dir_out) = (@ARGV);
# set options in opt_HH
opt_SetFromUserHash(\%GetOptions_H, \%opt_HH);
# validate options (check for conflicts)
opt_ValidateSet(\%opt_HH, \@opt_order_A);
my $cmd = undef; # a command to be run by utl_RunCommand()
my $ncpu = opt_Get("-n" , \%opt_HH); # number of CPUs to use with search command (default 0: --cpu 0)
my @early_cmd_A = (); # array of commands we run before our log file is opened
my @to_remove_A = (); # array of files to remove at end
# the way we handle the $dir_out differs markedly if we have --skipsearch enabled
# so we handle that separately
if(opt_Get("--skipsearch", \%opt_HH)) {
if(-d $dir_out) {
# this is what we expect, do nothing
}
elsif(-e $dir_out) {
die "ERROR with --skipsearch, $dir_out must already exist as a directory, but it exists as a file, delete it first, then run without --skipsearch";
}
else {
die "ERROR with --skipsearch, $dir_out must already exist as a directory, but it does not. Run without --skipsearch";
}
}
else { # --skipsearch not used, normal case
if(-d $dir_out) {
$cmd = "rm -rf $dir_out";
if(opt_Get("--psave", \%opt_HH)) {
die "ERROR you used --psave but directory $dir_out already exists.\nYou can either run with --skipsearch to create the psave file and not redo the searches OR\nremove the $dir_out directory and then rerun with --psave if you really want to redo the search steps";
}
elsif(opt_Get("-f", \%opt_HH)) {
utl_RunCommand($cmd, opt_Get("-v", \%opt_HH), 0, undef);
}
else {
die "ERROR directory named $dir_out already exists. Remove it, or use -f to overwrite it.";
}
}
elsif(-e $dir_out) {
$cmd = "rm $dir_out";
if(opt_Get("-f", \%opt_HH)) { utl_RunCommand($cmd, opt_Get("-v", \%opt_HH), 0, undef); }
else { die "ERROR a file named $dir_out already exists. Remove it, or use -f to overwrite it."; }
}
}
# if $dir_out does not exist, create it
if(! -d $dir_out) {
$cmd = "mkdir $dir_out";
utl_RunCommand($cmd, opt_Get("-v", \%opt_HH), 0, undef);
}
# if -p used and "time" exists (we checked above), then leave execs_H{"time"} alone, else undefine it so we won't use it
my $use_time_program = ((opt_Get("-p", \%opt_HH)) && (defined $execs_H{"time"})) ? 1 : 0;
if(! $use_time_program) { $execs_H{"time"} = undef; }
my $dir_out_tail = $dir_out;
$dir_out_tail =~ s/^.+\///; # remove all but last dir
my $out_root = $dir_out . "/" . $dir_out_tail . ".ribosensor";
#############################################
# output program banner and open output files
#############################################
# output preamble
my @arg_desc_A = ();
my @arg_A = ();
push(@arg_desc_A, "target sequence input file");
push(@arg_A, $seq_file);
push(@arg_desc_A, "output directory name");
push(@arg_A, $dir_out);
my %extra_H = ();
$extra_H{"\$RIBOSCRIPTSDIR"} = $env_riboscripts_dir;
$extra_H{"\$RRNASENSORDIR"} = $env_rrnasensor_dir;
$extra_H{"\$RIBOINFERNALDIR"} = $env_riboinfernal_dir;
$extra_H{"\$RIBOEASELDIR"} = $env_riboeasel_dir;
$extra_H{"\$RIBOBLASTDIR"} = $env_riboblast_dir;
if($use_time_program) {
$extra_H{"\$RIBOTIMEDIR"} = $env_ribotime_dir;
}
ofile_OutputBanner(*STDOUT, $package_name, $version, $releasedate, $synopsis, $date, \%extra_H);
opt_OutputPreamble(*STDOUT, \@arg_desc_A, \@arg_A, \%opt_HH, \@opt_order_A);
# open the log and command files:
# set output file names and file handles, and open those file handles
my %ofile_info_HH = (); # hash of information on output files we created,
# 1D keys:
# "fullpath": full path to the file
# "nodirpath": file name, full path minus all directories
# "desc": short description of the file
# "FH": file handle to output to for this file, maybe undef
# 2D keys:
# "log": log file of what's output to stdout
# "cmd": command file with list of all commands executed
# open the list, log and command files
ofile_OpenAndAddFileToOutputInfo(\%ofile_info_HH, "list", $out_root . ".list", 1, 1, "List and description of all output files");
ofile_OpenAndAddFileToOutputInfo(\%ofile_info_HH, "log", $out_root . ".log", 1, 1, "Output printed to screen");
ofile_OpenAndAddFileToOutputInfo(\%ofile_info_HH, "cmd", $out_root . ".cmd", 1, 1, "List of executed commands");
my $log_FH = $ofile_info_HH{"FH"}{"log"};
my $cmd_FH = $ofile_info_HH{"FH"}{"cmd"};
# output files are all open, if we exit after this point, we'll need
# to close these first.
# now we have the log file open, output the banner there too
ofile_OutputBanner($log_FH, $package_name, $version, $releasedate, $synopsis, $date, \%extra_H);
opt_OutputPreamble($log_FH, \@arg_desc_A, \@arg_A, \%opt_HH, \@opt_order_A);
# output any commands we already executed to $log_FH
foreach $cmd (@early_cmd_A) {
print $cmd_FH $cmd . "\n";
}
# make sure the sequence, modelinfo, and qsubinfo (if -p) files exist
my $df_modelinfo_file = $df_model_dir . "ribosensor.modelinfo";
my $modelinfo_file = undef;
if(! opt_IsUsed("-i", \%opt_HH)) { $modelinfo_file = $df_modelinfo_file; }
else { $modelinfo_file = opt_Get("-i", \%opt_HH); }
utl_FileValidateExistsAndNonEmpty($seq_file, "sequence file", undef, 1, $ofile_info_HH{"FH"}); # '1' says: die if it doesn't exist or is empty
if(! opt_IsUsed("-i", \%opt_HH)) {
utl_FileValidateExistsAndNonEmpty($modelinfo_file, "default model info file", undef, 1, $ofile_info_HH{"FH"}); # '1' says: die if it doesn't exist or is empty
}
else { # -i used on the command line
utl_FileValidateExistsAndNonEmpty($modelinfo_file, "model info file specified with -i", undef, 1, $ofile_info_HH{"FH"}); # '1' says: die if it doesn't exist or is empty
}
my $df_qsubinfo_file = $df_model_dir . "ribo.qsubinfo";
my $qsubinfo_file = undef;
# if -p, check for existence of qsub info file
if(opt_IsUsed("-p", \%opt_HH)) {
if(! opt_IsUsed("-q", \%opt_HH)) { $qsubinfo_file = $df_qsubinfo_file; }
else { $qsubinfo_file = opt_Get("-q", \%opt_HH); }
if(! opt_IsUsed("-q", \%opt_HH)) {
utl_FileValidateExistsAndNonEmpty($qsubinfo_file, "default qsub info file", undef, 1, $ofile_info_HH{"FH"}); # '1' says: die if it doesn't exist or is empty
}
else { # -q used on the command line
utl_FileValidateExistsAndNonEmpty($qsubinfo_file, "qsub info file specified with -q", undef, 1, $ofile_info_HH{"FH"}); # 1 says: die if it doesn't exist or is empty
}
}
# we check for the existence of model file after we parse the model info file
##############################
# define and open output files
##############################
my $unsrt_sensor_indi_file = $out_root . ".sensor.unsrt.out"; # ribosensor-processed, unsorted sensor output
my $sensor_indi_file = $out_root . ".sensor.out"; # ribosensor-processed, sorted 'genbank' format sensor output
my $ribo_indi_file = $out_root . ".ribo.out"; # ribosensor-processed, ribotyper output
my $combined_out_file = $out_root . ".out"; # ribosensor-processed, sensor+ribotyper combined output, human readable
my $combined_genbank_file = $out_root . ".gbank"; # ribosensor-processed, sensor+ribotyper combined output, machine readable with genbank errors
my $passes_sfetch_file = $out_root . ".pass.sfetch"; # input file for esl-sfetch that will fetch all sequences that passed
my $passes_seq_file = $out_root . ".pass.fa"; # all sequences that passed as a FASTA-formatted file
if(! opt_Get("--keep", \%opt_HH)) {
push(@to_remove_A, $unsrt_sensor_indi_file);
if(opt_Get("--psave", \%opt_HH)) {
push(@to_remove_A, $passes_sfetch_file);
}
}
my $unsrt_sensor_indi_FH = undef; # output file handle for unsorted sensor genbank file
my $sensor_indi_FH = undef; # output file handle for genbank file sorted by input sequence index
my $ribo_indi_FH = undef; # output file handle for ribotyper genbank file sorted by input sequence index
my $combined_out_FH = undef; # output file handle for the combined output file
my $combined_genbank_FH = undef; # output file handle for the combined genbank file
open($unsrt_sensor_indi_FH, ">", $unsrt_sensor_indi_file) || ofile_FileOpenFailure($unsrt_sensor_indi_file, "ribosensor::main()", $!, "writing", $ofile_info_HH{"FH"});
open($sensor_indi_FH, ">", $sensor_indi_file) || ofile_FileOpenFailure($sensor_indi_file, "ribosensor::main()", $!, "writing", $ofile_info_HH{"FH"});
open($ribo_indi_FH, ">", $ribo_indi_file) || ofile_FileOpenFailure($ribo_indi_file, "ribosensor::main()", $!, "writing", $ofile_info_HH{"FH"});
open($combined_out_FH, ">", $combined_out_file) || ofile_FileOpenFailure($combined_out_file, "ribosensor::main()", $!, "writing", $ofile_info_HH{"FH"});
open($combined_genbank_FH, ">", $combined_genbank_file) || ofile_FileOpenFailure($combined_genbank_file, "ribosensor::main()", $!, "writing", $ofile_info_HH{"FH"});
# parse the model info file
my ($sensor_blastdb, $ribo_modelinfo_file, $ribo_accept_file) = parse_modelinfo_file($modelinfo_file, $execs_H{"blastdbcmd"}, opt_Get("-m", \%opt_HH), $df_model_dir, $env_rrnasensor_dir, \%opt_HH, $ofile_info_HH{"FH"});
my $qsub_prefix = undef; # qsub prefix for submitting jobs to the farm
my $qsub_suffix = undef; # qsub suffix for submitting jobs to the farm
if(opt_IsUsed("-p", \%opt_HH)) {
($qsub_prefix, $qsub_suffix) = ribo_ParseQsubFile($qsubinfo_file, $ofile_info_HH{"FH"});
}
###################################################################
# Step 1: Split up input sequence file into 3 files based on length
###################################################################
# The primary reason for the split is that rRNA_sensor uses different thresholds
# depending on whether the length is [0,350], [351,600}, or [601, infinity]
# The filter that rRNA sequences are expected to be below a certain length
# is applied within rRNA_sensor, not here.
# We do this split by length before running ribotyper, even though ribotyper is run
# on the full file. A beneficial side effect is that we exit early, if there
# is a detectable syntactic problem in the sequence file.
my $progress_w = 60; # the width of the left hand column in our progress output, hard-coded
my $start_secs;
my @seqorder_A = (); # array of sequences in order they appear in input file
my %seqidx_H = (); # key: sequence name, value: index of sequence in original input sequence file (1..$nseq)
my %seqlen_H = (); # key: sequence name, value: length of sequence
my %width_H = (); # hash, key is "model" or "target", value is maximum length of any model/target
my $tot_nseq = 0; # total number of sequences in the sequence file
my $tot_nnt = 0; # total number of nucleotides in the full sequence file
$width_H{"taxonomy"} = length("SSU.Euk-Microsporidia"); # longest possible classification in number of characters in the column header
$width_H{"strand"} = length("mixed(S):minus(R)"); # longest possible strand string in number of characters
$width_H{"index"} = length("#idx"); # longest possible index string in number of characters
my $ssi_file = $seq_file . ".ssi";
my $seqstat_file = $out_root . ".seqstat";
my $i;
my $nseq_parts = 3; # hard-coded, number of sequence partitions based on length
my @spart_minlen_A = (0, 351, 601); # hard-coded, minimum length for each sequence partition
my @spart_maxlen_A = (350, 600, -1); # hard-coded, maximum length for each sequence partition, -1 represents infinity
my @spart_desc_A = ("0..350", "351..600", "601..inf");
my $ncov_parts = 2; # hard-coded, number of coverage threshold partitions based on length
my @cpart_minlen_A = (0, 351); # hard-coded, minimum length for each coverage threshold partition
my @cpart_maxlen_A = (350, -1); # hard-coded, maximum length for each coverage threshold partition, -1 represents infinity
my @subseq_file_A = (); # array of fasta files that we fetch into
my @subseq_sfetch_A = (); # array of sfetch input files that we created
my @subseq_nseq_A = (); # array of number of sequences in each length range
my @subseq_nnt_A = (); # array of summed length of sequences in each length range
if(! opt_Get("--skipsearch", \%opt_HH)) {
$start_secs = ofile_OutputProgressPrior("Partitioning sequence file based on sequence lengths", $progress_w, $log_FH, *STDOUT);
# check for SSI index file for the sequence file,
# if it doesn't exist, create it
if(utl_FileValidateExistsAndNonEmpty($ssi_file, undef, undef, 0, $ofile_info_HH{"FH"}) != 1) {
utl_RunCommand($execs_H{"esl-sfetch"} . " --index $seq_file > /dev/null", opt_Get("-v", \%opt_HH), 0, $ofile_info_HH{"FH"});
if(utl_FileValidateExistsAndNonEmpty($ssi_file, undef, undef, 0, $ofile_info_HH{"FH"}) != 1) {
ofile_FAIL("ERROR, tried to create $ssi_file, but failed", 1, $ofile_info_HH{"FH"});
}
}
}
else {
$start_secs = ofile_OutputProgressPrior("Determining size of input sequence file", $progress_w, $log_FH, *STDOUT);
}
$tot_nnt = ribo_ProcessSequenceFile($execs_H{"esl-seqstat"}, $seq_file, $seqstat_file, \@seqorder_A, \%seqidx_H, \%seqlen_H, \%width_H, \%opt_HH, \%ofile_info_HH);
$tot_nseq = scalar(keys %seqidx_H);
if(length($tot_nseq) > $width_H{"index"}) {
$width_H{"index"} = length($tot_nseq);
}
if(! opt_Get("--keep", \%opt_HH)) {
push(@to_remove_A, $seqstat_file);
}
# create new files for the 3 sequence length ranges:
my $do_fetch = (opt_Get("--skipsearch", \%opt_HH)) ? 0 : 1; # do not fetch the sequences if --skipsearch enabled
for($i = 0; $i < $nseq_parts; $i++) {
$subseq_sfetch_A[$i] = $out_root . "." . ($i+1) . ".sfetch";
$subseq_file_A[$i] = $out_root . "." . ($i+1) . ".fa";
($subseq_nseq_A[$i], $subseq_nnt_A[$i]) = fetch_seqs_in_length_range($execs_H{"esl-sfetch"}, $seq_file, $do_fetch, $spart_minlen_A[$i], $spart_maxlen_A[$i], \%seqlen_H, $subseq_sfetch_A[$i], $subseq_file_A[$i], \%opt_HH, $ofile_info_HH{"FH"});
# files are marked for removal at this step, but not actually
# removed until the rRNA_sensor analysis has been completed
if(! opt_Get("--keep", \%opt_HH)) {
push(@to_remove_A, $subseq_sfetch_A[$i]);
if($subseq_nseq_A[$i] > 0) {
push(@to_remove_A, $subseq_file_A[$i]);
}
}
}
ofile_OutputProgressComplete($start_secs, undef, $log_FH, *STDOUT);
#############################################
# Step 2: Run ribotyper on full sequence file
#############################################
# It's important that we run ribotyper only once on the full file so that E-values are accurate.
my $ribo_dir_out = $dir_out . "/ribo-out";
my $ribo_stdoutfile = $out_root . ".ribotyper.stdout";
# determine ribotyper options
my $ribotyper_options = " -f -i $ribo_modelinfo_file --inaccept $ribo_accept_file --scfail --covfail --tshortcov 0.80 --tshortlen 350 ";
if(opt_IsUsed("-n", \%opt_HH)) { $ribotyper_options .= " -n " . opt_Get("-n", \%opt_HH); }
if(opt_IsUsed("-p", \%opt_HH)) { $ribotyper_options .= " -p"; }
if(opt_IsUsed("-q", \%opt_HH)) { $ribotyper_options .= " -q " . opt_Get("-q", \%opt_HH); }
if(opt_IsUsed("-s", \%opt_HH)) { $ribotyper_options .= " -s " . opt_Get("-s", \%opt_HH); }
if(opt_IsUsed("--nkb", \%opt_HH)) { $ribotyper_options .= " --nkb " . opt_Get("--nkb", \%opt_HH); }
if(opt_IsUsed("--wait", \%opt_HH)) { $ribotyper_options .= " --wait " . opt_Get("--wait", \%opt_HH); }
if(opt_IsUsed("--errcheck", \%opt_HH)) { $ribotyper_options .= " --errcheck"; }
if(opt_IsUsed("--keep", \%opt_HH)) { $ribotyper_options .= " --keep"; }
my $ribotyper_cmd = $execs_H{"ribo"} . " $ribotyper_options $seq_file $ribo_dir_out > $ribo_stdoutfile";
my $ribo_secs = 0.; # total number of seconds elapsed for ribotyper stage
my $ribo_p_secs = 0.; # if -p: summed number of seconds elapsed for all ribotyper jobs
my $ribo_shortfile = $ribo_dir_out . "/ribo-out.ribotyper.short.out";
my $ribo_logfile = $ribo_dir_out . "/ribo-out.ribotyper.log";
if(! opt_Get("--skipsearch", \%opt_HH)) {
$start_secs = ofile_OutputProgressPrior("Running ribotyper on full sequence file", $progress_w, $log_FH, *STDOUT);
utl_RunCommand($ribotyper_cmd, opt_Get("-v", \%opt_HH), 0, $ofile_info_HH{"FH"});
$ribo_secs = ofile_OutputProgressComplete($start_secs, undef, $log_FH, *STDOUT);
ofile_AddClosedFileToOutputInfo(\%ofile_info_HH, "ribostdout", $ribo_stdoutfile, 0, 1, "ribotyper stdout output");
}
# if 'time' is being used (only true if -p and 'time' exists): parse the ribotyper log file to get CPU+wait time for parallel
if($use_time_program) {
$ribo_p_secs = ribo_ParseLogFileForParallelTime($ribo_logfile, $ofile_info_HH{"FH"});
}
##############################################################################
# Step 3: Run rRNA_sensor on the (up to 3) length-partitioned sequence files
##############################################################################
my @sensor_dir_out_A = (); # [0..$i..$nseq_parts-1], directory created for sensor run on partition $i
my @sensor_stdoutfile_A = (); # [0..$i..$nseq_parts-1], standard output file for sensor run on partition $i
my @sensor_classfile_argument_A = (); # [0..$i..$nseq_parts-1], sensor script argument for classification output file for partition $i
my @sensor_classfile_fullpath_A = (); # [0..$i..$nseq_parts-1], full path to classification output file name for partition $i
my @sensor_minid_A = (); # [0..$i..$nseq_parts-1], minimum identity percentage threshold to use for round $i
my $sensor_cmd = undef; # command used to run sensor
my $sensor_minlen = opt_Get("--Sminlen", \%opt_HH);
my $sensor_maxlen = opt_Get("--Smaxlen", \%opt_HH);
my $sensor_maxevalue = opt_Get("--Smaxevalue", \%opt_HH);
my $sensor_secs = 0.; # total number of seconds elapsed for rRNA_sensor stage
my $sensor_p_secs = 0.; # if -p: summed number of seconds elapsed for all rRNA_sensor jobs
my $sensor_ncpu = ($ncpu == 0) ? 1 : $ncpu;
for($i = 0; $i < $nseq_parts; $i++) {
$sensor_minid_A[$i] = opt_Get("--Sminid" . ($i+1), \%opt_HH);
if($subseq_nseq_A[$i] > 0) {
$sensor_dir_out_A[$i] = $dir_out . "/sensor-" . ($i+1) . "-out";
$sensor_stdoutfile_A[$i] = $out_root . ".sensor-" . ($i+1) . ".stdout";
$sensor_classfile_argument_A[$i] = "sensor-class." . ($i+1) . ".out";
$sensor_classfile_fullpath_A[$i] = $sensor_dir_out_A[$i] . "/sensor-class." . ($i+1) . ".out";
#$sensor_cmd = $execs_H{"sensor"} . " $sensor_minlen $sensor_maxlen $subseq_file_A[$i] $sensor_classfile_argument_A[$i] $sensor_minid_A[$i] $sensor_maxevalue $sensor_ncpu $sensor_dir_out_A[$i] $sensor_blastdb > $sensor_stdoutfile_A[$i]";
if(! opt_Get("--skipsearch", \%opt_HH)) {
$start_secs = ofile_OutputProgressPrior("Running rRNA_sensor on seqs of length $spart_desc_A[$i]", $progress_w, $log_FH, *STDOUT);
my %info_H = ();
$info_H{"IN:seqfile"} = $subseq_file_A[$i];
$info_H{"minlen"} = $sensor_minlen;
$info_H{"maxlen"} = $sensor_maxlen;
$info_H{"OUT-DIR:classpath"} = $sensor_classfile_fullpath_A[$i];
$info_H{"OUT-DIR:lensum"} = $sensor_dir_out_A[$i] . "/length_summary1.txt";
$info_H{"OUT-DIR:blastout"} = $sensor_dir_out_A[$i] . "/middle_out_" . $sensor_blastdb . "_blastn_fmt6.txt";
$info_H{"minid"} = $sensor_minid_A[$i];
$info_H{"maxevalue"} = $sensor_maxevalue;
$info_H{"ncpu"} = $sensor_ncpu;
$info_H{"OUT-NAME:outdir"} = $sensor_dir_out_A[$i];
$info_H{"blastdb"} = $sensor_blastdb;
$info_H{"OUT-NAME:stdout"} = $sensor_stdoutfile_A[$i];
$info_H{"OUT-NAME:time"} = $sensor_stdoutfile_A[$i] . ".time";;
$info_H{"OUT-NAME:stderr"} = $sensor_stdoutfile_A[$i] . ".err";
$info_H{"OUT-NAME:qcmd"} = $sensor_stdoutfile_A[$i] . ".qcmd";
ribo_RunCmsearchOrCmalignOrRRnaSensorWrapper(\%execs_H, "rRNA_sensor_script", $qsub_prefix, $qsub_suffix, \%seqlen_H, $progress_w,
$out_root, $subseq_nseq_A[$i], $subseq_nnt_A[$i], "", \%info_H, \%opt_HH, \%ofile_info_HH);
if($use_time_program) {
$sensor_p_secs += ribo_ParseUnixTimeOutput($info_H{"OUT-NAME:time"}, $ofile_info_HH{"FH"});
}
$sensor_secs += ofile_OutputProgressComplete($start_secs, undef, $log_FH, *STDOUT);
ofile_AddClosedFileToOutputInfo(\%ofile_info_HH, "sensorstdout" . $i, $sensor_stdoutfile_A[$i], 0, 1, "rRNA_sensor stdout output for length class" . ($i+1));
if(! opt_IsUsed("--keep", \%opt_HH)) { # remove the fasta files that rRNA_sensor created
my $sensor_mid_fafile = $sensor_dir_out_A[$i] . "/middle_queries.fsa";
my $sensor_out_fafile = $sensor_dir_out_A[$i] . "/outlier_queries.fsa";
push(@to_remove_A, $sensor_mid_fafile);
push(@to_remove_A, $sensor_out_fafile);
}
}
}
else {
$sensor_dir_out_A[$i] = undef;
$sensor_stdoutfile_A[$i] = undef;
$sensor_classfile_fullpath_A[$i] = undef;
$sensor_classfile_argument_A[$i] = undef;
}
}
###########################################################################
# Step 4: Parse rRNA_sensor results and create intermediate file
###########################################################################
# define data structures for statistics/counts that we will output
my @outcome_type_A; # array of outcome 'types', in order they should be output
my @outcome_cat_A; # array of outcome 'categories' in order they should be output
my %outcome_ct_HH = (); # 2D hash of counts of 'outcomes'
# 1D key is outcome type, an element from @outcome_type_A
# 2D key is outcome category, an element from @outcome_cat_A
# value is count
my @herror_A = (); # array of 'human' error types, in order they should be output
my %herror_ct_HH = (); # 2D hash of counts of 'human' error types,
# 1D key is outcome type, e.g. "RPSF",
# 2D key is human error type, an element from @herror_A
# value is count
my %herror_failsto_H = (); # hash that explains if each human error fails to "submitter" or "indexer",
# key is $herror from @herror_A, value is "NONE, "submitter" or "indexer"
my @gerror_A = (); # array of 'genbank' error types, in order they should be output
my %gerror_ct_HH = (); # 2D hash of counts of 'genbank' error types,
# 1D key is outcome type, e.g. "RPSF",
# 2D key is genbank error type, an element from @gerror_A
# value is count
my @RPSF_ignore_A = (); # array of human errors to ignore for sequences that pass ribotyper and
# fail sensor (RPSF)
my @RFSP_ignore_A = (); # array of human errors to ignore for sequences that fail ribotyper and
# pass sensor (RFSP)
my %RFSF_ignore_HA = (); # hash of arrays, hash key: human error 1, value is array, where each element
# is human error 2..N. If human error 2..N is observed, then ignore human
# error 1 if sequence fails both ribotyper and sensor (RFSF)
my @indexer_A = (); # array of human errors that fail to indexer rather than submitter
my @submitter_A = (); # array of human errors that fail to submitter rather than indexer
@outcome_type_A = ("RPSP", "RPSF", "RFSP", "RFSF", "*all*");
@outcome_cat_A = ("total", "pass", "indexer", "submitter", "unmapped");
@herror_A = ("CLEAN",
"S_NoHits",
"S_TooLong",
"S_TooShort",
"S_LowScore",
"S_BothStrands",
"S_MultipleHits",
"S_NoSimilarity",
"S_LowSimilarity",
"R_NoHits",
"R_MultipleFamilies",
"R_BothStrands",
"R_UnacceptableModel",
"R_QuestionableModel",
"R_LowScore",
"R_LowCoverage",
"R_DuplicateRegion",
"R_InconsistentHits",
"R_MultipleHits");
@gerror_A = ("CLEAN",
"SEQ_HOM_NotSSUOrLSUrRNA",
"SEQ_HOM_SSUAndLSUrRNA",
"SEQ_HOM_LowSimilarity",
"SEQ_HOM_LengthShort",
"SEQ_HOM_LengthLong",
"SEQ_HOM_MisAsBothStrands",
"SEQ_HOM_MisAsHitOrder",
"SEQ_HOM_MisAsDupRegion",
"SEQ_HOM_TaxNotExpectedSSUrRNA",
"SEQ_HOM_TaxQuestionableSSUrRNA",
"SEQ_HOM_LowCoverage",
"SEQ_HOM_MultipleHits");
# hard-coded list of errors that we ignore when triggering GENBANK
# errors if sequence is RPSF (pass ribotyper, fail sensor) and -c not
# used
@RPSF_ignore_A = ("S_NoHits",
"S_LowScore",
"S_NoSimilarity",
"S_LowSimilarity");
# hard-coded list of errors that we ignore when triggering GENBANK
# errors if sequence is RFSP (fail ribotyper, pass sensor)
@RFSP_ignore_A = ("R_MultipleHits");
# hard-coded list of errors that we ignore (if other errors are also
# observed) when triggering GENBANK errors if sequence is RFSF (fail
# ribotyper, fail sensor), key is error to ignore, value is array of
# other errors, if any of the other errors are present we ignore the
# key error
@{$RFSF_ignore_HA{"S_NoHits"}} = ("R_UnacceptableModel", "R_QuestionableModel");
@{$RFSF_ignore_HA{"S_NoSimilarity"}} = ("R_UnacceptableModel", "R_QuestionableModel");
@{$RFSF_ignore_HA{"S_LowSimilarity"}} = ("R_UnacceptableModel", "R_QuestionableModel");
@{$RFSF_ignore_HA{"S_LowScore"}} = ("R_UnacceptableModel", "R_QuestionableModel");
# hard-coded list of errors that fail to the indexer, all other errors
# fail to the submitter
@indexer_A = ("R_QuestionableModel",
"R_LowCoverage",
"S_MultipleHits",
"R_MultipleHits");
# create the failsto hash, mapping each error type to indexer or submitter
define_failsto_hash(\@herror_A, \@indexer_A, \%herror_failsto_H);
# create the map of genbank errors to human errors
my %genbank2human_HH = ();
define_genbank_to_human_map(\%genbank2human_HH, \@gerror_A, \@herror_A);
$start_secs = ofile_OutputProgressPrior("Parsing and combining rRNA_sensor and ribotyper output", $progress_w, $log_FH, *STDOUT);
# parse rRNA_sensor file to create genbank format file
# first unsorted, then sort it.
parse_sensor_files($unsrt_sensor_indi_FH, \@sensor_classfile_fullpath_A, \@cpart_minlen_A, \@cpart_maxlen_A, \%seqidx_H, \%seqlen_H, \%width_H, \%opt_HH);
close($unsrt_sensor_indi_FH);
# sort sensor shortfile
output_headers_without_fails_to($sensor_indi_FH, \%width_H, $ofile_info_HH{"FH"});
close($sensor_indi_FH);
$cmd = "sort -n $unsrt_sensor_indi_file >> $sensor_indi_file";
utl_RunCommand($cmd, opt_Get("-v", \%opt_HH), 0, $ofile_info_HH{"FH"});
open($sensor_indi_FH, ">>", $sensor_indi_file) || die "ERROR, unable to open $sensor_indi_file for appending";
output_tail_without_fails_to($sensor_indi_FH, \%opt_HH);
close($sensor_indi_FH);
ofile_AddClosedFileToOutputInfo(\%ofile_info_HH, "sensorout", $sensor_indi_file, 1, 1, "summary of rRNA_sensor results");
# convert ribotyper output to genbank
output_headers_without_fails_to($ribo_indi_FH, \%width_H, $ofile_info_HH{"FH"});
convert_ribo_short_to_indi_file($ribo_indi_FH, $ribo_shortfile, \@herror_A, \%seqidx_H, \%width_H, \%opt_HH);
output_tail_without_fails_to($ribo_indi_FH, \%opt_HH);
close($ribo_indi_FH);
ofile_AddClosedFileToOutputInfo(\%ofile_info_HH, "riboout", $ribo_indi_file, 1, 1, "summary of ribotyper results");
initialize_hash_of_hash_of_counts(\%outcome_ct_HH, \@outcome_type_A, \@outcome_cat_A);
initialize_hash_of_hash_of_counts(\%herror_ct_HH, \@outcome_type_A, \@herror_A);
initialize_hash_of_hash_of_counts(\%gerror_ct_HH, \@outcome_type_A, \@gerror_A);
# combine sensor and ribotyper indi output files to get combined output file
output_headers_with_fails_to ($combined_out_FH, \%width_H, $ofile_info_HH{"FH"});
output_headers_without_fails_to($combined_genbank_FH, \%width_H, $ofile_info_HH{"FH"});
combine_genbank_files($combined_out_FH, $combined_genbank_FH, $sensor_indi_file, $ribo_indi_file,
\@gerror_A, \%genbank2human_HH, \%outcome_ct_HH,
\%herror_ct_HH, \%gerror_ct_HH,
(opt_Get("-c", \%opt_HH) ? undef : \@RPSF_ignore_A), # only ignore some sensor errors if -c not used
\@RFSP_ignore_A, # list of ribotyper errors to ignore if sensor pass
\%RFSF_ignore_HA, # list of errors to ignore if RFSF, if other errors are observed
\%herror_failsto_H, \%width_H, \%opt_HH);
output_tail_with_fails_to ($combined_out_FH, \%opt_HH);
output_tail_without_fails_to($combined_genbank_FH, \%opt_HH);
close($combined_out_FH);
close($combined_genbank_FH);
ofile_OutputProgressComplete($start_secs, undef, $log_FH, *STDOUT);
ofile_AddClosedFileToOutputInfo(\%ofile_info_HH, "combinedout", $combined_out_file, 1, 1, "summary of combined rRNA_sensor and ribotyper results (original errors)");
ofile_AddClosedFileToOutputInfo(\%ofile_info_HH, "combinedgenbank", $combined_genbank_file, 1, 1, "summary of combined rRNA_sensor and ribotyper results (GENBANK errors)");
# remove files we do not want anymore, then exit
foreach my $file (@to_remove_A) {
if(-e $file) {
unlink $file;
}
}
# save output files that were specified with cmdline options
my $nseq_passed = 0; # number of sequences
my $nseq_revcomped = 0; # number of sequences reverse complemented
if(opt_Get("--psave", \%opt_HH)) {
($nseq_passed, $nseq_revcomped) = fetch_seqs_given_genbank_file($execs_H{"esl-sfetch"}, $seq_file, $combined_out_file, "pass", 6, 1, $passes_sfetch_file, $passes_seq_file, \%seqlen_H, \%opt_HH, $ofile_info_HH{"FH"});
}
output_outcome_counts(*STDOUT, \%outcome_ct_HH, $ofile_info_HH{"FH"});
output_outcome_counts($log_FH, \%outcome_ct_HH, $ofile_info_HH{"FH"});
output_error_counts(*STDOUT, "Per-program error counts:", $tot_nseq, \%{$herror_ct_HH{"*all*"}}, \@herror_A, $ofile_info_HH{"FH"});
output_error_counts($log_FH, "Per-program error counts:", $tot_nseq, \%{$herror_ct_HH{"*all*"}}, \@herror_A, $ofile_info_HH{"FH"});
output_error_counts(*STDOUT, "GENBANK error counts:", $tot_nseq, \%{$gerror_ct_HH{"*all*"}}, \@gerror_A, $ofile_info_HH{"FH"});
output_error_counts($log_FH, "GENBANK error counts:", $tot_nseq, \%{$gerror_ct_HH{"*all*"}}, \@gerror_A, $ofile_info_HH{"FH"});
$total_seconds += ofile_SecondsSinceEpoch();
if((! opt_Get("-p", \%opt_HH)) || ($use_time_program)) {
output_timing_statistics(*STDOUT, $tot_nseq, $tot_nnt, $ncpu, $ribo_secs, $ribo_p_secs, $sensor_secs, $sensor_p_secs, $total_seconds, \%opt_HH, $ofile_info_HH{"FH"});
output_timing_statistics($log_FH, $tot_nseq, $tot_nnt, $ncpu, $ribo_secs, $ribo_p_secs, $sensor_secs, $sensor_p_secs, $total_seconds, \%opt_HH, $ofile_info_HH{"FH"});
}
else { # -p used and $RIBOTIMEDIR/time did not exist
ofile_OutputString($log_FH, 1, "#\n");
ofile_OutputString($log_FH, 1, sprintf("# Timing stats not computed because -p used and \$RIBOTIMEDIR/time executable did not exist or was not executable.\n"));
ofile_OutputString($log_FH, 1, "#\n");
}
printf("#\n# Human readable error-based output saved to file $combined_out_file\n");
printf("# GENBANK error-based output saved to file $combined_genbank_file\n");
if((opt_Get("--psave", \%opt_HH)) && ($nseq_passed > 0)) {
printf("#\n# The $nseq_passed sequences that passed (with $nseq_revcomped minus strand sequences\n# reverse complemented) saved to file $passes_seq_file\n");
}
ofile_OutputConclusionAndCloseFilesOk($total_seconds, $dir_out, \%ofile_info_HH);
exit(0);
###############
# SUBROUTINES #
###############
#################################################################
# Subroutine : fetch_seqs_in_length_range()
# Incept: EPN, Fri May 12 11:13:46 2017
#
# Purpose: Use esl-sfetch to fetch sequences in a given length
# range from <$seq_file> given the lengths in %{$seqlen_HR}.
#
# Arguments:
# $sfetch_exec: path to esl-sfetch executable
# $seq_file: sequence file to fetch sequences from
# $do_fetch: '1' to fetch the sequences, '0' not to
# $minlen: minimum length sequence to fetch
# $maxlen: maximum length sequence to fetch (-1 for infinity)
# $seqlen_HR: ref to hash of sequence lengths to fill here
# $sfetch_file: name of esl-sfetch input file to create
# $subseq_file: name of fasta file to create
# $opt_HHR: reference to 2D hash of cmdline options
# $FH_HR: ref to hash of file handles, including "cmd"
#
# Returns: Two values:
# $nseq_fetched: number of sequences fetched.
# $nnt_fetched: summed length of all seqs fetched.
#
# Dies: If the esl-sfetch command fails.
#
#################################################################
sub fetch_seqs_in_length_range {
my $nargs_expected = 10;
my $sub_name = "fetch_seqs_in_length_range";
if(scalar(@_) != $nargs_expected) { printf STDERR ("ERROR, $sub_name entered with %d != %d input arguments.\n", scalar(@_), $nargs_expected); exit(1); }
my ($sfetch_exec, $seq_file, $do_fetch, $minlen, $maxlen, $seqlen_HR, $sfetch_file, $subseq_file, $opt_HHR, $FH_HR) = (@_);
my $target; # name of a target sequence
my $nseq = 0; # number of sequences fetched
my $nnt = 0; # summed length of sequences fetched
open(SFETCH, ">", $sfetch_file) || die "ERROR unable to open $sfetch_file for writing";
foreach $target (keys %{$seqlen_HR}) {
if(! exists $seqlen_HR->{$target}) {
die "ERROR in $sub_name, no length data for $target";
}
if(($seqlen_HR->{$target} >= $minlen) &&
(($maxlen == -1) || ($seqlen_HR->{$target} <= $maxlen))) {
print SFETCH $target . "\n";
$nseq++;
$nnt += $seqlen_HR->{$target};
}
}
close(SFETCH);
if($nseq > 0 && ($do_fetch)) {
my $sfetch_cmd = $sfetch_exec . " -f $seq_file $sfetch_file > $subseq_file";
utl_RunCommand($sfetch_cmd, opt_Get("-v", $opt_HHR), 0, $FH_HR);
}
return ($nseq, $nnt);
}
#################################################################
# Subroutine : parse_sensor_files()
# Incept: EPN, Fri May 12 16:33:57 2017
#
# Purpose: For each sequence in a set of sensor 'classification'
# output files, output a single summary line to a new file.
#
# Arguments:
# $FH: filehandle to output to
# $classfile_AR: ref to array with names of sensor class files
# $minlen_AR: ref to array of minimum lengths for coverage threshold partitions
# $maxlen_AR: ref to array of maximum lengths for coverage threshold partitions
# $seqidx_HR: ref to hash of sequence indices
# $seqlen_HR: ref to hash of sequence lengths
# $width_HR: ref to hash with max lengths of sequence index and target
# $opt_HHR: reference to 2D hash of cmdline options
#
# Returns: Number of sequences fetched.
#
# Dies: If the esl-sfetch command fails.
#
#################################################################
sub parse_sensor_files {
my $nargs_expected = 8;
my $sub_name = "parse_sensor_files";
if(scalar(@_) != $nargs_expected) { printf STDERR ("ERROR, $sub_name entered with %d != %d input arguments.\n", scalar(@_), $nargs_expected); exit(1); }
my ($FH, $classfile_AR, $minlen_AR, $maxlen_AR, $seqidx_HR, $seqlen_HR, $width_HR, $opt_HHR) = (@_);
my $nclassfiles = scalar(@{$classfile_AR});
my $line = undef; # a line of input
my $seqid = undef; # name of a sequence
my $class = undef; # class of a sequence
my $strand = undef; # strand of a sequence
my $nhits = undef; # number of hits to a sequence
my $cov = undef; # coverage of a sequence;
my @el_A = (); # array of elements on a line
my $passfail = undef; # PASS or FAIL for a sequence
my $failmsg = undef; # list of errors for the sequence
my $i; # a counter
my $nexp_tokens = 5; # number of expected tokens/columns in a sensor 'class' file
# get the coverage thresholds for each coverage threshold partition
my $ncov_parts = scalar(@{$minlen_AR});
my $cthresh_all = opt_Get("--Smincovall", $opt_HHR);
my @cthresh_part_A = ();
my $cov_part = undef; # the coverage partition a sequence belongs to (index in $cthresh_part_)
for($i = 0; $i < $ncov_parts; $i++) {
$cthresh_part_A[$i] = opt_Get("--Smincov" . ($i+1), $opt_HHR);
}
foreach my $classfile (@{$classfile_AR}) {
if(defined $classfile) {
open(IN, $classfile) || die "ERROR unable to open $classfile for reading in $sub_name";
while($line = <IN>) {
# example lines:
#ALK.1_567808 imperfect_match minus 1 38
#T12A.3_40999 imperfect_match minus 1 41
#T13A.1_183523 imperfect_match minus 1 41
chomp $line;
my @el_A = split(/\t/, $line);
if(scalar(@el_A) != $nexp_tokens) { die "ERROR unable to parse sensor output file line: $line"; }
($seqid, $class, $strand, $nhits, $cov) = (@el_A);
$passfail = "PASS";
$failmsg = "";
# sanity check
if((! exists $seqidx_HR->{$seqid}) || (! exists $seqlen_HR->{$seqid})) {
die "ERROR in $sub_name, found unexpected sequence $seqid\n";
}
if($class eq "too long") {
$passfail = "FAIL";
$failmsg .= "S_TooLong;"; # TODO: add to analysis document
}
elsif($class eq "too short") {
$passfail = "FAIL";
$failmsg .= "S_TooShort;"; # TODO: add to analysis document
}
elsif($class eq "no") {
$passfail = "FAIL";
$failmsg .= "S_NoHits;"; # TODO: add to analysis document
}
elsif($class eq "yes") {
$passfail = "PASS";
}
#elsif($class eq "partial") {
# I think sensor no longer can output this
#}
elsif($class eq "imperfect_match") {
$passfail = "FAIL";
$failmsg .= "S_LowScore;";
}
# now stop the else, because remainder don't depend on class
if($strand eq "mixed") {
$passfail = "FAIL";
$failmsg .= "S_BothStrands;";
}
if(($nhits ne "NA") && ($nhits > 1)) {
$passfail = "FAIL";
$failmsg .= "S_MultipleHits;";
}
if($cov ne "NA") {
$cov_part = determine_coverage_threshold($seqlen_HR->{$seqid}, $minlen_AR, $maxlen_AR, $ncov_parts);
if($cov < $cthresh_all) {
$passfail = "FAIL";
$failmsg .= "S_NoSimilarity;";
# TODO put this in table 1 in analysis doc, in table 3 but not table 1
}
elsif($cov < $cthresh_part_A[$cov_part]) {
$passfail = "FAIL";
$failmsg .= "S_LowSimilarity;";
}
}
if($failmsg eq "") { $failmsg = "-"; }
output_genbank_line_without_fails_to($FH, $seqidx_HR->{$seqid}, $seqid, "?", $strand, $passfail, $failmsg, $width_HR, $opt_HHR);
}
}
}
return;
}
#################################################################
# Subroutine : determine_coverage_threshold()
# Incept: EPN, Fri May 12 17:02:43 2017
#
# Purpose: Given a sequence length and arrays of min and max values
# in arrays, determine what index of the array the length
# falls in between the min and max of.
#
# Arguments:
# $length: length of the sequence
# $min_AR: ref to array of minimum lengths for coverage threshold partitions
# $max_AR: ref to array of maximum lengths for coverage threshold partitions
# $n: size of the arrays
#
# Returns: Index (0..n-1).
#
# Dies: If $length is outside the range
#
#################################################################
sub determine_coverage_threshold {
my $nargs_expected = 4;
my $sub_name = "determine_coverage_threshold";
if(scalar(@_) != $nargs_expected) { printf STDERR ("ERROR, $sub_name entered with %d != %d input arguments.\n", scalar(@_), $nargs_expected); exit(1); }
my ($length, $min_AR, $max_AR, $n) = (@_);
my $i; # counter
for($i = 0; $i < $n; $i++) {
if($length < $min_AR->[$i]) { die "ERROR in $sub_name, length $length out of bounds (too short)"; }
if(($max_AR->[$i] == -1) || ($length <= $max_AR->[$i])) {
return $i;
}
}
die "ERROR in $sub_name, length $length out of bounds (too long)";
return 0; # never reached
}
#################################################################
# Subroutine : output_headers_without_fails_to()
# Incept: EPN, Sat May 13 05:51:17 2017
#
# Purpose: Output column headers to a genbank format output
# file for either sensor or ribotyper.
#
# Arguments:
# $FH: file handle to output to
# $width_HR: ref to hash, keys include "model" and "target",
# value is width (maximum length) of any target/model
# $FH_HR: ref to hash of file handles, including "cmd"
#
# Returns: Nothing.
#
# Dies: Never.
#
#################################################################
sub output_headers_without_fails_to {
my $nargs_expected = 3;
my $sub_name = "output_headers_without_fails_to";
if(scalar(@_) != $nargs_expected) { printf STDERR ("ERROR, $sub_name entered with %d != %d input arguments.\n", scalar(@_), $nargs_expected); exit(1); }
my ($FH, $width_HR, $FH_HR) = (@_);
my $index_dash_str = "#" . utl_StringMonoChar($width_HR->{"index"}-1, "-", $FH_HR);
my $target_dash_str = utl_StringMonoChar($width_HR->{"target"}, "-", $FH_HR);
my $tax_dash_str = utl_StringMonoChar($width_HR->{"taxonomy"}, "-", $FH_HR);
my $strand_dash_str = utl_StringMonoChar($width_HR->{"strand"}, "-", $FH_HR);
printf $FH ("%-*s %-*s %-*s %-*s %4s %s\n",
$width_HR->{"index"}, "#idx",
$width_HR->{"target"}, "sequence",
$width_HR->{"taxonomy"}, "taxonomy",
$width_HR->{"strand"}, "strand",
"p/f", "error(s)");
printf $FH ("%s %s %s %s %s %s\n", $index_dash_str, $target_dash_str, $tax_dash_str, $strand_dash_str, "----", "--------");
return;
}
#################################################################
# Subroutine : output_headers_with_fails_to()
# Incept: EPN, Mon May 22 14:51:15 2017
#
# Purpose: Output combined output file headers
#
# Arguments:
# $FH: file handle to output to
# $width_HR: ref to hash, keys include "model" and "target",
# value is width (maximum length) of any target/model
# $FH_HR: ref to hash of file handles, including "cmd"
#
# Returns: Nothing.
#
# Dies: Never.
#
#################################################################
sub output_headers_with_fails_to {
my $nargs_expected = 3;
my $sub_name = "output_headers_with_fails_to";
if(scalar(@_) != $nargs_expected) { printf STDERR ("ERROR, $sub_name entered with %d != %d input arguments.\n", scalar(@_), $nargs_expected); exit(1); }
my ($FH, $width_HR, $FH_HR) = (@_);