-
Notifications
You must be signed in to change notification settings - Fork 159
/
aligner_sw_driver.cpp
2403 lines (2366 loc) · 82.5 KB
/
aligner_sw_driver.cpp
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
/*
* Copyright 2011, Ben Langmead <[email protected]>
*
* This file is part of Bowtie 2.
*
* Bowtie 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Bowtie 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Bowtie 2. If not, see <http://www.gnu.org/licenses/>.
*/
#define TIMER_START() \
struct timeval tv_i, tv_f; \
struct timezone tz_i, tz_f; \
size_t total_usecs; \
gettimeofday(&tv_i, &tz_i)
#define IF_TIMER_END() \
gettimeofday(&tv_f, &tz_f); \
total_usecs = \
(tv_f.tv_sec - tv_i.tv_sec) * 1000000 + (tv_f.tv_usec - tv_i.tv_usec); \
if(total_usecs > 300000)
/*
* aligner_sw_driver.cpp
*
* Routines that drive the alignment process given a collection of seed hits.
* This is generally done in a few stages: extendSeeds visits the set of
* seed-hit BW elements in some order; for each element visited it resolves its
* reference offset; once the reference offset is known, bounds for a dynamic
* programming subproblem are established; if these bounds are distinct from
* the bounds we've already tried, we solve the dynamic programming subproblem
* and report the hit; if the AlnSinkWrap indicates that we can stop, we
* return, otherwise we continue on to the next BW element.
*/
#include <iostream>
#include "aligner_cache.h"
#include "aligner_sw_driver.h"
#include "pe.h"
#include "dp_framer.h"
// -- BTL remove --
#include <stdlib.h>
#include <sys/time.h>
// -- --
using namespace std;
/**
* Given end-to-end alignment results stored in the SeedResults structure, set
* up all of our state for resolving and keeping track of reference offsets for
* hits. Order the list of ranges to examine such that all exact end-to-end
* alignments are examined before any 1mm end-to-end alignments.
*
* Note: there might be a lot of hits and a lot of wide ranges to look for
* here. We use 'maxelt'.
*/
bool SwDriver::eeSaTups(
const Read& rd, // read
SeedResults& sh, // seed hits to extend into full alignments
const Ebwt& ebwt, // BWT
const BitPairReference& ref, // Reference strings
RandomSource& rnd, // pseudo-random generator
WalkMetrics& wlm, // group walk left metrics
SwMetrics& swmSeed, // metrics for seed extensions
size_t& nelt_out, // out: # elements total
size_t maxelt, // max elts we'll consider
bool all) // report all hits?
{
assert_eq(0, nelt_out);
gws_.clear();
rands_.clear();
satpos_.clear();
eehits_.clear();
// First, count up the total number of satpos_, rands_, eehits_, and gws_
// we're going to tuse
size_t nobj = 0;
if(!sh.exactFwEEHit().empty()) nobj++;
if(!sh.exactRcEEHit().empty()) nobj++;
nobj += sh.mm1EEHits().size();
nobj = min(nobj, maxelt);
gws_.ensure(nobj);
rands_.ensure(nobj);
satpos_.ensure(nobj);
eehits_.ensure(nobj);
size_t tot = sh.exactFwEEHit().size() + sh.exactRcEEHit().size();
bool succ = false;
bool firstEe = true;
bool done = false;
if(tot > 0) {
bool fwFirst = true;
// Pick fw / rc to go first in a weighted random fashion
#ifdef BOWTIE_64BIT_INDEX
TIndexOffU rn64 = rnd.nextU64();
TIndexOffU rn = rn64 % (uint64_t)tot;
#else
TIndexOffU rn32 = rnd.nextU32();
TIndexOffU rn = rn32 % (uint32_t)tot;
#endif
if(rn >= sh.exactFwEEHit().size()) {
fwFirst = false;
}
for(int fwi = 0; fwi < 2 && !done; fwi++) {
bool fw = ((fwi == 0) == fwFirst);
EEHit hit = fw ? sh.exactFwEEHit() : sh.exactRcEEHit();
if(hit.empty()) {
continue;
}
assert(hit.fw == fw);
if(hit.bot > hit.top) {
// Possibly adjust bot and width if we would have exceeded maxelt
TIndexOffU tops[2] = { hit.top, 0 };
TIndexOffU bots[2] = { hit.bot, 0 };
TIndexOffU width = hit.bot - hit.top;
if(nelt_out + width > maxelt) {
TIndexOffU trim = (TIndexOffU)((nelt_out + width) - maxelt);
#ifdef BOWTIE_64BIT_INDEX
TIndexOffU rn = rnd.nextU64() % width;
#else
TIndexOffU rn = rnd.nextU32() % width;
#endif
TIndexOffU newwidth = width - trim;
if(hit.top + rn + newwidth > hit.bot) {
// Two pieces
tops[0] = hit.top + rn;
bots[0] = hit.bot;
tops[1] = hit.top;
bots[1] = hit.top + newwidth - (bots[0] - tops[0]);
} else {
// One piece
tops[0] = hit.top + rn;
bots[0] = tops[0] + newwidth;
}
assert_leq(bots[0], hit.bot);
assert_leq(bots[1], hit.bot);
assert_geq(bots[0], tops[0]);
assert_geq(bots[1], tops[1]);
assert_eq(newwidth, (bots[0] - tops[0]) + (bots[1] - tops[1]));
}
for(int i = 0; i < 2 && !done; i++) {
if(bots[i] <= tops[i]) break;
TIndexOffU width = bots[i] - tops[i];
TIndexOffU top = tops[i];
// Clear list where resolved offsets are stored
swmSeed.exranges++;
swmSeed.exrows += width;
if(!succ) {
swmSeed.exsucc++;
succ = true;
}
if(firstEe) {
salistEe_.clear();
pool_.clear();
firstEe = false;
}
// We have to be careful not to allocate excessive amounts of memory here
TSlice o(salistEe_, (TIndexOffU)salistEe_.size(), width);
for(TIndexOffU i = 0; i < width; i++) {
if(!salistEe_.add(pool_, OFF_MASK)) {
swmSeed.exooms++;
return false;
}
}
assert(!done);
eehits_.push_back(hit);
satpos_.expand();
satpos_.back().sat.init(SAKey(), top, OFF_MASK, o);
satpos_.back().sat.key.seq = MAX_U64;
satpos_.back().sat.key.len = (uint32_t)rd.length();
satpos_.back().pos.init(fw, 0, 0, (uint32_t)rd.length());
satpos_.back().origSz = width;
rands_.expand();
rands_.back().init(width, all);
gws_.expand();
SARangeWithOffs<TSlice> sa;
sa.topf = satpos_.back().sat.topf;
sa.len = satpos_.back().sat.key.len;
sa.offs = satpos_.back().sat.offs;
gws_.back().init(
ebwt, // forward Bowtie index
ref, // reference sequences
sa, // SATuple
rnd, // pseudo-random generator
wlm); // metrics
assert(gws_.back().repOk(sa));
nelt_out += width;
if(nelt_out >= maxelt) {
done = true;
}
}
}
}
}
succ = false;
if(!done && !sh.mm1EEHits().empty()) {
sh.sort1mmEe(rnd);
size_t sz = sh.mm1EEHits().size();
for(size_t i = 0; i < sz && !done; i++) {
EEHit hit = sh.mm1EEHits()[i];
assert(hit.repOk(rd));
assert(!hit.empty());
// Possibly adjust bot and width if we would have exceeded maxelt
TIndexOffU tops[2] = { hit.top, 0 };
TIndexOffU bots[2] = { hit.bot, 0 };
TIndexOffU width = hit.bot - hit.top;
if(nelt_out + width > maxelt) {
TIndexOffU trim = (TIndexOffU)((nelt_out + width) - maxelt);
#ifdef BOWTIE_64BIT_INDEX
TIndexOffU rn = rnd.nextU64() % width;
#else
TIndexOffU rn = rnd.nextU32() % width;
#endif
TIndexOffU newwidth = width - trim;
if(hit.top + rn + newwidth > hit.bot) {
// Two pieces
tops[0] = hit.top + rn;
bots[0] = hit.bot;
tops[1] = hit.top;
bots[1] = hit.top + newwidth - (bots[0] - tops[0]);
} else {
// One piece
tops[0] = hit.top + rn;
bots[0] = tops[0] + newwidth;
}
assert_leq(bots[0], hit.bot);
assert_leq(bots[1], hit.bot);
assert_geq(bots[0], tops[0]);
assert_geq(bots[1], tops[1]);
assert_eq(newwidth, (bots[0] - tops[0]) + (bots[1] - tops[1]));
}
for(int i = 0; i < 2 && !done; i++) {
if(bots[i] <= tops[i]) break;
TIndexOffU width = bots[i] - tops[i];
TIndexOffU top = tops[i];
// Clear list where resolved offsets are stored
swmSeed.mm1ranges++;
swmSeed.mm1rows += width;
if(!succ) {
swmSeed.mm1succ++;
succ = true;
}
if(firstEe) {
salistEe_.clear();
pool_.clear();
firstEe = false;
}
TSlice o(salistEe_, (TIndexOffU)salistEe_.size(), width);
for(size_t i = 0; i < width; i++) {
if(!salistEe_.add(pool_, OFF_MASK)) {
swmSeed.mm1ooms++;
return false;
}
}
eehits_.push_back(hit);
satpos_.expand();
satpos_.back().sat.init(SAKey(), top, OFF_MASK, o);
satpos_.back().sat.key.seq = MAX_U64;
satpos_.back().sat.key.len = (uint32_t)rd.length();
satpos_.back().pos.init(hit.fw, 0, 0, (uint32_t)rd.length());
satpos_.back().origSz = width;
rands_.expand();
rands_.back().init(width, all);
gws_.expand();
SARangeWithOffs<TSlice> sa;
sa.topf = satpos_.back().sat.topf;
sa.len = satpos_.back().sat.key.len;
sa.offs = satpos_.back().sat.offs;
gws_.back().init(
ebwt, // forward Bowtie index
ref, // reference sequences
sa, // SATuple
rnd, // pseudo-random generator
wlm); // metrics
assert(gws_.back().repOk(sa));
nelt_out += width;
if(nelt_out >= maxelt) {
done = true;
}
}
}
}
return true;
}
/**
* Extend a seed hit out on either side. Requires that we know the seed hit's
* offset into the read and orientation. Also requires that we know top/bot
* for the seed hit in both the forward and (if we want to extend to the right)
* reverse index.
*/
void SwDriver::extend(
const Read& rd, // read
const Ebwt& ebwtFw, // Forward Bowtie index
const Ebwt* ebwtBw, // Backward Bowtie index
TIndexOffU topf, // top in fw index
TIndexOffU botf, // bot in fw index
TIndexOffU topb, // top in bw index
TIndexOffU botb, // bot in bw index
bool fw, // seed orientation
size_t off, // seed offset from 5' end
size_t len, // seed length
PerReadMetrics& prm, // per-read metrics
size_t& nlex, // # positions we can extend to left w/o edit
size_t& nrex) // # positions we can extend to right w/o edit
{
TIndexOffU t[4], b[4];
TIndexOffU tp[4], bp[4];
SideLocus tloc, bloc;
size_t rdlen = rd.length();
size_t lim = fw ? off : rdlen - len - off;
// We're about to add onto the beginning, so reverse it
#ifndef NDEBUG
if(false) {
// TODO: This will sometimes fail even when the extension is legitimate
// This is because contains() comes in from one extreme or the other,
// whereas we started from the inside and worked outwards. This
// affects which Ns are OK and which are not OK.
// Have to do both because whether we can get through an N depends on
// which direction we're coming in
// bool fwContains = ebwtFw.contains(tmp_rdseq_);
// tmp_rdseq_.reverse();
// bool bwContains = ebwtBw != NULL && ebwtBw->contains(tmp_rdseq_);
// tmp_rdseq_.reverse();
// assert(fwContains || bwContains);
}
#endif
ASSERT_ONLY(tmp_rdseq_.reverse());
if(lim > 0) {
const Ebwt *ebwt = &ebwtFw;
assert(ebwt != NULL);
// Extend left using forward index
const BTDnaString& seq = fw ? rd.patFw : rd.patRc;
// See what we get by extending
TIndexOffU top = topf, bot = botf;
t[0] = t[1] = t[2] = t[3] = 0;
b[0] = b[1] = b[2] = b[3] = 0;
tp[0] = tp[1] = tp[2] = tp[3] = topb;
bp[0] = bp[1] = bp[2] = bp[3] = botb;
SideLocus tloc, bloc;
INIT_LOCS(top, bot, tloc, bloc, *ebwt);
for(size_t ii = 0; ii < lim; ii++) {
// Starting to left of seed (<off) and moving left
size_t i = 0;
if(fw) {
i = off - ii - 1;
} else {
i = rdlen - off - len - 1 - ii;
}
// Get char from read
int rdc = seq.get(i);
// See what we get by extending
if(bloc.valid()) {
prm.nSdFmops++;
t[0] = t[1] = t[2] = t[3] =
b[0] = b[1] = b[2] = b[3] = 0;
ebwt->mapBiLFEx(tloc, bloc, t, b, tp, bp);
SANITY_CHECK_4TUP(t, b, tp, bp);
int nonz = -1;
bool abort = false;
size_t origSz = bot - top;
for(int j = 0; j < 4; j++) {
if(b[j] > t[j]) {
if(nonz >= 0) {
abort = true;
break;
}
nonz = j;
top = t[j]; bot = b[j];
}
}
assert_leq(bot - top, origSz);
if(abort || (nonz != rdc && rdc <= 3) || bot - top < origSz) {
break;
}
} else {
assert_eq(bot, top+1);
prm.nSdFmops++;
int c = ebwt->mapLF1(top, tloc);
if(c != rdc && rdc <= 3) {
break;
}
bot = top + 1;
}
ASSERT_ONLY(tmp_rdseq_.append(rdc));
if(++nlex == 255) {
break;
}
INIT_LOCS(top, bot, tloc, bloc, *ebwt);
}
}
// We're about to add onto the end, so re-reverse
ASSERT_ONLY(tmp_rdseq_.reverse());
lim = fw ? rdlen - len - off : off;
if(lim > 0 && ebwtBw != NULL) {
const Ebwt *ebwt = ebwtBw;
assert(ebwt != NULL);
// Extend right using backward index
const BTDnaString& seq = fw ? rd.patFw : rd.patRc;
// See what we get by extending
TIndexOffU top = topb, bot = botb;
t[0] = t[1] = t[2] = t[3] = 0;
b[0] = b[1] = b[2] = b[3] = 0;
tp[0] = tp[1] = tp[2] = tp[3] = topf;
bp[0] = bp[1] = bp[2] = bp[3] = botf;
INIT_LOCS(top, bot, tloc, bloc, *ebwt);
for(size_t ii = 0; ii < lim; ii++) {
// Starting to right of seed (<off) and moving right
size_t i;
if(fw) {
i = ii + len + off;
} else {
i = rdlen - off + ii;
}
// Get char from read
int rdc = seq.get(i);
// See what we get by extending
if(bloc.valid()) {
prm.nSdFmops++;
t[0] = t[1] = t[2] = t[3] =
b[0] = b[1] = b[2] = b[3] = 0;
ebwt->mapBiLFEx(tloc, bloc, t, b, tp, bp);
SANITY_CHECK_4TUP(t, b, tp, bp);
int nonz = -1;
bool abort = false;
size_t origSz = bot - top;
for(int j = 0; j < 4; j++) {
if(b[j] > t[j]) {
if(nonz >= 0) {
abort = true;
break;
}
nonz = j;
top = t[j]; bot = b[j];
}
}
assert_leq(bot - top, origSz);
if(abort || (nonz != rdc && rdc <= 3) || bot - top < origSz) {
break;
}
} else {
assert_eq(bot, top+1);
prm.nSdFmops++;
int c = ebwt->mapLF1(top, tloc);
if(c != rdc && rdc <= 3) {
break;
}
bot = top + 1;
}
ASSERT_ONLY(tmp_rdseq_.append(rdc));
if(++nrex == 255) {
break;
}
INIT_LOCS(top, bot, tloc, bloc, *ebwt);
}
}
#ifndef NDEBUG
if(false) {
// TODO: This will sometimes fail even when the extension is legitimate
// This is because contains() comes in from one extreme or the other,
// whereas we started from the inside and worked outwards. This
// affects which Ns are OK and which are not OK.
// Have to do both because whether we can get through an N depends on
// which direction we're coming in
// bool fwContains = ebwtFw.contains(tmp_rdseq_);
// tmp_rdseq_.reverse();
// bool bwContains = ebwtBw != NULL && ebwtBw->contains(tmp_rdseq_);
// tmp_rdseq_.reverse();
// assert(fwContains || bwContains);
}
#endif
assert_lt(nlex, rdlen);
assert_lt(nrex, rdlen);
return;
}
/**
* Given seed results, set up all of our state for resolving and keeping
* track of reference offsets for hits.
*/
void SwDriver::prioritizeSATups(
const Read& read, // read
SeedResults& sh, // seed hits to extend into full alignments
const Ebwt& ebwtFw, // BWT
const Ebwt* ebwtBw, // BWT
const BitPairReference& ref, // Reference strings
int seedmms, // # mismatches allowed in seed
size_t maxelt, // max elts we'll consider
bool doExtend, // do extension of seed hits?
bool lensq, // square length in weight calculation
bool szsq, // square range size in weight calculation
size_t nsm, // if range as <= nsm elts, it's "small"
AlignmentCacheIface& ca, // alignment cache for seed hits
RandomSource& rnd, // pseudo-random generator
WalkMetrics& wlm, // group walk left metrics
PerReadMetrics& prm, // per-read metrics
size_t& nelt_out, // out: # elements total
bool all) // report all hits?
{
const size_t nonz = sh.nonzeroOffsets(); // non-zero positions
const int matei = (read.mate <= 1 ? 0 : 1);
satups_.clear();
gws_.clear();
rands_.clear();
rands2_.clear();
satpos_.clear();
satpos2_.clear();
size_t nrange = 0, nelt = 0, nsmall = 0, nsmall_elts = 0;
bool keepWhole = false;
EList<SATupleAndPos, 16>& satpos = keepWhole ? satpos_ : satpos2_;
for(size_t i = 0; i < nonz; i++) {
bool fw = true;
uint32_t offidx = 0, rdoff = 0, seedlen = 0;
QVal qv = sh.hitsByRank(i, offidx, rdoff, fw, seedlen);
assert(qv.valid());
assert(!qv.empty());
assert(qv.repOk(ca.current()));
ca.queryQval(qv, satups_, nrange, nelt);
for(size_t j = 0; j < satups_.size(); j++) {
const size_t sz = satups_[j].size();
// Check whether this hit occurs inside the extended boundaries of
// another hit we already processed for this read.
if(seedmms == 0) {
// See if we're covered by a previous extended seed hit
EList<ExtendRange>& range =
fw ? seedExRangeFw_[matei] : seedExRangeRc_[matei];
bool skip = false;
for(size_t k = 0; k < range.size(); k++) {
size_t p5 = range[k].off;
size_t len = range[k].len;
if(p5 <= rdoff && p5 + len >= (rdoff + seedlen)) {
if(sz <= range[k].sz) {
skip = true;
break;
}
}
}
if(skip) {
assert_gt(nrange, 0);
nrange--;
assert_geq(nelt, sz);
nelt -= sz;
continue; // Skip this seed
}
}
satpos.expand();
satpos.back().sat = satups_[j];
satpos.back().origSz = sz;
satpos.back().pos.init(fw, offidx, rdoff, seedlen);
if(sz <= nsm) {
nsmall++;
nsmall_elts += sz;
}
satpos.back().nlex = satpos.back().nrex = 0;
#ifndef NDEBUG
tmp_rdseq_.clear();
uint64_t key = satpos.back().sat.key.seq;
for(size_t k = 0; k < seedlen; k++) {
int c = (int)(key & 3);
tmp_rdseq_.append(c);
key >>= 2;
}
tmp_rdseq_.reverse();
#endif
size_t nlex = 0, nrex = 0;
if(doExtend) {
extend(
read,
ebwtFw,
ebwtBw,
satpos.back().sat.topf,
(TIndexOffU)(satpos.back().sat.topf + sz),
satpos.back().sat.topb,
(TIndexOffU)(satpos.back().sat.topb + sz),
fw,
rdoff,
seedlen,
prm,
nlex,
nrex);
}
satpos.back().nlex = nlex;
satpos.back().nrex = nrex;
if(seedmms == 0 && (nlex > 0 || nrex > 0)) {
assert_geq(rdoff, (fw ? nlex : nrex));
size_t p5 = rdoff - (fw ? nlex : nrex);
EList<ExtendRange>& range =
fw ? seedExRangeFw_[matei] : seedExRangeRc_[matei];
range.expand();
range.back().off = p5;
range.back().len = seedlen + nlex + nrex;
range.back().sz = sz;
}
}
satups_.clear();
}
assert_leq(nsmall, nrange);
nelt_out = nelt; // return the total number of elements
assert_eq(nrange, satpos.size());
satpos.sort();
if(keepWhole) {
gws_.ensure(nrange);
rands_.ensure(nrange);
for(size_t i = 0; i < nrange; i++) {
gws_.expand();
SARangeWithOffs<TSlice> sa;
sa.topf = satpos_.back().sat.topf;
sa.len = satpos_.back().sat.key.len;
sa.offs = satpos_.back().sat.offs;
gws_.back().init(
ebwtFw, // forward Bowtie index
ref, // reference sequences
sa, // SA tuples: ref hit, salist range
rnd, // pseudo-random generator
wlm); // metrics
assert(gws_.back().initialized());
rands_.expand();
rands_.back().init(satpos_[i].sat.size(), all);
}
return;
}
// Resize satups_ list so that ranges having elements that we might
// possibly explore are present
satpos_.ensure(min(maxelt, nelt));
gws_.ensure(min(maxelt, nelt));
rands_.ensure(min(maxelt, nelt));
rands2_.ensure(min(maxelt, nelt));
size_t nlarge_elts = nelt - nsmall_elts;
if(maxelt < nelt) {
size_t diff = nelt - maxelt;
if(diff >= nlarge_elts) {
nlarge_elts = 0;
} else {
nlarge_elts -= diff;
}
}
size_t nelt_added = 0;
// Now we have a collection of ranges in satpos2_. Now we want to decide
// how we explore elements from them. The basic idea is that: for very
// small guys, where "very small" means that the size of the range is less
// than or equal to the parameter 'nsz', we explore them in their entirety
// right away. For the rest, we want to select in a way that is (a)
// random, and (b) weighted toward examining elements from the smaller
// ranges more frequently (and first).
//
// 1. do the smalls
for(size_t j = 0; j < nsmall && nelt_added < maxelt; j++) {
satpos_.expand();
satpos_.back() = satpos2_[j];
gws_.expand();
SARangeWithOffs<TSlice> sa;
sa.topf = satpos_.back().sat.topf;
sa.len = satpos_.back().sat.key.len;
sa.offs = satpos_.back().sat.offs;
gws_.back().init(
ebwtFw, // forward Bowtie index
ref, // reference sequences
sa, // SA tuples: ref hit, salist range
rnd, // pseudo-random generator
wlm); // metrics
assert(gws_.back().initialized());
rands_.expand();
rands_.back().init(satpos_.back().sat.size(), all);
nelt_added += satpos_.back().sat.size();
#ifndef NDEBUG
for(size_t k = 0; k < satpos_.size()-1; k++) {
assert(!(satpos_[k] == satpos_.back()));
}
#endif
}
if(nelt_added >= maxelt || nsmall == satpos2_.size()) {
nelt_out = nelt_added;
return;
}
// 2. do the non-smalls
// Initialize the row sampler
rowsamp_.init(satpos2_, nsmall, satpos2_.size(), lensq, szsq);
// Initialize the random choosers
rands2_.resize(satpos2_.size());
for(size_t j = 0; j < satpos2_.size(); j++) {
rands2_[j].reset();
}
while(nelt_added < maxelt && nelt_added < nelt) {
// Pick a non-small range to sample from
size_t ri = rowsamp_.next(rnd) + nsmall;
assert_geq(ri, nsmall);
assert_lt(ri, satpos2_.size());
// Initialize random element chooser for that range
if(!rands2_[ri].inited()) {
rands2_[ri].init(satpos2_[ri].sat.size(), all);
assert(!rands2_[ri].done());
}
assert(!rands2_[ri].done());
// Choose an element from the range
size_t r = rands2_[ri].next(rnd);
if(rands2_[ri].done()) {
// Tell the row sampler this range is done
rowsamp_.finishedRange(ri - nsmall);
}
// Add the element to the satpos_ list
SATuple sat;
TSlice o;
o.init(satpos2_[ri].sat.offs, r, r+1);
sat.init(satpos2_[ri].sat.key, (TIndexOffU)(satpos2_[ri].sat.topf + r), OFF_MASK, o);
satpos_.expand();
satpos_.back().sat = sat;
satpos_.back().origSz = satpos2_[ri].origSz;
satpos_.back().pos = satpos2_[ri].pos;
// Initialize GroupWalk object
gws_.expand();
SARangeWithOffs<TSlice> sa;
sa.topf = sat.topf;
sa.len = sat.key.len;
sa.offs = sat.offs;
gws_.back().init(
ebwtFw, // forward Bowtie index
ref, // reference sequences
sa, // SA tuples: ref hit, salist range
rnd, // pseudo-random generator
wlm); // metrics
assert(gws_.back().initialized());
// Initialize random selector
rands_.expand();
rands_.back().init(1, all);
nelt_added++;
}
nelt_out = nelt_added;
return;
}
enum {
FOUND_NONE = 0,
FOUND_EE,
FOUND_UNGAPPED,
};
/**
* Given a collection of SeedHits for a single read, extend seed alignments
* into full alignments. Where possible, try to avoid redundant offset lookups
* and dynamic programming wherever possible. Optionally report alignments to
* a AlnSinkWrap object as they are discovered.
*
* If 'reportImmediately' is true, returns true iff a call to msink->report()
* returned true (indicating that the reporting policy is satisfied and we can
* stop). Otherwise, returns false.
*/
int SwDriver::extendSeeds(
Read& rd, // read to align
bool mate1, // true iff rd is mate #1
SeedResults& sh, // seed hits to extend into full alignments
const Ebwt& ebwtFw, // BWT
const Ebwt* ebwtBw, // BWT'
const BitPairReference& ref, // Reference strings
SwAligner& swa, // dynamic programming aligner
const Scoring& sc, // scoring scheme
int seedmms, // # mismatches allowed in seed
int seedlen, // length of seed
int seedival, // interval between seeds
TAlScore& minsc, // minimum score for anchor
int nceil, // maximum # Ns permitted in reference portion
size_t maxhalf, // max width in either direction for DP tables
bool doUngapped, // do ungapped alignment
size_t maxIters, // stop after this many seed-extend loop iters
size_t maxUg, // stop after this many ungaps
size_t maxDp, // stop after this many dps
size_t maxUgStreak, // stop after streak of this many ungap fails
size_t maxDpStreak, // stop after streak of this many dp fails
bool doExtend, // do seed extension
bool enable8, // use 8-bit SSE where possible
size_t cminlen, // use checkpointer if read longer than this
size_t cpow2, // interval between diagonals to checkpoint
bool doTri, // triangular mini-fills?
int tighten, // -M score tightening mode
AlignmentCacheIface& ca, // alignment cache for seed hits
RandomSource& rnd, // pseudo-random source
WalkMetrics& wlm, // group walk left metrics
SwMetrics& swmSeed, // DP metrics for seed-extend
PerReadMetrics& prm, // per-read metrics
AlnSinkWrap* msink, // AlnSink wrapper for multiseed-style aligner
bool reportImmediately, // whether to report hits immediately to msink
bool& exhaustive) // set to true iff we searched all seeds exhaustively
{
bool all = msink->allHits();
assert(!reportImmediately || msink != NULL);
assert(!reportImmediately || !msink->maxed());
assert_geq(nceil, 0);
assert_leq((size_t)nceil, rd.length());
// Calculate the largest possible number of read and reference gaps
const size_t rdlen = rd.length();
TAlScore perfectScore = sc.perfectScore(rdlen);
DynProgFramer dpframe(!gReportOverhangs);
swa.reset();
// Initialize a set of GroupWalks, one for each seed. Also, intialize the
// accompanying lists of reference seed hits (satups*)
const size_t nsm = 5;
const size_t nonz = sh.nonzeroOffsets(); // non-zero positions
size_t eeHits = sh.numE2eHits();
bool eeMode = eeHits > 0;
bool firstEe = true;
bool firstExtend = true;
// Reset all the counters related to streaks
prm.nEeFail = 0;
prm.nUgFail = 0;
prm.nDpFail = 0;
size_t nelt = 0, neltLeft = 0;
size_t rows = rdlen;
size_t eltsDone = 0;
// cerr << "===" << endl;
while(true) {
if(eeMode) {
if(firstEe) {
firstEe = false;
eeMode = eeSaTups(
rd, // read
sh, // seed hits to extend into full alignments
ebwtFw, // BWT
ref, // Reference strings
rnd, // pseudo-random generator
wlm, // group walk left metrics
swmSeed, // seed-extend metrics
nelt, // out: # elements total
maxIters, // max # to report
all); // report all hits?
assert_eq(gws_.size(), rands_.size());
assert_eq(gws_.size(), satpos_.size());
} else {
eeMode = false;
}
}
if(!eeMode) {
if(nonz == 0) {
return EXTEND_EXHAUSTED_CANDIDATES; // No seed hits! Bail.
}
if(minsc == perfectScore) {
return EXTEND_PERFECT_SCORE; // Already found all perfect hits!
}
if(firstExtend) {
nelt = 0;
prioritizeSATups(
rd, // read
sh, // seed hits to extend into full alignments
ebwtFw, // BWT
ebwtBw, // BWT'
ref, // Reference strings
seedmms, // # seed mismatches allowed
maxIters, // max rows to consider per position
doExtend, // extend out seeds
true, // square extended length
true, // square SA range size
nsm, // smallness threshold
ca, // alignment cache for seed hits
rnd, // pseudo-random generator
wlm, // group walk left metrics
prm, // per-read metrics
nelt, // out: # elements total
all); // report all hits?
assert_eq(gws_.size(), rands_.size());
assert_eq(gws_.size(), satpos_.size());
neltLeft = nelt;
firstExtend = false;
}
if(neltLeft == 0) {
// Finished examining gapped candidates
break;
}
}
for(size_t i = 0; i < gws_.size(); i++) {
if(eeMode && eehits_[i].score < minsc) {
return EXTEND_PERFECT_SCORE;
}
bool is_small = satpos_[i].sat.size() < nsm;
bool fw = satpos_[i].pos.fw;
uint32_t rdoff = satpos_[i].pos.rdoff;
uint32_t seedhitlen = satpos_[i].pos.seedlen;
if(!fw) {
// 'rdoff' and 'offidx' are with respect to the 5' end of
// the read. Here we convert rdoff to be with respect to
// the upstream (3') end of ther read.
rdoff = (uint32_t)(rdlen - rdoff - seedhitlen);
}
bool first = true;
// If the range is small, investigate all elements now. If the
// range is large, just investigate one and move on - we might come
// back to this range later.
size_t riter = 0;
while(!rands_[i].done() && (first || is_small || eeMode)) {
assert(!gws_[i].done());
riter++;
if(minsc == perfectScore) {
if(!eeMode || eehits_[i].score < perfectScore) {
return EXTEND_PERFECT_SCORE;
}
} else if(eeMode && eehits_[i].score < minsc) {
break;
}
if(prm.nExDps >= maxDp || prm.nMateDps >= maxDp) {
return EXTEND_EXCEEDED_HARD_LIMIT;
}
if(prm.nExUgs >= maxUg || prm.nMateUgs >= maxUg) {
return EXTEND_EXCEEDED_HARD_LIMIT;
}
if(prm.nExIters >= maxIters) {
return EXTEND_EXCEEDED_HARD_LIMIT;
}
prm.nExIters++;
first = false;
// Resolve next element offset
WalkResult wr;
size_t elt = rands_[i].next(rnd);
//cerr << "elt=" << elt << endl;
SARangeWithOffs<TSlice> sa;
sa.topf = satpos_[i].sat.topf;
sa.len = satpos_[i].sat.key.len;
sa.offs = satpos_[i].sat.offs;
gws_[i].advanceElement((TIndexOffU)elt, ebwtFw, ref, sa, gwstate_, wr, wlm, prm);
eltsDone++;
if(!eeMode) {
assert_gt(neltLeft, 0);
neltLeft--;
}
assert_neq(OFF_MASK, wr.toff);
TIndexOffU tidx = 0, toff = 0, tlen = 0;
bool straddled = false;
ebwtFw.joinedToTextOff(
wr.elt.len,
wr.toff,
tidx,
toff,
tlen,
eeMode, // reject straddlers?
straddled); // did it straddle?
if(tidx == OFF_MASK) {
// The seed hit straddled a reference boundary so the seed hit
// isn't valid
continue;
}
#ifndef NDEBUG
if(!eeMode && !straddled) { // Check that seed hit matches reference
uint64_t key = satpos_[i].sat.key.seq;
for(size_t k = 0; k < wr.elt.len; k++) {
int c = ref.getBase(tidx, toff + wr.elt.len - k - 1);
assert_leq(c, 3);
int ck = (int)(key & 3);
key >>= 2;
assert_eq(c, ck);
}
}
#endif
// Find offset of alignment's upstream base assuming net gaps=0
// between beginning of read and beginning of seed hit
int64_t refoff = (int64_t)toff - rdoff;
// Coordinate of the seed hit w/r/t the pasted reference string
Coord refcoord(tidx, refoff, fw);
if(seenDiags1_.locusPresent(refcoord)) {
// Already handled alignments seeded on this diagonal
prm.nRedundants++;
swmSeed.rshit++;
continue;
}
// Now that we have a seed hit, there are many issues to solve
// before we have a completely framed dynamic programming problem.
// They include:
//
// 1. Setting reference offsets on either side of the seed hit,
// accounting for where the seed occurs in the read
// 2. Adjusting the width of the banded dynamic programming problem
// and adjusting reference bounds to allow for gaps in the
// alignment
// 3. Accounting for the edges of the reference, which can impact
// the width of the DP problem and reference bounds.
// 4. Perhaps filtering the problem down to a smaller problem based
// on what DPs we've already solved for this read
//
// We do #1 here, since it is simple and we have all the seed-hit
// information here. #2 and #3 are handled in the DynProgFramer.
int readGaps = 0, refGaps = 0;
bool ungapped = false;
if(!eeMode) {
readGaps = sc.maxReadGaps(minsc, rdlen);
refGaps = sc.maxRefGaps(minsc, rdlen);
ungapped = (readGaps == 0 && refGaps == 0);
}
int state = FOUND_NONE;
bool found = false;