-
Notifications
You must be signed in to change notification settings - Fork 73
/
aligner_sw.cpp
2990 lines (2916 loc) · 96.6 KB
/
aligner_sw.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/>.
*/
#include <limits>
// -- BTL remove --
//#include <stdlib.h>
//#include <sys/time.h>
// -- --
#include "aligner_sw.h"
#include "aligner_result.h"
#include "search_globals.h"
#include "scoring.h"
#include "mask.h"
/**
* Initialize with a new read.
*/
void SwAligner::initRead(
const BTDnaString& rdfw, // forward read sequence
const BTDnaString& rdrc, // revcomp read sequence
const BTString& qufw, // forward read qualities
const BTString& qurc, // reverse read qualities
size_t rdi, // offset of first read char to align
size_t rdf, // offset of last read char to align
const Scoring& sc) // scoring scheme
{
assert_gt(rdf, rdi);
int nceil = sc.nCeil.f<int>((double)rdfw.length());
rdfw_ = &rdfw; // read sequence
rdrc_ = &rdrc; // read sequence
qufw_ = &qufw; // read qualities
qurc_ = &qurc; // read qualities
rdi_ = rdi; // offset of first read char to align
rdf_ = rdf; // offset of last read char to align
sc_ = ≻ // scoring scheme
nceil_ = nceil; // max # Ns allowed in ref portion of aln
readSse16_ = false; // true -> sse16 from now on for this read
initedRead_ = true;
#ifndef NO_SSE
sseU8fwBuilt_ = false; // built fw query profile, 8-bit score
sseU8rcBuilt_ = false; // built rc query profile, 8-bit score
sseI16fwBuilt_ = false; // built fw query profile, 16-bit score
sseI16rcBuilt_ = false; // built rc query profile, 16-bit score
#endif
}
/**
* Initialize with a new alignment problem.
*/
void SwAligner::initRef(
bool fw, // whether to forward or revcomp read is aligning
TRefId refidx, // id of reference aligned against
const DPRect& rect, // DP rectangle
char *rf, // reference sequence
size_t rfi, // offset of first reference char to align to
size_t rff, // offset of last reference char to align to
TRefOff reflen, // length of reference sequence
const Scoring& sc, // scoring scheme
TAlScore minsc, // minimum score
bool enable8, // use 8-bit SSE if possible?
size_t cminlen, // minimum length for using checkpointing scheme
size_t cpow2, // interval b/t checkpointed diags; 1 << this
bool doTri, // triangular mini-fills?
bool extend) // is this a seed extension?
{
size_t readGaps = sc.maxReadGaps(minsc, rdfw_->length());
size_t refGaps = sc.maxRefGaps(minsc, rdfw_->length());
assert_geq(readGaps, 0);
assert_geq(refGaps, 0);
assert_gt(rff, rfi);
rdgap_ = readGaps; // max # gaps in read
rfgap_ = refGaps; // max # gaps in reference
state_ = STATE_INITED;
fw_ = fw; // orientation
rd_ = fw ? rdfw_ : rdrc_; // read sequence
qu_ = fw ? qufw_ : qurc_; // quality sequence
refidx_ = refidx; // id of reference aligned against
rf_ = rf; // reference sequence
rfi_ = rfi; // offset of first reference char to align to
rff_ = rff; // offset of last reference char to align to
reflen_ = reflen; // length of entire reference sequence
rect_ = ▭ // DP rectangle
minsc_ = minsc; // minimum score
cural_ = 0; // idx of next alignment to give out
initedRef_ = true; // indicate we've initialized the ref portion
enable8_ = enable8; // use 8-bit SSE if possible?
extend_ = extend; // true iff this is a seed extension
cperMinlen_ = cminlen; // reads shorter than this won't use checkpointer
cperPerPow2_ = cpow2; // interval b/t checkpointed diags; 1 << this
cperEf_ = true; // whether to checkpoint H, E, and F
cperTri_ = doTri; // triangular mini-fills?
bter_.initRef(
fw_ ? rdfw_->buf() : // in: read sequence
rdrc_->buf(),
fw_ ? qufw_->buf() : // in: quality sequence
qurc_->buf(),
// daehwan
// rd_->length(), // in: read sequence length
rdf_ - rdi_,
rf_ + rfi_, // in: reference sequence
rff_ - rfi_, // in: in-rectangle reference sequence length
reflen, // in: total reference sequence length
refidx_, // in: reference id
rfi_, // in: reference offset
fw_, // in: orientation
rect_, // in: DP rectangle
&cper_, // in: checkpointer
*sc_, // in: scoring scheme
nceil_); // in: N ceiling
}
/**
* Given a read, an alignment orientation, a range of characters in a referece
* sequence, and a bit-encoded version of the reference, set up and execute the
* corresponding dynamic programming problem.
*
* The caller has already narrowed down the relevant portion of the reference
* using, e.g., the location of a seed hit, or the range of possible fragment
* lengths if we're searching for the opposite mate in a pair.
*/
void SwAligner::initRef(
bool fw, // whether to forward or revcomp read is aligning
TRefId refidx, // reference aligned against
const DPRect& rect, // DP rectangle
const BitPairReference& refs, // Reference strings
TRefOff reflen, // length of reference sequence
const Scoring& sc, // scoring scheme
TAlScore minsc, // minimum score
bool enable8, // use 8-bit SSE if possible?
size_t cminlen, // minimum length for using checkpointing scheme
size_t cpow2, // interval b/t checkpointed diags; 1 << this
bool doTri, // triangular mini-fills?
bool extend, // true iff this is a seed extension
size_t upto, // count the number of Ns up to this offset
size_t& nsUpto) // output: the number of Ns up to 'upto'
{
TRefOff rfi = rect.refl;
TRefOff rff = rect.refr + 1;
assert_gt(rff, rfi);
// Capture an extra reference character outside the rectangle so that we
// can check matches in the next column over to the right
rff++;
// rflen = full length of the reference substring to consider, including
// overhang off the boundaries of the reference sequence
const size_t rflen = (size_t)(rff - rfi);
// Figure the number of Ns we're going to add to either side
size_t leftNs =
(rfi >= 0 ? 0 : (size_t)std::abs(static_cast<long>(rfi)));
leftNs = min(leftNs, rflen);
size_t rightNs =
(rff <= (TRefOff)reflen ? 0 : (size_t)std::abs(static_cast<long>(rff - reflen)));
rightNs = min(rightNs, rflen);
// rflenInner = length of just the portion that doesn't overhang ref ends
assert_geq(rflen, leftNs + rightNs);
const size_t rflenInner = rflen - (leftNs + rightNs);
#ifndef NDEBUG
bool haveRfbuf2 = false;
EList<char> rfbuf2(rflen);
// This is really slow, so only do it some of the time
if((rand() % 10) == 0) {
TRefOff rfii = rfi;
for(size_t i = 0; i < rflen; i++) {
if(rfii < 0 || (TRefOff)rfii >= reflen) {
rfbuf2.push_back(4);
} else {
rfbuf2.push_back(refs.getBase(refidx, (uint32_t)rfii));
}
rfii++;
}
haveRfbuf2 = true;
}
#endif
// rfbuf_ = uint32_t list large enough to accommodate both the reference
// sequence and any Ns we might add to either side.
rfwbuf_.resize((rflen + 16) / 4);
int offset = refs.getStretch(
rfwbuf_.ptr(), // buffer to store words in
refidx, // which reference
(rfi < 0) ? 0 : (size_t)rfi, // starting offset (can't be < 0)
rflenInner // length to grab (exclude overhang)
ASSERT_ONLY(, tmp_destU32_));// for BitPairReference::getStretch()
assert_leq(offset, 16);
rf_ = (char*)rfwbuf_.ptr() + offset;
// Shift ref chars away from 0 so we can stick Ns at the beginning
if(leftNs > 0) {
// Slide everyone down
for(size_t i = rflenInner; i > 0; i--) {
rf_[i+leftNs-1] = rf_[i-1];
}
// Add Ns
for(size_t i = 0; i < leftNs; i++) {
rf_[i] = 4;
}
}
if(rightNs > 0) {
// Add Ns to the end
for(size_t i = 0; i < rightNs; i++) {
rf_[i + leftNs + rflenInner] = 4;
}
}
#ifndef NDEBUG
// Sanity check reference characters
for(size_t i = 0; i < rflen; i++) {
assert(!haveRfbuf2 || rf_[i] == rfbuf2[i]);
assert_range(0, 4, (int)rf_[i]);
}
#endif
// Count Ns and convert reference characters into A/C/G/T masks. Ambiguous
// nucleotides (IUPAC codes) have more than one mask bit set. If a
// reference scanner was provided, use it to opportunistically resolve seed
// hits.
nsUpto = 0;
for(size_t i = 0; i < rflen; i++) {
// rf_[i] gets mask version of refence char, with N=16
if(i < upto && rf_[i] > 3) {
nsUpto++;
}
rf_[i] = (1 << rf_[i]);
}
// Correct for having captured an extra reference character
rff--;
initRef(
fw, // whether to forward or revcomp read is aligning
refidx, // id of reference aligned against
rect, // DP rectangle
rf_, // reference sequence, wrapped up in BTString object
0, // use the whole thing
(size_t)(rff - rfi), // ditto
reflen, // reference length
sc, // scoring scheme
minsc, // minimum score
enable8, // use 8-bit SSE if possible?
cminlen, // minimum length for using checkpointing scheme
cpow2, // interval b/t checkpointed diags; 1 << this
doTri, // triangular mini-fills?
extend); // true iff this is a seed extension
}
/**
* Align read 'rd' to reference using read & reference information given
* last time init() was called.
*/
bool SwAligner::align(
RandomSource& rnd, // source of pseudo-randoms
TAlScore& best) // best alignment score observed in DP matrix
{
assert(initedRef() && initedRead());
assert_eq(STATE_INITED, state_);
state_ = STATE_ALIGNED;
// Reset solutions lists
btncand_.clear();
btncanddone_.clear();
btncanddoneSucc_ = btncanddoneFail_ = 0;
best = std::numeric_limits<TAlScore>::min();
sse8succ_ = sse16succ_ = false;
int flag = 0;
size_t rdlen = rdf_ - rdi_;
bool checkpointed = rdlen >= cperMinlen_;
bool gathered = false; // Did gathering happen along with alignment?
if(sc_->monotone) {
// End-to-end
if(enable8_ && !readSse16_ && minsc_ >= -254) {
// 8-bit end-to-end
if(checkpointed) {
best = alignGatherEE8(flag, false);
if(flag == 0) {
gathered = true;
}
} else {
best = alignNucleotidesEnd2EndSseU8(flag, false);
#ifndef NDEBUG
int flagtmp = 0;
TAlScore besttmp = alignGatherEE8(flagtmp, true); // debug
assert_eq(flagtmp, flag);
assert_eq(besttmp, best);
#endif
}
sse8succ_ = (flag == 0);
#ifndef NDEBUG
{
int flag2 = 0;
TAlScore best2 = alignNucleotidesEnd2EndSseI16(flag2, true);
{
int flagtmp = 0;
TAlScore besttmp = alignGatherEE16(flagtmp, true);
assert_eq(flagtmp, flag2);
assert(flag2 != 0 || best2 == besttmp);
}
assert(flag < 0 || best == best2);
sse16succ_ = (flag2 == 0);
}
#endif /*ndef NDEBUG*/
} else {
// 16-bit end-to-end
if(checkpointed) {
best = alignGatherEE16(flag, false);
if(flag == 0) {
gathered = true;
}
} else {
best = alignNucleotidesEnd2EndSseI16(flag, false);
#ifndef NDEBUG
int flagtmp = 0;
TAlScore besttmp = alignGatherEE16(flagtmp, true);
assert_eq(flagtmp, flag);
assert_eq(besttmp, best);
#endif
}
sse16succ_ = (flag == 0);
}
} else {
// Local
flag = -2;
if(enable8_ && !readSse16_) {
// 8-bit local
if(checkpointed) {
best = alignGatherLoc8(flag, false);
if(flag == 0) {
gathered = true;
}
} else {
best = alignNucleotidesLocalSseU8(flag, false);
#ifndef NDEBUG
int flagtmp = 0;
TAlScore besttmp = alignGatherLoc8(flagtmp, true);
assert_eq(flag, flagtmp);
assert_eq(best, besttmp);
#endif
}
}
if(flag == -2) {
// 16-bit local
flag = 0;
if(checkpointed) {
best = alignNucleotidesLocalSseI16(flag, false);
best = alignGatherLoc16(flag, false);
if(flag == 0) {
gathered = true;
}
} else {
best = alignNucleotidesLocalSseI16(flag, false);
#ifndef NDEBUG
int flagtmp = 0;
TAlScore besttmp = alignGatherLoc16(flagtmp, true);
assert_eq(flag, flagtmp);
assert_eq(best, besttmp);
#endif
}
sse16succ_ = (flag == 0);
} else {
sse8succ_ = (flag == 0);
#ifndef NDEBUG
int flag2 = 0;
TAlScore best2 = alignNucleotidesLocalSseI16(flag2, true);
{
int flagtmp = 0;
TAlScore besttmp = alignGatherLoc16(flagtmp, true);
assert_eq(flag2, flagtmp);
assert(flag2 != 0 || best2 == besttmp);
}
assert(flag2 < 0 || best == best2);
sse16succ_ = (flag2 == 0);
#endif /*ndef NDEBUG*/
}
}
#ifndef NDEBUG
if(!checkpointed && (rand() & 15) == 0 && sse8succ_ && sse16succ_) {
SSEData& d8 = fw_ ? sseU8fw_ : sseU8rc_;
SSEData& d16 = fw_ ? sseI16fw_ : sseI16rc_;
assert_eq(d8.mat_.nrow(), d16.mat_.nrow());
assert_eq(d8.mat_.ncol(), d16.mat_.ncol());
for(size_t i = 0; i < d8.mat_.nrow(); i++) {
for(size_t j = 0; j < colstop_; j++) {
int h8 = d8.mat_.helt(i, j);
int h16 = d16.mat_.helt(i, j);
int e8 = d8.mat_.eelt(i, j);
int e16 = d16.mat_.eelt(i, j);
int f8 = d8.mat_.felt(i, j);
int f16 = d16.mat_.felt(i, j);
TAlScore h8s =
(sc_->monotone ? (h8 - 0xff ) : h8);
TAlScore h16s =
(sc_->monotone ? (h16 - 0x7fff) : (h16 + 0x8000));
TAlScore e8s =
(sc_->monotone ? (e8 - 0xff ) : e8);
TAlScore e16s =
(sc_->monotone ? (e16 - 0x7fff) : (e16 + 0x8000));
TAlScore f8s =
(sc_->monotone ? (f8 - 0xff ) : f8);
TAlScore f16s =
(sc_->monotone ? (f16 - 0x7fff) : (f16 + 0x8000));
if(h8s < minsc_) {
h8s = minsc_ - 1;
}
if(h16s < minsc_) {
h16s = minsc_ - 1;
}
if(e8s < minsc_) {
e8s = minsc_ - 1;
}
if(e16s < minsc_) {
e16s = minsc_ - 1;
}
if(f8s < minsc_) {
f8s = minsc_ - 1;
}
if(f16s < minsc_) {
f16s = minsc_ - 1;
}
if((h8 != 0 || (int16_t)h16 != (int16_t)0x8000) && h8 > 0) {
assert_eq(h8s, h16s);
}
if((e8 != 0 || (int16_t)e16 != (int16_t)0x8000) && e8 > 0) {
assert_eq(e8s, e16s);
}
if((f8 != 0 || (int16_t)f16 != (int16_t)0x8000) && f8 > 0) {
assert_eq(f8s, f16s);
}
}
}
}
#endif
assert(repOk());
cural_ = 0;
if(best == MIN_I64 || best < minsc_) {
return false;
}
if(!gathered) {
// Look for solutions using SSE matrix
assert(sse8succ_ || sse16succ_);
if(sc_->monotone) {
if(sse8succ_) {
gatherCellsNucleotidesEnd2EndSseU8(best);
#ifndef NDEBUG
if(sse16succ_) {
cand_tmp_ = btncand_;
gatherCellsNucleotidesEnd2EndSseI16(best);
cand_tmp_.sort();
btncand_.sort();
assert(cand_tmp_ == btncand_);
}
#endif /*ndef NDEBUG*/
} else {
gatherCellsNucleotidesEnd2EndSseI16(best);
}
} else {
if(sse8succ_) {
gatherCellsNucleotidesLocalSseU8(best);
#ifndef NDEBUG
if(sse16succ_) {
cand_tmp_ = btncand_;
gatherCellsNucleotidesLocalSseI16(best);
cand_tmp_.sort();
btncand_.sort();
assert(cand_tmp_ == btncand_);
}
#endif /*ndef NDEBUG*/
} else {
gatherCellsNucleotidesLocalSseI16(best);
}
}
}
if(!btncand_.empty()) {
btncand_.sort();
}
return !btncand_.empty();
}
/**
* Populate the given SwResult with information about the "next best"
* alignment if there is one. If there isn't one, false is returned. Note
* that false might be returned even though a call to done() would have
* returned false.
*/
bool SwAligner::nextAlignment(
SwResult& res,
TAlScore minsc,
RandomSource& rnd)
{
assert(initedRead() && initedRef());
assert_eq(STATE_ALIGNED, state_);
assert(repOk());
if(done()) {
res.reset();
return false;
}
assert(!done());
size_t off = 0, nbts = 0;
assert_lt(cural_, btncand_.size());
assert(res.repOk());
// For each candidate cell that we should try to backtrack from...
const size_t candsz = btncand_.size();
size_t SQ = dpRows() >> 4;
if(SQ == 0) SQ = 1;
size_t rdlen = rdf_ - rdi_;
bool checkpointed = rdlen >= cperMinlen_;
while(cural_ < candsz) {
// Doing 'continue' anywhere in here simply causes us to move on to the
// next candidate
if(btncand_[cural_].score < minsc) {
btncand_[cural_].fate = BT_CAND_FATE_FILT_SCORE;
nbtfiltsc_++; cural_++; continue;
}
nbts = 0;
assert(sse8succ_ || sse16succ_);
size_t row = btncand_[cural_].row;
size_t col = btncand_[cural_].col;
assert_lt(row, dpRows());
assert_lt((TRefOff)col, rff_-rfi_);
if(sse16succ_) {
SSEData& d = fw_ ? sseI16fw_ : sseI16rc_;
if(!checkpointed && d.mat_.reset_[row] && d.mat_.reportedThrough(row, col)) {
// Skipping this candidate because a previous candidate already
// moved through this cell
btncand_[cural_].fate = BT_CAND_FATE_FILT_START;
//cerr << " skipped becuase starting cell was covered" << endl;
nbtfiltst_++; cural_++; continue;
}
} else if(sse8succ_) {
SSEData& d = fw_ ? sseU8fw_ : sseU8rc_;
if(!checkpointed && d.mat_.reset_[row] && d.mat_.reportedThrough(row, col)) {
// Skipping this candidate because a previous candidate already
// moved through this cell
btncand_[cural_].fate = BT_CAND_FATE_FILT_START;
//cerr << " skipped becuase starting cell was covered" << endl;
nbtfiltst_++; cural_++; continue;
}
}
if(sc_->monotone) {
bool ret = false;
if(sse8succ_) {
uint32_t reseed = rnd.nextU32() + 1;
rnd.init(reseed);
res.reset();
if(checkpointed) {
size_t maxiter = MAX_SIZE_T;
size_t niter = 0;
ret = backtrace(
btncand_[cural_].score, // in: expected score
true, // in: use mini-fill?
true, // in: use checkpoints?
res, // out: store results (edits and scores) here
off, // out: store diagonal projection of origin
row, // start in this rectangle row
col, // start in this rectangle column
maxiter, // max # extensions to try
niter, // # extensions tried
rnd); // random gen, to choose among equal paths
} else {
ret = backtraceNucleotidesEnd2EndSseU8(
btncand_[cural_].score, // in: expected score
res, // out: store results (edits and scores) here
off, // out: store diagonal projection of origin
nbts, // out: # backtracks
row, // start in this rectangle row
col, // start in this rectangle column
rnd); // random gen, to choose among equal paths
}
#ifndef NDEBUG
// if(...) statement here should check not whether the primary
// alignment was checkpointed, but whether a checkpointed
// alignment was done at all.
if(!checkpointed) {
SwResult res2;
size_t maxiter2 = MAX_SIZE_T;
size_t niter2 = 0;
bool ret2 = backtrace(
btncand_[cural_].score, // in: expected score
true, // in: use mini-fill?
true, // in: use checkpoints?
res2, // out: store results (edits and scores) here
off, // out: store diagonal projection of origin
row, // start in this rectangle row
col, // start in this rectangle column
maxiter2, // max # extensions to try
niter2, // # extensions tried
rnd); // random gen, to choose among equal paths
// After the first alignment, there's no guarantee we'll
// get the same answer from both backtrackers because of
// differences in how they handle marking cells as
// reported-through.
assert(cural_ > 0 || !ret || ret == ret2);
}
if(sse16succ_ && !checkpointed) {
SwResult res2;
size_t off2, nbts2 = 0;
rnd.init(reseed);
bool ret2 = backtraceNucleotidesEnd2EndSseI16(
btncand_[cural_].score, // in: expected score
res2, // out: store results (edits and scores) here
off2, // out: store diagonal projection of origin
nbts2, // out: # backtracks
row, // start in this rectangle row
col, // start in this rectangle column
rnd); // random gen, to choose among equal paths
assert_eq(ret, ret2);
assert_eq(nbts, nbts2);
assert(!ret || res2.alres.score() == res.alres.score());
#if 0
if(!checkpointed && (rand() & 15) == 0) {
// Check that same cells are reported through
SSEData& d8 = fw_ ? sseU8fw_ : sseU8rc_;
SSEData& d16 = fw_ ? sseI16fw_ : sseI16rc_;
for(size_t i = d8.mat_.nrow(); i > 0; i--) {
for(size_t j = 0; j < d8.mat_.ncol(); j++) {
assert_eq(d8.mat_.reportedThrough(i-1, j),
d16.mat_.reportedThrough(i-1, j));
}
}
}
#endif
}
#endif
rnd.init(reseed+1); // debug/release pseudo-randoms in lock step
} else if(sse16succ_) {
uint32_t reseed = rnd.nextU32() + 1;
res.reset();
if(checkpointed) {
size_t maxiter = MAX_SIZE_T;
size_t niter = 0;
ret = backtrace(
btncand_[cural_].score, // in: expected score
true, // in: use mini-fill?
true, // in: use checkpoints?
res, // out: store results (edits and scores) here
off, // out: store diagonal projection of origin
row, // start in this rectangle row
col, // start in this rectangle column
maxiter, // max # extensions to try
niter, // # extensions tried
rnd); // random gen, to choose among equal paths
} else {
ret = backtraceNucleotidesEnd2EndSseI16(
btncand_[cural_].score, // in: expected score
res, // out: store results (edits and scores) here
off, // out: store diagonal projection of origin
nbts, // out: # backtracks
row, // start in this rectangle row
col, // start in this rectangle column
rnd); // random gen, to choose among equal paths
}
#ifndef NDEBUG
// if(...) statement here should check not whether the primary
// alignment was checkpointed, but whether a checkpointed
// alignment was done at all.
if(!checkpointed) {
SwResult res2;
size_t maxiter2 = MAX_SIZE_T;
size_t niter2 = 0;
bool ret2 = backtrace(
btncand_[cural_].score, // in: expected score
true, // in: use mini-fill?
true, // in: use checkpoints?
res2, // out: store results (edits and scores) here
off, // out: store diagonal projection of origin
row, // start in this rectangle row
col, // start in this rectangle column
maxiter2, // max # extensions to try
niter2, // # extensions tried
rnd); // random gen, to choose among equal paths
// After the first alignment, there's no guarantee we'll
// get the same answer from both backtrackers because of
// differences in how they handle marking cells as
// reported-through.
assert(cural_ > 0 || !ret || ret == ret2);
}
#endif
rnd.init(reseed); // debug/release pseudo-randoms in lock step
}
if(ret) {
btncand_[cural_].fate = BT_CAND_FATE_SUCCEEDED;
break;
} else {
btncand_[cural_].fate = BT_CAND_FATE_FAILED;
}
} else {
// Local alignment
// Check if this solution is "dominated" by a prior one.
// Domination is a heuristic designed to eliminate the vast
// majority of valid-but-redundant candidates lying in the
// "penumbra" of a high-scoring alignment.
bool dom = false;
{
size_t donesz = btncanddone_.size();
const size_t col = btncand_[cural_].col;
const size_t row = btncand_[cural_].row;
for(size_t i = 0; i < donesz; i++) {
assert_gt(btncanddone_[i].fate, 0);
size_t colhi = col, rowhi = row;
size_t rowlo = btncanddone_[i].row;
size_t collo = btncanddone_[i].col;
if(colhi < collo) swap(colhi, collo);
if(rowhi < rowlo) swap(rowhi, rowlo);
if(colhi - collo <= SQ && rowhi - rowlo <= SQ) {
// Skipping this candidate because it's "dominated" by
// a previous candidate
dom = true;
break;
}
}
}
if(dom) {
btncand_[cural_].fate = BT_CAND_FATE_FILT_DOMINATED;
nbtfiltdo_++;
cural_++;
continue;
}
bool ret = false;
if(sse8succ_) {
uint32_t reseed = rnd.nextU32() + 1;
res.reset();
rnd.init(reseed);
if(checkpointed) {
size_t maxiter = MAX_SIZE_T;
size_t niter = 0;
ret = backtrace(
btncand_[cural_].score, // in: expected score
true, // in: use mini-fill?
true, // in: use checkpoints?
res, // out: store results (edits and scores) here
off, // out: store diagonal projection of origin
row, // start in this rectangle row
col, // start in this rectangle column
maxiter, // max # extensions to try
niter, // # extensions tried
rnd); // random gen, to choose among equal paths
} else {
ret = backtraceNucleotidesLocalSseU8(
btncand_[cural_].score, // in: expected score
res, // out: store results (edits and scores) here
off, // out: store diagonal projection of origin
nbts, // out: # backtracks
row, // start in this rectangle row
col, // start in this rectangle column
rnd); // random gen, to choose among equal paths
}
#ifndef NDEBUG
// if(...) statement here should check not whether the primary
// alignment was checkpointed, but whether a checkpointed
// alignment was done at all.
if(!checkpointed) {
SwResult res2;
size_t maxiter2 = MAX_SIZE_T;
size_t niter2 = 0;
bool ret2 = backtrace(
btncand_[cural_].score, // in: expected score
true, // in: use mini-fill?
true, // in: use checkpoints?
res2, // out: store results (edits and scores) here
off, // out: store diagonal projection of origin
row, // start in this rectangle row
col, // start in this rectangle column
maxiter2, // max # extensions to try
niter2, // # extensions tried
rnd); // random gen, to choose among equal paths
// After the first alignment, there's no guarantee we'll
// get the same answer from both backtrackers because of
// differences in how they handle marking cells as
// reported-through.
assert(cural_ > 0 || !ret || ret == ret2);
}
if(!checkpointed && sse16succ_) {
SwResult res2;
size_t off2, nbts2 = 0;
rnd.init(reseed); // same b/t backtrace calls
bool ret2 = backtraceNucleotidesLocalSseI16(
btncand_[cural_].score, // in: expected score
res2, // out: store results (edits and scores) here
off2, // out: store diagonal projection of origin
nbts2, // out: # backtracks
row, // start in this rectangle row
col, // start in this rectangle column
rnd); // random gen, to choose among equal paths
assert_eq(ret, ret2);
assert_eq(nbts, nbts2);
assert(!ret || res2.alres.score() == res.alres.score());
#if 0
if(!checkpointed && (rand() & 15) == 0) {
// Check that same cells are reported through
SSEData& d8 = fw_ ? sseU8fw_ : sseU8rc_;
SSEData& d16 = fw_ ? sseI16fw_ : sseI16rc_;
for(size_t i = d8.mat_.nrow(); i > 0; i--) {
for(size_t j = 0; j < d8.mat_.ncol(); j++) {
assert_eq(d8.mat_.reportedThrough(i-1, j),
d16.mat_.reportedThrough(i-1, j));
}
}
}
#endif
}
#endif
rnd.init(reseed+1); // debug/release pseudo-randoms in lock step
} else if(sse16succ_) {
uint32_t reseed = rnd.nextU32() + 1;
res.reset();
if(checkpointed) {
size_t maxiter = MAX_SIZE_T;
size_t niter = 0;
ret = backtrace(
btncand_[cural_].score, // in: expected score
true, // in: use mini-fill?
true, // in: use checkpoints?
res, // out: store results (edits and scores) here
off, // out: store diagonal projection of origin
row, // start in this rectangle row
col, // start in this rectangle column
maxiter, // max # extensions to try
niter, // # extensions tried
rnd); // random gen, to choose among equal paths
} else {
ret = backtraceNucleotidesLocalSseI16(
btncand_[cural_].score, // in: expected score
res, // out: store results (edits and scores) here
off, // out: store diagonal projection of origin
nbts, // out: # backtracks
row, // start in this rectangle row
col, // start in this rectangle column
rnd); // random gen, to choose among equal paths
}
#ifndef NDEBUG
// if(...) statement here should check not whether the primary
// alignment was checkpointed, but whether a checkpointed
// alignment was done at all.
if(!checkpointed) {
SwResult res2;
size_t maxiter2 = MAX_SIZE_T;
size_t niter2 = 0;
bool ret2 = backtrace(
btncand_[cural_].score, // in: expected score
true, // in: use mini-fill?
true, // in: use checkpoints?
res2, // out: store results (edits and scores) here
off, // out: store diagonal projection of origin
row, // start in this rectangle row
col, // start in this rectangle column
maxiter2, // max # extensions to try
niter2, // # extensions tried
rnd); // random gen, to choose among equal paths
// After the first alignment, there's no guarantee we'll
// get the same answer from both backtrackers because of
// differences in how they handle marking cells as
// reported-through.
assert(cural_ > 0 || !ret || ret == ret2);
}
#endif
rnd.init(reseed); // same b/t backtrace calls
}
if(ret) {
btncand_[cural_].fate = BT_CAND_FATE_SUCCEEDED;
btncanddone_.push_back(btncand_[cural_]);
btncanddoneSucc_++;
assert(res.repOk());
break;
} else {
btncand_[cural_].fate = BT_CAND_FATE_FAILED;
btncanddone_.push_back(btncand_[cural_]);
btncanddoneFail_++;
}
}
cural_++;
} // while(cural_ < btncand_.size())
if(cural_ == btncand_.size()) {
assert(res.repOk());
return false;
}
// assert(!res.alres.empty());
assert(res.repOk());
if(!fw_) {
// All edits are currently w/r/t upstream end; if read aligned
// to Crick strand, we need to invert them so that they're
// w/r/t the read's 5' end instead.
// res.alres.invertEdits();
}
cural_++;
assert(res.repOk());
return true;
}
#ifdef MAIN_ALIGNER_SW
#include <sstream>
#include <utility>
#include <getopt.h>
#include "scoring.h"
#include "aligner_seed_policy.h"
int gGapBarrier;
int gSnpPhred;
static int bonusMatchType; // how to reward matches
static int bonusMatch; // constant if match bonus is a constant
static int penMmcType; // how to penalize mismatches
static int penMmc; // constant if mm pelanty is a constant
static int penNType; // how to penalize Ns in the read
static int penN; // constant if N pelanty is a constant
static bool nPairCat; // true -> concatenate mates before N filter
static int penRdExConst; // constant coeff for cost of gap in read
static int penRfExConst; // constant coeff for cost of gap in ref
static int penRdExLinear; // linear coeff for cost of gap in read
static int penRfExLinear; // linear coeff for cost of gap in ref
static float costMinConst; // constant coeff for min score w/r/t read len
static float costMinLinear; // linear coeff for min score w/r/t read len
static float costFloorConst; // constant coeff for score floor w/r/t read len
static float costFloorLinear;// linear coeff for score floor w/r/t read len
static float nCeilConst; // constant coeff for N ceiling w/r/t read len
static float nCeilLinear; // linear coeff for N ceiling w/r/t read len
static bool nCatPair; // concat mates before applying N filter?
static int multiseedMms; // mismatches permitted in a multiseed seed
static int multiseedLen; // length of multiseed seeds
static int multiseedIvalType;
static float multiseedIvalA;
static float multiseedIvalB;
static float posmin;
static float posfrac;
static float rowmult;
enum {
ARG_TESTS = 256
};
static const char *short_opts = "s:m:r:d:i:";
static struct option long_opts[] = {
{(char*)"snppen", required_argument, 0, 's'},
{(char*)"misspen", required_argument, 0, 'm'},
{(char*)"seed", required_argument, 0, 'r'},
{(char*)"align-policy", no_argument, 0, 'A'},
{(char*)"test", no_argument, 0, ARG_TESTS},
};
static void printUsage(ostream& os) {
os << "Usage: aligner_sw <read-seq> <ref-nuc-seq> [options]*" << endl;
os << "Options:" << endl;
os << " -s/--snppen <int> penalty incurred by SNP; used for decoding"
<< endl;
os << " -m/--misspen <int> quality to use for read chars" << endl;
os << " -r/-seed <int> seed for pseudo-random generator" << endl;
}
/**
* Parse a T from a string 's'
*/
template<typename T>
T parse(const char *s) {
T tmp;
stringstream ss(s);
ss >> tmp;
return tmp;
}
static EList<bool> stbuf, enbuf;
static BTDnaString btread;
static BTString btqual;
static BTString btref;
static BTString btref2;
static BTDnaString readrc;
static BTString qualrc;
/**
* Helper function for running a case consisting of a read (sequence
* and quality), a reference string, and an offset that anchors the 0th
* character of the read to a reference position.
*/
static void doTestCase(
SwAligner& al,
const BTDnaString& read,
const BTString& qual,
const BTString& refin,
TRefOff off,
EList<bool> *en,
const Scoring& sc,
TAlScore minsc,
SwResult& res,
bool nsInclusive,
bool filterns,
uint32_t seed)
{
RandomSource rnd(seed);
btref2 = refin;
assert_eq(read.length(), qual.length());
size_t nrow = read.length();
TRefOff rfi, rff;
// Calculate the largest possible number of read and reference gaps given
// 'minsc' and 'pens'
size_t maxgaps;