]> git.donarmstrong.com Git - samtools.git/blob - bam_plcmd.c
* samtools-0.1.8-19 (r777)
[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 "khash.h"
9 #include "glf.h"
10 #include "kstring.h"
11
12 typedef int *indel_list_t;
13 KHASH_MAP_INIT_INT64(64, indel_list_t)
14
15 #define BAM_PLF_SIMPLE     0x01
16 #define BAM_PLF_CNS        0x02
17 #define BAM_PLF_INDEL_ONLY 0x04
18 #define BAM_PLF_GLF        0x08
19 #define BAM_PLF_VAR_ONLY   0x10
20 #define BAM_PLF_2ND        0x20
21 #define BAM_PLF_RANBASE    0x40
22 #define BAM_PLF_1STBASE    0x80
23 #define BAM_PLF_ALLBASE    0x100
24 #define BAM_PLF_READPOS    0x200
25 #define BAM_PLF_NOBAQ      0x400
26
27 typedef struct {
28         bam_header_t *h;
29         bam_maqcns_t *c;
30         bam_maqindel_opt_t *ido;
31         faidx_t *fai;
32         khash_t(64) *hash;
33         uint32_t format;
34         int tid, len, last_pos;
35         int mask;
36         int capQ_thres, min_baseQ;
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 {
238                         glf1_t *g = bam_maqcns_glfgen(n, pu, bam_nt16_table[rb], d->c);
239                         cns = g->depth == 0? (0xfu<<28 | 0xf<<24) : glf2cns(g, (int)(d->c->q_r + .499));
240                         free(g);
241                 }
242         }
243     if ((d->format & (BAM_PLF_CNS|BAM_PLF_INDEL_ONLY)) && d->ref && pos < d->len) { // call indels
244         int m = (!d->max_depth || d->max_depth>n) ? n : d->max_depth;
245         if (proposed_indels) // the first element gives the size of the array
246             r = bam_maqindel(m, pos, d->ido, pu, d->ref, proposed_indels[0], proposed_indels+1);
247         else r = bam_maqindel(m, pos, d->ido, pu, d->ref, 0, 0);
248         }
249         // when only variant sites are asked for, test if the site is a variant
250         if ((d->format & BAM_PLF_CNS) && (d->format & BAM_PLF_VAR_ONLY)) {
251                 if (!(bam_nt16_table[rb] != 15 && cns>>28 != 15 && cns>>28 != bam_nt16_table[rb])) { // not a SNP
252                         if (!(r && (r->gt == 2 || strcmp(r->s[r->gt], "*")))) { // not an indel
253                                 if (r) bam_maqindel_ret_destroy(r);
254                                 return 0;
255                         }
256                 }
257         }
258         // print the first 3 columns
259         printf("%s\t%d\t%c\t", d->h->target_name[tid], pos + 1, rb);
260         // print consensus information if required
261         if (d->format & BAM_PLF_CNS)
262                 printf("%c\t%d\t%d\t%d\t", bam_nt16_rev_table[cns>>28], cns>>8&0xff, cns&0xff, cns>>16&0xff);
263         // print pileup sequences
264         printf("%d\t", n);
265         rms_aux = 0; // we need to recalculate rms_mapq when -c is not flagged on the command line
266         for (i = 0; i < n; ++i) {
267                 const bam_pileup1_t *p = pu + i;
268                 int tmp = p->b->core.qual < d->c->cap_mapQ? p->b->core.qual : d->c->cap_mapQ;
269                 rms_aux += tmp * tmp;
270                 pileup_seq(p, pos, d->len, d->ref);
271         }
272         // finalize rms_mapq
273         rms_aux = (uint64_t)(sqrt((double)rms_aux / n) + .499);
274         if (rms_mapq < 0) rms_mapq = rms_aux;
275         putchar('\t');
276         // print quality
277         for (i = 0; i < n; ++i) {
278                 const bam_pileup1_t *p = pu + i;
279                 int c = bam1_qual(p->b)[p->qpos] + 33;
280                 if (c > 126) c = 126;
281                 putchar(c);
282         }
283         if (d->format & BAM_PLF_2ND) { // print 2nd calls and qualities
284                 const unsigned char *q;
285                 putchar('\t');
286                 for (i = 0; i < n; ++i) {
287                         const bam_pileup1_t *p = pu + i;
288                         q = bam_aux_get(p->b, "E2");
289                         putchar(q? q[p->qpos + 1] : 'N');
290                 }
291                 putchar('\t');
292                 for (i = 0; i < n; ++i) {
293                         const bam_pileup1_t *p = pu + i;
294                         q = bam_aux_get(p->b, "U2");
295                         putchar(q? q[p->qpos + 1] : '!');
296                 }
297         }
298         // print mapping quality if -s is flagged on the command line
299         if (d->format & BAM_PLF_SIMPLE) {
300                 putchar('\t');
301                 for (i = 0; i < n; ++i) {
302                         int c = pu[i].b->core.qual + 33;
303                         if (c > 126) c = 126;
304                         putchar(c);
305                 }
306         }
307         // print read position
308         if (d->format & BAM_PLF_READPOS) {
309                 putchar('\t');
310                 for (i = 0; i < n; ++i) {
311                         int x = pu[i].qpos;
312                         int l = pu[i].b->core.l_qseq;
313                         printf("%d,", x < l/2? x+1 : -((l-1)-x+1));
314                 }
315         }
316         putchar('\n');
317         // print the indel line if r has been calculated. This only happens if:
318         // a) -c or -i are flagged, AND b) the reference sequence is available
319         if (r) {
320                 printf("%s\t%d\t*\t", d->h->target_name[tid], pos + 1);
321                 if (r->gt < 2) printf("%s/%s\t", r->s[r->gt], r->s[r->gt]);
322                 else printf("%s/%s\t", r->s[0], r->s[1]);
323                 printf("%d\t%d\t", r->q_cns, r->q_ref);
324                 printf("%d\t%d\t", rms_mapq, n);
325                 printf("%s\t%s\t", r->s[0], r->s[1]);
326                 //printf("%d\t%d\t", r->gl[0], r->gl[1]);
327                 printf("%d\t%d\t%d\t", r->cnt1, r->cnt2, r->cnt_anti);
328                 printf("%d\t%d\n", r->cnt_ref, r->cnt_ambi);
329                 bam_maqindel_ret_destroy(r);
330         }
331         return 0;
332 }
333
334 int bam_pileup(int argc, char *argv[])
335 {
336         int c, is_SAM = 0;
337         char *fn_list = 0, *fn_fa = 0, *fn_pos = 0;
338         pu_data_t *d = (pu_data_t*)calloc(1, sizeof(pu_data_t));
339     d->max_depth = 1024; d->tid = -1; d->mask = BAM_DEF_MASK; d->min_baseQ = 13;
340         d->c = bam_maqcns_init();
341         d->c->errmod = BAM_ERRMOD_MAQ2; // change the default model
342         d->ido = bam_maqindel_opt_init();
343         while ((c = getopt(argc, argv, "st:f:cT:N:r:l:d:im:gI:G:vM:S2aR:PAQ:C:B")) >= 0) {
344                 switch (c) {
345                 case 'Q': d->c->min_baseQ = atoi(optarg); break;
346                 case 'C': d->capQ_thres = atoi(optarg); break;
347                 case 'B': d->format |= BAM_PLF_NOBAQ; break;
348                 case 'a': d->c->errmod = BAM_ERRMOD_SOAP; break;
349                 case 'A': d->c->errmod = BAM_ERRMOD_MAQ; break;
350                 case 's': d->format |= BAM_PLF_SIMPLE; break;
351                 case 't': fn_list = strdup(optarg); break;
352                 case 'l': fn_pos = strdup(optarg); break;
353                 case 'f': fn_fa = strdup(optarg); break;
354                 case 'T': d->c->theta = atof(optarg); break;
355                 case 'N': d->c->n_hap = atoi(optarg); break;
356                 case 'r': d->c->het_rate = atof(optarg); d->ido->r_snp = d->c->het_rate; break;
357                 case 'M': d->c->cap_mapQ = atoi(optarg); break;
358                 case 'd': d->max_depth = atoi(optarg); break;
359                 case 'c': d->format |= BAM_PLF_CNS; break;
360                 case 'i': d->format |= BAM_PLF_INDEL_ONLY; break;
361                 case 'v': d->format |= BAM_PLF_VAR_ONLY; break;
362                 case 'm': d->mask = strtol(optarg, 0, 0); break;
363                 case 'g': d->format |= BAM_PLF_GLF; break;
364                 case '2': d->format |= BAM_PLF_2ND; break;
365                 case 'P': d->format |= BAM_PLF_READPOS; break;
366                 case 'I': d->ido->q_indel = atoi(optarg); break;
367                 case 'G': d->ido->r_indel = atof(optarg); break;
368                 case 'S': is_SAM = 1; break;
369                 case 'R':
370                         if (strcmp(optarg, "random") == 0) d->format |= BAM_PLF_RANBASE;
371                         else if (strcmp(optarg, "first") == 0) d->format |= BAM_PLF_1STBASE;
372                         else if (strcmp(optarg, "all") == 0) d->format |= BAM_PLF_ALLBASE;
373                         else fprintf(stderr, "[bam_pileup] unrecognized -R\n");
374                         break;
375                 default: fprintf(stderr, "Unrecognizd option '-%c'.\n", c); return 1;
376                 }
377         }
378         if (d->c->errmod != BAM_ERRMOD_MAQ2) d->c->theta += 0.02;
379         if (d->c->theta > 1.0) d->c->theta = 1.0;
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, "        -B        disable BAQ computation\n");
387                 fprintf(stderr, "        -A        use the original MAQ model for SNP calling (DEPRECATED)\n");
388                 fprintf(stderr, "        -2        output the 2nd best call and quality\n");
389                 fprintf(stderr, "        -i        only show lines/consensus with indels\n");
390                 fprintf(stderr, "        -Q INT    min base quality (possibly capped by BAQ) [%d]\n", d->c->min_baseQ);
391                 fprintf(stderr, "        -C INT    coefficient for adjusting mapQ of poor mappings [%d]\n", d->capQ_thres);
392                 fprintf(stderr, "        -m INT    filtering reads with bits in INT [0x%x]\n", d->mask);
393                 fprintf(stderr, "        -M INT    cap mapping quality at INT [%d]\n", d->c->cap_mapQ);
394         fprintf(stderr, "        -d INT    limit maximum depth for indels [%d]\n", d->max_depth);
395                 fprintf(stderr, "        -t FILE   list of reference sequences (force -S)\n");
396                 fprintf(stderr, "        -l FILE   list of sites at which pileup is output\n");
397                 fprintf(stderr, "        -f FILE   reference sequence in the FASTA format\n\n");
398                 fprintf(stderr, "        -c        compute the consensus sequence\n");
399                 fprintf(stderr, "        -v        print variants only (for -c)\n");
400                 fprintf(stderr, "        -g        output in the GLFv3 format (DEPRECATED)\n");
401                 fprintf(stderr, "        -T FLOAT  theta in maq consensus calling model (for -c) [%.4g]\n", d->c->theta);
402                 fprintf(stderr, "        -N INT    number of haplotypes in the sample (for -c) [%d]\n", d->c->n_hap);
403                 fprintf(stderr, "        -r FLOAT  prior of a difference between two haplotypes (for -c) [%.4g]\n", d->c->het_rate);
404                 fprintf(stderr, "        -G FLOAT  prior of an indel between two haplotypes (for -c) [%.4g]\n", d->ido->r_indel);
405                 fprintf(stderr, "        -I INT    phred prob. of an indel in sequencing/prep. (for -c) [%d]\n", d->ido->q_indel);
406                 fprintf(stderr, "\n");
407                 free(fn_list); free(fn_fa); free(d);
408                 return 1;
409         }
410         if (d->format & (BAM_PLF_RANBASE|BAM_PLF_1STBASE|BAM_PLF_ALLBASE)) d->format |= BAM_PLF_CNS;
411         if (fn_fa) d->fai = fai_load(fn_fa);
412         if (d->format & (BAM_PLF_CNS|BAM_PLF_GLF)) bam_maqcns_prepare(d->c); // consensus calling
413         if (d->format & BAM_PLF_GLF) { // for glf output
414                 glf3_header_t *h;
415                 h = glf3_header_init();
416                 d->fp_glf = bgzf_fdopen(fileno(stdout), "w");
417                 glf3_header_write(d->fp_glf, h);
418                 glf3_header_destroy(h);
419         }
420         if (d->fai == 0 && (d->format & (BAM_PLF_CNS|BAM_PLF_INDEL_ONLY)))
421                 fprintf(stderr, "[bam_pileup] indels will not be called when -f is absent.\n");
422         if (fn_fa && is_SAM && fn_list == 0) fn_list = samfaipath(fn_fa);
423
424         {
425                 samfile_t *fp;
426                 fp = is_SAM? samopen(argv[optind], "r", fn_list) : samopen(argv[optind], "rb", 0);
427                 if (fp == 0 || fp->header == 0) {
428                         fprintf(stderr, "[bam_pileup] fail to read the header: non-exisiting file or wrong format.\n");
429                         return 1;
430                 }
431                 d->h = fp->header;
432                 if (fn_pos) d->hash = load_pos(fn_pos, d->h);
433                 { // run pileup
434                         extern int bam_prob_realn(bam1_t *b, const char *ref);
435                         extern int bam_cap_mapQ(bam1_t *b, char *ref, int thres);
436                         bam1_t *b;
437                         int ret, tid, pos, n_plp;
438                         bam_plp_t iter;
439                         const bam_pileup1_t *plp;
440                         b = bam_init1();
441                         iter = bam_plp_init(0, 0);
442                         bam_plp_set_mask(iter, d->mask);
443                         while ((ret = samread(fp, b)) >= 0) {
444                                 int skip = 0;
445                                 // update d->ref if necessary
446                                 if (d->fai && (int)b->core.tid != d->tid) {
447                                         free(d->ref);
448                                         d->ref = faidx_fetch_seq(d->fai, d->h->target_name[b->core.tid], 0, 0x7fffffff, &d->len);
449                                         d->tid = b->core.tid;
450                                 }
451                                 if (d->ref && (d->format&BAM_PLF_CNS) && !(d->format&BAM_PLF_NOBAQ)) bam_prob_realn(b, d->ref);
452                                 if (d->ref && (d->format&BAM_PLF_CNS) && d->capQ_thres > 10) {
453                                         int q = bam_cap_mapQ(b, d->ref, d->capQ_thres);
454                                         if (q < 0) skip = 1;
455                                         else if (b->core.qual > q) b->core.qual = q;
456                                 } else if (b->core.flag&BAM_FUNMAP) skip = 1;
457                                 else if ((d->format&BAM_PLF_CNS) && (b->core.flag&1) && !(b->core.flag&2)) skip = 1;
458                                 if (skip) continue;
459                                 bam_plp_push(iter, b);
460                                 while ((plp = bam_plp_next(iter, &tid, &pos, &n_plp)) != 0)
461                                         pileup_func(tid, pos, n_plp, plp, d);
462                         }
463                         bam_plp_push(iter, 0);
464                         while ((plp = bam_plp_next(iter, &tid, &pos, &n_plp)) != 0)
465                                 pileup_func(tid, pos, n_plp, plp, d);
466                         bam_plp_destroy(iter);
467                         bam_destroy1(b);
468                 }
469                 samclose(fp); // d->h will be destroyed here
470         }
471
472         // free
473         if (d->format & BAM_PLF_GLF) bgzf_close(d->fp_glf);
474         if (fn_pos) { // free the hash table
475                 khint_t k;
476                 for (k = kh_begin(d->hash); k < kh_end(d->hash); ++k)
477                         if (kh_exist(d->hash, k)) free(kh_val(d->hash, k));
478                 kh_destroy(64, d->hash);
479         }
480         free(fn_pos); free(fn_list); free(fn_fa);
481         if (d->fai) fai_destroy(d->fai);
482         bam_maqcns_destroy(d->c);
483         free(d->ido); free(d->ref); free(d);
484         return 0;
485 }
486
487 /***********
488  * mpileup *
489  ***********/
490
491 #include <assert.h>
492 #include "bam2bcf.h"
493 #include "sample.h"
494
495 #define MPLP_GLF   0x10
496 #define MPLP_NO_COMP 0x20
497 #define MPLP_NO_ORPHAN 0x40
498 #define MPLP_REALN   0x80
499
500 typedef struct {
501         int max_mq, min_mq, flag, min_baseQ, capQ_thres;
502         char *reg, *fn_pos;
503         faidx_t *fai;
504         kh_64_t *hash;
505 } mplp_conf_t;
506
507 typedef struct {
508         bamFile fp;
509         bam_iter_t iter;
510         int min_mq, flag, ref_id, capQ_thres;
511         char *ref;
512 } mplp_aux_t;
513
514 typedef struct {
515         int n;
516         int *n_plp, *m_plp;
517         bam_pileup1_t **plp;
518 } mplp_pileup_t;
519
520 static int mplp_func(void *data, bam1_t *b)
521 {
522         extern int bam_realn(bam1_t *b, const char *ref);
523         extern int bam_prob_realn(bam1_t *b, const char *ref);
524         extern int bam_cap_mapQ(bam1_t *b, char *ref, int thres);
525         mplp_aux_t *ma = (mplp_aux_t*)data;
526         int ret, skip = 0;
527         do {
528                 int has_ref = (ma->ref && ma->ref_id == b->core.tid)? 1 : 0;
529                 ret = ma->iter? bam_iter_read(ma->fp, ma->iter, b) : bam_read1(ma->fp, b);
530                 if (ret < 0) break;
531                 skip = 0;
532                 if (has_ref && (ma->flag&MPLP_REALN)) bam_prob_realn(b, ma->ref);
533                 if (has_ref && ma->capQ_thres > 10) {
534                         int q = bam_cap_mapQ(b, ma->ref, ma->capQ_thres);
535                         if (q < 0) skip = 1;
536                         else if (b->core.qual > q) b->core.qual = q;
537                 } else if (b->core.flag&BAM_FUNMAP) skip = 1;
538                 else if (b->core.qual < ma->min_mq) skip = 1; 
539                 else if ((ma->flag&MPLP_NO_ORPHAN) && (b->core.flag&1) && !(b->core.flag&2)) skip = 1;
540         } while (skip);
541         return ret;
542 }
543
544 static void group_smpl(mplp_pileup_t *m, bam_sample_t *sm, kstring_t *buf,
545                                            int n, char *const*fn, int *n_plp, const bam_pileup1_t **plp)
546 {
547         int i, j;
548         memset(m->n_plp, 0, m->n * sizeof(int));
549         for (i = 0; i < n; ++i) {
550                 for (j = 0; j < n_plp[i]; ++j) {
551                         const bam_pileup1_t *p = plp[i] + j;
552                         uint8_t *q;
553                         int id = -1;
554                         q = bam_aux_get(p->b, "RG");
555                         if (q) id = bam_smpl_rg2smid(sm, fn[i], (char*)q+1, buf);
556                         if (id < 0) id = bam_smpl_rg2smid(sm, fn[i], 0, buf);
557                         assert(id >= 0 && id < m->n);
558                         if (m->n_plp[id] == m->m_plp[id]) {
559                                 m->m_plp[id] = m->m_plp[id]? m->m_plp[id]<<1 : 8;
560                                 m->plp[id] = realloc(m->plp[id], sizeof(bam_pileup1_t) * m->m_plp[id]);
561                         }
562                         m->plp[id][m->n_plp[id]++] = *p;
563                 }
564         }
565 }
566
567 static int mpileup(mplp_conf_t *conf, int n, char **fn)
568 {
569         mplp_aux_t **data;
570         int i, tid, pos, *n_plp, beg0 = 0, end0 = 1u<<29, ref_len, ref_tid;
571         const bam_pileup1_t **plp;
572         bam_mplp_t iter;
573         bam_header_t *h = 0;
574         char *ref;
575         khash_t(64) *hash = 0;
576
577         bcf_callaux_t *bca = 0;
578         bcf_callret1_t *bcr = 0;
579         bcf_call_t bc;
580         bcf_t *bp = 0;
581         bcf_hdr_t *bh = 0;
582
583         bam_sample_t *sm = 0;
584         kstring_t buf;
585         mplp_pileup_t gplp;
586
587         memset(&gplp, 0, sizeof(mplp_pileup_t));
588         memset(&buf, 0, sizeof(kstring_t));
589         memset(&bc, 0, sizeof(bcf_call_t));
590         data = calloc(n, sizeof(void*));
591         plp = calloc(n, sizeof(void*));
592         n_plp = calloc(n, sizeof(int*));
593         sm = bam_smpl_init();
594
595         // read the header and initialize data
596         for (i = 0; i < n; ++i) {
597                 bam_header_t *h_tmp;
598                 data[i] = calloc(1, sizeof(mplp_aux_t));
599                 data[i]->min_mq = conf->min_mq;
600                 data[i]->flag = conf->flag;
601                 data[i]->capQ_thres = conf->capQ_thres;
602                 data[i]->fp = strcmp(fn[i], "-") == 0? bam_dopen(fileno(stdin), "r") : bam_open(fn[i], "r");
603                 h_tmp = bam_header_read(data[i]->fp);
604                 bam_smpl_add(sm, fn[i], h_tmp->text);
605                 if (conf->reg) {
606                         int beg, end;
607                         bam_index_t *idx;
608                         idx = bam_index_load(fn[i]);
609                         if (idx == 0) {
610                                 fprintf(stderr, "[%s] fail to load index for %d-th input.\n", __func__, i+1);
611                                 exit(1);
612                         }
613                         if (bam_parse_region(h_tmp, conf->reg, &tid, &beg, &end) < 0) {
614                                 fprintf(stderr, "[%s] malformatted region or wrong seqname for %d-th input.\n", __func__, i+1);
615                                 exit(1);
616                         }
617                         if (i == 0) beg0 = beg, end0 = end;
618                         data[i]->iter = bam_iter_query(idx, tid, beg, end);
619                         bam_index_destroy(idx);
620                 }
621                 if (i == 0) h = h_tmp;
622                 else {
623                         // FIXME: to check consistency
624                         bam_header_destroy(h_tmp);
625                 }
626         }
627         gplp.n = sm->n;
628         gplp.n_plp = calloc(sm->n, sizeof(int));
629         gplp.m_plp = calloc(sm->n, sizeof(int));
630         gplp.plp = calloc(sm->n, sizeof(void*));
631
632         fprintf(stderr, "[%s] %d samples in %d input files\n", __func__, sm->n, n);
633         if (conf->fn_pos) hash = load_pos(conf->fn_pos, h);
634         // write the VCF header
635         if (conf->flag & MPLP_GLF) {
636                 kstring_t s;
637                 bh = calloc(1, sizeof(bcf_hdr_t));
638                 s.l = s.m = 0; s.s = 0;
639                 bp = bcf_open("-", (conf->flag&MPLP_NO_COMP)? "wu" : "w");
640                 for (i = 0; i < h->n_targets; ++i) {
641                         kputs(h->target_name[i], &s);
642                         kputc('\0', &s);
643                 }
644                 bh->l_nm = s.l;
645                 bh->name = malloc(s.l);
646                 memcpy(bh->name, s.s, s.l);
647                 s.l = 0;
648                 for (i = 0; i < sm->n; ++i) {
649                         kputs(sm->smpl[i], &s); kputc('\0', &s);
650                 }
651                 bh->l_smpl = s.l;
652                 bh->sname = malloc(s.l);
653                 memcpy(bh->sname, s.s, s.l);
654                 bh->l_txt = 0;
655                 free(s.s);
656                 bcf_hdr_sync(bh);
657                 bcf_hdr_write(bp, bh);
658                 bca = bcf_call_init(-1., conf->min_baseQ);
659                 bcr = calloc(sm->n, sizeof(bcf_callret1_t));
660         }
661         ref_tid = -1; ref = 0;
662         iter = bam_mplp_init(n, mplp_func, (void**)data);
663         while (bam_mplp_auto(iter, &tid, &pos, n_plp, plp) > 0) {
664                 if (conf->reg && (pos < beg0 || pos >= end0)) continue; // out of the region requested
665                 if (hash) {
666                         khint_t k;
667                         k = kh_get(64, hash, (uint64_t)tid<<32 | pos);
668                         if (k == kh_end(hash)) continue;
669                 }
670                 if (tid != ref_tid) {
671                         free(ref); ref = 0;
672                         if (conf->fai) ref = fai_fetch(conf->fai, h->target_name[tid], &ref_len);
673                         for (i = 0; i < n; ++i) data[i]->ref = ref, data[i]->ref_id = tid;
674                         ref_tid = tid;
675                 }
676                 if (conf->flag & MPLP_GLF) {
677                         int _ref0, ref16;
678                         bcf1_t *b = calloc(1, sizeof(bcf1_t));
679                         group_smpl(&gplp, sm, &buf, n, fn, n_plp, plp);
680                         _ref0 = (ref && pos < ref_len)? ref[pos] : 'N';
681                         ref16 = bam_nt16_table[_ref0];
682                         for (i = 0; i < gplp.n; ++i)
683                                 bcf_call_glfgen(gplp.n_plp[i], gplp.plp[i], ref16, bca, bcr + i);
684                         bcf_call_combine(gplp.n, bcr, ref16, &bc);
685                         bcf_call2bcf(tid, pos, &bc, b);
686                         bcf_write(bp, bh, b);
687                         bcf_destroy(b);
688                 } else {
689                         printf("%s\t%d\t%c", h->target_name[tid], pos + 1, (ref && pos < ref_len)? ref[pos] : 'N');
690                         for (i = 0; i < n; ++i) {
691                                 int j;
692                                 printf("\t%d\t", n_plp[i]);
693                                 if (n_plp[i] == 0) printf("*\t*");
694                                 else {
695                                         for (j = 0; j < n_plp[i]; ++j)
696                                                 pileup_seq(plp[i] + j, pos, ref_len, ref);
697                                         putchar('\t');
698                                         for (j = 0; j < n_plp[i]; ++j) {
699                                                 const bam_pileup1_t *p = plp[i] + j;
700                                                 int c = bam1_qual(p->b)[p->qpos] + 33;
701                                                 if (c > 126) c = 126;
702                                                 putchar(c);
703                                         }
704                                 }
705                         }
706                         putchar('\n');
707                 }
708         }
709
710         bcf_close(bp);
711         bam_smpl_destroy(sm); free(buf.s);
712         for (i = 0; i < gplp.n; ++i) free(gplp.plp[i]);
713         free(gplp.plp); free(gplp.n_plp); free(gplp.m_plp);
714         if (hash) { // free the hash table
715                 khint_t k;
716                 for (k = kh_begin(hash); k < kh_end(hash); ++k)
717                         if (kh_exist(hash, k)) free(kh_val(hash, k));
718                 kh_destroy(64, hash);
719         }
720         bcf_hdr_destroy(bh); bcf_call_destroy(bca); free(bc.PL); free(bcr);
721         bam_mplp_destroy(iter);
722         bam_header_destroy(h);
723         for (i = 0; i < n; ++i) {
724                 bam_close(data[i]->fp);
725                 if (data[i]->iter) bam_iter_destroy(data[i]->iter);
726                 free(data[i]);
727         }
728         free(data); free(plp); free(ref); free(n_plp);
729         return 0;
730 }
731
732 int bam_mpileup(int argc, char *argv[])
733 {
734         int c;
735         mplp_conf_t mplp;
736         memset(&mplp, 0, sizeof(mplp_conf_t));
737         mplp.max_mq = 60;
738         mplp.min_baseQ = 13;
739         mplp.capQ_thres = 0;
740         while ((c = getopt(argc, argv, "gf:r:l:M:q:Q:uaORC:")) >= 0) {
741                 switch (c) {
742                 case 'f':
743                         mplp.fai = fai_load(optarg);
744                         if (mplp.fai == 0) return 1;
745                         break;
746                 case 'r': mplp.reg = strdup(optarg); break;
747                 case 'l': mplp.fn_pos = strdup(optarg); break;
748                 case 'g': mplp.flag |= MPLP_GLF; break;
749                 case 'u': mplp.flag |= MPLP_NO_COMP | MPLP_GLF; break;
750                 case 'a': mplp.flag |= MPLP_NO_ORPHAN | MPLP_REALN; break;
751                 case 'O': mplp.flag |= MPLP_NO_ORPHAN; break;
752                 case 'R': mplp.flag |= MPLP_REALN; break;
753                 case 'C': mplp.capQ_thres = atoi(optarg); break;
754                 case 'M': mplp.max_mq = atoi(optarg); break;
755                 case 'q': mplp.min_mq = atoi(optarg); break;
756                 case 'Q': mplp.min_baseQ = atoi(optarg); break;
757                 }
758         }
759         if (argc == 1) {
760                 fprintf(stderr, "\n");
761                 fprintf(stderr, "Usage:   samtools mpileup [options] in1.bam [in2.bam [...]]\n\n");
762                 fprintf(stderr, "Options: -f FILE     reference sequence file [null]\n");
763                 fprintf(stderr, "         -r STR      region in which pileup is generated [null]\n");
764                 fprintf(stderr, "         -l FILE     list of positions (format: chr pos) [null]\n");
765                 fprintf(stderr, "         -M INT      cap mapping quality at INT [%d]\n", mplp.max_mq);
766                 fprintf(stderr, "         -Q INT      min base quality [%d]\n", mplp.min_baseQ);
767                 fprintf(stderr, "         -q INT      filter out alignment with MQ smaller than INT [%d]\n", mplp.min_mq);
768                 fprintf(stderr, "         -g          generate BCF output\n");
769                 fprintf(stderr, "         -u          do not compress BCF output\n");
770                 fprintf(stderr, "\n");
771                 fprintf(stderr, "Notes: Assuming diploid individuals.\n\n");
772                 return 1;
773         }
774         mpileup(&mplp, argc - optind, argv + optind);
775         free(mplp.reg);
776         if (mplp.fai) fai_destroy(mplp.fai);
777         return 0;
778 }