Debian Codegraph @

bcftools/edlib.c.pysam.c

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