-
Notifications
You must be signed in to change notification settings - Fork 77
/
ebwt_search_backtrack.h
3143 lines (3028 loc) · 99.7 KB
/
ebwt_search_backtrack.h
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
#ifndef EBWT_SEARCH_BACKTRACK_H_
#define EBWT_SEARCH_BACKTRACK_H_
#include <stdexcept>
#include "aligner_metrics.h"
#include "ds.h"
#include "ebwt_search_util.h"
#include "pat.h"
#include "qual.h"
#include "range.h"
#include "range_source.h"
#include "search_globals.h"
#include "sstring.h"
/**
* Class that coordinates quality- and quantity-aware backtracking over
* some range of a read sequence.
*
* The creator can configure the BacktrackManager to treat different
* stretches of the read differently.
*/
class GreedyDFSRangeSource {
typedef std::pair<int, int> TIntPair;
public:
GreedyDFSRangeSource(
const Ebwt* ebwt,
const EbwtSearchParams& params,
uint32_t qualThresh, /// max acceptable q-distance
const int maxBts, /// maximum # backtracks allowed
uint32_t reportPartials = 0,
bool reportExacts = true,
bool reportRanges = false,
PartialAlignmentManager* partials = NULL,
EList<QueryMutation>* muts = NULL,
bool verbose = true,
EList<BTRefString >* os = NULL,
bool considerQuals = true, // whether to consider quality values when making backtracking decisions
bool halfAndHalf = false, // hacky way of supporting separate revisitable regions
bool maqPenalty = true) :
_qry(NULL),
_qlen(0),
_qual(NULL),
_name(NULL),
_ebwt(ebwt),
_params(params),
_unrevOff(0),
_1revOff(0),
_2revOff(0),
_3revOff(0),
_maqPenalty(maqPenalty),
_qualThresh(qualThresh),
_pairs(NULL),
_elims(NULL),
_mms(),
_refcs(),
_chars(NULL),
_reportPartials(reportPartials),
_reportExacts(reportExacts),
_reportRanges(reportRanges),
_partials(partials),
_muts(muts),
_os(os),
_sanity(_os != NULL && _os->size() > 0),
_considerQuals(considerQuals),
_halfAndHalf(halfAndHalf),
_5depth(0),
_3depth(0),
_numBts(0),
_totNumBts(0),
_maxBts(maxBts),
_precalcedSideLocus(false),
_preLtop(),
_preLbot(),
_verbose(verbose),
_ihits(0llu)
{ }
~GreedyDFSRangeSource() {
if(_pairs != NULL) delete[] _pairs;
if(_elims != NULL) delete[] _elims;
if(_chars != NULL) delete[] _chars;
}
/**
* Set a new query read.
*/
void setQuery(Read& r) {
const bool fw = _params.fw();
const bool ebwtFw = _ebwt->fw();
if(ebwtFw) {
_qry = fw ? &r.patFw : &r.patRc;
_qual = fw ? &r.qual : &r.qualRev;
} else {
_qry = fw ? &r.patFwRev : &r.patRcRev;
_qual = fw ? &r.qualRev : &r.qual;
}
_name = &r.name;
// Reset _qlen
if(_qry->length() > _qlen) {
try {
_qlen = _qry->length();
// Resize _pairs
if(_pairs != NULL) { delete[] _pairs; }
_pairs = new TIndexOffU[_qlen*_qlen*8];
// Resize _elims
if(_elims != NULL) { delete[] _elims; }
_elims = new uint8_t[_qlen*_qlen];
memset(_elims, 0, _qlen*_qlen);
// Resize _chars
if(_chars != NULL) { delete[] _chars; }
_chars = new char[_qlen];
assert(_pairs != NULL && _elims != NULL && _chars != NULL);
} catch(std::bad_alloc& e) {
ThreadSafe _ts(&gLock);
cerr << "Unable to allocate memory for depth-first "
<< "backtracking search; new length = " << _qry->length()
<< endl;
throw 1;
}
} else {
// New length is less than old length, so there's no need
// to resize any data structures.
assert(_pairs != NULL && _elims != NULL && _chars != NULL);
_qlen = _qry->length();
}
_mms.clear();
_refcs.clear();
assert_geq(_qual->length(), _qlen);
if(_verbose) {
cout << "setQuery(_qry=" << (*_qry) << ", _qual=" << (*_qual) << ")" << endl;
}
// Initialize the random source using new read as part of the
// seed.
_seed = r.seed;
_patid = r.rdid;
_rand.init(r.seed);
}
/**
* Apply a batch of mutations to this read, possibly displacing a
* previous batch of mutations.
*/
void setMuts(EList<QueryMutation>* muts) {
if(_muts != NULL) {
// Undo previous mutations
assert_gt(_muts->size(), 0);
undoPartialMutations();
}
_muts = muts;
if(_muts != NULL) {
assert_gt(_muts->size(), 0);
applyPartialMutations();
}
}
/**
* Set backtracking constraints.
*/
void setOffs(uint32_t depth5, // depth of far edge of hi-half
uint32_t depth3, // depth of far edge of lo-half
uint32_t unrevOff, // depth above which we cannot backtrack
uint32_t revOff1, // depth above which we may backtrack just once
uint32_t revOff2, // depth above which we may backtrack just twice
uint32_t revOff3) // depth above which we may backtrack just three times
{
_5depth = depth5;
_3depth = depth3;
assert_geq(depth3, depth5);
_unrevOff = unrevOff;
_1revOff = revOff1;
_2revOff = revOff2;
_3revOff = revOff3;
}
/**
* Reset number of backtracks to 0.
*/
void resetNumBacktracks() {
_totNumBts = 0;
}
/**
* Return number of backtracks since the last time the count was
* reset.
*/
uint32_t numBacktracks() {
return _totNumBts;
}
/**
* Set whether to report exact hits.
*/
void setReportExacts(int stratum) {
_reportExacts = stratum;
}
/**
* Set the Bowtie index to search against.
*/
void setEbwt(const Ebwt* ebwt) {
_ebwt = ebwt;
}
/**
* Return the current range
*/
Range& range() {
return _curRange;
}
/**
* Set _qlen. Don't let it exceed length of query.
*/
void setQlen(uint32_t qlen) {
assert(_qry != NULL);
_qlen = min<uint32_t>((uint32_t)_qry->length(), qlen);
}
/// Return the maximum number of allowed backtracks in a given call
/// to backtrack()
uint32_t maxBacktracks() {
return _maxBts;
}
/**
* Initiate the recursive backtracking routine starting at the
* extreme right-hand side of the pattern. Use the ftab to match
* the first several characters in one chomp, as long as doing so
* does not "jump over" any legal backtracking targets.
*
* Return true iff the HitSink has indicated that we're done with
* this read.
*/
bool backtrack(uint32_t ham = 0) {
assert_gt(_qry->length(), 0);
assert_leq(_qlen, _qry->length());
assert_geq(_qual->length(), _qry->length());
const Ebwt& ebwt = *_ebwt;
int ftabChars = ebwt._eh._ftabChars;
int nsInSeed = 0; int nsInFtab = 0;
if(!tallyNs(nsInSeed, nsInFtab)) {
// No alignments are possible because of the distribution
// of Ns in the read in combination with the backtracking
// constraints.
return false;
}
bool ret;
// m = depth beyond which ftab must not extend or else we might
// miss some legitimate paths
uint32_t m = min<uint32_t>(_unrevOff, (uint32_t)_qlen);
if(nsInFtab == 0 && m >= (uint32_t)ftabChars) {
uint32_t ftabOff = calcFtabOff();
TIndexOffU top = ebwt.ftabHi(ftabOff);
TIndexOffU bot = ebwt.ftabLo(ftabOff+1);
if(_qlen == (TIndexOffU)ftabChars && bot > top) {
// We have a match!
if(_reportPartials > 0) {
// Oops - we're trying to find seedlings, so we've
// gone too far; start again
ret = backtrack(0, // depth
0, // top
0, // bot
ham,
nsInFtab > 0);
} else {
// We have a match!
ret = reportAlignment(0, top, bot, ham);
}
} else if (bot > top) {
// We have an arrow pair from which we can backtrack
ret = backtrack(ftabChars, // depth
top, // top
bot, // bot
ham,
nsInFtab > 0);
} else {
// The arrows are already closed; give up
ret = false;
}
} else {
// The ftab *does* extend past the unrevisitable portion;
// we can't use it in this case, because we might jump past
// a legitimate mismatch
ret = backtrack(0, // depth
0, // top
0, // bot
ham,
// disable ftab jumping if there is more
// than 1 N in it
nsInFtab > 0);
}
if(finalize()) ret = true;
return ret;
}
/**
* If there are any buffered results that have yet to be committed,
* commit them. This happens when looking for partial alignments.
*/
bool finalize() {
bool ret = false;
if(_reportPartials > 0) {
// We're in partial alignment mode; take elements of the
// _partialBuf and install them in the _partials database
assert(_partials != NULL);
if(_partialsBuf.size() > 0) {
#ifndef NDEBUG
for(size_t i = 0; i < _partialsBuf.size(); i++) {
assert(_partialsBuf[i].repOk(_qualThresh, (uint32_t)_qlen, (*_qual), _maqPenalty));
}
#endif
_partials->addPartials(_params.patId(), _partialsBuf);
_partialsBuf.clear();
ret = true;
} else {
assert(!ret);
}
}
assert_eq(0, _partialsBuf.size());
return ret;
}
/**
* Starting at the given "depth" relative to the 5' end, and the
* given top and bot indexes (where top=0 and bot=0 means it's up
* to us to calculate the initial range), and initial weighted
* hamming distance iham, find a hit using randomized, quality-
* aware backtracking.
*/
bool backtrack(uint32_t depth,
TIndexOffU top,
TIndexOffU bot,
uint32_t iham = 0,
bool disableFtab = false)
{
HitSinkPerThread& sink = _params.sink();
_ihits = sink.retainedHits().size();
// Initiate the recursive, randomized quality-aware backtracker
// with a stack depth of 0 (no backtracks so far)
_bailedOnBacktracks = false;
bool done = backtrack(0, depth, _unrevOff, _1revOff, _2revOff, _3revOff,
top, bot, iham, iham, _pairs, _elims, disableFtab);
_totNumBts += _numBts;
_numBts = 0;
_precalcedSideLocus = false;
_bailedOnBacktracks = false;
return done;
}
/**
* Recursive routine for progressing to the next backtracking
* decision given some initial conditions. If a hit is found, it
* is recorded and true is returned. Otherwise, if there are more
* backtracking opportunities, the function will call itself
* recursively and return the result. As soon as there is a
* mismatch and no backtracking opportunities, false is returned.
*/
bool backtrack(uint32_t stackDepth, // depth of the recursion stack; = # mismatches so far
uint32_t depth, // next depth where a post-pair needs to be calculated
uint32_t unrevOff, // depths < unrevOff are unrevisitable
uint32_t oneRevOff,// depths < oneRevOff are 1-revisitable
uint32_t twoRevOff,// depths < twoRevOff are 2-revisitable
uint32_t threeRevOff,// depths < threeRevOff are 3-revisitable
TIndexOffU top, // top arrow in pair prior to 'depth'
TIndexOffU bot, // bottom arrow in pair prior to 'depth'
uint32_t ham, // weighted hamming distance so far
uint32_t iham, // initial weighted hamming distance
TIndexOffU* pairs, // portion of pairs array to be used for this backtrack frame
uint8_t* elims, // portion of elims array to be used for this backtrack frame
bool disableFtab = false)
{
// Can't have already exceeded weighted hamming distance threshold
assert_leq(stackDepth, depth);
assert_gt(_qry->length(), 0);
assert_leq(_qlen, _qry->length());
assert_geq(_qual->length(), _qry->length());
assert(_qry != NULL);
assert(_qual != NULL);
assert(_name != NULL);
assert(_qlen != 0);
assert_leq(ham, _qualThresh);
assert_lt(depth, _qlen); // can't have run off the end of qry
assert_geq(bot, top); // could be that both are 0
assert(pairs != NULL);
assert(elims != NULL);
assert_leq(stackDepth, _qlen);
const Ebwt& ebwt = *_ebwt;
HitSinkPerThread& sink = _params.sink();
uint64_t prehits = sink.numValidHits();
if(_halfAndHalf) {
assert_eq(0, _reportPartials);
assert_gt(_3depth, _5depth);
}
if(_reportPartials) {
assert(!_halfAndHalf);
}
if(_verbose) {
cout << " backtrack(stackDepth=" << stackDepth << ", "
<< "depth=" << depth << ", "
<< "top=" << top << ", "
<< "bot=" << bot << ", "
<< "ham=" << ham << ", "
<< "iham=" << iham << ", "
<< "pairs=" << pairs << ", "
<< "elims=" << (void*)elims << "): \"";
for(int i = (int)depth - 1; i >= 0; i--) {
cout << _chars[i];
}
cout << "\"" << endl;
}
// Do this early on so that we can clear _precalcedSideLocus
// before we have too many opportunities to bail and leave it
// 'true'
SideLocus ltop, lbot;
if(_precalcedSideLocus) {
ltop = _preLtop;
lbot = _preLbot;
_precalcedSideLocus = false;
} else if(top != 0 || bot != 0) {
SideLocus::initFromTopBot(top, bot, ebwt._eh, ebwt._ebwt, ltop, lbot);
}
// Check whether we've exceeded any backtracking limit
if(_halfAndHalf) {
if(_maxBts > 0 && _numBts == _maxBts) {
_bailedOnBacktracks = true;
return false;
}
_numBts++;
}
// # positions with at least one legal outgoing path
uint32_t altNum = 0;
// # positions tied for "best" outgoing qual
uint32_t eligibleNum = 0;
// total range-size for all eligibles
TIndexOffU eligibleSz = 0;
// If there is just one eligible slot at the moment (a common
// case), these are its parameters
uint32_t eli = 0;
bool elignore = true; // ignore the el values because they didn't come from a recent override
TIndexOffU eltop = 0;
TIndexOffU elbot = 0;
uint32_t elham = ham;
char elchar = 0;
int elcint = 0;
// The lowest quality value associated with any alternative
// ranges; all alternative ranges with this quality are
// eligible
uint8_t lowAltQual = 0xff;
uint32_t d = depth;
uint32_t cur = (uint32_t)_qlen - d - 1; // current offset into _qry
while(cur < _qlen) {
// Try to advance further given that
if(_verbose) {
cout << " cur=" << cur << " \"";
for(int i = (int)d - 1; i >= 0; i--) {
cout << _chars[i];
}
cout << "\"";
}
// If we're searching for a half-and-half solution, then
// enforce the boundary-crossing constraints here.
if(_halfAndHalf && !hhCheckTop(stackDepth, d, iham, _mms, prehits)) {
return false;
}
bool curIsEligible = false;
// Reset eligibleNum and eligibleSz if there are any
// eligible pairs discovered at this spot
bool curOverridesEligible = false;
// Determine whether ranges at this location are
// candidates for backtracking
int c = (int)(*_qry)[cur];
assert_leq(c, 4);
uint8_t q = qualAt(cur);
// The current query position is a legit alternative if it a) is
// not in the unrevisitable region, and b) the quality ceiling (if
// one exists) is not exceeded
bool curIsAlternative =
(d >= unrevOff) &&
(!_considerQuals ||
(ham + mmPenalty(_maqPenalty, q) <= _qualThresh));
if(curIsAlternative) {
if(_considerQuals) {
// Is it the best alternative?
if(q < lowAltQual) {
// Ranges at this depth in this backtracking frame are
// eligible, unless we learn otherwise. Ranges previously
// thought to be eligible are not any longer.
curIsEligible = true;
curOverridesEligible = true;
} else if(q == lowAltQual) {
// Ranges at this depth in this backtracking frame
// are eligible, unless we learn otherwise
curIsEligible = true;
}
} else {
// When quality values are not considered, all positions
// are eligible
curIsEligible = true;
}
}
if(curIsEligible) assert(curIsAlternative);
if(curOverridesEligible) assert(curIsEligible);
if(curIsAlternative && !curIsEligible) {
assert_gt(eligibleSz, 0);
assert_gt(eligibleNum, 0);
}
if(_verbose) {
cout << " alternative: " << curIsAlternative;
cout << ", eligible: " << curIsEligible;
if(curOverridesEligible) cout << "(overrides)";
cout << endl;
}
// If c is 'N', then it's guaranteed to be a mismatch
if(c == 4 && d > 0) {
// Force the 'else if(curIsAlternative)' branch below
top = bot = 1;
} else if(c == 4) {
// We'll take the 'if(top == 0 && bot == 0)' branch below
assert_eq(0, top);
assert_eq(0, bot);
}
// Calculate the ranges for this position
if(top == 0 && bot == 0) {
// Calculate first quartet of ranges using the _fchr[]
// array
pairs[0 + 0] = ebwt._fchr[0];
pairs[0 + 4] = pairs[1 + 0] = ebwt._fchr[1];
pairs[1 + 4] = pairs[2 + 0] = ebwt._fchr[2];
pairs[2 + 4] = pairs[3 + 0] = ebwt._fchr[3];
pairs[3 + 4] = ebwt._fchr[4];
// Update top and bot
if(c < 4) {
top = pairTop(pairs, d, c); bot = pairBot(pairs, d, c);
assert_geq(bot, top);
}
} else if(curIsAlternative) {
// Clear pairs
memset(&pairs[d*8], 0, 8 * OFF_SIZE);
// Calculate next quartet of ranges
ebwt.mapLFEx(ltop, lbot, &pairs[d*8], &pairs[(d*8)+4]);
// Update top and bot
if(c < 4) {
top = pairTop(pairs, d, c); bot = pairBot(pairs, d, c);
assert_geq(bot, top);
}
} else {
// This query character is not even a legitimate
// alternative (because backtracking here would blow
// our mismatch quality budget), so no need to do the
// bookkeeping for the entire quartet, just do c
if(c < 4) {
if(top+1 == bot) {
bot = top = ebwt.mapLF1(top, ltop, c);
if(bot != OFF_MASK) bot++;
} else {
top = ebwt.mapLF(ltop, c); bot = ebwt.mapLF(lbot, c);
assert_geq(bot, top);
}
}
}
if(top != bot) {
// Calculate loci from row indices; do it now so that
// those prefetches are fired off as soon as possible.
// This eventually calls SideLocus.initfromRow().
SideLocus::initFromTopBot(top, bot, ebwt._eh, ebwt._ebwt, ltop, lbot);
}
// Update the elim array
eliminate(elims, d, c);
if(curIsAlternative) {
// Given the just-calculated range quartet, update
// elims, altNum, eligibleNum, eligibleSz
for(int i = 0; i < 4; i++) {
if(i == c) continue;
assert_leq(pairTop(pairs, d, i), pairBot(pairs, d, i));
TIndexOffU spread = pairSpread(pairs, d, i);
if(spread == 0) {
// Indicate this char at this position is
// eliminated as far as this backtracking frame is
// concerned, since its range is empty
elims[d] |= (1 << i);
assert_lt(elims[d], 16);
}
if(spread > 0 && ((elims[d] & (1 << i)) == 0)) {
// This char at this position is an alternative
if(curIsEligible) {
if(curOverridesEligible) {
// Only now that we know there is at least
// one potential backtrack target at this
// most-eligible position should we reset
// these eligibility parameters
lowAltQual = q;
eligibleNum = 0;
eligibleSz = 0;
curOverridesEligible = false;
// Remember these parameters in case
// this turns out to be the only
// eligible target
eli = d;
eltop = pairTop(pairs, d, i);
elbot = pairBot(pairs, d, i);
assert_eq(elbot-eltop, spread);
elham = mmPenalty(_maqPenalty, q);
elchar = "acgt"[i];
elcint = i;
elignore = false;
}
eligibleSz += spread;
eligibleNum++;
}
assert_gt(eligibleSz, 0);
assert_gt(eligibleNum, 0);
altNum++;
}
}
}
if(altNum > 0) {
assert_gt(eligibleSz, 0);
assert_gt(eligibleNum, 0);
}
assert_leq(eligibleNum, eligibleSz);
assert_leq(eligibleNum, altNum);
assert_lt(elims[d], 16);
assert(sanityCheckEligibility(depth, d, unrevOff, lowAltQual, eligibleSz, eligibleNum, pairs, elims));
// Achieved a match, but need to keep going
bool backtrackDespiteMatch = false;
bool reportedPartial = false;
if(cur == 0 && // we've consumed the entire pattern
top < bot && // there's a hit to report
stackDepth < _reportPartials && // not yet used up our mismatches
_reportPartials > 0) // there are still legel backtracking targets
{
assert(!_halfAndHalf);
if(altNum > 0) backtrackDespiteMatch = true;
if(stackDepth > 0) {
// This is a legit seedling; report it
reportPartial(stackDepth);
reportedPartial = true;
}
// Now continue on to find legitimate seedlings with
// more mismatches than this one
}
// Check whether we've obtained an exact alignment when
// we've been instructed not to report exact alignments
bool invalidExact = false;
if(cur == 0 && stackDepth == 0 && bot > top && !_reportExacts) {
invalidExact = true;
backtrackDespiteMatch = true;
}
// Set this to true if the only way to make legal progress
// is via one or more additional backtracks. This is
// helpful in half-and-half mode.
bool mustBacktrack = false;
bool invalidHalfAndHalf = false;
if(_halfAndHalf) {
ASSERT_ONLY(uint32_t lim = (_3revOff == _2revOff)? 2 : 3);
if((d == (_5depth-1)) && top < bot) {
// We're crossing the boundary separating the hi-half
// from the non-seed portion of the read.
// We should induce a mismatch if we haven't mismatched
// yet, so that we don't waste time pursuing a match
// that was covered by a previous phase
assert_eq(0, _reportPartials);
assert_leq(stackDepth, lim-1);
invalidHalfAndHalf = (stackDepth == 0);
if(stackDepth == 0 && altNum > 0) {
backtrackDespiteMatch = true;
mustBacktrack = true;
} else if(stackDepth == 0) {
// We're returning from the bottommost frame
// without having found any hits; let's
// sanity-check that there really aren't any
return false;
}
}
else if((d == (_3depth-1)) && top < bot) {
// We're crossing the boundary separating the lo-half
// from the non-seed portion of the read
assert_eq(0, _reportPartials);
assert_leq(stackDepth, lim);
assert_gt(stackDepth, 0);
// Count the mismatches in the lo and hi halves
uint32_t loHalfMms = 0, hiHalfMms = 0;
assert_geq(_mms.size(), stackDepth);
for(size_t i = 0; i < stackDepth; i++) {
uint32_t d = (uint32_t)_qlen - _mms[i] - 1;
if (d < _5depth) hiHalfMms++;
else if(d < _3depth) loHalfMms++;
else assert(false);
}
assert_leq(loHalfMms + hiHalfMms, lim);
invalidHalfAndHalf = (loHalfMms == 0 || hiHalfMms == 0);
if((stackDepth < 2 || invalidHalfAndHalf) && altNum > 0) {
// We backtracked fewer times than necessary;
// force a backtrack
mustBacktrack = true;
backtrackDespiteMatch = true;
} else if(stackDepth < 2) {
return false;
}
}
if(d < _5depth-1) {
assert_leq(stackDepth, lim-1);
}
else if(d >= _5depth && d < _3depth-1) {
assert_gt(stackDepth, 0);
assert_leq(stackDepth, lim);
}
}
// This is necessary for the rare case where we're about
// to declare success because bot > top and we've consumed
// the final character, but all hits between top and bot
// are spurious. This check ensures that we keep looking
// for non-spurious hits in that case.
if(cur == 0 && // we made it to the left-hand-side of the read
bot > top && // there are alignments to report
!invalidHalfAndHalf && // alignment isn't disqualified by half-and-half requirement
!invalidExact && // alignment isn't disqualified by no-exact-hits setting
!reportedPartial) // for when it's a partial alignment we've already reported
{
bool ret = reportAlignment(stackDepth, top, bot, ham);
if(!ret) {
// reportAlignment returned false, so enter the
// backtrack loop and keep going
top = bot;
} else {
// reportAlignment returned true, so stop
return true;
}
}
//
// Mismatch with alternatives
//
while((top == bot || backtrackDespiteMatch) && altNum > 0) {
if(_verbose) cout << " top (" << top << "), bot ("
<< bot << ") with " << altNum
<< " alternatives, eligible: "
<< eligibleNum << ", " << eligibleSz
<< endl;
assert_gt(eligibleSz, 0);
assert_gt(eligibleNum, 0);
// Mismatch! Must now choose where we are going to
// take our quality penalty. We can only look as far
// back as our last decision point.
assert(sanityCheckEligibility(depth, d, unrevOff, lowAltQual, eligibleSz, eligibleNum, pairs, elims));
// Pick out the arrow pair we selected and target it
// for backtracking
ASSERT_ONLY(uint32_t eligiblesVisited = 0);
size_t i = d, j = 0;
assert_geq(i, depth);
TIndexOffU bttop = 0;
TIndexOffU btbot = 0;
uint32_t btham = ham;
char btchar = 0;
int btcint = 0;
uint32_t icur = 0;
// The common case is that eligibleSz == 1
if(eligibleNum > 1 || elignore) {
ASSERT_ONLY(bool foundTarget = false);
// Walk from left to right
for(; i >= depth; i--) {
assert_geq(i, unrevOff);
icur = (uint32_t)(_qlen - i - 1); // current offset into _qry
uint8_t qi = qualAt(icur);
assert_lt(elims[i], 16);
if((qi == lowAltQual || !_considerQuals) && elims[i] != 15) {
// This is the leftmost eligible position with at
// least one remaining backtrack target
TIndexOffU posSz = 0;
// Add up the spreads for A, C, G, T
for(j = 0; j < 4; j++) {
if((elims[i] & (1 << j)) == 0) {
assert_gt(pairSpread(pairs, i, j), 0);
posSz += pairSpread(pairs, i, j);
}
}
// Generate a random number
assert_gt(posSz, 0);
uint32_t r = _rand.nextU32() % posSz;
for(j = 0; j < 4; j++) {
if((elims[i] & (1 << j)) == 0) {
// This range has not been eliminated
ASSERT_ONLY(eligiblesVisited++);
uint32_t spread = pairSpread(pairs, i, j);
if(r < spread) {
// This is our randomly-selected
// backtrack target
ASSERT_ONLY(foundTarget = true);
bttop = pairTop(pairs, i, j);
btbot = pairBot(pairs, i, j);
btham += mmPenalty(_maqPenalty, qi);
btcint = (uint32_t)j;
btchar = "acgt"[j];
assert_leq(btham, _qualThresh);
break; // found our target; we can stop
}
r -= spread;
}
}
assert(foundTarget);
break; // escape left-to-right walk
}
}
assert_leq(i, d);
assert_lt(j, 4);
assert_leq(eligiblesVisited, eligibleNum);
assert(foundTarget);
assert_neq(0, btchar);
assert_gt(btbot, bttop);
assert_leq(btbot-bttop, eligibleSz);
} else {
// There was only one eligible target; we can just
// copy its parameters
assert_eq(1, eligibleNum);
assert(!elignore);
i = eli;
bttop = eltop;
btbot = elbot;
btham += elham;
j = btcint = elcint;
btchar = elchar;
assert_neq(0, btchar);
assert_gt(btbot, bttop);
assert_leq(btbot-bttop, eligibleSz);
}
// This is the earliest that we know what the next top/
// bot combo is going to be
SideLocus::initFromTopBot(bttop, btbot,
ebwt._eh, ebwt._ebwt,
_preLtop, _preLbot);
icur = (uint32_t)(_qlen - i - 1); // current offset into _qry
// Slide over to the next backtacking frame within
// pairs and elims; won't interfere with our frame or
// any of our parents' frames
TIndexOffU *newPairs = pairs + (_qlen*8);
uint8_t *newElims = elims + (_qlen);
// If we've selected a backtracking target that's in
// the 1-revisitable region, then we ask the recursive
// callee to consider the 1-revisitable region as also
// being unrevisitable (since we just "used up" all of
// our visits)
uint32_t btUnrevOff = unrevOff;
uint32_t btOneRevOff = oneRevOff;
uint32_t btTwoRevOff = twoRevOff;
uint32_t btThreeRevOff = threeRevOff;
assert_geq(i, unrevOff);
assert_geq(oneRevOff, unrevOff);
assert_geq(twoRevOff, oneRevOff);
assert_geq(threeRevOff, twoRevOff);
if(i < oneRevOff) {
// Extend unrevisitable region to include former 1-
// revisitable region
btUnrevOff = oneRevOff;
// Extend 1-revisitable region to include former 2-
// revisitable region
btOneRevOff = twoRevOff;
// Extend 2-revisitable region to include former 3-
// revisitable region
btTwoRevOff = threeRevOff;
}
else if(i < twoRevOff) {
// Extend 1-revisitable region to include former 2-
// revisitable region
btOneRevOff = twoRevOff;
// Extend 2-revisitable region to include former 3-
// revisitable region
btTwoRevOff = threeRevOff;
}
else if(i < threeRevOff) {
// Extend 2-revisitable region to include former 3-
// revisitable region
btTwoRevOff = threeRevOff;
}
// Note the character that we're backtracking on in the
// mm array:
if(_mms.size() <= stackDepth) {
assert_eq(_mms.size(), stackDepth);
_mms.push_back(icur);
} else {
_mms[stackDepth] = icur;
}
assert_eq(1, dna4Cat[(int)btchar]);
if(_refcs.size() <= stackDepth) {
assert_eq(_refcs.size(), stackDepth);
_refcs.push_back(btchar);
} else {
_refcs[stackDepth] = btchar;
}
#ifndef NDEBUG
for(uint32_t j = 0; j < stackDepth; j++) {
assert_neq(_mms[j], icur);
}
#endif
_chars[i] = btchar;
assert_leq(i+1, _qlen);
bool ret;
if(i+1 == _qlen) {
ret = reportAlignment(stackDepth+1, bttop, btbot, btham);
} else if(_halfAndHalf &&
!disableFtab &&
_2revOff == _3revOff &&
i+1 < (uint32_t)ebwt._eh._ftabChars &&
(uint32_t)ebwt._eh._ftabChars <= _5depth)
{
// The ftab doesn't extend past the unrevisitable portion,
// so we can go ahead and use it
// Rightmost char gets least significant bit-pairs
int ftabChars = ebwt._eh._ftabChars;
TIndexOffU ftabOff = (TIndexOffU)(int)(*_qry)[_qlen - ftabChars];
assert_lt(ftabOff, 4);
assert_lt(ftabOff, ebwt._eh._ftabLen-1);
for(int j = ftabChars - 1; j > 0; j--) {
ftabOff <<= 2;
if(_qlen-j == icur) {
ftabOff |= btcint;
} else {
assert_lt((int)(*_qry)[_qlen-j], 4);
ftabOff |= (int)(*_qry)[_qlen-j];
}
assert_lt(ftabOff, ebwt._eh._ftabLen-1);
}
assert_lt(ftabOff, ebwt._eh._ftabLen-1);
TIndexOffU ftabTop = ebwt.ftabHi(ftabOff);
TIndexOffU ftabBot = ebwt.ftabLo(ftabOff+1);
assert_geq(ftabBot, ftabTop);
if(ftabTop == ftabBot) {
ret = false;
} else {
assert(!_precalcedSideLocus);
assert_leq(iham, _qualThresh);
ret = backtrack(stackDepth+1,
ebwt._eh._ftabChars,
btUnrevOff, // new unrevisitable boundary
btOneRevOff, // new 1-revisitable boundary
btTwoRevOff, // new 2-revisitable boundary
btThreeRevOff, // new 3-revisitable boundary
ftabTop, // top arrow in range prior to 'depth'
ftabBot, // bottom arrow in range prior to 'depth'
btham, // weighted hamming distance so far
iham, // initial weighted hamming distance
newPairs,
newElims);
}
} else {
// We already called initFromTopBot for the range
// we're going to continue from
_precalcedSideLocus = true;
assert_leq(iham, _qualThresh);
// Continue from selected alternative range
ret = backtrack(stackDepth+1,// added 1 mismatch to alignment
(uint32_t)i+1, // start from next position after
btUnrevOff, // new unrevisitable boundary
btOneRevOff, // new 1-revisitable boundary
btTwoRevOff, // new 2-revisitable boundary
btThreeRevOff, // new 3-revisitable boundary
bttop, // top arrow in range prior to 'depth'
btbot, // bottom arrow in range prior to 'depth'
btham, // weighted hamming distance so far
iham, // initial weighted hamming distance
newPairs,
newElims);
}
if(ret) {
assert_gt(sink.numValidHits(), prehits);
return true; // return, signaling that we're done
}
if(_bailedOnBacktracks ||
(_halfAndHalf && (_maxBts > 0) && (_numBts >= _maxBts)))
{
_bailedOnBacktracks = true;
return false;
}
// No hit was reported; update elims[], eligibleSz,
// eligibleNum, altNum
_chars[i] = (*_qry)[icur];
assert_neq(15, elims[i]);
ASSERT_ONLY(uint8_t oldElim = elims[i]);
elims[i] |= (1 << j);
assert_lt(elims[i], 16);
assert_gt(elims[i], oldElim);
eligibleSz -= (btbot-bttop);
eligibleNum--;
elignore = true;
assert_geq(eligibleNum, 0);
altNum--;
assert_geq(altNum, 0);
if(altNum == 0) {
// No alternative backtracking points; all legal
// backtracking targets have been exhausted
assert_eq(0, altNum);
assert_eq(0, eligibleSz);