Debian Codegraph @

src/abpoa_seed.c

raw
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <assert.h>
4 #include <string.h>
5 #include <inttypes.h>
6 #include "abpoa.h"
7 #include "abpoa_seed.h"
8 #include "utils.h"
9 #include "kvec.h"
10 #include "ksort.h"
11
12 const char LogTable256[256] = {
13 #define LT(n) n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n
14 -1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3,
15 LT(4), LT(5), LT(5), LT(6), LT(6), LT(6), LT(6),
16 LT(7), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7)
17 };
18
19 static inline int ilog2_32(uint32_t v) {
20 uint32_t t, tt;
21 if ((tt = v>>16)) return (t = tt>>8) ? 24 + LogTable256[t] : 16 + LogTable256[tt];
22 return (t = v>>8) ? 8 + LogTable256[t] : LogTable256[v];
23 }
24
25 #define mm_sketch abpoa_mm_sketch
26 #define mm_aa_sketch abpoa_mm_aa_sketch
27
28 #define ab_sort_key_128x(a) ((a).x)
29 #define rs_insertsort_ab_128x abpoa_rs_insertsort_ab_128x
30 #define rs_sort_ab_128x abpoa_rs_sort_ab_128x
31 #define radix_sort_ab_128x abpoa_radix_sort_ab_128x
32 KRADIX_SORT_INIT(ab_128x, ab_u128_t, ab_sort_key_128x, 8)
33
34 #define ab_sort_key_128y(a) ((a).y)
35 #define rs_insertsort_ab_128y abpoa_rs_insertsort_ab_128y
36 #define rs_sort_ab_128y abpoa_rs_sort_ab_128y
37 #define radix_sort_ab_128y abpoa_radix_sort_ab_128y
38 KRADIX_SORT_INIT(ab_128y, ab_u128_t, ab_sort_key_128y, 8)
39
40 #define ab_sort_key_64(a) (a)
41 #define rs_insertsort_64 abpoa_rs_insertsort_64
42 #define rs_sort_64 abpoa_rs_sort_64
43 #define radix_sort_64 abpoa_radix_sort_64
44 KRADIX_SORT_INIT(64, uint64_t, ab_sort_key_64, 8)
45
46 /* from lh3/minimap2/sketch.c */
47 /********** start *************/
48 static inline uint64_t hash64(uint64_t key, uint64_t mask)
49 {
50 key = (~key + (key << 21)) & mask; // key = (key << 21) - key - 1;
51 key = key ^ key >> 24;
52 key = ((key + (key << 3)) + (key << 8)) & mask; // key * 265
53 key = key ^ key >> 14;
54 key = ((key + (key << 2)) + (key << 4)) & mask; // key * 21
55 key = key ^ key >> 28;
56 key = (key + (key << 31)) & mask;
57 return key;
58 }
59
60 typedef struct { // a simplified version of kdq
61 int front, count;
62 int a[32];
63 } tiny_queue_t;
64
65 static inline void tq_push(tiny_queue_t *q, int x)
66 {
67 q->a[((q->count++) + q->front) & 0x1f] = x;
68 }
69
70 static inline int tq_shift(tiny_queue_t *q)
71 {
72 int x;
73 if (q->count == 0) return -1;
74 x = q->a[q->front++];
75 q->front &= 0x1f;
76 --q->count;
77 return x;
78 }
79
80 /**
81 * Find symmetric (w,k)-minimizers on a DNA sequence
82 *
83 * @param km thread-local memory pool; using NULL falls back to malloc()
84 * @param str DNA sequence
85 * @param len length of $str
86 * @param w find a minimizer for every $w consecutive k-mers
87 * @param k k-mer size
88 * @param rid reference ID; will be copied to the output $p array
89 * @param is_hpc homopolymer-compressed or not
90 * @param p minimizers
91 * p->a[i].x = kMer<<8 | kmerSpan
92 * p->a[i].y = rid<<32 | lastPos<<1 | strand
93 * where lastPos is the position of the last base of the i-th minimizer,
94 * and strand indicates whether the minimizer comes from the top or the bottom strand.
95 * Callers may want to set "p->n = 0"; otherwise results are appended to p
96 */
97 void mm_sketch(void *km, const uint8_t *str, int len, int w, int k, uint32_t rid, int is_hpc, int both_strand, ab_u128_v *p)
98 {
99 uint64_t shift1 = 2 * (k - 1), mask = (1ULL<<2*k) - 1, kmer[2] = {0,0};
100 int i, j, l, buf_pos, min_pos, kmer_span = 0;
101 ab_u128_t buf[256], min = { UINT64_MAX, UINT64_MAX };
102 tiny_queue_t tq;
103
104 assert(len > 0 && (w > 0 && w < 256) && (k > 0 && k <= 28)); // 56 bits for k-mer; could use long k-mers, but 28 enough in practice
105 memset(buf, 0xff, w * 16);
106 memset(&tq, 0, sizeof(tiny_queue_t));
107 kv_resize(ab_u128_t, km, *p, p->n + len/w);
108
109 for (i = l = buf_pos = min_pos = 0; i < len; ++i) {
110 int c = str[i];
111 ab_u128_t info = { UINT64_MAX, UINT64_MAX };
112 if (c < 4) { // not an ambiguous base
113 uint32_t z;
114 if (is_hpc) {
115 int skip_len = 1;
116 if (i + 1 < len && str[i + 1] == c) {
117 for (skip_len = 2; i + skip_len < len; ++skip_len)
118 if (str[i + skip_len] != c)
119 break;
120 i += skip_len - 1; // put $i at the end of the current homopolymer run
121 }
122 tq_push(&tq, skip_len);
123 kmer_span += skip_len;
124 if (tq.count > k) kmer_span -= tq_shift(&tq);
125 } else kmer_span = l + 1 < k? l + 1 : k;
126 if (both_strand) {
127 kmer[0] = (kmer[0] << 2 | c) & mask; // forward k-mer
128 kmer[1] = (kmer[1] >> 2) | (3ULL^c) << shift1; // reverse k-mer
129 if (kmer[0] == kmer[1]) continue; // skip "symmetric k-mers" as we don't know it strand
130 z = kmer[0] < kmer[1]? 0 : 1; // strand
131 } else {
132 kmer[0] = (kmer[0] << 2 | c) & mask; // forward k-mer
133 z = 0;
134 }
135 ++l;
136 if (l >= k && kmer_span < 256) {
137 info.x = hash64(kmer[z], mask) << 8 | kmer_span;
138 info.y = (uint64_t)rid<<32 | (uint32_t)i<<1 | z;
139 }
140 } else l = 0, tq.count = tq.front = 0, kmer_span = 0;
141 buf[buf_pos] = info; // need to do this here as appropriate buf_pos and buf[buf_pos] are needed below
142 if (l == w + k - 1 && min.x != UINT64_MAX) { // special case for the first window - because identical k-mers are not stored yet
143 for (j = buf_pos + 1; j < w; ++j)
144 if (min.x == buf[j].x && buf[j].y != min.y) kv_push(ab_u128_t, km, *p, buf[j]);
145 for (j = 0; j < buf_pos; ++j)
146 if (min.x == buf[j].x && buf[j].y != min.y) kv_push(ab_u128_t, km, *p, buf[j]);
147 }
148 if (info.x <= min.x) { // a new minimum; then write the old min
149 if (l >= w + k && min.x != UINT64_MAX) kv_push(ab_u128_t, km, *p, min);
150 min = info, min_pos = buf_pos;
151 } else if (buf_pos == min_pos) { // old min has moved outside the window
152 if (l >= w + k - 1 && min.x != UINT64_MAX) kv_push(ab_u128_t, km, *p, min);
153 for (j = buf_pos + 1, min.x = UINT64_MAX; j < w; ++j) // the two loops are necessary when there are identical k-mers
154 if (min.x >= buf[j].x) min = buf[j], min_pos = j; // >= is important s.t. min is always the closest k-mer
155 for (j = 0; j <= buf_pos; ++j)
156 if (min.x >= buf[j].x) min = buf[j], min_pos = j;
157 if (l >= w + k - 1 && min.x != UINT64_MAX) { // write identical k-mers
158 for (j = buf_pos + 1; j < w; ++j) // these two loops make sure the output is sorted
159 if (min.x == buf[j].x && min.y != buf[j].y) kv_push(ab_u128_t, km, *p, buf[j]);
160 for (j = 0; j <= buf_pos; ++j)
161 if (min.x == buf[j].x && min.y != buf[j].y) kv_push(ab_u128_t, km, *p, buf[j]);
162 }
163 }
164 if (++buf_pos == w) buf_pos = 0;
165 }
166 if (min.x != UINT64_MAX)
167 kv_push(ab_u128_t, km, *p, min);
168 }
169
170 // For amino acid sequence
171 void mm_aa_sketch(void *km, const uint8_t *str, int len, int w, int k, uint32_t rid, int is_hpc, ab_u128_v *p)
172 {
173 uint64_t mask = (1ULL<<5*k) - 1, kmer[2] = {0,0};
174 int i, j, l, buf_pos, min_pos, kmer_span = 0;
175 ab_u128_t buf[256], min = { UINT64_MAX, UINT64_MAX };
176 tiny_queue_t tq;
177
178 assert(len > 0 && (w > 0 && w < 256) && (k > 0 && k <= 11)); // 56 / 5 == 11
179 memset(buf, 0xff, w * 16);
180 memset(&tq, 0, sizeof(tiny_queue_t));
181 kv_resize(ab_u128_t, km, *p, p->n + len/w);
182
183 for (i = l = buf_pos = min_pos = 0; i < len; ++i) {
184 int c = str[i];
185 ab_u128_t info = { UINT64_MAX, UINT64_MAX };
186 if (c < 26) { // not an ambiguous base
187 uint32_t z;
188 if (is_hpc) {
189 int skip_len = 1;
190 if (i + 1 < len && str[i + 1] == c) {
191 for (skip_len = 2; i + skip_len < len; ++skip_len)
192 if (str[i + skip_len] != c)
193 break;
194 i += skip_len - 1; // put $i at the end of the current homopolymer run
195 }
196 tq_push(&tq, skip_len);
197 kmer_span += skip_len;
198 if (tq.count > k) kmer_span -= tq_shift(&tq);
199 } else kmer_span = l + 1 < k? l + 1 : k;
200
201 kmer[0] = (kmer[0] << 5 | c) & mask; // only forward k-mer for aa seq
202 z = 0;
203 ++l;
204 if (l >= k && kmer_span < 256) {
205 info.x = hash64(kmer[z], mask) << 8 | kmer_span;
206 info.y = (uint64_t)rid<<32 | (uint32_t)i<<1 | z;
207 }
208 } else l = 0, tq.count = tq.front = 0, kmer_span = 0;
209 buf[buf_pos] = info; // need to do this here as appropriate buf_pos and buf[buf_pos] are needed below
210 if (l == w + k - 1 && min.x != UINT64_MAX) { // special case for the first window - because identical k-mers are not stored yet
211 for (j = buf_pos + 1; j < w; ++j)
212 if (min.x == buf[j].x && buf[j].y != min.y) kv_push(ab_u128_t, km, *p, buf[j]);
213 for (j = 0; j < buf_pos; ++j)
214 if (min.x == buf[j].x && buf[j].y != min.y) kv_push(ab_u128_t, km, *p, buf[j]);
215 }
216 if (info.x <= min.x) { // a new minimum; then write the old min
217 if (l >= w + k && min.x != UINT64_MAX) kv_push(ab_u128_t, km, *p, min);
218 min = info, min_pos = buf_pos;
219 } else if (buf_pos == min_pos) { // old min has moved outside the window
220 if (l >= w + k - 1 && min.x != UINT64_MAX) kv_push(ab_u128_t, km, *p, min);
221 for (j = buf_pos + 1, min.x = UINT64_MAX; j < w; ++j) // the two loops are necessary when there are identical k-mers
222 if (min.x >= buf[j].x) min = buf[j], min_pos = j; // >= is important s.t. min is always the closest k-mer
223 for (j = 0; j <= buf_pos; ++j)
224 if (min.x >= buf[j].x) min = buf[j], min_pos = j;
225 if (l >= w + k - 1 && min.x != UINT64_MAX) { // write identical k-mers
226 for (j = buf_pos + 1; j < w; ++j) // these two loops make sure the output is sorted
227 if (min.x == buf[j].x && min.y != buf[j].y) kv_push(ab_u128_t, km, *p, buf[j]);
228 for (j = 0; j <= buf_pos; ++j)
229 if (min.x == buf[j].x && min.y != buf[j].y) kv_push(ab_u128_t, km, *p, buf[j]);
230 }
231 }
232 if (++buf_pos == w) buf_pos = 0;
233 }
234 if (min.x != UINT64_MAX)
235 kv_push(ab_u128_t, km, *p, min);
236 }
237 /************ end *************/
238
239 // tree_id_map: guide tree node id -> original input order id
240 /* mm: is unsorted
241 * a.x = kMer<<8 | kmerSpan
242 * a.y = rid<<32 | strand<<31 | lastPos
243 */
244 int abpoa_build_guide_tree(abpoa_para_t *abpt, int n_seq, ab_u128_v *mm, int *tree_id_map) {
245 if (mm->n == 0) return 0;
246
247 if (abpt->verbose >= ABPOA_INFO_VERBOSE) fprintf(stderr, "[%s] Building progressive guide tree ... ", __func__);
248 size_t i, _i, j; int rid1, rid2; // mm_hit_n: mimizer hits between each two sequences
249 // 0: 0
250 // 1: 0 1
251 // 2: 0 1 2
252 int *mm_hit_n = (int*)_err_calloc((n_seq * (n_seq+1)) >> 1, sizeof(int)); // ...
253 // n: 0 1 ... n-1 n
254 //
255 // # total mimizers of i: mm_hit_n[(i*(i+1))/2+i]
256 // # total hits for i and j (i>j): mm_hit_n[(i*(i+1)/2)+j]
257 radix_sort_ab_128x(mm->a, mm->a + mm->n); // sort mm by k-mer hash values
258 uint64_t last_x = mm->a[0].x;
259 int *mm_cnt = (int*)_err_malloc(n_seq * sizeof(int));
260 for (_i = 0, i = 1; i < mm->n; ++i) { // collect mm hits
261 if (mm->a[i].x != last_x) {
262 // now [_i, i-1] have the same minimizer k-mer
263 memset(mm_cnt, 0, n_seq * sizeof(int));
264 for (j = _i; j < i; ++j) {
265 // count mm->a[j]
266 rid1 = mm->a[j].y >> 32;
267 ++mm_cnt[rid1];
268 ++mm_hit_n[((rid1 * (rid1+1)) >> 1) + rid1];
269 }
270 for (rid1 = 0; rid1 < n_seq-1; ++rid1) {
271 for (rid2 = rid1+1; rid2 < n_seq; ++rid2) {
272 mm_hit_n[((rid2 * (rid2 + 1)) >> 1) + rid1] += MIN_OF_TWO(mm_cnt[rid1], mm_cnt[rid2]);
273 }
274 }
275 // next minimizer
276 last_x = mm->a[i].x, _i = i;
277 }
278 }
279 // now [_i, i-1] have the same minimizer k-mer
280 memset(mm_cnt, 0, n_seq * sizeof(int));
281 for (j = _i; j < i; ++j) {
282 // count mm->a[j]
283 rid1 = mm->a[j].y >> 32;
284 ++mm_cnt[rid1];
285 ++mm_hit_n[((rid1 * (rid1+1)) >> 1) + rid1];
286 }
287 for (rid1 = 0; rid1 < n_seq-1; ++rid1) {
288 for (rid2 = rid1+1; rid2 < n_seq; ++rid2) {
289 mm_hit_n[((rid2 * (rid2 + 1)) >> 1) + rid1] += MIN_OF_TWO(mm_cnt[rid1], mm_cnt[rid2]);
290 }
291 }
292 free(mm_cnt);
293
294 // calculate jaccard similarity between each two sequences
295 double *jac_sim = (double*)_err_calloc((n_seq * (n_seq-1)) >> 1, sizeof(double));
296 double max_jac = -1.0, jac; int max_i=-1, max_j=-1;
297 for (i = 1; i < (size_t)n_seq; ++i) {
298 for (j = 0; j < i; ++j) {
299 int tot_n = mm_hit_n[((i*(i+1))>>1)+i] + mm_hit_n[((j*(j+1))>>1)+j] - mm_hit_n[((i*(i+1))>>1)+j];
300 if (tot_n == 0) jac = 0;
301 else if (tot_n < 0) err_fatal(__func__, "Bug in progressive tree building. (1)");
302 else jac = (0.0+mm_hit_n[((i*(i+1))>>1)+j]) / tot_n;
303 jac_sim[((i * (i-1)) >> 1) + j] = jac; // jac_sim[rid2*(rid2-1)/2 + rid1]
304 if (jac > max_jac) {
305 max_jac = jac; max_i = i, max_j = j;
306 }
307 }
308 }
309
310 // build guide tree
311 // first pick two with the biggest jac (max_i, max_j)
312 int n_in_map = 2; tree_id_map[0] = max_j, tree_id_map[1] = max_i;
313
314 // then, pick one with biggest jac sum with existing sequence in tree_id_map
315 while (n_in_map < n_seq) {
316 max_jac = -1.0, max_i = n_seq;
317 for (rid1 = 0; rid1 < n_seq; ++rid1) {
318 jac = 0.0;
319 for (i = 0; i < (size_t)n_in_map; ++i) {
320 rid2 = tree_id_map[i];
321 if (rid1 == rid2) { jac = -1.0; break; }
322 else if (rid1 > rid2) jac += jac_sim[((rid1 * (rid1-1)) >> 1) + rid2];
323 else jac += jac_sim[((rid2 * (rid2-1)) >> 1) + rid1];
324 }
325 if (jac > max_jac) {
326 max_jac = jac;
327 max_i = rid1;
328 }
329 }
330 if (max_i == n_seq) err_fatal(__func__, "Bug in progressive tree building. (2)");
331 tree_id_map[n_in_map++] = max_i;
332 }
333
334 free(mm_hit_n); free(jac_sim);
335 if (abpt->verbose >= ABPOA_INFO_VERBOSE) fprintf(stderr, "done!\n");
336 return 0;
337 }
338
339 // t's mm: is sorted, q's mm is unsorted
340 // | r1's minimizers | r2's minimizers | ... | rn's minimizers |
341 // mm_c: | 0 | n_r1_mm | n_r1..2_mm | ... | n_r1..n-1_mm | n_r1..n_mm |
342 // t is already in the graph, q is query sequence
343 // merge sort for t and q's minimizer buckets
344 int collect_anchors1(void *km, ab_u64_v *anchors, ab_u128_v mm, int *mm_c, int tid, int qid, int qlen, int k) {
345 int i, j, _i, _j; uint64_t xi, xj, _xi, _xj, _yi, _yj, a;
346 i = mm_c[tid], j = mm_c[qid];
347 // t's mm is already sorted XXX
348 radix_sort_ab_128x(mm.a + j, mm.a + mm_c[qid+1]);
349
350 while (i < mm_c[tid+1] && j < mm_c[qid+1]) {
351 xi = mm.a[i].x, xj = mm.a[j].x;
352 if (xi == xj) {
353 for (_i = i; _i < mm_c[tid+1]; ++_i) {
354 _xi = mm.a[_i].x;
355 if (_xi != xi) break;
356 _yi = mm.a[_i].y;
357 for (_j = j; _j < mm_c[qid+1]; ++_j) {
358 _xj = mm.a[_j].x;
359 if (_xj != xj) break;
360 _yj = mm.a[_j].y;
361 // t_strand<<63 | t_lastPos<<32 | q_lastPos
362 if ((_yi & 1) == (_yj & 1)) { // same strand
363 a = (uint64_t)((uint32_t)_yi>>1)<<32 | ((uint32_t)_yj>>1);
364 } else { // different strand
365 a = 1ULL<<63 | (uint64_t)((uint32_t)_yi>>1)<<32 | (qlen - (((uint32_t)_yj>>1)+1-k) - 1); // XXX qlen < pow(2,28)
366 }
367 kv_push(uint64_t, km, *anchors, a);
368 }
369 }
370 i = _i, j = _j;
371 } else if (xi < xj) ++i;
372 else if (xi > xj) ++j;
373 }
374 // sort by tpos
375 radix_sort_64(anchors->a, anchors->a + anchors->n);
376 return anchors->n;
377 }
378
379 int get_local_chain_score(int j_end_tpos, int j_end_qpos, int i_end_anchor_i, ab_u64_v *anchors, int *pre_id, int *score) {
380 int i = i_end_anchor_i, chain_score = 0;
381 int i_tpos, i_qpos;
382 do {
383 i_tpos = (anchors->a[i] >> 32) & 0x7fffffff, i_qpos = (int32_t)anchors->a[i];
384
385 if (i_tpos <= j_end_tpos && i_qpos <= j_end_qpos) break;
386 i = pre_id[i];
387 } while (i != -1);
388
389 if (i == -1) chain_score = score[i_end_anchor_i];
390 else chain_score = score[i_end_anchor_i] - score[i];
391 return chain_score;
392 }
393
394
395 // local chains:
396 // x: strand | end_tpos | end_qpos
397 // y: end_anchor_i | start_anchor_i
398 int abpoa_dp_chaining_of_local_chains(void *km, ab_u128_t *local_chains, int n_local_chains,
399 ab_u64_v *anchors, int *score, int *pre_id, ab_u64_v *par_anchors,
400 int min_w, int tlen, int qlen, int verbose) {
401 int i, j, st, score1, global_max_score=INT32_MIN, global_max_i=-1;
402 int *chain_score = (int*)kmalloc(km, n_local_chains * 4), *pre_chain_id = (int*)kmalloc(km, n_local_chains * 4);
403 size_t _n = par_anchors->n;
404
405 for (i = st = 0; i < n_local_chains; ++i) {
406 uint64_t ix = local_chains[i].x, iy = local_chains[i].y;
407 int istrand = ix >> 63, i_end_qpos = (int32_t)ix, i_end_anchor_i = iy >> 32, i_start_anchor_i = (int32_t)iy;
408 int i_start_tpos = (anchors->a[i_start_anchor_i] >> 32) & 0x7fffffff, i_start_qpos = (int32_t)anchors->a[i_start_anchor_i];
409 int max_j = -1, max_score = score[i_end_anchor_i];
410 while (st < i) {
411 if ((int)((local_chains[st].x) >> 63) != istrand) ++st;
412 else break;
413 }
414 for (j = i-1; j >= st; --j) {
415 uint64_t jx = local_chains[j].x;
416 int j_end_tpos = (jx >> 32) & 0x7fffffff, j_end_qpos = (int32_t)jx; //, j_end_anchor_i = iy >> 32;
417 if (j_end_qpos >= i_end_qpos) continue;
418
419 if (i_start_tpos > j_end_tpos && i_start_qpos > j_end_qpos) score1 = chain_score[j] + score[i_end_anchor_i];
420 else score1 = chain_score[j] + get_local_chain_score(j_end_tpos, j_end_qpos, i_end_anchor_i, anchors, pre_id, score);
421
422 if (score1 > max_score) {
423 max_score = score1; max_j = j;
424 }
425 }
426 chain_score[i] = max_score; pre_chain_id[i] = max_j;
427 if (max_score > global_max_score) {
428 global_max_score = max_score;
429 global_max_i = i;
430 }
431 }
432 if (global_max_i < 0) return 0;
433 // collect anchors based on global_max_i
434 int cur_i = global_max_i, pre_i = pre_chain_id[global_max_i];
435 uint64_t cur_y = local_chains[cur_i].y, pre_x, pre_y;
436 int last_tpos=tlen, last_qpos=qlen;
437 while (pre_i != -1) { // collect valid anchors in local_chains[cur_i], constrained by local_chains[pre_i]
438 pre_x = local_chains[pre_i].x, pre_y = local_chains[pre_i].y;
439 int pre_end_tpos = (pre_x >> 32) & 0x7fffffff, pre_end_qpos = (int32_t)pre_x;
440 i = cur_y >> 32;
441 while (i != -1) {
442 int cur_tpos = (anchors->a[i] >> 32) & 0x7fffffff, cur_qpos = (int32_t)anchors->a[i];
443 if (cur_tpos > pre_end_tpos && cur_qpos > pre_end_qpos) {
444 if (last_tpos - cur_tpos >= min_w && last_qpos - cur_qpos >= min_w) {
445 kv_push(uint64_t, 0, *par_anchors, anchors->a[i]);
446 last_tpos = cur_tpos, last_qpos = cur_qpos;
447 }
448 } else break;
449 i = pre_id[i];
450 }
451 cur_i = pre_i, pre_i = pre_chain_id[pre_i], cur_y = pre_y;
452 }
453 // collect anchors of last chain: local_chains[cur_i]
454 i = cur_y >> 32;
455 while (i != -1) {
456 int cur_tpos = (anchors->a[i] >> 32) & 0x7fffffff, cur_qpos = (int32_t)anchors->a[i];
457 if (last_tpos - cur_tpos >= min_w && last_qpos - cur_qpos >= min_w) {
458 kv_push(uint64_t, 0, *par_anchors, anchors->a[i]);
459 last_tpos = cur_tpos, last_qpos = cur_qpos;
460 }
461 i = pre_id[i];
462 }
463 // reverse order of par_anchors
464 for (i = 0; i < (int)(par_anchors->n-_n) >> 1; ++i) {
465 uint64_t tmp = par_anchors->a[_n+i];
466 par_anchors->a[_n+i] = par_anchors->a[par_anchors->n-i-1];
467 par_anchors->a[par_anchors->n-i-1] = tmp;
468 }
469
470 if (verbose >= ABPOA_LONG_DEBUG_VERBOSE) {
471 for (i = _n; i < par_anchors->n; ++i) {
472 uint64_t ia = par_anchors->a[i];
473 // strand, rpos, qpos
474 fprintf(stderr, "%c\t%" PRIu64 "\t%d\n", "+-"[ia >> 63], (ia>>32) & 0x7fffffff, ((uint32_t)ia));
475 }
476 }
477 kfree(km, chain_score), kfree(km, pre_chain_id);
478 return 0;
479 }
480
481 // for DP chaining
482 static int get_chain_score(int max_bw, int *score, int i_qpos, int i_tpos, int j_qpos, int j_tpos, int k) {
483 int delta_q, delta_t, delta_tq, min_d;
484
485 delta_q = i_qpos - j_qpos; delta_t = i_tpos - j_tpos;
486 min_d = MIN_OF_THREE(delta_q, delta_t, k);
487 *score = min_d;
488 if (delta_q >= delta_t) {
489 if ((delta_tq = delta_q - delta_t) > max_bw) return 0;
490 } else {
491 if ((delta_tq = delta_t - delta_q) > max_bw) return 0;
492 }
493 *score -= ((ilog2_32(delta_tq) >> 1) + delta_tq * 0.01 * k);
494 return 1;
495 }
496
497 // Dynamic Programming-based Chaining for global alignment mode
498 // anchors:
499 // strand<<63 | tpos<<32 | qpos
500 int abpoa_dp_chaining(void *km, ab_u64_v *anchors, ab_u64_v *par_anchors, abpoa_para_t *abpt, int tlen, int qlen, int verbose) {
501 int i, j, st, n_a = anchors->n;
502 int *score = (int32_t*)kmalloc(km, n_a * 4), *pre_id = (int32_t*)kmalloc(km, n_a * 4), *end_pos = (int32_t*)kmalloc(km, n_a * 4);
503 memset(end_pos, 0, n_a * 4);
504
505 int max_bw = 100, max_dis = 100, max_skip_anchors = 25, max_non_best_anchors = 50, min_local_chain_score = 100;
506 int min_w = abpt->min_w+abpt->k;
507 int i_qpos, i_tpos, i_tstrand, j_qpos, j_tpos;
508 for (i = st = 0; i < (int)anchors->n; ++i) {
509 uint64_t ia = anchors->a[i];
510 i_qpos = (int32_t)ia, i_tpos = (ia >> 32) & 0x7fffffff, i_tstrand = ia >> 63;
511 int max_j = -1, n_skip=0, non_best_iter_n = 0, max_score=abpt->k, _score;
512 while (st < i) {
513 uint64_t st_a = anchors->a[st];
514 if ((int)(st_a >> 63) != i_tstrand || (int)((st_a >> 32) & 0x7fffffff) + max_dis < i_tpos) ++st;
515 else break;
516 }
517
518 for (j = i-1; j >= st; --j) { // check if j is i's optimal pre anchor
519 uint64_t ja = anchors->a[j];
520 j_qpos = (uint32_t)ja; j_tpos = (ja >> 32) & 0x7fffffff;
521 if (j_qpos >= i_qpos || j_qpos + max_dis < i_qpos) continue;
522 if (!get_chain_score(max_bw, &_score, i_qpos, i_tpos, j_qpos, j_tpos, abpt->k)) continue;
523 _score += score[j];
524 if (_score > max_score) {
525 max_score = _score; max_j = j;
526 non_best_iter_n = 0;
527 if (n_skip > 0) --n_skip;
528 } else if (end_pos[j] == i) {
529 if (++n_skip > max_skip_anchors) break;
530 } else if (++non_best_iter_n > max_non_best_anchors) break;
531
532 if (pre_id[j] >= 0) end_pos[pre_id[j]] = i;
533 }
534 if (verbose >= ABPOA_LONG_DEBUG_VERBOSE) fprintf(stderr, "%d pre_id: %d, score: %d, tpos: %d, qpos: %d\n", i, max_j, max_score, i_tpos, i_qpos);
535 score[i] = max_score, pre_id[i] = max_j;
536 }
537
538 memset(end_pos, 0, n_a * 4);
539 int n_local_chains = 0;
540 for (i = n_a-1; i >= 0; --i) {
541 if (pre_id[i] >= 0) end_pos[pre_id[i]] = 1;
542 if (end_pos[i] == 0 && score[i] >= min_local_chain_score) {
543 end_pos[i] = 2;
544 ++n_local_chains;
545 }
546 }
547 // collect local chains
548 // x: score
549 // y: e_a_i
550 ab_u128_t *local_chains = (ab_u128_t*)kmalloc(km, n_local_chains * sizeof(ab_u128_t));
551 for (i = n_local_chains = 0; i < n_a; ++i) {
552 if (end_pos[i] == 2) {
553 local_chains[n_local_chains].x = score[i];
554 local_chains[n_local_chains++].y = i;
555 }
556 }
557 radix_sort_ab_128x(local_chains, local_chains + n_local_chains);
558
559 // collect local chains
560 // x: strand | endpos | score
561 // y: s_a_i | e_a_i
562 int32_t *anchor_map = end_pos; memset(anchor_map, 0, n_a * 4);
563 int start_id, end_id, tot_chain_i; uint64_t strand, tpos, qpos;
564
565 for (i = tot_chain_i = n_local_chains-1; i >=0; --i) {
566 j = local_chains[i].y; end_id = j; strand = anchors->a[i] >> 63; tpos = (anchors->a[j] >> 32) & 0x7fffffff, qpos = (int32_t)anchors->a[j];
567 do {
568 start_id = j;
569 anchor_map[j] = 1;
570 j = pre_id[j];
571 } while (j >= 0 && anchor_map[j] == 0);
572
573 if (j < 0) { // reach the start of the chain
574 local_chains[tot_chain_i].x = strand << 63 | tpos << 32 | qpos;
575 local_chains[tot_chain_i--].y = (uint64_t)end_id << 32 | start_id;
576 }
577 // not keep branched chains
578 /*else if ((int32_t)local_chains[i].x - score[j] >= min_local_chain_score) { // anchor_map == 1, anchor was already used in other chain
579 local_chains[tot_chain_i].x = strand << 63 | tpos << 32 | qpos;
580 local_chains[tot_chain_i--].y = (uint64_t)end_id << 32 | ((int32_t)local_chains[i].x - score[j]);
581 pre_id[start_id] = -1;
582 }*/
583 }
584
585 radix_sort_ab_128x(local_chains+tot_chain_i+1, local_chains + n_local_chains);
586 abpoa_dp_chaining_of_local_chains(km, local_chains+tot_chain_i+1, n_local_chains-1-tot_chain_i,
587 anchors, score, pre_id, par_anchors, min_w, tlen, qlen, abpt->verbose);
588
589 kfree(km, score); kfree(km, pre_id); kfree(km, end_pos); kfree(km, local_chains);
590 return 0;
591 }
592
593 int bin_search_min_larger(int *lis, int left, int right, int key) {
594 int mid;
595 while (right - left > 1) {
596 mid = ((right - left) >> 1) + left;
597
598 if (lis[mid] >= key) right = mid;
599 else left = mid;
600 }
601 return right;
602 }
603
604 // rank: qpos<<32 | tpos_rank
605 int LIS(void *km, int tot_n, uint64_t *rank, int n) {
606 int *pre_rank = (int*)kcalloc(km, tot_n+1, sizeof(int));
607 int *lis = (int*)kmalloc(km, n * sizeof(int));
608 int i, n_lis, irank, idx;
609 lis[0] = (uint32_t)rank[0]; n_lis = 1;
610
611 // calculate LIS length
612 for (i = 1; i < n; ++i) {
613 irank = (uint32_t)rank[i];
614 if (irank < lis[0]) {
615 lis[0] = irank;
616 } else if (irank > lis[n_lis-1]) {
617 lis[n_lis] = irank;
618 pre_rank[irank] = lis[n_lis-1];
619 ++n_lis;
620 } else {
621 idx = bin_search_min_larger(lis, -1, n_lis-1, irank);
622 lis[idx] = irank;
623 if (idx > 0) pre_rank[irank] = lis[idx-1];
624 }
625 }
626 // collect LIS, store ids in rank
627 int r = lis[n_lis-1]; i = n_lis-1;
628 while (r != 0) {
629 if (i < 0) err_fatal_simple("Error in LIS.");
630 rank[i--] = r;
631 r = pre_rank[r];
632 }
633 kfree(km, pre_rank); kfree(km, lis);
634 return n_lis;
635 }
636
637 // XXX TODO use dp-based chaining
638 // XXX TODO remove q_span
639
640 // Longest Increasing Subsequence-based Chaining (only works for global alignment mode)
641 // input:
642 // anchors: (sorted by tpos)
643 // strand<<63 | tpos<<32 | qpos
644 // output:
645 // anchor list size: n
646 // list of anchors: anchors
647 int LIS_chaining(void *km, ab_u64_v *anchors, ab_u64_v *par_anchors, int min_w, int verbose) {
648 size_t i, j, n_a = anchors->n, n_for, n_rev;
649 uint64_t *for_rank = (uint64_t*)kmalloc(km, sizeof(uint64_t) * n_a);
650 uint64_t *rev_rank = (uint64_t*)kmalloc(km, sizeof(uint64_t) * n_a);
651 uint64_t qpos;
652
653 n_for = 0, n_rev = 0;
654 for (i = 0; i < n_a; ++i) {
655 uint64_t ia = anchors->a[i];
656 qpos = (uint32_t)ia;
657 if (ia >> 63) { // reverse
658 rev_rank[n_rev++] = qpos << 32 | (i+1);
659 } else { // forward
660 for_rank[n_for++] = qpos << 32 | (i+1);
661 }
662 }
663
664 if (n_for > 0) {
665 radix_sort_64(for_rank, for_rank + n_for);
666 n_for = LIS(km, n_a, for_rank, n_for);
667 }
668 if (n_rev > 0) {
669 radix_sort_64(rev_rank, rev_rank + n_rev);
670 n_rev = LIS(km, n_a, rev_rank, n_rev);
671 }
672
673 size_t n; uint64_t *rank;
674 if (n_for > n_rev) {
675 n = n_for; rank = for_rank; kfree(km, rev_rank);
676 } else {
677 n = n_rev; rank = rev_rank; kfree(km, for_rank);
678 }
679 // filter anchors
680 int last_tpos = -1, last_qpos = -1, cur_tpos, cur_qpos; size_t _n = 0;
681 if (verbose >= ABPOA_LONG_DEBUG_VERBOSE) _n = par_anchors->n;
682 for (i = 0; i < n; ++i) {
683 j = (int)rank[i]-1;
684 cur_tpos = (anchors->a[j] >> 32) & 0x7fffffff;
685 if (cur_tpos - last_tpos < min_w) continue;
686 cur_qpos = (uint32_t)anchors->a[j];
687 if (cur_qpos - last_qpos < min_w) continue;
688
689 kv_push(uint64_t, 0, *par_anchors, anchors->a[j]); // store LIS anchors into par_anchors
690 last_tpos = cur_tpos; last_qpos = cur_qpos;
691 }
692
693 if (verbose >= ABPOA_LONG_DEBUG_VERBOSE) {
694 for (i = _n; i < par_anchors->n; ++i) {
695 uint64_t ia = par_anchors->a[i];
696 // strand, rpos, qpos
697 fprintf(stderr, "%c\t%" PRIu64 "\t%d\n", "+-"[ia >> 63], (ia>>32) & 0x7fffffff, ((uint32_t)ia));
698 }
699 }
700 return 0;
701 }
702
703 int abpoa_collect_mm(void *km, uint8_t **seqs, int *seq_lens, int n_seq, abpoa_para_t *abpt, ab_u128_v *mm, int *mm_c) {
704 if (abpt->verbose >= ABPOA_INFO_VERBOSE) fprintf(stderr, "[%s] Collecting minimizers ... ", __func__);
705 int i;
706 mm_c[0] = 0;
707 for (i = 0; i < n_seq; ++i) { // collect minimizers
708 if (abpt->m > 5) mm_aa_sketch(km, seqs[i], seq_lens[i], abpt->w, abpt->k, i, 0, mm);
709 else mm_sketch(km, seqs[i], seq_lens[i], abpt->w, abpt->k, i, 0, abpt->amb_strand, mm);
710 mm_c[i+1] = mm->n;
711 }
712 if (abpt->verbose >= ABPOA_INFO_VERBOSE) fprintf(stderr, "done!\n");
713 return mm->n;
714 }
715
716 // split guide tree and seeding and partition
717 int abpoa_build_guide_tree_partition(uint8_t **seqs, int *seq_lens, int n_seq, abpoa_para_t *abpt, int *read_id_map, ab_u64_v *par_anchors, int *par_c) {
718 int i; void *km = km_init();
719 for (i = 0; i < n_seq; ++i) read_id_map[i] = i;
720 ab_u128_v mm1 = {0, 0, 0}; int *mm_c = (int*)_err_malloc((n_seq+1) * sizeof(int));
721 abpoa_collect_mm(km, seqs, seq_lens, n_seq, abpt, &mm1, mm_c);
722
723 if (abpt->progressive_poa && n_seq > 2) {
724 // copy mm1 to mm2
725 ab_u128_v mm2 = {0, 0, 0};
726 for (i = 0; i < (int)mm1.n; ++i) kv_push(ab_u128_t, km, mm2, mm1.a[i]);
727 // use mm2 to build guide tree
728 abpoa_build_guide_tree(abpt, n_seq, &mm2, read_id_map);
729 kfree(km, mm2.a);
730 }
731 if (abpt->disable_seeding || n_seq < 2) {
732 kfree(km, mm1.a); free(mm_c); km_destroy(km);
733 return 0; // no anchor
734 }
735 // partition into small windows
736 int qid, tid;
737 tid = read_id_map[0];
738 radix_sort_ab_128x(mm1.a + mm_c[tid], mm1.a + mm_c[tid+1]);
739
740 par_c[0] = 0;
741 for (i = 1; i < n_seq; ++i) {
742 tid = read_id_map[i-1]; qid = read_id_map[i];
743 ab_u64_v anchors = {0, 0, 0};
744 // collect minimizer hit anchors between t and q
745 collect_anchors1(km, &anchors, mm1, mm_c, tid, qid, seq_lens[qid], abpt->k);
746 // filtering and only keep LIS anchors
747 if (abpt->verbose >= ABPOA_LONG_DEBUG_VERBOSE) fprintf(stderr, "%d vs %d (tot_n: %ld)\n", tid, qid, anchors.n);
748 // alignment mode: different chaining result for global/local/extend
749 abpoa_dp_chaining(km, &anchors, par_anchors, abpt, seq_lens[tid], seq_lens[qid], abpt->verbose);
750 par_c[i] = par_anchors->n;
751 kfree(km, anchors.a);
752 }
753
754 kfree(km, mm1.a); free(mm_c); km_destroy(km);
755 return 0; // par_anchors->n;
756 }