7 #include "bam_maqcns.h"
12 typedef int *indel_list_t;
13 KHASH_MAP_INIT_INT64(64, indel_list_t)
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
30 bam_maqindel_opt_t *ido;
34 int tid, len, last_pos;
36 int capQ_thres, min_baseQ;
37 int max_depth; // for indel calling, ignore reads with the depth too high. 0 for unlimited
39 glfFile fp_glf; // for glf output only
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);
46 static khash_t(64) *load_pos(const char *fn, bam_header_t *h)
49 int i, j, n, *fields, max_fields;
51 bam_init_header_hash(h);
52 list = __bam_get_lines(fn, &n);
54 max_fields = 0; fields = 0;
55 for (i = 0; i < n; ++i) {
57 int chr, n_fields, ret;
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]);
64 fprintf(stderr, "[load_pos] unknown reference sequence name: %s\n", str + fields[0]);
67 x = (uint64_t)chr << 32 | (atoi(str + fields[1]) - 1);
68 k = kh_put(64, hash, x, &ret);
70 fprintf(stderr, "[load_pos] position %s:%s has been loaded.\n", str+fields[0], str+fields[1]);
76 for (j = 2; j < n_fields; ++j) {
77 char *s = str + fields[j];
78 if ((*s != '+' && *s != '-') || !isdigit(s[1])) break;
80 if (j > 2) { // update kh_val()
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]);
90 free(list); free(fields);
94 static inline int printw(int c, FILE *fp)
98 if (c == 0) return fputc('0', fp);
99 for (l = 0, x = c < 0? -c : c; x > 0; x /= 10) buf[l++] = x%10 + '0';
100 if (c < 0) buf[l++] = '-';
102 for (x = 0; x < l/2; ++x) {
103 int y = buf[x]; buf[x] = buf[l-1-x]; buf[l-1-x] = y;
109 // an analogy to pileup_func() below
110 static int glt3_func(uint32_t tid, uint32_t pos, int n, const bam_pileup1_t *pu, void *data)
112 pu_data_t *d = (pu_data_t*)data;
113 bam_maqindel_ret_t *r = 0;
114 int rb, *proposed_indels = 0;
119 fprintf(stderr, "[glt3_func] reference sequence is required for generating GLT. Abort!\n");
122 if (d->hash) { // only output a list of sites
123 khint_t k = kh_get(64, d->hash, (uint64_t)tid<<32|pos);
124 if (k == kh_end(d->hash)) return 0;
125 proposed_indels = kh_val(d->hash, k);
128 if (d->fai && (int)tid != d->tid) {
129 if (d->ref) { // then write the end mark
130 g3->rtype = GLF3_RTYPE_END;
131 glf3_write1(d->fp_glf, g3);
133 glf3_ref_write(d->fp_glf, d->h->target_name[tid], d->h->target_len[tid]); // write reference
135 d->ref = fai_fetch(d->fai, d->h->target_name[tid], &d->len);
139 rb = (d->ref && (int)pos < d->len)? d->ref[pos] : 'N';
140 g = bam_maqcns_glfgen(n, pu, bam_nt16_table[rb], d->c);
141 memcpy(g3, g, sizeof(glf1_t));
142 g3->rtype = GLF3_RTYPE_SUB;
143 g3->offset = pos - d->last_pos;
145 glf3_write1(d->fp_glf, g3);
147 int m = (!d->max_depth || d->max_depth>n) ? n : d->max_depth;
149 r = bam_maqindel(m, pos, d->ido, pu, d->ref, proposed_indels[0], proposed_indels+1);
150 else r = bam_maqindel(m, pos, d->ido, pu, d->ref, 0, 0);
152 if (r) { // then write indel line
153 int het = 3 * n, min;
155 if (min > r->gl[0]) min = r->gl[0];
156 if (min > r->gl[1]) min = r->gl[1];
158 g3->rtype = GLF3_RTYPE_INDEL;
159 memset(g3->lk, 0, 10);
160 g3->lk[0] = r->gl[0] - min < 255? r->gl[0] - min : 255;
161 g3->lk[1] = r->gl[1] - min < 255? r->gl[1] - min : 255;
162 g3->lk[2] = het - min < 255? het - min : 255;
164 g3->indel_len[0] = r->indel1;
165 g3->indel_len[1] = r->indel2;
166 g3->min_lk = min < 255? min : 255;
167 g3->max_len = (abs(r->indel1) > abs(r->indel2)? abs(r->indel1) : abs(r->indel2)) + 1;
168 g3->indel_seq[0] = strdup(r->s[0]+1);
169 g3->indel_seq[1] = strdup(r->s[1]+1);
170 glf3_write1(d->fp_glf, g3);
171 bam_maqindel_ret_destroy(r);
178 static inline void pileup_seq(const bam_pileup1_t *p, int pos, int ref_len, const char *ref)
183 putchar(p->b->core.qual > 93? 126 : p->b->core.qual + 33);
186 int c = bam_nt16_rev_table[bam1_seqi(bam1_seq(p->b), p->qpos)];
188 int rb = pos < ref_len? ref[pos] : 'N';
189 if (c == '=' || bam_nt16_table[c] == bam_nt16_table[rb]) c = bam1_strand(p->b)? ',' : '.';
190 else c = bam1_strand(p->b)? tolower(c) : toupper(c);
192 if (c == '=') c = bam1_strand(p->b)? ',' : '.';
193 else c = bam1_strand(p->b)? tolower(c) : toupper(c);
196 } else putchar(p->is_refskip? (bam1_strand(p->b)? '<' : '>') : '*');
198 putchar('+'); printw(p->indel, stdout);
199 for (j = 1; j <= p->indel; ++j) {
200 int c = bam_nt16_rev_table[bam1_seqi(bam1_seq(p->b), p->qpos + j)];
201 putchar(bam1_strand(p->b)? tolower(c) : toupper(c));
203 } else if (p->indel < 0) {
204 printw(p->indel, stdout);
205 for (j = 1; j <= -p->indel; ++j) {
206 int c = (ref && (int)pos+j < ref_len)? ref[pos+j] : 'N';
207 putchar(bam1_strand(p->b)? tolower(c) : toupper(c));
210 if (p->is_tail) putchar('$');
213 static int pileup_func(uint32_t tid, uint32_t pos, int n, const bam_pileup1_t *pu, void *data)
215 pu_data_t *d = (pu_data_t*)data;
216 bam_maqindel_ret_t *r = 0;
217 int i, rb, rms_mapq = -1, *proposed_indels = 0;
221 // if GLF is required, suppress -c completely
222 if (d->format & BAM_PLF_GLF) return glt3_func(tid, pos, n, pu, data);
223 // if d->hash is initialized, only output the sites in the hash table
225 khint_t k = kh_get(64, d->hash, (uint64_t)tid<<32|pos);
226 if (k == kh_end(d->hash)) return 0;
227 proposed_indels = kh_val(d->hash, k);
229 // update d->ref if necessary
230 if (d->fai && (int)tid != d->tid) {
232 d->ref = faidx_fetch_seq(d->fai, d->h->target_name[tid], 0, 0x7fffffff, &d->len);
235 rb = (d->ref && (int)pos < d->len)? d->ref[pos] : 'N';
236 // when the indel-only mode is asked for, return if no reads mapped with indels
237 if (d->format & BAM_PLF_INDEL_ONLY) {
238 for (i = 0; i < n; ++i)
239 if (pu[i].indel != 0) break;
240 if (i == n) return 0;
242 // call the consensus and indel
243 if (d->format & BAM_PLF_CNS) { // call consensus
244 if (d->format & (BAM_PLF_RANBASE|BAM_PLF_1STBASE)) { // use a random base or the 1st base as the consensus call
245 const bam_pileup1_t *p = (d->format & BAM_PLF_1STBASE)? pu : pu + (int)(drand48() * n);
246 int q = bam1_qual(p->b)[p->qpos];
247 int mapQ = p->b->core.qual < d->c->cap_mapQ? p->b->core.qual : d->c->cap_mapQ;
248 uint32_t b = bam1_seqi(bam1_seq(p->b), p->qpos);
249 cns = b<<28 | 0xf<<24 | mapQ<<16 | q<<8;
250 } else if (d->format & BAM_PLF_ALLBASE) { // collapse all bases
253 for (i = 0; i < n; ++i) {
254 const bam_pileup1_t *p = pu + i;
255 int q = p->b->core.qual < d->c->cap_mapQ? p->b->core.qual : d->c->cap_mapQ;
256 b |= bam1_seqi(bam1_seq(p->b), p->qpos);
259 rmsQ = (uint64_t)(sqrt((double)rmsQ / n) + .499);
260 cns = b<<28 | 0xf<<24 | rmsQ<<16 | 60<<8;
262 glf1_t *g = bam_maqcns_glfgen(n, pu, bam_nt16_table[rb], d->c);
263 cns = g->depth == 0? (0xfu<<28 | 0xf<<24) : glf2cns(g, (int)(d->c->q_r + .499));
267 if ((d->format & (BAM_PLF_CNS|BAM_PLF_INDEL_ONLY)) && d->ref && pos < d->len) { // call indels
268 int m = (!d->max_depth || d->max_depth>n) ? n : d->max_depth;
269 if (proposed_indels) // the first element gives the size of the array
270 r = bam_maqindel(m, pos, d->ido, pu, d->ref, proposed_indels[0], proposed_indels+1);
271 else r = bam_maqindel(m, pos, d->ido, pu, d->ref, 0, 0);
273 // when only variant sites are asked for, test if the site is a variant
274 if ((d->format & BAM_PLF_CNS) && (d->format & BAM_PLF_VAR_ONLY)) {
275 if (!(bam_nt16_table[rb] != 15 && cns>>28 != 15 && cns>>28 != bam_nt16_table[rb])) { // not a SNP
276 if (!(r && (r->gt == 2 || strcmp(r->s[r->gt], "*")))) { // not an indel
277 if (r) bam_maqindel_ret_destroy(r);
282 // print the first 3 columns
283 fputs(d->h->target_name[tid], stdout); putchar('\t');
284 printw(pos+1, stdout); putchar('\t'); putchar(rb); putchar('\t');
285 // print consensus information if required
286 if (d->format & BAM_PLF_CNS) {
287 putchar(bam_nt16_rev_table[cns>>28]); putchar('\t');
288 printw(cns>>8&0xff, stdout); putchar('\t');
289 printw(cns&0xff, stdout); putchar('\t');
290 printw(cns>>16&0xff, stdout); putchar('\t');
292 // print pileup sequences
293 printw(n, stdout); putchar('\t');
294 for (i = 0; i < n; ++i)
295 pileup_seq(pu + i, pos, d->len, d->ref);
297 if (d->format & BAM_PLF_CNS) {
298 for (i = rms_aux = 0; i < n; ++i) {
299 const bam_pileup1_t *p = pu + i;
300 int tmp = p->b->core.qual < d->c->cap_mapQ? p->b->core.qual : d->c->cap_mapQ;
301 rms_aux += tmp * tmp;
303 rms_aux = (uint64_t)(sqrt((double)rms_aux / n) + .499);
304 if (rms_mapq < 0) rms_mapq = rms_aux;
308 for (i = 0; i < n; ++i) {
309 const bam_pileup1_t *p = pu + i;
310 int c = bam1_qual(p->b)[p->qpos] + 33;
311 if (c > 126) c = 126;
314 if (d->format & BAM_PLF_2ND) { // print 2nd calls and qualities
315 const unsigned char *q;
317 for (i = 0; i < n; ++i) {
318 const bam_pileup1_t *p = pu + i;
319 q = bam_aux_get(p->b, "E2");
320 putchar(q? q[p->qpos + 1] : 'N');
323 for (i = 0; i < n; ++i) {
324 const bam_pileup1_t *p = pu + i;
325 q = bam_aux_get(p->b, "U2");
326 putchar(q? q[p->qpos + 1] : '!');
329 // print mapping quality if -s is flagged on the command line
330 if (d->format & BAM_PLF_SIMPLE) {
332 for (i = 0; i < n; ++i) {
333 int c = pu[i].b->core.qual + 33;
334 if (c > 126) c = 126;
338 // print read position
339 if (d->format & BAM_PLF_READPOS) {
341 for (i = 0; i < n; ++i) {
343 int l = pu[i].b->core.l_qseq;
344 printw(x < l/2? x+1 : -((l-1)-x+1), stdout); putchar(',');
348 // print the indel line if r has been calculated. This only happens if:
349 // a) -c or -i are flagged, AND b) the reference sequence is available
351 printf("%s\t%d\t*\t", d->h->target_name[tid], pos + 1);
352 if (r->gt < 2) printf("%s/%s\t", r->s[r->gt], r->s[r->gt]);
353 else printf("%s/%s\t", r->s[0], r->s[1]);
354 printf("%d\t%d\t", r->q_cns, r->q_ref);
355 printf("%d\t%d\t", rms_mapq, n);
356 printf("%s\t%s\t", r->s[0], r->s[1]);
357 //printf("%d\t%d\t", r->gl[0], r->gl[1]);
358 printf("%d\t%d\t%d\t", r->cnt1, r->cnt2, r->cnt_anti);
359 printf("%d\t%d\n", r->cnt_ref, r->cnt_ambi);
360 bam_maqindel_ret_destroy(r);
365 int bam_pileup(int argc, char *argv[])
368 char *fn_list = 0, *fn_fa = 0, *fn_pos = 0;
369 pu_data_t *d = (pu_data_t*)calloc(1, sizeof(pu_data_t));
370 d->max_depth = 1024; d->tid = -1; d->mask = BAM_DEF_MASK; d->min_baseQ = 13;
371 d->c = bam_maqcns_init();
372 d->c->errmod = BAM_ERRMOD_MAQ2; // change the default model
373 d->ido = bam_maqindel_opt_init();
374 while ((c = getopt(argc, argv, "st:f:cT:N:r:l:d:im:gI:G:vM:S2aR:PAQ:C:B")) >= 0) {
376 case 'Q': d->c->min_baseQ = atoi(optarg); break;
377 case 'C': d->capQ_thres = atoi(optarg); break;
378 case 'B': d->format |= BAM_PLF_NOBAQ; break;
379 case 'a': d->c->errmod = BAM_ERRMOD_SOAP; break;
380 case 'A': d->c->errmod = BAM_ERRMOD_MAQ; break;
381 case 's': d->format |= BAM_PLF_SIMPLE; break;
382 case 't': fn_list = strdup(optarg); break;
383 case 'l': fn_pos = strdup(optarg); break;
384 case 'f': fn_fa = strdup(optarg); break;
385 case 'T': d->c->theta = atof(optarg); break;
386 case 'N': d->c->n_hap = atoi(optarg); break;
387 case 'r': d->c->het_rate = atof(optarg); d->ido->r_snp = d->c->het_rate; break;
388 case 'M': d->c->cap_mapQ = atoi(optarg); break;
389 case 'd': d->max_depth = atoi(optarg); break;
390 case 'c': d->format |= BAM_PLF_CNS; break;
391 case 'i': d->format |= BAM_PLF_INDEL_ONLY; break;
392 case 'v': d->format |= BAM_PLF_VAR_ONLY; break;
393 case 'm': d->mask = strtol(optarg, 0, 0); break;
394 case 'g': d->format |= BAM_PLF_GLF; break;
395 case '2': d->format |= BAM_PLF_2ND; break;
396 case 'P': d->format |= BAM_PLF_READPOS; break;
397 case 'I': d->ido->q_indel = atoi(optarg); break;
398 case 'G': d->ido->r_indel = atof(optarg); break;
399 case 'S': is_SAM = 1; break;
401 if (strcmp(optarg, "random") == 0) d->format |= BAM_PLF_RANBASE;
402 else if (strcmp(optarg, "first") == 0) d->format |= BAM_PLF_1STBASE;
403 else if (strcmp(optarg, "all") == 0) d->format |= BAM_PLF_ALLBASE;
404 else fprintf(stderr, "[bam_pileup] unrecognized -R\n");
406 default: fprintf(stderr, "Unrecognizd option '-%c'.\n", c); return 1;
409 if (d->c->errmod != BAM_ERRMOD_MAQ2) d->c->theta += 0.02;
410 if (d->c->theta > 1.0) d->c->theta = 1.0;
411 if (fn_list) is_SAM = 1;
412 if (optind == argc) {
413 fprintf(stderr, "\n");
414 fprintf(stderr, "Usage: samtools pileup [options] <in.bam>|<in.sam>\n\n");
415 fprintf(stderr, "Option: -s simple (yet incomplete) pileup format\n");
416 fprintf(stderr, " -S the input is in SAM\n");
417 fprintf(stderr, " -B disable BAQ computation\n");
418 fprintf(stderr, " -A use the original MAQ model for SNP calling (DEPRECATED)\n");
419 fprintf(stderr, " -2 output the 2nd best call and quality\n");
420 fprintf(stderr, " -i only show lines/consensus with indels\n");
421 fprintf(stderr, " -Q INT min base quality (possibly capped by BAQ) [%d]\n", d->c->min_baseQ);
422 fprintf(stderr, " -C INT coefficient for adjusting mapQ of poor mappings [%d]\n", d->capQ_thres);
423 fprintf(stderr, " -m INT filtering reads with bits in INT [0x%x]\n", d->mask);
424 fprintf(stderr, " -M INT cap mapping quality at INT [%d]\n", d->c->cap_mapQ);
425 fprintf(stderr, " -d INT limit maximum depth for indels [%d]\n", d->max_depth);
426 fprintf(stderr, " -t FILE list of reference sequences (force -S)\n");
427 fprintf(stderr, " -l FILE list of sites at which pileup is output\n");
428 fprintf(stderr, " -f FILE reference sequence in the FASTA format\n\n");
429 fprintf(stderr, " -c compute the consensus sequence\n");
430 fprintf(stderr, " -v print variants only (for -c)\n");
431 fprintf(stderr, " -g output in the GLFv3 format (DEPRECATED)\n");
432 fprintf(stderr, " -T FLOAT theta in maq consensus calling model (for -c) [%.4g]\n", d->c->theta);
433 fprintf(stderr, " -N INT number of haplotypes in the sample (for -c) [%d]\n", d->c->n_hap);
434 fprintf(stderr, " -r FLOAT prior of a difference between two haplotypes (for -c) [%.4g]\n", d->c->het_rate);
435 fprintf(stderr, " -G FLOAT prior of an indel between two haplotypes (for -c) [%.4g]\n", d->ido->r_indel);
436 fprintf(stderr, " -I INT phred prob. of an indel in sequencing/prep. (for -c) [%d]\n", d->ido->q_indel);
437 fprintf(stderr, "\n");
438 free(fn_list); free(fn_fa); free(d);
441 if (d->format & (BAM_PLF_RANBASE|BAM_PLF_1STBASE|BAM_PLF_ALLBASE)) d->format |= BAM_PLF_CNS;
442 if (fn_fa) d->fai = fai_load(fn_fa);
443 if (d->format & (BAM_PLF_CNS|BAM_PLF_GLF)) bam_maqcns_prepare(d->c); // consensus calling
444 if (d->format & BAM_PLF_GLF) { // for glf output
446 h = glf3_header_init();
447 d->fp_glf = bgzf_fdopen(fileno(stdout), "w");
448 glf3_header_write(d->fp_glf, h);
449 glf3_header_destroy(h);
451 if (d->fai == 0 && (d->format & (BAM_PLF_CNS|BAM_PLF_INDEL_ONLY)))
452 fprintf(stderr, "[bam_pileup] indels will not be called when -f is absent.\n");
453 if (fn_fa && is_SAM && fn_list == 0) fn_list = samfaipath(fn_fa);
457 fp = is_SAM? samopen(argv[optind], "r", fn_list) : samopen(argv[optind], "rb", 0);
458 if (fp == 0 || fp->header == 0) {
459 fprintf(stderr, "[bam_pileup] fail to read the header: non-exisiting file or wrong format.\n");
463 if (fn_pos) d->hash = load_pos(fn_pos, d->h);
465 extern int bam_prob_realn(bam1_t *b, const char *ref);
466 extern int bam_cap_mapQ(bam1_t *b, char *ref, int thres);
468 int ret, tid, pos, n_plp;
470 const bam_pileup1_t *plp;
472 iter = bam_plp_init(0, 0);
473 bam_plp_set_mask(iter, d->mask);
474 while ((ret = samread(fp, b)) >= 0) {
476 if ((int)b->core.tid < 0) break;
477 // update d->ref if necessary
478 if (d->fai && (int)b->core.tid != d->tid) {
480 d->ref = faidx_fetch_seq(d->fai, d->h->target_name[b->core.tid], 0, 0x7fffffff, &d->len);
481 d->tid = b->core.tid;
483 if (d->ref && (d->format&BAM_PLF_CNS) && !(d->format&BAM_PLF_NOBAQ)) bam_prob_realn(b, d->ref);
484 if (d->ref && (d->format&BAM_PLF_CNS) && d->capQ_thres > 10) {
485 int q = bam_cap_mapQ(b, d->ref, d->capQ_thres);
487 else if (b->core.qual > q) b->core.qual = q;
488 } else if (b->core.flag&BAM_FUNMAP) skip = 1;
489 else if ((d->format&BAM_PLF_CNS) && (b->core.flag&1) && !(b->core.flag&2)) skip = 1;
491 bam_plp_push(iter, b);
492 while ((plp = bam_plp_next(iter, &tid, &pos, &n_plp)) != 0)
493 pileup_func(tid, pos, n_plp, plp, d);
495 bam_plp_push(iter, 0);
496 while ((plp = bam_plp_next(iter, &tid, &pos, &n_plp)) != 0)
497 pileup_func(tid, pos, n_plp, plp, d);
498 bam_plp_destroy(iter);
501 samclose(fp); // d->h will be destroyed here
505 if (d->format & BAM_PLF_GLF) bgzf_close(d->fp_glf);
506 if (fn_pos) { // free the hash table
508 for (k = kh_begin(d->hash); k < kh_end(d->hash); ++k)
509 if (kh_exist(d->hash, k)) free(kh_val(d->hash, k));
510 kh_destroy(64, d->hash);
512 free(fn_pos); free(fn_list); free(fn_fa);
513 if (d->fai) fai_destroy(d->fai);
514 bam_maqcns_destroy(d->c);
515 free(d->ido); free(d->ref); free(d);
527 #define MPLP_GLF 0x10
528 #define MPLP_NO_COMP 0x20
529 #define MPLP_NO_ORPHAN 0x40
530 #define MPLP_REALN 0x80
531 #define MPLP_SAMINFO 0x100
534 int max_mq, min_mq, flag, min_baseQ, capQ_thres;
543 int min_mq, flag, ref_id, capQ_thres;
553 static int mplp_func(void *data, bam1_t *b)
555 extern int bam_realn(bam1_t *b, const char *ref);
556 extern int bam_prob_realn(bam1_t *b, const char *ref);
557 extern int bam_cap_mapQ(bam1_t *b, char *ref, int thres);
558 mplp_aux_t *ma = (mplp_aux_t*)data;
561 int has_ref = (ma->ref && ma->ref_id == b->core.tid)? 1 : 0;
562 ret = ma->iter? bam_iter_read(ma->fp, ma->iter, b) : bam_read1(ma->fp, b);
565 if (has_ref && (ma->flag&MPLP_REALN)) bam_prob_realn(b, ma->ref);
566 if (has_ref && ma->capQ_thres > 10) {
567 int q = bam_cap_mapQ(b, ma->ref, ma->capQ_thres);
569 else if (b->core.qual > q) b->core.qual = q;
570 } else if (b->core.flag&BAM_FUNMAP) skip = 1;
571 else if (b->core.qual < ma->min_mq) skip = 1;
572 else if ((ma->flag&MPLP_NO_ORPHAN) && (b->core.flag&1) && !(b->core.flag&2)) skip = 1;
577 static void group_smpl(mplp_pileup_t *m, bam_sample_t *sm, kstring_t *buf,
578 int n, char *const*fn, int *n_plp, const bam_pileup1_t **plp)
581 memset(m->n_plp, 0, m->n * sizeof(int));
582 for (i = 0; i < n; ++i) {
583 for (j = 0; j < n_plp[i]; ++j) {
584 const bam_pileup1_t *p = plp[i] + j;
587 q = bam_aux_get(p->b, "RG");
588 if (q) id = bam_smpl_rg2smid(sm, fn[i], (char*)q+1, buf);
589 if (id < 0) id = bam_smpl_rg2smid(sm, fn[i], 0, buf);
590 assert(id >= 0 && id < m->n);
591 if (m->n_plp[id] == m->m_plp[id]) {
592 m->m_plp[id] = m->m_plp[id]? m->m_plp[id]<<1 : 8;
593 m->plp[id] = realloc(m->plp[id], sizeof(bam_pileup1_t) * m->m_plp[id]);
595 m->plp[id][m->n_plp[id]++] = *p;
600 static int mpileup(mplp_conf_t *conf, int n, char **fn)
603 int i, tid, pos, *n_plp, beg0 = 0, end0 = 1u<<29, ref_len, ref_tid;
604 const bam_pileup1_t **plp;
608 khash_t(64) *hash = 0;
610 bcf_callaux_t *bca = 0;
611 bcf_callret1_t *bcr = 0;
616 bam_sample_t *sm = 0;
620 memset(&gplp, 0, sizeof(mplp_pileup_t));
621 memset(&buf, 0, sizeof(kstring_t));
622 memset(&bc, 0, sizeof(bcf_call_t));
623 data = calloc(n, sizeof(void*));
624 plp = calloc(n, sizeof(void*));
625 n_plp = calloc(n, sizeof(int*));
626 sm = bam_smpl_init();
628 // read the header and initialize data
629 for (i = 0; i < n; ++i) {
631 data[i] = calloc(1, sizeof(mplp_aux_t));
632 data[i]->min_mq = conf->min_mq;
633 data[i]->flag = conf->flag;
634 data[i]->capQ_thres = conf->capQ_thres;
635 data[i]->fp = strcmp(fn[i], "-") == 0? bam_dopen(fileno(stdin), "r") : bam_open(fn[i], "r");
636 h_tmp = bam_header_read(data[i]->fp);
637 bam_smpl_add(sm, fn[i], h_tmp->text);
641 idx = bam_index_load(fn[i]);
643 fprintf(stderr, "[%s] fail to load index for %d-th input.\n", __func__, i+1);
646 if (bam_parse_region(h_tmp, conf->reg, &tid, &beg, &end) < 0) {
647 fprintf(stderr, "[%s] malformatted region or wrong seqname for %d-th input.\n", __func__, i+1);
650 if (i == 0) beg0 = beg, end0 = end;
651 data[i]->iter = bam_iter_query(idx, tid, beg, end);
652 bam_index_destroy(idx);
654 if (i == 0) h = h_tmp;
656 // FIXME: to check consistency
657 bam_header_destroy(h_tmp);
661 gplp.n_plp = calloc(sm->n, sizeof(int));
662 gplp.m_plp = calloc(sm->n, sizeof(int));
663 gplp.plp = calloc(sm->n, sizeof(void*));
665 fprintf(stderr, "[%s] %d samples in %d input files\n", __func__, sm->n, n);
666 if (conf->fn_pos) hash = load_pos(conf->fn_pos, h);
667 // write the VCF header
668 if (conf->flag & MPLP_GLF) {
670 bh = calloc(1, sizeof(bcf_hdr_t));
671 s.l = s.m = 0; s.s = 0;
672 bp = bcf_open("-", (conf->flag&MPLP_NO_COMP)? "wu" : "w");
673 for (i = 0; i < h->n_targets; ++i) {
674 kputs(h->target_name[i], &s);
678 bh->name = malloc(s.l);
679 memcpy(bh->name, s.s, s.l);
681 for (i = 0; i < sm->n; ++i) {
682 kputs(sm->smpl[i], &s); kputc('\0', &s);
685 bh->sname = malloc(s.l);
686 memcpy(bh->sname, s.s, s.l);
690 bcf_hdr_write(bp, bh);
691 bca = bcf_call_init(-1., conf->min_baseQ);
692 bcr = calloc(sm->n, sizeof(bcf_callret1_t));
694 ref_tid = -1; ref = 0;
695 iter = bam_mplp_init(n, mplp_func, (void**)data);
696 while (bam_mplp_auto(iter, &tid, &pos, n_plp, plp) > 0) {
697 if (conf->reg && (pos < beg0 || pos >= end0)) continue; // out of the region requested
700 k = kh_get(64, hash, (uint64_t)tid<<32 | pos);
701 if (k == kh_end(hash)) continue;
703 if (tid != ref_tid) {
705 if (conf->fai) ref = fai_fetch(conf->fai, h->target_name[tid], &ref_len);
706 for (i = 0; i < n; ++i) data[i]->ref = ref, data[i]->ref_id = tid;
709 if (conf->flag & MPLP_GLF) {
711 bcf1_t *b = calloc(1, sizeof(bcf1_t));
712 group_smpl(&gplp, sm, &buf, n, fn, n_plp, plp);
713 _ref0 = (ref && pos < ref_len)? ref[pos] : 'N';
714 ref16 = bam_nt16_table[_ref0];
715 for (i = 0; i < gplp.n; ++i)
716 bcf_call_glfgen(gplp.n_plp[i], gplp.plp[i], ref16, bca, bcr + i);
717 bcf_call_combine(gplp.n, bcr, ref16, &bc);
718 bcf_call2bcf(tid, pos, &bc, b, (conf->flag&MPLP_SAMINFO)? bcr : 0);
719 bcf_write(bp, bh, b);
722 printf("%s\t%d\t%c", h->target_name[tid], pos + 1, (ref && pos < ref_len)? ref[pos] : 'N');
723 for (i = 0; i < n; ++i) {
725 printf("\t%d\t", n_plp[i]);
726 if (n_plp[i] == 0) printf("*\t*");
728 for (j = 0; j < n_plp[i]; ++j)
729 pileup_seq(plp[i] + j, pos, ref_len, ref);
731 for (j = 0; j < n_plp[i]; ++j) {
732 const bam_pileup1_t *p = plp[i] + j;
733 int c = bam1_qual(p->b)[p->qpos] + 33;
734 if (c > 126) c = 126;
744 bam_smpl_destroy(sm); free(buf.s);
745 for (i = 0; i < gplp.n; ++i) free(gplp.plp[i]);
746 free(gplp.plp); free(gplp.n_plp); free(gplp.m_plp);
747 if (hash) { // free the hash table
749 for (k = kh_begin(hash); k < kh_end(hash); ++k)
750 if (kh_exist(hash, k)) free(kh_val(hash, k));
751 kh_destroy(64, hash);
753 bcf_hdr_destroy(bh); bcf_call_destroy(bca); free(bc.PL); free(bcr);
754 bam_mplp_destroy(iter);
755 bam_header_destroy(h);
756 for (i = 0; i < n; ++i) {
757 bam_close(data[i]->fp);
758 if (data[i]->iter) bam_iter_destroy(data[i]->iter);
761 free(data); free(plp); free(ref); free(n_plp);
765 int bam_mpileup(int argc, char *argv[])
769 memset(&mplp, 0, sizeof(mplp_conf_t));
773 mplp.flag = MPLP_NO_ORPHAN | MPLP_REALN;
774 while ((c = getopt(argc, argv, "gf:r:l:M:q:Q:uaORC:BI")) >= 0) {
777 mplp.fai = fai_load(optarg);
778 if (mplp.fai == 0) return 1;
780 case 'r': mplp.reg = strdup(optarg); break;
781 case 'l': mplp.fn_pos = strdup(optarg); break;
782 case 'g': mplp.flag |= MPLP_GLF; break;
783 case 'u': mplp.flag |= MPLP_NO_COMP | MPLP_GLF; break;
784 case 'a': mplp.flag |= MPLP_NO_ORPHAN | MPLP_REALN; break;
785 case 'B': mplp.flag &= ~MPLP_REALN & ~MPLP_NO_ORPHAN; break;
786 case 'O': mplp.flag |= MPLP_NO_ORPHAN; break;
787 case 'R': mplp.flag |= MPLP_REALN; break;
788 case 'I': mplp.flag |= MPLP_SAMINFO; break;
789 case 'C': mplp.capQ_thres = atoi(optarg); break;
790 case 'M': mplp.max_mq = atoi(optarg); break;
791 case 'q': mplp.min_mq = atoi(optarg); break;
792 case 'Q': mplp.min_baseQ = atoi(optarg); break;
796 fprintf(stderr, "\n");
797 fprintf(stderr, "Usage: samtools mpileup [options] in1.bam [in2.bam [...]]\n\n");
798 fprintf(stderr, "Options: -f FILE reference sequence file [null]\n");
799 fprintf(stderr, " -r STR region in which pileup is generated [null]\n");
800 fprintf(stderr, " -l FILE list of positions (format: chr pos) [null]\n");
801 fprintf(stderr, " -M INT cap mapping quality at INT [%d]\n", mplp.max_mq);
802 fprintf(stderr, " -Q INT min base quality [%d]\n", mplp.min_baseQ);
803 fprintf(stderr, " -q INT filter out alignment with MQ smaller than INT [%d]\n", mplp.min_mq);
804 fprintf(stderr, " -g generate BCF output\n");
805 fprintf(stderr, " -u do not compress BCF output\n");
806 fprintf(stderr, " -B disable BAQ computation\n");
807 fprintf(stderr, " -I additional individual information (DP and ST)\n");
808 fprintf(stderr, "\n");
809 fprintf(stderr, "Notes: Assuming diploid individuals.\n\n");
812 mpileup(&mplp, argc - optind, argv + optind);
814 if (mplp.fai) fai_destroy(mplp.fai);