File: rtaxSearch.pl

package info (click to toggle)
rtax 0.984-7
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 308 kB
  • sloc: perl: 1,123; sh: 203; makefile: 2
file content (1062 lines) | stat: -rwxr-xr-x 40,395 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
#!/usr/bin/perl

# RTAX: Rapid and accurate taxonomic classification of short paired-end
#       sequence reads from the 16S ribosomal RNA gene.
#
# David A. W. Soergel 1*, Rob Knight 2, and Steven E. Brenner 1
#
# 1 Department of Plant and Microbial Biology,
#   University of California, Berkeley
# 2 Howard Hughes Medical Institute and Department of Chemistry
#   and Biochemistry, University of Colorado at Boulder
# * Corresponding author: soergel@cs.umass.edu
#
# http://www.davidsoergel.com/rtax
#
# Version 0.984  (August 7, 2013)
#
# For usage instructions: just run the script with no arguments
#
#
# Copyright (c) 2011 Regents of the University of California
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#     * Redistributions of source code must retain the above copyright notice,
#       this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of the University of California, Berkeley nor the
#       names of its contributors may be used to endorse or promote products
#       derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use strict;
use warnings;
use Getopt::Long;
use File::Temp qw/ tempdir /;

use FindBin;
use lib "$FindBin::Bin";
use FastaIndex;

### command-line arguments get stored in globals

use vars qw (
    $usearch
    $slop
    $minMaxAccepts
    $maxMaxAccepts
    $maxPercentDifferenceThreshold
    $databaseFile
    $readAFileAll
    $readBFileAll
    $revCompReadA
    $revCompReadB
    $idRegex
    $idList
    $singleOK
    $singleOKgeneric
);

# just store these as globals for now-- they're basically like command-line args
my $indexA;
my $indexB;

sub init {
    $singleOKgeneric = 1;    # default value; GetOptions may override

    Getopt::Long::Configure("bundling");
    GetOptions(
        "usearch=s"                       => \$usearch,
        "slop=s"                          => \$slop,
        "minMaxAccepts=s"                 => \$minMaxAccepts,
        "maxMaxAccepts=s"                 => \$maxMaxAccepts,
        "maxPercentDifferenceThreshold=s" => \$maxPercentDifferenceThreshold,
        "databaseFile=s"                  => \$databaseFile,
        "idRegex=s"                       => \$idRegex,
        "queryA=s"                        => \$readAFileAll,
        "queryB=s"                        => \$readBFileAll,
        "revcompA"                        => \$revCompReadA,
        "revcompB"                        => \$revCompReadB,
        "idList=s"                        => \$idList,
        "singleOK"                        => \$singleOK,
        "singleOKgeneric!"                => \$singleOKgeneric
    );

    if (   !defined $databaseFile
        || !defined $readAFileAll )
    {
        print STDERR "Missing required argument!\n\n";
        usage();
    }

    if ( !defined $usearch ) {
        $usearch = `whereis usearch`;
        chomp $usearch;
        if ( !defined $usearch || $usearch eq "" ) {
            print STDERR "Could not find usearch.\n\n";
            usage();
        }
    }

    if ( !defined $slop )          { $slop          = 0.005; }
    if ( !defined $minMaxAccepts ) { $minMaxAccepts = 1000; }
    if ( !defined $maxMaxAccepts ) { $maxMaxAccepts = 16000; }
    if ( !defined $maxPercentDifferenceThreshold ) {
        $maxPercentDifferenceThreshold = 0.2;
    }
    if ( !defined $idRegex || $idRegex eq "" ) { $idRegex = "(\\S+)"; }
    print STDERR "Header Regex: $idRegex\n";

    # these are redundant between multiple runs, oh well
    # but the DBM indexes should persist, in the same directory as the original files
    $indexA = FastaIndex->new();    # '-filename' => "A.idx", '-write_flag' => 1 );
	if ($revCompReadA) {
            $readAFileAll = revcompFile($readAFileAll);
        }
    $indexA->make_index( $readAFileAll, $idRegex, $readAFileAll );

    $indexB = FastaIndex->new();
    if ( defined $readBFileAll ) {    # '-filename' => "B.idx", '-write_flag' => 1 );
        if ($revCompReadB) {
            $readBFileAll = revcompFile($readBFileAll);
        }
        $indexB->make_index( $readBFileAll, $idRegex, $readBFileAll );
    }
}

