Debian Codegraph @

src/edlib.cpp

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