ksw.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. /* The MIT License
  2. Copyright (c) 2011 by Attractive Chaos <attractor@live.co.uk>
  3. Permission is hereby granted, free of charge, to any person obtaining
  4. a copy of this software and associated documentation files (the
  5. "Software"), to deal in the Software without restriction, including
  6. without limitation the rights to use, copy, modify, merge, publish,
  7. distribute, sublicense, and/or sell copies of the Software, and to
  8. permit persons to whom the Software is furnished to do so, subject to
  9. the following conditions:
  10. The above copyright notice and this permission notice shall be
  11. included in all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  13. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  14. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  15. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  16. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  17. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  18. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. SOFTWARE.
  20. */
  21. #include <stdlib.h>
  22. #include <stdint.h>
  23. #include <emmintrin.h>
  24. #include "ksw.h"
  25. #ifdef USE_MALLOC_WRAPPERS
  26. # include "malloc_wrap.h"
  27. #endif
  28. #ifdef __GNUC__
  29. #define LIKELY(x) __builtin_expect((x),1)
  30. #define UNLIKELY(x) __builtin_expect((x),0)
  31. #else
  32. #define LIKELY(x) (x)
  33. #define UNLIKELY(x) (x)
  34. #endif
  35. const kswr_t g_defr = { 0, -1, -1, -1, -1, -1, -1 };
  36. struct _kswq_t {
  37. int qlen, slen;
  38. uint8_t shift, mdiff, max, size;
  39. __m128i *qp, *H0, *H1, *E, *Hmax;
  40. };
  41. /**
  42. * Initialize the query data structure
  43. *
  44. * @param size Number of bytes used to store a score; valid valures are 1 or 2
  45. * @param qlen Length of the query sequence
  46. * @param query Query sequence
  47. * @param m Size of the alphabet
  48. * @param mat Scoring matrix in a one-dimension array
  49. *
  50. * @return Query data structure
  51. */
  52. kswq_t *ksw_qinit(int size, int qlen, const uint8_t *query, int m, const int8_t *mat)
  53. {
  54. kswq_t *q;
  55. int slen, a, tmp, p;
  56. size = size > 1? 2 : 1;
  57. p = 8 * (3 - size); // # values per __m128i
  58. slen = (qlen + p - 1) / p; // segmented length
  59. q = (kswq_t*)malloc(sizeof(kswq_t) + 256 + 16 * slen * (m + 4)); // a single block of memory
  60. q->qp = (__m128i*)(((size_t)q + sizeof(kswq_t) + 15) >> 4 << 4); // align memory
  61. q->H0 = q->qp + slen * m;
  62. q->H1 = q->H0 + slen;
  63. q->E = q->H1 + slen;
  64. q->Hmax = q->E + slen;
  65. q->slen = slen; q->qlen = qlen; q->size = size;
  66. // compute shift
  67. tmp = m * m;
  68. for (a = 0, q->shift = 127, q->mdiff = 0; a < tmp; ++a) { // find the minimum and maximum score
  69. if (mat[a] < (int8_t)q->shift) q->shift = mat[a];
  70. if (mat[a] > (int8_t)q->mdiff) q->mdiff = mat[a];
  71. }
  72. q->max = q->mdiff;
  73. q->shift = 256 - q->shift; // NB: q->shift is uint8_t
  74. q->mdiff += q->shift; // this is the difference between the min and max scores
  75. // An example: p=8, qlen=19, slen=3 and segmentation:
  76. // {{0,3,6,9,12,15,18,-1},{1,4,7,10,13,16,-1,-1},{2,5,8,11,14,17,-1,-1}}
  77. if (size == 1) {
  78. int8_t *t = (int8_t*)q->qp;
  79. for (a = 0; a < m; ++a) {
  80. int i, k, nlen = slen * p;
  81. const int8_t *ma = mat + a * m;
  82. for (i = 0; i < slen; ++i)
  83. for (k = i; k < nlen; k += slen) // p iterations
  84. *t++ = (k >= qlen? 0 : ma[query[k]]) + q->shift;
  85. }
  86. } else {
  87. int16_t *t = (int16_t*)q->qp;
  88. for (a = 0; a < m; ++a) {
  89. int i, k, nlen = slen * p;
  90. const int8_t *ma = mat + a * m;
  91. for (i = 0; i < slen; ++i)
  92. for (k = i; k < nlen; k += slen) // p iterations
  93. *t++ = (k >= qlen? 0 : ma[query[k]]);
  94. }
  95. }
  96. return q;
  97. }
  98. kswr_t ksw_u8(kswq_t *q, int tlen, const uint8_t *target, int _o_del, int _e_del, int _o_ins, int _e_ins, int xtra) // the first gap costs -(_o+_e)
  99. {
  100. int slen, i, m_b, n_b, te = -1, gmax = 0, minsc, endsc;
  101. uint64_t *b;
  102. __m128i zero, oe_del, e_del, oe_ins, e_ins, shift, *H0, *H1, *E, *Hmax;
  103. kswr_t r;
  104. #define __max_16(ret, xx) do { \
  105. (xx) = _mm_max_epu8((xx), _mm_srli_si128((xx), 8)); \
  106. (xx) = _mm_max_epu8((xx), _mm_srli_si128((xx), 4)); \
  107. (xx) = _mm_max_epu8((xx), _mm_srli_si128((xx), 2)); \
  108. (xx) = _mm_max_epu8((xx), _mm_srli_si128((xx), 1)); \
  109. (ret) = _mm_extract_epi16((xx), 0) & 0x00ff; \
  110. } while (0)
  111. // initialization
  112. r = g_defr;
  113. minsc = (xtra&KSW_XSUBO)? xtra&0xffff : 0x10000;
  114. endsc = (xtra&KSW_XSTOP)? xtra&0xffff : 0x10000;
  115. m_b = n_b = 0; b = 0;
  116. zero = _mm_set1_epi32(0);
  117. oe_del = _mm_set1_epi8(_o_del + _e_del);
  118. e_del = _mm_set1_epi8(_e_del);
  119. oe_ins = _mm_set1_epi8(_o_ins + _e_ins);
  120. e_ins = _mm_set1_epi8(_e_ins);
  121. shift = _mm_set1_epi8(q->shift);
  122. H0 = q->H0; H1 = q->H1; E = q->E; Hmax = q->Hmax;
  123. slen = q->slen;
  124. for (i = 0; i < slen; ++i) {
  125. _mm_store_si128(E + i, zero);
  126. _mm_store_si128(H0 + i, zero);
  127. _mm_store_si128(Hmax + i, zero);
  128. }
  129. // the core loop
  130. for (i = 0; i < tlen; ++i) {
  131. int j, k, cmp, imax;
  132. __m128i e, h, t, f = zero, max = zero, *S = q->qp + target[i] * slen; // s is the 1st score vector
  133. h = _mm_load_si128(H0 + slen - 1); // h={2,5,8,11,14,17,-1,-1} in the above example
  134. h = _mm_slli_si128(h, 1); // h=H(i-1,-1); << instead of >> because x64 is little-endian
  135. for (j = 0; LIKELY(j < slen); ++j) {
  136. /* SW cells are computed in the following order:
  137. * H(i,j) = max{H(i-1,j-1)+S(i,j), E(i,j), F(i,j)}
  138. * E(i+1,j) = max{H(i,j)-q, E(i,j)-r}
  139. * F(i,j+1) = max{H(i,j)-q, F(i,j)-r}
  140. */
  141. // compute H'(i,j); note that at the beginning, h=H'(i-1,j-1)
  142. h = _mm_adds_epu8(h, _mm_load_si128(S + j));
  143. h = _mm_subs_epu8(h, shift); // h=H'(i-1,j-1)+S(i,j)
  144. e = _mm_load_si128(E + j); // e=E'(i,j)
  145. h = _mm_max_epu8(h, e);
  146. h = _mm_max_epu8(h, f); // h=H'(i,j)
  147. max = _mm_max_epu8(max, h); // set max
  148. _mm_store_si128(H1 + j, h); // save to H'(i,j)
  149. // now compute E'(i+1,j)
  150. e = _mm_subs_epu8(e, e_del); // e=E'(i,j) - e_del
  151. t = _mm_subs_epu8(h, oe_del); // h=H'(i,j) - o_del - e_del
  152. e = _mm_max_epu8(e, t); // e=E'(i+1,j)
  153. _mm_store_si128(E + j, e); // save to E'(i+1,j)
  154. // now compute F'(i,j+1)
  155. f = _mm_subs_epu8(f, e_ins);
  156. t = _mm_subs_epu8(h, oe_ins); // h=H'(i,j) - o_ins - e_ins
  157. f = _mm_max_epu8(f, t);
  158. // get H'(i-1,j) and prepare for the next j
  159. h = _mm_load_si128(H0 + j); // h=H'(i-1,j)
  160. }
  161. // NB: we do not need to set E(i,j) as we disallow adjecent insertion and then deletion
  162. for (k = 0; LIKELY(k < 16); ++k) { // this block mimics SWPS3; NB: H(i,j) updated in the lazy-F loop cannot exceed max
  163. f = _mm_slli_si128(f, 1);
  164. for (j = 0; LIKELY(j < slen); ++j) {
  165. h = _mm_load_si128(H1 + j);
  166. h = _mm_max_epu8(h, f); // h=H'(i,j)
  167. _mm_store_si128(H1 + j, h);
  168. h = _mm_subs_epu8(h, oe_ins);
  169. f = _mm_subs_epu8(f, e_ins);
  170. cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(_mm_subs_epu8(f, h), zero));
  171. if (UNLIKELY(cmp == 0xffff)) goto end_loop16;
  172. }
  173. }
  174. end_loop16:
  175. //int k;for (k=0;k<16;++k)printf("%d ", ((uint8_t*)&max)[k]);printf("\n");
  176. __max_16(imax, max); // imax is the maximum number in max
  177. if (imax >= minsc) { // write the b array; this condition adds branching unfornately
  178. if (n_b == 0 || (int32_t)b[n_b-1] + 1 != i) { // then append
  179. if (n_b == m_b) {
  180. m_b = m_b? m_b<<1 : 8;
  181. b = (uint64_t*)realloc(b, 8 * m_b);
  182. }
  183. b[n_b++] = (uint64_t)imax<<32 | i;
  184. } else if ((int)(b[n_b-1]>>32) < imax) b[n_b-1] = (uint64_t)imax<<32 | i; // modify the last
  185. }
  186. if (imax > gmax) {
  187. gmax = imax; te = i; // te is the end position on the target
  188. for (j = 0; LIKELY(j < slen); ++j) // keep the H1 vector
  189. _mm_store_si128(Hmax + j, _mm_load_si128(H1 + j));
  190. if (gmax + q->shift >= 255 || gmax >= endsc) break;
  191. }
  192. S = H1; H1 = H0; H0 = S; // swap H0 and H1
  193. }
  194. r.score = gmax + q->shift < 255? gmax : 255;
  195. r.te = te;
  196. // modified by Jue Ruan
  197. //if (r.score != 255) { // get a->qe, the end of query match; find the 2nd best score
  198. { // get a->qe, the end of query match; find the 2nd best score
  199. int max = -1, tmp, low, high, qlen = slen * 16;
  200. uint8_t *t = (uint8_t*)Hmax;
  201. for (i = 0; i < qlen; ++i, ++t)
  202. if ((int)*t > max) max = *t, r.qe = i / 16 + i % 16 * slen;
  203. else if ((int)*t == max && (tmp = i / 16 + i % 16 * slen) < r.qe) r.qe = tmp;
  204. //printf("%d,%d\n", max, gmax);
  205. if (b) {
  206. i = (r.score + q->max - 1) / q->max;
  207. low = te - i; high = te + i;
  208. for (i = 0; i < n_b; ++i) {
  209. int e = (int32_t)b[i];
  210. if ((e < low || e > high) && (int)(b[i]>>32) > r.score2)
  211. r.score2 = b[i]>>32, r.te2 = e;
  212. }
  213. }
  214. }
  215. free(b);
  216. return r;
  217. }
  218. kswr_t ksw_i16(kswq_t *q, int tlen, const uint8_t *target, int _o_del, int _e_del, int _o_ins, int _e_ins, int xtra) // the first gap costs -(_o+_e)
  219. {
  220. int slen, i, m_b, n_b, te = -1, gmax = 0, minsc, endsc;
  221. uint64_t *b;
  222. __m128i zero, oe_del, e_del, oe_ins, e_ins, *H0, *H1, *E, *Hmax;
  223. kswr_t r;
  224. #define __max_8(ret, xx) do { \
  225. (xx) = _mm_max_epi16((xx), _mm_srli_si128((xx), 8)); \
  226. (xx) = _mm_max_epi16((xx), _mm_srli_si128((xx), 4)); \
  227. (xx) = _mm_max_epi16((xx), _mm_srli_si128((xx), 2)); \
  228. (ret) = _mm_extract_epi16((xx), 0); \
  229. } while (0)
  230. // initialization
  231. r = g_defr;
  232. minsc = (xtra&KSW_XSUBO)? xtra&0xffff : 0x10000;
  233. endsc = (xtra&KSW_XSTOP)? xtra&0xffff : 0x10000;
  234. m_b = n_b = 0; b = 0;
  235. zero = _mm_set1_epi32(0);
  236. oe_del = _mm_set1_epi16(_o_del + _e_del);
  237. e_del = _mm_set1_epi16(_e_del);
  238. oe_ins = _mm_set1_epi16(_o_ins + _e_ins);
  239. e_ins = _mm_set1_epi16(_e_ins);
  240. H0 = q->H0; H1 = q->H1; E = q->E; Hmax = q->Hmax;
  241. slen = q->slen;
  242. for (i = 0; i < slen; ++i) {
  243. _mm_store_si128(E + i, zero);
  244. _mm_store_si128(H0 + i, zero);
  245. _mm_store_si128(Hmax + i, zero);
  246. }
  247. // the core loop
  248. for (i = 0; i < tlen; ++i) {
  249. int j, k, imax;
  250. __m128i e, t, h, f = zero, max = zero, *S = q->qp + target[i] * slen; // s is the 1st score vector
  251. h = _mm_load_si128(H0 + slen - 1); // h={2,5,8,11,14,17,-1,-1} in the above example
  252. h = _mm_slli_si128(h, 2);
  253. for (j = 0; LIKELY(j < slen); ++j) {
  254. h = _mm_adds_epi16(h, *S++);
  255. e = _mm_load_si128(E + j);
  256. h = _mm_max_epi16(h, e);
  257. h = _mm_max_epi16(h, f);
  258. max = _mm_max_epi16(max, h);
  259. _mm_store_si128(H1 + j, h);
  260. e = _mm_subs_epu16(e, e_del);
  261. t = _mm_subs_epu16(h, oe_del);
  262. e = _mm_max_epi16(e, t);
  263. _mm_store_si128(E + j, e);
  264. f = _mm_subs_epu16(f, e_ins);
  265. t = _mm_subs_epu16(h, oe_ins);
  266. f = _mm_max_epi16(f, t);
  267. h = _mm_load_si128(H0 + j);
  268. }
  269. for (k = 0; LIKELY(k < 16); ++k) {
  270. f = _mm_slli_si128(f, 2);
  271. for (j = 0; LIKELY(j < slen); ++j) {
  272. h = _mm_load_si128(H1 + j);
  273. h = _mm_max_epi16(h, f);
  274. _mm_store_si128(H1 + j, h);
  275. h = _mm_subs_epu16(h, oe_ins);
  276. f = _mm_subs_epu16(f, e_ins);
  277. if(UNLIKELY(!_mm_movemask_epi8(_mm_cmpgt_epi16(f, h)))) goto end_loop8;
  278. }
  279. }
  280. end_loop8:
  281. __max_8(imax, max);
  282. if (imax >= minsc) {
  283. if (n_b == 0 || (int32_t)b[n_b-1] + 1 != i) {
  284. if (n_b == m_b) {
  285. m_b = m_b? m_b<<1 : 8;
  286. b = (uint64_t*)realloc(b, 8 * m_b);
  287. }
  288. b[n_b++] = (uint64_t)imax<<32 | i;
  289. } else if ((int)(b[n_b-1]>>32) < imax) b[n_b-1] = (uint64_t)imax<<32 | i; // modify the last
  290. }
  291. if (imax > gmax) {
  292. gmax = imax; te = i;
  293. for (j = 0; LIKELY(j < slen); ++j)
  294. _mm_store_si128(Hmax + j, _mm_load_si128(H1 + j));
  295. if (gmax >= endsc) break;
  296. }
  297. S = H1; H1 = H0; H0 = S;
  298. }
  299. r.score = gmax; r.te = te;
  300. {
  301. int max = -1, tmp, low, high, qlen = slen * 8;
  302. uint16_t *t = (uint16_t*)Hmax;
  303. for (i = 0, r.qe = -1; i < qlen; ++i, ++t)
  304. if ((int)*t > max) max = *t, r.qe = i / 8 + i % 8 * slen;
  305. else if ((int)*t == max && (tmp = i / 8 + i % 8 * slen) < r.qe) r.qe = tmp;
  306. if (b) {
  307. i = (r.score + q->max - 1) / q->max;
  308. low = te - i; high = te + i;
  309. for (i = 0; i < n_b; ++i) {
  310. int e = (int32_t)b[i];
  311. if ((e < low || e > high) && (int)(b[i]>>32) > r.score2)
  312. r.score2 = b[i]>>32, r.te2 = e;
  313. }
  314. }
  315. }
  316. free(b);
  317. return r;
  318. }
  319. static inline void revseq(int l, uint8_t *s)
  320. {
  321. int i, t;
  322. for (i = 0; i < l>>1; ++i)
  323. t = s[i], s[i] = s[l - 1 - i], s[l - 1 - i] = t;
  324. }
  325. kswr_t ksw_align2(int qlen, uint8_t *query, int tlen, uint8_t *target, int m, const int8_t *mat, int o_del, int e_del, int o_ins, int e_ins, int xtra, kswq_t **qry)
  326. {
  327. int size;
  328. kswq_t *q;
  329. kswr_t r, rr;
  330. kswr_t (*func)(kswq_t*, int, const uint8_t*, int, int, int, int, int);
  331. q = (qry && *qry)? *qry : ksw_qinit((xtra&KSW_XBYTE)? 1 : 2, qlen, query, m, mat);
  332. if (qry && *qry == 0) *qry = q;
  333. func = q->size == 2? ksw_i16 : ksw_u8;
  334. size = q->size;
  335. r = func(q, tlen, target, o_del, e_del, o_ins, e_ins, xtra);
  336. if (qry == 0) free(q);
  337. if ((xtra&KSW_XSTART) == 0 || ((xtra&KSW_XSUBO) && r.score < (xtra&0xffff))) return r;
  338. revseq(r.qe + 1, query); revseq(r.te + 1, target); // +1 because qe/te points to the exact end, not the position after the end
  339. q = ksw_qinit(size, r.qe + 1, query, m, mat);
  340. rr = func(q, tlen, target, o_del, e_del, o_ins, e_ins, KSW_XSTOP | r.score);
  341. revseq(r.qe + 1, query); revseq(r.te + 1, target);
  342. free(q);
  343. if (r.score == rr.score)
  344. r.tb = r.te - rr.te, r.qb = r.qe - rr.qe;
  345. return r;
  346. }
  347. kswr_t ksw_align(int qlen, uint8_t *query, int tlen, uint8_t *target, int m, const int8_t *mat, int gapo, int gape, int xtra, kswq_t **qry)
  348. {
  349. return ksw_align2(qlen, query, tlen, target, m, mat, gapo, gape, gapo, gape, xtra, qry);
  350. }
  351. /********************
  352. *** SW extension ***
  353. ********************/
  354. typedef struct {
  355. int32_t h, e;
  356. } eh_t;
  357. int ksw_extend2(int qlen, const uint8_t *query, int tlen, const uint8_t *target, int m, const int8_t *mat, int o_del, int e_del, int o_ins, int e_ins, int w, int end_bonus, int zdrop, int h0, int *_qle, int *_tle, int *_gtle, int *_gscore, int *_max_off)
  358. {
  359. eh_t *eh; // score array
  360. int8_t *qp; // query profile
  361. int i, j, k, oe_del = o_del + e_del, oe_ins = o_ins + e_ins, beg, end, max, max_i, max_j, max_ins, max_del, max_ie, gscore, max_off;
  362. if (h0 < 0) h0 = 0;
  363. // allocate memory
  364. qp = malloc(qlen * m);
  365. eh = calloc(qlen + 1, 8);
  366. // generate the query profile
  367. for (k = i = 0; k < m; ++k) {
  368. const int8_t *p = &mat[k * m];
  369. for (j = 0; j < qlen; ++j) qp[i++] = p[query[j]];
  370. }
  371. // fill the first row
  372. eh[0].h = h0; eh[1].h = h0 > oe_ins? h0 - oe_ins : 0;
  373. for (j = 2; j <= qlen && eh[j-1].h > e_ins; ++j)
  374. eh[j].h = eh[j-1].h - e_ins;
  375. // adjust $w if it is too large
  376. k = m * m;
  377. for (i = 0, max = 0; i < k; ++i) // get the max score
  378. max = max > mat[i]? max : mat[i];
  379. max_ins = (int)((double)(qlen * max + end_bonus - o_ins) / e_ins + 1.);
  380. max_ins = max_ins > 1? max_ins : 1;
  381. w = w < max_ins? w : max_ins;
  382. max_del = (int)((double)(qlen * max + end_bonus - o_del) / e_del + 1.);
  383. max_del = max_del > 1? max_del : 1;
  384. w = w < max_del? w : max_del; // TODO: is this necessary?
  385. // DP loop
  386. max = h0, max_i = max_j = -1; max_ie = -1, gscore = -1;
  387. max_off = 0;
  388. beg = 0, end = qlen;
  389. for (i = 0; LIKELY(i < tlen); ++i) {
  390. int t, f = 0, h1, m = 0, mj = -1;
  391. int8_t *q = &qp[target[i] * qlen];
  392. // compute the first column
  393. h1 = h0 - (o_del + e_del * (i + 1));
  394. if (h1 < 0) h1 = 0;
  395. // apply the band and the constraint (if provided)
  396. if (beg < i - w) beg = i - w;
  397. if (end > i + w + 1) end = i + w + 1;
  398. if (end > qlen) end = qlen;
  399. for (j = beg; LIKELY(j < end); ++j) {
  400. // At the beginning of the loop: eh[j] = { H(i-1,j-1), E(i,j) }, f = F(i,j) and h1 = H(i,j-1)
  401. // Similar to SSE2-SW, cells are computed in the following order:
  402. // H(i,j) = max{H(i-1,j-1)+S(i,j), E(i,j), F(i,j)}
  403. // E(i+1,j) = max{H(i,j)-gapo, E(i,j)} - gape
  404. // F(i,j+1) = max{H(i,j)-gapo, F(i,j)} - gape
  405. eh_t *p = &eh[j];
  406. int h, M = p->h, e = p->e; // get H(i-1,j-1) and E(i-1,j)
  407. p->h = h1; // set H(i,j-1) for the next row
  408. M += q[j]; // separating H and M to disallow a cigar like "100M3I3D20M"
  409. h = M > e? M : e;
  410. h = h > f? h : f;
  411. h1 = h; // save H(i,j) to h1 for the next column
  412. mj = m > h? mj : j; // record the position where max score is achieved
  413. m = m > h? m : h; // m is stored at eh[mj+1]
  414. t = M - oe_del;
  415. t = t > 0? t : 0;
  416. e -= e_del;
  417. e = e > t? e : t; // computed E(i+1,j)
  418. p->e = e; // save E(i+1,j) for the next row
  419. t = M - oe_ins;
  420. t = t > 0? t : 0;
  421. f -= e_ins;
  422. f = f > t? f : t; // computed F(i,j+1)
  423. }
  424. eh[end].h = h1; eh[end].e = 0;
  425. if (j == qlen) {
  426. max_ie = gscore > h1? max_ie : i;
  427. gscore = gscore > h1? gscore : h1;
  428. }
  429. if (m == 0) break;
  430. if (m > max) {
  431. max = m, max_i = i, max_j = mj;
  432. max_off = max_off > abs(mj - i)? max_off : abs(mj - i);
  433. } else if (zdrop > 0) {
  434. if (i - max_i > mj - max_j) {
  435. if (max - m - ((i - max_i) - (mj - max_j)) * e_del > zdrop) break;
  436. } else {
  437. if (max - m - ((mj - max_j) - (i - max_i)) * e_ins > zdrop) break;
  438. }
  439. }
  440. // update beg and end for the next round
  441. for (j = mj; j >= beg && eh[j].h; --j);
  442. beg = j + 1;
  443. for (j = mj + 2; j <= end && eh[j].h; ++j);
  444. end = j;
  445. //beg = 0; end = qlen; // uncomment this line for debugging
  446. }
  447. free(eh); free(qp);
  448. if (_qle) *_qle = max_j + 1;
  449. if (_tle) *_tle = max_i + 1;
  450. if (_gtle) *_gtle = max_ie + 1;
  451. if (_gscore) *_gscore = gscore;
  452. if (_max_off) *_max_off = max_off;
  453. return max;
  454. }
  455. int ksw_extend(int qlen, const uint8_t *query, int tlen, const uint8_t *target, int m, const int8_t *mat, int gapo, int gape, int w, int end_bonus, int zdrop, int h0, int *qle, int *tle, int *gtle, int *gscore, int *max_off)
  456. {
  457. return ksw_extend2(qlen, query, tlen, target, m, mat, gapo, gape, gapo, gape, w, end_bonus, zdrop, h0, qle, tle, gtle, gscore, max_off);
  458. }
  459. /********************
  460. * Global alignment *
  461. ********************/
  462. #define MINUS_INF -0x40000000
  463. static inline uint32_t *push_cigar(int *n_cigar, int *m_cigar, uint32_t *cigar, int op, int len)
  464. {
  465. if (*n_cigar == 0 || op != (int)(cigar[(*n_cigar) - 1]&0xf)) {
  466. if (*n_cigar == *m_cigar) {
  467. *m_cigar = *m_cigar? (*m_cigar)<<1 : 4;
  468. cigar = realloc(cigar, (*m_cigar) << 2);
  469. }
  470. cigar[(*n_cigar)++] = len<<4 | op;
  471. } else cigar[(*n_cigar)-1] += len<<4;
  472. return cigar;
  473. }
  474. int ksw_global2(int qlen, const uint8_t *query, int tlen, const uint8_t *target, int m, const int8_t *mat, int o_del, int e_del, int o_ins, int e_ins, int w, int *n_cigar_, uint32_t **cigar_)
  475. {
  476. eh_t *eh;
  477. int8_t *qp; // query profile
  478. int i, j, k, oe_del = o_del + e_del, oe_ins = o_ins + e_ins, score, n_col;
  479. uint8_t *z; // backtrack matrix; in each cell: f<<4|e<<2|h; in principle, we can halve the memory, but backtrack will be a little more complex
  480. if (n_cigar_) *n_cigar_ = 0;
  481. // allocate memory
  482. n_col = qlen < 2*w+1? qlen : 2*w+1; // maximum #columns of the backtrack matrix
  483. z = malloc(n_col * tlen);
  484. qp = malloc(qlen * m);
  485. eh = calloc(qlen + 1, 8);
  486. // generate the query profile
  487. for (k = i = 0; k < m; ++k) {
  488. const int8_t *p = &mat[k * m];
  489. for (j = 0; j < qlen; ++j) qp[i++] = p[query[j]];
  490. }
  491. // fill the first row
  492. eh[0].h = 0; eh[0].e = MINUS_INF;
  493. for (j = 1; j <= qlen && j <= w; ++j)
  494. eh[j].h = -(o_ins + e_ins * j), eh[j].e = MINUS_INF;
  495. for (; j <= qlen; ++j) eh[j].h = eh[j].e = MINUS_INF; // everything is -inf outside the band
  496. // DP loop
  497. for (i = 0; LIKELY(i < tlen); ++i) { // target sequence is in the outer loop
  498. int32_t f = MINUS_INF, h1, beg, end, t;
  499. int8_t *q = &qp[target[i] * qlen];
  500. uint8_t *zi = &z[i * n_col];
  501. beg = i > w? i - w : 0;
  502. end = i + w + 1 < qlen? i + w + 1 : qlen; // only loop through [beg,end) of the query sequence
  503. h1 = beg == 0? -(o_del + e_del * (i + 1)) : MINUS_INF;
  504. for (j = beg; LIKELY(j < end); ++j) {
  505. // At the beginning of the loop: eh[j] = { H(i-1,j-1), E(i,j) }, f = F(i,j) and h1 = H(i,j-1)
  506. // Cells are computed in the following order:
  507. // M(i,j) = H(i-1,j-1) + S(i,j)
  508. // H(i,j) = max{M(i,j), E(i,j), F(i,j)}
  509. // E(i+1,j) = max{M(i,j)-gapo, E(i,j)} - gape
  510. // F(i,j+1) = max{M(i,j)-gapo, F(i,j)} - gape
  511. // We have to separate M(i,j); otherwise the direction may not be recorded correctly.
  512. // However, a CIGAR like "10M3I3D10M" allowed by local() is disallowed by global().
  513. // Such a CIGAR may occur, in theory, if mismatch_penalty > 2*gap_ext_penalty + 2*gap_open_penalty/k.
  514. // In practice, this should happen very rarely given a reasonable scoring system.
  515. eh_t *p = &eh[j];
  516. int32_t h, m = p->h, e = p->e;
  517. uint8_t d; // direction
  518. p->h = h1;
  519. m += q[j];
  520. d = m >= e? 0 : 1;
  521. h = m >= e? m : e;
  522. d = h >= f? d : 2;
  523. h = h >= f? h : f;
  524. h1 = h;
  525. t = m - oe_del;
  526. e -= e_del;
  527. d |= e > t? 1<<2 : 0;
  528. e = e > t? e : t;
  529. p->e = e;
  530. t = m - oe_ins;
  531. f -= e_ins;
  532. d |= f > t? 2<<4 : 0; // if we want to halve the memory, use one bit only, instead of two
  533. f = f > t? f : t;
  534. zi[j - beg] = d; // z[i,j] keeps h for the current cell and e/f for the next cell
  535. }
  536. eh[end].h = h1; eh[end].e = MINUS_INF;
  537. }
  538. score = eh[qlen].h;
  539. if (n_cigar_ && cigar_) { // backtrack
  540. int n_cigar = 0, m_cigar = 0, which = 0;
  541. uint32_t *cigar = 0, tmp;
  542. i = tlen - 1; k = (i + w + 1 < qlen? i + w + 1 : qlen) - 1; // (i,k) points to the last cell
  543. while (i >= 0 && k >= 0) {
  544. which = z[i * n_col + (k - (i > w? i - w : 0))] >> (which<<1) & 3;
  545. if (which == 0) cigar = push_cigar(&n_cigar, &m_cigar, cigar, 0, 1), --i, --k;
  546. else if (which == 1) cigar = push_cigar(&n_cigar, &m_cigar, cigar, 2, 1), --i;
  547. else cigar = push_cigar(&n_cigar, &m_cigar, cigar, 1, 1), --k;
  548. }
  549. if (i >= 0) cigar = push_cigar(&n_cigar, &m_cigar, cigar, 2, i + 1);
  550. if (k >= 0) cigar = push_cigar(&n_cigar, &m_cigar, cigar, 1, k + 1);
  551. for (i = 0; i < n_cigar>>1; ++i) // reverse CIGAR
  552. tmp = cigar[i], cigar[i] = cigar[n_cigar-1-i], cigar[n_cigar-1-i] = tmp;
  553. *n_cigar_ = n_cigar, *cigar_ = cigar;
  554. }
  555. free(eh); free(qp); free(z);
  556. return score;
  557. }
  558. int ksw_global(int qlen, const uint8_t *query, int tlen, const uint8_t *target, int m, const int8_t *mat, int gapo, int gape, int w, int *n_cigar_, uint32_t **cigar_)
  559. {
  560. return ksw_global2(qlen, query, tlen, target, m, mat, gapo, gape, gapo, gape, w, n_cigar_, cigar_);
  561. }
  562. /*******************************************
  563. * Main function (not compiled by default) *
  564. *******************************************/
  565. #ifdef _KSW_MAIN
  566. #include <unistd.h>
  567. #include <stdio.h>
  568. #include <zlib.h>
  569. #include "kseq.h"
  570. KSEQ_INIT(gzFile, err_gzread)
  571. unsigned char seq_nt4_table[256] = {
  572. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  573. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  574. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  575. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  576. 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4,
  577. 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  578. 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4,
  579. 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  580. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  581. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  582. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  583. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  584. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  585. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  586. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  587. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4
  588. };
  589. int main(int argc, char *argv[])
  590. {
  591. int c, sa = 1, sb = 3, i, j, k, forward_only = 0, max_rseq = 0;
  592. int8_t mat[25];
  593. int gapo = 5, gape = 2, minsc = 0, xtra = KSW_XSTART;
  594. uint8_t *rseq = 0;
  595. gzFile fpt, fpq;
  596. kseq_t *kst, *ksq;
  597. // parse command line
  598. while ((c = getopt(argc, argv, "a:b:q:r:ft:1")) >= 0) {
  599. switch (c) {
  600. case 'a': sa = atoi(optarg); break;
  601. case 'b': sb = atoi(optarg); break;
  602. case 'q': gapo = atoi(optarg); break;
  603. case 'r': gape = atoi(optarg); break;
  604. case 't': minsc = atoi(optarg); break;
  605. case 'f': forward_only = 1; break;
  606. case '1': xtra |= KSW_XBYTE; break;
  607. }
  608. }
  609. if (optind + 2 > argc) {
  610. fprintf(stderr, "Usage: ksw [-1] [-f] [-a%d] [-b%d] [-q%d] [-r%d] [-t%d] <target.fa> <query.fa>\n", sa, sb, gapo, gape, minsc);
  611. return 1;
  612. }
  613. if (minsc > 0xffff) minsc = 0xffff;
  614. xtra |= KSW_XSUBO | minsc;
  615. // initialize scoring matrix
  616. for (i = k = 0; i < 4; ++i) {
  617. for (j = 0; j < 4; ++j)
  618. mat[k++] = i == j? sa : -sb;
  619. mat[k++] = 0; // ambiguous base
  620. }
  621. for (j = 0; j < 5; ++j) mat[k++] = 0;
  622. // open file
  623. fpt = xzopen(argv[optind], "r"); kst = kseq_init(fpt);
  624. fpq = xzopen(argv[optind+1], "r"); ksq = kseq_init(fpq);
  625. // all-pair alignment
  626. while (kseq_read(ksq) > 0) {
  627. kswq_t *q[2] = {0, 0};
  628. kswr_t r;
  629. for (i = 0; i < (int)ksq->seq.l; ++i) ksq->seq.s[i] = seq_nt4_table[(int)ksq->seq.s[i]];
  630. if (!forward_only) { // reverse
  631. if ((int)ksq->seq.m > max_rseq) {
  632. max_rseq = ksq->seq.m;
  633. rseq = (uint8_t*)realloc(rseq, max_rseq);
  634. }
  635. for (i = 0, j = ksq->seq.l - 1; i < (int)ksq->seq.l; ++i, --j)
  636. rseq[j] = ksq->seq.s[i] == 4? 4 : 3 - ksq->seq.s[i];
  637. }
  638. gzrewind(fpt); kseq_rewind(kst);
  639. while (kseq_read(kst) > 0) {
  640. for (i = 0; i < (int)kst->seq.l; ++i) kst->seq.s[i] = seq_nt4_table[(int)kst->seq.s[i]];
  641. r = ksw_align(ksq->seq.l, (uint8_t*)ksq->seq.s, kst->seq.l, (uint8_t*)kst->seq.s, 5, mat, gapo, gape, xtra, &q[0]);
  642. if (r.score >= minsc)
  643. err_printf("%s\t%d\t%d\t%s\t%d\t%d\t%d\t%d\t%d\n", kst->name.s, r.tb, r.te+1, ksq->name.s, r.qb, r.qe+1, r.score, r.score2, r.te2);
  644. if (rseq) {
  645. r = ksw_align(ksq->seq.l, rseq, kst->seq.l, (uint8_t*)kst->seq.s, 5, mat, gapo, gape, xtra, &q[1]);
  646. if (r.score >= minsc)
  647. err_printf("%s\t%d\t%d\t%s\t%d\t%d\t%d\t%d\t%d\n", kst->name.s, r.tb, r.te+1, ksq->name.s, (int)ksq->seq.l - r.qb, (int)ksq->seq.l - 1 - r.qe, r.score, r.score2, r.te2);
  648. }
  649. }
  650. free(q[0]); free(q[1]);
  651. }
  652. free(rseq);
  653. kseq_destroy(kst); err_gzclose(fpt);
  654. kseq_destroy(ksq); err_gzclose(fpq);
  655. return 0;
  656. }
  657. #endif