]> git.donarmstrong.com Git - samtools.git/blob - phase.c
* put version number in bam.h
[samtools.git] / phase.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <stdint.h>
5 #include <math.h>
6 #include <zlib.h>
7 #include "bam.h"
8 #include "errmod.h"
9
10 #include "kseq.h"
11 KSTREAM_INIT(gzFile, gzread, 16384)
12
13 #define MAX_VARS 256
14 #define FLIP_PENALTY 2
15 #define FLIP_THRES 4
16 #define MASK_THRES 3
17
18 #define FLAG_FIX_CHIMERA 0x1
19 #define FLAG_LIST_EXCL   0x4
20
21 typedef struct {
22         // configurations, initialized in the main function
23         int flag, k, min_baseQ, min_varLOD, max_depth;
24         // other global variables
25         int vpos_shift;
26         bamFile fp;
27         char *pre;
28         bamFile out[3];
29         // alignment queue
30         int n, m;
31         bam1_t **b;
32 } phaseg_t;
33
34 typedef struct {
35         int8_t seq[MAX_VARS]; // TODO: change to dynamic memory allocation!
36         int vpos, beg, end;
37         uint32_t vlen:16, single:1, flip:1, phase:1, phased:1;
38         uint32_t in:16, out:16; // in-phase and out-phase
39 } frag_t, *frag_p;
40
41 #define rseq_lt(a,b) ((a)->vpos < (b)->vpos)
42
43 #include "khash.h"
44 KHASH_SET_INIT_INT64(set64)
45 KHASH_MAP_INIT_INT64(64, frag_t)
46
47 typedef khash_t(64) nseq_t;
48
49 #include "ksort.h"
50 KSORT_INIT(rseq, frag_p, rseq_lt)
51
52 static char nt16_nt4_table[] = { 4, 0, 1, 4, 2, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4 };
53
54 static inline uint64_t X31_hash_string(const char *s)
55 {
56         uint64_t h = *s;
57         if (h) for (++s ; *s; ++s) h = (h << 5) - h + *s;
58         return h;
59 }
60
61 static void count1(int l, const uint8_t *seq, int *cnt)
62 {
63         int i, j, n_ambi;
64         uint32_t z, x;
65         if (seq[l-1] == 0) return; // do nothing is the last base is ambiguous
66         for (i = n_ambi = 0; i < l; ++i) // collect ambiguous bases
67                 if (seq[i] == 0) ++n_ambi;
68         if (l - n_ambi <= 1) return; // only one SNP
69         for (x = 0; x < 1u<<n_ambi; ++x) { // count
70                 for (i = j = 0, z = 0; i < l; ++i) {
71                         int c;
72                         if (seq[i]) c = seq[i] - 1;
73                         else {
74                                 c = x>>j&1;
75                                 ++j;
76                         }
77                         z = z<<1 | c;
78                 }
79                 ++cnt[z];
80         }
81 }
82
83 static int **count_all(int l, int vpos, nseq_t *hash)
84 {
85         khint_t k;
86         int i, j, **cnt;
87         uint8_t *seq;
88         seq = calloc(l, 1);
89         cnt = calloc(vpos, sizeof(void*));
90         for (i = 0; i < vpos; ++i) cnt[i] = calloc(1<<l, sizeof(int));
91         for (k = 0; k < kh_end(hash); ++k) {
92                 if (kh_exist(hash, k)) {
93                         frag_t *f = &kh_val(hash, k);
94                         if (f->vpos >= vpos || f->single) continue; // out of region; or singleton
95                         if (f->vlen == 1) { // such reads should be flagged as deleted previously if everything is right
96                                 f->single = 1;
97                                 continue;
98                         }
99                         for (j = 1; j < f->vlen; ++j) {
100                                 for (i = 0; i < l; ++i)
101                                         seq[i] = j < l - 1 - i? 0 : f->seq[j - (l - 1 - i)];
102                                 count1(l, seq, cnt[f->vpos + j]);
103                         }
104                 }
105         }
106         free(seq);
107         return cnt;
108 }
109
110 // phasing
111 static int8_t *dynaprog(int l, int vpos, int **w)
112 {
113         int *f[2], *curr, *prev, max, i;
114         int8_t **b, *h = 0;
115         uint32_t x, z = 1u<<(l-1), mask = (1u<<l) - 1;
116         f[0] = calloc(z, sizeof(int));
117         f[1] = calloc(z, sizeof(int));
118         b = calloc(vpos, sizeof(void*));
119         prev = f[0]; curr = f[1];
120         // fill the backtrack matrix
121         for (i = 0; i < vpos; ++i) {
122                 int *wi = w[i], *tmp;
123                 int8_t *bi;
124                 bi = b[i] = calloc(z, 1);
125                 /* In the following, x is the current state, which is the
126                  * lexicographically smaller local haplotype. xc is the complement of
127                  * x, or the larger local haplotype; y0 and y1 are the two predecessors
128                  * of x. */
129                 for (x = 0; x < z; ++x) { // x0 is the smaller 
130                         uint32_t y0, y1, xc;
131                         int c0, c1;
132                         xc = ~x&mask; y0 = x>>1; y1 = xc>>1;
133                         c0 = prev[y0] + wi[x] + wi[xc];
134                         c1 = prev[y1] + wi[x] + wi[xc];
135                         if (c0 > c1) bi[x] = 0, curr[x] = c0;
136                         else bi[x] = 1, curr[x] = c1;
137                 }
138                 tmp = prev; prev = curr; curr = tmp; // swap
139         }
140         { // backtrack
141                 uint32_t max_x = 0;
142                 int which = 0;
143                 h = calloc(vpos, 1);
144                 for (x = 0, max = 0, max_x = 0; x < z; ++x)
145                         if (prev[x] > max) max = prev[x], max_x = x;
146                 for (i = vpos - 1, x = max_x; i >= 0; --i) {
147                         h[i] = which? (~x&1) : (x&1);
148                         which = b[i][x]? !which : which;
149                         x = b[i][x]? (~x&mask)>>1 : x>>1;
150                 }
151         }
152         // free
153         for (i = 0; i < vpos; ++i) free(b[i]);
154         free(f[0]); free(f[1]); free(b);
155         return h;
156 }
157
158 // phase each fragment
159 static uint64_t *fragphase(int vpos, const int8_t *path, nseq_t *hash, int flip)
160 {
161         khint_t k;
162         uint64_t *pcnt;
163         uint32_t *left, *rght, max;
164         left = rght = 0; max = 0;
165         pcnt = calloc(vpos, 8);
166         for (k = 0; k < kh_end(hash); ++k) {
167                 if (kh_exist(hash, k)) {
168                         int i, c[2];
169                         frag_t *f = &kh_val(hash, k);
170                         if (f->vpos >= vpos) continue;
171                         // get the phase
172                         c[0] = c[1] = 0;
173                         for (i = 0; i < f->vlen; ++i) {
174                                 if (f->seq[i] == 0) continue;
175                                 ++c[f->seq[i] == path[f->vpos + i] + 1? 0 : 1];
176                         }
177                         f->phase = c[0] > c[1]? 0 : 1;
178                         f->in = c[f->phase]; f->out = c[1 - f->phase];
179                         if (f->in && f->out && f->in <= f->out + 1) f->phased = 0;
180                         // fix chimera
181                         f->flip = 0;
182                         if (flip && c[0] >= 3 && c[1] >= 3) {
183                                 int sum[2], m, mi, md;
184                                 if (f->vlen > max) { // enlarge the array
185                                         max = f->vlen;
186                                         kroundup32(max);
187                                         left = realloc(left, max * 4);
188                                         rght = realloc(rght, max * 4);
189                                 }
190                                 for (i = 0, sum[0] = sum[1] = 0; i < f->vlen; ++i) { // get left counts
191                                         if (f->seq[i]) {
192                                                 int c = f->phase? 2 - f->seq[i] : f->seq[i] - 1;
193                                                 ++sum[c == path[f->vpos + i]? 0 : 1];
194                                         }
195                                         left[i] = sum[1]<<16 | sum[0];
196                                 }
197                                 for (i = f->vlen - 1, sum[0] = sum[1] = 0; i >= 0; --i) { // get right counts
198                                         if (f->seq[i]) {
199                                                 int c = f->phase? 2 - f->seq[i] : f->seq[i] - 1;
200                                                 ++sum[c == path[f->vpos + i]? 0 : 1];
201                                         }
202                                         rght[i] = sum[1]<<16 | sum[0];
203                                 }
204                                 // find the best flip point
205                                 for (i = m = 0, mi = -1, md = -1; i < f->vlen - 1; ++i) {
206                                         int a[2];
207                                         a[0] = (left[i]&0xffff) + (rght[i+1]>>16&0xffff) - (rght[i+1]&0xffff) * FLIP_PENALTY;
208                                         a[1] = (left[i]>>16&0xffff) + (rght[i+1]&0xffff) - (rght[i+1]>>16&0xffff) * FLIP_PENALTY;
209                                         if (a[0] > a[1]) {
210                                                 if (a[0] > m) m = a[0], md = 0, mi = i;
211                                         } else {
212                                                 if (a[1] > m) m = a[1], md = 1, mi = i;
213                                         }
214                                 }
215                                 if (m - c[0] >= FLIP_THRES && m - c[1] >= FLIP_THRES) { // then flip
216                                         f->flip = 1;
217                                         if (md == 0) { // flip the tail
218                                                 for (i = mi + 1; i < f->vlen; ++i)
219                                                         if (f->seq[i] == 1) f->seq[i] = 2;
220                                                         else if (f->seq[i] == 2) f->seq[i] = 1;
221                                         } else { // flip the head
222                                                 for (i = 0; i <= mi; ++i)
223                                                         if (f->seq[i] == 1) f->seq[i] = 2;
224                                                         else if (f->seq[i] == 2) f->seq[i] = 1;
225                                         }
226                                 }
227                         }
228                         // update pcnt[]
229                         if (!f->single) {
230                                 for (i = 0; i < f->vlen; ++i) {
231                                         int c;
232                                         if (f->seq[i] == 0) continue;
233                                         c = f->phase? 2 - f->seq[i] : f->seq[i] - 1;
234                                         if (c == path[f->vpos + i]) {
235                                                 if (f->phase == 0) ++pcnt[f->vpos + i];
236                                                 else pcnt[f->vpos + i] += 1ull<<32;
237                                         } else {
238                                                 if (f->phase == 0) pcnt[f->vpos + i] += 1<<16;
239                                                 else pcnt[f->vpos + i] += 1ull<<48;
240                                         }
241                                 }
242                         }
243                 }
244         }
245         free(left); free(rght);
246         return pcnt;
247 }
248
249 static uint64_t *genmask(int vpos, const uint64_t *pcnt, int *_n)
250 {
251         int i, max = 0, max_i = -1, m = 0, n = 0, beg = 0, score = 0;
252         uint64_t *list = 0;
253         for (i = 0; i < vpos; ++i) {
254                 uint64_t x = pcnt[i];
255                 int c[4], pre = score, s;
256                 c[0] = x&0xffff; c[1] = x>>16&0xffff; c[2] = x>>32&0xffff; c[3] = x>>48&0xffff;
257                 s = (c[1] + c[3] == 0)? -(c[0] + c[2]) : (c[1] + c[3] - 1);
258                 if (c[3] > c[2]) s += c[3] - c[2];
259                 if (c[1] > c[0]) s += c[1] - c[0];
260                 score += s;
261                 if (score < 0) score = 0;
262                 if (pre == 0 && score > 0) beg = i; // change from zero to non-zero
263                 if ((i == vpos - 1 || score == 0) && max >= MASK_THRES) {
264                         if (n == m) {
265                                 m = m? m<<1 : 4;
266                                 list = realloc(list, m * 8);
267                         }
268                         list[n++] = (uint64_t)beg<<32 | max_i;
269                         i = max_i; // reset i to max_i
270                         score = 0;
271                 } else if (score > max) max = score, max_i = i;
272                 if (score == 0) max = 0;
273         }
274         *_n = n;
275         return list;
276 }
277
278 // trim heading and tailing ambiguous bases; mark deleted and remove sequence
279 static int clean_seqs(int vpos, nseq_t *hash)
280 {
281         khint_t k;
282         int ret = 0;
283         for (k = 0; k < kh_end(hash); ++k) {
284                 if (kh_exist(hash, k)) {
285                         frag_t *f = &kh_val(hash, k);
286                         int beg, end, i;
287                         if (f->vpos >= vpos) {
288                                 ret = 1;
289                                 continue;
290                         }
291                         for (i = 0; i < f->vlen; ++i)
292                                 if (f->seq[i] != 0) break;
293                         beg = i;
294                         for (i = f->vlen - 1; i >= 0; --i)
295                                 if (f->seq[i] != 0) break;
296                         end = i + 1;
297                         if (end - beg <= 0) kh_del(64, hash, k);
298                         else {
299                                 if (beg != 0) memmove(f->seq, f->seq + beg, end - beg);
300                                 f->vpos += beg; f->vlen = end - beg;
301                                 f->single = f->vlen == 1? 1 : 0;
302                         }
303                 }
304         }
305         return ret;
306 }
307
308 static void dump_aln(phaseg_t *g, int min_pos, const nseq_t *hash)
309 {
310         int i, is_flip;
311         is_flip = (drand48() < 0.5);
312         for (i = 0; i < g->n; ++i) {
313                 int end, which;
314                 uint64_t key;
315                 khint_t k;
316                 bam1_t *b = g->b[i];
317                 key = X31_hash_string(bam1_qname(b));
318                 end = bam_calend(&b->core, bam1_cigar(b));
319                 if (end > min_pos) break;
320                 k = kh_get(64, hash, key);
321                 if (k == kh_end(hash)) which = 3;
322                 else {
323                         frag_t *f = &kh_val(hash, k);
324                         if (f->phased && f->flip) which = 2;
325                         else if (f->phased == 0) which = 2;
326                         else { // phased and not flipped
327                                 char c = 'Y';
328                                 which = f->phase;
329                                 bam_aux_append(b, "ZP", 'A', 1, (uint8_t*)&c);
330                         }
331                         if (which < 2 && is_flip) which = 1 - which; // increase the randomness
332                 }
333                 if (which == 3) which = (drand48() < 0.5);
334                 bam_write1(g->out[which], b);
335                 bam_destroy1(b);
336                 g->b[i] = 0;
337         }
338         memmove(g->b, g->b + i, (g->n - i) * sizeof(void*));
339         g->n -= i;
340 }
341
342 static int phase(phaseg_t *g, const char *chr, int vpos, uint64_t *cns, nseq_t *hash)
343 {
344         int i, j, n_seqs = kh_size(hash), n_masked = 0, min_pos;
345         khint_t k;
346         frag_t **seqs;
347         int8_t *path, *sitemask;
348         uint64_t *pcnt, *regmask;
349
350         if (vpos == 0) return 0;
351         i = clean_seqs(vpos, hash); // i is true if hash has an element with its vpos >= vpos
352         min_pos = i? cns[vpos]>>32 : 0x7fffffff;
353         if (vpos == 1) {
354                 printf("PS\t%s\t%d\t%d\n", chr, (int)(cns[0]>>32) + 1, (int)(cns[0]>>32) + 1);
355                 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,
356                         "ACGTX"[cns[0]&3], "ACGTX"[cns[0]>>16&3], g->vpos_shift + 1);
357                 for (k = 0; k < kh_end(hash); ++k) {
358                         if (kh_exist(hash, k)) {
359                                 frag_t *f = &kh_val(hash, k);
360                                 if (f->vpos) continue;
361                                 f->flip = 0;
362                                 if (f->seq[0] == 0) f->phased = 0;
363                                 else f->phased = 1, f->phase = f->seq[0] - 1;
364                         }
365                 }
366                 dump_aln(g, min_pos, hash);
367                 ++g->vpos_shift;
368                 return 1;
369         }
370         { // phase
371                 int **cnt;
372                 uint64_t *mask;
373                 printf("PS\t%s\t%d\t%d\n", chr, (int)(cns[0]>>32) + 1, (int)(cns[vpos-1]>>32) + 1);
374                 sitemask = calloc(vpos, 1);
375                 cnt = count_all(g->k, vpos, hash);
376                 path = dynaprog(g->k, vpos, cnt);
377                 for (i = 0; i < vpos; ++i) free(cnt[i]);
378                 free(cnt);
379                 pcnt = fragphase(vpos, path, hash, 0); // do not fix chimeras when masking
380                 mask = genmask(vpos, pcnt, &n_masked);
381                 regmask = calloc(n_masked, 8);
382                 for (i = 0; i < n_masked; ++i) {
383                         regmask[i] = cns[mask[i]>>32]>>32<<32 | cns[(uint32_t)mask[i]]>>32;
384                         for (j = mask[i]>>32; j <= (int32_t)mask[i]; ++j)
385                                 sitemask[j] = 1;
386                 }
387                 free(mask);
388                 if (g->flag & FLAG_FIX_CHIMERA) {
389                         free(pcnt);
390                         pcnt = fragphase(vpos, path, hash, 1);
391                 }
392         }
393         for (i = 0; i < n_masked; ++i)
394                 printf("FL\t%s\t%d\t%d\n", chr, (int)(regmask[i]>>32) + 1, (int)regmask[i] + 1);
395         for (i = 0; i < vpos; ++i) {
396                 uint64_t x = pcnt[i];
397                 int8_t c[2];
398                 c[0] = (cns[i]&0xffff)>>2 == 0? 4 : (cns[i]&3);
399                 c[1] = (cns[i]>>16&0xffff)>>2 == 0? 4 : (cns[i]>>16&3);
400                 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]]],
401                         i + g->vpos_shift + 1, (int)(x&0xffff), (int)(x>>16&0xffff), (int)(x>>32&0xffff), (int)(x>>48&0xffff));
402         }
403         free(path); free(pcnt); free(regmask); free(sitemask);
404         seqs = calloc(n_seqs, sizeof(void*));
405         for (k = 0, i = 0; k < kh_end(hash); ++k) 
406                 if (kh_exist(hash, k) && kh_val(hash, k).vpos < vpos && !kh_val(hash, k).single)
407                         seqs[i++] = &kh_val(hash, k);
408         n_seqs = i;
409         ks_introsort_rseq(n_seqs, seqs);
410         for (i = 0; i < n_seqs; ++i) {
411                 frag_t *f = seqs[i];
412                 printf("EV\t0\t%s\t%d\t40\t%dM\t*\t0\t0\t", chr, f->vpos + 1 + g->vpos_shift, f->vlen);
413                 for (j = 0; j < f->vlen; ++j) {
414                         uint32_t c = cns[f->vpos + j];
415                         if (f->seq[j] == 0) putchar('N');
416                         else putchar("ACGT"[f->seq[j] == 1? (c&3) : (c>>16&3)]);
417                 }
418                 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);
419         }
420         free(seqs);
421         printf("//\n");
422         fflush(stdout);
423         g->vpos_shift += vpos;
424         dump_aln(g, min_pos, hash);
425         return vpos;
426 }
427
428 static void update_vpos(int vpos, nseq_t *hash)
429 {
430         khint_t k;
431         for (k = 0; k < kh_end(hash); ++k) {
432                 if (kh_exist(hash, k)) {
433                         frag_t *f = &kh_val(hash, k);
434                         if (f->vpos < vpos) kh_del(64, hash, k); // TODO: if frag_t::seq is allocated dynamically, free it
435                         else f->vpos -= vpos;
436                 }
437         }
438 }
439
440 static nseq_t *shrink_hash(nseq_t *hash) // TODO: to implement
441 {
442         return hash;
443 }
444
445 static int readaln(void *data, bam1_t *b)
446 {
447         phaseg_t *g = (phaseg_t*)data;
448         int ret;
449         ret = bam_read1(g->fp, b);
450         if (ret < 0) return ret;
451         if (!(b->core.flag & (BAM_FUNMAP|BAM_FSECONDARY|BAM_FQCFAIL|BAM_FDUP)) && g->pre) {
452                 if (g->n == g->m) {
453                         g->m = g->m? g->m<<1 : 16;
454                         g->b = realloc(g->b, g->m * sizeof(void*));
455                 }
456                 g->b[g->n++] = bam_dup1(b);
457         }
458         return ret;
459 }
460
461 static khash_t(set64) *loadpos(const char *fn, bam_header_t *h)
462 {
463         gzFile fp;
464         kstream_t *ks;
465         int ret, dret;
466         kstring_t *str;
467         khash_t(set64) *hash;
468
469         hash = kh_init(set64);
470         str = calloc(1, sizeof(kstring_t));
471         fp = strcmp(fn, "-")? gzopen(fn, "r") : gzdopen(fileno(stdin), "r");
472         ks = ks_init(fp);
473         while (ks_getuntil(ks, 0, str, &dret) >= 0) {
474                 int tid = bam_get_tid(h, str->s);
475                 if (tid >= 0 && dret != '\n') {
476                         if (ks_getuntil(ks, 0, str, &dret) >= 0) {
477                                 uint64_t x = (uint64_t)tid<<32 | (atoi(str->s) - 1);
478                                 kh_put(set64, hash, x, &ret);
479                         } else break;
480                 }
481                 if (dret != '\n') while ((dret = ks_getc(ks)) > 0 && dret != '\n');
482                 if (dret < 0) break;
483         }
484         ks_destroy(ks);
485         gzclose(fp);
486         free(str->s); free(str);
487         return hash;
488 }
489
490 static int gl2cns(float q[16])
491 {
492         int i, j, min_ij;
493         float min, min2;
494         min = min2 = 1e30; min_ij = -1;
495         for (i = 0; i < 4; ++i) {
496                 for (j = i; j < 4; ++j) {
497                         if (q[i<<2|j] < min) min_ij = i<<2|j, min2 = min, min = q[i<<2|j];
498                         else if (q[i<<2|j] < min2) min2 = q[i<<2|j];
499                 }
500         }
501         return (min_ij>>2&3) == (min_ij&3)? 0 : 1<<18 | (min_ij>>2&3)<<16 | (min_ij&3) | (int)(min2 - min + .499) << 2;
502 }
503
504 int main_phase(int argc, char *argv[])
505 {
506         extern void bam_init_header_hash(bam_header_t *header);
507         int c, tid, pos, vpos = 0, n, lasttid = -1, max_vpos = 0;
508         const bam_pileup1_t *plp;
509         bam_plp_t iter;
510         bam_header_t *h;
511         nseq_t *seqs;
512         uint64_t *cns = 0;
513         phaseg_t g;
514         char *fn_list = 0;
515         khash_t(set64) *set = 0;
516         errmod_t *em;
517         uint16_t *bases;
518
519         memset(&g, 0, sizeof(phaseg_t));
520         g.flag = FLAG_FIX_CHIMERA;
521         g.min_varLOD = 37; g.k = 13; g.min_baseQ = 13; g.max_depth = 256;
522         while ((c = getopt(argc, argv, "Q:eFq:k:b:l:D:")) >= 0) {
523                 switch (c) {
524                         case 'D': g.max_depth = atoi(optarg); break;
525                         case 'q': g.min_varLOD = atoi(optarg); break;
526                         case 'Q': g.min_baseQ = atoi(optarg); break;
527                         case 'k': g.k = atoi(optarg); break;
528                         case 'F': g.flag &= ~FLAG_FIX_CHIMERA; break;
529                         case 'e': g.flag |= FLAG_LIST_EXCL; break;
530                         case 'b': g.pre = strdup(optarg); break;
531                         case 'l': fn_list = strdup(optarg); break;
532                 }
533         }
534         if (argc == optind) {
535                 fprintf(stderr, "\n");
536                 fprintf(stderr, "Usage:   samtools phase [options] <in.bam>\n\n");
537                 fprintf(stderr, "Options: -k INT    block length [%d]\n", g.k);
538                 fprintf(stderr, "         -b STR    prefix of BAMs to output [null]\n");
539                 fprintf(stderr, "         -q INT    min het phred-LOD [%d]\n", g.min_varLOD);
540                 fprintf(stderr, "         -Q INT    min base quality in het calling [%d]\n", g.min_baseQ);
541                 fprintf(stderr, "         -D INT    max read depth [%d]\n", g.max_depth);
542 //              fprintf(stderr, "         -l FILE   list of sites to phase [null]\n");
543                 fprintf(stderr, "         -F        do not attempt to fix chimeras\n");
544 //              fprintf(stderr, "         -e        do not discover SNPs (effective with -l)\n");
545                 fprintf(stderr, "\n");
546                 return 1;
547         }
548         g.fp = strcmp(argv[optind], "-")? bam_open(argv[optind], "r") : bam_dopen(fileno(stdin), "r");
549         h = bam_header_read(g.fp);
550         if (fn_list) { // read the list of sites to phase
551                 bam_init_header_hash(h);
552                 set = loadpos(fn_list, h);
553                 free(fn_list);
554         } else g.flag &= ~FLAG_LIST_EXCL;
555         if (g.pre) { // open BAMs to write
556                 char *s = malloc(strlen(g.pre) + 20);
557                 strcpy(s, g.pre); strcat(s, ".0.bam"); g.out[0] = bam_open(s, "w");
558                 strcpy(s, g.pre); strcat(s, ".1.bam"); g.out[1] = bam_open(s, "w");
559                 strcpy(s, g.pre); strcat(s, ".chimera.bam"); g.out[2] = bam_open(s, "w");
560                 for (c = 0; c <= 2; ++c) bam_header_write(g.out[c], h);
561                 free(s);
562         }
563
564         iter = bam_plp_init(readaln, &g);
565         g.vpos_shift = 0;
566         seqs = kh_init(64);
567         em = errmod_init(1. - 0.83);
568         bases = calloc(g.max_depth, 2);
569         printf("CC\n");
570         printf("CC\tDescriptions:\nCC\n");
571         printf("CC\t  CC      comments\n");
572         printf("CC\t  PS      start of a phase set\n");
573         printf("CC\t  FL      filtered region\n");
574         printf("CC\t  M[012]  markers; 0 for singletons, 1 for phased and 2 for filtered\n");
575         printf("CC\t  EV      supporting reads; SAM format\n");
576         printf("CC\t  //      end of a phase set\nCC\n");
577         printf("CC\tFormats of PS, FL and M[012] lines (1-based coordinates):\nCC\n");
578         printf("CC\t  PS  chr  phaseSetStart  phaseSetEnd\n");
579         printf("CC\t  FL  chr  filterStart    filterEnd\n");
580         printf("CC\t  M?  chr  PS  pos  allele0  allele1  hetIndex  #supports0  #errors0  #supp1  #err1\n");
581         printf("CC\nCC\n");
582         fflush(stdout);
583         while ((plp = bam_plp_auto(iter, &tid, &pos, &n)) != 0) {
584                 int i, k, c, tmp, dophase = 1, in_set = 0;
585                 float q[16];
586                 if (tid < 0) break;
587                 if (tid != lasttid) { // change of chromosome
588                         g.vpos_shift = 0;
589                         if (lasttid >= 0) {
590                                 seqs = shrink_hash(seqs);
591                                 phase(&g, h->target_name[lasttid], vpos, cns, seqs);
592                                 update_vpos(0x7fffffff, seqs);
593                         }
594                         lasttid = tid;
595                         vpos = 0;
596                 }
597                 if (set && kh_get(set64, set, (uint64_t)tid<<32 | pos) != kh_end(set)) in_set = 1;
598                 if (n > g.max_depth) continue; // do not proceed if the depth is too high
599                 // fill the bases array and check if there is a variant
600                 for (i = k = 0; i < n; ++i) {
601                         const bam_pileup1_t *p = plp + i;
602                         uint8_t *seq;
603                         int q, baseQ, b;
604                         if (p->is_del || p->is_refskip) continue;
605                         baseQ = bam1_qual(p->b)[p->qpos];
606                         if (baseQ < g.min_baseQ) continue;
607                         seq = bam1_seq(p->b);
608                         b = bam_nt16_nt4_table[bam1_seqi(seq, p->qpos)];
609                         if (b > 3) continue;
610                         q = baseQ < p->b->core.qual? baseQ : p->b->core.qual;
611                         if (q < 4) q = 4;
612                         if (q > 63) q = 63;
613                         bases[k++] = q<<5 | (int)bam1_strand(p->b)<<4 | b;
614                 }
615                 if (k == 0) continue;
616                 errmod_cal(em, k, 4, bases, q); // compute genotype likelihood
617                 c = gl2cns(q); // get the consensus
618                 // tell if to proceed
619                 if (set && (g.flag&FLAG_LIST_EXCL) && !in_set) continue; // not in the list
620                 if (!in_set && (c&0xffff)>>2 < g.min_varLOD) continue; // not a variant
621                 // add the variant
622                 if (vpos == max_vpos) {
623                         max_vpos = max_vpos? max_vpos<<1 : 128;
624                         cns = realloc(cns, max_vpos * 8);
625                 }
626                 cns[vpos] = (uint64_t)pos<<32 | c;
627                 for (i = 0; i < n; ++i) {
628                         const bam_pileup1_t *p = plp + i;
629                         uint64_t key;
630                         khint_t k;
631                         uint8_t *seq = bam1_seq(p->b);
632                         frag_t *f;
633                         if (p->is_del || p->is_refskip) continue;
634                         if (p->b->core.qual == 0) continue;
635                         // get the base code
636                         c = nt16_nt4_table[(int)bam1_seqi(seq, p->qpos)];
637                         if (c == (cns[vpos]&3)) c = 1;
638                         else if (c == (cns[vpos]>>16&3)) c = 2;
639                         else c = 0;
640                         // write to seqs
641                         key = X31_hash_string(bam1_qname(p->b));
642                         k = kh_put(64, seqs, key, &tmp);
643                         f = &kh_val(seqs, k);
644                         if (tmp == 0) { // present in the hash table
645                                 if (vpos - f->vpos + 1 < MAX_VARS) {
646                                         f->vlen = vpos - f->vpos + 1;
647                                         f->seq[f->vlen-1] = c;
648                                         f->end = bam_calend(&p->b->core, bam1_cigar(p->b));
649                                 }
650                                 dophase = 0;
651                         } else { // absent
652                                 memset(f->seq, 0, MAX_VARS);
653                                 f->beg = p->b->core.pos;
654                                 f->end = bam_calend(&p->b->core, bam1_cigar(p->b));
655                                 f->vpos = vpos, f->vlen = 1, f->seq[0] = c, f->single = f->phased = f->flip = 0;
656                         }
657                 }
658                 if (dophase) {
659                         seqs = shrink_hash(seqs);
660                         phase(&g, h->target_name[tid], vpos, cns, seqs);
661                         update_vpos(vpos, seqs);
662                         cns[0] = cns[vpos];
663                         vpos = 0;
664                 }
665                 ++vpos;
666         }
667         if (tid >= 0) phase(&g, h->target_name[tid], vpos, cns, seqs);
668         bam_header_destroy(h);
669         bam_plp_destroy(iter);
670         bam_close(g.fp);
671         kh_destroy(64, seqs);
672         kh_destroy(set64, set);
673         free(cns);
674         errmod_destroy(em);
675         free(bases);
676         if (g.pre) {
677                 for (c = 0; c <= 2; ++c) bam_close(g.out[c]);
678                 free(g.pre); free(g.b);
679         }
680         return 0;
681 }