sub usage {
    print STDERR << "EOF";

RTAX: Rapid and accurate taxonomic classification of short paired-end
      sequence reads from the 16S ribosomal RNA gene.
      
David A. W. Soergel (1*), Rob Knight (2), and Steven E. Brenner (1)
1 Department of Plant and Microbial Biology, University of California, Berkeley 
2 Howard Hughes Medical Institute and Department of Chemistry and Biochemistry,
  University of Colorado at Boulder
* Corresponding author: soergel\@berkeley.edu

http://www.davidsoergel.com/rtax

Version 0.984  (August 7, 2013)

OPTIONS:

    --usearch <path>    location of usearch program
                        (defaults to result of "whereis usearch")
     
    --slop <number>     %id difference from maximum to accept
                        (default 0.005, i.e. accept hits to a 200nt query that
                        has 1 more mismatch than the best match, or 2 extra
                        mismatches out of 400nt.)
     
    --minMaxAccepts <number>
                        The initial maxaccepts value to pass to USEARCH,
                        controlling the maximum number of hits that will be
                        returned in the first iteration.  If this number of hits
                        is reached, the search is repeated with a doubled
                        maxaccepts value.  Thus, a smaller value causes the
                        first iteration to run faster, but increases the
                        probability of needing more iterations.
                        (Default 1000)
     
    --maxMaxAccepts <number>
                        The highest escalated maxaccepts value to allow.  The
                        maxaccepts value is doubled on every iteration, so this
                        value is effectively rounded down to a power of two 
                        factor of minMaxAccepts.  USEARCH runs with large 
                        maxaccepts values are very slow, so this controls when 
                        RTAX gives up on a query because there are too many
                        hits (i.e., a query that is too short and/or too highly
                        conserved to be informative).  (Default 16000) 

    --maxPercentDifferenceThreshold <number>
                        The largest percent difference to allow between a query
                        (considering the read pair jointly) and a database hit.
                        (Default 0.2, i.e. reference sequences of less than 80%
                        identity with the query sequence are never matched)

    --databaseFile <file>
                        A FASTA file containing a reference database.
                        
    --queryA <file>     A FASTA file containing one set of query reads.
    
    --queryB <file>     A FASTA file containing the other set of query reads
                        (if any).  Must be provided in the forward sense
                        unless --revcompB is used.

    --revcompB          Reverse-complement read B.  Required if the queryB file
                        is provided in the reverse sense, as is typical with
                        paired-end experiments.
                        
    --singleOK          Classify a sequence based on only one read when the
                        other read is missing.  Required when queryB is absent.
                        Default: false, so sequences present in only one of the
                        two input files are dropped.  When enabled, paired-end
                        sequences are classified using both reads as usual, but
                        any remaining single-ended reads are also classified.
                        
    --singleOKgeneric   Classify a sequence based on only one read when the
                        other read is present but uninformative.  This occurs
                        when one read is so generic (i.e., short, or highly
                        conserved) that more than maxMaxAccepts hits are
                        found.  Default: true; use --nosingleOKgeneric to
                        disable.
    
    --idRegex <regex>   A regular expression for extracting IDs from fasta
                        headers.  The first capture group (aka \$1) will be
                        used as the sequence ID; these should be unique.
                        This is useful when the ID needed to match mate
                        pairs is embedded in the header in some way.
                        "^>" is automatically prepended to the regex
                        provided here.  Take care that double escaping may
                        be required.  Default: "(\\S+)" (the first field)
    
    --idList <file>     A file containing a list of IDs to process (one per 
                        line).  By default all IDs found in the query files
                        are used.
    
    Note that the two query files must provide mate-paired reads with exactly
    matching identifiers (though they need not be in the same order).  Any ids
    present in one file but not the other are classified in single-ended mode.
    Alternate naming schemes for the paired reads (e.g., "SOMEID.a" paired with
    "SOMEID.b", and so forth) are handled via the --idRegex option.
    
    Various indexes and derived FASTA files will be created in a temporary
    directory and are cleaned up afterwards.
    
    The output is tab-delimited text, one line per query pair, in the form
    
        <query ID>  <%id>   <list of reference IDs>
    
    where the second column gives the %id between the query and the best match,
    and the reference IDs provided are all those matches within "slop" of this
    best value.
    
    This output is suitable for piping directly into rtaxVote for taxonomy
    assignment.

EOF

    exit;
}

sub main {

    init();

    my ( $pairedReadAFile, $pairedReadBFile, $pairedBothCount, $singleReadAFile, $singleReadACount, $singleReadBFile, $singleReadBCount, $allSingleIDs ) =
        partitionReadFiles();

    processPairs( $pairedReadAFile, $pairedReadBFile, $pairedBothCount );

    if ($singleOK) {
        processSingle( $singleReadAFile, $indexA, $singleReadACount );
        processSingle( $singleReadBFile, $indexB, $singleReadBCount );
    }
	else {
		for my $queryLabel (@$allSingleIDs) {
        	print "$queryLabel\t\tNOMATEPAIR\n";
    	}
	}
}

