]> git.donarmstrong.com Git - samtools.git/blob - bam_plcmd.c
Generate binary VCF
[samtools.git] / bam_plcmd.c
1 #include <math.h>
2 #include <stdio.h>
3 #include <unistd.h>
4 #include <ctype.h>
5 #include "sam.h"
6 #include "faidx.h"
7 #include "bam_maqcns.h"
8 #include "bam_mcns.h"
9 #include "bam2bcf.h"
10 #include "khash.h"
11 #include "glf.h"
12 #include "kstring.h"
13
14 typedef int *indel_list_t;
15 KHASH_MAP_INIT_INT64(64, indel_list_t)
16
17 #define BAM_PLF_SIMPLE     0x01
18 #define BAM_PLF_CNS        0x02
19 #define BAM_PLF_INDEL_ONLY 0x04
20 #define BAM_PLF_GLF        0x08
21 #define BAM_PLF_VAR_ONLY   0x10
22 #define BAM_PLF_2ND        0x20
23 #define BAM_PLF_RANBASE    0x40
24 #define BAM_PLF_1STBASE    0x80
25 #define BAM_PLF_ALLBASE    0x100
26 #define BAM_PLF_READPOS    0x200
27
28 typedef struct {
29         bam_header_t *h;
30         bam_maqcns_t *c;
31         bam_maqindel_opt_t *ido;
32         faidx_t *fai;
33         khash_t(64) *hash;
34         uint32_t format;
35         int tid, len, last_pos;
36         int mask;
37     int max_depth;  // for indel calling, ignore reads with the depth too high. 0 for unlimited
38         char *ref;
39         glfFile fp_glf; // for glf output only
40 } pu_data_t;
41
42 char **__bam_get_lines(const char *fn, int *_n);
43 void bam_init_header_hash(bam_header_t *header);
44 int32_t bam_get_tid(const bam_header_t *header, const char *seq_name);
45
46 static khash_t(64) *load_pos(const char *fn, bam_header_t *h)
47 {
48         char **list;
49         int i, j, n, *fields, max_fields;
50         khash_t(64) *hash;
51         bam_init_header_hash(h);
52         list = __bam_get_lines(fn, &n);
53         hash = kh_init(64);
54         max_fields = 0; fields = 0;
55         for (i = 0; i < n; ++i) {
56                 char *str = list[i];
57                 int chr, n_fields, ret;
58                 khint_t k;
59                 uint64_t x;
60                 n_fields = ksplit_core(str, 0, &max_fields, &fields);
61                 if (n_fields < 2) continue;
62                 chr = bam_get_tid(h, str + fields[0]);
63                 if (chr < 0) {
64                         fprintf(stderr, "[load_pos] unknown reference sequence name: %s\n", str + fields[0]);
65                         continue;
66                 }
67                 x = (uint64_t)chr << 32 | (atoi(str + fields[1]) - 1);
68                 k = kh_put(64, hash, x, &ret);
69                 if (ret == 0) {
70                         fprintf(stderr, "[load_pos] position %s:%s has been loaded.\n", str+fields[0], str+fields[1]);
71                         continue;
72                 }
73                 kh_val(hash, k) = 0;
74                 if (n_fields > 2) {
75                         // count
76                         for (j = 2; j < n_fields; ++j) {
77                                 char *s = str + fields[j];
78                                 if ((*s != '+' && *s != '-') || !isdigit(s[1])) break;
79                         }
80                         if (j > 2) { // update kh_val()
81                                 int *q, y, z;
82                                 q = kh_val(hash, k) = (int*)calloc(j - 1, sizeof(int));
83                                 q[0] = j - 2; z = j; y = 1;
84                                 for (j = 2; j < z; ++j)
85                                         q[y++] = atoi(str + fields[j]);
86                         }
87                 }
88                 free(str);
89         }
90         free(list); free(fields);
91         return hash;
92 }
93
94 // an analogy to pileup_func() below
95 static int glt3_func(uint32_t tid, uint32_t pos, int n, const bam_pileup1_t *pu, void *data)
96 {
97         pu_data_t *d = (pu_data_t*)data;
98         bam_maqindel_ret_t *r = 0;
99         int rb, *proposed_indels = 0;
100         glf1_t *g;
101         glf3_t *g3;
102
103         if (d->fai == 0) {
104                 fprintf(stderr, "[glt3_func] reference sequence is required for generating GLT. Abort!\n");
105                 exit(1);
106         }
107         if (d->hash) { // only output a list of sites
108                 khint_t k = kh_get(64, d->hash, (uint64_t)tid<<32|pos);
109                 if (k == kh_end(d->hash)) return 0;
110                 proposed_indels = kh_val(d->hash, k);
111         }
112         g3 = glf3_init1();
113         if (d->fai && (int)tid != d->tid) {
114                 if (d->ref) { // then write the end mark
115                         g3->rtype = GLF3_RTYPE_END;
116                         glf3_write1(d->fp_glf, g3);
117                 }
118                 glf3_ref_write(d->fp_glf, d->h->target_name[tid], d->h->target_len[tid]); // write reference
119                 free(d->ref);
120                 d->ref = fai_fetch(d->fai, d->h->target_name[tid], &d->len);
121                 d->tid = tid;
122                 d->last_pos = 0;
123         }
124         rb = (d->ref && (int)pos < d->len)? d->ref[pos] : 'N';
125         g = bam_maqcns_glfgen(n, pu, bam_nt16_table[rb], d->c);
126         memcpy(g3, g, sizeof(glf1_t));
127         g3->rtype = GLF3_RTYPE_SUB;
128         g3->offset = pos - d->last_pos;
129         d->last_pos = pos;
130         glf3_write1(d->fp_glf, g3);
131     if (pos < d->len) {
132         int m = (!d->max_depth || d->max_depth>n) ? n : d->max_depth;
133                 if (proposed_indels)
134                         r = bam_maqindel(m, pos, d->ido, pu, d->ref, proposed_indels[0], proposed_indels+1);
135                 else r = bam_maqindel(m, pos, d->ido, pu, d->ref, 0, 0);
136         }
137         if (r) { // then write indel line
138                 int het = 3 * n, min;
139                 min = het;
140                 if (min > r->gl[0]) min = r->gl[0];
141                 if (min > r->gl[1]) min = r->gl[1];
142                 g3->ref_base = 0;
143                 g3->rtype = GLF3_RTYPE_INDEL;
144                 memset(g3->lk, 0, 10);
145                 g3->lk[0] = r->gl[0] - min < 255? r->gl[0] - min : 255;
146                 g3->lk[1] = r->gl[1] - min < 255? r->gl[1] - min : 255;
147                 g3->lk[2] = het - min < 255? het - min : 255;
148                 g3->offset = 0;
149                 g3->indel_len[0] = r->indel1;
150                 g3->indel_len[1] = r->indel2;
151                 g3->min_lk = min < 255? min : 255;
152                 g3->max_len = (abs(r->indel1) > abs(r->indel2)? abs(r->indel1) : abs(r->indel2)) + 1;
153                 g3->indel_seq[0] = strdup(r->s[0]+1);
154                 g3->indel_seq[1] = strdup(r->s[1]+1);
155                 glf3_write1(d->fp_glf, g3);
156                 bam_maqindel_ret_destroy(r);
157         }
158         free(g);
159         glf3_destroy1(g3);
160         return 0;
161 }
162
163 static void pileup_seq(const bam_pileup1_t *p, int pos, int ref_len, const char *ref)
164 {
165         if (p->is_head) printf("^%c", p->b->core.qual > 93? 126 : p->b->core.qual + 33);
166         if (!p->is_del) {
167                 int j, rb, c = bam_nt16_rev_table[bam1_seqi(bam1_seq(p->b), p->qpos)];
168                 rb = (ref && pos < ref_len)? ref[pos] : 'N';
169                 if (c == '=' || toupper(c) == toupper(rb)) c = bam1_strand(p->b)? ',' : '.';
170                 else c = bam1_strand(p->b)? tolower(c) : toupper(c);
171                 putchar(c);
172                 if (p->indel > 0) {
173                         printf("+%d", p->indel);
174                         for (j = 1; j <= p->indel; ++j) {
175                                 c = bam_nt16_rev_table[bam1_seqi(bam1_seq(p->b), p->qpos + j)];
176                                 putchar(bam1_strand(p->b)? tolower(c) : toupper(c));
177                         }
178                 } else if (p->indel < 0) {
179                         printf("%d", p->indel);
180                         for (j = 1; j <= -p->indel; ++j) {
181                                 c = (ref && (int)pos+j < ref_len)? ref[pos+j] : 'N';
182                                 putchar(bam1_strand(p->b)? tolower(c) : toupper(c));
183                         }
184                 }
185         } else putchar('*');
186         if (p->is_tail) putchar('$');
187 }
188
189 static int pileup_func(uint32_t tid, uint32_t pos, int n, const bam_pileup1_t *pu, void *data)
190 {
191         pu_data_t *d = (pu_data_t*)data;
192         bam_maqindel_ret_t *r = 0;
193         int i, rb, rms_mapq = -1, *proposed_indels = 0;
194         uint64_t rms_aux;
195         uint32_t cns = 0;
196
197         // if GLF is required, suppress -c completely
198         if (d->format & BAM_PLF_GLF) return glt3_func(tid, pos, n, pu, data);
199         // if d->hash is initialized, only output the sites in the hash table
200         if (d->hash) {
201                 khint_t k = kh_get(64, d->hash, (uint64_t)tid<<32|pos);
202                 if (k == kh_end(d->hash)) return 0;
203                 proposed_indels = kh_val(d->hash, k);
204         }
205         // update d->ref if necessary
206         if (d->fai && (int)tid != d->tid) {
207                 free(d->ref);
208                 d->ref = faidx_fetch_seq(d->fai, d->h->target_name[tid], 0, 0x7fffffff, &d->len);
209                 d->tid = tid;
210         }
211         rb = (d->ref && (int)pos < d->len)? d->ref[pos] : 'N';
212         // when the indel-only mode is asked for, return if no reads mapped with indels
213         if (d->format & BAM_PLF_INDEL_ONLY) {
214                 for (i = 0; i < n; ++i)
215                         if (pu[i].indel != 0) break;
216                 if (i == n) return 0;
217         }
218         // call the consensus and indel
219         if (d->format & BAM_PLF_CNS) { // call consensus
220                 if (d->format & (BAM_PLF_RANBASE|BAM_PLF_1STBASE)) { // use a random base or the 1st base as the consensus call
221                         const bam_pileup1_t *p = (d->format & BAM_PLF_1STBASE)? pu : pu + (int)(drand48() * n);
222                         int q = bam1_qual(p->b)[p->qpos];
223                         int mapQ = p->b->core.qual < d->c->cap_mapQ? p->b->core.qual : d->c->cap_mapQ;
224                         uint32_t b = bam1_seqi(bam1_seq(p->b), p->qpos);
225                         cns = b<<28 | 0xf<<24 | mapQ<<16 | q<<8;
226                 } else if (d->format & BAM_PLF_ALLBASE) { // collapse all bases
227                         uint64_t rmsQ = 0;
228                         uint32_t b = 0;
229                         for (i = 0; i < n; ++i) {
230                                 const bam_pileup1_t *p = pu + i;
231                                 int q = p->b->core.qual < d->c->cap_mapQ? p->b->core.qual : d->c->cap_mapQ;
232                                 b |= bam1_seqi(bam1_seq(p->b), p->qpos);
233                                 rmsQ += q * q;
234                         }
235                         rmsQ = (uint64_t)(sqrt((double)rmsQ / n) + .499);
236                         cns = b<<28 | 0xf<<24 | rmsQ<<16 | 60<<8;
237                 } else cns = bam_maqcns_call(n, pu, d->c);
238         }
239     if ((d->format & (BAM_PLF_CNS|BAM_PLF_INDEL_ONLY)) && d->ref && pos < d->len) { // call indels
240         int m = (!d->max_depth || d->max_depth>n) ? n : d->max_depth;
241         if (proposed_indels) // the first element gives the size of the array
242             r = bam_maqindel(m, pos, d->ido, pu, d->ref, proposed_indels[0], proposed_indels+1);
243         else r = bam_maqindel(m, pos, d->ido, pu, d->ref, 0, 0);
244         }
245         // when only variant sites are asked for, test if the site is a variant
246         if ((d->format & BAM_PLF_CNS) && (d->format & BAM_PLF_VAR_ONLY)) {
247                 if (!(bam_nt16_table[rb] != 15 && cns>>28 != bam_nt16_table[rb])) { // not a SNP
248                         if (!(r && (r->gt == 2 || strcmp(r->s[r->gt], "*")))) { // not an indel
249                                 if (r) bam_maqindel_ret_destroy(r);
250                                 return 0;
251                         }
252                 }
253         }
254         // print the first 3 columns
255         printf("%s\t%d\t%c\t", d->h->target_name[tid], pos + 1, rb);
256         // print consensus information if required
257         if (d->format & BAM_PLF_CNS) {
258                 int ref_q, rb4 = bam_nt16_table[rb];
259                 ref_q = 0;
260                 if (rb4 != 15 && cns>>28 != 15 && cns>>28 != rb4) { // a SNP
261                         ref_q = ((cns>>24&0xf) == rb4)? cns>>8&0xff : (cns>>8&0xff) + (cns&0xff);
262                         if (ref_q > 255) ref_q = 255;
263                 }
264                 rms_mapq = cns>>16&0xff;
265                 printf("%c\t%d\t%d\t%d\t", bam_nt16_rev_table[cns>>28], cns>>8&0xff, ref_q, rms_mapq);
266         }
267         // print pileup sequences
268         printf("%d\t", n);
269         rms_aux = 0; // we need to recalculate rms_mapq when -c is not flagged on the command line
270         for (i = 0; i < n; ++i) {
271                 const bam_pileup1_t *p = pu + i;
272                 int tmp = p->b->core.qual < d->c->cap_mapQ? p->b->core.qual : d->c->cap_mapQ;
273                 rms_aux += tmp * tmp;
274                 pileup_seq(p, pos, d->len, d->ref);
275         }
276         // finalize rms_mapq
277         rms_aux = (uint64_t)(sqrt((double)rms_aux / n) + .499);
278         if (rms_mapq < 0) rms_mapq = rms_aux;
279         putchar('\t');
280         // print quality
281         for (i = 0; i < n; ++i) {
282                 const bam_pileup1_t *p = pu + i;
283                 int c = bam1_qual(p->b)[p->qpos] + 33;
284                 if (c > 126) c = 126;
285                 putchar(c);
286         }
287         if (d->format & BAM_PLF_2ND) { // print 2nd calls and qualities
288                 const unsigned char *q;
289                 putchar('\t');
290                 for (i = 0; i < n; ++i) {
291                         const bam_pileup1_t *p = pu + i;
292                         q = bam_aux_get(p->b, "E2");
293                         putchar(q? q[p->qpos + 1] : 'N');
294                 }
295                 putchar('\t');
296                 for (i = 0; i < n; ++i) {
297                         const bam_pileup1_t *p = pu + i;
298                         q = bam_aux_get(p->b, "U2");
299                         putchar(q? q[p->qpos + 1] : '!');
300                 }
301         }
302         // print mapping quality if -s is flagged on the command line
303         if (d->format & BAM_PLF_SIMPLE) {
304                 putchar('\t');
305                 for (i = 0; i < n; ++i) {
306                         int c = pu[i].b->core.qual + 33;
307                         if (c > 126) c = 126;
308                         putchar(c);
309                 }
310         }
311         // print read position
312         if (d->format & BAM_PLF_READPOS) {
313                 putchar('\t');
314                 for (i = 0; i < n; ++i) {
315                         int x = pu[i].qpos;
316                         int l = pu[i].b->core.l_qseq;
317                         printf("%d,", x < l/2? x+1 : -((l-1)-x+1));
318                 }
319         }
320         putchar('\n');
321         // print the indel line if r has been calculated. This only happens if:
322         // a) -c or -i are flagged, AND b) the reference sequence is available
323         if (r) {
324                 printf("%s\t%d\t*\t", d->h->target_name[tid], pos + 1);
325                 if (r->gt < 2) printf("%s/%s\t", r->s[r->gt], r->s[r->gt]);
326                 else printf("%s/%s\t", r->s[0], r->s[1]);
327                 printf("%d\t%d\t", r->q_cns, r->q_ref);
328                 printf("%d\t%d\t", rms_mapq, n);
329                 printf("%s\t%s\t", r->s[0], r->s[1]);
330                 //printf("%d\t%d\t", r->gl[0], r->gl[1]);
331                 printf("%d\t%d\t%d\t", r->cnt1, r->cnt2, r->cnt_anti);
332                 printf("%d\t%d\n", r->cnt_ref, r->cnt_ambi);
333                 bam_maqindel_ret_destroy(r);
334         }
335         return 0;
336 }
337
338 int bam_pileup(int argc, char *argv[])
339 {
340         int c, is_SAM = 0;
341         char *fn_list = 0, *fn_fa = 0, *fn_pos = 0;
342         pu_data_t *d = (pu_data_t*)calloc(1, sizeof(pu_data_t));
343     d->max_depth = 0;
344         d->tid = -1; d->mask = BAM_DEF_MASK;
345         d->c = bam_maqcns_init();
346         d->c->is_soap = 1; // change the default model
347         d->ido = bam_maqindel_opt_init();
348         while ((c = getopt(argc, argv, "st:f:cT:N:r:l:d:im:gI:G:vM:S2aR:PA")) >= 0) {
349                 switch (c) {
350                 case 'a': d->c->is_soap = 1; break;
351                 case 'A': d->c->is_soap = 0; break;
352                 case 's': d->format |= BAM_PLF_SIMPLE; break;
353                 case 't': fn_list = strdup(optarg); break;
354                 case 'l': fn_pos = strdup(optarg); break;
355                 case 'f': fn_fa = strdup(optarg); break;
356                 case 'T': d->c->theta = atof(optarg); break;
357                 case 'N': d->c->n_hap = atoi(optarg); break;
358                 case 'r': d->c->het_rate = atof(optarg); d->ido->r_snp = d->c->het_rate; break;
359                 case 'M': d->c->cap_mapQ = atoi(optarg); break;
360                 case 'd': d->max_depth = atoi(optarg); break;
361                 case 'c': d->format |= BAM_PLF_CNS; break;
362                 case 'i': d->format |= BAM_PLF_INDEL_ONLY; break;
363                 case 'v': d->format |= BAM_PLF_VAR_ONLY; break;
364                 case 'm': d->mask = strtol(optarg, 0, 0); break;
365                 case 'g': d->format |= BAM_PLF_GLF; break;
366                 case '2': d->format |= BAM_PLF_2ND; break;
367                 case 'P': d->format |= BAM_PLF_READPOS; break;
368                 case 'I': d->ido->q_indel = atoi(optarg); break;
369                 case 'G': d->ido->r_indel = atof(optarg); break;
370                 case 'S': is_SAM = 1; break;
371                 case 'R':
372                         if (strcmp(optarg, "random") == 0) d->format |= BAM_PLF_RANBASE;
373                         else if (strcmp(optarg, "first") == 0) d->format |= BAM_PLF_1STBASE;
374                         else if (strcmp(optarg, "all") == 0) d->format |= BAM_PLF_ALLBASE;
375                         else fprintf(stderr, "[bam_pileup] unrecognized -R\n");
376                         break;
377                 default: fprintf(stderr, "Unrecognizd option '-%c'.\n", c); return 1;
378                 }
379         }
380         if (fn_list) is_SAM = 1;
381         if (optind == argc) {
382                 fprintf(stderr, "\n");
383                 fprintf(stderr, "Usage:  samtools pileup [options] <in.bam>|<in.sam>\n\n");
384                 fprintf(stderr, "Option: -s        simple (yet incomplete) pileup format\n");
385                 fprintf(stderr, "        -S        the input is in SAM\n");
386                 fprintf(stderr, "        -A        use the MAQ model for SNP calling\n");
387                 fprintf(stderr, "        -2        output the 2nd best call and quality\n");
388                 fprintf(stderr, "        -i        only show lines/consensus with indels\n");
389                 fprintf(stderr, "        -m INT    filtering reads with bits in INT [%d]\n", d->mask);
390                 fprintf(stderr, "        -M INT    cap mapping quality at INT [%d]\n", d->c->cap_mapQ);
391         fprintf(stderr, "        -d INT    limit maximum depth for indels [unlimited]\n");
392                 fprintf(stderr, "        -t FILE   list of reference sequences (force -S)\n");
393                 fprintf(stderr, "        -l FILE   list of sites at which pileup is output\n");
394                 fprintf(stderr, "        -f FILE   reference sequence in the FASTA format\n\n");
395                 fprintf(stderr, "        -c        output the SOAPsnp consensus sequence\n");
396                 fprintf(stderr, "        -v        print variants only (for -c)\n");
397                 fprintf(stderr, "        -g        output in the GLFv3 format (suppressing -c/-i/-s)\n");
398                 fprintf(stderr, "        -T FLOAT  theta in maq consensus calling model (for -c/-g) [%f]\n", d->c->theta);
399                 fprintf(stderr, "        -N INT    number of haplotypes in the sample (for -c/-g) [%d]\n", d->c->n_hap);
400                 fprintf(stderr, "        -r FLOAT  prior of a difference between two haplotypes (for -c/-g) [%f]\n", d->c->het_rate);
401                 fprintf(stderr, "        -G FLOAT  prior of an indel between two haplotypes (for -c/-g) [%f]\n", d->ido->r_indel);
402                 fprintf(stderr, "        -I INT    phred prob. of an indel in sequencing/prep. (for -c/-g) [%d]\n", d->ido->q_indel);
403                 fprintf(stderr, "\n");
404                 free(fn_list); free(fn_fa); free(d);
405                 return 1;
406         }
407         if (d->format & (BAM_PLF_RANBASE|BAM_PLF_1STBASE|BAM_PLF_ALLBASE)) d->format |= BAM_PLF_CNS;
408         if (fn_fa) d->fai = fai_load(fn_fa);
409         if (d->format & (BAM_PLF_CNS|BAM_PLF_GLF)) bam_maqcns_prepare(d->c); // consensus calling
410         if (d->format & BAM_PLF_GLF) { // for glf output
411                 glf3_header_t *h;
412                 h = glf3_header_init();
413                 d->fp_glf = bgzf_fdopen(fileno(stdout), "w");
414                 glf3_header_write(d->fp_glf, h);
415                 glf3_header_destroy(h);
416         }
417         if (d->fai == 0 && (d->format & (BAM_PLF_CNS|BAM_PLF_INDEL_ONLY)))
418                 fprintf(stderr, "[bam_pileup] indels will not be called when -f is absent.\n");
419         if (fn_fa && is_SAM && fn_list == 0) fn_list = samfaipath(fn_fa);
420
421         {
422                 samfile_t *fp;
423                 fp = is_SAM? samopen(argv[optind], "r", fn_list) : samopen(argv[optind], "rb", 0);
424                 if (fp == 0 || fp->header == 0) {
425                         fprintf(stderr, "[bam_pileup] fail to read the header: non-exisiting file or wrong format.\n");
426                         return 1;
427                 }
428                 d->h = fp->header;
429                 if (fn_pos) d->hash = load_pos(fn_pos, d->h);
430                 sampileup(fp, d->mask, pileup_func, d);
431                 samclose(fp); // d->h will be destroyed here
432         }
433
434         // free
435         if (d->format & BAM_PLF_GLF) bgzf_close(d->fp_glf);
436         if (fn_pos) { // free the hash table
437                 khint_t k;
438                 for (k = kh_begin(d->hash); k < kh_end(d->hash); ++k)
439                         if (kh_exist(d->hash, k)) free(kh_val(d->hash, k));
440                 kh_destroy(64, d->hash);
441         }
442         free(fn_pos); free(fn_list); free(fn_fa);
443         if (d->fai) fai_destroy(d->fai);
444         bam_maqcns_destroy(d->c);
445         free(d->ido); free(d->ref); free(d);
446         return 0;
447 }
448
449 /***********
450  * mpileup *
451  ***********/
452
453 #define MPLP_VCF   0x1
454 #define MPLP_VAR   0x2
455 #define MPLP_AFALL 0x8
456 #define MPLP_GLF   0x10
457
458 #define MPLP_AFS_BLOCK 0x10000
459
460 typedef struct {
461         int max_mq, min_mq, prior_type, flag;
462         double theta;
463         char *reg, *fn_pos;
464         faidx_t *fai;
465         kh_64_t *hash;
466 } mplp_conf_t;
467
468 typedef struct {
469         bamFile fp;
470         bam_iter_t iter;
471         int min_mq;
472 } mplp_aux_t;
473
474 static int mplp_func(void *data, bam1_t *b)
475 {
476         mplp_aux_t *ma = (mplp_aux_t*)data;
477         int ret;
478         do {
479                 ret = ma->iter? bam_iter_read(ma->fp, ma->iter, b) : bam_read1(ma->fp, b);
480         } while (b->core.qual < ma->min_mq && ret >= 0);
481         return ret;
482 }
483
484 static int mpileup(mplp_conf_t *conf, int n, char **fn)
485 {
486         mplp_aux_t **data;
487         int i, tid, pos, *n_plp, beg0 = 0, end0 = 1u<<29, ref_len, ref_tid;
488         const bam_pileup1_t **plp;
489         bam_mplp_t iter;
490         bam_header_t *h = 0;
491         uint64_t N = 0;
492         char *ref;
493         khash_t(64) *hash = 0;
494
495         mc_aux_t *ma = 0;
496
497         bcf_callaux_t *bca = 0;
498         bcf_callret1_t *bcr = 0;
499         bcf_call_t bc;
500         bcf_t *bp = 0;
501
502         memset(&bc, 0, sizeof(bcf_call_t));
503         data = calloc(n, sizeof(void*));
504         plp = calloc(n, sizeof(void*));
505         n_plp = calloc(n, sizeof(int*));
506
507         // read the header and initialize data
508         for (i = 0; i < n; ++i) {
509                 bam_header_t *h_tmp;
510                 data[i] = calloc(1, sizeof(mplp_aux_t));
511                 data[i]->min_mq = conf->min_mq;
512                 data[i]->fp = bam_open(fn[i], "r");
513                 h_tmp = bam_header_read(data[i]->fp);
514                 if (conf->reg) {
515                         int beg, end;
516                         bam_index_t *idx;
517                         idx = bam_index_load(fn[i]);
518                         if (idx == 0) {
519                                 fprintf(stderr, "[%s] fail to load index for %d-th input.\n", __func__, i+1);
520                                 exit(1);
521                         }
522                         if (bam_parse_region(h_tmp, conf->reg, &tid, &beg, &end) < 0) {
523                                 fprintf(stderr, "[%s] malformatted region or wrong seqname for %d-th input.\n", __func__, i+1);
524                                 exit(1);
525                         }
526                         if (i == 0) beg0 = beg, end0 = end;
527                         data[i]->iter = bam_iter_query(idx, tid, beg, end);
528                         bam_index_destroy(idx);
529                 }
530                 if (i == 0) h = h_tmp;
531                 else {
532                         // FIXME: to check consistency
533                         bam_header_destroy(h_tmp);
534                 }
535         }
536         if (conf->fn_pos) hash = load_pos(conf->fn_pos, h);
537         // write the VCF header
538         if (conf->flag & MPLP_GLF) {
539                 kstring_t s;
540                 s.l = s.m = 0; s.s = 0;
541                 bp = bcf_open("-", "w");
542                 for (i = 0; i < h->n_targets; ++i) {
543                         kputs(h->target_name[i], &s);
544                         kputc('\0', &s);
545                 }
546                 bp->h.l_nm = s.l;
547                 bp->h.name = malloc(s.l);
548                 memcpy(bp->h.name, s.s, s.l);
549                 s.l = 0;
550                 for (i = 0; i < n; ++i) {
551                         const char *p;
552                         if ((p = strstr(fn[i], ".bam")) != 0)
553                                 kputsn(fn[i], p - fn[i], &s);
554                         else kputs(fn[i], &s);
555                         kputc('\0', &s);
556                 }
557                 bp->h.l_smpl = s.l;
558                 bp->h.sname = malloc(s.l);
559                 memcpy(bp->h.sname, s.s, s.l);
560                 bp->h.l_txt = 0;
561                 free(s.s);
562                 bcf_hdr_sync(&bp->h);
563                 bcf_hdr_write(bp);
564         } else if (conf->flag & MPLP_VCF) {
565                 kstring_t s;
566                 s.l = s.m = 0; s.s = 0;
567                 puts("##fileformat=VCFv4.0");
568                 puts("##INFO=<ID=DP,Number=1,Type=Integer,Description=\"Total read depth\">");
569                 puts("##INFO=<ID=AF,Number=1,Type=Float,Description=\"Non-reference allele frequency \\argmax_f P(D|f)\">");
570                 puts("##INFO=<ID=AFE,Number=1,Type=Float,Description=\"Expected non-reference allele frequency\">");
571                 puts("##FILTER=<ID=Q13,Description=\"All min{baseQ,mapQ} below 13\">");
572                 puts("##FILTER=<ID=FPE,Description=\"Floating point error\">");
573                 kputs("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT", &s);
574                 for (i = 0; i < n; ++i) {
575                         const char *p;
576                         kputc('\t', &s);
577                         if ((p = strstr(fn[i], ".bam")) != 0)
578                                 kputsn(fn[i], p - fn[i], &s);
579                         else kputs(fn[i], &s);
580                 }
581                 puts(s.s);
582                 free(s.s);
583         }
584         // mpileup
585         if (conf->flag & MPLP_GLF) {
586                 bca = bcf_call_init(-1.);
587                 bcr = calloc(n, sizeof(bcf_callret1_t));
588         } else if (conf->flag & MPLP_VCF) {
589                 ma = mc_init(n);
590                 mc_init_prior(ma, conf->prior_type, conf->theta);
591         }
592         ref_tid = -1; ref = 0;
593         iter = bam_mplp_init(n, mplp_func, (void**)data);
594         while (bam_mplp_auto(iter, &tid, &pos, n_plp, plp) > 0) {
595                 if (conf->reg && (pos < beg0 || pos >= end0)) continue; // out of the region requested
596                 if (hash) {
597                         khint_t k;
598                         k = kh_get(64, hash, (uint64_t)tid<<32 | pos);
599                         if (k == kh_end(hash)) continue;
600                 }
601                 if (tid != ref_tid) {
602                         free(ref);
603                         if (conf->fai) ref = fai_fetch(conf->fai, h->target_name[tid], &ref_len);
604                         ref_tid = tid;
605                 }
606                 if (conf->flag & MPLP_GLF) {
607                         int _ref0, ref16;
608                         bcf1_t *b = calloc(1, sizeof(bcf1_t));
609                         _ref0 = (ref && pos < ref_len)? ref[pos] : 'N';
610                         ref16 = bam_nt16_table[_ref0];
611                         for (i = 0; i < n; ++i)
612                                 bcf_call_glfgen(n_plp[i], plp[i], ref16, bca, bcr + i);
613                         bcf_call_combine(n, bcr, ref16, &bc);
614                         bcf_call2bcf(tid, pos, &bc, b);
615                         bcf_write(bp, b);
616                         //fprintf(stderr, "%d,%d,%d\n", b->tid, b->pos, b->l_str);
617                         bcf_destroy(b);
618                 } else if (conf->flag & MPLP_VCF) {
619                         mc_rst_t r;
620                         int j, _ref0, depth, rms_q, _ref0b, is_var = 0, qref = 0, level = 2, tot;
621                         uint64_t sqr_sum;
622                         _ref0 = _ref0b = (ref && pos < ref_len)? ref[pos] : 'N';
623                         _ref0 = bam_nt16_nt4_table[bam_nt16_table[_ref0]];
624                         tot = mc_cal(_ref0, n_plp, plp, ma, &r, level);
625                         if (tot) { // has good bases
626                                 double q;
627                                 is_var = (r.p_ref < .5);
628                                 q = is_var? r.p_ref : 1. - r.p_ref;
629                                 if (q < 1e-308) q = 1e-308;
630                                 qref = (int)(-3.434 * log(q) + .499);
631                                 if (qref > 99) qref = 99;
632                         }
633                         if ((conf->flag & MPLP_VAR) && !is_var) continue;
634                         ++N; // number of processed lines
635                         printf("%s\t%d\t.\t%c\t", h->target_name[tid], pos + 1, _ref0b);
636                         if (is_var) {
637                                 putchar("ACGTN"[r.alt]);
638                                 if (r.alt2 >= 0 && r.alt2 < 4) printf(",%c", "ACGT"[r.alt2]);
639                         } else putchar('.');
640                         printf("\t%d\t", qref);
641                         if (!tot) printf("Q13\t");
642                         else if (r.f_exp < 0.) printf("FPE\t");
643                         else printf(".\t");
644                         for (i = depth = 0, sqr_sum = 0; i < n; ++i) {
645                                 depth += n_plp[i];
646                                 for (j = 0; j < n_plp[i]; ++j) {
647                                         int q = plp[i][j].b->core.qual;
648                                         if (q > conf->max_mq) q = conf->max_mq;
649                                         sqr_sum += q * q;
650                                 }
651                         }
652                         rms_q = (int)(sqrt((double)sqr_sum / depth) + .499);
653                         printf("DP=%d;MQ=%d", depth, rms_q);
654                         if (tot) {
655                                 printf(";AF=%.3lf", 1. - r.f_em);
656                                 if (level >= 2) printf(";AFE=%.3lf", 1-r.f_exp);
657                                 if (conf->flag & MPLP_AFALL)
658                                         printf(";AF0=%.3lf;AFN=%.3lf", 1-r.f_naive, 1-r.f_nielsen);
659                         }
660                         printf("\tGT:GQ:DP");
661                         if (tot) {
662                                 for (i = 0; i < n; ++i) {
663                                         int x = mc_call_gt(ma, r.f_exp, i);
664                                         printf("\t%c/%c:%d:%d", "10"[((x&3)==2)], "10"[((x&3)>0)], x>>2, n_plp[i]);
665                                 }
666                         } else for (i = 0; i < n; ++i) printf("\t./.:0:0");
667                         putchar('\n');
668                         if (N % MPLP_AFS_BLOCK == 0) mc_dump_afs(ma);
669                 } else {
670                         printf("%s\t%d\t%c", h->target_name[tid], pos + 1, (ref && pos < ref_len)? ref[pos] : 'N');
671                         for (i = 0; i < n; ++i) {
672                                 int j;
673                                 printf("\t%d\t", n_plp[i]);
674                                 if (n_plp[i] == 0) printf("*\t*");
675                                 else {
676                                         for (j = 0; j < n_plp[i]; ++j)
677                                                 pileup_seq(plp[i] + j, pos, ref_len, ref);
678                                         putchar('\t');
679                                         for (j = 0; j < n_plp[i]; ++j) {
680                                                 const bam_pileup1_t *p = plp[i] + j;
681                                                 int c = bam1_qual(p->b)[p->qpos] + 33;
682                                                 if (c > 126) c = 126;
683                                                 putchar(c);
684                                         }
685                                 }
686                         }
687                         putchar('\n');
688                 }
689         }
690         bcf_close(bp);
691         if (conf->flag&MPLP_VCF) mc_dump_afs(ma);
692         if (hash) { // free the hash table
693                 khint_t k;
694                 for (k = kh_begin(hash); k < kh_end(hash); ++k)
695                         if (kh_exist(hash, k)) free(kh_val(hash, k));
696                 kh_destroy(64, hash);
697         }
698         bcf_call_destroy(bca); free(bc.PL); free(bcr);
699         mc_destroy(ma);
700         bam_mplp_destroy(iter);
701         bam_header_destroy(h);
702         for (i = 0; i < n; ++i) {
703                 bam_close(data[i]->fp);
704                 if (data[i]->iter) bam_iter_destroy(data[i]->iter);
705                 free(data[i]);
706         }
707         free(data); free(plp); free(ref); free(n_plp);
708         return 0;
709 }
710
711 int bam_mpileup(int argc, char *argv[])
712 {
713         int c;
714         mplp_conf_t mplp;
715         memset(&mplp, 0, sizeof(mplp_conf_t));
716         mplp.max_mq = 60;
717         mplp.prior_type = MC_PTYPE_FULL;
718         mplp.theta = 1e-3;
719         while ((c = getopt(argc, argv, "gvVcFSP:f:r:l:VM:q:t:")) >= 0) {
720                 switch (c) {
721                 case 't': mplp.theta = atof(optarg); break;
722                 case 'P':
723                         if (strcmp(optarg, "full") == 0) mplp.prior_type = MC_PTYPE_FULL;
724                         else if (strcmp(optarg, "cond2") == 0) mplp.prior_type = MC_PTYPE_COND2;
725                         else if (strcmp(optarg, "flat") == 0) mplp.prior_type = MC_PTYPE_FLAT;
726                         else {
727                                 fprintf(stderr, "[%s] unrecognized prior type.\n", __func__);
728                                 return 1;
729                         }
730                         break;
731                 case 'f':
732                         mplp.fai = fai_load(optarg);
733                         if (mplp.fai == 0) return 1;
734                         break;
735                 case 'r': mplp.reg = strdup(optarg); break;
736                 case 'l': mplp.fn_pos = strdup(optarg); break;
737                 case 'g': mplp.flag |= MPLP_GLF; break;
738                 case 'V':
739                 case 'c': mplp.flag |= MPLP_VCF; break;
740                 case 'F': mplp.flag |= MPLP_AFALL; break;
741                 case 'v': mplp.flag |= MPLP_VAR; break;
742                 case 'M': mplp.max_mq = atoi(optarg); break;
743                 case 'q': mplp.min_mq = atoi(optarg); break;
744                 }
745         }
746         if (mplp.flag&MPLP_GLF) mplp.flag &= ~MPLP_VCF;
747         if (argc == 1) {
748                 fprintf(stderr, "\n");
749                 fprintf(stderr, "Usage:   samtools mpileup [options] in1.bam [in2.bam [...]]\n\n");
750                 fprintf(stderr, "Options: -f FILE     reference sequence file [null]\n");
751                 fprintf(stderr, "         -r STR      region in which pileup is generated [null]\n");
752                 fprintf(stderr, "         -l FILE     list of positions (format: chr pos) [null]\n");
753                 fprintf(stderr, "         -M INT      cap mapping quality at INT [%d]\n", mplp.max_mq);
754                 fprintf(stderr, "         -q INT      filter out alignment with MQ smaller than INT [%d]\n", mplp.min_mq);
755                 fprintf(stderr, "         -t FLOAT    scaled mutation rate [%lg]\n", mplp.theta);
756                 fprintf(stderr, "         -P STR      prior: full, flat, cond2 [full]\n");
757                 fprintf(stderr, "         -c          generate VCF output (consensus calling)\n");
758                 fprintf(stderr, "         -g          generate GLF output\n");
759                 fprintf(stderr, "         -v          show variant sites only\n");
760                 fprintf(stderr, "\n");
761                 fprintf(stderr, "Notes: Assuming error independency and diploid individuals.\n\n");
762                 return 1;
763         }
764         mpileup(&mplp, argc - optind, argv + optind);
765         free(mplp.reg);
766         if (mplp.fai) fai_destroy(mplp.fai);
767         return 0;
768 }