Debian Codegraph @

src/third-party/edlib/edlib.cpp

raw
1 #include <pbcopper/third-party/edlib.h>
2
3 #include <stdint.h>
4 #include <algorithm>
5 #include <cstdlib>
6 #include <cstring>
7 #include <string>
8 #include <vector>
9
10 using namespace std;
11
12 typedef uint64_t Word;
13 static const int WORD_SIZE = sizeof(Word) * 8; // Size of Word in bits
14 static const Word WORD_1 = static_cast<Word>(1);
15 static const Word HIGH_BIT_MASK = WORD_1 << (WORD_SIZE - 1); // 100..00
16 static const int MAX_UCHAR = 255;
17
18 // Data needed to find alignment.
19 struct AlignmentData
20 {
21 Word* Ps;
22 Word* Ms;
23 int* scores;
24 int* firstBlocks;
25 int* lastBlocks;
26
27 AlignmentData(int maxNumBlocks, int targetLength)
28 {
29 // We build a complete table and mark first and last block for each column
30 // (because algorithm is banded so only part of each columns is used).
31 // TODO: do not build a whole table, but just enough blocks for each column.
32 Ps = new Word[maxNumBlocks * targetLength];
33 Ms = new Word[maxNumBlocks * targetLength];
34 scores = new int[maxNumBlocks * targetLength];
35 firstBlocks = new int[targetLength];
36 lastBlocks = new int[targetLength];
37 }
38
39 ~AlignmentData()
40 {
41 delete[] Ps;
42 delete[] Ms;
43 delete[] scores;
44 delete[] firstBlocks;
45 delete[] lastBlocks;
46 }
47 };
48
49 struct Block
50 {
51 Word P; // Pvin
52 Word M; // Mvin
53 int score; // score of last cell in block;
54
55 Block() {}
56 Block(Word p, Word m, int s) : P(p), M(m), score(s) {}
57 };
58
59 /**
60 * Defines equality relation on alphabet characters.
61 * By default each character is always equal only to itself, but you can also provide additional equalities.
62 */
63 class EqualityDefinition
64 {
65 private:
66 bool matrix[MAX_UCHAR + 1][MAX_UCHAR + 1];
67
68 public:
69 EqualityDefinition(const string& alphabet, const EdlibEqualityPair* additionalEqualities = NULL,
70 const int additionalEqualitiesLength = 0)
71 {
72 for (int i = 0; i < static_cast<int>(alphabet.size()); i++) {
73 for (int j = 0; j < static_cast<int>(alphabet.size()); j++) {
74 matrix[i][j] = (i == j);
75 }
76 }
77 if (additionalEqualities != NULL) {
78 for (int i = 0; i < additionalEqualitiesLength; i++) {
79 size_t firstTransformed = alphabet.find(additionalEqualities[i].first);
80 size_t secondTransformed = alphabet.find(additionalEqualities[i].second);
81 if (firstTransformed != string::npos && secondTransformed != string::npos) {
82 matrix[firstTransformed][secondTransformed] =
83 matrix[secondTransformed][firstTransformed] = true;
84 }
85 }
86 }
87 }
88
89 /**
90 * @param a Element from transformed sequence.
91 * @param b Element from transformed sequence.
92 * @return True if a and b are defined as equal, false otherwise.
93 */
94 bool areEqual(unsigned char a, unsigned char b) const { return matrix[a][b]; }
95 };
96
97 static int myersCalcEditDistanceSemiGlobal(const Word* Peq, int W, int maxNumBlocks,
98 int queryLength, const unsigned char* target,
99 int targetLength, int k, EdlibAlignMode mode,
100 int* bestScore_, int** positions_, int* numPositions_);
101
102 static int myersCalcEditDistanceNW(const Word* Peq, int W, int maxNumBlocks, int queryLength,
103 const unsigned char* target, int targetLength, int k,
104 int* bestScore_, int* position_, bool findAlignment,
105 AlignmentData** alignData, int targetStopPosition);
106
107 static int obtainAlignment(const unsigned char* query, const unsigned char* rQuery, int queryLength,
108 const unsigned char* target, const unsigned char* rTarget,
109 int targetLength, const EqualityDefinition& equalityDefinition,
110 int alphabetLength, int bestScore, unsigned char** alignment,
111 int* alignmentLength);
112
113 static int obtainAlignmentHirschberg(const unsigned char* query, const unsigned char* rQuery,
114 int queryLength, const unsigned char* target,
115 const unsigned char* rTarget, int targetLength,
116 const EqualityDefinition& equalityDefinition,
117 int alphabetLength, int bestScore, unsigned char** alignment,
118 int* alignmentLength);
119
120 static int obtainAlignmentTraceback(int queryLength, int targetLength, int bestScore,
121 const AlignmentData* alignData, unsigned char** alignment,
122 int* alignmentLength);
123
124 static string transformSequences(const char* queryOriginal, int queryLength,
125 const char* targetOriginal, int targetLength,
126 unsigned char** queryTransformed,
127 unsigned char** targetTransformed);
128
129 static inline int ceilDiv(int x, int y);
130
131 static inline unsigned char* createReverseCopy(const unsigned char* seq, int length);
132
133 static inline Word* buildPeq(const int alphabetLength, const unsigned char* query,
134 const int queryLength, const EqualityDefinition& equalityDefinition);
135
136 /**
137 * Main edlib method.
138 */
139 extern "C" EdlibAlignResult edlibAlign(const char* const queryOriginal, const int queryLength,
140 const char* const targetOriginal, const int targetLength,
141 const EdlibAlignConfig config)
142 {
143 EdlibAlignResult result;
144 result.status = EDLIB_STATUS_OK;
145 result.editDistance = -1;
146 result.endLocations = result.startLocations = NULL;
147 result.numLocations = 0;
148 result.alignment = NULL;
149 result.alignmentLength = 0;
150 result.alphabetLength = 0;
151
152 /*------------ TRANSFORM SEQUENCES AND RECOGNIZE ALPHABET -----------*/
153 unsigned char *query, *target;
154 string alphabet = transformSequences(queryOriginal, queryLength, targetOriginal, targetLength,
155 &query, &target);
156 result.alphabetLength = static_cast<int>(alphabet.size());
157 /*-------------------------------------------------------*/
158
159 /*--------------------- INITIALIZATION ------------------*/
160 int maxNumBlocks = ceilDiv(queryLength, WORD_SIZE); // bmax in Myers
161 int W =
162 maxNumBlocks * WORD_SIZE - queryLength; // number of redundant cells in last level blocks
163 EqualityDefinition equalityDefinition(alphabet, config.additionalEqualities,
164 config.additionalEqualitiesLength);
165 Word* Peq = buildPeq(static_cast<int>(alphabet.size()), query, queryLength, equalityDefinition);
166 /*-------------------------------------------------------*/
167
168 /*------------------ MAIN CALCULATION -------------------*/
169 // TODO: Store alignment data only after k is determined? That could make things faster.
170 int positionNW; // Used only when mode is NW.
171 AlignmentData* alignData = NULL;
172 bool dynamicK = false;
173 int k = config.k;
174 if (k < 0) { // If valid k is not given, auto-adjust k until solution is found.
175 dynamicK = true;
176 k = WORD_SIZE; // Gives better results than smaller k.
177 }
178
179 do {
180 if (config.mode == EDLIB_MODE_HW || config.mode == EDLIB_MODE_SHW) {
181 myersCalcEditDistanceSemiGlobal(Peq, W, maxNumBlocks, queryLength, target, targetLength,
182 k, config.mode, &(result.editDistance),
183 &(result.endLocations), &(result.numLocations));
184 } else { // mode == EDLIB_MODE_NW
185 myersCalcEditDistanceNW(Peq, W, maxNumBlocks, queryLength, target, targetLength, k,
186 &(result.editDistance), &positionNW, false, &alignData, -1);
187 }
188 k *= 2;
189 } while (dynamicK && result.editDistance == -1);
190
191 if (result.editDistance >= 0) { // If there is solution.
192 // If NW mode, set end location explicitly.
193 if (config.mode == EDLIB_MODE_NW) {
194 result.endLocations = static_cast<int*>(malloc(sizeof(int) * 1));
195 result.endLocations[0] = targetLength - 1;
196 result.numLocations = 1;
197 }
198
199 // Find starting locations.
200 if (config.task == EDLIB_TASK_LOC || config.task == EDLIB_TASK_PATH) {
201 result.startLocations = static_cast<int*>(malloc(result.numLocations * sizeof(int)));
202 if (config.mode == EDLIB_MODE_HW) { // If HW, I need to calculate start locations.
203 const unsigned char* rTarget = createReverseCopy(target, targetLength);
204 const unsigned char* rQuery = createReverseCopy(query, queryLength);
205 // Peq for reversed query.
206 Word* rPeq = buildPeq(static_cast<int>(alphabet.size()), rQuery, queryLength,
207 equalityDefinition);
208 for (int i = 0; i < result.numLocations; i++) {
209 int endLocation = result.endLocations[i];
210 if (endLocation == -1) {
211 // NOTE: Sometimes one of optimal solutions is that query starts before target, like this:
212 // AAGG <- target
213 // CCTT <- query
214 // It will never be only optimal solution and it does not happen often, however it is
215 // possible and in that case end location will be -1. What should we do with that?
216 // Should we just skip reporting such end location, although it is a solution?
217 // If we do report it, what is the start location? -4? -1? Nothing?
218 // TODO: Figure this out. This has to do in general with how we think about start
219 // and end locations.
220 // Also, we have alignment later relying on this locations to limit the space of it's
221 // search -> how can it do it right if these locations are negative or incorrect?
222 result.startLocations[i] =
223 0; // I put 0 for now, but it does not make much sense.
224 } else {
225 int bestScoreSHW, numPositionsSHW;
226 int* positionsSHW;
227 myersCalcEditDistanceSemiGlobal(rPeq, W, maxNumBlocks, queryLength,
228 rTarget + targetLength - endLocation - 1,
229 endLocation + 1, result.editDistance,
230 EDLIB_MODE_SHW, &bestScoreSHW,
231 &positionsSHW, &numPositionsSHW);
232 // Taking last location as start ensures that alignment will not start with insertions
233 // if it can start with mismatches instead.
234 result.startLocations[i] = endLocation - positionsSHW[numPositionsSHW - 1];
235 free(positionsSHW);
236 }
237 }
238 delete[] rTarget;
239 delete[] rQuery;
240 delete[] rPeq;
241 } else { // If mode is SHW or NW
242 for (int i = 0; i < result.numLocations; i++) {
243 result.startLocations[i] = 0;
244 }
245 }
246 }
247
248 // Find alignment -> all comes down to finding alignment for NW.
249 // Currently we return alignment only for first pair of locations.
250 if (config.task == EDLIB_TASK_PATH) {
251 int alnStartLocation = result.startLocations[0];
252 int alnEndLocation = result.endLocations[0];
253 const unsigned char* alnTarget = target + alnStartLocation;
254 const int alnTargetLength = alnEndLocation - alnStartLocation + 1;
255 const unsigned char* rAlnTarget = createReverseCopy(alnTarget, alnTargetLength);
256 const unsigned char* rQuery = createReverseCopy(query, queryLength);
257 obtainAlignment(query, rQuery, queryLength, alnTarget, rAlnTarget, alnTargetLength,
258 equalityDefinition, static_cast<int>(alphabet.size()),
259 result.editDistance, &(result.alignment), &(result.alignmentLength));
260 delete[] rAlnTarget;
261 delete[] rQuery;
262 }
263 }
264 /*-------------------------------------------------------*/
265
266 //--- Free memory ---//
267 delete[] Peq;
268 free(query);
269 free(target);
270 if (alignData) delete alignData;
271 //-------------------//
272
273 return result;
274 }
275
276 extern "C" char* edlibAlignmentToCigar(const unsigned char* const alignment,
277 const int alignmentLength,
278 const EdlibCigarFormat cigarFormat)
279 {
280 if (cigarFormat != EDLIB_CIGAR_EXTENDED && cigarFormat != EDLIB_CIGAR_STANDARD) {
281 return 0;
282 }
283
284 // Maps move code from alignment to char in cigar.
285 // 0 1 2 3
286 char moveCodeToChar[] = {'=', 'I', 'D', 'X'};
287 if (cigarFormat == EDLIB_CIGAR_STANDARD) {
288 moveCodeToChar[0] = moveCodeToChar[3] = 'M';
289 }
290
291 vector<char>* cigar = new vector<char>();
292 char lastMove = 0; // Char of last move. 0 if there was no previous move.
293 int numOfSameMoves = 0;
294 for (int i = 0; i <= alignmentLength; i++) {
295 // if new sequence of same moves started
296 if (i == alignmentLength || (moveCodeToChar[alignment[i]] != lastMove && lastMove != 0)) {
297 // Write number of moves to cigar string.
298 int numDigits = 0;
299 for (; numOfSameMoves; numOfSameMoves /= 10) {
300 cigar->push_back('0' + numOfSameMoves % 10);
301 numDigits++;
302 }
303 reverse(cigar->end() - numDigits, cigar->end());
304 // Write code of move to cigar string.
305 cigar->push_back(lastMove);
306 // If not at the end, start new sequence of moves.
307 if (i < alignmentLength) {
308 // Check if alignment has valid values.
309 if (alignment[i] > 3) {
310 delete cigar;
311 return 0;
312 }
313 numOfSameMoves = 0;
314 }
315 }
316 if (i < alignmentLength) {
317 lastMove = moveCodeToChar[alignment[i]];
318 numOfSameMoves++;
319 }
320 }
321 cigar->push_back(0); // Null character termination.
322 char* cigar_ = static_cast<char*>(malloc(cigar->size() * sizeof(char)));
323 memcpy(cigar_, &(*cigar)[0], cigar->size() * sizeof(char));
324 delete cigar;
325
326 return cigar_;
327 }
328
329 /**
330 * Build Peq table for given query and alphabet.
331 * Peq is table of dimensions alphabetLength+1 x maxNumBlocks.
332 * 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.
333 * NOTICE: free returned array with delete[]!
334 */
335 static inline Word* buildPeq(const int alphabetLength, const unsigned char* const query,
336 const int queryLength, const EqualityDefinition& equalityDefinition)
337 {
338 int maxNumBlocks = ceilDiv(queryLength, WORD_SIZE);
339 // table of dimensions alphabetLength+1 x maxNumBlocks. Last symbol is wildcard.
340 Word* Peq = new Word[(alphabetLength + 1) * maxNumBlocks];
341
342 // Build Peq (1 is match, 0 is mismatch). NOTE: last column is wildcard(symbol that matches anything) with just 1s
343 for (unsigned char symbol = 0; symbol <= alphabetLength; symbol++) {
344 for (int b = 0; b < maxNumBlocks; b++) {
345 if (symbol < alphabetLength) {
346 Peq[symbol * maxNumBlocks + b] = 0;
347 for (int r = (b + 1) * WORD_SIZE - 1; r >= b * WORD_SIZE; r--) {
348 Peq[symbol * maxNumBlocks + b] <<= 1;
349 // NOTE: We pretend like query is padded at the end with W wildcard symbols
350 if (r >= queryLength || equalityDefinition.areEqual(query[r], symbol))
351 Peq[symbol * maxNumBlocks + b] += 1;
352 }
353 } else { // Last symbol is wildcard, so it is all 1s
354 Peq[symbol * maxNumBlocks + b] = static_cast<Word>(-1);
355 }
356 }
357 }
358
359 return Peq;
360 }
361
362 /**
363 * Returns new sequence that is reverse of given sequence.
364 * Free returned array with delete[].
365 */
366 static inline unsigned char* createReverseCopy(const unsigned char* const seq, const int length)
367 {
368 unsigned char* rSeq = new unsigned char[length];
369 for (int i = 0; i < length; i++) {
370 rSeq[i] = seq[length - i - 1];
371 }
372 return rSeq;
373 }
374
375 /**
376 * Corresponds to Advance_Block function from Myers.
377 * Calculates one word(block), which is part of a column.
378 * Highest bit of word (one most to the left) is most bottom cell of block from column.
379 * Pv[i] and Mv[i] define vin of cell[i]: vin = cell[i] - cell[i-1].
380 * @param [in] Pv Bitset, Pv[i] == 1 if vin is +1, otherwise Pv[i] == 0.
381 * @param [in] Mv Bitset, Mv[i] == 1 if vin is -1, otherwise Mv[i] == 0.
382 * @param [in] Eq Bitset, Eq[i] == 1 if match, 0 if mismatch.
383 * @param [in] hin Will be +1, 0 or -1.
384 * @param [out] PvOut Bitset, PvOut[i] == 1 if vout is +1, otherwise PvOut[i] == 0.
385 * @param [out] MvOut Bitset, MvOut[i] == 1 if vout is -1, otherwise MvOut[i] == 0.
386 * @param [out] hout Will be +1, 0 or -1.
387 */
388 static inline int calculateBlock(Word Pv, Word Mv, Word Eq, const int hin, Word& PvOut, Word& MvOut)
389 {
390 // hin can be 1, -1 or 0.
391 // 1 -> 00...01
392 // 0 -> 00...00
393 // -1 -> 11...11 (2-complement)
394
395 Word hinIsNeg =
396 static_cast<Word>(hin >> 2) & WORD_1; // 00...001 if hin is -1, 00...000 if 0 or 1
397
398 Word Xv = Eq | Mv;
399 // This is instruction below written using 'if': if (hin < 0) Eq |= (Word)1;
400 Eq |= hinIsNeg;
401 Word Xh = (((Eq & Pv) + Pv) ^ Pv) | Eq;
402
403 Word Ph = Mv | ~(Xh | Pv);
404 Word Mh = Pv & Xh;
405
406 int hout = 0;
407 // This is instruction below written using 'if': if (Ph & HIGH_BIT_MASK) hout = 1;
408 hout = (Ph & HIGH_BIT_MASK) >> (WORD_SIZE - 1);
409 // This is instruction below written using 'if': if (Mh & HIGH_BIT_MASK) hout = -1;
410 hout -= (Mh & HIGH_BIT_MASK) >> (WORD_SIZE - 1);
411
412 Ph <<= 1;
413 Mh <<= 1;
414
415 // This is instruction below written using 'if': if (hin < 0) Mh |= (Word)1;
416 Mh |= hinIsNeg;
417 // This is instruction below written using 'if': if (hin > 0) Ph |= (Word)1;
418 Ph |= static_cast<Word>((hin + 1) >> 1);
419
420 PvOut = Mh | ~(Xv | Ph);
421 MvOut = Ph & Xv;
422
423 return hout;
424 }
425
426 /**
427 * Does ceiling division x / y.
428 * Note: x and y must be non-negative and x + y must not overflow.
429 */
430 static inline int ceilDiv(const int x, const int y) { return x % y ? x / y + 1 : x / y; }
431
432 static inline int min(const int x, const int y) { return x < y ? x : y; }
433
434 static inline int max(const int x, const int y) { return x > y ? x : y; }
435
436 /**
437 * @param [in] block
438 * @return Values of cells in block, starting with bottom cell in block.
439 */
440 static inline vector<int> getBlockCellValues(const Block block)
441 {
442 vector<int> scores(WORD_SIZE);
443 int score = block.score;
444 Word mask = HIGH_BIT_MASK;
445 for (int i = 0; i < WORD_SIZE - 1; i++) {
446 scores[i] = score;
447 if (block.P & mask) score--;
448 if (block.M & mask) score++;
449 mask >>= 1;
450 }
451 scores[WORD_SIZE - 1] = score;
452 return scores;
453 }
454
455 /**
456 * Writes values of cells in block into given array, starting with first/top cell.
457 * @param [in] block
458 * @param [out] dest Array into which cell values are written. Must have size of at least WORD_SIZE.
459 */
460 static inline void readBlock(const Block block, int* const dest)
461 {
462 int score = block.score;
463 Word mask = HIGH_BIT_MASK;
464 for (int i = 0; i < WORD_SIZE - 1; i++) {
465 dest[WORD_SIZE - 1 - i] = score;
466 if (block.P & mask) score--;
467 if (block.M & mask) score++;
468 mask >>= 1;
469 }
470 dest[0] = score;
471 }
472
473 /**
474 * Writes values of cells in block into given array, starting with last/bottom cell.
475 * @param [in] block
476 * @param [out] dest Array into which cell values are written. Must have size of at least WORD_SIZE.
477 */
478 static inline void readBlockReverse(const Block block, int* const dest)
479 {
480 int score = block.score;
481 Word mask = HIGH_BIT_MASK;
482 for (int i = 0; i < WORD_SIZE - 1; i++) {
483 dest[i] = score;
484 if (block.P & mask) score--;
485 if (block.M & mask) score++;
486 mask >>= 1;
487 }
488 dest[WORD_SIZE - 1] = score;
489 }
490
491 /**
492 * @param [in] block
493 * @param [in] k
494 * @return True if all cells in block have value larger than k, otherwise false.
495 */
496 static inline bool allBlockCellsLarger(const Block block, const int k)
497 {
498 vector<int> scores = getBlockCellValues(block);
499 for (int i = 0; i < WORD_SIZE; i++) {
500 if (scores[i] <= k) return false;
501 }
502 return true;
503 }
504
505 /**
506 * Uses Myers' bit-vector algorithm to find edit distance for one of semi-global alignment methods.
507 * @param [in] Peq Query profile.
508 * @param [in] W Size of padding in last block.
509 * TODO: Calculate this directly from query, instead of passing it.
510 * @param [in] maxNumBlocks Number of blocks needed to cover the whole query.
511 * TODO: Calculate this directly from query, instead of passing it.
512 * @param [in] queryLength
513 * @param [in] target
514 * @param [in] targetLength
515 * @param [in] k
516 * @param [in] mode EDLIB_MODE_HW or EDLIB_MODE_SHW
517 * @param [out] bestScore_ Edit distance.
518 * @param [out] positions_ Array of 0-indexed positions in target at which best score was found.
519 Make sure to free this array with free().
520 * @param [out] numPositions_ Number of positions in the positions_ array.
521 * @return Status.
522 */
523 static int myersCalcEditDistanceSemiGlobal(const Word* const Peq, const int W,
524 const int maxNumBlocks, const int queryLength,
525 const unsigned char* const target,
526 const int targetLength, int k, const EdlibAlignMode mode,
527 int* const bestScore_, int** const positions_,
528 int* const numPositions_)
529 {
530 *positions_ = NULL;
531 *numPositions_ = 0;
532
533 // firstBlock is 0-based index of first block in Ukkonen band.
534 // lastBlock is 0-based index of last block in Ukkonen band.
535 int firstBlock = 0;
536 int lastBlock = min(ceilDiv(k + 1, WORD_SIZE), maxNumBlocks) - 1; // y in Myers
537 Block* bl; // Current block
538
539 Block* blocks = new Block[maxNumBlocks];
540
541 // For HW, solution will never be larger then queryLength.
542 if (mode == EDLIB_MODE_HW) {
543 k = min(queryLength, k);
544 }
545
546 // Each STRONG_REDUCE_NUM column is reduced in more expensive way.
547 // This gives speed up of about 2 times for small k.
548 const int STRONG_REDUCE_NUM = 2048;
549
550 // Initialize P, M and score
551 bl = blocks;
552 for (int b = 0; b <= lastBlock; b++) {
553 bl->score = (b + 1) * WORD_SIZE;
554 bl->P = static_cast<Word>(-1); // All 1s
555 bl->M = static_cast<Word>(0);
556 bl++;
557 }
558
559 int bestScore = -1;
560 vector<int> positions; // TODO: Maybe put this on heap?
561 const int startHout =
562 mode == EDLIB_MODE_HW ? 0 : 1; // If 0 then gap before query is not penalized;
563 const unsigned char* targetChar = target;
564 for (int c = 0; c < targetLength; c++) { // for each column
565 const Word* Peq_c = Peq + (*targetChar) * maxNumBlocks;
566
567 //----------------------- Calculate column -------------------------//
568 int hout = startHout;
569 bl = blocks + firstBlock;
570 Peq_c += firstBlock;
571 for (int b = firstBlock; b <= lastBlock; b++) {
572 hout = calculateBlock(bl->P, bl->M, *Peq_c, hout, bl->P, bl->M);
573 bl->score += hout;
574 bl++;
575 Peq_c++;
576 }
577 bl--;
578 Peq_c--;
579 //------------------------------------------------------------------//
580
581 //---------- Adjust number of blocks according to Ukkonen ----------//
582 if ((lastBlock < maxNumBlocks - 1) &&
583 (bl->score - hout <= k) // bl is pointing to last block
584 && ((*(Peq_c + 1) & WORD_1) || hout < 0)) { // Peq_c is pointing to last block
585 // If score of left block is not too big, calculate one more block
586 lastBlock++;
587 bl++;
588 Peq_c++;
589 bl->P = static_cast<Word>(-1); // All 1s
590 bl->M = static_cast<Word>(0);
591 bl->score = (bl - 1)->score - hout + WORD_SIZE +
592 calculateBlock(bl->P, bl->M, *Peq_c, hout, bl->P, bl->M);
593 } else {
594 while (lastBlock >= firstBlock && bl->score >= k + WORD_SIZE) {
595 lastBlock--;
596 bl--;
597 Peq_c--;
598 }
599 }
600
601 // Every some columns, do some expensive but also more efficient block reducing.
602 // This is important!
603 //
604 // Reduce the band by decreasing last block if possible.
605 if (c % STRONG_REDUCE_NUM == 0) {
606 while (lastBlock >= 0 && lastBlock >= firstBlock && allBlockCellsLarger(*bl, k)) {
607 lastBlock--;
608 bl--;
609 Peq_c--;
610 }
611 }
612 // For HW, even if all cells are > k, there still may be solution in next
613 // column because starting conditions at upper boundary are 0.
614 // That means that first block is always candidate for solution,
615 // and we can never end calculation before last column.
616 if (mode == EDLIB_MODE_HW && lastBlock == -1) {
617 lastBlock++;
618 bl++;
619 Peq_c++;
620 }
621
622 // Reduce band by increasing first block if possible. Not applicable to HW.
623 if (mode != EDLIB_MODE_HW) {
624 while (firstBlock <= lastBlock && blocks[firstBlock].score >= k + WORD_SIZE) {
625 firstBlock++;
626 }
627 if (c % STRONG_REDUCE_NUM == 0) { // Do strong reduction every some blocks
628 while (firstBlock <= lastBlock && allBlockCellsLarger(blocks[firstBlock], k)) {
629 firstBlock++;
630 }
631 }
632 }
633
634 // If band stops to exist finish
635 if (lastBlock < firstBlock) {
636 *bestScore_ = bestScore;
637 if (bestScore != -1) {
638 *positions_ =
639 static_cast<int*>(malloc(sizeof(int) * static_cast<int>(positions.size())));
640 *numPositions_ = static_cast<int>(positions.size());
641 copy(positions.begin(), positions.end(), *positions_);
642 }
643 delete[] blocks;
644 return EDLIB_STATUS_OK;
645 }
646 //------------------------------------------------------------------//
647
648 //------------------------- Update best score ----------------------//
649 if (lastBlock == maxNumBlocks - 1) {
650 int colScore = bl->score;
651 if (colScore <=
652 k) { // Scores > k dont have correct values (so we cannot use them), but are certainly > k.
653 // NOTE: Score that I find in column c is actually score from column c-W
654 if (bestScore == -1 || colScore <= bestScore) {
655 if (colScore != bestScore) {
656 positions.clear();
657 bestScore = colScore;
658 // Change k so we will look only for equal or better
659 // scores then the best found so far.
660 k = bestScore;
661 }
662 positions.push_back(c - W);
663 }
664 }
665 }
666 //------------------------------------------------------------------//
667
668 targetChar++;
669 }
670
671 // Obtain results for last W columns from last column.
672 if (lastBlock == maxNumBlocks - 1) {
673 vector<int> blockScores = getBlockCellValues(*bl);
674 for (int i = 0; i < W; i++) {
675 int colScore = blockScores[i + 1];
676 if (colScore <= k && (bestScore == -1 || colScore <= bestScore)) {
677 if (colScore != bestScore) {
678 positions.clear();
679 k = bestScore = colScore;
680 }
681 positions.push_back(targetLength - W + i);
682 }
683 }
684 }
685
686 *bestScore_ = bestScore;
687 if (bestScore != -1) {
688 *positions_ = static_cast<int*>(malloc(sizeof(int) * static_cast<int>(positions.size())));
689 *numPositions_ = static_cast<int>(positions.size());
690 copy(positions.begin(), positions.end(), *positions_);
691 }
692
693 delete[] blocks;
694 return EDLIB_STATUS_OK;
695 }
696
697 /**
698 * Uses Myers' bit-vector algorithm to find edit distance for global(NW) alignment method.
699 * @param [in] Peq Query profile.
700 * @param [in] W Size of padding in last block.
701 * TODO: Calculate this directly from query, instead of passing it.
702 * @param [in] maxNumBlocks Number of blocks needed to cover the whole query.
703 * TODO: Calculate this directly from query, instead of passing it.
704 * @param [in] queryLength
705 * @param [in] target
706 * @param [in] targetLength
707 * @param [in] k
708 * @param [out] bestScore_ Edit distance.
709 * @param [out] position_ 0-indexed position in target at which best score was found.
710 * @param [in] findAlignment If true, whole matrix is remembered and alignment data is returned.
711 * Quadratic amount of memory is consumed.
712 * @param [out] alignData Data needed for alignment traceback (for reconstruction of alignment).
713 * Set only if findAlignment is set to true, otherwise it is NULL.
714 * Make sure to free this array using delete[].
715 * @param [out] targetStopPosition If set to -1, whole calculation is performed normally, as expected.
716 * If set to p, calculation is performed up to position p in target (inclusive)
717 * and column p is returned as the only column in alignData.
718 * @return Status.
719 */
720 static int myersCalcEditDistanceNW(const Word* const Peq, const int W, const int maxNumBlocks,
721 const int queryLength, const unsigned char* const target,
722 const int targetLength, int k, int* const bestScore_,
723 int* const position_, const bool findAlignment,
724 AlignmentData** const alignData, const int targetStopPosition)
725 {
726 if (targetStopPosition > -1 && findAlignment) {
727 // They can not be both set at the same time!
728 return EDLIB_STATUS_ERROR;
729 }
730
731 // Each STRONG_REDUCE_NUM column is reduced in more expensive way.
732 const int STRONG_REDUCE_NUM =
733 2048; // TODO: Choose this number dinamically (based on query and target lengths?), so it does not affect speed of computation
734
735 if (k < abs(targetLength - queryLength)) {
736 *bestScore_ = *position_ = -1;
737 return EDLIB_STATUS_OK;
738 }
739
740 k = min(k, max(queryLength, targetLength)); // Upper bound for k
741
742 // firstBlock is 0-based index of first block in Ukkonen band.
743 // lastBlock is 0-based index of last block in Ukkonen band.
744 int firstBlock = 0;
745 // This is optimal now, by my formula.
746 int lastBlock =
747 min(maxNumBlocks, ceilDiv(min(k, (k + queryLength - targetLength) / 2) + 1, WORD_SIZE)) - 1;
748 Block* bl; // Current block
749
750 Block* blocks = new Block[maxNumBlocks];
751
752 // Initialize P, M and score
753 bl = blocks;
754 for (int b = 0; b <= lastBlock; b++) {
755 bl->score = (b + 1) * WORD_SIZE;
756 bl->P = static_cast<Word>(-1); // All 1s
757 bl->M = static_cast<Word>(0);
758 bl++;
759 }
760
761 // If we want to find alignment, we have to store needed data.
762 if (findAlignment)
763 *alignData = new AlignmentData(maxNumBlocks, targetLength);
764 else if (targetStopPosition > -1)
765 *alignData = new AlignmentData(maxNumBlocks, 1);
766 else
767 *alignData = NULL;
768
769 const unsigned char* targetChar = target;
770 for (int c = 0; c < targetLength; c++) { // for each column
771 const Word* Peq_c = Peq + *targetChar * maxNumBlocks;
772
773 //----------------------- Calculate column -------------------------//
774 int hout = 1;
775 bl = blocks + firstBlock;
776 for (int b = firstBlock; b <= lastBlock; b++) {
777 hout = calculateBlock(bl->P, bl->M, Peq_c[b], hout, bl->P, bl->M);
778 bl->score += hout;
779 bl++;
780 }
781 bl--;
782 //------------------------------------------------------------------//
783 // bl now points to last block
784
785 // Update k. I do it only on end of column because it would slow calculation too much otherwise.
786 // NOTICE: I add W when in last block because it is actually result from W cells to the left and W cells up.
787 k = min(k,
788 bl->score +
789 max(targetLength - c - 1, queryLength - ((1 + lastBlock) * WORD_SIZE - 1) - 1) +
790 (lastBlock == maxNumBlocks - 1 ? W : 0));
791
792 //---------- Adjust number of blocks according to Ukkonen ----------//
793 //--- Adjust last block ---//
794 // If block is not beneath band, calculate next block. Only next because others are certainly beneath band.
795 if (lastBlock + 1 < maxNumBlocks &&
796 !( //score[lastBlock] >= k + WORD_SIZE || // NOTICE: this condition could be satisfied if above block also!
797 ((lastBlock + 1) * WORD_SIZE - 1 >
798 k - bl->score + 2 * WORD_SIZE - 2 - targetLength + c + queryLength))) {
799 lastBlock++;
800 bl++;
801 bl->P = static_cast<Word>(-1); // All 1s
802 bl->M = static_cast<Word>(0);
803 int newHout = calculateBlock(bl->P, bl->M, Peq_c[lastBlock], hout, bl->P, bl->M);
804 bl->score = (bl - 1)->score - hout + WORD_SIZE + newHout;
805 hout = newHout;
806 }
807
808 // While block is out of band, move one block up.
809 // NOTE: Condition used here is more loose than the one from the article, since I simplified the max() part of it.
810 // I could consider adding that max part, for optimal performance.
811 while (lastBlock >= firstBlock &&
812 (bl->score >= k + WORD_SIZE ||
813 ((lastBlock + 1) * WORD_SIZE - 1 >
814 // TODO: Does not work if do not put +1! Why???
815 k - bl->score + 2 * WORD_SIZE - 2 - targetLength + c + queryLength + 1))) {
816 lastBlock--;
817 bl--;
818 }
819 //-------------------------//
820
821 //--- Adjust first block ---//
822 // While outside of band, advance block
823 while (firstBlock <= lastBlock &&
824 (blocks[firstBlock].score >= k + WORD_SIZE ||
825 ((firstBlock + 1) * WORD_SIZE - 1 <
826 blocks[firstBlock].score - k - targetLength + queryLength + c))) {
827 firstBlock++;
828 }
829 //--------------------------/
830
831 // TODO: consider if this part is useful, it does not seem to help much
832 if (c % STRONG_REDUCE_NUM ==
833 0) { // Every some columns do more expensive but more efficient reduction
834 while (lastBlock >= firstBlock) {
835 // If all cells outside of band, remove block
836 vector<int> scores = getBlockCellValues(*bl);
837 int numCells = lastBlock == maxNumBlocks - 1 ? WORD_SIZE - W : WORD_SIZE;
838 int r = lastBlock * WORD_SIZE + numCells - 1;
839 bool reduce = true;
840 for (int i = WORD_SIZE - numCells; i < WORD_SIZE; i++) {
841 // TODO: Does not work if do not put +1! Why???
842 if (scores[i] <= k && r <= k - scores[i] - targetLength + c + queryLength + 1) {
843 reduce = false;
844 break;
845 }
846 r--;
847 }
848 if (!reduce) break;
849 lastBlock--;
850 bl--;
851 }
852
853 while (firstBlock <= lastBlock) {
854 // If all cells outside of band, remove block
855 vector<int> scores = getBlockCellValues(blocks[firstBlock]);
856 int numCells = firstBlock == maxNumBlocks - 1 ? WORD_SIZE - W : WORD_SIZE;
857 int r = firstBlock * WORD_SIZE + numCells - 1;
858 bool reduce = true;
859 for (int i = WORD_SIZE - numCells; i < WORD_SIZE; i++) {
860 if (scores[i] <= k && r >= scores[i] - k - targetLength + c + queryLength) {
861 reduce = false;
862 break;
863 }
864 r--;
865 }
866 if (!reduce) break;
867 firstBlock++;
868 }
869 }
870
871 // If band stops to exist finish
872 if (lastBlock < firstBlock) {
873 *bestScore_ = *position_ = -1;
874 delete[] blocks;
875 return EDLIB_STATUS_OK;
876 }
877 //------------------------------------------------------------------//
878
879 //---- Save column so it can be used for reconstruction ----//
880 if (findAlignment && c < targetLength) {
881 bl = blocks + firstBlock;
882 for (int b = firstBlock; b <= lastBlock; b++) {
883 (*alignData)->Ps[maxNumBlocks * c + b] = bl->P;
884 (*alignData)->Ms[maxNumBlocks * c + b] = bl->M;
885 (*alignData)->scores[maxNumBlocks * c + b] = bl->score;
886 (*alignData)->firstBlocks[c] = firstBlock;
887 (*alignData)->lastBlocks[c] = lastBlock;
888 bl++;
889 }
890 }
891 //----------------------------------------------------------//
892 //---- If this is stop column, save it and finish ----//
893 if (c == targetStopPosition) {
894 for (int b = firstBlock; b <= lastBlock; b++) {
895 (*alignData)->Ps[b] = (blocks + b)->P;
896 (*alignData)->Ms[b] = (blocks + b)->M;
897 (*alignData)->scores[b] = (blocks + b)->score;
898 (*alignData)->firstBlocks[0] = firstBlock;
899 (*alignData)->lastBlocks[0] = lastBlock;
900 }
901 *bestScore_ = -1;
902 *position_ = targetStopPosition;
903 delete[] blocks;
904 return EDLIB_STATUS_OK;
905 }
906 //----------------------------------------------------//
907
908 targetChar++;
909 }
910
911 if (lastBlock == maxNumBlocks - 1) { // If last block of last column was calculated
912 // Obtain best score from block -> it is complicated because query is padded with W cells
913 int bestScore = getBlockCellValues(blocks[lastBlock])[W];
914 if (bestScore <= k) {
915 *bestScore_ = bestScore;
916 *position_ = targetLength - 1;
917 delete[] blocks;
918 return EDLIB_STATUS_OK;
919 }
920 }
921
922 *bestScore_ = *position_ = -1;
923 delete[] blocks;
924 return EDLIB_STATUS_OK;
925 }
926
927 /**
928 * Finds one possible alignment that gives optimal score by moving back through the dynamic programming matrix,
929 * that is stored in alignData. Consumes large amount of memory: O(queryLength * targetLength).
930 * @param [in] queryLength Normal length, without W.
931 * @param [in] targetLength Normal length, without W.
932 * @param [in] bestScore Best score.
933 * @param [in] alignData Data obtained during finding best score that is useful for finding alignment.
934 * @param [out] alignment Alignment.
935 * @param [out] alignmentLength Length of alignment.
936 * @return Status code.
937 */
938 static int obtainAlignmentTraceback(const int queryLength, const int targetLength,
939 const int bestScore, const AlignmentData* const alignData,
940 unsigned char** const alignment, int* const alignmentLength)
941 {
942 const int maxNumBlocks = ceilDiv(queryLength, WORD_SIZE);
943 const int W = maxNumBlocks * WORD_SIZE - queryLength;
944
945 *alignment = static_cast<unsigned char*>(
946 malloc((queryLength + targetLength - 1) * sizeof(unsigned char)));
947 *alignmentLength = 0;
948 int c = targetLength - 1; // index of column
949 int b = maxNumBlocks - 1; // index of block in column
950 int currScore = bestScore; // Score of current cell
951 int lScore = -1; // Score of left cell
952 int uScore = -1; // Score of upper cell
953 int ulScore = -1; // Score of upper left cell
954 Word currP = alignData->Ps[c * maxNumBlocks + b]; // P of current block
955 Word currM = alignData->Ms[c * maxNumBlocks + b]; // M of current block
956 // True if block to left exists and is in band
957 bool thereIsLeftBlock =
958 c > 0 && b >= alignData->firstBlocks[c - 1] && b <= alignData->lastBlocks[c - 1];
959 // We set initial values of lP and lM to 0 only to avoid compiler warnings, they should not affect the
960 // calculation as both lP and lM should be initialized at some moment later (but compiler can not
961 // detect it since this initialization is guaranteed by "business" logic).
962 Word lP = 0, lM = 0;
963 if (thereIsLeftBlock) {
964 lP = alignData->Ps[(c - 1) * maxNumBlocks + b]; // P of block to the left
965 lM = alignData->Ms[(c - 1) * maxNumBlocks + b]; // M of block to the left
966 }
967 currP <<= W;
968 currM <<= W;
969 int blockPos = WORD_SIZE - W - 1; // 0 based index of current cell in blockPos
970
971 // TODO(martin): refactor this whole piece of code. There are too many if-else statements,
972 // it is too easy for a bug to hide and to hard to effectively cover all the edge-cases.
973 // We need better separation of logic and responsibilities.
974 while (true) {
975 if (c == 0) {
976 thereIsLeftBlock = true;
977 lScore = b * WORD_SIZE + blockPos + 1;
978 ulScore = lScore - 1;
979 }
980
981 // TODO: improvement: calculate only those cells that are needed,
982 // for example if I calculate upper cell and can move up,
983 // there is no need to calculate left and upper left cell
984 //---------- Calculate scores ---------//
985 if (lScore == -1 && thereIsLeftBlock) {
986 lScore = alignData->scores[(c - 1) * maxNumBlocks + b]; // score of block to the left
987 for (int i = 0; i < WORD_SIZE - blockPos - 1; i++) {
988 if (lP & HIGH_BIT_MASK) lScore--;
989 if (lM & HIGH_BIT_MASK) lScore++;
990 lP <<= 1;
991 lM <<= 1;
992 }
993 }
994 if (ulScore == -1) {
995 if (lScore != -1) {
996 ulScore = lScore;
997 if (lP & HIGH_BIT_MASK) ulScore--;
998 if (lM & HIGH_BIT_MASK) ulScore++;
999 } else if (c > 0 && b - 1 >= alignData->firstBlocks[c - 1] &&
1000 b - 1 <= alignData->lastBlocks[c - 1]) {
1001 // This is the case when upper left cell is last cell in block,
1002 // and block to left is not in band so lScore is -1.
1003 ulScore = alignData->scores[(c - 1) * maxNumBlocks + b - 1];
1004 }
1005 }
1006 if (uScore == -1) {
1007 uScore = currScore;
1008 if (currP & HIGH_BIT_MASK) uScore--;
1009 if (currM & HIGH_BIT_MASK) uScore++;
1010 currP <<= 1;
1011 currM <<= 1;
1012 }
1013 //-------------------------------------//
1014
1015 // TODO: should I check if there is upper block?
1016
1017 //-------------- Move --------------//
1018 // Move up - insertion to target - deletion from query
1019 if (uScore != -1 && uScore + 1 == currScore) {
1020 currScore = uScore;
1021 lScore = ulScore;
1022 uScore = ulScore = -1;
1023 if (blockPos == 0) { // If entering new (upper) block
1024 if (b == 0) { // If there are no cells above (only boundary cells)
1025 (*alignment)[(*alignmentLength)++] = EDLIB_EDOP_INSERT; // Move up
1026 for (int i = 0; i < c + 1; i++) // Move left until end
1027 (*alignment)[(*alignmentLength)++] = EDLIB_EDOP_DELETE;
1028 break;
1029 } else {
1030 blockPos = WORD_SIZE - 1;
1031 b--;
1032 currP = alignData->Ps[c * maxNumBlocks + b];
1033 currM = alignData->Ms[c * maxNumBlocks + b];
1034 if (c > 0 && b >= alignData->firstBlocks[c - 1] &&
1035 b <= alignData->lastBlocks[c - 1]) {
1036 thereIsLeftBlock = true;
1037 lP = alignData->Ps[(c - 1) * maxNumBlocks +
1038 b]; // TODO: improve this, too many operations
1039 lM = alignData->Ms[(c - 1) * maxNumBlocks + b];
1040 } else {
1041 thereIsLeftBlock = false;
1042 // TODO(martin): There may not be left block, but there can be left boundary - do we
1043 // handle this correctly then? Are l and ul score set correctly? I should check that / refactor this.
1044 }
1045 }
1046 } else {
1047 blockPos--;
1048 lP <<= 1;
1049 lM <<= 1;
1050 }
1051 // Mark move
1052 (*alignment)[(*alignmentLength)++] = EDLIB_EDOP_INSERT;
1053 }
1054 // Move left - deletion from target - insertion to query
1055 else if (lScore != -1 && lScore + 1 == currScore) {
1056 currScore = lScore;
1057 uScore = ulScore;
1058 lScore = ulScore = -1;
1059 c--;
1060 if (c == -1) { // If there are no cells to the left (only boundary cells)
1061 (*alignment)[(*alignmentLength)++] = EDLIB_EDOP_DELETE; // Move left
1062 int numUp = b * WORD_SIZE + blockPos + 1;
1063 for (int i = 0; i < numUp; i++) // Move up until end
1064 (*alignment)[(*alignmentLength)++] = EDLIB_EDOP_INSERT;
1065 break;
1066 }
1067 currP = lP;
1068 currM = lM;
1069 if (c > 0 && b >= alignData->firstBlocks[c - 1] && b <= alignData->lastBlocks[c - 1]) {
1070 thereIsLeftBlock = true;
1071 lP = alignData->Ps[(c - 1) * maxNumBlocks + b];
1072 lM = alignData->Ms[(c - 1) * maxNumBlocks + b];
1073 } else {
1074 if (c == 0) { // If there are no cells to the left (only boundary cells)
1075 thereIsLeftBlock = true;
1076 lScore = b * WORD_SIZE + blockPos + 1;
1077 ulScore = lScore - 1;
1078 } else {
1079 thereIsLeftBlock = false;
1080 }
1081 }
1082 // Mark move
1083 (*alignment)[(*alignmentLength)++] = EDLIB_EDOP_DELETE;
1084 }
1085 // Move up left - (mis)match
1086 else if (ulScore != -1) {
1087 unsigned char moveCode = ulScore == currScore ? EDLIB_EDOP_MATCH : EDLIB_EDOP_MISMATCH;
1088 currScore = ulScore;
1089 uScore = lScore = ulScore = -1;
1090 c--;
1091 if (c == -1) { // If there are no cells to the left (only boundary cells)
1092 (*alignment)[(*alignmentLength)++] = moveCode; // Move left
1093 int numUp = b * WORD_SIZE + blockPos;
1094 for (int i = 0; i < numUp; i++) // Move up until end
1095 (*alignment)[(*alignmentLength)++] = EDLIB_EDOP_INSERT;
1096 break;
1097 }
1098 if (blockPos == 0) { // If entering upper left block
1099 if (b == 0) { // If there are no more cells above (only boundary cells)
1100 (*alignment)[(*alignmentLength)++] = moveCode; // Move up left
1101 for (int i = 0; i < c + 1; i++) // Move left until end
1102 (*alignment)[(*alignmentLength)++] = EDLIB_EDOP_DELETE;
1103 break;
1104 }
1105 blockPos = WORD_SIZE - 1;
1106 b--;
1107 currP = alignData->Ps[c * maxNumBlocks + b];
1108 currM = alignData->Ms[c * maxNumBlocks + b];
1109 } else { // If entering left block
1110 blockPos--;
1111 currP = lP;
1112 currM = lM;
1113 currP <<= 1;
1114 currM <<= 1;
1115 }
1116 // Set new left block
1117 if (c > 0 && b >= alignData->firstBlocks[c - 1] && b <= alignData->lastBlocks[c - 1]) {
1118 thereIsLeftBlock = true;
1119 lP = alignData->Ps[(c - 1) * maxNumBlocks + b];
1120 lM = alignData->Ms[(c - 1) * maxNumBlocks + b];
1121 } else {
1122 if (c == 0) { // If there are no cells to the left (only boundary cells)
1123 thereIsLeftBlock = true;
1124 lScore = b * WORD_SIZE + blockPos + 1;
1125 ulScore = lScore - 1;
1126 } else {
1127 thereIsLeftBlock = false;
1128 }
1129 }
1130 // Mark move
1131 (*alignment)[(*alignmentLength)++] = moveCode;
1132 } else {
1133 // Reached end - finished!
1134 break;
1135 }
1136 //----------------------------------//
1137 }
1138
1139 *alignment = static_cast<unsigned char*>(
1140 realloc(*alignment, (*alignmentLength) * sizeof(unsigned char)));
1141 reverse(*alignment, *alignment + (*alignmentLength));
1142 return EDLIB_STATUS_OK;
1143 }
1144
1145 /**
1146 * Finds one possible alignment that gives optimal score (bestScore).
1147 * It will split problem into smaller problems using Hirschberg's algorithm and when they are small enough,
1148 * it will solve them using traceback algorithm.
1149 * @param [in] query
1150 * @param [in] rQuery Reversed query.
1151 * @param [in] queryLength
1152 * @param [in] target
1153 * @param [in] rTarget Reversed target.
1154 * @param [in] targetLength
1155 * @param [in] equalityDefinition
1156 * @param [in] alphabetLength
1157 * @param [in] bestScore Best(optimal) score.
1158 * @param [out] alignment Sequence of edit operations that make target equal to query.
1159 * @param [out] alignmentLength Length of alignment.
1160 * @return Status code.
1161 */
1162 static int obtainAlignment(const unsigned char* const query, const unsigned char* const rQuery,
1163 const int queryLength, const unsigned char* const target,
1164 const unsigned char* const rTarget, const int targetLength,
1165 const EqualityDefinition& equalityDefinition, const int alphabetLength,
1166 const int bestScore, unsigned char** const alignment,
1167 int* const alignmentLength)
1168 {
1169
1170 // Handle special case when one of sequences has length of 0.
1171 if (queryLength == 0 || targetLength == 0) {
1172 *alignmentLength = targetLength + queryLength;
1173 *alignment =
1174 static_cast<unsigned char*>(malloc((*alignmentLength) * sizeof(unsigned char)));
1175 for (int i = 0; i < *alignmentLength; i++) {
1176 (*alignment)[i] = queryLength == 0 ? EDLIB_EDOP_DELETE : EDLIB_EDOP_INSERT;
1177 }
1178 return EDLIB_STATUS_OK;
1179 }
1180
1181 const int maxNumBlocks = ceilDiv(queryLength, WORD_SIZE);
1182 const int W = maxNumBlocks * WORD_SIZE - queryLength;
1183 int statusCode;
1184
1185 // TODO: think about reducing number of memory allocations in alignment functions, probably
1186 // by sharing some memory that is allocated only once. That refers to: Peq, columns in Hirschberg,
1187 // and it could also be done for alignments - we could have one big array for alignment that would be
1188 // sparsely populated by each of steps in recursion, and at the end we would just consolidate those results.
1189
1190 // If estimated memory consumption for traceback algorithm is smaller than 1MB use it,
1191 // otherwise use Hirschberg's algorithm. By running few tests I choose boundary of 1MB as optimal.
1192 long long alignmentDataSize = (2ll * sizeof(Word) + sizeof(int)) * maxNumBlocks * targetLength +
1193 2ll * sizeof(int) * targetLength;
1194 if (alignmentDataSize < 1024 * 1024) {
1195 int score_, endLocation_; // Used only to call function.
1196 AlignmentData* alignData = NULL;
1197 Word* Peq = buildPeq(alphabetLength, query, queryLength, equalityDefinition);
1198 myersCalcEditDistanceNW(Peq, W, maxNumBlocks, queryLength, target, targetLength, bestScore,
1199 &score_, &endLocation_, true, &alignData, -1);
1200 //assert(score_ == bestScore);
1201 //assert(endLocation_ == targetLength - 1);
1202
1203 statusCode = obtainAlignmentTraceback(queryLength, targetLength, bestScore, alignData,
1204 alignment, alignmentLength);
1205 delete alignData;
1206 delete[] Peq;
1207 } else {
1208 statusCode = obtainAlignmentHirschberg(query, rQuery, queryLength, target, rTarget,
1209 targetLength, equalityDefinition, alphabetLength,
1210 bestScore, alignment, alignmentLength);
1211 }
1212 return statusCode;
1213 }
1214
1215 /**
1216 * Finds one possible alignment that gives optimal score (bestScore).
1217 * Uses Hirschberg's algorithm to split problem into two sub-problems, solve them and combine them together.
1218 * @param [in] query
1219 * @param [in] rQuery Reversed query.
1220 * @param [in] queryLength
1221 * @param [in] target
1222 * @param [in] rTarget Reversed target.
1223 * @param [in] targetLength
1224 * @param [in] alphabetLength
1225 * @param [in] bestScore Best(optimal) score.
1226 * @param [out] alignment Sequence of edit operations that make target equal to query.
1227 * @param [out] alignmentLength Length of alignment.
1228 * @return Status code.
1229 */
1230 static int obtainAlignmentHirschberg(const unsigned char* const query,
1231 const unsigned char* const rQuery, const int queryLength,
1232 const unsigned char* const target,
1233 const unsigned char* const rTarget, const int targetLength,
1234 const EqualityDefinition& equalityDefinition,
1235 const int alphabetLength, const int bestScore,
1236 unsigned char** const alignment, int* const alignmentLength)
1237 {
1238
1239 const int maxNumBlocks = ceilDiv(queryLength, WORD_SIZE);
1240 const int W = maxNumBlocks * WORD_SIZE - queryLength;
1241
1242 Word* Peq = buildPeq(alphabetLength, query, queryLength, equalityDefinition);
1243 Word* rPeq = buildPeq(alphabetLength, rQuery, queryLength, equalityDefinition);
1244
1245 // Used only to call functions.
1246 int score_, endLocation_;
1247
1248 // Divide dynamic matrix into two halfs, left and right.
1249 const int leftHalfWidth = targetLength / 2;
1250 const int rightHalfWidth = targetLength - leftHalfWidth;
1251
1252 // Calculate left half.
1253 AlignmentData* alignDataLeftHalf = NULL;
1254 int leftHalfCalcStatus = myersCalcEditDistanceNW(
1255 Peq, W, maxNumBlocks, queryLength, target, targetLength, bestScore, &score_, &endLocation_,
1256 false, &alignDataLeftHalf, leftHalfWidth - 1);
1257
1258 // Calculate right half.
1259 AlignmentData* alignDataRightHalf = NULL;
1260 int rightHalfCalcStatus = myersCalcEditDistanceNW(
1261 rPeq, W, maxNumBlocks, queryLength, rTarget, targetLength, bestScore, &score_,
1262 &endLocation_, false, &alignDataRightHalf, rightHalfWidth - 1);
1263
1264 delete[] Peq;
1265 delete[] rPeq;
1266
1267 if (leftHalfCalcStatus == EDLIB_STATUS_ERROR || rightHalfCalcStatus == EDLIB_STATUS_ERROR) {
1268 if (alignDataLeftHalf) delete alignDataLeftHalf;
1269 if (alignDataRightHalf) delete alignDataRightHalf;
1270 return EDLIB_STATUS_ERROR;
1271 }
1272
1273 // Unwrap the left half.
1274 int firstBlockIdxLeft = alignDataLeftHalf->firstBlocks[0];
1275 int lastBlockIdxLeft = alignDataLeftHalf->lastBlocks[0];
1276 // TODO: avoid this allocation by using some shared array?
1277 // scoresLeft contains scores from left column, starting with scoresLeftStartIdx row (query index)
1278 // and ending with scoresLeftEndIdx row (0-indexed).
1279 int scoresLeftLength = (lastBlockIdxLeft - firstBlockIdxLeft + 1) * WORD_SIZE;
1280 int* scoresLeft = new int[scoresLeftLength];
1281 for (int blockIdx = firstBlockIdxLeft; blockIdx <= lastBlockIdxLeft; blockIdx++) {
1282 Block block(alignDataLeftHalf->Ps[blockIdx], alignDataLeftHalf->Ms[blockIdx],
1283 alignDataLeftHalf->scores[blockIdx]);
1284 readBlock(block, scoresLeft + (blockIdx - firstBlockIdxLeft) * WORD_SIZE);
1285 }
1286 int scoresLeftStartIdx = firstBlockIdxLeft * WORD_SIZE;
1287 // If last block contains padding, shorten the length of scores for the length of padding.
1288 if (lastBlockIdxLeft == maxNumBlocks - 1) {
1289 scoresLeftLength -= W;
1290 }
1291
1292 // Unwrap the right half (I also reverse it while unwraping).
1293 int firstBlockIdxRight = alignDataRightHalf->firstBlocks[0];
1294 int lastBlockIdxRight = alignDataRightHalf->lastBlocks[0];
1295 int scoresRightLength = (lastBlockIdxRight - firstBlockIdxRight + 1) * WORD_SIZE;
1296 int* scoresRight = new int[scoresRightLength];
1297 int* scoresRightOriginalStart = scoresRight;
1298 for (int blockIdx = firstBlockIdxRight; blockIdx <= lastBlockIdxRight; blockIdx++) {
1299 Block block(alignDataRightHalf->Ps[blockIdx], alignDataRightHalf->Ms[blockIdx],
1300 alignDataRightHalf->scores[blockIdx]);
1301 readBlockReverse(block, scoresRight + (lastBlockIdxRight - blockIdx) * WORD_SIZE);
1302 }
1303 int scoresRightStartIdx = queryLength - (lastBlockIdxRight + 1) * WORD_SIZE;
1304 // If there is padding at the beginning of scoresRight (that can happen because of reversing that we do),
1305 // move pointer forward to remove the padding (that is why we remember originalStart).
1306 if (scoresRightStartIdx < 0) {
1307 //assert(scoresRightStartIdx == -1 * W);
1308 scoresRight += W;
1309 scoresRightStartIdx += W;
1310 scoresRightLength -= W;
1311 }
1312
1313 delete alignDataLeftHalf;
1314 delete alignDataRightHalf;
1315
1316 //--------------------- Find the best move ----------------//
1317 // Find the query/row index of cell in left column which together with its lower right neighbour
1318 // from right column gives the best score (when summed). We also have to consider boundary cells
1319 // (those cells at -1 indexes).
1320 // x|
1321 // -+-
1322 // |x
1323 int queryIdxLeftStart = max(scoresLeftStartIdx, scoresRightStartIdx - 1);
1324 int queryIdxLeftEnd =
1325 min(scoresLeftStartIdx + scoresLeftLength - 1, scoresRightStartIdx + scoresRightLength - 2);
1326 int leftScore = -1, rightScore = -1;
1327 int queryIdxLeftAlignment =
1328 -1; // Query/row index of cell in left column where alignment is passing through.
1329 bool queryIdxLeftAlignmentFound = false;
1330 for (int queryIdx = queryIdxLeftStart; queryIdx <= queryIdxLeftEnd; queryIdx++) {
1331 leftScore = scoresLeft[queryIdx - scoresLeftStartIdx];
1332 rightScore = scoresRight[queryIdx + 1 - scoresRightStartIdx];
1333 if (leftScore + rightScore == bestScore) {
1334 queryIdxLeftAlignment = queryIdx;
1335 queryIdxLeftAlignmentFound = true;
1336 break;
1337 }
1338 }
1339 // Check boundary cells.
1340 if (!queryIdxLeftAlignmentFound && scoresLeftStartIdx == 0 && scoresRightStartIdx == 0) {
1341 leftScore = leftHalfWidth;
1342 rightScore = scoresRight[0];
1343 if (leftScore + rightScore == bestScore) {
1344 queryIdxLeftAlignment = -1;
1345 queryIdxLeftAlignmentFound = true;
1346 }
1347 }
1348 if (!queryIdxLeftAlignmentFound && scoresLeftStartIdx + scoresLeftLength == queryLength &&
1349 scoresRightStartIdx + scoresRightLength == queryLength) {
1350 leftScore = scoresLeft[scoresLeftLength - 1];
1351 rightScore = rightHalfWidth;
1352 if (leftScore + rightScore == bestScore) {
1353 queryIdxLeftAlignment = queryLength - 1;
1354 queryIdxLeftAlignmentFound = true;
1355 }
1356 }
1357
1358 delete[] scoresLeft;
1359 delete[] scoresRightOriginalStart;
1360
1361 if (queryIdxLeftAlignmentFound == false) {
1362 // If there was no move that is part of optimal alignment, then there is no such alignment
1363 // or given bestScore is not correct!
1364 return EDLIB_STATUS_ERROR;
1365 }
1366 //----------------------------------------------------------//
1367
1368 // Calculate alignments for upper half of left half (upper left - ul)
1369 // and lower half of right half (lower right - lr).
1370 const int ulHeight = queryIdxLeftAlignment + 1;
1371 const int lrHeight = queryLength - ulHeight;
1372 const int ulWidth = leftHalfWidth;
1373 const int lrWidth = rightHalfWidth;
1374 unsigned char* ulAlignment = NULL;
1375 int ulAlignmentLength;
1376 int ulStatusCode = obtainAlignment(query, rQuery + lrHeight, ulHeight, target,
1377 rTarget + lrWidth, ulWidth, equalityDefinition,
1378 alphabetLength, leftScore, &ulAlignment, &ulAlignmentLength);
1379 unsigned char* lrAlignment = NULL;
1380 int lrAlignmentLength;
1381 int lrStatusCode = obtainAlignment(query + ulHeight, rQuery, lrHeight, target + ulWidth,
1382 rTarget, lrWidth, equalityDefinition, alphabetLength,
1383 rightScore, &lrAlignment, &lrAlignmentLength);
1384 if (ulStatusCode == EDLIB_STATUS_ERROR || lrStatusCode == EDLIB_STATUS_ERROR) {
1385 if (ulAlignment) free(ulAlignment);
1386 if (lrAlignment) free(lrAlignment);
1387 return EDLIB_STATUS_ERROR;
1388 }
1389
1390 // Build alignment by concatenating upper left alignment with lower right alignment.
1391 *alignmentLength = ulAlignmentLength + lrAlignmentLength;
1392 *alignment = static_cast<unsigned char*>(malloc((*alignmentLength) * sizeof(unsigned char)));
1393 memcpy(*alignment, ulAlignment, ulAlignmentLength);
1394 memcpy(*alignment + ulAlignmentLength, lrAlignment, lrAlignmentLength);
1395
1396 free(ulAlignment);
1397 free(lrAlignment);
1398 return EDLIB_STATUS_OK;
1399 }
1400
1401 /**
1402 * Takes char query and char target, recognizes alphabet and transforms them into unsigned char sequences
1403 * where elements in sequences are not any more letters of alphabet, but their index in alphabet.
1404 * Most of internal edlib functions expect such transformed sequences.
1405 * This function will allocate queryTransformed and targetTransformed, so make sure to free them when done.
1406 * Example:
1407 * Original sequences: "ACT" and "CGT".
1408 * Alphabet would be recognized as "ACTG". Alphabet length = 4.
1409 * Transformed sequences: [0, 1, 2] and [1, 3, 2].
1410 * @param [in] queryOriginal
1411 * @param [in] queryLength
1412 * @param [in] targetOriginal
1413 * @param [in] targetLength
1414 * @param [out] queryTransformed It will contain values in range [0, alphabet length - 1].
1415 * @param [out] targetTransformed It will contain values in range [0, alphabet length - 1].
1416 * @return Alphabet as a string of unique characters, where index of each character is its value in transformed
1417 * sequences.
1418 */
1419 static string transformSequences(const char* const queryOriginal, const int queryLength,
1420 const char* const targetOriginal, const int targetLength,
1421 unsigned char** const queryTransformed,
1422 unsigned char** const targetTransformed)
1423 {
1424 // Alphabet is constructed from letters that are present in sequences.
1425 // Each letter is assigned an ordinal number, starting from 0 up to alphabetLength - 1,
1426 // and new query and target are created in which letters are replaced with their ordinal numbers.
1427 // This query and target are used in all the calculations later.
1428 *queryTransformed = static_cast<unsigned char*>(malloc(sizeof(unsigned char) * queryLength));
1429 *targetTransformed = static_cast<unsigned char*>(malloc(sizeof(unsigned char) * targetLength));
1430
1431 string alphabet = "";
1432
1433 // Alphabet information, it is constructed on fly while transforming sequences.
1434 // letterIdx[c] is index of letter c in alphabet.
1435 unsigned char letterIdx[MAX_UCHAR + 1];
1436 bool inAlphabet[MAX_UCHAR + 1]; // inAlphabet[c] is true if c is in alphabet
1437 for (int i = 0; i < MAX_UCHAR + 1; i++)
1438 inAlphabet[i] = false;
1439
1440 for (int i = 0; i < queryLength; i++) {
1441 unsigned char c = static_cast<unsigned char>(queryOriginal[i]);
1442 if (!inAlphabet[c]) {
1443 inAlphabet[c] = true;
1444 letterIdx[c] = static_cast<unsigned char>(alphabet.size());
1445 alphabet += queryOriginal[i];
1446 }
1447 (*queryTransformed)[i] = letterIdx[c];
1448 }
1449 for (int i = 0; i < targetLength; i++) {
1450 unsigned char c = static_cast<unsigned char>(targetOriginal[i]);
1451 if (!inAlphabet[c]) {
1452 inAlphabet[c] = true;
1453 letterIdx[c] = static_cast<unsigned char>(alphabet.size());
1454 alphabet += targetOriginal[i];
1455 }
1456 (*targetTransformed)[i] = letterIdx[c];
1457 }
1458
1459 return alphabet;
1460 }
1461
1462 extern "C" EdlibAlignConfig edlibNewAlignConfig(int k, EdlibAlignMode mode, EdlibAlignTask task,
1463 const EdlibEqualityPair* additionalEqualities,
1464 int additionalEqualitiesLength)
1465 {
1466 EdlibAlignConfig config;
1467 config.k = k;
1468 config.mode = mode;
1469 config.task = task;
1470 config.additionalEqualities = additionalEqualities;
1471 config.additionalEqualitiesLength = additionalEqualitiesLength;
1472 return config;
1473 }
1474
1475 extern "C" EdlibAlignConfig edlibDefaultAlignConfig(void)
1476 {
1477 return edlibNewAlignConfig(-1, EDLIB_MODE_NW, EDLIB_TASK_DISTANCE, NULL, 0);
1478 }
1479
1480 extern "C" void edlibFreeAlignResult(EdlibAlignResult result)
1481 {
1482 if (result.endLocations) free(result.endLocations);
1483 if (result.startLocations) free(result.startLocations);
1484 if (result.alignment) free(result.alignment);
1485 }