Debian Codegraph @

src/align/cssw/ssw.c

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 /* The MIT License
2
3 Copyright (c) 2012-1015 Boston College.
4
5 Permission is hereby granted, free of charge, to any person obtaining
6 a copy of this software and associated documentation files (the
7 "Software"), to deal in the Software without restriction, including
8 without limitation the rights to use, copy, modify, merge, publish,
9 distribute, sublicense, and/or sell copies of the Software, and to
10 permit persons to whom the Software is furnished to do so, subject to
11 the following conditions:
12
13 The above copyright notice and this permission notice shall be
14 included in all copies or substantial portions of the Software.
15
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
20 BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
21 ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 SOFTWARE.
24 */
25
26 /* Contact: Mengyao Zhao <[email protected]> */
27
28 /*
29 * ssw.c
30 *
31 * Created by Mengyao Zhao on 6/22/10.
32 * Copyright 2010 Boston College. All rights reserved.
33 * Version 1.2
34 * Last revision by Mengyao Zhao on 11/29/16.
35 *
36 */
37
38 #include "../../../third-party/simde/x86/sse2.h"
39 #include <pbcopper/align/cssw/ssw.h>
40
41 #include <stdint.h>
42 #include <stdlib.h>
43 #include <stdio.h>
44 #include <string.h>
45 #include <math.h>
46
47 #ifdef __GNUC__
48 #define LIKELY(x) __builtin_expect((x),1)
49 #define UNLIKELY(x) __builtin_expect((x),0)
50 #else
51 #define LIKELY(x) (x)
52 #define UNLIKELY(x) (x)
53 #endif
54
55 /* Convert the coordinate in the scoring matrix into the coordinate in one line of the band. */
56 #define set_u(u, w, i, j) { int x=(i)-(w); x=x>0?x:0; (u)=(j)-x+1; }
57
58 /* Convert the coordinate in the direction matrix into the coordinate in one line of the band. */
59 #define set_d(u, w, i, j, p) { int x=(i)-(w); x=x>0?x:0; x=(j)-x; (u)=x*3+p; }
60
61 /*! @function
62 @abstract Round an integer to the next closest power-2 integer.
63 @param x integer to be rounded (in place)
64 @discussion x will be modified.
65 */
66 #define kroundup32(x) (--(x), (x)|=(x)>>1, (x)|=(x)>>2, (x)|=(x)>>4, (x)|=(x)>>8, (x)|=(x)>>16, ++(x))
67
68 typedef struct {
69 uint16_t score;
70 int32_t ref; //0-based position
71 int32_t read; //alignment ending position on read, 0-based
72 } alignment_end;
73
74 typedef struct {
75 uint32_t* seq;
76 int32_t length;
77 } cigar;
78
79 struct _profile{
80 simde__m128i* profile_byte; // 0: none
81 simde__m128i* profile_word; // 0: none
82 const int8_t* read;
83 const int8_t* mat;
84 int32_t readLen;
85 int32_t n;
86 uint8_t bias;
87 };
88
89 /* Generate query profile rearrange query sequence & calculate the weight of match/mismatch. */
90 static simde__m128i* qP_byte (const int8_t* read_num,
91 const int8_t* mat,
92 const int32_t readLen,
93 const int32_t n, /* the edge length of the squre matrix mat */
94 uint8_t bias) {
95
96 int32_t segLen = (readLen + 15) / 16; /* Split the 128 bit register into 16 pieces.
97 Each piece is 8 bit. Split the read into 16 segments.
98 Calculat 16 segments in parallel.
99 */
100 simde__m128i* vProfile = (simde__m128i*)malloc(n * segLen * sizeof(simde__m128i));
101 int8_t* t = (int8_t*)vProfile;
102 int32_t nt, i, j, segNum;
103
104 /* Generate query profile rearrange query sequence & calculate the weight of match/mismatch */
105 for (nt = 0; LIKELY(nt < n); nt ++) {
106 for (i = 0; i < segLen; i ++) {
107 j = i;
108 for (segNum = 0; LIKELY(segNum < 16) ; segNum ++) {
109 *t++ = j>= readLen ? bias : mat[nt * n + read_num[j]] + bias;
110 j += segLen;
111 }
112 }
113 }
114 return vProfile;
115 }
116
117 /* Striped Smith-Waterman
118 Record the highest score of each reference position.
119 Return the alignment score and ending position of the best alignment, 2nd best alignment, etc.
120 Gap begin and gap extension are different.
121 wight_match > 0, all other weights < 0.
122 The returned positions are 0-based.
123 */
124 static alignment_end* sw_sse2_byte (const int8_t* ref,
125 int8_t ref_dir, // 0: forward ref; 1: reverse ref
126 int32_t refLen,
127 int32_t readLen,
128 const uint8_t weight_gapO, /* will be used as - */
129 const uint8_t weight_gapE, /* will be used as - */
130 const simde__m128i* vProfile,
131 uint8_t terminate, /* the best alignment score: used to terminate
132 the matrix calculation when locating the
133 alignment beginning point. If this score
134 is set to 0, it will not be used */
135 uint8_t bias, /* Shift 0 point to a positive value. */
136 int32_t maskLen) {
137
138 #define max16(m, vm) (vm) = simde_mm_max_epu8((vm), simde_mm_srli_si128((vm), 8)); \
139 (vm) = simde_mm_max_epu8((vm), simde_mm_srli_si128((vm), 4)); \
140 (vm) = simde_mm_max_epu8((vm), simde_mm_srli_si128((vm), 2)); \
141 (vm) = simde_mm_max_epu8((vm), simde_mm_srli_si128((vm), 1)); \
142 (m) = simde_mm_extract_epi16((vm), 0)
143
144 uint8_t max = 0; /* the max alignment score */
145 int32_t end_read = readLen - 1;
146 int32_t end_ref = -1; /* 0_based best alignment ending point; Initialized as isn't aligned -1. */
147 int32_t segLen = (readLen + 15) / 16; /* number of segment */
148
149 /* array to record the largest score of each reference position */
150 uint8_t* maxColumn = (uint8_t*) calloc(refLen, 1);
151
152 /* array to record the alignment read ending position of the largest score of each reference position */
153 int32_t* end_read_column = (int32_t*) calloc(refLen, sizeof(int32_t));
154
155 /* Define 16 byte 0 vector. */
156 simde__m128i vZero = simde_mm_set1_epi32(0);
157
158 simde__m128i* pvHStore = (simde__m128i*) calloc(segLen, sizeof(simde__m128i));
159 simde__m128i* pvHLoad = (simde__m128i*) calloc(segLen, sizeof(simde__m128i));
160 simde__m128i* pvE = (simde__m128i*) calloc(segLen, sizeof(simde__m128i));
161 simde__m128i* pvHmax = (simde__m128i*) calloc(segLen, sizeof(simde__m128i));
162
163 int32_t i, j;
164 /* 16 byte insertion begin vector */
165 simde__m128i vGapO = simde_mm_set1_epi8(weight_gapO);
166
167 /* 16 byte insertion extension vector */
168 simde__m128i vGapE = simde_mm_set1_epi8(weight_gapE);
169
170 /* 16 byte bias vector */
171 simde__m128i vBias = simde_mm_set1_epi8(bias);
172
173 simde__m128i vMaxScore = vZero; /* Trace the highest score of the whole SW matrix. */
174 simde__m128i vMaxMark = vZero; /* Trace the highest score till the previous column. */
175 simde__m128i vTemp;
176 int32_t edge, begin = 0, end = refLen, step = 1;
177
178 /* outer loop to process the reference sequence */
179 if (ref_dir == 1) {
180 begin = refLen - 1;
181 end = -1;
182 step = -1;
183 }
184 for (i = begin; LIKELY(i != end); i += step) {
185 int32_t cmp;
186 simde__m128i e, vF = vZero, vMaxColumn = vZero; /* Initialize F value to 0.
187 Any errors to vH values will be corrected in the Lazy_F loop.
188 */
189
190 simde__m128i vH = pvHStore[segLen - 1];
191 vH = simde_mm_slli_si128 (vH, 1); /* Shift the 128-bit value in vH left by 1 byte. */
192 const simde__m128i* vP = vProfile + ref[i] * segLen; /* Right part of the vProfile */
193
194 /* Swap the 2 H buffers. */
195 simde__m128i* pv = pvHLoad;
196 pvHLoad = pvHStore;
197 pvHStore = pv;
198
199 /* inner loop to process the query sequence */
200 for (j = 0; LIKELY(j < segLen); ++j) {
201 vH = simde_mm_adds_epu8(vH, simde_mm_load_si128(vP + j));
202 vH = simde_mm_subs_epu8(vH, vBias); /* vH will be always > 0 */
203
204 /* Get max from vH, vE and vF. */
205 e = simde_mm_load_si128(pvE + j);
206 vH = simde_mm_max_epu8(vH, e);
207 vH = simde_mm_max_epu8(vH, vF);
208 vMaxColumn = simde_mm_max_epu8(vMaxColumn, vH);
209
210 /* Save vH values. */
211 simde_mm_store_si128(pvHStore + j, vH);
212
213 /* Update vE value. */
214 vH = simde_mm_subs_epu8(vH, vGapO); /* saturation arithmetic, result >= 0 */
215 e = simde_mm_subs_epu8(e, vGapE);
216 e = simde_mm_max_epu8(e, vH);
217 simde_mm_store_si128(pvE + j, e);
218
219 /* Update vF value. */
220 vF = simde_mm_subs_epu8(vF, vGapE);
221 vF = simde_mm_max_epu8(vF, vH);
222
223 /* Load the next vH. */
224 vH = simde_mm_load_si128(pvHLoad + j);
225 }
226
227 /* Lazy_F loop: has been revised to disallow adjecent insertion and then deletion, so don't update E(i, j), learn from SWPS3 */
228 /* reset pointers to the start of the saved data */
229 j = 0;
230 vH = simde_mm_load_si128 (pvHStore + j);
231
232 /* the computed vF value is for the given column. since */
233 /* we are at the end, we need to shift the vF value over */
234 /* to the next column. */
235 vF = simde_mm_slli_si128 (vF, 1);
236 vTemp = simde_mm_subs_epu8 (vH, vGapO);
237 vTemp = simde_mm_subs_epu8 (vF, vTemp);
238 vTemp = simde_mm_cmpeq_epi8 (vTemp, vZero);
239 cmp = simde_mm_movemask_epi8 (vTemp);
240
241 while (cmp != 0xffff)
242 {
243 vH = simde_mm_max_epu8 (vH, vF);
244 vMaxColumn = simde_mm_max_epu8(vMaxColumn, vH);
245 simde_mm_store_si128 (pvHStore + j, vH);
246 vF = simde_mm_subs_epu8 (vF, vGapE);
247 j++;
248 if (j >= segLen)
249 {
250 j = 0;
251 vF = simde_mm_slli_si128 (vF, 1);
252 }
253 vH = simde_mm_load_si128 (pvHStore + j);
254
255 vTemp = simde_mm_subs_epu8 (vH, vGapO);
256 vTemp = simde_mm_subs_epu8 (vF, vTemp);
257 vTemp = simde_mm_cmpeq_epi8 (vTemp, vZero);
258 cmp = simde_mm_movemask_epi8 (vTemp);
259 }
260
261 vMaxScore = simde_mm_max_epu8(vMaxScore, vMaxColumn);
262 vTemp = simde_mm_cmpeq_epi8(vMaxMark, vMaxScore);
263 cmp = simde_mm_movemask_epi8(vTemp);
264 if (cmp != 0xffff) {
265 uint8_t temp;
266 vMaxMark = vMaxScore;
267 max16(temp, vMaxScore);
268 vMaxScore = vMaxMark;
269
270 if (LIKELY(temp > max)) {
271 max = temp;
272 if (max + bias >= 255) break; //overflow
273 end_ref = i;
274
275 /* Store the column with the highest alignment score in order to trace the alignment ending position on read. */
276 for (j = 0; LIKELY(j < segLen); ++j) pvHmax[j] = pvHStore[j];
277 }
278 }
279
280 /* Record the max score of current column. */
281 max16(maxColumn[i], vMaxColumn);
282 if (maxColumn[i] == terminate) break;
283 }
284
285 /* Trace the alignment ending position on read. */
286 uint8_t *t = (uint8_t*)pvHmax;
287 int32_t column_len = segLen * 16;
288 for (i = 0; LIKELY(i < column_len); ++i, ++t) {
289 int32_t temp;
290 if (*t == max) {
291 temp = i / 16 + i % 16 * segLen;
292 if (temp < end_read) end_read = temp;
293 }
294 }
295
296 free(pvHmax);
297 free(pvE);
298 free(pvHLoad);
299 free(pvHStore);
300
301 /* Find the most possible 2nd best alignment. */
302 alignment_end* bests = (alignment_end*) calloc(2, sizeof(alignment_end));
303 bests[0].score = max + bias >= 255 ? 255 : max;
304 bests[0].ref = end_ref;
305 bests[0].read = end_read;
306
307 bests[1].score = 0;
308 bests[1].ref = 0;
309 bests[1].read = 0;
310
311 edge = (end_ref - maskLen) > 0 ? (end_ref - maskLen) : 0;
312 for (i = 0; i < edge; i ++) {
313 if (maxColumn[i] > bests[1].score) {
314 bests[1].score = maxColumn[i];
315 bests[1].ref = i;
316 }
317 }
318 edge = (end_ref + maskLen) > refLen ? refLen : (end_ref + maskLen);
319 for (i = edge + 1; i < refLen; i ++) {
320 if (maxColumn[i] > bests[1].score) {
321 bests[1].score = maxColumn[i];
322 bests[1].ref = i;
323 }
324 }
325
326 free(maxColumn);
327 free(end_read_column);
328 return bests;
329 }
330
331 static simde__m128i* qP_word (const int8_t* read_num,
332 const int8_t* mat,
333 const int32_t readLen,
334 const int32_t n) {
335
336 int32_t segLen = (readLen + 7) / 8;
337 simde__m128i* vProfile = (simde__m128i*)malloc(n * segLen * sizeof(simde__m128i));
338 int16_t* t = (int16_t*)vProfile;
339 int32_t nt, i, j;
340 int32_t segNum;
341
342 /* Generate query profile rearrange query sequence & calculate the weight of match/mismatch */
343 for (nt = 0; LIKELY(nt < n); nt ++) {
344 for (i = 0; i < segLen; i ++) {
345 j = i;
346 for (segNum = 0; LIKELY(segNum < 8) ; segNum ++) {
347 *t++ = j>= readLen ? 0 : mat[nt * n + read_num[j]];
348 j += segLen;
349 }
350 }
351 }
352 return vProfile;
353 }
354
355 static alignment_end* sw_sse2_word (const int8_t* ref,
356 int8_t ref_dir, // 0: forward ref; 1: reverse ref
357 int32_t refLen,
358 int32_t readLen,
359 const uint8_t weight_gapO, /* will be used as - */
360 const uint8_t weight_gapE, /* will be used as - */
361 const simde__m128i* vProfile,
362 uint16_t terminate,
363 int32_t maskLen) {
364
365 #define max8(m, vm) (vm) = simde_mm_max_epi16((vm), simde_mm_srli_si128((vm), 8)); \
366 (vm) = simde_mm_max_epi16((vm), simde_mm_srli_si128((vm), 4)); \
367 (vm) = simde_mm_max_epi16((vm), simde_mm_srli_si128((vm), 2)); \
368 (m) = simde_mm_extract_epi16((vm), 0)
369
370 uint16_t max = 0; /* the max alignment score */
371 int32_t end_read = readLen - 1;
372 int32_t end_ref = 0; /* 1_based best alignment ending point; Initialized as isn't aligned - 0. */
373 int32_t segLen = (readLen + 7) / 8; /* number of segment */
374
375 /* array to record the largest score of each reference position */
376 uint16_t* maxColumn = (uint16_t*) calloc(refLen, 2);
377
378 /* array to record the alignment read ending position of the largest score of each reference position */
379 int32_t* end_read_column = (int32_t*) calloc(refLen, sizeof(int32_t));
380
381 /* Define 16 byte 0 vector. */
382 simde__m128i vZero = simde_mm_set1_epi32(0);
383
384 simde__m128i* pvHStore = (simde__m128i*) calloc(segLen, sizeof(simde__m128i));
385 simde__m128i* pvHLoad = (simde__m128i*) calloc(segLen, sizeof(simde__m128i));
386 simde__m128i* pvE = (simde__m128i*) calloc(segLen, sizeof(simde__m128i));
387 simde__m128i* pvHmax = (simde__m128i*) calloc(segLen, sizeof(simde__m128i));
388
389 int32_t i, j, k;
390 /* 16 byte insertion begin vector */
391 simde__m128i vGapO = simde_mm_set1_epi16(weight_gapO);
392
393 /* 16 byte insertion extension vector */
394 simde__m128i vGapE = simde_mm_set1_epi16(weight_gapE);
395
396 simde__m128i vMaxScore = vZero; /* Trace the highest score of the whole SW matrix. */
397 simde__m128i vMaxMark = vZero; /* Trace the highest score till the previous column. */
398 simde__m128i vTemp;
399 int32_t edge, begin = 0, end = refLen, step = 1;
400
401 /* outer loop to process the reference sequence */
402 if (ref_dir == 1) {
403 begin = refLen - 1;
404 end = -1;
405 step = -1;
406 }
407 for (i = begin; LIKELY(i != end); i += step) {
408 int32_t cmp;
409 simde__m128i e, vF = vZero; /* Initialize F value to 0.
410 Any errors to vH values will be corrected in the Lazy_F loop.
411 */
412 simde__m128i vH = pvHStore[segLen - 1];
413 vH = simde_mm_slli_si128 (vH, 2); /* Shift the 128-bit value in vH left by 2 byte. */
414
415 /* Swap the 2 H buffers. */
416 simde__m128i* pv = pvHLoad;
417
418 simde__m128i vMaxColumn = vZero; /* vMaxColumn is used to record the max values of column i. */
419
420 const simde__m128i* vP = vProfile + ref[i] * segLen; /* Right part of the vProfile */
421 pvHLoad = pvHStore;
422 pvHStore = pv;
423
424 /* inner loop to process the query sequence */
425 for (j = 0; LIKELY(j < segLen); j ++) {
426 vH = simde_mm_adds_epi16(vH, simde_mm_load_si128(vP + j));
427
428 /* Get max from vH, vE and vF. */
429 e = simde_mm_load_si128(pvE + j);
430 vH = simde_mm_max_epi16(vH, e);
431 vH = simde_mm_max_epi16(vH, vF);
432 vMaxColumn = simde_mm_max_epi16(vMaxColumn, vH);
433
434 /* Save vH values. */
435 simde_mm_store_si128(pvHStore + j, vH);
436
437 /* Update vE value. */
438 vH = simde_mm_subs_epu16(vH, vGapO); /* saturation arithmetic, result >= 0 */
439 e = simde_mm_subs_epu16(e, vGapE);
440 e = simde_mm_max_epi16(e, vH);
441 simde_mm_store_si128(pvE + j, e);
442
443 /* Update vF value. */
444 vF = simde_mm_subs_epu16(vF, vGapE);
445 vF = simde_mm_max_epi16(vF, vH);
446
447 /* Load the next vH. */
448 vH = simde_mm_load_si128(pvHLoad + j);
449 }
450
451 /* Lazy_F loop: has been revised to disallow adjecent insertion and then deletion, so don't update E(i, j), learn from SWPS3 */
452 for (k = 0; LIKELY(k < 8); ++k) {
453 vF = simde_mm_slli_si128 (vF, 2);
454 for (j = 0; LIKELY(j < segLen); ++j) {
455 vH = simde_mm_load_si128(pvHStore + j);
456 vH = simde_mm_max_epi16(vH, vF);
457 vMaxColumn = simde_mm_max_epi16(vMaxColumn, vH); //newly added line
458 simde_mm_store_si128(pvHStore + j, vH);
459 vH = simde_mm_subs_epu16(vH, vGapO);
460 vF = simde_mm_subs_epu16(vF, vGapE);
461 if (UNLIKELY(! simde_mm_movemask_epi8(simde_mm_cmpgt_epi16(vF, vH)))) goto end;
462 }
463 }
464
465 end:
466 vMaxScore = simde_mm_max_epi16(vMaxScore, vMaxColumn);
467 vTemp = simde_mm_cmpeq_epi16(vMaxMark, vMaxScore);
468 cmp = simde_mm_movemask_epi8(vTemp);
469 if (cmp != 0xffff) {
470 uint16_t temp;
471 vMaxMark = vMaxScore;
472 max8(temp, vMaxScore);
473 vMaxScore = vMaxMark;
474
475 if (LIKELY(temp > max)) {
476 max = temp;
477 end_ref = i;
478 for (j = 0; LIKELY(j < segLen); ++j) pvHmax[j] = pvHStore[j];
479 }
480 }
481
482 /* Record the max score of current column. */
483 max8(maxColumn[i], vMaxColumn);
484 if (maxColumn[i] == terminate) break;
485 }
486
487 /* Trace the alignment ending position on read. */
488 uint16_t *t = (uint16_t*)pvHmax;
489 int32_t column_len = segLen * 8;
490 for (i = 0; LIKELY(i < column_len); ++i, ++t) {
491 int32_t temp;
492 if (*t == max) {
493 temp = i / 8 + i % 8 * segLen;
494 if (temp < end_read) end_read = temp;
495 }
496 }
497
498 free(pvHmax);
499 free(pvE);
500 free(pvHLoad);
501 free(pvHStore);
502
503 /* Find the most possible 2nd best alignment. */
504 alignment_end* bests = (alignment_end*) calloc(2, sizeof(alignment_end));
505 bests[0].score = max;
506 bests[0].ref = end_ref;
507 bests[0].read = end_read;
508
509 bests[1].score = 0;
510 bests[1].ref = 0;
511 bests[1].read = 0;
512
513 edge = (end_ref - maskLen) > 0 ? (end_ref - maskLen) : 0;
514 for (i = 0; i < edge; i ++) {
515 if (maxColumn[i] > bests[1].score) {
516 bests[1].score = maxColumn[i];
517 bests[1].ref = i;
518 }
519 }
520 edge = (end_ref + maskLen) > refLen ? refLen : (end_ref + maskLen);
521 for (i = edge; i < refLen; i ++) {
522 if (maxColumn[i] > bests[1].score) {
523 bests[1].score = maxColumn[i];
524 bests[1].ref = i;
525 }
526 }
527
528 free(maxColumn);
529 free(end_read_column);
530 return bests;
531 }
532
533 /*! @function Produce CIGAR 32-bit unsigned integer from CIGAR operation and CIGAR length
534 @param length length of CIGAR
535 @param op_letter CIGAR operation character ('M', 'I', etc)
536 @return 32-bit unsigned integer, representing encoded CIGAR operation and length
537 */
538 uint32_t to_cigar_int (uint32_t length, char op_letter)
539 {
540 switch (op_letter) {
541 case 'M': /* alignment match (can be a sequence match or mismatch */
542 default:
543 return length << BAM_CIGAR_SHIFT;
544 case 'S': /* soft clipping (clipped sequences present in SEQ) */
545 return (length << BAM_CIGAR_SHIFT) | (4u);
546 case 'D': /* deletion from the reference */
547 return (length << BAM_CIGAR_SHIFT) | (2u);
548 case 'I': /* insertion to the reference */
549 return (length << BAM_CIGAR_SHIFT) | (1u);
550 case 'H': /* hard clipping (clipped sequences NOT present in SEQ) */
551 return (length << BAM_CIGAR_SHIFT) | (5u);
552 case 'N': /* skipped region from the reference */
553 return (length << BAM_CIGAR_SHIFT) | (3u);
554 case 'P': /* padding (silent deletion from padded reference) */
555 return (length << BAM_CIGAR_SHIFT) | (6u);
556 case '=': /* sequence match */
557 return (length << BAM_CIGAR_SHIFT) | (7u);
558 case 'X': /* sequence mismatch */
559 return (length << BAM_CIGAR_SHIFT) | (8u);
560 }
561 return (uint32_t)-1; // This never happens
562 }
563
564 static cigar* banded_sw (const int8_t* ref,
565 const int8_t* read,
566 int32_t refLen,
567 int32_t readLen,
568 int32_t score,
569 const uint32_t weight_gapO, /* will be used as - */
570 const uint32_t weight_gapE, /* will be used as - */
571 int32_t band_width,
572 const int8_t* mat, /* pointer to the weight matrix */
573 int32_t n) {
574
575 uint32_t *c = (uint32_t*)malloc(16 * sizeof(uint32_t)), *c1;
576 int32_t i, j, e, f, temp1, temp2, s = 16, s1 = 8, l, max = 0;
577 int64_t s2 = 1024;
578 char op, prev_op;
579 int32_t width, width_d, *h_b, *e_b, *h_c;
580 int8_t *direction, *direction_line;
581 cigar* result = (cigar*)malloc(sizeof(cigar));
582 h_b = (int32_t*)malloc(s1 * sizeof(int32_t));
583 e_b = (int32_t*)malloc(s1 * sizeof(int32_t));
584 h_c = (int32_t*)malloc(s1 * sizeof(int32_t));
585 direction = (int8_t*)malloc(s2 * sizeof(int8_t));
586
587 do {
588 width = band_width * 2 + 3, width_d = band_width * 2 + 1;
589 while (width >= s1) {
590 ++s1;
591 kroundup32(s1);
592 h_b = (int32_t*)realloc(h_b, s1 * sizeof(int32_t));
593 e_b = (int32_t*)realloc(e_b, s1 * sizeof(int32_t));
594 h_c = (int32_t*)realloc(h_c, s1 * sizeof(int32_t));
595 }
596 while (width_d * readLen * 3 >= s2) {
597 ++s2;
598 kroundup32(s2);
599 if (s2 < 0) {
600 fprintf(stderr, "Alignment score and position are not consensus.\n");
601 exit(1);
602 }
603 direction = (int8_t*)realloc(direction, s2 * sizeof(int8_t));
604 }
605 direction_line = direction;
606 for (j = 1; LIKELY(j < width - 1); j ++) h_b[j] = 0;
607 for (i = 0; LIKELY(i < readLen); i ++) {
608 int32_t beg = 0, end = refLen - 1, u = 0, edge;
609 j = i - band_width; beg = beg > j ? beg : j; // band start
610 j = i + band_width; end = end < j ? end : j; // band end
611 edge = end + 1 < width - 1 ? end + 1 : width - 1;
612 f = h_b[0] = e_b[0] = h_b[edge] = e_b[edge] = h_c[0] = 0;
613 direction_line = direction + width_d * i * 3;
614
615 for (j = beg; LIKELY(j <= end); j ++) {
616 int32_t b, e1, f1, d, de, df, dh;
617 set_u(u, band_width, i, j); set_u(e, band_width, i - 1, j);
618 set_u(b, band_width, i, j - 1); set_u(d, band_width, i - 1, j - 1);
619 set_d(de, band_width, i, j, 0);
620 set_d(df, band_width, i, j, 1);
621 set_d(dh, band_width, i, j, 2);
622
623 temp1 = i == 0 ? -weight_gapO : h_b[e] - weight_gapO;
624 temp2 = i == 0 ? -weight_gapE : e_b[e] - weight_gapE;
625 e_b[u] = temp1 > temp2 ? temp1 : temp2;
626 direction_line[de] = temp1 > temp2 ? 3 : 2;
627
628 temp1 = h_c[b] - weight_gapO;
629 temp2 = f - weight_gapE;
630 f = temp1 > temp2 ? temp1 : temp2;
631 direction_line[df] = temp1 > temp2 ? 5 : 4;
632
633 e1 = e_b[u] > 0 ? e_b[u] : 0;
634 f1 = f > 0 ? f : 0;
635 temp1 = e1 > f1 ? e1 : f1;
636 temp2 = h_b[d] + mat[ref[j] * n + read[i]];
637 h_c[u] = temp1 > temp2 ? temp1 : temp2;
638
639 if (h_c[u] > max) max = h_c[u];
640
641 if (temp1 <= temp2) direction_line[dh] = 1;
642 else direction_line[dh] = e1 > f1 ? direction_line[de] : direction_line[df];
643 }
644 for (j = 1; j <= u; j ++) h_b[j] = h_c[j];
645 }
646 band_width *= 2;
647 } while (LIKELY(max < score));
648 band_width /= 2;
649
650 // trace back
651 i = readLen - 1;
652 j = refLen - 1;
653 e = 0; // Count the number of M, D or I.
654 l = 0; // record length of current cigar
655 op = prev_op = 'M';
656 temp2 = 2; // h
657 while (LIKELY(i > 0)) {
658 set_d(temp1, band_width, i, j, temp2);
659 switch (direction_line[temp1]) {
660 case 1:
661 --i;
662 --j;
663 temp2 = 2;
664 direction_line -= width_d * 3;
665 op = 'M';
666 break;
667 case 2:
668 --i;
669 temp2 = 0; // e
670 direction_line -= width_d * 3;
671 op = 'I';
672 break;
673 case 3:
674 --i;
675 temp2 = 2;
676 direction_line -= width_d * 3;
677 op = 'I';
678 break;
679 case 4:
680 --j;
681 temp2 = 1;
682 op = 'D';
683 break;
684 case 5:
685 --j;
686 temp2 = 2;
687 op = 'D';
688 break;
689 default:
690 fprintf(stderr, "Trace back error: %d.\n", direction_line[temp1 - 1]);
691 free(direction);
692 free(h_c);
693 free(e_b);
694 free(h_b);
695 free(c);
696 free(result);
697 return 0;
698 }
699 if (op == prev_op) ++e;
700 else {
701 ++l;
702 while (l >= s) {
703 ++s;
704 kroundup32(s);
705 c = (uint32_t*)realloc(c, s * sizeof(uint32_t));
706 }
707 c[l - 1] = to_cigar_int(e, prev_op);
708 prev_op = op;
709 e = 1;
710 }
711 }
712 if (op == 'M') {
713 ++l;
714 while (l >= s) {
715 ++s;
716 kroundup32(s);
717 c = (uint32_t*)realloc(c, s * sizeof(uint32_t));
718 }
719 c[l - 1] = to_cigar_int(e + 1, op);
720 }else {
721 l += 2;
722 while (l >= s) {
723 ++s;
724 kroundup32(s);
725 c = (uint32_t*)realloc(c, s * sizeof(uint32_t));
726 }
727 c[l - 2] = to_cigar_int(e, op);
728 c[l - 1] = to_cigar_int(1, 'M');
729 }
730
731 // reverse cigar
732 c1 = (uint32_t*)malloc(l * sizeof(uint32_t));
733 s = 0;
734 e = l - 1;
735 while (LIKELY(s <= e)) {
736 c1[s] = c[e];
737 c1[e] = c[s];
738 ++ s;
739 -- e;
740 }
741 result->seq = c1;
742 result->length = l;
743
744 free(direction);
745 free(h_c);
746 free(e_b);
747 free(h_b);
748 free(c);
749 return result;
750 }
751
752 static int8_t* seq_reverse(const int8_t* seq, int32_t end) /* end is 0-based alignment ending position */
753 {
754 int8_t* reverse = (int8_t*)calloc(end + 1, sizeof(int8_t));
755 int32_t start = 0;
756 while (LIKELY(start <= end)) {
757 reverse[start] = seq[end];
758 reverse[end] = seq[start];
759 ++ start;
760 -- end;
761 }
762 return reverse;
763 }
764
765 s_profile* ssw_init (const int8_t* read, const int32_t readLen, const int8_t* mat, const int32_t n, const int8_t score_size) {
766 s_profile* p = (s_profile*)calloc(1, sizeof(struct _profile));
767 p->profile_byte = 0;
768 p->profile_word = 0;
769 p->bias = 0;
770
771 if (score_size == 0 || score_size == 2) {
772 /* Find the bias to use in the substitution matrix */
773 int32_t bias = 0, i;
774 for (i = 0; i < n*n; i++) if (mat[i] < bias) bias = mat[i];
775 bias = abs(bias);
776
777 p->bias = bias;
778 p->profile_byte = qP_byte (read, mat, readLen, n, bias);
779 }
780 if (score_size == 1 || score_size == 2) p->profile_word = qP_word (read, mat, readLen, n);
781 p->read = read;
782 p->mat = mat;
783 p->readLen = readLen;
784 p->n = n;
785 return p;
786 }
787
788 void init_destroy (s_profile* p) {
789 free(p->profile_byte);
790 free(p->profile_word);
791 free(p);
792 }
793
794 s_align* ssw_align (const s_profile* prof,
795 const int8_t* ref,
796 int32_t refLen,
797 const uint8_t weight_gapO,
798 const uint8_t weight_gapE,
799 const uint8_t flag, // (from high to low) bit 5: return the best alignment beginning position; 6: if (ref_end1 - ref_begin1 <= filterd) && (read_end1 - read_begin1 <= filterd), return cigar; 7: if max score >= filters, return cigar; 8: always return cigar; if 6 & 7 are both setted, only return cigar when both filter fulfilled
800 const uint16_t filters,
801 const int32_t filterd,
802 const int32_t maskLen) {
803
804 alignment_end* bests = 0, *bests_reverse = 0;
805 simde__m128i* vP = 0;
806 int32_t word = 0, band_width = 0, readLen = prof->readLen;
807 int8_t* read_reverse = 0;
808 cigar* path;
809 s_align* r = (s_align*)calloc(1, sizeof(s_align));
810 r->ref_begin1 = -1;
811 r->read_begin1 = -1;
812 r->cigar = 0;
813 r->cigarLen = 0;
814 if (maskLen < 15) {
815 fprintf(stderr, "When maskLen < 15, the function ssw_align doesn't return 2nd best alignment information.\n");
816 }
817
818 // Find the alignment scores and ending positions
819 if (prof->profile_byte) {
820 bests = sw_sse2_byte(ref, 0, refLen, readLen, weight_gapO, weight_gapE, prof->profile_byte, -1, prof->bias, maskLen);
821 if (prof->profile_word && bests[0].score == 255) {
822 free(bests);
823 bests = sw_sse2_word(ref, 0, refLen, readLen, weight_gapO, weight_gapE, prof->profile_word, -1, maskLen);
824 word = 1;
825 } else if (bests[0].score == 255) {
826 fprintf(stderr, "Please set 2 to the score_size parameter of the function ssw_init, otherwise the alignment results will be incorrect.\n");
827 free(r);
828 return NULL;
829 }
830 }else if (prof->profile_word) {
831 bests = sw_sse2_word(ref, 0, refLen, readLen, weight_gapO, weight_gapE, prof->profile_word, -1, maskLen);
832 word = 1;
833 }else {
834 fprintf(stderr, "Please call the function ssw_init before ssw_align.\n");
835 free(r);
836 return NULL;
837 }
838 r->score1 = bests[0].score;
839 r->ref_end1 = bests[0].ref;
840 r->read_end1 = bests[0].read;
841 if (maskLen >= 15) {
842 r->score2 = bests[1].score;
843 r->ref_end2 = bests[1].ref;
844 } else {
845 r->score2 = 0;
846 r->ref_end2 = -1;
847 }
848 free(bests);
849 if (flag == 0 || (flag == 2 && r->score1 < filters)) goto end;
850
851 // Find the beginning position of the best alignment.
852 read_reverse = seq_reverse(prof->read, r->read_end1);
853 if (word == 0) {
854 vP = qP_byte(read_reverse, prof->mat, r->read_end1 + 1, prof->n, prof->bias);
855 bests_reverse = sw_sse2_byte(ref, 1, r->ref_end1 + 1, r->read_end1 + 1, weight_gapO, weight_gapE, vP, r->score1, prof->bias, maskLen);
856 } else {
857 vP = qP_word(read_reverse, prof->mat, r->read_end1 + 1, prof->n);
858 bests_reverse = sw_sse2_word(ref, 1, r->ref_end1 + 1, r->read_end1 + 1, weight_gapO, weight_gapE, vP, r->score1, maskLen);
859 }
860 free(vP);
861 free(read_reverse);
862 r->ref_begin1 = bests_reverse[0].ref;
863 r->read_begin1 = r->read_end1 - bests_reverse[0].read;
864 free(bests_reverse);
865 if ((7&flag) == 0 || ((2&flag) != 0 && r->score1 < filters) || ((4&flag) != 0 && (r->ref_end1 - r->ref_begin1 > filterd || r->read_end1 - r->read_begin1 > filterd))) goto end;
866
867 // Generate cigar.
868 refLen = r->ref_end1 - r->ref_begin1 + 1;
869 readLen = r->read_end1 - r->read_begin1 + 1;
870 band_width = abs(refLen - readLen) + 1;
871 path = banded_sw(ref + r->ref_begin1, prof->read + r->read_begin1, refLen, readLen, r->score1, weight_gapO, weight_gapE, band_width, prof->mat, prof->n);
872 if (path == 0) {
873 free(r);
874 r = NULL;
875 }
876 else {
877 r->cigar = path->seq;
878 r->cigarLen = path->length;
879 free(path);
880 }
881
882 end:
883 return r;
884 }
885
886 void align_destroy (s_align* a) {
887 free(a->cigar);
888 free(a);
889 }
890
891 uint32_t* add_cigar (uint32_t* new_cigar, int32_t* p, int32_t* s, uint32_t length, char op) {
892 if ((*p) >= (*s)) {
893 ++(*s);
894 kroundup32(*s);
895 new_cigar = (uint32_t*)realloc(new_cigar, (*s)*sizeof(uint32_t));
896 }
897 new_cigar[(*p) ++] = to_cigar_int(length, op);
898 return new_cigar;
899 }
900
901 uint32_t* store_previous_m (int8_t choice, // 0: current not M, 1: current match, 2: current mismatch
902 uint32_t* length_m,
903 uint32_t* length_x,
904 int32_t* p,
905 int32_t* s,
906 uint32_t* new_cigar) {
907
908 if ((*length_m) && (choice == 2 || !choice)) {
909 new_cigar = add_cigar (new_cigar, p, s, (*length_m), '=');
910 (*length_m) = 0;
911 } else if ((*length_x) && (choice == 1 || !choice)) {
912 new_cigar = add_cigar (new_cigar, p, s, (*length_x), 'X');
913 (*length_x) = 0;
914 }
915 return new_cigar;
916 }
917
918 /*! @function:
919 1. Calculate the number of mismatches.
920 2. Modify the cigar string:
921 differentiate matches (=) and mismatches(X); add softclip(S) at the beginning and ending of the original cigar.
922 @return:
923 The number of mismatches.
924 The cigar and cigarLen are modified.
925 */
926 int32_t mark_mismatch (int32_t ref_begin1,
927 int32_t read_begin1,
928 int32_t read_end1,
929 const int8_t* ref,
930 const int8_t* read,
931 int32_t readLen,
932 uint32_t** cigar,
933 int32_t* cigarLen) {
934
935 int32_t mismatch_length = 0, p = 0, i, length, j, s = *cigarLen + 2;
936 uint32_t *new_cigar = (uint32_t*)malloc(s*sizeof(uint32_t)), length_m = 0, length_x = 0;
937 char op;
938
939 ref += ref_begin1;
940 read += read_begin1;
941 if (read_begin1 > 0) new_cigar[p ++] = to_cigar_int(read_begin1, 'S');
942 for (i = 0; i < (*cigarLen); ++i) {
943 op = cigar_int_to_op((*cigar)[i]);
944 length = cigar_int_to_len((*cigar)[i]);
945 if (op == 'M') {
946 for (j = 0; j < length; ++j) {
947 if (*ref != *read) {
948 ++ mismatch_length;
949 // the previous is match; however the current one is mismatche
950 new_cigar = store_previous_m (2, &length_m, &length_x, &p, &s, new_cigar);
951 ++ length_x;
952 } else {
953 // the previous is mismatch; however the current one is matche
954 new_cigar = store_previous_m (1, &length_m, &length_x, &p, &s, new_cigar);
955 ++ length_m;
956 }
957 ++ ref;
958 ++ read;
959 }
960 }else if (op == 'I') {
961 read += length;
962 mismatch_length += length;
963 new_cigar = store_previous_m (0, &length_m, &length_x, &p, &s, new_cigar);
964 new_cigar = add_cigar (new_cigar, &p, &s, length, 'I');
965 }else if (op == 'D') {
966 ref += length;
967 mismatch_length += length;
968 new_cigar = store_previous_m (0, &length_m, &length_x, &p, &s, new_cigar);
969 new_cigar = add_cigar (new_cigar, &p, &s, length, 'D');
970 }
971 }
972 new_cigar = store_previous_m (0, &length_m, &length_x, &p, &s, new_cigar);
973
974 length = readLen - read_end1 - 1;
975 if (length > 0) new_cigar = add_cigar(new_cigar, &p, &s, length, 'S');
976
977 (*cigarLen) = p;
978 free(*cigar);
979 (*cigar) = new_cigar;
980 return mismatch_length;
981 }
982