]> git.donarmstrong.com Git - samtools.git/blob - bam_plcmd.c
* the code base is stablized again.
[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 #define MPLP_NO_COMP 0x20
458
459 #define MPLP_AFS_BLOCK 0x10000
460
461 typedef struct {
462         int max_mq, min_mq, prior_type, flag, min_baseQ;
463         double theta;
464         char *reg, *fn_pos;
465         faidx_t *fai;
466         kh_64_t *hash;
467 } mplp_conf_t;
468
469 typedef struct {
470         bamFile fp;
471         bam_iter_t iter;
472         int min_mq;
473 } mplp_aux_t;
474
475 static int mplp_func(void *data, bam1_t *b)
476 {
477         mplp_aux_t *ma = (mplp_aux_t*)data;
478         int ret;
479         do {
480                 ret = ma->iter? bam_iter_read(ma->fp, ma->iter, b) : bam_read1(ma->fp, b);
481         } while (b->core.qual < ma->min_mq && ret >= 0);
482         return ret;
483 }
484
485 static int mpileup(mplp_conf_t *conf, int n, char **fn)
486 {
487         mplp_aux_t **data;
488         int i, tid, pos, *n_plp, beg0 = 0, end0 = 1u<<29, ref_len, ref_tid;
489         const bam_pileup1_t **plp;
490         bam_mplp_t iter;
491         bam_header_t *h = 0;
492         uint64_t N = 0;
493         char *ref;
494         khash_t(64) *hash = 0;
495
496         mc_aux_t *ma = 0;
497
498         bcf_callaux_t *bca = 0;
499         bcf_callret1_t *bcr = 0;
500         bcf_call_t bc;
501         bcf_t *bp = 0;
502         bcf_hdr_t *bh = 0;
503
504         memset(&bc, 0, sizeof(bcf_call_t));
505         data = calloc(n, sizeof(void*));
506         plp = calloc(n, sizeof(void*));
507         n_plp = calloc(n, sizeof(int*));
508
509         // read the header and initialize data
510         for (i = 0; i < n; ++i) {
511                 bam_header_t *h_tmp;
512                 data[i] = calloc(1, sizeof(mplp_aux_t));
513                 data[i]->min_mq = conf->min_mq;
514                 data[i]->fp = bam_open(fn[i], "r");
515                 h_tmp = bam_header_read(data[i]->fp);
516                 if (conf->reg) {
517                         int beg, end;
518                         bam_index_t *idx;
519                         idx = bam_index_load(fn[i]);
520                         if (idx == 0) {
521                                 fprintf(stderr, "[%s] fail to load index for %d-th input.\n", __func__, i+1);
522                                 exit(1);
523                         }
524                         if (bam_parse_region(h_tmp, conf->reg, &tid, &beg, &end) < 0) {
525                                 fprintf(stderr, "[%s] malformatted region or wrong seqname for %d-th input.\n", __func__, i+1);
526                                 exit(1);
527                         }
528                         if (i == 0) beg0 = beg, end0 = end;
529                         data[i]->iter = bam_iter_query(idx, tid, beg, end);
530                         bam_index_destroy(idx);
531                 }
532                 if (i == 0) h = h_tmp;
533                 else {
534                         // FIXME: to check consistency
535                         bam_header_destroy(h_tmp);
536                 }
537         }
538         if (conf->fn_pos) hash = load_pos(conf->fn_pos, h);
539         // write the VCF header
540         if (conf->flag & MPLP_GLF) {
541                 kstring_t s;
542                 bh = calloc(1, sizeof(bcf_hdr_t));
543                 s.l = s.m = 0; s.s = 0;
544                 bp = bcf_open("-", (conf->flag&MPLP_NO_COMP)? "wu" : "w");
545                 for (i = 0; i < h->n_targets; ++i) {
546                         kputs(h->target_name[i], &s);
547                         kputc('\0', &s);
548                 }
549                 bh->l_nm = s.l;
550                 bh->name = malloc(s.l);
551                 memcpy(bh->name, s.s, s.l);
552                 s.l = 0;
553                 for (i = 0; i < n; ++i) {
554                         const char *p;
555                         if ((p = strstr(fn[i], ".bam")) != 0)
556                                 kputsn(fn[i], p - fn[i], &s);
557                         else kputs(fn[i], &s);
558                         kputc('\0', &s);
559                 }
560                 bh->l_smpl = s.l;
561                 bh->sname = malloc(s.l);
562                 memcpy(bh->sname, s.s, s.l);
563                 bh->l_txt = 0;
564                 free(s.s);
565                 bcf_hdr_sync(bh);
566                 bcf_hdr_write(bp, bh);
567         } else if (conf->flag & MPLP_VCF) {
568                 kstring_t s;
569                 s.l = s.m = 0; s.s = 0;
570                 puts("##fileformat=VCFv4.0");
571                 puts("##INFO=<ID=DP,Number=1,Type=Integer,Description=\"Total read depth\">");
572                 puts("##INFO=<ID=AF,Number=1,Type=Float,Description=\"Non-reference allele frequency \\argmax_f P(D|f)\">");
573                 puts("##INFO=<ID=AFE,Number=1,Type=Float,Description=\"Expected non-reference allele frequency\">");
574                 puts("##FILTER=<ID=Q13,Description=\"All min{baseQ,mapQ} below 13\">");
575                 puts("##FILTER=<ID=FPE,Description=\"Floating point error\">");
576                 kputs("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT", &s);
577                 for (i = 0; i < n; ++i) {
578                         const char *p;
579                         kputc('\t', &s);
580                         if ((p = strstr(fn[i], ".bam")) != 0)
581                                 kputsn(fn[i], p - fn[i], &s);
582                         else kputs(fn[i], &s);
583                 }
584                 puts(s.s);
585                 free(s.s);
586         }
587         // mpileup
588         if (conf->flag & MPLP_GLF) {
589                 bca = bcf_call_init(-1., conf->min_baseQ);
590                 bcr = calloc(n, sizeof(bcf_callret1_t));
591         } else if (conf->flag & MPLP_VCF) {
592                 ma = mc_init(n);
593                 mc_init_prior(ma, conf->prior_type, conf->theta);
594         }
595         ref_tid = -1; ref = 0;
596         iter = bam_mplp_init(n, mplp_func, (void**)data);
597         while (bam_mplp_auto(iter, &tid, &pos, n_plp, plp) > 0) {
598                 if (conf->reg && (pos < beg0 || pos >= end0)) continue; // out of the region requested
599                 if (hash) {
600                         khint_t k;
601                         k = kh_get(64, hash, (uint64_t)tid<<32 | pos);
602                         if (k == kh_end(hash)) continue;
603                 }
604                 if (tid != ref_tid) {
605                         free(ref);
606                         if (conf->fai) ref = fai_fetch(conf->fai, h->target_name[tid], &ref_len);
607                         ref_tid = tid;
608                 }
609                 if (conf->flag & MPLP_GLF) {
610                         int _ref0, ref16;
611                         bcf1_t *b = calloc(1, sizeof(bcf1_t));
612                         _ref0 = (ref && pos < ref_len)? ref[pos] : 'N';
613                         ref16 = bam_nt16_table[_ref0];
614                         for (i = 0; i < n; ++i)
615                                 bcf_call_glfgen(n_plp[i], plp[i], ref16, bca, bcr + i);
616                         bcf_call_combine(n, bcr, ref16, &bc);
617                         bcf_call2bcf(tid, pos, &bc, b);
618                         bcf_write(bp, bh, b);
619                         //fprintf(stderr, "%d,%d,%d\n", b->tid, b->pos, b->l_str);
620                         bcf_destroy(b);
621                 } else if (conf->flag & MPLP_VCF) {
622                         mc_rst_t r;
623                         int j, _ref0, depth, rms_q, _ref0b, is_var = 0, qref = 0, level = 2, tot;
624                         uint64_t sqr_sum;
625                         _ref0 = _ref0b = (ref && pos < ref_len)? ref[pos] : 'N';
626                         _ref0 = bam_nt16_nt4_table[bam_nt16_table[_ref0]];
627                         tot = mc_cal(_ref0, n_plp, plp, ma, &r, level);
628                         if (tot) { // has good bases
629                                 double q;
630                                 is_var = (r.p_ref < .5);
631                                 q = is_var? r.p_ref : 1. - r.p_ref;
632                                 if (q < 1e-308) q = 1e-308;
633                                 qref = (int)(-3.434 * log(q) + .499);
634                                 if (qref > 99) qref = 99;
635                         }
636                         if ((conf->flag & MPLP_VAR) && !is_var) continue;
637                         ++N; // number of processed lines
638                         printf("%s\t%d\t.\t%c\t", h->target_name[tid], pos + 1, _ref0b);
639                         if (is_var) {
640                                 putchar("ACGTN"[r.alt]);
641                                 if (r.alt2 >= 0 && r.alt2 < 4) printf(",%c", "ACGT"[r.alt2]);
642                         } else putchar('.');
643                         printf("\t%d\t", qref);
644                         if (!tot) printf("Q13\t");
645                         else if (r.f_exp < 0.) printf("FPE\t");
646                         else printf(".\t");
647                         for (i = depth = 0, sqr_sum = 0; i < n; ++i) {
648                                 depth += n_plp[i];
649                                 for (j = 0; j < n_plp[i]; ++j) {
650                                         int q = plp[i][j].b->core.qual;
651                                         if (q > conf->max_mq) q = conf->max_mq;
652                                         sqr_sum += q * q;
653                                 }
654                         }
655                         rms_q = (int)(sqrt((double)sqr_sum / depth) + .499);
656                         printf("DP=%d;MQ=%d", depth, rms_q);
657                         if (tot) {
658                                 printf(";AF=%.3lf", 1. - r.f_em);
659                                 if (level >= 2) printf(";AFE=%.3lf", 1-r.f_exp);
660                                 if (conf->flag & MPLP_AFALL)
661                                         printf(";AF0=%.3lf;AFN=%.3lf", 1-r.f_naive, 1-r.f_nielsen);
662                         }
663                         printf("\tGT:GQ:DP");
664                         if (tot) {
665                                 for (i = 0; i < n; ++i) {
666                                         int x = mc_call_gt(ma, r.f_exp, i);
667                                         printf("\t%c/%c:%d:%d", "10"[((x&3)==2)], "10"[((x&3)>0)], x>>2, n_plp[i]);
668                                 }
669                         } else for (i = 0; i < n; ++i) printf("\t./.:0:0");
670                         putchar('\n');
671                         if (N % MPLP_AFS_BLOCK == 0) mc_dump_afs(ma);
672                 } else {
673                         printf("%s\t%d\t%c", h->target_name[tid], pos + 1, (ref && pos < ref_len)? ref[pos] : 'N');
674                         for (i = 0; i < n; ++i) {
675                                 int j;
676                                 printf("\t%d\t", n_plp[i]);
677                                 if (n_plp[i] == 0) printf("*\t*");
678                                 else {
679                                         for (j = 0; j < n_plp[i]; ++j)
680                                                 pileup_seq(plp[i] + j, pos, ref_len, ref);
681                                         putchar('\t');
682                                         for (j = 0; j < n_plp[i]; ++j) {
683                                                 const bam_pileup1_t *p = plp[i] + j;
684                                                 int c = bam1_qual(p->b)[p->qpos] + 33;
685                                                 if (c > 126) c = 126;
686                                                 putchar(c);
687                                         }
688                                 }
689                         }
690                         putchar('\n');
691                 }
692         }
693         bcf_close(bp);
694         if (conf->flag&MPLP_VCF) mc_dump_afs(ma);
695         if (hash) { // free the hash table
696                 khint_t k;
697                 for (k = kh_begin(hash); k < kh_end(hash); ++k)
698                         if (kh_exist(hash, k)) free(kh_val(hash, k));
699                 kh_destroy(64, hash);
700         }
701         bcf_hdr_destroy(bh); bcf_call_destroy(bca); free(bc.PL); free(bcr);
702         mc_destroy(ma);
703         bam_mplp_destroy(iter);
704         bam_header_destroy(h);
705         for (i = 0; i < n; ++i) {
706                 bam_close(data[i]->fp);
707                 if (data[i]->iter) bam_iter_destroy(data[i]->iter);
708                 free(data[i]);
709         }
710         free(data); free(plp); free(ref); free(n_plp);
711         return 0;
712 }
713
714 int bam_mpileup(int argc, char *argv[])
715 {
716         int c;
717         mplp_conf_t mplp;
718         memset(&mplp, 0, sizeof(mplp_conf_t));
719         mplp.max_mq = 60;
720         mplp.prior_type = MC_PTYPE_FULL;
721         mplp.theta = 1e-3;
722         mplp.min_baseQ = 13;
723         while ((c = getopt(argc, argv, "gvVcFSP:f:r:l:VM:q:t:Q:u")) >= 0) {
724                 switch (c) {
725                 case 't': mplp.theta = atof(optarg); break;
726                 case 'P':
727                         if (strcmp(optarg, "full") == 0) mplp.prior_type = MC_PTYPE_FULL;
728                         else if (strcmp(optarg, "cond2") == 0) mplp.prior_type = MC_PTYPE_COND2;
729                         else if (strcmp(optarg, "flat") == 0) mplp.prior_type = MC_PTYPE_FLAT;
730                         else {
731                                 fprintf(stderr, "[%s] unrecognized prior type.\n", __func__);
732                                 return 1;
733                         }
734                         break;
735                 case 'f':
736                         mplp.fai = fai_load(optarg);
737                         if (mplp.fai == 0) return 1;
738                         break;
739                 case 'r': mplp.reg = strdup(optarg); break;
740                 case 'l': mplp.fn_pos = strdup(optarg); break;
741                 case 'g': mplp.flag |= MPLP_GLF; break;
742                 case 'V':
743                 case 'c': mplp.flag |= MPLP_VCF; break;
744                 case 'F': mplp.flag |= MPLP_AFALL; break;
745                 case 'v': mplp.flag |= MPLP_VAR; break;
746                 case 'u': mplp.flag |= MPLP_NO_COMP; break;
747                 case 'M': mplp.max_mq = atoi(optarg); break;
748                 case 'q': mplp.min_mq = atoi(optarg); break;
749                 case 'Q': mplp.min_baseQ = atoi(optarg); break;
750                 }
751         }
752         if (mplp.flag&MPLP_GLF) mplp.flag &= ~MPLP_VCF;
753         if (argc == 1) {
754                 fprintf(stderr, "\n");
755                 fprintf(stderr, "Usage:   samtools mpileup [options] in1.bam [in2.bam [...]]\n\n");
756                 fprintf(stderr, "Options: -f FILE     reference sequence file [null]\n");
757                 fprintf(stderr, "         -r STR      region in which pileup is generated [null]\n");
758                 fprintf(stderr, "         -l FILE     list of positions (format: chr pos) [null]\n");
759                 fprintf(stderr, "         -M INT      cap mapping quality at INT [%d]\n", mplp.max_mq);
760                 fprintf(stderr, "         -q INT      filter out alignment with MQ smaller than INT [%d]\n", mplp.min_mq);
761                 fprintf(stderr, "         -t FLOAT    scaled mutation rate [%lg]\n", mplp.theta);
762                 fprintf(stderr, "         -P STR      prior: full, flat, cond2 [full]\n");
763                 fprintf(stderr, "         -Q INT      min base quality [%d]\n", mplp.min_baseQ);
764                 fprintf(stderr, "         -c          generate VCF output (consensus calling)\n");
765                 fprintf(stderr, "         -g          generate GLF output\n");
766                 fprintf(stderr, "         -v          show variant sites only\n");
767                 fprintf(stderr, "\n");
768                 fprintf(stderr, "Notes: Assuming error independency and diploid individuals.\n\n");
769                 return 1;
770         }
771         mpileup(&mplp, argc - optind, argv + optind);
772         free(mplp.reg);
773         if (mplp.fai) fai_destroy(mplp.fai);
774         return 0;
775 }