forked from Martinsos/edlib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
edlib.cpp
1255 lines (1118 loc) · 52.3 KB
/
edlib.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
#include "edlib.h"
#include <stdint.h>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <cstring>
#include <cassert>
using namespace std;
typedef uint64_t Word;
static const int WORD_SIZE = sizeof(Word) * 8; // Size of Word in bits
static const Word WORD_1 = (Word)1;
static const Word HIGH_BIT_MASK = WORD_1 << (WORD_SIZE - 1); // 100..00
// Data needed to find alignment.
struct AlignmentData {
Word* Ps;
Word* Ms;
int* scores;
int* firstBlocks;
int* lastBlocks;
AlignmentData(int maxNumBlocks, int targetLength) {
// We build a complete table and mark first and last block for each column
// (because algorithm is banded so only part of each columns is used).
// TODO: do not build a whole table, but just enough blocks for each column.
Ps = new Word[maxNumBlocks * targetLength];
Ms = new Word[maxNumBlocks * targetLength];
scores = new int[maxNumBlocks * targetLength];
firstBlocks = new int[targetLength];
lastBlocks = new int[targetLength];
}
~AlignmentData() {
delete[] Ps;
delete[] Ms;
delete[] scores;
delete[] firstBlocks;
delete[] lastBlocks;
}
};
struct Block {
Word P; // Pvin
Word M; // Mvin
int score; // score of last cell in block;
Block() {}
Block(Word P, Word M, int score) :P(P), M(M), score(score) {}
};
static int myersCalcEditDistanceSemiGlobal(Word* Peq, int W, int maxNumBlocks,
const unsigned char* query, int queryLength,
const unsigned char* target, int targetLength,
int alphabetLength, int k, int mode, int* bestScore,
int** positions, int* numPositions);
static int myersCalcEditDistanceNW(Word* Peq, int W, int maxNumBlocks,
const unsigned char* query, int queryLength,
const unsigned char* target, int targetLength,
int alphabetLength, int k, int* bestScore, int* position,
bool findAlignment, AlignmentData** alignData, int targetStopPosition);
static int obtainAlignment(
const unsigned char* query, const unsigned char* rQuery, const int queryLength,
const unsigned char* target, const unsigned char* rTarget, const int targetLength,
const int alphabetLength, const int bestScore,
unsigned char** alignment, int* alignmentLength);
static int obtainAlignmentHirschberg(
const unsigned char* query, const unsigned char* rQuery, const int queryLength,
const unsigned char* target, const unsigned char* rTarget, const int targetLength,
const int alphabetLength, const int bestScore,
unsigned char** alignment, int* alignmentLength);
static int obtainAlignmentTraceback(const int queryLength, const int targetLength,
const int bestScore, const AlignmentData* alignData,
unsigned char** alignment, int* alignmentLength);
static inline int ceilDiv(int x, int y);
static inline unsigned char* createReverseCopy(const unsigned char* seq, int length);
static inline Word* buildPeq(int alphabetLength, const unsigned char* query, int queryLength);
/**
* Entry function.
*/
int edlibCalcEditDistance(
const unsigned char* query, int queryLength,
const unsigned char* target, int targetLength,
int alphabetLength, int k, int mode,
bool findStartLocations, bool findAlignment,
int* bestScore, int** endLocations, int** startLocations, int* numLocations,
unsigned char** alignment, int* alignmentLength) {
*alignment = NULL;
/*--------------------- INITIALIZATION ------------------*/
int maxNumBlocks = ceilDiv(queryLength, WORD_SIZE); // bmax in Myers
int W = maxNumBlocks * WORD_SIZE - queryLength; // number of redundant cells in last level blocks
Word* Peq = buildPeq(alphabetLength, query, queryLength);
/*-------------------------------------------------------*/
/*------------------ MAIN CALCULATION -------------------*/
// TODO: Store alignment data only after k is determined? That could make things faster.
*bestScore = -1;
*endLocations = *startLocations = NULL;
*numLocations = 0;
int positionNW; // Used only when mode is NW.
AlignmentData* alignData = NULL;
bool dynamicK = false;
if (k < 0) { // If valid k is not given, auto-adjust k until solution is found.
dynamicK = true;
k = WORD_SIZE; // Gives better results than smaller k.
}
do {
if (mode == EDLIB_MODE_HW || mode == EDLIB_MODE_SHW) {
myersCalcEditDistanceSemiGlobal(Peq, W, maxNumBlocks,
query, queryLength, target, targetLength,
alphabetLength, k, mode, bestScore,
endLocations, numLocations);
} else { // mode == EDLIB_MODE_NW
myersCalcEditDistanceNW(Peq, W, maxNumBlocks,
query, queryLength, target, targetLength,
alphabetLength, k, bestScore, &positionNW,
false, &alignData, -1);
}
k *= 2;
} while(dynamicK && *bestScore == -1);
if (*bestScore >= 0) { // If there is solution.
// If NW mode, set end location explicitly.
if (mode == EDLIB_MODE_NW) {
*endLocations = (int *) malloc(sizeof(int) * 1);
(*endLocations)[0] = targetLength - 1;
*numLocations = 1;
}
// Find starting locations.
if (findStartLocations || findAlignment) {
*startLocations = (int*) malloc((*numLocations) * sizeof(int));
if (mode == EDLIB_MODE_HW) { // If HW, I need to calculate start locations.
const unsigned char* rTarget = createReverseCopy(target, targetLength);
const unsigned char* rQuery = createReverseCopy(query, queryLength);
Word* rPeq = buildPeq(alphabetLength, rQuery, queryLength); // Peq for reversed query
for (int i = 0; i < *numLocations; i++) {
int endLocation = (*endLocations)[i];
int bestScoreSHW, numPositionsSHW;
int* positionsSHW;
myersCalcEditDistanceSemiGlobal(
rPeq, W, maxNumBlocks,
rQuery, queryLength, rTarget + targetLength - endLocation - 1, endLocation + 1,
alphabetLength, *bestScore, EDLIB_MODE_SHW,
&bestScoreSHW, &positionsSHW, &numPositionsSHW);
// Taking last location as start ensures that alignment will not start with insertions
// if it can start with mismatches instead.
(*startLocations)[i] = endLocation - positionsSHW[numPositionsSHW - 1];
delete[] positionsSHW;
}
delete[] rTarget;
delete[] rQuery;
delete[] rPeq;
} else { // If mode is SHW or NW
for (int i = 0; i < *numLocations; i++) {
(*startLocations)[i] = 0;
}
}
}
// Find alignment -> all comes down to finding alignment for NW.
// Currently we return alignment only for first pair of locations.
if (findAlignment) {
int alnStartLocation = (*startLocations)[0];
int alnEndLocation = (*endLocations)[0];
const unsigned char* alnTarget = target + alnStartLocation;
const int alnTargetLength = alnEndLocation - alnStartLocation + 1;
const unsigned char* rAlnTarget = createReverseCopy(alnTarget, alnTargetLength);
const unsigned char* rQuery = createReverseCopy(query, queryLength);
obtainAlignment(query, rQuery, queryLength,
alnTarget, rAlnTarget, alnTargetLength,
alphabetLength, *bestScore,
alignment, alignmentLength);
delete[] rAlnTarget;
delete[] rQuery;
}
}
/*-------------------------------------------------------*/
//--- Free memory ---//
delete[] Peq;
if (alignData) delete alignData;
//-------------------//
return EDLIB_STATUS_OK;
}
int edlibAlignmentToCigar(unsigned char* alignment, int alignmentLength,
int cigarFormat, char** cigar_) {
*cigar_ = NULL;
if (cigarFormat != EDLIB_CIGAR_EXTENDED && cigarFormat != EDLIB_CIGAR_STANDARD) {
return EDLIB_STATUS_ERROR;
}
// Maps move code from alignment to char in cigar.
// 0 1 2 3
char moveCodeToChar[] = {'=', 'I', 'D', 'X'};
if (cigarFormat == EDLIB_CIGAR_STANDARD) {
moveCodeToChar[0] = moveCodeToChar[3] = 'M';
}
vector<char>* cigar = new vector<char>();
char lastMove = 0; // Char of last move. 0 if there was no previous move.
int numOfSameMoves = 0;
for (int i = 0; i <= alignmentLength; i++) {
// if new sequence of same moves started
if (i == alignmentLength || (moveCodeToChar[alignment[i]] != lastMove && lastMove != 0)) {
// Write number of moves to cigar string.
int numDigits = 0;
for (; numOfSameMoves; numOfSameMoves /= 10) {
cigar->push_back('0' + numOfSameMoves % 10);
numDigits++;
}
reverse(cigar->end() - numDigits, cigar->end());
// Write code of move to cigar string.
cigar->push_back(lastMove);
// If not at the end, start new sequence of moves.
if (i < alignmentLength) {
// Check if alignment has valid values.
if (alignment[i] > 3) {
delete cigar;
return EDLIB_STATUS_ERROR;
}
numOfSameMoves = 0;
}
}
if (i < alignmentLength) {
lastMove = moveCodeToChar[alignment[i]];
numOfSameMoves++;
}
}
cigar->push_back(0); // Null character termination.
*cigar_ = (char*) malloc(cigar->size() * sizeof(char));
memcpy(*cigar_, &(*cigar)[0], cigar->size() * sizeof(char));
delete cigar;
return EDLIB_STATUS_OK;
}
/**
* Build Peq table for given query and alphabet.
* Peq is table of dimensions alphabetLength+1 x maxNumBlocks.
* Bit i of Peq[s * maxNumBlocks + b] is 1 if i-th symbol from block b of query equals symbol s, otherwise it is 0.
* NOTICE: free returned array with delete[]!
*/
static inline Word* buildPeq(int alphabetLength, const unsigned char* query, int queryLength) {
int maxNumBlocks = ceilDiv(queryLength, WORD_SIZE);
// table of dimensions alphabetLength+1 x maxNumBlocks. Last symbol is wildcard.
Word* Peq = new Word[(alphabetLength + 1) * maxNumBlocks];
// Build Peq (1 is match, 0 is mismatch). NOTE: last column is wildcard(symbol that matches anything) with just 1s
for (int symbol = 0; symbol <= alphabetLength; symbol++) {
for (int b = 0; b < maxNumBlocks; b++) {
if (symbol < alphabetLength) {
Peq[symbol * maxNumBlocks + b] = 0;
for (int r = (b+1) * WORD_SIZE - 1; r >= b * WORD_SIZE; r--) {
Peq[symbol * maxNumBlocks + b] <<= 1;
// NOTE: We pretend like query is padded at the end with W wildcard symbols
if (r >= queryLength || query[r] == symbol)
Peq[symbol * maxNumBlocks + b] += 1;
}
} else { // Last symbol is wildcard, so it is all 1s
Peq[symbol * maxNumBlocks + b] = (Word)-1;
}
}
}
return Peq;
}
/**
* Returns new sequence that is reverse of given sequence.
*/
static inline unsigned char* createReverseCopy(const unsigned char* seq, int length) {
unsigned char* rSeq = new unsigned char[length];
for (int i = 0; i < length; i++) {
rSeq[i] = seq[length - i - 1];
}
return rSeq;
}
/**
* Corresponds to Advance_Block function from Myers.
* Calculates one word(block), which is part of a column.
* Highest bit of word (one most to the left) is most bottom cell of block from column.
* Pv[i] and Mv[i] define vin of cell[i]: vin = cell[i] - cell[i-1].
* @param [in] Pv Bitset, Pv[i] == 1 if vin is +1, otherwise Pv[i] == 0.
* @param [in] Mv Bitset, Mv[i] == 1 if vin is -1, otherwise Mv[i] == 0.
* @param [in] Eq Bitset, Eq[i] == 1 if match, 0 if mismatch.
* @param [in] hin Will be +1, 0 or -1.
* @param [out] PvOut Bitset, PvOut[i] == 1 if vout is +1, otherwise PvOut[i] == 0.
* @param [out] MvOut Bitset, MvOut[i] == 1 if vout is -1, otherwise MvOut[i] == 0.
* @param [out] hout Will be +1, 0 or -1.
*/
static inline int calculateBlock(Word Pv, Word Mv, Word Eq, const int hin,
Word &PvOut, Word &MvOut) {
// hin can be 1, -1 or 0.
// 1 -> 00...01
// 0 -> 00...00
// -1 -> 11...11 (2-complement)
Word hinIsNeg = (Word)(hin >> 2) & WORD_1; // 00...001 if hin is -1, 00...000 if 0 or 1
Word Xv = Eq | Mv;
// This is instruction below written using 'if': if (hin < 0) Eq |= (Word)1;
Eq |= hinIsNeg;
Word Xh = (((Eq & Pv) + Pv) ^ Pv) | Eq;
Word Ph = Mv | ~(Xh | Pv);
Word Mh = Pv & Xh;
int hout = 0;
// This is instruction below written using 'if': if (Ph & HIGH_BIT_MASK) hout = 1;
hout = (Ph & HIGH_BIT_MASK) >> (WORD_SIZE - 1);
// This is instruction below written using 'if': if (Mh & HIGH_BIT_MASK) hout = -1;
hout -= (Mh & HIGH_BIT_MASK) >> (WORD_SIZE - 1);
Ph <<= 1;
Mh <<= 1;
// This is instruction below written using 'if': if (hin < 0) Mh |= (Word)1;
Mh |= hinIsNeg;
// This is instruction below written using 'if': if (hin > 0) Ph |= (Word)1;
Ph |= (Word)((hin + 1) >> 1);
PvOut = Mh | ~(Xv | Ph);
MvOut = Ph & Xv;
return hout;
}
/**
* Does ceiling division x / y.
* Note: x and y must be non-negative and x + y must not overflow.
*/
static inline int ceilDiv(int x, int y) {
return x % y ? x / y + 1 : x / y;
}
static inline int min(int x, int y) {
return x < y ? x : y;
}
static inline int max(int x, int y) {
return x > y ? x : y;
}
/**
* @param [in] block
* @return Values of cells in block, starting with bottom cell in block.
*/
static inline vector<int> getBlockCellValues(const Block block) {
vector<int> scores(WORD_SIZE);
int score = block.score;
Word mask = HIGH_BIT_MASK;
for (int i = 0; i < WORD_SIZE - 1; i++) {
scores[i] = score;
if (block.P & mask) score--;
if (block.M & mask) score++;
mask >>= 1;
}
scores[WORD_SIZE - 1] = score;
return scores;
}
/**
* Writes values of cells in block into given array, starting with first/top cell.
* @param [in] block
* @param [out] dest Array into which cell values are written. Must have size of at least WORD_SIZE.
*/
static inline void readBlock(const Block block, int* const dest) {
int score = block.score;
Word mask = HIGH_BIT_MASK;
for (int i = 0; i < WORD_SIZE - 1; i++) {
dest[WORD_SIZE - 1 - i] = score;
if (block.P & mask) score--;
if (block.M & mask) score++;
mask >>= 1;
}
dest[0] = score;
}
/**
* Writes values of cells in block into given array, starting with last/bottom cell.
* @param [in] block
* @param [out] dest Array into which cell values are written. Must have size of at least WORD_SIZE.
*/
static inline void readBlockReverse(const Block block, int* const dest) {
int score = block.score;
Word mask = HIGH_BIT_MASK;
for (int i = 0; i < WORD_SIZE - 1; i++) {
dest[i] = score;
if (block.P & mask) score--;
if (block.M & mask) score++;
mask >>= 1;
}
dest[WORD_SIZE - 1] = score;
}
/**
* @param [in] block
* @param [in] k
* @return True if all cells in block have value larger than k, otherwise false.
*/
static inline bool allBlockCellsLarger(const Block block, const int k) {
vector<int> scores = getBlockCellValues(block);
for (int i = 0; i < WORD_SIZE; i++) {
if (scores[i] <= k) return false;
}
return true;
}
/**
* @param [in] mode EDLIB_MODE_HW or EDLIB_MODE_SHW or EDLIB_MODE_OV
*/
static int myersCalcEditDistanceSemiGlobal(Word* const Peq, const int W, const int maxNumBlocks,
const unsigned char* const query, const int queryLength,
const unsigned char* const target, const int targetLength,
const int alphabetLength, int k, const int mode, int* bestScore_,
int** positions_, int* numPositions_) {
*positions_ = NULL;
*numPositions_ = 0;
// firstBlock is 0-based index of first block in Ukkonen band.
// lastBlock is 0-based index of last block in Ukkonen band.
int firstBlock = 0;
int lastBlock = min(ceilDiv(k + 1, WORD_SIZE), maxNumBlocks) - 1; // y in Myers
Block *bl; // Current block
Block* blocks = new Block[maxNumBlocks];
// For HW, solution will never be larger then queryLength.
if (mode == EDLIB_MODE_HW) {
k = min(queryLength, k);
}
// Each STRONG_REDUCE_NUM column is reduced in more expensive way.
// This gives speed up of about 2 times for small k.
const int STRONG_REDUCE_NUM = 2048;
// Initialize P, M and score
bl = blocks;
for (int b = 0; b <= lastBlock; b++) {
bl->score = (b + 1) * WORD_SIZE;
bl->P = (Word)-1; // All 1s
bl->M = (Word)0;
bl++;
}
int bestScore = -1;
vector<int> positions; // TODO: Maybe put this on heap?
const int startHout = mode == EDLIB_MODE_HW ? 0 : 1; // If 0 then gap before query is not penalized;
const unsigned char* targetChar = target;
for (int c = 0; c < targetLength; c++) { // for each column
const Word* Peq_c = Peq + (*targetChar) * maxNumBlocks;
//----------------------- Calculate column -------------------------//
int hout = startHout;
bl = blocks + firstBlock;
Peq_c += firstBlock;
for (int b = firstBlock; b <= lastBlock; b++) {
hout = calculateBlock(bl->P, bl->M, *Peq_c, hout, bl->P, bl->M);
bl->score += hout;
bl++; Peq_c++;
}
bl--; Peq_c--;
//------------------------------------------------------------------//
//---------- Adjust number of blocks according to Ukkonen ----------//
if ((lastBlock < maxNumBlocks - 1) && (bl->score - hout <= k) // bl is pointing to last block
&& ((*(Peq_c + 1) & WORD_1) || hout < 0)) { // Peq_c is pointing to last block
// If score of left block is not too big, calculate one more block
lastBlock++; bl++; Peq_c++;
bl->P = (Word)-1; // All 1s
bl->M = (Word)0;
bl->score = (bl - 1)->score - hout + WORD_SIZE + calculateBlock(bl->P, bl->M, *Peq_c, hout, bl->P, bl->M);
} else {
while (lastBlock >= firstBlock && bl->score >= k + WORD_SIZE) {
lastBlock--; bl--; Peq_c--;
}
}
// Every some columns, do some expensive but also more efficient block reducing -> this is important!
if (c % STRONG_REDUCE_NUM == 0) {
while (lastBlock >= firstBlock && allBlockCellsLarger(*bl, k)) {
lastBlock--; bl--; Peq_c--;
}
}
if (mode != EDLIB_MODE_HW) {
while (firstBlock <= lastBlock && blocks[firstBlock].score >= k + WORD_SIZE) {
firstBlock++;
}
if (c % STRONG_REDUCE_NUM == 0) { // Do strong reduction every some blocks
while (firstBlock <= lastBlock && allBlockCellsLarger(blocks[firstBlock], k)) {
firstBlock++;
}
}
}
// For HW, even if all cells are > k, there still may be solution in next
// column because starting conditions at upper boundary are 0.
// That means that first block is always candidate for solution,
// and we can never end calculation before last column.
if (mode == EDLIB_MODE_HW) {
lastBlock = max(0, lastBlock);
}
// If band stops to exist finish
if (lastBlock < firstBlock) {
*bestScore_ = bestScore;
if (bestScore != -1) {
*positions_ = (int *) malloc(sizeof(int) * positions.size());
*numPositions_ = positions.size();
copy(positions.begin(), positions.end(), *positions_);
}
delete[] blocks;
return EDLIB_STATUS_OK;
}
//------------------------------------------------------------------//
//------------------------- Update best score ----------------------//
if (lastBlock == maxNumBlocks - 1) {
int colScore = bl->score;
if (colScore <= k) { // Scores > k dont have correct values (so we cannot use them), but are certainly > k.
// NOTE: Score that I find in column c is actually score from column c-W
if (bestScore == -1 || colScore <= bestScore) {
if (colScore != bestScore) {
positions.clear();
bestScore = colScore;
// Change k so we will look only for equal or better
// scores then the best found so far.
k = bestScore;
}
positions.push_back(c - W);
}
}
}
//------------------------------------------------------------------//
targetChar++;
}
// Obtain results for last W columns from last column.
if (lastBlock == maxNumBlocks - 1) {
vector<int> blockScores = getBlockCellValues(*bl);
for (int i = 0; i < W; i++) {
int colScore = blockScores[i + 1];
if (colScore <= k && (bestScore == -1 || colScore <= bestScore)) {
if (colScore != bestScore) {
positions.clear();
k = bestScore = colScore;
}
positions.push_back(targetLength - W + i);
}
}
}
*bestScore_ = bestScore;
if (bestScore != -1) {
*positions_ = (int *) malloc(sizeof(int) * positions.size());
*numPositions_ = positions.size();
copy(positions.begin(), positions.end(), *positions_);
}
delete[] blocks;
return EDLIB_STATUS_OK;
}
/**
* @param alignData Data generated during calculation, that is needed for reconstruction of alignment.
* I it is allocated with new, so free it with delete.
* Data is generated only if findAlignment is true.
* @param targetStopPosition If set to -1, whole calculation is performed.
* If set to p, calculation is performed up to position p in target (inclusive)
* and column p is returned as the only column in alignData.
*/
static int myersCalcEditDistanceNW(Word* Peq, int W, int maxNumBlocks,
const unsigned char* query, int queryLength,
const unsigned char* target, int targetLength,
int alphabetLength, int k, int* bestScore_, int* position_,
bool findAlignment, AlignmentData** alignData,
int targetStopPosition) {
if (targetStopPosition > -1 && findAlignment) {
// They can not be both set at the same time!
return EDLIB_STATUS_ERROR;
}
// Each STRONG_REDUCE_NUM column is reduced in more expensive way.
const int STRONG_REDUCE_NUM = 2048; // TODO: Choose this number dinamically (based on query and target lengths?), so it does not affect speed of computation
if (k < abs(targetLength - queryLength)) {
*bestScore_ = *position_ = -1;
return EDLIB_STATUS_OK;
}
k = min(k, max(queryLength, targetLength)); // Upper bound for k
// firstBlock is 0-based index of first block in Ukkonen band.
// lastBlock is 0-based index of last block in Ukkonen band.
int firstBlock = 0;
// This is optimal now, by my formula.
int lastBlock = min(maxNumBlocks, ceilDiv(min(k, (k + queryLength - targetLength) / 2) + 1, WORD_SIZE)) - 1;
Block* bl; // Current block
Block* blocks = new Block[maxNumBlocks];
// Initialize P, M and score
bl = blocks;
for (int b = 0; b <= lastBlock; b++) {
bl->score = (b + 1) * WORD_SIZE;
bl->P = (Word)-1; // All 1s
bl->M = (Word)0;
bl++;
}
// If we want to find alignment, we have to store needed data.
if (findAlignment)
*alignData = new AlignmentData(maxNumBlocks, targetLength);
else if (targetStopPosition > -1)
*alignData = new AlignmentData(maxNumBlocks, 1);
else
*alignData = NULL;
const unsigned char* targetChar = target;
for (int c = 0; c < targetLength; c++) { // for each column
Word* Peq_c = Peq + *targetChar * maxNumBlocks;
//----------------------- Calculate column -------------------------//
int hout = 1;
bl = blocks + firstBlock;
for (int b = firstBlock; b <= lastBlock; b++) {
hout = calculateBlock(bl->P, bl->M, Peq_c[b], hout, bl->P, bl->M);
bl->score += hout;
bl++;
}
bl--;
//------------------------------------------------------------------//
// bl now points to last block
// Update k. I do it only on end of column because it would slow calculation too much otherwise.
// NOTICE: I add W when in last block because it is actually result from W cells to the left and W cells up.
k = min(k, bl->score
+ max(targetLength - c - 1, queryLength - ((1 + lastBlock) * WORD_SIZE - 1) - 1)
+ (lastBlock == maxNumBlocks - 1 ? W : 0));
//---------- Adjust number of blocks according to Ukkonen ----------//
//--- Adjust last block ---//
// If block is not beneath band, calculate next block. Only next because others are certainly beneath band.
if (lastBlock + 1 < maxNumBlocks
&& !(//score[lastBlock] >= k + WORD_SIZE || // NOTICE: this condition could be satisfied if above block also!
((lastBlock + 1) * WORD_SIZE - 1
> k - bl->score + 2 * WORD_SIZE - 2 - targetLength + c + queryLength))) {
lastBlock++; bl++;
bl->P = (Word)-1; // All 1s
bl->M = (Word)0;
int newHout = calculateBlock(bl->P, bl->M, Peq_c[lastBlock], hout, bl->P, bl->M);
bl->score = (bl - 1)->score - hout + WORD_SIZE + newHout;
hout = newHout;
}
// While block is out of band, move one block up. - This is optimal now, by my formula.
// NOTICE: I added + W, and now it works! This has to be added because query is padded with W cells.
while (lastBlock >= firstBlock
&& (bl->score >= k + WORD_SIZE
|| ((lastBlock + 1) * WORD_SIZE - 1 >
k - bl->score + 2 * WORD_SIZE - 2 - targetLength + c + queryLength + W))) {
lastBlock--; bl--;
}
//-------------------------//
//--- Adjust first block ---//
// While outside of band, advance block
while (firstBlock <= lastBlock
&& (blocks[firstBlock].score >= k + WORD_SIZE
|| ((firstBlock + 1) * WORD_SIZE - 1 <
blocks[firstBlock].score - k - targetLength + queryLength + c))) {
firstBlock++;
}
//--------------------------/
// TODO: consider if this part is useful, it does not seem to help much
if (c % STRONG_REDUCE_NUM == 0) { // Every some columns do more expensive but more efficient reduction
while (lastBlock >= firstBlock) {
// If all cells outside of band, remove block
vector<int> scores = getBlockCellValues(*bl);
int r = (lastBlock + 1) * WORD_SIZE - 1;
bool reduce = true;
for (int i = 0; i < WORD_SIZE; i++) {
// TODO: Does not work if do not put +1! Why???
if (scores[i] <= k && r <= k - scores[i] - targetLength + c + queryLength + W + 1) {
reduce = false;
break;
}
r--;
}
if (!reduce) break;
lastBlock--; bl--;
}
while (firstBlock <= lastBlock) {
// If all cells outside of band, remove block
vector<int> scores = getBlockCellValues(blocks[firstBlock]);
int r = (firstBlock + 1) * WORD_SIZE - 1;
bool reduce = true;
for (int i = 0; i < WORD_SIZE; i++) {
if (scores[i] <= k && r >= scores[i] - k - targetLength + c + queryLength) {
reduce = false;
break;
}
r--;
}
if (!reduce) break;
firstBlock++;
}
}
// If band stops to exist finish
if (lastBlock < firstBlock) {
*bestScore_ = *position_ = -1;
delete[] blocks;
return EDLIB_STATUS_OK;
}
//------------------------------------------------------------------//
//---- Save column so it can be used for reconstruction ----//
if (findAlignment && c < targetLength) {
bl = blocks + firstBlock;
for (int b = firstBlock; b <= lastBlock; b++) {
(*alignData)->Ps[maxNumBlocks * c + b] = bl->P;
(*alignData)->Ms[maxNumBlocks * c + b] = bl->M;
(*alignData)->scores[maxNumBlocks * c + b] = bl->score;
(*alignData)->firstBlocks[c] = firstBlock;
(*alignData)->lastBlocks[c] = lastBlock;
bl++;
}
}
//----------------------------------------------------------//
//---- If this is stop column, save it and finish ----//
if (c == targetStopPosition) {
for (int b = firstBlock; b <= lastBlock; b++) {
(*alignData)->Ps[b] = (blocks + b)->P;
(*alignData)->Ms[b] = (blocks + b)->M;
(*alignData)->scores[b] = (blocks + b)->score;
(*alignData)->firstBlocks[0] = firstBlock;
(*alignData)->lastBlocks[0] = lastBlock;
}
*bestScore_ = -1;
*position_ = targetStopPosition;
delete[] blocks;
return EDLIB_STATUS_OK;
}
//----------------------------------------------------//
targetChar++;
}
if (lastBlock == maxNumBlocks - 1) { // If last block of last column was calculated
// Obtain best score from block -> it is complicated because query is padded with W cells
int bestScore = getBlockCellValues(blocks[lastBlock])[W];
if (bestScore <= k) {
*bestScore_ = bestScore;
*position_ = targetLength - 1;
delete[] blocks;
return EDLIB_STATUS_OK;
}
}
*bestScore_ = *position_ = -1;
delete[] blocks;
return EDLIB_STATUS_OK;
}
/**
* Finds one possible alignment that gives optimal score by moving back through the dynamic programming matrix,
* that is stored in alignData. Consumes large amount of memory: O(queryLength * targetLength).
* @param [in] queryLength Normal length, without W.
* @param [in] targetLength Normal length, without W.
* @param [in] bestScore Best score.
* @param [in] alignData Data obtained during finding best score that is useful for finding alignment.
* @param [out] alignment Alignment.
* @param [out] alignmentLength Length of alignment.
* @return Status code.
*/
static int obtainAlignmentTraceback(const int queryLength, const int targetLength,
const int bestScore, const AlignmentData* alignData,
unsigned char** alignment, int* alignmentLength) {
const int maxNumBlocks = ceilDiv(queryLength, WORD_SIZE);
const int W = maxNumBlocks * WORD_SIZE - queryLength;
*alignment = (unsigned char*) malloc((queryLength + targetLength - 1) * sizeof(unsigned char));
*alignmentLength = 0;
int c = targetLength - 1; // index of column
int b = maxNumBlocks - 1; // index of block in column
int currScore = bestScore; // Score of current cell
int lScore = -1; // Score of left cell
int uScore = -1; // Score of upper cell
int ulScore = -1; // Score of upper left cell
Word currP = alignData->Ps[c * maxNumBlocks + b]; // P of current block
Word currM = alignData->Ms[c * maxNumBlocks + b]; // M of current block
// True if block to left exists and is in band
bool thereIsLeftBlock = c > 0 && b >= alignData->firstBlocks[c-1] && b <= alignData->lastBlocks[c-1];
Word lP, lM;
if (thereIsLeftBlock) {
lP = alignData->Ps[(c - 1) * maxNumBlocks + b]; // P of block to the left
lM = alignData->Ms[(c - 1) * maxNumBlocks + b]; // M of block to the left
}
currP <<= W;
currM <<= W;
int blockPos = WORD_SIZE - W - 1; // 0 based index of current cell in blockPos
if (c == 0) {
thereIsLeftBlock = true;
lScore = b * WORD_SIZE + blockPos + 1;
ulScore = lScore - 1;
}
while (true) {
// TODO: improvement: calculate only those cells that are needed,
// for example if I calculate upper cell and can move up,
// there is no need to calculate left and upper left cell
//---------- Calculate scores ---------//
if (lScore == -1 && thereIsLeftBlock) {
lScore = alignData->scores[(c - 1) * maxNumBlocks + b]; // score of block to the left
for (int i = 0; i < WORD_SIZE - blockPos - 1; i++) {
if (lP & HIGH_BIT_MASK) lScore--;
if (lM & HIGH_BIT_MASK) lScore++;
lP <<= 1;
lM <<= 1;
}
}
if (ulScore == -1) {
if (lScore != -1) {
ulScore = lScore;
if (lP & HIGH_BIT_MASK) ulScore--;
if (lM & HIGH_BIT_MASK) ulScore++;
}
else if (c > 0 && b-1 >= alignData->firstBlocks[c-1] && b-1 <= alignData->lastBlocks[c-1]) {
// This is the case when upper left cell is last cell in block,
// and block to left is not in band so lScore is -1.
ulScore = alignData->scores[(c - 1) * maxNumBlocks + b - 1];
}
}
if (uScore == -1) {
uScore = currScore;
if (currP & HIGH_BIT_MASK) uScore--;
if (currM & HIGH_BIT_MASK) uScore++;
currP <<= 1;
currM <<= 1;
}
//-------------------------------------//
// TODO: should I check if there is upper block?
//-------------- Move --------------//
// Move up - insertion to target - deletion from query
if (uScore != -1 && uScore + 1 == currScore) {
currScore = uScore;
lScore = ulScore;
uScore = ulScore = -1;
if (blockPos == 0) { // If entering new (upper) block
if (b == 0) { // If there are no cells above (only boundary cells)
(*alignment)[(*alignmentLength)++] = EDLIB_EDOP_INSERT; // Move up
for (int i = 0; i < c + 1; i++) // Move left until end
(*alignment)[(*alignmentLength)++] = EDLIB_EDOP_DELETE;
break;
} else {
blockPos = WORD_SIZE - 1;
b--;
currP = alignData->Ps[c * maxNumBlocks + b];
currM = alignData->Ms[c * maxNumBlocks + b];
if (c > 0 && b >= alignData->firstBlocks[c-1] && b <= alignData->lastBlocks[c-1]) {
thereIsLeftBlock = true;
lP = alignData->Ps[(c - 1) * maxNumBlocks + b]; // TODO: improve this, too many operations
lM = alignData->Ms[(c - 1) * maxNumBlocks + b];
} else {
thereIsLeftBlock = false;
}
}
} else {
blockPos--;
lP <<= 1;
lM <<= 1;
}
// Mark move
(*alignment)[(*alignmentLength)++] = EDLIB_EDOP_INSERT;
}
// Move left - deletion from target - insertion to query
else if (lScore != -1 && lScore + 1 == currScore) {
currScore = lScore;
uScore = ulScore;
lScore = ulScore = -1;
c--;
if (c == -1) { // If there are no cells to the left (only boundary cells)
(*alignment)[(*alignmentLength)++] = EDLIB_EDOP_DELETE; // Move left
int numUp = b * WORD_SIZE + blockPos + 1;
for (int i = 0; i < numUp; i++) // Move up until end
(*alignment)[(*alignmentLength)++] = EDLIB_EDOP_INSERT;
break;
}
currP = lP;
currM = lM;
if (c > 0 && b >= alignData->firstBlocks[c-1] && b <= alignData->lastBlocks[c-1]) {
thereIsLeftBlock = true;
lP = alignData->Ps[(c - 1) * maxNumBlocks + b];
lM = alignData->Ms[(c - 1) * maxNumBlocks + b];
} else {
if (c == 0) { // If there are no cells to the left (only boundary cells)
thereIsLeftBlock = true;
lScore = b * WORD_SIZE + blockPos + 1;
ulScore = lScore - 1;
} else {
thereIsLeftBlock = false;
}
}
// Mark move
(*alignment)[(*alignmentLength)++] = EDLIB_EDOP_DELETE;
}
// Move up left - (mis)match
else if (ulScore != -1) {
unsigned char moveCode = ulScore == currScore ? EDLIB_EDOP_MATCH : EDLIB_EDOP_MISMATCH;
currScore = ulScore;
uScore = lScore = ulScore = -1;
c--;
if (c == -1) { // If there are no cells to the left (only boundary cells)
(*alignment)[(*alignmentLength)++] = moveCode; // Move left
int numUp = b * WORD_SIZE + blockPos;
for (int i = 0; i < numUp; i++) // Move up until end
(*alignment)[(*alignmentLength)++] = EDLIB_EDOP_INSERT;
break;
}
if (blockPos == 0) { // If entering upper left block
if (b == 0) { // If there are no more cells above (only boundary cells)
(*alignment)[(*alignmentLength)++] = moveCode; // Move up left
for (int i = 0; i < c + 1; i++) // Move left until end
(*alignment)[(*alignmentLength)++] = EDLIB_EDOP_DELETE;
break;
}
blockPos = WORD_SIZE - 1;
b--;
currP = alignData->Ps[c * maxNumBlocks + b];
currM = alignData->Ms[c * maxNumBlocks + b];
} else { // If entering left block
blockPos--;
currP = lP;
currM = lM;
currP <<= 1;
currM <<= 1;
}
// Set new left block
if (c > 0 && b >= alignData->firstBlocks[c-1] && b <= alignData->lastBlocks[c-1]) {
thereIsLeftBlock = true;
lP = alignData->Ps[(c - 1) * maxNumBlocks + b];
lM = alignData->Ms[(c - 1) * maxNumBlocks + b];
} else {
if (c == 0) { // If there are no cells to the left (only boundary cells)
thereIsLeftBlock = true;
lScore = b * WORD_SIZE + blockPos + 1;
ulScore = lScore - 1;
} else {
thereIsLeftBlock = false;
}
}
// Mark move
(*alignment)[(*alignmentLength)++] = moveCode;
} else {
// Reached end - finished!
break;
}