sub partitionReadFiles {

    my @idList = ();
    if ($idList) {
        open( IDLIST, "$idList" ) or die "Could not open $idList";
        while (<IDLIST>) { chomp; push @idList, $_; }
        close IDLIST;
    }

    my @idsA = keys %{ $indexA->startpos() };
    my @idsB =
        defined $indexB->startpos() ? keys %{ $indexB->startpos() } : ();    # in the single-read case, there should still be an empty index

    my @bothAandB = ();
    my @aOnly     = ();
    my @bOnly     = ();

    # encode which of the input files contain which IDs in three bits

    my %count = ();

    foreach my $element (@idsA) {
        if ( ( $element =~ /[\t ]/ ) > 0 )                                   # $indexA->db() should return parsed IDs with no whitespace
        {
            die "Invalid FASTA id: $element\n";
        }
        $count{$element} += 1;
    }

    foreach my $element (@idsB) {
        if ( ( $element =~ /[\t ]/ ) > 0 )                                   # $indexA->db() should return parsed IDs with no whitespace
        {
            die "Invalid FASTA id: $element\n";
        }
        $count{$element} += 2;
    }

    foreach my $element (@idList) {
        if ( ( $element =~ /[\t ]/ ) > 0 ) { die "Invalid FASTA id: $element\n"; }
        $count{$element} += 4;
    }

    if ($idList) {
        foreach my $element ( keys %count ) {
            $count{$element} -= 4;
        }
    }

    foreach my $element ( keys %count ) {
        if ( !( $element =~ /^__/ ) ) {
            if    ( $count{$element} == 1 ) { push @aOnly,     $element }
            elsif ( $count{$element} == 2 ) { push @bOnly,     $element }
            elsif ( $count{$element} == 3 ) { push @bothAandB, $element }
            else {

                # no problem; these are sequences not in the idList
            }
        }
    }

    print STDERR "file a only = " . scalar(@aOnly) . " sequences\n";
    print STDERR "file b only = " . scalar(@bOnly) . " sequences\n";
    print STDERR "both        = " . scalar(@bothAandB) . " sequences\n";

    my $pairedReadAFile = extractFasta( $indexA, \@bothAandB );
    my $pairedReadBFile = extractFasta( $indexB, \@bothAandB );

    my $singleReadAFile = extractFasta( $indexA, \@aOnly );
    my $singleReadBFile = extractFasta( $indexB, \@bOnly );

	my @allSingleIDs = (@aOnly, @bOnly);

    return ( $pairedReadAFile, $pairedReadBFile, scalar(@bothAandB), $singleReadAFile, scalar(@aOnly), $singleReadBFile, scalar(@bOnly), \@allSingleIDs );
}

sub processPairs {
    my ( $pairedReadAFile, $pairedReadBFile, $pairedBothCount ) = @_;
    if ( $pairedBothCount == 0 ) { return; }

    my $nohitQueryIds = [];
    push @$nohitQueryIds, "ALL";
    my $tooManyHitQueryIds = [];

    my $percentDifferenceThreshold = 0.005;    # this gets doubled to 1% before being used the first time

    while ( @$nohitQueryIds > 0 ) {

        # double the allowed %diff on every round
        $percentDifferenceThreshold *= 2;
        if ( $percentDifferenceThreshold > $maxPercentDifferenceThreshold ) {
            last;
        }

        if ( $nohitQueryIds->[0] ne "ALL" ) {

            # prepare input files with the remaining sequences
            $pairedReadAFile = extractFasta( $indexA, $nohitQueryIds );
            $pairedReadBFile = extractFasta( $indexB, $nohitQueryIds );
        }

        # within doPairSearch we escalate maxAccepts, so if a queryLabel is still marked tooManyHits at this point,
        # that means that there are more than maxMaxAccepts hits for this threshold--
        # so there's really no point in testing this query again at an even lower threshold
        my $tooManyHitQueryIdsThisRound;

        my $numRemaining = ( $nohitQueryIds->[0] eq "ALL" ) ? $pairedBothCount : scalar(@$nohitQueryIds);

        print STDERR
            "doPairSearch $pairedReadAFile, $pairedReadBFile: $numRemaining query sequences remaining\n     searching with pair %id "
            . $percentDifferenceThreshold
            . " and maxAccepts "
            . $minMaxAccepts . "\n";

        ( $nohitQueryIds, $tooManyHitQueryIdsThisRound ) =
            doPairSearch( $pairedReadAFile, $pairedReadBFile, $percentDifferenceThreshold, $minMaxAccepts );

        print STDERR "MAIN: Finished round at threshold $percentDifferenceThreshold; "
            . scalar(@$nohitQueryIds)
            . " NOHIT, "
            . scalar(@$tooManyHitQueryIdsThisRound)
            . " TOOMANYHIT.\n";

        push @$tooManyHitQueryIds, @$tooManyHitQueryIdsThisRound;
    }

    print STDERR "MAIN: " . scalar(@$nohitQueryIds) . " query sequences remaining with NOHIT\n";
    for my $queryLabel (@$nohitQueryIds) {
        print "$queryLabel\t\tNOHIT\n";
    }

    print STDERR "MAIN: " . scalar(@$tooManyHitQueryIds) . " query sequences remaining with TOOMANYHITS\n";
    for my $queryLabel (@$tooManyHitQueryIds) {
        print "$queryLabel\t\tTOOMANYHITS\n";
    }
}

