Debian Codegraph @

samtools/phase.c.pysam.c

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