-
Notifications
You must be signed in to change notification settings - Fork 0
/
wfa_lm.hpp
3161 lines (2757 loc) · 132 KB
/
wfa_lm.hpp
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
//
// wfa_lm.hpp
//
// MIT License
//
// Copyright (c) 2022 Jordan Eizenga
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#ifndef wfa_lm_hpp_included
#define wfa_lm_hpp_included
#include <cstdint>
#include <vector>
#include <string>
#include <utility>
#include <algorithm>
#include <iostream>
#include <deque>
#include <sstream>
#include <limits>
#include <tuple>
#include <array>
#if defined(__SSE4_1__) || defined(__SSE4_2__)
#include <x86intrin.h>
#else
#define SIMDE_ENABLE_NATIVE_ALIASES
#include "simde/x86/sse4.1.h"
#endif
namespace wfalm {
/*
* Operation in a CIGAR string (as defined in SAM format specification)
*/
struct CIGAROp {
CIGAROp(char op, uint32_t len) : op(op), len(len) {}
CIGAROp() = default;
char op;
uint32_t len;
};
template<int NumPW> class WFAligner; // forward declaration
/*
* A convenience specialization that uses a linear gap penalty.
*/
typedef WFAligner<0> LinearWFAligner;
/// Construct with WFA-style scoring parameters
inline LinearWFAligner make_linear_wfaligner(uint32_t mismatch, uint32_t gap);
/// Construct with Smith-Waterman-Gotoh-style scoring parameters
inline LinearWFAligner make_linear_wfaligner(uint32_t match, uint32_t mismatch, uint32_t gap);
/*
* A convenience specialization that uses an affine gap penalty.
*/
typedef WFAligner<1> AffineWFAligner;
/// Construct with WFA-style scoring parameters
inline AffineWFAligner make_affine_wfaligner(uint32_t mismatch, uint32_t gap_extend, uint32_t gap_open);
/// Construct with Smith-Waterman-Gotoh-style scoring parameters
inline AffineWFAligner make_affine_wfaligner(uint32_t match, uint32_t mismatch, uint32_t gap_extend, uint32_t gap_open);
/*
* A convenience specialization that uses a convex gap penalty.
*/
typedef WFAligner<2> ConvexWFAligner;
/// Construct with WFA-style scoring parameters
inline ConvexWFAligner make_convex_wfaligner(uint32_t mismatch, uint32_t gap_extend_1, uint32_t gap_open_1,
uint32_t gap_extend_2, uint32_t gap_open_2);
/// Construct with Smith-Waterman-Gotoh-style scoring parameters
inline ConvexWFAligner make_convex_wfaligner(uint32_t match, uint32_t mismatch,
uint32_t gap_extend_1, uint32_t gap_open_1,
uint32_t gap_extend_2, uint32_t gap_open_2);
/*
* Class that performs WFA with the standard, low-memory, or recusive variants. The aligner objects are
* relatively lightweight and can be constructed for single-use with limited overhead. They are also
* threadsafe, as long as the configurable parameters are not being altered.
* The template integer controls how many piecewise-affine segments there are in the gap penalty. As a
* special case, a template parameter of 0 performs linear gap alignment.
*/
template<int NumPW>
class WFAligner {
public:
/// Initialize with WFA-style score parameters. On opening an insertion or
/// deletion, *both* the gap open and gap extend penalties are applied.
/// Scores returned by alignment methods will also be WFA-style.
/// One gap extend and gap open penalty are required for each of the piecewise
/// affine segments. If the template parameter is set to 0, then one gap extend
/// is still required, ang the aligner then performs linear gap alignment.
WFAligner(uint32_t mismatch,
std::array<uint32_t, std::max(1, NumPW)> gap_extend,
std::array<uint32_t, NumPW> gap_open);
/// Initialize with Smith-Waterman-Gotoh-style score parameters. On opening an
/// insertion or deletion, *both* the gap open and gap extend penalties are applied.
/// Scores returned by alignment methods will also be Smith-Waterman-Gotoh-style.
/// One gap extend and gap open penalty are required for each of the piecewise
/// affine segments. If the template parameter is set to 0, then one gap extend
/// is still required, ang the aligner then performs linear gap alignment.
WFAligner(uint32_t match, uint32_t mismatch,
std::array<uint32_t, std::max(1, NumPW)> gap_extend,
std::array<uint32_t, NumPW> gap_open);
/// Default constructor
WFAligner();
/*****************************
* Configurable parameters *
*****************************/
/// If set to a number >= 0, prunes diagonals that fall this many anti-diagonals
/// behind the furthest-reaching diagonal. This can lead to suboptimal alignments,
/// but it also can increase speed and reduce memory use. If set to a number < 0,
/// no pruning is performed.
int32_t lagging_diagonal_prune = -1;
/***********************
* Alignment methods *
***********************/
/// Globally align two sequences using the fastest algorithm that will remain
/// constrained to a given maximum memory.
///
/// Args:
/// seq1 First sequence to be aligned (need not be null-terminated)
/// len1 Length of first sequence to be aligned
/// seq2 Second sequence to be aligned (need not be null-terminated)
/// len2 Length of second sequence to be aligned
/// max_mem The target maximum memory use in bytes
///
/// Return value:
/// Pair consisting of CIGAR string for alignment and the alignment score.
inline std::pair<std::vector<CIGAROp>, int32_t>
wavefront_align_adaptive(const char* seq1, size_t len1,
const char* seq2, size_t len2,
uint64_t max_mem) const;
/// Globally align two sequences in O(s log s) memory and O(sN log s) time using the recursive WFA algorithm.
///
/// Args:
/// seq1 First sequence to be aligned (need not be null-terminated)
/// len1 Length of first sequence to be aligned
/// seq2 Second sequence to be aligned (need not be null-terminated)
/// len2 Length of second sequence to be aligned
///
/// Return value:
/// Pair consisting of CIGAR string for alignment and the alignment score.
inline std::pair<std::vector<CIGAROp>, int32_t>
wavefront_align_recursive(const char* seq1, size_t len1,
const char* seq2, size_t len2) const;
/// Globally align two sequences in O(s^3/2) memory and O(sN) time using the low-memory WFA algorithm.
///
/// Args:
/// seq1 First sequence to be aligned (need not be null-terminated)
/// len1 Length of first sequence to be aligned
/// seq2 Second sequence to be aligned (need not be null-terminated)
/// len2 Length of second sequence to be aligned
///
/// Return value:
/// Pair consisting of CIGAR string for alignment and the alignment score.
inline std::pair<std::vector<CIGAROp>, int32_t>
wavefront_align_low_mem(const char* seq1, size_t len1,
const char* seq2, size_t len2) const;
/// Globally align two sequences in O(s^2) memory and O(sN) time using the standard WFA algorithm.
///
/// Args:
/// seq1 First sequence to be aligned (need not be null-terminated)
/// len1 Length of first sequence to be aligned
/// seq2 Second sequence to be aligned (need not be null-terminated)
/// len2 Length of second sequence to be aligned
///
/// Return value:
/// Pair consisting of CIGAR string for alignment and the alignment score.
inline std::pair<std::vector<CIGAROp>, int32_t>
wavefront_align(const char* seq1, size_t len1,
const char* seq2, size_t len2) const;
/// Locally align two sequences from a seed using the adaptive WFA as an
/// alignment engine.
/// *Can only called if WFAligner was initialized with Smith-Waterman-Gotoh
/// scoring parameters in the constructor.*
///
/// Args:
/// seq1 First sequence to be aligned (need not be null-terminated)
/// len1 Length of first sequence to be aligned
/// seq2 Second sequence to be aligned (need not be null-terminated)
/// len2 Length of second sequence to be aligned
/// max_mem The target maximum memory use in bytes
/// anchor_begin_1 First index of the anchor on seq1
/// anchor_end_1 Past-the-last index of the anchor on seq1
/// anchor_begin_2 First index of the anchor on seq2
/// anchor_end_2 Past-the-last index of the anchor on seq2
/// anchor_is_match If false, the anchor sequence will be aligned, otherwise
/// it will be assumed to be a match
///
/// Return value:
/// A tuple consisting of:
/// - CIGAR string for alignment
/// - the alignment score
/// - a pair of indexes indicating the interval of aligned sequence on seq1
/// - a pair of indexes indicating the interval of aligned sequence on seq2
inline std::tuple<std::vector<CIGAROp>, int32_t, std::pair<size_t, size_t>, std::pair<size_t, size_t>>
wavefront_align_local_adaptive(const char* seq1, size_t len1,
const char* seq2, size_t len2,
uint64_t max_mem,
size_t anchor_begin_1, size_t anchor_end_1,
size_t anchor_begin_2, size_t anchor_end_2,
bool anchor_is_match = true) const;
/// Locally align two sequences from a seed using the recursive WFA as an
/// alignment engine.
/// *Can only called if WFAligner was initialized with Smith-Waterman-Gotoh
/// scoring parameters in the constructor.*
///
/// Args:
/// seq1 First sequence to be aligned (need not be null-terminated)
/// len1 Length of first sequence to be aligned
/// seq2 Second sequence to be aligned (need not be null-terminated)
/// len2 Length of second sequence to be aligned
/// anchor_begin_1 First index of the anchor on seq1
/// anchor_end_1 Past-the-last index of the anchor on seq1
/// anchor_begin_2 First index of the anchor on seq2
/// anchor_end_2 Past-the-last index of the anchor on seq2
/// anchor_is_match If false, the anchor sequence will be aligned, otherwise
/// it will be assumed to be a match
///
/// Return value:
/// A tuple consisting of:
/// - CIGAR string for alignment
/// - the alignment score
/// - a pair of indexes indicating the interval of aligned sequence on seq1
/// - a pair of indexes indicating the interval of aligned sequence on seq2
inline std::tuple<std::vector<CIGAROp>, int32_t, std::pair<size_t, size_t>, std::pair<size_t, size_t>>
wavefront_align_local_recursive(const char* seq1, size_t len1,
const char* seq2, size_t len2,
size_t anchor_begin_1, size_t anchor_end_1,
size_t anchor_begin_2, size_t anchor_end_2,
bool anchor_is_match = true) const;
/// Locally align two sequences from a seed using the low memory WFA as an
/// alignment engine.
/// *Can only called if WFAligner was initialized with Smith-Waterman-Gotoh
/// scoring parameters in the constructor.*
///
/// Args:
/// seq1 First sequence to be aligned (need not be null-terminated)
/// len1 Length of first sequence to be aligned
/// seq2 Second sequence to be aligned (need not be null-terminated)
/// len2 Length of second sequence to be aligned
/// anchor_begin_1 First index of the anchor on seq1
/// anchor_end_1 Past-the-last index of the anchor on seq1
/// anchor_begin_2 First index of the anchor on seq2
/// anchor_end_2 Past-the-last index of the anchor on seq2
/// anchor_is_match If false, the anchor sequence will be aligned, otherwise
/// it will be assumed to be a match
///
/// Return value:
/// A tuple consisting of:
/// - CIGAR string for alignment
/// - the alignment score
/// - a pair of indexes indicating the interval of aligned sequence on seq1
/// - a pair of indexes indicating the interval of aligned sequence on seq2
inline std::tuple<std::vector<CIGAROp>, int32_t, std::pair<size_t, size_t>, std::pair<size_t, size_t>>
wavefront_align_local_low_mem(const char* seq1, size_t len1,
const char* seq2, size_t len2,
size_t anchor_begin_1, size_t anchor_end_1,
size_t anchor_begin_2, size_t anchor_end_2,
bool anchor_is_match = true) const;
/// Locally align two sequences from a seed using the standard WFA as an
/// alignment engine.
/// *Can only called if WFAligner was initialized with Smith-Waterman-Gotoh
/// scoring parameters in the constructor.*
///
/// Args:
/// seq1 First sequence to be aligned (need not be null-terminated)
/// len1 Length of first sequence to be aligned
/// seq2 Second sequence to be aligned (need not be null-terminated)
/// len2 Length of second sequence to be aligned
/// anchor_begin_1 First index of the anchor on seq1
/// anchor_end_1 Past-the-last index of the anchor on seq1
/// anchor_begin_2 First index of the anchor on seq2
/// anchor_end_2 Past-the-last index of the anchor on seq2
/// anchor_is_match If false, the anchor sequence will be aligned, otherwise
/// it will be assumed to be a match
///
/// Return value:
/// A tuple consisting of:
/// - CIGAR string for alignment
/// - the alignment score
/// - a pair of indexes indicating the interval of aligned sequence on seq1
/// - a pair of indexes indicating the interval of aligned sequence on seq2
inline std::tuple<std::vector<CIGAROp>, int32_t, std::pair<size_t, size_t>, std::pair<size_t, size_t>>
wavefront_align_local(const char* seq1, size_t len1,
const char* seq2, size_t len2,
size_t anchor_begin_1, size_t anchor_end_1,
size_t anchor_begin_2, size_t anchor_end_2,
bool anchor_is_match = true) const;
/*******************************************************************
*******************************************************************
*** Only internal functions below here ***
*******************************************************************
*******************************************************************/
protected:
static const int StdMem = 0;
static const int LowMem = 1;
static const int Recursive = 2;
static const int AdaptiveMem = 3;
// forward declaration
template<typename IntType> struct Wavefront;
/*
* Allows the WF bank to be used in wf_next
*/
template<typename IntType>
struct WFBankAdapter {
WFBankAdapter(const std::vector<std::pair<int32_t, Wavefront<IntType>>>& wf_bank) : wf_bank(wf_bank) {
}
inline const Wavefront<IntType>& operator[](size_t i) const {
return wf_bank[i].second;
};
inline size_t size() const {
return wf_bank.size();
}
const std::vector<std::pair<int32_t, Wavefront<IntType>>>& wf_bank;
};
/*
* wrappers to perform WFA alignment algorithms for dependency injection
*/
template<typename MatchFunc, typename StringType>
struct StandardGlobalWFA {
StandardGlobalWFA(const WFAligner<NumPW>* aligner, uint64_t max_mem) : aligner(aligner) {}
inline std::pair<std::vector<CIGAROp>, int32_t>
operator()(const StringType& seq1, const StringType& seq2) const {
return aligner->wavefront_dispatch<false, WFAligner<NumPW>::StdMem, MatchFunc, StringType>(seq1, seq2,
std::numeric_limits<uint64_t>::max());
}
const WFAligner<NumPW>* aligner = nullptr;
};
template<typename MatchFunc, typename StringType>
struct StandardSemilocalWFA {
StandardSemilocalWFA(const WFAligner<NumPW>* aligner, uint64_t max_mem) : aligner(aligner) {}
inline std::pair<std::vector<CIGAROp>, int32_t>
operator()(const StringType& seq1, const StringType& seq2) const {
return aligner->wavefront_dispatch<true, WFAligner<NumPW>::StdMem, MatchFunc, StringType>(seq1, seq2,
std::numeric_limits<uint64_t>::max());
}
const WFAligner<NumPW>* aligner = nullptr;
};
template<typename MatchFunc, typename StringType>
struct LowMemGlobalWFA {
LowMemGlobalWFA(const WFAligner<NumPW>* aligner, uint64_t max_mem) : aligner(aligner) {}
inline std::pair<std::vector<CIGAROp>, int32_t>
operator()(const StringType& seq1, const StringType& seq2) const {
return aligner->wavefront_dispatch<false, WFAligner<NumPW>::LowMem, MatchFunc, StringType>(seq1, seq2,
std::numeric_limits<uint64_t>::max());
}
const WFAligner<NumPW>* aligner = nullptr;
};
template<typename MatchFunc, typename StringType>
struct LowMemSemilocalWFA {
LowMemSemilocalWFA(const WFAligner<NumPW>* aligner, uint64_t max_mem) : aligner(aligner) {}
inline std::pair<std::vector<CIGAROp>, int32_t>
operator()(const StringType& seq1, const StringType& seq2) const {
return aligner->wavefront_dispatch<true, WFAligner<NumPW>::LowMem, MatchFunc, StringType>(seq1, seq2,
std::numeric_limits<uint64_t>::max());
}
const WFAligner<NumPW>* aligner = nullptr;
};
template<typename MatchFunc, typename StringType>
struct RecursiveGlobalWFA {
RecursiveGlobalWFA(const WFAligner<NumPW>* aligner, uint64_t max_mem) : aligner(aligner) {}
inline std::pair<std::vector<CIGAROp>, int32_t>
operator()(const StringType& seq1, const StringType& seq2) const {
return aligner->wavefront_dispatch<false, WFAligner<NumPW>::Recursive, MatchFunc, StringType>(seq1, seq2,
std::numeric_limits<uint64_t>::max());
}
const WFAligner<NumPW>* aligner = nullptr;
};
template<typename MatchFunc, typename StringType>
struct RecursiveSemilocalWFA {
RecursiveSemilocalWFA(const WFAligner<NumPW>* aligner, uint64_t max_mem) : aligner(aligner) {}
inline std::pair<std::vector<CIGAROp>, int32_t>
operator()(const StringType& seq1, const StringType& seq2) const {
return aligner->wavefront_dispatch<true, WFAligner<NumPW>::Recursive, MatchFunc, StringType>(seq1, seq2,
std::numeric_limits<uint64_t>::max());
}
const WFAligner<NumPW>* aligner = nullptr;
};
template<typename MatchFunc, typename StringType>
struct AdaptiveGlobalWFA {
AdaptiveGlobalWFA(const WFAligner<NumPW>* aligner, uint64_t max_mem) : aligner(aligner), max_mem(max_mem) {}
inline std::pair<std::vector<CIGAROp>, int32_t>
operator()(const StringType& seq1, const StringType& seq2) const {
return aligner->wavefront_dispatch<false, WFAligner<NumPW>::AdaptiveMem, MatchFunc, StringType>(seq1, seq2,
max_mem);
}
const WFAligner<NumPW>* aligner = nullptr;
uint64_t max_mem = 0;
};
template<typename MatchFunc, typename StringType>
struct AdaptiveSemilocalWFA {
AdaptiveSemilocalWFA(const WFAligner<NumPW>* aligner, uint64_t max_mem) : aligner(aligner), max_mem(max_mem) {}
inline std::pair<std::vector<CIGAROp>, int32_t>
operator()(const StringType& seq1, const StringType& seq2) const {
return aligner->wavefront_dispatch<true, WFAligner<NumPW>::AdaptiveMem, MatchFunc, StringType>(seq1, seq2,
max_mem);
}
const WFAligner<NumPW>* aligner = nullptr;
uint64_t max_mem = 0;
};
// give the wrapper access to the dispatch function
template<class MatchFunc, class StringType> friend class StandardGlobalWFA;
template<class MatchFunc, class StringType> friend class StandardSemilocalWFA;
template<class MatchFunc, class StringType> friend class LowMemGlobalWFA;
template<class MatchFunc, class StringType> friend class LowMemSemilocalWFA;
template<class MatchFunc, class StringType> friend class RecursiveGlobalWFA;
template<class MatchFunc, class StringType> friend class RecursiveSemilocalWFA;
template<class MatchFunc, class StringType> friend class AdaptiveGlobalWFA;
template<class MatchFunc, class StringType> friend class AdaptiveSemilocalWFA;
inline void init(uint32_t mismatch,
std::array<uint32_t, std::max(1, NumPW)> gap_extend,
std::array<uint32_t, NumPW> gap_open);
// central routine that back-ends the user-facing interface
template<bool Local, int Mem, typename MatchFunc, typename StringType>
inline std::pair<std::vector<CIGAROp>, int32_t>
wavefront_dispatch(const StringType& seq1, const StringType& seq2, uint64_t max_mem) const;
// greedy take matches in WFA
template<typename StringType, typename MatchFunc, typename IntType>
inline void wavefront_extend(const StringType& seq1, const StringType& seq2,
Wavefront<IntType>& wf, const MatchFunc& match_func) const;
// increase score and initialize row in WFA
template<typename IntType, typename WFVector, typename StringType>
inline Wavefront<IntType> wavefront_next(const StringType& seq1, const StringType& seq2,
const WFVector& wfs) const;
// prune lagging diagonals in WFA
template<bool Local, typename IntType>
inline void wavefront_prune(Wavefront<IntType>& wf) const;
// check if reached complete alignment
template<typename IntType>
inline bool wavefront_reached(const Wavefront<IntType>& wf, int32_t diag, int32_t anti_diag) const;
// traceback through a complete DP structure
template <typename StringType, typename IntType>
inline std::vector<CIGAROp> wavefront_traceback(const StringType& seq1, const StringType& seq2,
const std::vector<Wavefront<IntType>>& wfs,
int64_t s, int64_t d) const;
// traceback as far as possible through a possibly incomplete DP structure
// creates the CIGAR in reverse order,
// appends new CIGAR operations to the CIGAR string that is passed in
template<typename WFVector, typename StringType>
void wavefront_traceback_internal(const StringType& seq1, const StringType& seq2,
const WFVector& wfs, int64_t& d, int64_t& lead_matches,
int& mat, int64_t& s, std::vector<CIGAROp>& cigar) const;
// traceback through the low memory algorithms DP structure, with recomputation
template <bool Local, typename StringType, typename MatchFunc, typename IntType>
std::vector<CIGAROp> wavefront_traceback_low_mem(const StringType& seq1, const StringType& seq2,
std::vector<std::pair<int32_t, Wavefront<IntType>>>& wf_bank,
int64_t s, int64_t d, const MatchFunc& match_func) const;
// do classic WFA
template<bool Local, bool Adaptive, typename IntType, typename StringType, typename MatchFunc>
std::pair<std::vector<CIGAROp>, int32_t>
wavefront_align_core(const StringType& seq1, const StringType& seq2,
const MatchFunc& match_func, uint64_t max_mem) const;
// do low memory WFA
template<bool Local, typename IntType, typename StringType, typename MatchFunc>
std::pair<std::vector<CIGAROp>, int32_t>
wavefront_align_low_mem_core(const StringType& seq1, const StringType& seq2,
const MatchFunc& match_func) const;
// internal routine for low memory WFA after initialization or fall-back
template<bool Local, bool Adaptive, typename IntType, typename StringType, typename MatchFunc>
inline std::pair<std::vector<CIGAROp>, int32_t>
wavefront_align_low_mem_core_internal(const StringType& seq1, const StringType& seq2,
const MatchFunc& match_func, uint64_t max_mem,
int64_t epoch_len, int64_t epoch_end, int64_t sample_rate,
int64_t opt, int64_t opt_diag, int64_t opt_s, size_t max_s,
std::deque<Wavefront<IntType>>& wf_buffer, size_t s,
std::vector<std::pair<int32_t, Wavefront<IntType>>>& wf_bank,
uint64_t curr_mem_buffer, uint64_t curr_mem_bank,
uint64_t curr_mem_block, uint64_t max_mem_block) const;
// do recursive WFA
template<bool Local, typename IntType, typename StringType, typename MatchFunc>
std::pair<std::vector<CIGAROp>, int32_t>
wavefront_align_recursive_core(const StringType& seq1, const StringType& seq2,
const MatchFunc& match_func) const;
// internal routine for recursive WFA after initialization or fall-back
template<bool Local, typename IntType, typename StringType, typename MatchFunc>
inline std::pair<std::vector<CIGAROp>, int32_t>
wavefront_align_recursive_core_internal(const StringType& seq1, const StringType& seq2,
const MatchFunc& match_func,
int64_t opt, int64_t opt_diag, int64_t opt_s, size_t max_s,
std::vector<Wavefront<IntType>>& opt_stripe,
std::vector<Wavefront<IntType>>& first_stripe,
std::deque<Wavefront<IntType>>& wf_buffer, size_t s) const;
// recursive calls of recursive WFA
template<bool Local, typename IntType, typename StringType, typename MatchFunc, typename WFVector1, typename WFVector2>
void wavefront_align_recursive_internal(const StringType& seq1, const StringType& seq2,
int64_t lower_stripe_num, WFVector1& lower_stripe,
int64_t upper_stripe_num, WFVector2& upper_stripe,
int64_t& traceback_s, int64_t& traceback_d,
int& traceback_mat, int64_t& lead_matches,
std::vector<CIGAROp>& cigar,
const MatchFunc& match_func) const;
// give up on a standard WFA and switch to doing low memory WFA
template<bool Local, typename IntType, typename StringType, typename MatchFunc>
std::pair<std::vector<CIGAROp>, int32_t>
fall_back_to_low_mem(const StringType& seq1, const StringType& seq2,
const MatchFunc& match_func, uint64_t max_mem,
int64_t opt, int64_t opt_diag, int64_t opt_s, size_t max_s,
std::vector<Wavefront<IntType>>& wfs) const;
// give up on low memory WFA and switch to doing recursive WFA
template<bool Local, typename IntType, typename StringType, typename MatchFunc>
std::pair<std::vector<CIGAROp>, int32_t>
fall_back_to_recursive(const StringType& seq1, const StringType& seq2,
const MatchFunc& match_func,
int64_t opt, int64_t opt_diag, int64_t opt_s, size_t max_s,
std::deque<Wavefront<IntType>>& wf_buffer, size_t s,
std::vector<std::pair<int32_t, Wavefront<IntType>>>& wf_bank) const;
// check score that are SWG-locally optimal
template<typename StringType, typename IntType>
inline void find_local_opt(const StringType& seq1, const StringType& seq2,
int64_t s, const Wavefront<IntType>& wf,
int64_t& opt, int64_t& opt_diag, int64_t& opt_s, size_t& max_s) const;
// do anchored local alignment
template<typename PrefSemilocalWFA, typename AnchorGlobalWFA, typename SuffSemilocalWFA>
std::tuple<std::vector<CIGAROp>, int32_t, std::pair<size_t, size_t>, std::pair<size_t, size_t>>
wavefront_align_local_core(const char* seq1, size_t len1,
const char* seq2, size_t len2,
uint64_t max_mem,
size_t anchor_begin_1, size_t anchor_end_1,
size_t anchor_begin_2, size_t anchor_end_2,
bool anchor_is_match) const;
// greatest commmon denominator
uint32_t gcd(uint32_t a, uint32_t b) const;
// convert a WFA score into a SWG score
inline int32_t convert_score(size_t len1, size_t len2, int32_t score) const;
// merge adjacent CIGAR ops that are the same type
inline void coalesce_cigar(std::vector<CIGAROp>& cigar) const;
// get the length of the aligned sequence on both sequences
inline std::pair<size_t, size_t> cigar_base_length(const std::vector<CIGAROp>& cigar) const;
// WFA-style parameters
uint32_t mismatch = 1;
std::array<uint32_t, std::max(1, NumPW)> gap_extend;
std::array<uint32_t, NumPW> gap_open;
// scores are reduced by a constant factor if they have a non-trivial common
// denominator to reduce run time
uint32_t factor = 1;
// SWG match score, or 0 if not using SWG scoring
uint32_t match = 0;
// how many subsequent wavefronts are required to do DP with these scoring parameters
int64_t stripe_width = 1;
private:
/* debug functions*/
template<typename IntType>
inline void print_wf(const Wavefront<IntType>& wf, int diag_begin, int diag_end) const;
template<typename WFVector>
void print_wfs(const WFVector& wfs) const;
template<typename IntType>
inline void print_wfs_low_mem(const std::vector<std::pair<int32_t, Wavefront<IntType>>>& wf_bank,
const std::deque<Wavefront<IntType>>& wf_buffer, int s) const;
template<typename IntType>
inline void print_wfs_tb(const std::deque<Wavefront<IntType>>& traceback_block,
const std::vector<std::pair<int32_t, Wavefront<IntType>>>& wf_bank,
int i) const;
template <typename StringType, typename WFVector>
void wavefront_viz(const StringType& seq1, const StringType& seq2,
const WFVector& wfs) const;
static_assert(NumPW >= 0, "Must choose a non-negative number of piecewise linear penalities");
};
/*
* Adapter to avoid string copying for when aligning subintervals
*/
class StringView {
public:
StringView(const char* seq, size_t i, size_t len) : seq(seq + i), len(len)
{
}
inline const char& operator[](size_t idx) const {
return seq[idx];
}
inline size_t size() const {
return len;
}
private:
const char* seq;
size_t len;
};
/*
* Adapter to avoid string copying for when aligning subintervals
* that also reverses the string
*/
class RevStringView {
public:
// note: interval is provided in forward direction
RevStringView(const char* seq, size_t i, size_t len) : seql(seq + i + len - 1), len(len)
{
}
inline const char& operator[](size_t idx) const {
return *(seql - idx);
}
inline size_t size() const {
return len;
}
private:
// last char in the seq
const char* seql;
size_t len;
};
/*
* templated SIMD operations by integer width
*/
template<typename IntType>
struct SIMD {
static inline int vec_size() {
return sizeof(__m128i) / sizeof(IntType);
}
static inline int round_up(int l) {
return (l + vec_size() - 1) / vec_size();
}
static inline int round_down(int l) {
return l / vec_size();
}
static inline bool is_aligned(__m128i* ptr) {
return !(((uintptr_t) ptr) & (sizeof(__m128i) - 1));
}
static inline __m128i load_unaligned(const __m128i* ptr) {
return _mm_loadu_si128(ptr);
}
static inline __m128i broadcast(IntType i);
static inline __m128i min_inf() {
return broadcast(std::numeric_limits<IntType>::min());
}
// O, 1, ..., L-1
static inline __m128i range();
static inline __m128i mask_and(__m128i a, __m128i b) {
return _mm_and_si128(a, b);
}
static inline __m128i mask_not(__m128i a) {
// there's not bitwise not, so i have to simulate it with xor
return _mm_xor_si128(a, broadcast(-1));
}
static inline __m128i eq(__m128i a, __m128i b);
static inline __m128i less(__m128i a, __m128i b);
static inline __m128i leq(__m128i a, __m128i b) {
return mask_not(less(b, a));
}
static inline __m128i max(__m128i a, __m128i b);
static inline __m128i add(__m128i a, __m128i b);
static inline __m128i subtract(__m128i a, __m128i b);
//static inline __m128i div2(__m128i a);
// t ? a : b
// note: assumes all 1 bits in condition so that 8-bit wors for all widths
static inline __m128i ifelse(__m128i t, __m128i a, __m128i b) {
return _mm_blendv_epi8(b, a, t);
}
};
// a match-computing function based on direct character comparison
class CompareMatchFunc {
protected:
template<bool Reversed, class StringType>
inline void load(const StringType& seq1, const StringType& seq2,
size_t i, size_t j, __m128i& vec1, __m128i& vec2) const {
if (Reversed) {
static const __m128i reverser = _mm_setr_epi8(15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0);
vec1 = _mm_shuffle_epi8(SIMD<int8_t>::load_unaligned((__m128i const*)(&seq1[i] - sizeof(__m128i) + 1)), reverser);
vec2 = _mm_shuffle_epi8(SIMD<int8_t>::load_unaligned((__m128i const*)(&seq2[j] - sizeof(__m128i) + 1)), reverser);
}
else {
vec1 = SIMD<int8_t>::load_unaligned((__m128i const*)&seq1[i]);
vec2 = SIMD<int8_t>::load_unaligned((__m128i const*)&seq2[j]);
}
}
// sub-routine of the internal function that computes the length of the prefix match
// in the first 8 bytes of an equality mask vector
inline size_t partial_vec_match(const __m128i& eq) const {
// find the mismatch among the first 8 bytes if there is one
__m128i pos = _mm_minpos_epu16(_mm_cvtepi8_epi16(eq));
return _mm_extract_epi16(pos, 0) == 0 ? _mm_extract_epi16(pos, 1) : 8;
}
// a template-controlled generic function for the specializations to call
template<bool Reversed, class StringType>
inline size_t match_func_internal(const StringType& seq1, const StringType& seq2, size_t i, size_t j) const {
// remember where we start from
size_t init = i;
// TODO: is it safe to make this execute within 8 bytes from the end since the first
// comparison is only of the first 8 bases anyway?
// use vectorized operations to find matches if we can
bool found_mismatch = false;
if (i + SIMD<int8_t>::vec_size() <= seq1.size() &&
j + SIMD<int8_t>::vec_size() <= seq2.size()) {
// try to find a partial match of the first 8 bases
__m128i vec1, vec2;
load<Reversed, StringType>(seq1, seq2, i, j, vec1, vec2);
__m128i eq = SIMD<int8_t>::eq(vec1, vec2);
size_t match_len = partial_vec_match(eq);
i += match_len;
j += match_len;
found_mismatch = (match_len < 8);
if (!found_mismatch) {
// we matched the first 8 bases, so now we transition into a cheaper matching of an
// entire vector to move quickly in instances of very long matches
// TODO: i could maybe load aligned after the first iteration, but you can't guarantee
// alignment of both strings...
while (i + SIMD<int8_t>::vec_size() <= seq1.size() &&
j + SIMD<int8_t>::vec_size() <= seq2.size()) {
load<Reversed, StringType>(seq1, seq2, i, j, vec1, vec2);
eq = SIMD<int8_t>::eq(vec1, vec2);
if (_mm_test_all_ones(eq)) {
// we matched the entire vector
i += 16;
j += 16;
}
else {
// there's a mismatch in the vector somewhere
match_len = partial_vec_match(eq);
i += match_len;
j += match_len;
if (match_len == 8) {
// the mismatch is after the first 8 bases, shift over and find it
eq = _mm_alignr_epi8(SIMD<int8_t>::broadcast(0), eq, 8);
match_len = partial_vec_match(eq);
i += match_len;
j += match_len;
}
found_mismatch = true;
break;
}
}
}
}
if (!found_mismatch) {
// we got too close to the end of the sequences to do vectorized operations
// without finding a mismatch, finish out with
while (i < seq1.size() && j < seq2.size() && seq1[i] == seq2[j]) {
++i;
++j;
}
}
return i - init;
}
};
/**
* Specialization for forward matching
*/
class FwdCompareMatchFunc : public CompareMatchFunc {
public:
FwdCompareMatchFunc(const StringView& seq1, const StringView& seq2)
: seq1(seq1), seq2(seq2)
{
}
// leave the actual implementation to the template specializations
inline size_t operator()(size_t i, size_t j) const {
return match_func_internal<false, StringView>(seq1, seq2, i, j);
}
protected:
const StringView& seq1;
const StringView& seq2;
};
/**
* Specialization for reverse matching
*/
class RevCompareMatchFunc : public CompareMatchFunc {
public:
RevCompareMatchFunc(const RevStringView& seq1, const RevStringView& seq2)
: seq1(seq1), seq2(seq2)
{
}
// leave the actual implementation to the template specializations
inline size_t operator()(size_t i, size_t j) const {
return match_func_internal<true, RevStringView>(seq1, seq2, i, j);
}
protected:
const RevStringView& seq1;
const RevStringView& seq2;
};
template<int NumPW>
template<typename IntType>
struct WFAligner<NumPW>::Wavefront {
private:
inline void init_arrays() {
// we pad the array with a full vector on each end to handle boundary conditions
interval = SIMD<IntType>::round_up(len) + 2;
int alloc_size = (2 * NumPW + 1) * interval * sizeof(__m128i);
if (posix_memalign((void**)&alloced, sizeof(__m128i), alloc_size)) {
throw std::runtime_error(std::string("error:[WFAligner] could not perform aligned allocation of size "
+ std::to_string(alloc_size)).c_str());
}
// M is at the middle of the array
M = alloced + interval * NumPW + 1;
}
public:
Wavefront() {}
Wavefront(int32_t diag_begin, int32_t diag_end)
: diag_begin(diag_begin), len(diag_end - diag_begin)
{
init_arrays();
for (int32_t i = 0, n = interval * (2 * NumPW + 1); i < n; ++i) {
// TODO: i might be able to get away with only setting the
// shoulders now that the ifelse condition in DP assigns -infinity
alloced[i] = SIMD<IntType>::min_inf();
}
}
inline Wavefront& operator=(const Wavefront& other) noexcept {
if (this != &other) {
diag_begin = other.diag_begin;
len = other.len;
init_arrays();
// set the boundaries
for (int i = -NumPW; i <= NumPW; ++i) {
auto A = M + interval * i;
*(A - 1) = SIMD<IntType>::min_inf();
*(A + interval - 2) = SIMD<IntType>::min_inf();
}
// copy the interior of the array
auto vec_n = SIMD<IntType>::round_up(len);
if (SIMD<IntType>::is_aligned(other.M)) {
// the arrays are aligned
for (int i = -NumPW; i <= NumPW; ++i) {
auto A = M + interval * i;
auto B = other.M + other.interval * i;
for (int32_t j = 0; j < vec_n; ++j) {
A[i] = B[i];
}
}
}
else {
// the other arrays are not aligned
for (int i = -NumPW; i <= NumPW; ++i) {
auto A = M + interval * i;
auto B = other.M + other.interval * i;
for (int32_t j = 0; j < vec_n; ++j) {
A[i] = SIMD<IntType>::load_unaligned(B + i);
}
}
}
}
return *this;
}
inline Wavefront& operator=(Wavefront&& other) noexcept {
if (this != &other) {
diag_begin = other.diag_begin;
len = other.len;
interval = other.interval;
if (alloced) {
free(alloced);
}
alloced = other.alloced;
M = other.M;
other.alloced = other.M = nullptr;
other.len = 0;
other.interval = 0;
}
return *this;
}
Wavefront(const Wavefront& other) noexcept {
*this = other;
}