Debian Codegraph @

bcftools/edlib.c

raw symbols SCIP
1 /*
2 * A cut down C translated of the C++ edlib.cpp file.
3 * Taken from edlib v0.1.0-166-g931be2b
4 */
5
6 #include <stdint.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <stdbool.h>
10
11 #include "edlib.h"
12
13 typedef uint64_t Word;
14 static const int WORD_SIZE = 64; // Size of Word in bits
15 static const Word WORD_1 = (Word)1;
16 static const Word HIGH_BIT_MASK = 1LL << 63; // 100..00
17 //#define MAX_UCHAR 255
18 #define MAX_UCHAR 7 // better cache usage for our data
19
20 #ifndef MAX
21 #define MAX(a,b) ((a)>(b)?(a):(b))
22 #endif
23
24 typedef struct Block {
25 Word P; // Pvin
26 Word M; // Mvin
27 int score; // score of last cell in block;
28 } Block;
29
30
31 /**
32 * Defines equality relation on alphabet characters.
33 * By default each character is always equal only to itself, but you can also provide additional equalities.
34 */
35 typedef struct EqualityDefinition {
36 bool matrix[MAX_UCHAR + 1][MAX_UCHAR + 1];
37 } EqualityDefinition;
38
39 static EqualityDefinition *
40 CreateEqualityDefinition(const char *alphabet, int alphabet_size,
41 const EdlibEqualityPair* additionalEqualities,
42 const int additionalEqualitiesLength) {
43 EqualityDefinition *ed = malloc(sizeof(*ed));
44
45 for (size_t i = 0; i < alphabet_size; i++) {
46 for (size_t j = 0; j < alphabet_size; j++) {
47 ed->matrix[i][j] = (i == j);
48 }
49 }
50 if (additionalEqualities != NULL) {
51 for (int i = 0; i < additionalEqualitiesLength; i++) {
52 const char *firstTransformed = strchr(alphabet, additionalEqualities[i].first);
53 const char *secondTransformed = strchr(alphabet, additionalEqualities[i].second);
54 if (firstTransformed && alphabet_size) {
55 ed->matrix[firstTransformed - alphabet][secondTransformed - alphabet] =
56 ed->matrix[secondTransformed - alphabet][firstTransformed - alphabet]
57 = true;
58 }
59 }
60 }
61
62 return ed;
63 }
64
65 /**
66 * @param a Element from transformed sequence.
67 * @param b Element from transformed sequence.
68 * @return True if a and b are defined as equal, false otherwise.
69 */
70 static inline const /* attribute pure or const? */
71 bool equalityDefinition_areEqual(const EqualityDefinition *ed, unsigned char a, unsigned char b) {
72 return ed->matrix[a][b];
73 }
74
75 static int myersCalcEditDistanceSemiGlobal(const Word* Peq, int W, int maxNumBlocks,
76 int queryLength,
77 const unsigned char* target, int targetLength,
78 int k, EdlibAlignMode mode,
79 int* bestScore_, int** positions_, int* numPositions_);
80
81 static char *transformSequences(const char* queryOriginal, int queryLength,
82 const char* targetOriginal, int targetLength,
83 unsigned char** queryTransformed,
84 unsigned char** targetTransformed,
85 int *alphabet_size);
86
87 static inline int ceilDiv(int x, int y);
88
89 static inline unsigned char* createReverseCopy(const unsigned char* seq, int length);
90
91 static inline Word* buildPeq(const int alphabetLength,
92 const unsigned char* query,
93 const int queryLength,
94 const EqualityDefinition* equalityDefinition);
95
96
97 /**
98 * Main edlib method.
99 */
100 EdlibAlignResult edlibAlign(const char* const queryOriginal, const int queryLength,
101 const char* const targetOriginal, const int targetLength,
102 const EdlibAlignConfig config) {
103 EdlibAlignResult result;
104 result.status = EDLIB_STATUS_OK;
105 result.editDistance = -1;
106 result.endLocations = result.startLocations = NULL;
107 result.numLocations = 0;
108 result.alignment = NULL;
109 result.alignmentLength = 0;
110 result.alphabetLength = 0;
111
112 /*------------ TRANSFORM SEQUENCES AND RECOGNIZE ALPHABET -----------*/
113 unsigned char* query, * target;
114 int alphabet_size;
115 char *alphabet = transformSequences(queryOriginal, queryLength, targetOriginal, targetLength,
116 &query, &target, &alphabet_size);
117 result.alphabetLength = alphabet_size;
118 /*-------------------------------------------------------*/
119
120 // Handle special situation when at least one of the sequences has length 0.
121 if (queryLength == 0 || targetLength == 0) {
122 if (config.mode == EDLIB_MODE_NW) {
123 result.editDistance = MAX(queryLength, targetLength);
124 result.endLocations = malloc(sizeof(int) * 1);
125 result.endLocations[0] = targetLength - 1;
126 result.numLocations = 1;
127 } else if (config.mode == EDLIB_MODE_SHW || config.mode == EDLIB_MODE_HW) {
128 result.editDistance = queryLength;
129 result.endLocations = malloc(sizeof(int) * 1);
130 result.endLocations[0] = -1;
131 result.numLocations = 1;
132 } else {
133 result.status = EDLIB_STATUS_ERROR;
134 }
135
136 free(query);
137 free(target);
138 free(alphabet);
139 return result;
140 }
141
142 /*--------------------- INITIALIZATION ------------------*/
143 int maxNumBlocks = ceilDiv(queryLength, WORD_SIZE); // bmax in Myers
144 int W = maxNumBlocks * WORD_SIZE - queryLength; // number of redundant cells in last level blocks
145 EqualityDefinition *equalityDefinition =
146 CreateEqualityDefinition(alphabet, alphabet_size, config.additionalEqualities, config.additionalEqualitiesLength);
147 Word* Peq = buildPeq(alphabet_size, query, queryLength, equalityDefinition);
148 /*-------------------------------------------------------*/
149
150 /*------------------ MAIN CALCULATION -------------------*/
151 // TODO: Store alignment data only after k is determined? That could make things faster.
152 // int positionNW; // Used only when mode is NW.
153 // AlignmentData* alignData = NULL;
154 bool dynamicK = false;
155 int k = config.k;
156 if (k < 0) { // If valid k is not given, auto-adjust k until solution is found.
157 dynamicK = true;
158 k = WORD_SIZE; // Gives better results than smaller k.
159 }
160
161 do {
162 if (config.mode == EDLIB_MODE_HW || config.mode == EDLIB_MODE_SHW) {
163 myersCalcEditDistanceSemiGlobal(Peq, W, maxNumBlocks,
164 queryLength, target, targetLength,
165 k, config.mode, &(result.editDistance),
166 &(result.endLocations), &(result.numLocations));
167 } else { // mode == EDLIB_MODE_NW
168 // myersCalcEditDistanceNW(Peq, W, maxNumBlocks,
169 // queryLength, target, targetLength,
170 // k, &(result.editDistance), &positionNW,
171 // false, &alignData, -1);
172 }
173 k *= 2;
174 } while(dynamicK && result.editDistance == -1);
175
176 if (result.editDistance >= 0) { // If there is solution.
177 // If NW mode, set end location explicitly.
178 if (config.mode == EDLIB_MODE_NW) {
179 result.endLocations = malloc(sizeof(int) * 1);
180 result.endLocations[0] = targetLength - 1;
181 result.numLocations = 1;
182 }
183
184 // Find starting locations.
185 if (config.task == EDLIB_TASK_LOC || config.task == EDLIB_TASK_PATH) {
186 result.startLocations = malloc(result.numLocations * sizeof(int));
187 if (config.mode == EDLIB_MODE_HW) { // If HW, I need to calculate start locations.
188 const unsigned char* rTarget = createReverseCopy(target, targetLength);
189 const unsigned char* rQuery = createReverseCopy(query, queryLength);
190 // Peq for reversed query.
191 Word* rPeq = buildPeq(alphabet_size, rQuery, queryLength, equalityDefinition);
192 for (int i = 0; i < result.numLocations; i++) {
193 int endLocation = result.endLocations[i];
194 if (endLocation == -1) {
195 // NOTE: Sometimes one of optimal solutions is that query starts before target, like this:
196 // AAGG <- target
197 // CCTT <- query
198 // It will never be only optimal solution and it does not happen often, however it is
199 // possible and in that case end location will be -1. What should we do with that?
200 // Should we just skip reporting such end location, although it is a solution?
201 // If we do report it, what is the start location? -4? -1? Nothing?
202 // TODO: Figure this out. This has to do in general with how we think about start
203 // and end locations.
204 // Also, we have alignment later relying on this locations to limit the space of it's
205 // search -> how can it do it right if these locations are negative or incorrect?
206 result.startLocations[i] = 0; // I put 0 for now, but it does not make much sense.
207 } else {
208 int bestScoreSHW, numPositionsSHW;
209 int* positionsSHW;
210 myersCalcEditDistanceSemiGlobal(
211 rPeq, W, maxNumBlocks,
212 queryLength, rTarget + targetLength - endLocation - 1, endLocation + 1,
213 result.editDistance, EDLIB_MODE_SHW,
214 &bestScoreSHW, &positionsSHW, &numPositionsSHW);
215 // Taking last location as start ensures that alignment will not start with insertions
216 // if it can start with mismatches instead.
217 result.startLocations[i] = endLocation - positionsSHW[numPositionsSHW - 1];
218 free(positionsSHW);
219 }
220 }
221 free((void *)rTarget);
222 free((void *)rQuery);
223 free(rPeq);
224 } else { // If mode is SHW or NW
225 for (int i = 0; i < result.numLocations; i++) {
226 result.startLocations[i] = 0;
227 }
228 }
229 }
230 }
231 /*-------------------------------------------------------*/
232
233 //--- Free memory ---//
234 free(Peq);
235 free(query);
236 free(target);
237 free(alphabet);
238 free(equalityDefinition);
239 // DestroyAlignmentData(alignData);
240 //-------------------//
241
242 return result;
243 }
244
245 /**
246 * Build Peq table for given query and alphabet.
247 * Peq is table of dimensions alphabetLength+1 x maxNumBlocks.
248 * 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.
249 * NOTICE: free returned array with free()!
250 */
251 static inline Word* buildPeq(const int alphabetLength,
252 const unsigned char* const query,
253 const int queryLength,
254 const EqualityDefinition* equalityDefinition) {
255 int maxNumBlocks = ceilDiv(queryLength, WORD_SIZE);
256 // table of dimensions alphabetLength+1 x maxNumBlocks. Last symbol is wildcard.
257 Word* Peq = malloc((alphabetLength + 1) * maxNumBlocks * sizeof(*Peq));
258
259 // Build Peq (1 is match, 0 is mismatch). NOTE: last column is wildcard(symbol that matches anything) with just 1s
260 // Optimised Peq building avoiding branching.
261 for (int symbol = 0; symbol < alphabetLength; symbol++) {
262 for (int b = 0; b < maxNumBlocks; b++) {
263 Word PeqW = 0;
264 for (int r = (b+1) * WORD_SIZE - 1; r >= b * WORD_SIZE; r--) {
265 PeqW = (PeqW<<1)
266 + (r >= queryLength
267 || equalityDefinition_areEqual(equalityDefinition,
268 query[r], symbol));
269 }
270 Peq[symbol * maxNumBlocks + b] = PeqW;
271 }
272 }
273 {
274 int symbol = alphabetLength;
275 for (int b = 0; b < maxNumBlocks; b++) {
276 // Last symbol is wildcard, so it is all 1s
277 Peq[symbol * maxNumBlocks + b] = (Word)-1;
278 }
279 }
280
281 return Peq;
282 }
283
284
285 /**
286 * Returns new sequence that is reverse of given sequence.
287 * Free returned array with free()
288 */
289 static inline unsigned char* createReverseCopy(const unsigned char* const seq, const int length) {
290 unsigned char* rSeq = malloc(length);
291 for (int i = 0; i < length; i++) {
292 rSeq[i] = seq[length - i - 1];
293 }
294 return rSeq;
295 }
296
297 /**
298 * Corresponds to Advance_Block function from Myers.
299 * Calculates one word(block), which is part of a column.
300 * Highest bit of word (one most to the left) is most bottom cell of block from column.
301 * Pv[i] and Mv[i] define vin of cell[i]: vin = cell[i] - cell[i-1].
302 * @param [in] Pv Bitset, Pv[i] == 1 if vin is +1, otherwise Pv[i] == 0.
303 * @param [in] Mv Bitset, Mv[i] == 1 if vin is -1, otherwise Mv[i] == 0.
304 * @param [in] Eq Bitset, Eq[i] == 1 if match, 0 if mismatch.
305 * @param [in] hin Will be +1, 0 or -1.
306 * @param [out] PvOut Bitset, PvOut[i] == 1 if vout is +1, otherwise PvOut[i] == 0.
307 * @param [out] MvOut Bitset, MvOut[i] == 1 if vout is -1, otherwise MvOut[i] == 0.
308 * @param [out] hout Will be +1, 0 or -1.
309 */
310 static inline int calculateBlock(Word Pv, Word Mv, Word Eq, const int hin,
311 Word *PvOut, Word *MvOut) {
312 // hin can be 1, -1 or 0.
313 // 1 -> 00...01
314 // 0 -> 00...00
315 // -1 -> 11...11 (2-complement)
316
317 Word hinIsNeg = (Word)(hin >> 2) & WORD_1; // 00...001 if hin is -1, 00...000 if 0 or 1
318
319 Word Xv = Eq | Mv;
320 // This is instruction below written using 'if': if (hin < 0) Eq |= (Word)1;
321 Eq |= hinIsNeg;
322 Word Xh = (((Eq & Pv) + Pv) ^ Pv) | Eq;
323
324 Word Ph = Mv | ~(Xh | Pv);
325 Word Mh = Pv & Xh;
326
327 int hout = 0;
328 // This is instruction below written using 'if': if (Ph & HIGH_BIT_MASK) hout = 1;
329 hout = (Ph & HIGH_BIT_MASK) >> (WORD_SIZE - 1);
330 // This is instruction below written using 'if': if (Mh & HIGH_BIT_MASK) hout = -1;
331 hout -= (Mh & HIGH_BIT_MASK) >> (WORD_SIZE - 1);
332
333 Ph <<= 1;
334 Mh <<= 1;
335
336 // This is instruction below written using 'if': if (hin < 0) Mh |= (Word)1;
337 Mh |= hinIsNeg;
338 // This is instruction below written using 'if': if (hin > 0) Ph |= (Word)1;
339 Ph |= (Word)((hin + 1) >> 1);
340
341 *PvOut = Mh | ~(Xv | Ph);
342 *MvOut = Ph & Xv;
343
344 return hout;
345 }
346
347 /**
348 * Does ceiling division x / y.
349 * Note: x and y must be non-negative and x + y must not overflow.
350 */
351 static inline int ceilDiv(const int x, const int y) {
352 return x % y ? x / y + 1 : x / y;
353 }
354
355 static inline int min(const int x, const int y) {
356 return x < y ? x : y;
357 }
358
359
360 /**
361 * @param [in] block
362 * @return Values of cells in block, starting with bottom cell in block.
363 */
364 static inline int *getBlockCellValues(const Block block) {
365 int *scores = malloc(WORD_SIZE * sizeof(*scores));
366 int score = block.score;
367 Word mask = HIGH_BIT_MASK;
368 for (int i = 0; i < WORD_SIZE - 1; i++) {
369 scores[i] = score;
370 if (block.P & mask) score--;
371 if (block.M & mask) score++;
372 mask >>= 1;
373 }
374 scores[WORD_SIZE - 1] = score;
375 return scores;
376 }
377
378 /**
379 * @param [in] block
380 * @param [in] k
381 * @return True if all cells in block have value larger than k, otherwise false.
382 */
383 static inline bool allBlockCellsLarger(const Block block, const int k) {
384 int *scores = getBlockCellValues(block);
385 for (int i = 0; i < WORD_SIZE; i++) {
386 if (scores[i] <= k) {
387 free(scores);
388 return false;
389 }
390 }
391
392 free(scores);
393 return true;
394 }
395
396
397 /**
398 * Uses Myers' bit-vector algorithm to find edit distance for one of semi-global alignment methods.
399 * @param [in] Peq Query profile.
400 * @param [in] W Size of padding in last block.
401 * TODO: Calculate this directly from query, instead of passing it.
402 * @param [in] maxNumBlocks Number of blocks needed to cover the whole query.
403 * TODO: Calculate this directly from query, instead of passing it.
404 * @param [in] queryLength
405 * @param [in] target
406 * @param [in] targetLength
407 * @param [in] k
408 * @param [in] mode EDLIB_MODE_HW or EDLIB_MODE_SHW
409 * @param [out] bestScore_ Edit distance.
410 * @param [out] positions_ Array of 0-indexed positions in target at which best score was found.
411 Make sure to free this array with free().
412 * @param [out] numPositions_ Number of positions in the positions_ array.
413 * @return Status.
414 */
415 static int myersCalcEditDistanceSemiGlobal(
416 const Word* const Peq, const int W, const int maxNumBlocks,
417 const int queryLength,
418 const unsigned char* const target, const int targetLength,
419 int k, const EdlibAlignMode mode,
420 int* const bestScore_, int** const positions_, int* const numPositions_) {
421 *positions_ = NULL;
422 *numPositions_ = 0;
423
424 // firstBlock is 0-based index of first block in Ukkonen band.
425 // lastBlock is 0-based index of last block in Ukkonen band.
426 int firstBlock = 0;
427 int lastBlock = min(ceilDiv(k + 1, WORD_SIZE), maxNumBlocks) - 1; // y in Myers
428 Block *bl; // Current block
429
430 Block* blocks = malloc(maxNumBlocks * sizeof(*blocks));
431
432 // For HW, solution will never be larger then queryLength.
433 if (mode == EDLIB_MODE_HW) {
434 k = min(queryLength, k);
435 }
436
437 // Each STRONG_REDUCE_NUM column is reduced in more expensive way.
438 // This gives speed up of about 2 times for small k.
439 const int STRONG_REDUCE_NUM = 2048;
440
441 // Initialize P, M and score
442 bl = blocks;
443 for (int b = 0; b <= lastBlock; b++) {
444 bl->score = (b + 1) * WORD_SIZE;
445 bl->P = (Word)(-1); // All 1s
446 bl->M = (Word)(0);
447 bl++;
448 }
449
450 int bestScore = -1;
451 #define MAX_POS 100 // maximum number of positions returned.
452 int positions[MAX_POS];
453 int npositions = 0;
454 const int startHout = mode == EDLIB_MODE_HW ? 0 : 1; // If 0 then gap before query is not penalized;
455 const unsigned char* targetChar = target;
456 for (int c = 0; c < targetLength; c++) { // for each column
457 const Word* Peq_c = Peq + (*targetChar) * maxNumBlocks;
458
459 //----------------------- Calculate column -------------------------//
460 int hout = startHout;
461 bl = blocks + firstBlock;
462 Peq_c += firstBlock;
463 for (int b = firstBlock; b <= lastBlock; b++) {
464 hout = calculateBlock(bl->P, bl->M, *Peq_c, hout, &bl->P, &bl->M);
465 bl->score += hout;
466 bl++; Peq_c++;
467 }
468 bl--; Peq_c--;
469 //------------------------------------------------------------------//
470
471 //---------- Adjust number of blocks according to Ukkonen ----------//
472 if ((lastBlock < maxNumBlocks - 1) && (bl->score - hout <= k) // bl is pointing to last block
473 && ((*(Peq_c + 1) & WORD_1) || hout < 0)) { // Peq_c is pointing to last block
474 // If score of left block is not too big, calculate one more block
475 lastBlock++; bl++; Peq_c++;
476 bl->P = (Word)(-1); // All 1s
477 bl->M = (Word)(0);
478 bl->score = (bl - 1)->score - hout + WORD_SIZE + calculateBlock(bl->P, bl->M, *Peq_c, hout, &bl->P, &bl->M);
479 } else {
480 while (lastBlock >= firstBlock && bl->score >= k + WORD_SIZE) {
481 lastBlock--; bl--; Peq_c--;
482 }
483 }
484
485 // Every some columns, do some expensive but also more efficient block reducing.
486 // This is important!
487 //
488 // Reduce the band by decreasing last block if possible.
489 if (c % STRONG_REDUCE_NUM == 0) {
490 while (lastBlock >= 0 && lastBlock >= firstBlock && allBlockCellsLarger(*bl, k)) {
491 lastBlock--; bl--; Peq_c--;
492 }
493 }
494 // For HW, even if all cells are > k, there still may be solution in next
495 // column because starting conditions at upper boundary are 0.
496 // That means that first block is always candidate for solution,
497 // and we can never end calculation before last column.
498 if (mode == EDLIB_MODE_HW && lastBlock == -1) {
499 lastBlock++; bl++; Peq_c++;
500 }
501
502 // Reduce band by increasing first block if possible. Not applicable to HW.
503 if (mode != EDLIB_MODE_HW) {
504 while (firstBlock <= lastBlock && blocks[firstBlock].score >= k + WORD_SIZE) {
505 firstBlock++;
506 }
507 if (c % STRONG_REDUCE_NUM == 0) { // Do strong reduction every some blocks
508 while (firstBlock <= lastBlock && allBlockCellsLarger(blocks[firstBlock], k)) {
509 firstBlock++;
510 }
511 }
512 }
513
514 // If band stops to exist finish
515 if (lastBlock < firstBlock) {
516 *bestScore_ = bestScore;
517 if (bestScore != -1) {
518 *positions_ = malloc(npositions * sizeof(int));
519 *numPositions_ = npositions;
520 memcpy(*positions_, positions, npositions * sizeof(int));
521 }
522 free(blocks);
523 return EDLIB_STATUS_OK;
524 }
525 //------------------------------------------------------------------//
526
527 //------------------------- Update best score ----------------------//
528 if (lastBlock == maxNumBlocks - 1) {
529 int colScore = bl->score;
530 if (colScore <= k) { // Scores > k dont have correct values (so we cannot use them), but are certainly > k.
531 // NOTE: Score that I find in column c is actually score from column c-W
532 if (bestScore == -1 || colScore <= bestScore) {
533 if (colScore != bestScore) {
534 npositions = 0;
535 bestScore = colScore;
536 // Change k so we will look only for equal or better
537 // scores then the best found so far.
538 k = bestScore;
539 }
540 if (npositions < MAX_POS)
541 positions[npositions++] = c - W;
542 }
543 }
544 }
545 //------------------------------------------------------------------//
546
547 targetChar++;
548 }
549
550
551 // Obtain results for last W columns from last column.
552 if (lastBlock == maxNumBlocks - 1) {
553 int *blockScores = getBlockCellValues(*bl);
554 for (int i = 0; i < W; i++) {
555 int colScore = blockScores[i + 1];
556 if (colScore <= k && (bestScore == -1 || colScore <= bestScore)) {
557 if (colScore != bestScore) {
558 npositions = 0;
559 k = bestScore = colScore;
560 }
561 if (npositions < MAX_POS)
562 positions[npositions++] = targetLength - W + i;
563 }
564 }
565 free(blockScores);
566 }
567
568 *bestScore_ = bestScore;
569 if (bestScore != -1) {
570 *positions_ = malloc(npositions * sizeof(int));
571 *numPositions_ = npositions;
572 memcpy(*positions_, positions, npositions * sizeof(int));
573 }
574
575 free(blocks);
576 return EDLIB_STATUS_OK;
577 }
578
579
580 /**
581 * Takes char query and char target, recognizes alphabet and transforms them into unsigned char sequences
582 * where elements in sequences are not any more letters of alphabet, but their index in alphabet.
583 * Most of internal edlib functions expect such transformed sequences.
584 * This function will allocate queryTransformed and targetTransformed, so make sure to free them when done.
585 * Example:
586 * Original sequences: "ACT" and "CGT".
587 * Alphabet would be recognized as "ACTG". Alphabet length = 4.
588 * Transformed sequences: [0, 1, 2] and [1, 3, 2].
589 * @param [in] queryOriginal
590 * @param [in] queryLength
591 * @param [in] targetOriginal
592 * @param [in] targetLength
593 * @param [out] queryTransformed It will contain values in range [0, alphabet length - 1].
594 * @param [out] targetTransformed It will contain values in range [0, alphabet length - 1].
595 * @return Alphabet as a string of unique characters, where index of each character is its value in transformed
596 * sequences.
597 */
598 static char *transformSequences(const char* const queryOriginal, const int queryLength,
599 const char* const targetOriginal, const int targetLength,
600 unsigned char** const queryTransformed,
601 unsigned char** const targetTransformed,
602 int *alphabet_size) {
603 // Alphabet is constructed from letters that are present in sequences.
604 // Each letter is assigned an ordinal number, starting from 0 up to alphabetLength - 1,
605 // and new query and target are created in which letters are replaced with their ordinal numbers.
606 // This query and target are used in all the calculations later.
607 *queryTransformed = malloc(sizeof(unsigned char) * queryLength);
608 *targetTransformed = malloc(sizeof(unsigned char) * targetLength);
609
610 char *alphabet = malloc(MAX_UCHAR+1), *alphabet_cp = alphabet;
611
612 // Alphabet information, it is constructed on fly while transforming sequences.
613 // letterIdx[c] is index of letter c in alphabet.
614 unsigned char letterIdx[MAX_UCHAR + 1];
615 bool inAlphabet[MAX_UCHAR + 1]; // inAlphabet[c] is true if c is in alphabet
616 for (int i = 0; i < MAX_UCHAR + 1; i++) inAlphabet[i] = false;
617
618 for (int i = 0; i < queryLength; i++) {
619 unsigned char c = queryOriginal[i];
620 if (!inAlphabet[c]) {
621 inAlphabet[c] = true;
622 letterIdx[c] = alphabet_cp - alphabet;
623 *alphabet_cp++ = queryOriginal[i];
624 }
625 (*queryTransformed)[i] = letterIdx[c];
626 }
627 for (int i = 0; i < targetLength; i++) {
628 unsigned char c = targetOriginal[i];
629 if (!inAlphabet[c]) {
630 inAlphabet[c] = true;
631 letterIdx[c] = alphabet_cp - alphabet;
632 *alphabet_cp++ = targetOriginal[i];
633 }
634 (*targetTransformed)[i] = letterIdx[c];
635 }
636
637 *alphabet_size = alphabet_cp - alphabet;
638 return alphabet;
639 }
640
641
642 EdlibAlignConfig edlibNewAlignConfig(int k, EdlibAlignMode mode, EdlibAlignTask task,
643 const EdlibEqualityPair* additionalEqualities,
644 int additionalEqualitiesLength) {
645 EdlibAlignConfig config;
646 config.k = k;
647 config.mode = mode;
648 config.task = task;
649 config.additionalEqualities = additionalEqualities;
650 config.additionalEqualitiesLength = additionalEqualitiesLength;
651 return config;
652 }
653
654 EdlibAlignConfig edlibDefaultAlignConfig(void) {
655 return edlibNewAlignConfig(-1, EDLIB_MODE_NW, EDLIB_TASK_DISTANCE, NULL, 0);
656 }
657
658 void edlibFreeAlignResult(EdlibAlignResult result) {
659 if (result.endLocations) free(result.endLocations);
660 if (result.startLocations) free(result.startLocations);
661 if (result.alignment) free(result.alignment);
662 }