Debian Codegraph @

samtools/phase.c

raw symbols SCIP
1 /* phase.c -- phase subcommand.
2
3 Copyright (C) 2011 Broad Institute.
4 Copyright (C) 2013-2016, 2019 Genome Research Ltd.
5
6 Author: Heng Li <[email protected]>
7
8 Permission is hereby granted, free of charge, to any person obtaining a copy
9 of this software and associated documentation files (the "Software"), to deal
10 in the Software without restriction, including without limitation the rights
11 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 copies of the Software, and to permit persons to whom the Software is
13 furnished to do so, subject to the following conditions:
14
15 The above copyright notice and this permission notice shall be included in
16 all copies or substantial portions of the Software.
17
18 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 DEALINGS IN THE SOFTWARE. */
25
26 #include <config.h>
27
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <unistd.h>
31 #include <stdint.h>
32 #include <math.h>
33 #include <zlib.h>
34 #include "htslib/hts.h"
35 #include "htslib/sam.h"
36 #include "htslib/kstring.h"
37 #include "sam_opts.h"
38 #include "samtools.h"
39 #include "htslib/hts_os.h"
40
41 #include "htslib/kseq.h"
42 KSTREAM_INIT(gzFile, gzread, 16384)
43
44 #define MAX_VARS 256
45 #define FLIP_PENALTY 2
46 #define FLIP_THRES 4
47 #define MASK_THRES 3
48
49 #define FLAG_FIX_CHIMERA 0x1
50 #define FLAG_LIST_EXCL 0x4
51 #define FLAG_DROP_AMBI 0x8
52
53 typedef struct {
54 // configurations, initialized in the main function
55 int flag, k, min_baseQ, min_varLOD, max_depth, no_pg;
56 // other global variables
57 int vpos_shift;
58 samFile* fp;
59 sam_hdr_t* fp_hdr;
60 char *pre, *arg_list;
61 char *out_name[3];
62 samFile* out[3];
63 sam_hdr_t* out_hdr[3];
64 // alignment queue
65 int n, m;
66 bam1_t **b;
67 } phaseg_t;
68
69 typedef struct {
70 int8_t seq[MAX_VARS]; // TODO: change to dynamic memory allocation!
71 int vpos, beg, end;
72 uint32_t vlen:16, single:1, flip:1, phase:1, phased:1, ambig:1;
73 uint32_t in:16, out:16; // in-phase and out-phase
74 } frag_t, *frag_p;
75
76 #define rseq_lt(a,b) ((a)->vpos < (b)->vpos)
77
78 #include "htslib/khash.h"
79 KHASH_SET_INIT_INT64(set64)
80 KHASH_MAP_INIT_INT64(64, frag_t)
81
82 typedef khash_t(64) nseq_t;
83
84 #include "htslib/ksort.h"
85 KSORT_INIT(rseq, frag_p, rseq_lt)
86
87 static inline uint64_t X31_hash_string(const char *s)
88 {
89 uint64_t h = *s;
90 if (h) for (++s ; *s; ++s) h = (h << 5) - h + *s;
91 return h;
92 }
93
94 static void count1(int l, const uint8_t *seq, int *cnt)
95 {
96 int i, j, n_ambi;
97 uint32_t z, x;
98 if (seq[l-1] == 0) return; // do nothing is the last base is ambiguous
99 for (i = n_ambi = 0; i < l; ++i) // collect ambiguous bases
100 if (seq[i] == 0) ++n_ambi;
101 if (l - n_ambi <= 1) return; // only one SNP
102 for (x = 0; x < 1u<<n_ambi; ++x) { // count
103 for (i = j = 0, z = 0; i < l; ++i) {
104 int c;
105 if (seq[i]) c = seq[i] - 1;
106 else {
107 c = x>>j&1;
108 ++j;
109 }
110 z = z<<1 | c;
111 }
112 ++cnt[z];
113 }
114 }
115
116 static int **count_all(int l, int vpos, nseq_t *hash)
117 {
118 khint_t k;
119 int i, j, **cnt = NULL;
120 uint8_t *seq = NULL;
121 size_t cnt_sz = ((size_t)1) << l;
122 if (cnt_sz > SSIZE_MAX / sizeof(int) / vpos) {
123 errno = ENOMEM;
124 goto fail;
125 }
126 seq = calloc(l, 1);
127 if (!seq) goto fail;
128 cnt = calloc(vpos, sizeof(int*));
129 if (!cnt) goto fail;
130 for (i = 0; i < vpos; ++i) {
131 cnt[i] = calloc(cnt_sz, sizeof(int));
132 if (!cnt[i]) goto fail;
133 }
134 for (k = 0; k < kh_end(hash); ++k) {
135 if (kh_exist(hash, k)) {
136 frag_t *f = &kh_val(hash, k);
137 if (f->vpos >= vpos || f->single) continue; // out of region; or singleton
138 if (f->vlen == 1) { // such reads should be flagged as deleted previously if everything is right
139 f->single = 1;
140 continue;
141 }
142 for (j = 1; j < f->vlen; ++j) {
143 for (i = 0; i < l; ++i)
144 seq[i] = j < l - 1 - i? 0 : f->seq[j - (l - 1 - i)];
145 count1(l, seq, cnt[f->vpos + j]);
146 }
147 }
148 }
149 free(seq);
150 return cnt;
151 fail:
152 free(seq);
153 if (cnt) {
154 for (i = 0; i < vpos; i++)
155 free(cnt[i]);
156 free(cnt);
157 }
158 print_error_errno("phase", "Couldn't allocate memory for counts");
159 return NULL;
160 }
161
162 // phasing
163 static int8_t *dynaprog(int l, int vpos, int **w)
164 {
165 int *f[2], *curr, *prev, max, i;
166 int8_t **b, *h = 0;
167 uint32_t x, z = 1u<<(l-1), mask = (1u<<l) - 1;
168 f[0] = calloc(z, sizeof(int));
169 f[1] = calloc(z, sizeof(int));
170 b = calloc(vpos, sizeof(int8_t*));
171 prev = f[0]; curr = f[1];
172 // fill the backtrack matrix
173 for (i = 0; i < vpos; ++i) {
174 int *wi = w[i], *tmp;
175 int8_t *bi;
176 bi = b[i] = calloc(z, 1);
177 /* In the following, x is the current state, which is the
178 * lexicographically smaller local haplotype. xc is the complement of
179 * x, or the larger local haplotype; y0 and y1 are the two predecessors
180 * of x. */
181 for (x = 0; x < z; ++x) { // x0 is the smaller
182 uint32_t y0, y1, xc;
183 int c0, c1;
184 xc = ~x&mask; y0 = x>>1; y1 = xc>>1;
185 c0 = prev[y0] + wi[x] + wi[xc];
186 c1 = prev[y1] + wi[x] + wi[xc];
187 if (c0 > c1) bi[x] = 0, curr[x] = c0;
188 else bi[x] = 1, curr[x] = c1;
189 }
190 tmp = prev; prev = curr; curr = tmp; // swap
191 }
192 { // backtrack
193 uint32_t max_x = 0;
194 int which = 0;
195 h = calloc(vpos, 1);
196 for (x = 0, max = 0, max_x = 0; x < z; ++x)
197 if (prev[x] > max) max = prev[x], max_x = x;
198 for (i = vpos - 1, x = max_x; i >= 0; --i) {
199 h[i] = which? (~x&1) : (x&1);
200 which = b[i][x]? !which : which;
201 x = b[i][x]? (~x&mask)>>1 : x>>1;
202 }
203 }
204 // free
205 for (i = 0; i < vpos; ++i) free(b[i]);
206 free(f[0]); free(f[1]); free(b);
207 return h;
208 }
209
210 // phase each fragment
211 static uint64_t *fragphase(int vpos, const int8_t *path, nseq_t *hash, int flip)
212 {
213 khint_t k;
214 uint64_t *pcnt;
215 uint32_t *left, *rght, max;
216 left = rght = 0; max = 0;
217 pcnt = calloc(vpos, 8);
218 for (k = 0; k < kh_end(hash); ++k) {
219 if (kh_exist(hash, k)) {
220 int i, c[2];
221 frag_t *f = &kh_val(hash, k);
222 if (f->vpos >= vpos) continue;
223 // get the phase
224 c[0] = c[1] = 0;
225 for (i = 0; i < f->vlen; ++i) {
226 if (f->seq[i] == 0) continue;
227 ++c[f->seq[i] == path[f->vpos + i] + 1? 0 : 1];
228 }
229 f->phase = c[0] > c[1]? 0 : 1;
230 f->in = c[f->phase]; f->out = c[1 - f->phase];
231 f->phased = f->in == f->out? 0 : 1;
232 f->ambig = (f->in && f->out && f->out < 3 && f->in <= f->out + 1)? 1 : 0;
233 // fix chimera
234 f->flip = 0;
235 if (flip && c[0] >= 3 && c[1] >= 3) {
236 int sum[2], m, mi, md;
237 if (f->vlen > max) { // enlarge the array
238 max = f->vlen;
239 kroundup32(max);
240 left = realloc(left, max * 4);
241 rght = realloc(rght, max * 4);
242 }
243 for (i = 0, sum[0] = sum[1] = 0; i < f->vlen; ++i) { // get left counts
244 if (f->seq[i]) {
245 int c = f->phase? 2 - f->seq[i] : f->seq[i] - 1;
246 ++sum[c == path[f->vpos + i]? 0 : 1];
247 }
248 left[i] = sum[1]<<16 | sum[0];
249 }
250 for (i = f->vlen - 1, sum[0] = sum[1] = 0; i >= 0; --i) { // get right counts
251 if (f->seq[i]) {
252 int c = f->phase? 2 - f->seq[i] : f->seq[i] - 1;
253 ++sum[c == path[f->vpos + i]? 0 : 1];
254 }
255 rght[i] = sum[1]<<16 | sum[0];
256 }
257 // find the best flip point
258 for (i = m = 0, mi = -1, md = -1; i < f->vlen - 1; ++i) {
259 int a[2];
260 a[0] = (left[i]&0xffff) + (rght[i+1]>>16&0xffff) - (rght[i+1]&0xffff) * FLIP_PENALTY;
261 a[1] = (left[i]>>16&0xffff) + (rght[i+1]&0xffff) - (rght[i+1]>>16&0xffff) * FLIP_PENALTY;
262 if (a[0] > a[1]) {
263 if (a[0] > m) m = a[0], md = 0, mi = i;
264 } else {
265 if (a[1] > m) m = a[1], md = 1, mi = i;
266 }
267 }
268 if (m - c[0] >= FLIP_THRES && m - c[1] >= FLIP_THRES) { // then flip
269 f->flip = 1;
270 if (md == 0) { // flip the tail
271 for (i = mi + 1; i < f->vlen; ++i)
272 if (f->seq[i] == 1) f->seq[i] = 2;
273 else if (f->seq[i] == 2) f->seq[i] = 1;
274 } else { // flip the head
275 for (i = 0; i <= mi; ++i)
276 if (f->seq[i] == 1) f->seq[i] = 2;
277 else if (f->seq[i] == 2) f->seq[i] = 1;
278 }
279 }
280 }
281 // update pcnt[]
282 if (!f->single) {
283 for (i = 0; i < f->vlen; ++i) {
284 int c;
285 if (f->seq[i] == 0) continue;
286 c = f->phase? 2 - f->seq[i] : f->seq[i] - 1;
287 if (c == path[f->vpos + i]) {
288 if (f->phase == 0) ++pcnt[f->vpos + i];
289 else pcnt[f->vpos + i] += 1ull<<32;
290 } else {
291 if (f->phase == 0) pcnt[f->vpos + i] += 1<<16;
292 else pcnt[f->vpos + i] += 1ull<<48;
293 }
294 }
295 }
296 }
297 }
298 free(left); free(rght);
299 return pcnt;
300 }
301
302 static uint64_t *genmask(int vpos, const uint64_t *pcnt, int *_n)
303 {
304 int i, max = 0, max_i = -1, m = 0, n = 0, beg = 0, score = 0;
305 uint64_t *list = 0;
306 for (i = 0; i < vpos; ++i) {
307 uint64_t x = pcnt[i];
308 int c[4], pre = score, s;
309 c[0] = x&0xffff; c[1] = x>>16&0xffff; c[2] = x>>32&0xffff; c[3] = x>>48&0xffff;
310 s = (c[1] + c[3] == 0)? -(c[0] + c[2]) : (c[1] + c[3] - 1);
311 if (c[3] > c[2]) s += c[3] - c[2];
312 if (c[1] > c[0]) s += c[1] - c[0];
313 score += s;
314 if (score < 0) score = 0;
315 if (pre == 0 && score > 0) beg = i; // change from zero to non-zero
316 if ((i == vpos - 1 || score == 0) && max >= MASK_THRES) {
317 if (n == m) {
318 m = m? m<<1 : 4;
319 list = realloc(list, m * 8);
320 }
321 list[n++] = (uint64_t)beg<<32 | max_i;
322 i = max_i; // reset i to max_i
323 score = 0;
324 } else if (score > max) max = score, max_i = i;
325 if (score == 0) max = 0;
326 }
327 *_n = n;
328 return list;
329 }
330
331 // trim heading and tailing ambiguous bases; mark deleted and remove sequence
332 static int clean_seqs(int vpos, nseq_t *hash)
333 {
334 khint_t k;
335 int ret = 0;
336 for (k = 0; k < kh_end(hash); ++k) {
337 if (kh_exist(hash, k)) {
338 frag_t *f = &kh_val(hash, k);
339 int beg, end, i;
340 if (f->vpos >= vpos) {
341 ret = 1;
342 continue;
343 }
344 for (i = 0; i < f->vlen; ++i)
345 if (f->seq[i] != 0) break;
346 beg = i;
347 for (i = f->vlen - 1; i >= 0; --i)
348 if (f->seq[i] != 0) break;
349 end = i + 1;
350 if (end - beg <= 0) kh_del(64, hash, k);
351 else {
352 if (beg != 0) memmove(f->seq, f->seq + beg, end - beg);
353 f->vpos += beg; f->vlen = end - beg;
354 f->single = f->vlen == 1? 1 : 0;
355 }
356 }
357 }
358 return ret;
359 }
360
361 static int dump_aln(phaseg_t *g, int min_pos, const nseq_t *hash)
362 {
363 int i, is_flip, drop_ambi;
364 drop_ambi = g->flag & FLAG_DROP_AMBI;
365 is_flip = (drand48() < 0.5);
366 for (i = 0; i < g->n; ++i) {
367 int end, which;
368 uint64_t key;
369 khint_t k;
370 bam1_t *b = g->b[i];
371 key = X31_hash_string(bam_get_qname(b));
372 end = bam_endpos(b);
373 if (end > min_pos) break;
374 k = kh_get(64, hash, key);
375 if (k == kh_end(hash)) which = 3;
376 else {
377 frag_t *f = &kh_val(hash, k);
378 if (f->ambig) which = drop_ambi? 2 : 3;
379 else if (f->phased && f->flip) which = 2;
380 else if (f->phased == 0) which = 3;
381 else { // phased and not flipped
382 char c = 'Y';
383 which = f->phase;
384 bam_aux_append(b, "ZP", 'A', 1, (uint8_t*)&c);
385 }
386 if (which < 2 && is_flip) which = 1 - which; // increase the randomness
387 }
388 if (which == 3) which = (drand48() < 0.5);
389 if (sam_write1(g->out[which], g->out_hdr[which], b) < 0) {
390 print_error_errno("phase", "error writing to '%s'", g->out_name[which]);
391 return -1;
392 }
393 bam_destroy1(b);
394 g->b[i] = 0;
395 }
396 memmove(g->b, g->b + i, (g->n - i) * sizeof(void*));
397 g->n -= i;
398 return 0;
399 }
400
401 static int phase(phaseg_t *g, const char *chr, int vpos, uint64_t *cns, nseq_t *hash)
402 {
403 int i, j, n_seqs = kh_size(hash), n_masked = 0, min_pos;
404 khint_t k;
405 frag_t **seqs;
406 int8_t *path, *sitemask;
407 uint64_t *pcnt, *regmask;
408
409 if (vpos == 0) return 0;
410 i = clean_seqs(vpos, hash); // i is true if hash has an element with its vpos >= vpos
411 min_pos = i? cns[vpos]>>32 : 0x7fffffff;
412 if (vpos == 1) {
413 printf("PS\t%s\t%d\t%d\n", chr, (int)(cns[0]>>32) + 1, (int)(cns[0]>>32) + 1);
414 printf("M0\t%s\t%d\t%d\t%c\t%c\t%d\t0\t0\t0\t0\n//\n", chr, (int)(cns[0]>>32) + 1, (int)(cns[0]>>32) + 1,
415 "ACGTX"[cns[0]&3], "ACGTX"[cns[0]>>16&3], g->vpos_shift + 1);
416 for (k = 0; k < kh_end(hash); ++k) {
417 if (kh_exist(hash, k)) {
418 frag_t *f = &kh_val(hash, k);
419 if (f->vpos) continue;
420 f->flip = 0;
421 if (f->seq[0] == 0) f->phased = 0;
422 else f->phased = 1, f->phase = f->seq[0] - 1;
423 }
424 }
425 if (dump_aln(g, min_pos, hash) < 0) return -1;
426 ++g->vpos_shift;
427 return 1;
428 }
429 { // phase
430 int **cnt;
431 uint64_t *mask;
432 printf("PS\t%s\t%d\t%d\n", chr, (int)(cns[0]>>32) + 1, (int)(cns[vpos-1]>>32) + 1);
433 sitemask = calloc(vpos, 1);
434 cnt = count_all(g->k, vpos, hash);
435 if (!cnt) return -1;
436 path = dynaprog(g->k, vpos, cnt);
437 for (i = 0; i < vpos; ++i) free(cnt[i]);
438 free(cnt);
439 pcnt = fragphase(vpos, path, hash, 0); // do not fix chimeras when masking
440 mask = genmask(vpos, pcnt, &n_masked);
441 regmask = calloc(n_masked, 8);
442 for (i = 0; i < n_masked; ++i) {
443 regmask[i] = cns[mask[i]>>32]>>32<<32 | cns[(uint32_t)mask[i]]>>32;
444 for (j = mask[i]>>32; j <= (int32_t)mask[i]; ++j)
445 sitemask[j] = 1;
446 }
447 free(mask);
448 if (g->flag & FLAG_FIX_CHIMERA) {
449 free(pcnt);
450 pcnt = fragphase(vpos, path, hash, 1);
451 }
452 }
453 for (i = 0; i < n_masked; ++i)
454 printf("FL\t%s\t%d\t%d\n", chr, (int)(regmask[i]>>32) + 1, (int)regmask[i] + 1);
455 for (i = 0; i < vpos; ++i) {
456 uint64_t x = pcnt[i];
457 int8_t c[2];
458 c[0] = (cns[i]&0xffff)>>2 == 0? 4 : (cns[i]&3);
459 c[1] = (cns[i]>>16&0xffff)>>2 == 0? 4 : (cns[i]>>16&3);
460 printf("M%d\t%s\t%d\t%d\t%c\t%c\t%d\t%d\t%d\t%d\t%d\n", sitemask[i]+1, chr, (int)(cns[0]>>32) + 1, (int)(cns[i]>>32) + 1, "ACGTX"[c[path[i]]], "ACGTX"[c[1-path[i]]],
461 i + g->vpos_shift + 1, (int)(x&0xffff), (int)(x>>16&0xffff), (int)(x>>32&0xffff), (int)(x>>48&0xffff));
462 }
463 free(path); free(pcnt); free(regmask); free(sitemask);
464 seqs = calloc(n_seqs, sizeof(frag_t*));
465 for (k = 0, i = 0; k < kh_end(hash); ++k)
466 if (kh_exist(hash, k) && kh_val(hash, k).vpos < vpos && !kh_val(hash, k).single)
467 seqs[i++] = &kh_val(hash, k);
468 n_seqs = i;
469 ks_introsort_rseq(n_seqs, seqs);
470 for (i = 0; i < n_seqs; ++i) {
471 frag_t *f = seqs[i];
472 printf("EV\t0\t%s\t%d\t40\t%dM\t*\t0\t0\t", chr, f->vpos + 1 + g->vpos_shift, f->vlen);
473 for (j = 0; j < f->vlen; ++j) {
474 uint32_t c = cns[f->vpos + j];
475 if (f->seq[j] == 0) putchar('N');
476 else putchar("ACGT"[f->seq[j] == 1? (c&3) : (c>>16&3)]);
477 }
478 printf("\t*\tYP:i:%d\tYF:i:%d\tYI:i:%d\tYO:i:%d\tYS:i:%d\n", f->phase, f->flip, f->in, f->out, f->beg+1);
479 }
480 free(seqs);
481 printf("//\n");
482 fflush(stdout);
483 g->vpos_shift += vpos;
484 if (dump_aln(g, min_pos, hash) < 0) return -1;
485 return vpos;
486 }
487
488 static void update_vpos(int vpos, nseq_t *hash)
489 {
490 khint_t k;
491 for (k = 0; k < kh_end(hash); ++k) {
492 if (kh_exist(hash, k)) {
493 frag_t *f = &kh_val(hash, k);
494 if (f->vpos < vpos) kh_del(64, hash, k); // TODO: if frag_t::seq is allocated dynamically, free it
495 else f->vpos -= vpos;
496 }
497 }
498 }
499
500 static nseq_t *shrink_hash(nseq_t *hash) // TODO: to implement
501 {
502 return hash;
503 }
504
505 static int readaln(void *data, bam1_t *b)
506 {
507 phaseg_t *g = (phaseg_t*)data;
508 int ret;
509 while (1)
510 {
511 ret = sam_read1(g->fp, g->fp_hdr, b);
512 if (ret < 0) break;
513 if ( b->core.flag & (BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP) ) continue;
514 if ( g->pre ) {
515 if (g->n == g->m) {
516 g->m = g->m? g->m<<1 : 16;
517 g->b = realloc(g->b, g->m * sizeof(bam1_t*));
518 }
519 g->b[g->n++] = bam_dup1(b);
520 }
521 break;
522 }
523 return ret;
524 }
525
526 static khash_t(set64) *loadpos(const char *fn, sam_hdr_t *h)
527 {
528 gzFile fp;
529 kstream_t *ks;
530 int ret, dret;
531 kstring_t *str;
532 khash_t(set64) *hash;
533
534 fp = strcmp(fn, "-")? gzopen(fn, "r") : gzdopen(fileno(stdin), "r");
535 if (fp == NULL) {
536 print_error_errno("phase", "Couldn't open site file '%s'", fn);
537 return NULL;
538 }
539
540 hash = kh_init(set64);
541 str = calloc(1, sizeof(kstring_t));
542
543 ks = ks_init(fp);
544 while (ks_getuntil(ks, 0, str, &dret) >= 0) {
545 int tid = bam_name2id(h, str->s);
546 if (tid >= 0 && dret != '\n') {
547 if (ks_getuntil(ks, 0, str, &dret) >= 0) {
548 uint64_t x = (uint64_t)tid<<32 | (atoi(str->s) - 1);
549 kh_put(set64, hash, x, &ret);
550 } else break;
551 }
552 if (dret != '\n') while ((dret = ks_getc(ks)) > 0 && dret != '\n');
553 if (dret < 0) break;
554 }
555 ks_destroy(ks);
556 gzclose(fp);
557 free(str->s); free(str);
558 return hash;
559 }
560
561 static int gl2cns(float q[16])
562 {
563 int i, j, min_ij;
564 float min, min2;
565 min = min2 = 1e30; min_ij = -1;
566 for (i = 0; i < 4; ++i) {
567 for (j = i; j < 4; ++j) {
568 if (q[i<<2|j] < min) min_ij = i<<2|j, min2 = min, min = q[i<<2|j];
569 else if (q[i<<2|j] < min2) min2 = q[i<<2|j];
570 }
571 }
572 return (min_ij>>2&3) == (min_ij&3)? 0 : 1<<18 | (min_ij>>2&3)<<16 | (min_ij&3) | (int)(min2 - min + .499) << 2;
573 }
574
575 static int start_output(phaseg_t *g, int c, const char *middle, const htsFormat *fmt)
576 {
577 kstring_t s = { 0, 0, NULL };
578 ksprintf(&s, "%s.%s.%s", g->pre, middle, hts_format_file_extension(fmt));
579 g->out_name[c] = ks_release(&s);
580 g->out[c] = sam_open_format(g->out_name[c], "wb", fmt);
581 if (! g->out[c]) {
582 print_error_errno("phase", "Failed to open output file '%s'", g->out_name[c]);
583 return -1;
584 }
585
586 g->out_hdr[c] = sam_hdr_dup(g->fp_hdr);
587 if (!g->no_pg && sam_hdr_add_pg(g->out_hdr[c], "samtools",
588 "VN", samtools_version(),
589 g->arg_list ? "CL": NULL,
590 g->arg_list ? g->arg_list : NULL,
591 NULL)) {
592 print_error("phase", "failed to add PG line to header");
593 return -1;
594 }
595 if (sam_hdr_write(g->out[c], g->out_hdr[c]) < 0) {
596 print_error_errno("phase", "Failed to write header for '%s'", g->out_name[c]);
597 return -1;
598 }
599
600 return 0;
601 }
602
603 int main_phase(int argc, char *argv[])
604 {
605 int c, tid, pos, vpos = 0, n, lasttid = -1, max_vpos = 0, usage = 0;
606 int status = EXIT_SUCCESS;
607 const bam_pileup1_t *plp;
608 bam_plp_t iter;
609 nseq_t *seqs;
610 uint64_t *cns = 0;
611 phaseg_t g;
612 char *fn_list = 0;
613 khash_t(set64) *set = 0;
614 errmod_t *em;
615 uint16_t *bases;
616
617 sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
618 static const struct option lopts[] = {
619 SAM_OPT_GLOBAL_OPTIONS('-', 0, 0, 0, 0, '-'),
620 {"min-BQ", required_argument, NULL, 'Q'},
621 {"min-bq", required_argument, NULL, 'Q'},
622 {"no-PG", no_argument, NULL, 1},
623 { NULL, 0, NULL, 0 }
624 };
625
626 // FIXME Leaks galore in the case of error returns
627
628 memset(&g, 0, sizeof(phaseg_t));
629 g.flag = FLAG_FIX_CHIMERA;
630 g.min_varLOD = 37; g.k = 13; g.min_baseQ = 13; g.max_depth = 256;
631 while ((c = getopt_long(argc, argv, "Q:eFq:k:b:l:D:A", lopts, NULL)) >= 0) {
632 switch (c) {
633 case 'D': g.max_depth = atoi(optarg); break;
634 case 'q': g.min_varLOD = atoi(optarg); break;
635 case 'Q': g.min_baseQ = atoi(optarg); break;
636 case 'k': g.k = atoi(optarg); break;
637 case 'F': g.flag &= ~FLAG_FIX_CHIMERA; break;
638 case 'e': g.flag |= FLAG_LIST_EXCL; break;
639 case 'A': g.flag |= FLAG_DROP_AMBI; break;
640 case 'b': g.pre = strdup(optarg); break;
641 case 'l': fn_list = strdup(optarg); break;
642 case 1: g.no_pg = 1; break;
643 default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
644 /* else fall-through */
645 case '?': usage=1; break;
646 }
647 if (usage) break;
648 }
649 if (usage || argc == optind) {
650 fprintf(stderr, "\n");
651 fprintf(stderr, "Usage: samtools phase [options] <in.bam>\n\n");
652 fprintf(stderr, "Options: -k INT block length [%d]\n", g.k);
653 fprintf(stderr, " -b STR prefix of BAMs to output [null]\n");
654 fprintf(stderr, " -q INT min het phred-LOD [%d]\n", g.min_varLOD);
655 fprintf(stderr, " -Q, --min-BQ INT\n"
656 " min base quality in het calling [%d]\n", g.min_baseQ);
657 fprintf(stderr, " -D INT max read depth [%d]\n", g.max_depth);
658 // fprintf(stderr, " -l FILE list of sites to phase [null]\n");
659 fprintf(stderr, " -F do not attempt to fix chimeras\n");
660 fprintf(stderr, " -A drop reads with ambiguous phase\n");
661 fprintf(stderr, " --no-PG do not add a PG line\n");
662 // fprintf(stderr, " -e do not discover SNPs (effective with -l)\n");
663 fprintf(stderr, "\n");
664
665 sam_global_opt_help(stderr, "-....--.");
666
667 return 1;
668 }
669 g.fp = sam_open_format(argv[optind], "r", &ga.in);
670 if (!g.fp) {
671 print_error_errno("phase", "Couldn't open '%s'", argv[optind]);
672 return 1;
673 }
674 g.fp_hdr = sam_hdr_read(g.fp);
675 if (g.fp_hdr == NULL) {
676 fprintf(stderr, "[%s] Failed to read header for '%s'\n",
677 __func__, argv[optind]);
678 return 1;
679 }
680 if (!g.no_pg && !(g.arg_list = stringify_argv(argc+1, argv-1))) {
681 print_error("phase", "failed to create arg_list");
682 return 1;
683 }
684 if (fn_list) { // read the list of sites to phase
685 set = loadpos(fn_list, g.fp_hdr);
686 if (set == NULL) return 1;
687 free(fn_list);
688 } else g.flag &= ~FLAG_LIST_EXCL;
689 if (g.pre) { // open BAMs to write
690 if (ga.out.format == unknown_format)
691 ga.out.format = bam; // default via "wb".
692
693 // Open each output file g.out[0..2], dupping and writing the header
694 if (start_output(&g, 0, "0", &ga.out) < 0 ||
695 start_output(&g, 1, "1", &ga.out) < 0 ||
696 start_output(&g, 2, "chimera", &ga.out) < 0) return 1;
697 }
698
699 iter = bam_plp_init(readaln, &g);
700 g.vpos_shift = 0;
701 seqs = kh_init(64);
702 em = errmod_init(1. - 0.83);
703 bases = calloc(g.max_depth, 2);
704 printf("CC\n");
705 printf("CC\tDescriptions:\nCC\n");
706 printf("CC\t CC comments\n");
707 printf("CC\t PS start of a phase set\n");
708 printf("CC\t FL filtered region\n");
709 printf("CC\t M[012] markers; 0 for singletons, 1 for phased and 2 for filtered\n");
710 printf("CC\t EV supporting reads; SAM format\n");
711 printf("CC\t // end of a phase set\nCC\n");
712 printf("CC\tFormats of PS, FL and M[012] lines (1-based coordinates):\nCC\n");
713 printf("CC\t PS chr phaseSetStart phaseSetEnd\n");
714 printf("CC\t FL chr filterStart filterEnd\n");
715 printf("CC\t M? chr PS pos allele0 allele1 hetIndex #supports0 #errors0 #supp1 #err1\n");
716 printf("CC\nCC\n");
717 fflush(stdout);
718 while ((plp = bam_plp_auto(iter, &tid, &pos, &n)) != 0) {
719 int i, k, c, tmp, dophase = 1, in_set = 0;
720 float q[16];
721 if (tid < 0) break;
722 if (tid != lasttid) { // change of chromosome
723 g.vpos_shift = 0;
724 if (lasttid >= 0) {
725 seqs = shrink_hash(seqs);
726 if (phase(&g, sam_hdr_tid2name(g.fp_hdr, lasttid),
727 vpos, cns, seqs) < 0) {
728 return 1;
729 }
730 update_vpos(0x7fffffff, seqs);
731 }
732 lasttid = tid;
733 vpos = 0;
734 }
735 if (set && kh_get(set64, set, (uint64_t)tid<<32 | pos) != kh_end(set)) in_set = 1;
736 if (n > g.max_depth) continue; // do not proceed if the depth is too high
737 // fill the bases array and check if there is a variant
738 for (i = k = 0; i < n; ++i) {
739 const bam_pileup1_t *p = plp + i;
740 uint8_t *seq;
741 int q, baseQ, b;
742 if (p->is_del || p->is_refskip) continue;
743 baseQ = bam_get_qual(p->b)[p->qpos];
744 if (baseQ < g.min_baseQ) continue;
745 seq = bam_get_seq(p->b);
746 b = seq_nt16_int[bam_seqi(seq, p->qpos)];
747 if (b > 3) continue;
748 q = baseQ < p->b->core.qual? baseQ : p->b->core.qual;
749 if (q < 4) q = 4;
750 if (q > 63) q = 63;
751 bases[k++] = q<<5 | (int)bam_is_rev(p->b)<<4 | b;
752 }
753 if (k == 0) continue;
754 errmod_cal(em, k, 4, bases, q); // compute genotype likelihood
755 c = gl2cns(q); // get the consensus
756 // tell if to proceed
757 if (set && (g.flag&FLAG_LIST_EXCL) && !in_set) continue; // not in the list
758 if (!in_set && (c&0xffff)>>2 < g.min_varLOD) continue; // not a variant
759 // add the variant
760 if (vpos == max_vpos) {
761 max_vpos = max_vpos? max_vpos<<1 : 128;
762 cns = realloc(cns, max_vpos * 8);
763 }
764 cns[vpos] = (uint64_t)pos<<32 | c;
765 for (i = 0; i < n; ++i) {
766 const bam_pileup1_t *p = plp + i;
767 uint64_t key;
768 khint_t k;
769 uint8_t *seq = bam_get_seq(p->b);
770 frag_t *f;
771 if (p->is_del || p->is_refskip) continue;
772 if (p->b->core.qual == 0) continue;
773 // get the base code
774 c = seq_nt16_int[bam_seqi(seq, p->qpos)];
775 if (c == (cns[vpos]&3)) c = 1;
776 else if (c == (cns[vpos]>>16&3)) c = 2;
777 else c = 0;
778 // write to seqs
779 key = X31_hash_string(bam_get_qname(p->b));
780 k = kh_put(64, seqs, key, &tmp);
781 f = &kh_val(seqs, k);
782 if (tmp == 0) { // present in the hash table
783 if (vpos - f->vpos + 1 < MAX_VARS) {
784 f->vlen = vpos - f->vpos + 1;
785 f->seq[f->vlen-1] = c;
786 f->end = bam_endpos(p->b);
787 }
788 dophase = 0;
789 } else { // absent
790 memset(f->seq, 0, MAX_VARS);
791 f->beg = p->b->core.pos;
792 f->end = bam_endpos(p->b);
793 f->vpos = vpos, f->vlen = 1, f->seq[0] = c, f->single = f->phased = f->flip = f->ambig = 0;
794 }
795 }
796 if (dophase) {
797 seqs = shrink_hash(seqs);
798 if (phase(&g, sam_hdr_tid2name(g.fp_hdr, tid), vpos, cns, seqs) < 0) {
799 return 1;
800 }
801 update_vpos(vpos, seqs);
802 cns[0] = cns[vpos];
803 vpos = 0;
804 }
805 ++vpos;
806 }
807 if (tid >= 0) {
808 if (phase(&g, sam_hdr_tid2name(g.fp_hdr, tid), vpos, cns, seqs) < 0) {
809 return 1;
810 }
811 }
812
813 if (n < 0) {
814 print_error("phase", "error reading from '%s'", argv[optind]);
815 status = EXIT_FAILURE;
816 }
817
818 sam_hdr_destroy(g.fp_hdr);
819 bam_plp_destroy(iter);
820 sam_close(g.fp);
821 kh_destroy(64, seqs);
822 kh_destroy(set64, set);
823 free(cns);
824 errmod_destroy(em);
825 free(bases);
826 if (g.pre) {
827 int res = 0;
828 for (c = 0; c <= 2; ++c) {
829 if (sam_close(g.out[c]) < 0) {
830 fprintf(stderr, "[%s] error on closing '%s'\n",
831 __func__, g.out_name[c]);
832 res = 1;
833 }
834 sam_hdr_destroy(g.out_hdr[c]);
835 free(g.out_name[c]);
836 }
837 free(g.pre); free(g.b);
838 if (res) return 1;
839 }
840 free(g.arg_list);
841 sam_global_args_free(&ga);
842 return status;
843 }