-
Notifications
You must be signed in to change notification settings - Fork 119
/
aligner_sw_driver.h
2938 lines (2857 loc) · 106 KB
/
aligner_sw_driver.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
/*
* 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/>.
*/
/*
* aligner_sw_driver.h
*
* REDUNDANT SEED HITS
*
* We say that two seed hits are redundant if they trigger identical
* seed-extend dynamic programming problems. Put another way, they both lie on
* the same diagonal of the overall read/reference dynamic programming matrix.
* Detecting redundant seed hits is simple when the seed hits are ungapped. We
* do this after offset resolution but before the offset is converted to genome
* coordinates (see uses of the seenDiags1_/seenDiags2_ fields for examples).
*
* REDUNDANT ALIGNMENTS
*
* In an unpaired context, we say that two alignments are redundant if they
* share any cells in the global DP table. Roughly speaking, this is like
* saying that two alignments are redundant if any read character aligns to the
* same reference character (same reference sequence, same strand, same offset)
* in both alignments.
*
* In a paired-end context, we say that two paired-end alignments are redundant
* if the mate #1s are redundant and the mate #2s are redundant.
*
* How do we enforce this? In the unpaired context, this is relatively simple:
* the cells from each alignment are checked against a set containing all cells
* from all previous alignments. Given a new alignment, for each cell in the
* new alignment we check whether it is in the set. If there is any overlap,
* the new alignment is rejected as redundant. Otherwise, the new alignment is
* accepted and its cells are added to the set.
*
* Enforcement in a paired context is a little trickier. Consider the
* following approaches:
*
* 1. Skip anchors that are redundant with any previous anchor or opposite
* alignment. This is sufficient to ensure no two concordant alignments
* found are redundant.
*
* 2. Same as scheme 1, but with a "transitive closure" scheme for finding all
* concordant pairs in the vicinity of an anchor. Consider the AB/AC
* scenario from the previous paragraph. If B is the anchor alignment, we
* will find AB but not AC. But under this scheme, once we find AB we then
* let B be a new anchor and immediately look for its opposites. Likewise,
* if we find any opposite, we make them anchors and continue searching. We
* don't stop searching until every opposite is used as an anchor.
*
* 3. Skip anchors that are redundant with any previous anchor alignment (but
* allow anchors that are redundant with previous opposite alignments).
* This isn't sufficient to avoid redundant concordant alignments. To avoid
* redundant concordants, we need an additional procedure that checks each
* new concordant alignment one-by-one against a list of previous concordant
* alignments to see if it is redundant.
*
* We take approach 1.
*/
#ifndef ALIGNER_SW_DRIVER_H_
#define ALIGNER_SW_DRIVER_H_
#include <iostream>
// -- BTL remove --
#include <stdlib.h>
#include <sys/time.h>
// -- --
#include <utility>
#include "ds.h"
#include "aligner_seed.h"
#include "aligner_sw.h"
#include "aligner_cache.h"
#include "reference.h"
#include "group_walk.h"
#include "gfm.h"
#include "mem_ids.h"
#include "aln_sink.h"
#include "pe.h"
#include "ival_list.h"
#include "simple_func.h"
#include "random_util.h"
#include "dp_framer.h"
using namespace std;
template <typename index_t>
struct SeedPos {
SeedPos() : fw(false), offidx(0), rdoff(0), seedlen(0) { }
SeedPos(
bool fw_,
index_t offidx_,
index_t rdoff_,
index_t seedlen_)
{
init(fw_, offidx_, rdoff_, seedlen_);
}
void init(
bool fw_,
index_t offidx_,
index_t rdoff_,
index_t seedlen_)
{
fw = fw_;
offidx = offidx_;
rdoff = rdoff_;
seedlen = seedlen_;
}
bool operator<(const SeedPos& o) const {
if(offidx < o.offidx) return true;
if(offidx > o.offidx) return false;
if(rdoff < o.rdoff) return true;
if(rdoff > o.rdoff) return false;
if(seedlen < o.seedlen) return true;
if(seedlen > o.seedlen) return false;
if(fw && !o.fw) return true;
if(!fw && o.fw) return false;
return false;
}
bool operator>(const SeedPos& o) const {
if(offidx < o.offidx) return false;
if(offidx > o.offidx) return true;
if(rdoff < o.rdoff) return false;
if(rdoff > o.rdoff) return true;
if(seedlen < o.seedlen) return false;
if(seedlen > o.seedlen) return true;
if(fw && !o.fw) return false;
if(!fw && o.fw) return true;
return false;
}
bool operator==(const SeedPos& o) const {
return fw == o.fw && offidx == o.offidx &&
rdoff == o.rdoff && seedlen == o.seedlen;
}
bool fw;
index_t offidx;
index_t rdoff;
index_t seedlen;
};
/**
* An SATuple along with the associated seed position.
*/
template <typename index_t>
struct SATupleAndPos {
SATuple<index_t> sat; // result for this seed hit
SeedPos<index_t> pos; // seed position that yielded the range this was taken from
index_t origSz; // size of range this was taken from
index_t nlex; // # position we can extend seed hit to left w/o edit
index_t nrex; // # position we can extend seed hit to right w/o edit
bool operator<(const SATupleAndPos& o) const {
if(sat < o.sat) return true;
if(sat > o.sat) return false;
return pos < o.pos;
}
bool operator==(const SATupleAndPos& o) const {
return sat == o.sat && pos == o.pos;
}
};
/**
* Encapsulates the weighted random sampling scheme we want to use to pick
* which seed hit range to sample a row from.
*/
template <typename index_t>
class RowSampler {
public:
RowSampler(int cat = 0) : elim_(cat), masses_(cat) {
mass_ = 0.0f;
}
/**
* Initialze sampler with respect to a range of elements in a list of
* SATupleAndPos's.
*/
void init(
const EList<SATupleAndPos<index_t>, 16>& salist,
index_t sai,
index_t saf,
bool lensq, // whether to square the numerator, which = extended length
bool szsq) // whether to square denominator, which =
{
assert_gt(saf, sai);
elim_.resize(saf - sai);
elim_.fill(false);
// Initialize mass
mass_ = 0.0f;
masses_.resize(saf - sai);
for(index_t i = sai; i < saf; i++) {
index_t len = salist[i].nlex + salist[i].nrex + 1; // + salist[i].sat.key.len;
double num = (double)len;
if(lensq) {
num *= num;
}
double denom = (double)salist[i].sat.size();
if(szsq) {
denom *= denom;
}
masses_[i - sai] = num / denom;
mass_ += masses_[i - sai];
}
}
/**
* Caller is indicating that the bin at index i is exhausted and we should
* exclude it from our sampling from now on.
*/
void finishedRange(index_t i) {
assert_lt(i, masses_.size());
elim_[i] = true;
mass_ -= masses_[i];
}
/**
* Sample randomly from the mass.
*/
size_t next(RandomSource& rnd) {
// Throw the dart
double rd = rnd.nextFloat() * mass_;
double mass_sofar = 0.0f;
size_t sz = masses_.size();
size_t last_unelim = std::numeric_limits<size_t>::max();
for(size_t i = 0; i < sz; i++) {
if(!elim_[i]) {
last_unelim = i;
mass_sofar += masses_[i];
if(rd < mass_sofar) {
// This is the one we hit
return i;
}
}
}
assert_neq(std::numeric_limits<size_t>::max(), last_unelim);
return last_unelim;
}
protected:
double mass_; // total probability mass to throw darts at
EList<bool> elim_; // whether the range is eliminated
EList<double> masses_; // mass of each range
};
/**
* Return values from extendSeeds and extendSeedsPaired.
*/
enum {
// All end-to-end and seed hits were examined
// The policy does not need us to look any further
EXTEND_EXHAUSTED_CANDIDATES = 1,
EXTEND_POLICY_FULFILLED,
// We stopped because we reached a point where the only remaining
// alignments of interest have perfect scores, but we already investigated
// perfect alignments
EXTEND_PERFECT_SCORE,
// We stopped because we ran up against a limit on how much work we should
// do for one set of seed ranges, e.g. the limit on number of consecutive
// unproductive DP extensions
EXTEND_EXCEEDED_SOFT_LIMIT,
// We stopped because we ran up against a limit on how much work we should
// do for overall before giving up on a mate
EXTEND_EXCEEDED_HARD_LIMIT
};
/**
* Data structure encapsulating a range that's been extended out in two
* directions.
*/
struct ExtendRange {
void init(size_t off_, size_t len_, size_t sz_) {
off = off_; len = len_; sz = sz_;
}
size_t off; // offset of extended region
size_t len; // length between extremes of extended region
size_t sz; // # of elements in SA range
};
template <typename index_t>
class SwDriver {
typedef PList<index_t, CACHE_PAGE_SZ> TSAList;
public:
SwDriver(size_t bytes) :
satups_(DP_CAT),
gws_(DP_CAT),
seenDiags1_(DP_CAT),
seenDiags2_(DP_CAT),
redAnchor_(DP_CAT),
redMate1_(DP_CAT),
redMate2_(DP_CAT),
pool_(bytes, CACHE_PAGE_SZ, DP_CAT),
salistEe_(DP_CAT),
gwstate_(GW_CAT) { }
/**
* 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 problems. Optionally report alignments
* to a AlnSinkWrap object as they are discovered.
*
* If 'reportImmediately' is true, returns true iff a call to
* mhs->report() returned true (indicating that the reporting
* policy is satisfied and we can stop). Otherwise, returns false.
*/
int extendSeeds(
Read& rd, // read to align
bool mate1, // true iff rd is mate #1
SeedResults<index_t>& sh, // seed hits to extend into full alignments
const GFM<index_t>& gfmFw, // BWT
const GFM<index_t>* gfmBw, // 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 ref portion
size_t maxhalf, // maximum width on one side of DP table
bool doUngapped, // do ungapped alignment
size_t maxIters, // stop after this many seed-extend loop iters
size_t maxUg, // max # ungapped extends
size_t maxDp, // max # 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<index_t>& 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<index_t>* mhs, // HitSink for multiseed-style aligner
bool reportImmediately, // whether to report hits immediately to mhs
bool& exhaustive);
/**
* Given a collection of SeedHits for a read pair, extend seed
* alignments into full alignments and then look for the opposite
* mate using dynamic programming. Where possible, try to avoid
* redundant offset lookups. Optionally report alignments to a
* AlnSinkWrap object as they are discovered.
*
* If 'reportImmediately' is true, returns true iff a call to
* mhs->report() returned true (indicating that the reporting
* policy is satisfied and we can stop). Otherwise, returns false.
*/
int extendSeedsPaired(
Read& rd, // mate to align as anchor
Read& ord, // mate to align as opposite
bool anchor1, // true iff anchor mate is mate1
bool oppFilt, // true iff opposite mate was filtered out
SeedResults<index_t>& sh, // seed hits for anchor
const GFM<index_t>& gfmFw, // BWT
const GFM<index_t>* gfmBw, // BWT'
const BitPairReference& ref, // Reference strings
SwAligner& swa, // dyn programming aligner for anchor
SwAligner& swao, // dyn programming aligner for opposite
const Scoring& sc, // scoring scheme
const PairedEndPolicy& pepol,// paired-end policy
int seedmms, // # mismatches allowed in seed
int seedlen, // length of seed
int seedival, // interval between seeds
TAlScore& minsc, // minimum score for anchor
TAlScore& ominsc, // minimum score for opposite
int nceil, // max # Ns permitted in ref for anchor
int onceil, // max # Ns permitted in ref for opposite
bool nofw, // don't align forward read
bool norc, // don't align revcomp read
size_t maxhalf, // maximum width on one side of DP table
bool doUngapped, // do ungapped alignment
size_t maxIters, // stop after this many seed-extend loop iters
size_t maxUg, // max # ungapped extends
size_t maxDp, // max # DPs
size_t maxEeStreak, // stop after streak of this many end-to-end fails
size_t maxUgStreak, // stop after streak of this many ungap fails
size_t maxDpStreak, // stop after streak of this many dp fails
size_t maxMateStreak, // stop seed range after N mate-find 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<index_t>& cs, // alignment cache for seed hits
RandomSource& rnd, // pseudo-random source
WalkMetrics& wlm, // group walk left metrics
SwMetrics& swmSeed, // DP metrics for seed-extend
SwMetrics& swmMate, // DP metrics for mate finidng
PerReadMetrics& prm, // per-read metrics for anchor
AlnSinkWrap<index_t>* msink, // AlnSink wrapper for multiseed-style aligner
bool swMateImmediately, // whether to look for mate immediately
bool reportImmediately, // whether to report hits immediately to msink
bool discord, // look for discordant alignments?
bool mixed, // look for unpaired as well as paired alns?
bool& exhaustive);
/**
* Prepare for a new read.
*/
void nextRead(bool paired, size_t mate1len, size_t mate2len) {
redAnchor_.reset();
seenDiags1_.reset();
seenDiags2_.reset();
seedExRangeFw_[0].clear(); // mate 1 fw
seedExRangeFw_[1].clear(); // mate 2 fw
seedExRangeRc_[0].clear(); // mate 1 rc
seedExRangeRc_[1].clear(); // mate 2 rc
size_t maxlen = mate1len;
if(paired) {
redMate1_.reset();
redMate1_.init(mate1len);
redMate2_.reset();
redMate2_.init(mate2len);
if(mate2len > maxlen) {
maxlen = mate2len;
}
}
redAnchor_.init(maxlen);
}
protected:
bool eeSaTups(
const Read& rd, // read
SeedResults<index_t>& sh, // seed hits to extend into full alignments
const GFM<index_t>& gfm, // BWT
const BitPairReference& ref, // Reference strings
RandomSource& rnd, // pseudo-random generator
WalkMetrics& wlm, // group walk left metrics
SwMetrics& swmSeed, // metrics for seed extensions
index_t& nelt_out, // out: # elements total
index_t maxelts, // max # elts to report
bool all); // report all hits?
void extend(
const Read& rd, // read
const GFM<index_t>& gfmFw, // Forward Bowtie index
const GFM<index_t>* gfmBw, // Backward Bowtie index
index_t topf, // top in fw index
index_t botf, // bot in fw index
index_t topb, // top in bw index
index_t botb, // bot in bw index
bool fw, // seed orientation
index_t off, // seed offset from 5' end
index_t len, // seed length
PerReadMetrics& prm, // per-read metrics
index_t& nlex, // # positions we can extend to left w/o edit
index_t& nrex); // # positions we can extend to right w/o edit
void prioritizeSATups(
const Read& rd, // read
SeedResults<index_t>& sh, // seed hits to extend into full alignments
const GFM<index_t>& gfmFw, // BWT
const GFM<index_t>* gfmBw, // BWT'
const BitPairReference& ref, // Reference strings
int seedmms, // # seed mismatches allowed
index_t maxelt, // max elts we'll consider
bool doExtend, // extend out seeds
bool lensq, // square extended length
bool szsq, // square SA range size
index_t nsm, // if range as <= nsm elts, it's "small"
AlignmentCacheIface<index_t>& ca, // alignment cache for seed hits
RandomSource& rnd, // pseudo-random generator
WalkMetrics& wlm, // group walk left metrics
PerReadMetrics& prm, // per-read metrics
index_t& nelt_out, // out: # elements total
bool all); // report all hits?
Random1toN rand_; // random number generators
EList<Random1toN, 16> rands_; // random number generators
EList<Random1toN, 16> rands2_; // random number generators
EList<EEHit<index_t>, 16> eehits_; // holds end-to-end hits
EList<SATupleAndPos<index_t>, 16> satpos_; // holds SATuple, SeedPos pairs
EList<SATupleAndPos<index_t>, 16> satpos2_; // holds SATuple, SeedPos pairs
EList<SATuple<index_t>, 16> satups_; // holds SATuples to explore elements from
EList<GroupWalk2S<index_t, TSlice, 16> > gws_; // list of GroupWalks; no particular order
EList<size_t> mateStreaks_; // mate-find fail streaks
RowSampler<index_t> rowsamp_; // row sampler
// Ranges that we've extended through when extending seed hits
EList<ExtendRange> seedExRangeFw_[2];
EList<ExtendRange> seedExRangeRc_[2];
// Data structures encapsulating the diagonals that have already been used
// to seed alignment for mate 1 and mate 2.
EIvalMergeListBinned seenDiags1_;
EIvalMergeListBinned seenDiags2_;
// For weeding out redundant alignments
RedundantAlns redAnchor_; // database of cells used for anchor alignments
RedundantAlns redMate1_; // database of cells used for mate 1 alignments
RedundantAlns redMate2_; // database of cells used for mate 2 alignments
// For holding results for anchor (res_) and opposite (ores_) mates
SwResult resGap_; // temp holder for alignment result
SwResult oresGap_; // temp holder for alignment result, opp mate
SwResult resUngap_; // temp holder for ungapped alignment result
SwResult oresUngap_; // temp holder for ungap. aln. opp mate
SwResult resEe_; // temp holder for ungapped alignment result
SwResult oresEe_; // temp holder for ungap. aln. opp mate
Pool pool_; // memory pages for salistExact_
TSAList salistEe_; // PList for offsets for end-to-end hits
GroupWalkState<index_t> gwstate_; // some per-thread state shared by all GroupWalks
// For AlnRes::matchesRef:
ASSERT_ONLY(SStringExpandable<char> raw_refbuf_);
ASSERT_ONLY(SStringExpandable<uint32_t> raw_destU32_);
ASSERT_ONLY(EList<bool> raw_matches_);
ASSERT_ONLY(BTDnaString tmp_rf_);
ASSERT_ONLY(BTDnaString tmp_rdseq_);
ASSERT_ONLY(BTString tmp_qseq_);
ASSERT_ONLY(EList<index_t> tmp_reflens_);
ASSERT_ONLY(EList<index_t> tmp_refoffs_);
};
#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.
*/
/**
* 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'.
*/
template <typename index_t>
bool SwDriver<index_t>::eeSaTups(
const Read& rd, // read
SeedResults<index_t>& sh, // seed hits to extend into full alignments
const GFM<index_t>& gfm, // BWT
const BitPairReference& ref, // Reference strings
RandomSource& rnd, // pseudo-random generator
WalkMetrics& wlm, // group walk left metrics
SwMetrics& swmSeed, // metrics for seed extensions
index_t& nelt_out, // out: # elements total
index_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
index_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);
index_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
index_t rn64 = rnd.nextU64();
index_t rn = rn64 % (uint64_t)tot;
#else
index_t rn32 = rnd.nextU32();
index_t 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<index_t> 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
index_t tops[2] = { hit.top, 0 };
index_t bots[2] = { hit.bot, 0 };
index_t width = hit.bot - hit.top;
if(nelt_out + width > maxelt) {
index_t trim = (index_t)((nelt_out + width) - maxelt);
#ifdef BOWTIE_64BIT_INDEX
index_t rn = rnd.nextU64() % width;
#else
index_t rn = rnd.nextU32() % width;
#endif
index_t 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;
index_t width = bots[i] - tops[i];
index_t 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_, (index_t)salistEe_.size(), width);
for(index_t i = 0; i < width; i++) {
if(!salistEe_.add(pool_, (index_t)OFF_MASK)) {
swmSeed.exooms++;
return false;
}
}
assert(!done);
eehits_.push_back(hit);
satpos_.expand();
satpos_.back().sat.init(SAKey(), top, (index_t)OFF_MASK, o);
satpos_.back().sat.key.seq = MAX_U64;
satpos_.back().sat.key.len = (index_t)rd.length();
satpos_.back().pos.init(fw, 0, 0, (index_t)rd.length());
satpos_.back().origSz = width;
rands_.expand();
rands_.back().init(width, all);
gws_.expand();
SARangeWithOffs<TSlice, index_t> sa;
sa.topf = satpos_.back().sat.topf;
sa.len = satpos_.back().sat.key.len;
sa.offs = satpos_.back().sat.offs;
gws_.back().init(
gfm, // 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);
index_t sz = sh.mm1EEHits().size();
for(index_t i = 0; i < sz && !done; i++) {
EEHit<index_t> hit = sh.mm1EEHits()[i];
assert(hit.repOk(rd));
assert(!hit.empty());
// Possibly adjust bot and width if we would have exceeded maxelt
index_t tops[2] = { hit.top, 0 };
index_t bots[2] = { hit.bot, 0 };
index_t width = hit.bot - hit.top;
if(nelt_out + width > maxelt) {
index_t trim = (index_t)((nelt_out + width) - maxelt);
#ifdef BOWTIE_64BIT_INDEX
index_t rn = rnd.nextU64() % width;
#else
index_t rn = rnd.nextU32() % width;
#endif
index_t 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;
index_t width = bots[i] - tops[i];
index_t 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_, (index_t)salistEe_.size(), width);
for(size_t i = 0; i < width; i++) {
if(!salistEe_.add(pool_, (index_t)OFF_MASK)) {
swmSeed.mm1ooms++;
return false;
}
}
eehits_.push_back(hit);
satpos_.expand();
satpos_.back().sat.init(SAKey(), top, (index_t)OFF_MASK, o);
satpos_.back().sat.key.seq = MAX_U64;
satpos_.back().sat.key.len = (index_t)rd.length();
satpos_.back().pos.init(hit.fw, 0, 0, (index_t)rd.length());
satpos_.back().origSz = width;
rands_.expand();
rands_.back().init(width, all);
gws_.expand();
SARangeWithOffs<TSlice, index_t> sa;
sa.topf = satpos_.back().sat.topf;
sa.len = satpos_.back().sat.key.len;
sa.offs = satpos_.back().sat.offs;
gws_.back().init(
gfm, // 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.
*/
template <typename index_t>
void SwDriver<index_t>::extend(
const Read& rd, // read
const GFM<index_t>& gfmFw, // Forward Bowtie index
const GFM<index_t>* gfmBw, // Backward Bowtie index
index_t topf, // top in fw index
index_t botf, // bot in fw index
index_t topb, // top in bw index
index_t botb, // bot in bw index
bool fw, // seed orientation
index_t off, // seed offset from 5' end
index_t len, // seed length
PerReadMetrics& prm, // per-read metrics
index_t& nlex, // # positions we can extend to left w/o edit
index_t& nrex) // # positions we can extend to right w/o edit
{
index_t t[4], b[4];
index_t tp[4], bp[4];
SideLocus<index_t> tloc, bloc;
index_t rdlen = (index_t)rd.length();
index_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 = gfmFw.contains(tmp_rdseq_);
tmp_rdseq_.reverse();
bool bwContains = gfmBw != NULL && gfmBw->contains(tmp_rdseq_);
tmp_rdseq_.reverse();
assert(fwContains || bwContains);
}
#endif
ASSERT_ONLY(tmp_rdseq_.reverse());
if(lim > 0) {
const GFM<index_t> *gfm = &gfmFw;
assert(gfm != NULL);
// Extend left using forward index
const BTDnaString& seq = fw ? rd.patFw : rd.patRc;
// See what we get by extending
index_t 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<index_t> tloc, bloc;
INIT_LOCS(top, bot, tloc, bloc, *gfm);
for(index_t ii = 0; ii < lim; ii++) {
// Starting to left of seed (<off) and moving left
index_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;
gfm->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 = gfm->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, *gfm);
}
}
// 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 && gfmBw != NULL) {
const GFM<index_t> *gfm = gfmBw;
assert(gfm != NULL);
// Extend right using backward index
const BTDnaString& seq = fw ? rd.patFw : rd.patRc;
// See what we get by extending
index_t 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, *gfm);
for(index_t ii = 0; ii < lim; ii++) {
// Starting to right of seed (<off) and moving right
index_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;
gfm->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 = gfm->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, *gfm);
}
}
#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 = gfmFw.contains(tmp_rdseq_);
tmp_rdseq_.reverse();
bool bwContains = gfmBw != NULL && gfmBw->contains(tmp_rdseq_);
tmp_rdseq_.reverse();
assert(fwContains || bwContains);