sub processSingle {
    my ( $singleReadFile, $singleIndex, $singleReadCount ) = @_;
    if ( !defined $singleReadFile || $singleReadFile eq "" || $singleReadCount == 0 ) { return; }

    my $nohitQueryIds = [];
    push @$nohitQueryIds, "ALL";
    my $tooManyHitQueryIds = [];

    my $singlePercentDifferenceThreshold = 0.005;    # this gets doubled to 1% before being used the first time

    while ( @$nohitQueryIds > 0 ) {

        # double the allowed %diff on every round
        $singlePercentDifferenceThreshold *= 2;
        if ( $singlePercentDifferenceThreshold > $maxPercentDifferenceThreshold ) {
            last;
        }

        if ( $nohitQueryIds->[0] ne "ALL" ) {

            # prepare input files with the remaining sequences
            $singleReadFile = extractFasta( $singleIndex, $nohitQueryIds );
        }

        my $numRemaining = ( $nohitQueryIds->[0] eq "ALL" ) ? $singleReadCount : scalar(@$nohitQueryIds);

        # within doSearch we escalate maxAccepts, so if a queryLabel is still marked tooManyHits at this point,
        # that means that there are more than maxMaxAccepts hits for this threshold--
        # so there's really no point in testing this query again at an even lower threshold
        my $tooManyHitQueryIdsThisRound;

        print STDERR "doSingleSearch $singleReadFile: $numRemaining query sequences remaining\n     searching with %id "
            . $singlePercentDifferenceThreshold
            . " and maxAccepts "
            . $minMaxAccepts . "\n";

        ( $nohitQueryIds, $tooManyHitQueryIdsThisRound ) =
            doSingleSearch( $singleReadFile, $singleIndex, $singlePercentDifferenceThreshold, $minMaxAccepts );

        print STDERR "Finished round at threshold $singlePercentDifferenceThreshold; "
            . scalar(@$nohitQueryIds)
            . " NOHIT, "
            . scalar(@$tooManyHitQueryIdsThisRound)
            . " TOOMANYHIT.\n";

        push @$tooManyHitQueryIds, @$tooManyHitQueryIdsThisRound;
    }

    print STDERR scalar(@$nohitQueryIds) . " query sequences remaining with NOHIT\n";
    for my $queryLabel (@$nohitQueryIds) {
        print "$queryLabel\t\tNOHIT\n";
    }

    print STDERR scalar(@$tooManyHitQueryIds) . " query sequences remaining with TOOMANYHITS\n";
    for my $queryLabel (@$tooManyHitQueryIds) {
        print "$queryLabel\t\tTOOMANYHITS\n";
    }

}

sub doSingleSearch {
    my $singleReadFile                   = shift;
    my $singleIndex                      = shift;
    my $singlePercentDifferenceThreshold = shift;
    my $maxAccepts                       = shift;

    my $singlePercentIdThreshold = 1. - $singlePercentDifferenceThreshold;

    my $nohitQueryIds      = [];
    my $tooManyHitQueryIds = [];

# open the USEARCH streams
#  print STDERR "$usearch --quiet --global --iddef 2 --query $singleReadFile --db $databaseFile --uc /dev/stdout --id $singlePercentIdThreshold --maxaccepts $maxAccepts --maxrejects 128 --nowordcountreject\n";
# open( UCA,
# "$usearch --quiet --global --iddef 2 --query $singleReadFile --db $databaseFile --uc /dev/stdout --id $singlePercentIdThreshold --maxaccepts $maxAccepts --maxrejects 128 --nowordcountreject |"
#    ) || die "can't fork usearch: $!";

    my $dir = tempdir(CLEANUP => 1);
    if ( system( 'mknod', "$dir/a", 'p' ) && system( 'mkfifo', "$dir/a" ) ) { die "mk{nod,fifo} $dir/a failed"; }
    if ( !fork() ) {

        # see paired end case for explanation
        open( UCAW, ">$dir/a" ) || die("Couldn't write named pipe: $dir/a");
        print UCAW "# pipe open!\n";
        close UCAW;

        my $cmd =
"$usearch --quiet --global --iddef 2 --query $singleReadFile --db $databaseFile --uc $dir/a --id $singlePercentIdThreshold --maxaccepts $maxAccepts --maxrejects 128 --nowordcountreject";
        print STDERR $cmd . "\n";
        exec $cmd || die "can't fork usearch: $!";
    }

    open( UCA, "$dir/a" ) || die("Couldn't read named pipe from usearch: $dir/a");

    #print STDERR "Reading named pipe from usearch: $dir/a\n";

    # Load the first non-comment line from each stream
    my $nextLineA;
    my $pipeARetryCount = 0;
    while ( !defined $nextLineA ) {

        # keep trying to read from the pipe even if the writer disconnects
        while (<UCA>) {
            if (/^\s*#/) { next; }
            if (/^\s*$/) { next; }
            $nextLineA = $_;
            last;
        }

        #print STDERR "Waiting for named pipe $dir/a\n";
        sleep 1;
        $pipeARetryCount++;
        if ( $pipeARetryCount > 10 ) { die "Named pipe communication with usearch failed: $dir/a\n"; }
    }

    # read synchronized blocks from each stream
    while (1) {
        my ( $queryLabelA, $idsA );

        #print STDERR "reading next block...\n";

        # idsA is a reference to a hash from targetIds to %ids
        ( $queryLabelA, $idsA, $nextLineA ) = collectIds( *UCA, $nextLineA );

        if ( ( scalar keys %$idsA ) >= $maxAccepts ) {
            push @$tooManyHitQueryIds, $queryLabelA;
        }

        elsif ( !reconcileSingleHitsAndPrint( $queryLabelA, $idsA, $singlePercentIdThreshold ) ) {
            push @$nohitQueryIds, $queryLabelA;
        }

        if ( !$nextLineA ) {

            #print STDERR "End of stream, close\n";
            last;
        }

    }

    close(UCA) || die "can't close usearch: $!";

    #print STDERR "Closed usearch stream.\n";

    # for the TOOMANYHITS cases, escalate maxAccepts and try again
    # Note this recurses, so no need to iterate here
    if ( scalar(@$tooManyHitQueryIds) && ( $maxAccepts * 2 <= $maxMaxAccepts ) ) {
        my $nohitQueryIdsB;

        print STDERR "Escalating maxAccepts to " . ( $maxAccepts * 2 ) . " for " . scalar(@$tooManyHitQueryIds) . " sequences.\n";

        # prepare input files with the remaining sequences
        $singleReadFile = extractFasta( $singleIndex, $tooManyHitQueryIds );

        ( $nohitQueryIdsB, $tooManyHitQueryIds ) =
            doSingleSearch( $singleReadFile, $singleIndex, $singlePercentDifferenceThreshold, $maxAccepts * 2 );
        if (@$nohitQueryIdsB) {
            die "A TOOMANYHITS case can't turn into a NOHITS case";
        }
    }

    print STDERR
        "doSingleSearch $singleReadFile: Finished at pair threshold $singlePercentDifferenceThreshold and maxAccepts $maxAccepts\n";
    print STDERR "         NOHITS: " . scalar(@$nohitQueryIds) . "\n";
    print STDERR "    TOOMANYHITS: " . scalar(@$tooManyHitQueryIds) . "\n";

    # print STDERR "         NOHITS: " .      ( join ", ", @$nohitQueryIds ) . "\n";
    # print STDERR "    TOOMANYHITS: " . ( join ", ", @$tooManyHitQueryIds ) . "\n";

    # any tooManyHitQueryIds that remain had more than maxMaxAccepts hits
    return ( $nohitQueryIds, $tooManyHitQueryIds );
}

sub reconcileSingleHitsAndPrint {
    my ( $queryLabel, $idsA, $singlePercentIdThreshold ) = @_;

    my $idsByIdentity = {};
    for my $targetLabel ( keys %$idsA ) {
        my $percentIdA = $idsA->{$targetLabel};
        if ( !defined $idsByIdentity->{$percentIdA} ) {
            $idsByIdentity->{$percentIdA} = [];
        }
        push @{ $idsByIdentity->{$percentIdA} }, $targetLabel;

    }

    if ( !%$idsByIdentity ) {

        #print STDERR "$queryLabel -> no reconciled hits at $singlePercentIdThreshold%\n";

        # this is the NOHIT case, but we'll back off and try again
        return 0;
    }
    else {

        #print STDERR "$queryLabel -> printing reconciled hits at $singlePercentIdThreshold%\n";
        printLine( $queryLabel, $idsByIdentity );
        return 1;
    }

}

sub doPairSearch {
    my $readAFile                      = shift;
    my $readBFile                      = shift;
    my $pairPercentDifferenceThreshold = shift;
    my $maxAccepts                     = shift;

    my $pairPercentIdThreshold = 1. - $pairPercentDifferenceThreshold;

    # because we're going to average the two %ids, we have to search each read with twice the %diff for the pair
    my $singlePercentDifferenceThreshold = $pairPercentDifferenceThreshold * 2;
    my $singlePercentIdThreshold         = 1. - $singlePercentDifferenceThreshold;

    my $nohitQueryIds      = [];
    my $tooManyHitQueryIds = [];

# open the USEARCH streams
#    print STDERR
#"$usearch --quiet --global --iddef 2 --query $readAFile --db $databaseFile --uc /dev/stdout --id $singlePercentIdThreshold --maxaccepts $maxAccepts --maxrejects 128 --nowordcountreject\n";

#    open( UCA,
#"$usearch --quiet --global --iddef 2 --query $readAFile --db $databaseFile --uc /dev/stdout --id $singlePercentIdThreshold --maxaccepts $maxAccepts --maxrejects 128 --nowordcountreject |"
#    ) || die "can't fork usearch: $!";

#    print STDERR
#"$usearch --quiet --global --iddef 2 --query $readBFile --db $databaseFile --uc /dev/stdout --id $singlePercentIdThreshold --maxaccepts $maxAccepts --maxrejects 128 --nowordcountreject\n";

#    open( UCB,
#"$usearch --quiet --global --iddef 2 --query $readBFile --db $databaseFile --uc /dev/stdout --id $singlePercentIdThreshold --maxaccepts $maxAccepts --maxrejects 128 --nowordcountreject |"
#    ) || die "can't fork usearch: $!";

    my $dir = tempdir(CLEANUP => 1);
    if ( system( 'mknod', "$dir/a", 'p' ) && system( 'mkfifo', "$dir/a" ) ) { die "mk{nod,fifo} $dir/a failed"; }
    if ( system( 'mknod', "$dir/b", 'p' ) && system( 'mkfifo', "$dir/b" ) ) { die "mk{nod,fifo} $dir/b failed"; }

    # try to avoid mysterious intermittent condition where opening a named pipe blocks forever
    #while ( !-p "$dir/a" ) {
    #    print STDERR "Waiting for named pipe $dir/a\n";
    #    sleep 1;
    #}
    #while ( !-p "$dir/b" ) {
    #    print STDERR "Waiting for named pipe $dir/b\n";
    #    sleep 1;
    #}

    if ( !fork() ) {

# there is a mysterious intermittent condition where opening a named pipe blocks forever.
# I think what is happening may be:
# if the reader side of the named pipe is not already connected when usearch tries to write to it, usearch gets confused and never writes anything
# thus when the reader side does connect, it blocks.

        # one hack is just to sleep here for a while in hopes that the reader thread gets all hooked up
        # sleep 5;

        # let's try writing to it, so we block here until we know it works, and then continue on to usearch
        open( UCAW, ">$dir/a" ) || die("Couldn't write named pipe: $dir/a");
        print UCAW "# pipe open!\n";
        close UCAW;

        my $cmd =
"$usearch --quiet --global --iddef 2 --query $readAFile --db $databaseFile --uc $dir/a --id $singlePercentIdThreshold --maxaccepts $maxAccepts --maxrejects 128 --nowordcountreject";
        print STDERR $cmd . "\n";
        exec $cmd || die("can't fork usearch: $!");
    }

    if ( !fork() ) {
        open( UCBW, ">$dir/b" ) || die("Couldn't write named pipe: $dir/b");
        print UCBW "# pipe open!\n";
        close UCBW;

        my $cmd =
"$usearch --quiet --global --iddef 2 --query $readBFile --db $databaseFile --uc $dir/b --id $singlePercentIdThreshold --maxaccepts $maxAccepts --maxrejects 128 --nowordcountreject";
        print STDERR $cmd . "\n";
        exec $cmd || die("can't fork usearch: $!");
    }
    open( UCA, "$dir/a" ) || die("Couldn't read named pipe from usearch: $dir/a");

    #print STDERR "Reading named pipe from usearch: $dir/a\n";

    open( UCB, "$dir/b" ) || die("Couldn't read named pipe from usearch: $dir/b");

    #print STDERR "Reading named pipe from usearch: $dir/b\n";

    # Load the first non-comment line from each stream
    my $nextLineA;
    my $pipeARetryCount = 0;
    while ( !defined $nextLineA ) {

        # keep trying to read from the pipe even if the writer disconnects
        while (<UCA>) {
            if (/^\s*#/) { next; }
            if (/^\s*$/) { next; }
            $nextLineA = $_;
            last;
        }

        #print STDERR "Waiting for named pipe $dir/a\n";
        sleep 1;
        $pipeARetryCount++;
        if ( $pipeARetryCount > 10 ) { die("Named pipe communication with usearch failed: $dir/a\n"); }
    }

    my $nextLineB;
    my $pipeBRetryCount = 0;
    while ( !defined $nextLineB ) {

        # keep trying to read from the pipe even if the writer disconnects
        while (<UCB>) {
            if (/^\s*#/) { next; }
            if (/^\s*$/) { next; }
            $nextLineB = $_;
            last;
        }

        #print STDERR "Waiting for named pipe $dir/b\n";
        sleep 1;
        $pipeBRetryCount++;
        if ( $pipeBRetryCount > 10 ) { die("Named pipe communication with usearch failed: $dir/b\n"); }
    }

    # read synchronized blocks from each stream
    while (1) {
        my ( $queryLabelA, $idsA, $queryLabelB, $idsB );

        # idsA is a reference to a hash from targetIds to %ids
        ( $queryLabelA, $idsA, $nextLineA ) = collectIds( *UCA, $nextLineA );
        ( $queryLabelB, $idsB, $nextLineB ) = collectIds( *UCB, $nextLineB );

        if ( !( $queryLabelA eq $queryLabelB ) ) {
            die("Usearch results desynchronized: $queryLabelA neq $queryLabelB");
        }

        my $numHitsA = ( scalar keys %$idsA );
        my $numHitsB = ( scalar keys %$idsB );

        # if either read got NOHITS, then it's definitely NOHITS for the pair.  This trumps TOOMANYHITS for the other read.
        # don't bother trying to reconcile hits in this case

        if ( ( $numHitsA == 0 ) || ( $numHitsB == 0 ) ) {
            push @$nohitQueryIds, $queryLabelA;
        }

        # if both reads got TOOMANYHITS, then it's definitely TOOMANYHITS for the pair.

        elsif ( ( $numHitsA >= $maxAccepts ) && ( $numHitsB >= $maxAccepts ) ) {
            push @$tooManyHitQueryIds, $queryLabelA;
        }

        # if neither read got TOOMANYHITS, then we're good to go

        elsif ( ( $numHitsA < $maxAccepts ) && ( $numHitsB < $maxAccepts ) ) {
            if ( !reconcilePairedHitsAndPrint( $queryLabelA, $idsA, $idsB, $pairPercentIdThreshold ) ) {
                push @$nohitQueryIds, $queryLabelA;
            }

        }

        # if only one read got TOOMANYHITS...

        else {

            # escalate if possible
            if ( $maxAccepts < $maxMaxAccepts ) {
                push @$tooManyHitQueryIds, $queryLabelA;
            }

            # if we're already at maxMaxAccepts and we're allowed, fall back to the info provided by the other read.

          # This is a little tricky: which percent ID threshold do we use?
          # For consistency, I think we have to assume that the overly generic read is a 100% match.
          # the cleanest way to say this is to say that the "overly generic" read just matches everything, so
          # reconcilePairHitsAndPrint( $queryLabelA, $idsA, $allIds, $pairPercentIdThreshold )
          # but that would require a hash %allIds mapping every ID to 100, just because reconcilePairHitsAndPrint says $idsB->{$targetLabel}
          # it's equivalent to just use reconcileSingleHitsAndPrint with singlePercentIdThreshold.

            elsif ($singleOKgeneric) {
                if ( $numHitsA < $maxAccepts ) {
                    if ( !reconcileSingleHitsAndPrint( $queryLabelA, $idsA, $singlePercentIdThreshold ) ) {
                        push @$nohitQueryIds, $queryLabelA;
                    }
                }
                elsif ( $numHitsB < $maxAccepts ) {
                    if ( !reconcileSingleHitsAndPrint( $queryLabelA, $idsB, $singlePercentIdThreshold ) ) {
                        push @$nohitQueryIds, $queryLabelA;
                    }
                }
                else { die("impossible"); }
            }

            # if we're already at maxMaxAccepts, but not allowed to rely on the other read, just report TOOMANYHITS for the pair
            else {
                push @$tooManyHitQueryIds, $queryLabelA;
            }
        }
        if ( !$nextLineA || !$nextLineB ) {
            if ( !( !$nextLineA && !$nextLineB ) ) {
                die("Usearch results desynchronized at end:\nA: $nextLineA\nB: $nextLineB");
            }
            last;
        }

    }

    close(UCA) || die "can't close usearch: $!";
    close(UCB) || die "can't close usearch: $!";

    # for the TOOMANYHITS cases, escalate maxAccepts and try again
    # Note this recurses, so no need to iterate here
    if ( scalar(@$tooManyHitQueryIds) && ( $maxAccepts * 2 <= $maxMaxAccepts ) ) {
        my $nohitQueryIdsB;

        print STDERR "doPairSearch $readAFile, $readBFile: Escalating maxAccepts to "
            . ( $maxAccepts * 2 ) . " for "
            . scalar(@$tooManyHitQueryIds)
            . " sequences.\n";

        # prepare input files with the remaining sequences
        my $readAFileEsc = extractFasta( $indexA, $tooManyHitQueryIds );
        my $readBFileEsc = extractFasta( $indexB, $tooManyHitQueryIds );

        ( $nohitQueryIdsB, $tooManyHitQueryIds ) =
            doPairSearch( $readAFileEsc, $readBFileEsc, $pairPercentDifferenceThreshold, $maxAccepts * 2 );

        # A TOOMANYHITS case can certainly turn into a NOHITS case:
        # once one read is no longer TOOMANYHITS, it may turn out that nothing can be reconciled with the other read.

        #if (@$nohitQueryIdsB) {
        #    die(      "A TOOMANYHITS case can't turn into a NOHITS case: "
        #            . ( join ", ", @$nohitQueryIdsB )
        #            . " at pair threshold $pairPercentDifferenceThreshold and maxAccepts "
        #            . ( $maxAccepts * 2 ) );
        #  }

        push @$nohitQueryIds, @$nohitQueryIdsB;
    }

    print STDERR
        "doPairSearch $readAFile, $readBFile: Finished at pair threshold $pairPercentDifferenceThreshold and maxAccepts $maxAccepts\n";
    print STDERR "         NOHITS: " . scalar(@$nohitQueryIds) . "\n";
    print STDERR "    TOOMANYHITS: " . scalar(@$tooManyHitQueryIds) . "\n";

    # print STDERR "         NOHITS: " .      ( join ", ", @$nohitQueryIds ) . "\n";
    # print STDERR "    TOOMANYHITS: " . ( join ", ", @$tooManyHitQueryIds ) . "\n";

    # any tooManyHitQueryIds that remain had more than maxMaxAccepts hits
    return ( $nohitQueryIds, $tooManyHitQueryIds );
}

sub reconcilePairedHitsAndPrint {
    my ( $queryLabel, $idsA, $idsB, $pairPercentIdThreshold ) = @_;

    my $idsByIdentity = {};
    for my $targetLabel ( keys %$idsA ) {
        my $percentIdA = $idsA->{$targetLabel};
        my $percentIdB = $idsB->{$targetLabel};
        if ($percentIdB) {

            # both reads hit the same target
            # compute the average percent id
            my $pairPercentId = ( $percentIdA + $percentIdB ) / 2.0;
            if ( $pairPercentId >= $pairPercentIdThreshold ) {
                if ( !defined $idsByIdentity->{$pairPercentId} ) {
                    $idsByIdentity->{$pairPercentId} = [];
                }
                push @{ $idsByIdentity->{$pairPercentId} }, $targetLabel;
            }
        }
    }

    if ( !%$idsByIdentity ) {

        #print STDERR "$queryLabel -> no reconciled hits at $pairPercentIdThreshold%\n";

        # this is the NOHIT case, but we'll back off and try again
        return 0;
    }
    else {

        #print STDERR "$queryLabel -> printing reconciled hits at $pairPercentIdThreshold%\n";
        printLine( $queryLabel, $idsByIdentity );
        return 1;
    }

}

##### Read a block of target IDs for one query from a USEARCH stream
sub collectIds {

    # assume that the records for a given label are all grouped together, so we can collect the hits for each label and process them in turn
    # need to jump through some hoops to save the first line of the next block (since we can't rewind a pipe with seek()).

    my $fh        = shift;
    my $firstLine = shift;

    my %hits = ();

    # process the first line (cached from the previous call)
    #print STDERR "Processing firstLine: $firstLine\n";
    my ( $typeF, $clusterF, $sizeF, $percentIdF, $strandF, $queryStartF, $targetStartF, $alignmentF, $queryLabelF, $targetLabelF ) =
        split /\t/, $firstLine;
    chomp $targetLabelF;

    $queryLabelF =~ /$idRegex/;
    $queryLabelF = $1;

    #$queryLabelF =~ s/\s.*//;    # primary ID is only the portion before whitespace

    if ( $typeF eq "N" ) {

        #print STDERR "$queryLabelF -> N\n";

        # NOHIT represented as empty hash
        # note we still have to cache the next line, after filtering comments
        while (<$fh>) {
            if (/^\s*#/) { next; }
            if (/^\s*$/) { next; }
            my $line = $_;
            chomp $line;

            #print STDERR "$line\n";
            return ( $queryLabelF, \%hits, $line );
        }
    }
    elsif ( $typeF eq "H" ) {
        $hits{$targetLabelF} = $percentIdF;
    }

    # process the remaining lines
    while (<$fh>) {
        if (/^\s*#/) { next; }
        if (/^\s*$/) { next; }
        my $line = $_;
        chomp $line;

        #print STDERR "$line\n";

        my ( $type, $cluster, $size, $percentId, $strand, $queryStart, $targetStart, $alignment, $queryLabel, $targetLabel ) =
            split /\t/;
        chomp $targetLabel;

        $queryLabel =~ /$idRegex/;
        $queryLabel = $1;

        #$queryLabel =~ s/\s.*//;    # primary ID is only the portion before whitespace

        if ( $queryLabel ne $queryLabelF ) {

            # advanced past the end of the current block
            #print STDERR "End of block $queryLabelF -> block of " . scalar( keys %hits ) . " hits\n";

            #print STDERR "End of block, return\n";
            return ( $queryLabelF, \%hits, $line );
        }
        else {
            if ( $type eq "N" ) {
                die "impossible: $queryLabel reports no hit after it already had a hit";
            }
            elsif ( $type eq "H" ) {
                $hits{$targetLabel} = $percentId;
            }
        }
    }

    # end of the stream (the last block)
    #print STDERR "End of stream $queryLabelF -> block of " . scalar( keys %hits ) . " hits\n";

    #print STDERR "End of stream, return\n";
    return ( $queryLabelF, \%hits, "" );
}

my $fastaNum;

sub extractFasta {
    my $index = shift;
    my $ids   = shift;
    my $name  = $fastaNum++;

    # print STDERR "Extracting " . scalar(@$ids) . " to file $name\n";

    open( OUT, ">$name" );

    # my $out = Bio::SeqIO->new( '-format' => 'Fasta', '-fh' => \*OUT );
    for my $id (@$ids) {
        my $seqobj = $index->fetch($id);
        if ( !defined $seqobj ) {
            print STDERR "Extracting from " . $index->fastaFileName() . ": Undefined: $id\n";
        }

        # elsif ($seqobj->primary_id() ne $id)
        #    {
        #    print STDERR "Extracting from " . $index->filename() . ": ID problem: " . ($seqobj->primary_id()) . " ne $id\n";
        #    }
        else {

            #$out->write_seq($seqobj);
            print OUT $seqobj;
        }
    }
    close OUT;

    return $name;
}

sub printLine {
    my ( $label, $idsByIdentity ) = @_;

    my @ids        = ();
    my @pcids      = sort { $b <=> $a } keys %$idsByIdentity;
    my $bestPcid   = $pcids[0];
    my $acceptPcid = $bestPcid - $slop;
    for my $pcid (@pcids) {
        if ( $pcid < $acceptPcid ) { last; }
        push @ids, @{ $idsByIdentity->{$pcid} };
    }

    my $idString = ( join "\t", @ids );
    print "$label\t$bestPcid\t" . $idString . "\n";

    # print STDERR "$label\t$bestPcid\t" . $idString . "\n";
}

sub revcompFile {
    my $infile = shift;

    my $outfile = $infile . ".rc";

    open( IN,  $infile )     or die "Can't read $infile\n";
    open( OUT, ">$outfile" ) or die "Can't write $outfile\n";

    while (<IN>) {
        my $a = $_;
        chomp $a;
        if ( !( $a =~ /^>/ ) ) {
            $a = reverse $a;
            $a =~ tr/ACGTacgt/TGCAtgca/;
        }
        print OUT $a . "\n";
    }
    close IN;
    close OUT;
    return $outfile;
}

main();