11 #include "bam_maqcns.h"
16 typedef int *indel_list_t;
17 KHASH_MAP_INIT_INT64(64, indel_list_t)
19 #define BAM_PLF_SIMPLE 0x01
20 #define BAM_PLF_CNS 0x02
21 #define BAM_PLF_INDEL_ONLY 0x04
22 #define BAM_PLF_GLF 0x08
23 #define BAM_PLF_VAR_ONLY 0x10
24 #define BAM_PLF_2ND 0x20
25 #define BAM_PLF_RANBASE 0x40
26 #define BAM_PLF_1STBASE 0x80
27 #define BAM_PLF_ALLBASE 0x100
28 #define BAM_PLF_READPOS 0x200
29 #define BAM_PLF_NOBAQ 0x400
34 bam_maqindel_opt_t *ido;
38 int tid, len, last_pos;
40 int capQ_thres, min_baseQ;
41 int max_depth; // for indel calling, ignore reads with the depth too high. 0 for unlimited
43 glfFile fp_glf; // for glf output only
46 char **__bam_get_lines(const char *fn, int *_n);
47 void bam_init_header_hash(bam_header_t *header);
48 int32_t bam_get_tid(const bam_header_t *header, const char *seq_name);
50 static khash_t(64) *load_pos(const char *fn, bam_header_t *h)
53 int i, j, n, *fields, max_fields;
55 bam_init_header_hash(h);
56 list = __bam_get_lines(fn, &n);
58 max_fields = 0; fields = 0;
59 for (i = 0; i < n; ++i) {
61 int chr, n_fields, ret;
64 n_fields = ksplit_core(str, 0, &max_fields, &fields);
65 if (n_fields < 2) continue;
66 chr = bam_get_tid(h, str + fields[0]);
68 fprintf(pysamerr, "[load_pos] unknown reference sequence name: %s\n", str + fields[0]);
71 x = (uint64_t)chr << 32 | (atoi(str + fields[1]) - 1);
72 k = kh_put(64, hash, x, &ret);
74 fprintf(pysamerr, "[load_pos] position %s:%s has been loaded.\n", str+fields[0], str+fields[1]);
80 for (j = 2; j < n_fields; ++j) {
81 char *s = str + fields[j];
82 if ((*s != '+' && *s != '-') || !isdigit(s[1])) break;
84 if (j > 2) { // update kh_val()
86 q = kh_val(hash, k) = (int*)calloc(j - 1, sizeof(int));
87 q[0] = j - 2; z = j; y = 1;
88 for (j = 2; j < z; ++j)
89 q[y++] = atoi(str + fields[j]);
94 free(list); free(fields);
98 static inline int printw(int c, FILE *fp)
102 if (c == 0) return fputc('0', fp);
103 for (l = 0, x = c < 0? -c : c; x > 0; x /= 10) buf[l++] = x%10 + '0';
104 if (c < 0) buf[l++] = '-';
106 for (x = 0; x < l/2; ++x) {
107 int y = buf[x]; buf[x] = buf[l-1-x]; buf[l-1-x] = y;
113 // an analogy to pileup_func() below
114 static int glt3_func(uint32_t tid, uint32_t pos, int n, const bam_pileup1_t *pu, void *data)
116 pu_data_t *d = (pu_data_t*)data;
117 bam_maqindel_ret_t *r = 0;
118 int rb, *proposed_indels = 0;
123 fprintf(pysamerr, "[glt3_func] reference sequence is required for generating GLT. Abort!\n");
126 if (d->hash) { // only output a list of sites
127 khint_t k = kh_get(64, d->hash, (uint64_t)tid<<32|pos);
128 if (k == kh_end(d->hash)) return 0;
129 proposed_indels = kh_val(d->hash, k);
132 if (d->fai && (int)tid != d->tid) {
133 if (d->ref) { // then write the end mark
134 g3->rtype = GLF3_RTYPE_END;
135 glf3_write1(d->fp_glf, g3);
137 glf3_ref_write(d->fp_glf, d->h->target_name[tid], d->h->target_len[tid]); // write reference
139 d->ref = fai_fetch(d->fai, d->h->target_name[tid], &d->len);
143 rb = (d->ref && (int)pos < d->len)? d->ref[pos] : 'N';
144 g = bam_maqcns_glfgen(n, pu, bam_nt16_table[rb], d->c);
145 memcpy(g3, g, sizeof(glf1_t));
146 g3->rtype = GLF3_RTYPE_SUB;
147 g3->offset = pos - d->last_pos;
149 glf3_write1(d->fp_glf, g3);
151 int m = (!d->max_depth || d->max_depth>n) ? n : d->max_depth;
153 r = bam_maqindel(m, pos, d->ido, pu, d->ref, proposed_indels[0], proposed_indels+1);
154 else r = bam_maqindel(m, pos, d->ido, pu, d->ref, 0, 0);
156 if (r) { // then write indel line
157 int het = 3 * n, min;
159 if (min > r->gl[0]) min = r->gl[0];
160 if (min > r->gl[1]) min = r->gl[1];
162 g3->rtype = GLF3_RTYPE_INDEL;
163 memset(g3->lk, 0, 10);
164 g3->lk[0] = r->gl[0] - min < 255? r->gl[0] - min : 255;
165 g3->lk[1] = r->gl[1] - min < 255? r->gl[1] - min : 255;
166 g3->lk[2] = het - min < 255? het - min : 255;
168 g3->indel_len[0] = r->indel1;
169 g3->indel_len[1] = r->indel2;
170 g3->min_lk = min < 255? min : 255;
171 g3->max_len = (abs(r->indel1) > abs(r->indel2)? abs(r->indel1) : abs(r->indel2)) + 1;
172 g3->indel_seq[0] = strdup(r->s[0]+1);
173 g3->indel_seq[1] = strdup(r->s[1]+1);
174 glf3_write1(d->fp_glf, g3);
175 bam_maqindel_ret_destroy(r);
182 static inline void pileup_seq(const bam_pileup1_t *p, int pos, int ref_len, const char *ref)
187 putchar(p->b->core.qual > 93? 126 : p->b->core.qual + 33);
190 int c = bam_nt16_rev_table[bam1_seqi(bam1_seq(p->b), p->qpos)];
192 int rb = pos < ref_len? ref[pos] : 'N';
193 if (c == '=' || bam_nt16_table[c] == bam_nt16_table[rb]) c = bam1_strand(p->b)? ',' : '.';
194 else c = bam1_strand(p->b)? tolower(c) : toupper(c);
196 if (c == '=') c = bam1_strand(p->b)? ',' : '.';
197 else c = bam1_strand(p->b)? tolower(c) : toupper(c);
200 } else putchar(p->is_refskip? (bam1_strand(p->b)? '<' : '>') : '*');
202 putchar('+'); printw(p->indel, stdout);
203 for (j = 1; j <= p->indel; ++j) {
204 int c = bam_nt16_rev_table[bam1_seqi(bam1_seq(p->b), p->qpos + j)];
205 putchar(bam1_strand(p->b)? tolower(c) : toupper(c));
207 } else if (p->indel < 0) {
208 printw(p->indel, stdout);
209 for (j = 1; j <= -p->indel; ++j) {
210 int c = (ref && (int)pos+j < ref_len)? ref[pos+j] : 'N';
211 putchar(bam1_strand(p->b)? tolower(c) : toupper(c));
214 if (p->is_tail) putchar('$');
217 static int pileup_func(uint32_t tid, uint32_t pos, int n, const bam_pileup1_t *pu, void *data)
219 pu_data_t *d = (pu_data_t*)data;
220 bam_maqindel_ret_t *r = 0;
221 int i, rb, rms_mapq = -1, *proposed_indels = 0;
225 // if GLF is required, suppress -c completely
226 if (d->format & BAM_PLF_GLF) return glt3_func(tid, pos, n, pu, data);
227 // if d->hash is initialized, only output the sites in the hash table
229 khint_t k = kh_get(64, d->hash, (uint64_t)tid<<32|pos);
230 if (k == kh_end(d->hash)) return 0;
231 proposed_indels = kh_val(d->hash, k);
233 // update d->ref if necessary
234 if (d->fai && (int)tid != d->tid) {
236 d->ref = faidx_fetch_seq(d->fai, d->h->target_name[tid], 0, 0x7fffffff, &d->len);
239 rb = (d->ref && (int)pos < d->len)? d->ref[pos] : 'N';
240 // when the indel-only mode is asked for, return if no reads mapped with indels
241 if (d->format & BAM_PLF_INDEL_ONLY) {
242 for (i = 0; i < n; ++i)
243 if (pu[i].indel != 0) break;
244 if (i == n) return 0;
246 // call the consensus and indel
247 if (d->format & BAM_PLF_CNS) { // call consensus
248 if (d->format & (BAM_PLF_RANBASE|BAM_PLF_1STBASE)) { // use a random base or the 1st base as the consensus call
249 const bam_pileup1_t *p = (d->format & BAM_PLF_1STBASE)? pu : pu + (int)(drand48() * n);
250 int q = bam1_qual(p->b)[p->qpos];
251 int mapQ = p->b->core.qual < d->c->cap_mapQ? p->b->core.qual : d->c->cap_mapQ;
252 uint32_t b = bam1_seqi(bam1_seq(p->b), p->qpos);
253 cns = b<<28 | 0xf<<24 | mapQ<<16 | q<<8;
254 } else if (d->format & BAM_PLF_ALLBASE) { // collapse all bases
257 for (i = 0; i < n; ++i) {
258 const bam_pileup1_t *p = pu + i;
259 int q = p->b->core.qual < d->c->cap_mapQ? p->b->core.qual : d->c->cap_mapQ;
260 b |= bam1_seqi(bam1_seq(p->b), p->qpos);
263 rmsQ = (uint64_t)(sqrt((double)rmsQ / n) + .499);
264 cns = b<<28 | 0xf<<24 | rmsQ<<16 | 60<<8;
266 glf1_t *g = bam_maqcns_glfgen(n, pu, bam_nt16_table[rb], d->c);
267 cns = g->depth == 0? (0xfu<<28 | 0xf<<24) : glf2cns(g, (int)(d->c->q_r + .499));
271 if ((d->format & (BAM_PLF_CNS|BAM_PLF_INDEL_ONLY)) && d->ref && pos < d->len) { // call indels
272 int m = (!d->max_depth || d->max_depth>n) ? n : d->max_depth;
273 if (proposed_indels) // the first element gives the size of the array
274 r = bam_maqindel(m, pos, d->ido, pu, d->ref, proposed_indels[0], proposed_indels+1);
275 else r = bam_maqindel(m, pos, d->ido, pu, d->ref, 0, 0);
277 // when only variant sites are asked for, test if the site is a variant
278 if ((d->format & BAM_PLF_CNS) && (d->format & BAM_PLF_VAR_ONLY)) {
279 if (!(bam_nt16_table[rb] != 15 && cns>>28 != 15 && cns>>28 != bam_nt16_table[rb])) { // not a SNP
280 if (!(r && (r->gt == 2 || strcmp(r->s[r->gt], "*")))) { // not an indel
281 if (r) bam_maqindel_ret_destroy(r);
286 // print the first 3 columns
287 fputs(d->h->target_name[tid], stdout); putchar('\t');
288 printw(pos+1, stdout); putchar('\t'); putchar(rb); putchar('\t');
289 // print consensus information if required
290 if (d->format & BAM_PLF_CNS) {
291 putchar(bam_nt16_rev_table[cns>>28]); putchar('\t');
292 printw(cns>>8&0xff, stdout); putchar('\t');
293 printw(cns&0xff, stdout); putchar('\t');
294 printw(cns>>16&0xff, stdout); putchar('\t');
296 // print pileup sequences
297 printw(n, stdout); putchar('\t');
298 for (i = 0; i < n; ++i)
299 pileup_seq(pu + i, pos, d->len, d->ref);
301 if (d->format & BAM_PLF_CNS) {
302 for (i = rms_aux = 0; i < n; ++i) {
303 const bam_pileup1_t *p = pu + i;
304 int tmp = p->b->core.qual < d->c->cap_mapQ? p->b->core.qual : d->c->cap_mapQ;
305 rms_aux += tmp * tmp;
307 rms_aux = (uint64_t)(sqrt((double)rms_aux / n) + .499);
308 if (rms_mapq < 0) rms_mapq = rms_aux;
312 for (i = 0; i < n; ++i) {
313 const bam_pileup1_t *p = pu + i;
314 int c = bam1_qual(p->b)[p->qpos] + 33;
315 if (c > 126) c = 126;
318 if (d->format & BAM_PLF_2ND) { // print 2nd calls and qualities
319 const unsigned char *q;
321 for (i = 0; i < n; ++i) {
322 const bam_pileup1_t *p = pu + i;
323 q = bam_aux_get(p->b, "E2");
324 putchar(q? q[p->qpos + 1] : 'N');
327 for (i = 0; i < n; ++i) {
328 const bam_pileup1_t *p = pu + i;
329 q = bam_aux_get(p->b, "U2");
330 putchar(q? q[p->qpos + 1] : '!');
333 // print mapping quality if -s is flagged on the command line
334 if (d->format & BAM_PLF_SIMPLE) {
336 for (i = 0; i < n; ++i) {
337 int c = pu[i].b->core.qual + 33;
338 if (c > 126) c = 126;
342 // print read position
343 if (d->format & BAM_PLF_READPOS) {
345 for (i = 0; i < n; ++i) {
347 int l = pu[i].b->core.l_qseq;
348 printw(x < l/2? x+1 : -((l-1)-x+1), stdout); putchar(',');
352 // print the indel line if r has been calculated. This only happens if:
353 // a) -c or -i are flagged, AND b) the reference sequence is available
355 printf("%s\t%d\t*\t", d->h->target_name[tid], pos + 1);
356 if (r->gt < 2) printf("%s/%s\t", r->s[r->gt], r->s[r->gt]);
357 else printf("%s/%s\t", r->s[0], r->s[1]);
358 printf("%d\t%d\t", r->q_cns, r->q_ref);
359 printf("%d\t%d\t", rms_mapq, n);
360 printf("%s\t%s\t", r->s[0], r->s[1]);
361 //printf("%d\t%d\t", r->gl[0], r->gl[1]);
362 printf("%d\t%d\t%d\t", r->cnt1, r->cnt2, r->cnt_anti);
363 printf("%d\t%d\n", r->cnt_ref, r->cnt_ambi);
364 bam_maqindel_ret_destroy(r);
369 int bam_pileup(int argc, char *argv[])
372 char *fn_list = 0, *fn_fa = 0, *fn_pos = 0;
373 pu_data_t *d = (pu_data_t*)calloc(1, sizeof(pu_data_t));
374 d->max_depth = 1024; d->tid = -1; d->mask = BAM_DEF_MASK; d->min_baseQ = 13;
375 d->c = bam_maqcns_init();
376 d->c->errmod = BAM_ERRMOD_MAQ2; // change the default model
377 d->ido = bam_maqindel_opt_init();
378 while ((c = getopt(argc, argv, "st:f:cT:N:r:l:d:im:gI:G:vM:S2aR:PAQ:C:B")) >= 0) {
380 case 'Q': d->c->min_baseQ = atoi(optarg); break;
381 case 'C': d->capQ_thres = atoi(optarg); break;
382 case 'B': d->format |= BAM_PLF_NOBAQ; break;
383 case 'a': d->c->errmod = BAM_ERRMOD_SOAP; break;
384 case 'A': d->c->errmod = BAM_ERRMOD_MAQ; break;
385 case 's': d->format |= BAM_PLF_SIMPLE; break;
386 case 't': fn_list = strdup(optarg); break;
387 case 'l': fn_pos = strdup(optarg); break;
388 case 'f': fn_fa = strdup(optarg); break;
389 case 'T': d->c->theta = atof(optarg); break;
390 case 'N': d->c->n_hap = atoi(optarg); break;
391 case 'r': d->c->het_rate = atof(optarg); d->ido->r_snp = d->c->het_rate; break;
392 case 'M': d->c->cap_mapQ = atoi(optarg); break;
393 case 'd': d->max_depth = atoi(optarg); break;
394 case 'c': d->format |= BAM_PLF_CNS; break;
395 case 'i': d->format |= BAM_PLF_INDEL_ONLY; break;
396 case 'v': d->format |= BAM_PLF_VAR_ONLY; break;
397 case 'm': d->mask = strtol(optarg, 0, 0); break;
398 case 'g': d->format |= BAM_PLF_GLF; break;
399 case '2': d->format |= BAM_PLF_2ND; break;
400 case 'P': d->format |= BAM_PLF_READPOS; break;
401 case 'I': d->ido->q_indel = atoi(optarg); break;
402 case 'G': d->ido->r_indel = atof(optarg); break;
403 case 'S': is_SAM = 1; break;
405 if (strcmp(optarg, "random") == 0) d->format |= BAM_PLF_RANBASE;
406 else if (strcmp(optarg, "first") == 0) d->format |= BAM_PLF_1STBASE;
407 else if (strcmp(optarg, "all") == 0) d->format |= BAM_PLF_ALLBASE;
408 else fprintf(pysamerr, "[bam_pileup] unrecognized -R\n");
410 default: fprintf(pysamerr, "Unrecognizd option '-%c'.\n", c); return 1;
413 if (d->c->errmod != BAM_ERRMOD_MAQ2) d->c->theta += 0.02;
414 if (d->c->theta > 1.0) d->c->theta = 1.0;
415 if (fn_list) is_SAM = 1;
416 if (optind == argc) {
417 fprintf(pysamerr, "\n");
418 fprintf(pysamerr, "Usage: samtools pileup [options] <in.bam>|<in.sam>\n\n");
419 fprintf(pysamerr, "Option: -s simple (yet incomplete) pileup format\n");
420 fprintf(pysamerr, " -S the input is in SAM\n");
421 fprintf(pysamerr, " -B disable BAQ computation\n");
422 fprintf(pysamerr, " -A use the original MAQ model for SNP calling (DEPRECATED)\n");
423 fprintf(pysamerr, " -2 output the 2nd best call and quality\n");
424 fprintf(pysamerr, " -i only show lines/consensus with indels\n");
425 fprintf(pysamerr, " -Q INT min base quality (possibly capped by BAQ) [%d]\n", d->c->min_baseQ);
426 fprintf(pysamerr, " -C INT coefficient for adjusting mapQ of poor mappings [%d]\n", d->capQ_thres);
427 fprintf(pysamerr, " -m INT filtering reads with bits in INT [0x%x]\n", d->mask);
428 fprintf(pysamerr, " -M INT cap mapping quality at INT [%d]\n", d->c->cap_mapQ);
429 fprintf(pysamerr, " -d INT limit maximum depth for indels [%d]\n", d->max_depth);
430 fprintf(pysamerr, " -t FILE list of reference sequences (force -S)\n");
431 fprintf(pysamerr, " -l FILE list of sites at which pileup is output\n");
432 fprintf(pysamerr, " -f FILE reference sequence in the FASTA format\n\n");
433 fprintf(pysamerr, " -c compute the consensus sequence\n");
434 fprintf(pysamerr, " -v print variants only (for -c)\n");
435 fprintf(pysamerr, " -g output in the GLFv3 format (DEPRECATED)\n");
436 fprintf(pysamerr, " -T FLOAT theta in maq consensus calling model (for -c) [%.4g]\n", d->c->theta);
437 fprintf(pysamerr, " -N INT number of haplotypes in the sample (for -c) [%d]\n", d->c->n_hap);
438 fprintf(pysamerr, " -r FLOAT prior of a difference between two haplotypes (for -c) [%.4g]\n", d->c->het_rate);
439 fprintf(pysamerr, " -G FLOAT prior of an indel between two haplotypes (for -c) [%.4g]\n", d->ido->r_indel);
440 fprintf(pysamerr, " -I INT phred prob. of an indel in sequencing/prep. (for -c) [%d]\n", d->ido->q_indel);
441 fprintf(pysamerr, "\n");
442 fprintf(pysamerr, "Warning: Please use the `mpileup' command instead `pileup'. `Pileup' is deprecated!\n\n");
443 free(fn_list); free(fn_fa); free(d);
446 if (d->format & (BAM_PLF_RANBASE|BAM_PLF_1STBASE|BAM_PLF_ALLBASE)) d->format |= BAM_PLF_CNS;
447 if (fn_fa) d->fai = fai_load(fn_fa);
448 if (d->format & (BAM_PLF_CNS|BAM_PLF_GLF)) bam_maqcns_prepare(d->c); // consensus calling
449 if (d->format & BAM_PLF_GLF) { // for glf output
451 h = glf3_header_init();
452 d->fp_glf = bgzf_fdopen(fileno(stdout), "w");
453 glf3_header_write(d->fp_glf, h);
454 glf3_header_destroy(h);
456 if (d->fai == 0 && (d->format & (BAM_PLF_CNS|BAM_PLF_INDEL_ONLY)))
457 fprintf(pysamerr, "[bam_pileup] indels will not be called when -f is absent.\n");
458 if (fn_fa && is_SAM && fn_list == 0) fn_list = samfaipath(fn_fa);
462 fp = is_SAM? samopen(argv[optind], "r", fn_list) : samopen(argv[optind], "rb", 0);
463 if (fp == 0 || fp->header == 0) {
464 fprintf(pysamerr, "[bam_pileup] fail to read the header: non-exisiting file or wrong format.\n");
468 if (fn_pos) d->hash = load_pos(fn_pos, d->h);
470 extern int bam_prob_realn(bam1_t *b, const char *ref);
471 extern int bam_cap_mapQ(bam1_t *b, char *ref, int thres);
473 int ret, tid, pos, n_plp;
475 const bam_pileup1_t *plp;
477 iter = bam_plp_init(0, 0);
478 bam_plp_set_mask(iter, d->mask);
479 while ((ret = samread(fp, b)) >= 0) {
481 if ((int)b->core.tid < 0) break;
482 // update d->ref if necessary
483 if (d->fai && (int)b->core.tid != d->tid) {
485 d->ref = faidx_fetch_seq(d->fai, d->h->target_name[b->core.tid], 0, 0x7fffffff, &d->len);
486 d->tid = b->core.tid;
488 if (d->ref && (d->format&BAM_PLF_CNS) && !(d->format&BAM_PLF_NOBAQ)) bam_prob_realn(b, d->ref);
489 if (d->ref && (d->format&BAM_PLF_CNS) && d->capQ_thres > 10) {
490 int q = bam_cap_mapQ(b, d->ref, d->capQ_thres);
492 else if (b->core.qual > q) b->core.qual = q;
493 } else if (b->core.flag&BAM_FUNMAP) skip = 1;
494 else if ((d->format&BAM_PLF_CNS) && (b->core.flag&1) && !(b->core.flag&2)) skip = 1;
496 bam_plp_push(iter, b);
497 while ((plp = bam_plp_next(iter, &tid, &pos, &n_plp)) != 0)
498 pileup_func(tid, pos, n_plp, plp, d);
500 bam_plp_push(iter, 0);
501 while ((plp = bam_plp_next(iter, &tid, &pos, &n_plp)) != 0)
502 pileup_func(tid, pos, n_plp, plp, d);
503 bam_plp_destroy(iter);
506 samclose(fp); // d->h will be destroyed here
510 if (d->format & BAM_PLF_GLF) bgzf_close(d->fp_glf);
511 if (fn_pos) { // free the hash table
513 for (k = kh_begin(d->hash); k < kh_end(d->hash); ++k)
514 if (kh_exist(d->hash, k)) free(kh_val(d->hash, k));
515 kh_destroy(64, d->hash);
517 free(fn_pos); free(fn_list); free(fn_fa);
518 if (d->fai) fai_destroy(d->fai);
519 bam_maqcns_destroy(d->c);
520 free(d->ido); free(d->ref); free(d);
532 #define MPLP_GLF 0x10
533 #define MPLP_NO_COMP 0x20
534 #define MPLP_NO_ORPHAN 0x40
535 #define MPLP_REALN 0x80
536 #define MPLP_FMT_DP 0x100
537 #define MPLP_FMT_SP 0x200
538 #define MPLP_NO_INDEL 0x400
539 #define MPLP_EXT_BAQ 0x800
540 #define MPLP_ILLUMINA13 0x1000
542 void *bed_read(const char *fn);
543 void bed_destroy(void *_h);
544 int bed_overlap(const void *_h, const char *chr, int beg, int end);
547 int max_mq, min_mq, flag, min_baseQ, capQ_thres, max_depth, max_indel_depth;
548 int openQ, extQ, tandemQ, min_support; // for indels
549 double min_frac; // for indels
561 const mplp_conf_t *conf;
570 static int mplp_func(void *data, bam1_t *b)
572 extern int bam_realn(bam1_t *b, const char *ref);
573 extern int bam_prob_realn_core(bam1_t *b, const char *ref, int);
574 extern int bam_cap_mapQ(bam1_t *b, char *ref, int thres);
575 mplp_aux_t *ma = (mplp_aux_t*)data;
579 ret = ma->iter? bam_iter_read(ma->fp, ma->iter, b) : bam_read1(ma->fp, b);
581 if (b->core.tid < 0 || (b->core.flag&BAM_FUNMAP)) { // exclude unmapped reads
585 if (ma->conf->bed) { // test overlap
586 skip = !bed_overlap(ma->conf->bed, ma->h->target_name[b->core.tid], b->core.pos, bam_calend(&b->core, bam1_cigar(b)));
589 if (ma->conf->rghash) { // exclude read groups
590 uint8_t *rg = bam_aux_get(b, "RG");
591 skip = (rg && bcf_str2id(ma->conf->rghash, (const char*)(rg+1)) >= 0);
594 if (ma->conf->flag & MPLP_ILLUMINA13) {
596 uint8_t *qual = bam1_qual(b);
597 for (i = 0; i < b->core.l_qseq; ++i)
598 qual[i] = qual[i] > 31? qual[i] - 31 : 0;
600 has_ref = (ma->ref && ma->ref_id == b->core.tid)? 1 : 0;
602 if (has_ref && (ma->conf->flag&MPLP_REALN)) bam_prob_realn_core(b, ma->ref, (ma->conf->flag & MPLP_EXT_BAQ)? 3 : 1);
603 if (has_ref && ma->conf->capQ_thres > 10) {
604 int q = bam_cap_mapQ(b, ma->ref, ma->conf->capQ_thres);
606 else if (b->core.qual > q) b->core.qual = q;
608 else if (b->core.qual < ma->conf->min_mq) skip = 1;
609 else if ((ma->conf->flag&MPLP_NO_ORPHAN) && (b->core.flag&1) && !(b->core.flag&2)) skip = 1;
614 static void group_smpl(mplp_pileup_t *m, bam_sample_t *sm, kstring_t *buf,
615 int n, char *const*fn, int *n_plp, const bam_pileup1_t **plp)
618 memset(m->n_plp, 0, m->n * sizeof(int));
619 for (i = 0; i < n; ++i) {
620 for (j = 0; j < n_plp[i]; ++j) {
621 const bam_pileup1_t *p = plp[i] + j;
624 q = bam_aux_get(p->b, "RG");
625 if (q) id = bam_smpl_rg2smid(sm, fn[i], (char*)q+1, buf);
626 if (id < 0) id = bam_smpl_rg2smid(sm, fn[i], 0, buf);
627 if (id < 0 || id >= m->n) {
628 assert(q); // otherwise a bug
629 fprintf(pysamerr, "[%s] Read group %s used in file %s but absent from the header or an alignment missing read group.\n", __func__, (char*)q+1, fn[i]);
632 if (m->n_plp[id] == m->m_plp[id]) {
633 m->m_plp[id] = m->m_plp[id]? m->m_plp[id]<<1 : 8;
634 m->plp[id] = realloc(m->plp[id], sizeof(bam_pileup1_t) * m->m_plp[id]);
636 m->plp[id][m->n_plp[id]++] = *p;
641 static int mpileup(mplp_conf_t *conf, int n, char **fn)
643 extern void *bcf_call_add_rg(void *rghash, const char *hdtext, const char *list);
644 extern void bcf_call_del_rghash(void *rghash);
646 int i, tid, pos, *n_plp, beg0 = 0, end0 = 1u<<29, ref_len, ref_tid, max_depth, max_indel_depth;
647 const bam_pileup1_t **plp;
653 bcf_callaux_t *bca = 0;
654 bcf_callret1_t *bcr = 0;
659 bam_sample_t *sm = 0;
663 memset(&gplp, 0, sizeof(mplp_pileup_t));
664 memset(&buf, 0, sizeof(kstring_t));
665 memset(&bc, 0, sizeof(bcf_call_t));
666 data = calloc(n, sizeof(void*));
667 plp = calloc(n, sizeof(void*));
668 n_plp = calloc(n, sizeof(int*));
669 sm = bam_smpl_init();
671 // read the header and initialize data
672 for (i = 0; i < n; ++i) {
674 data[i] = calloc(1, sizeof(mplp_aux_t));
675 data[i]->fp = strcmp(fn[i], "-") == 0? bam_dopen(fileno(stdin), "r") : bam_open(fn[i], "r");
676 data[i]->conf = conf;
677 h_tmp = bam_header_read(data[i]->fp);
678 data[i]->h = i? h : h_tmp; // for i==0, "h" has not been set yet
679 bam_smpl_add(sm, fn[i], h_tmp->text);
680 rghash = bcf_call_add_rg(rghash, h_tmp->text, conf->pl_list);
684 idx = bam_index_load(fn[i]);
686 fprintf(pysamerr, "[%s] fail to load index for %d-th input.\n", __func__, i+1);
689 if (bam_parse_region(h_tmp, conf->reg, &tid, &beg, &end) < 0) {
690 fprintf(pysamerr, "[%s] malformatted region or wrong seqname for %d-th input.\n", __func__, i+1);
693 if (i == 0) beg0 = beg, end0 = end;
694 data[i]->iter = bam_iter_query(idx, tid, beg, end);
695 bam_index_destroy(idx);
697 if (i == 0) h = h_tmp;
699 // FIXME: to check consistency
700 bam_header_destroy(h_tmp);
704 gplp.n_plp = calloc(sm->n, sizeof(int));
705 gplp.m_plp = calloc(sm->n, sizeof(int));
706 gplp.plp = calloc(sm->n, sizeof(void*));
708 fprintf(pysamerr, "[%s] %d samples in %d input files\n", __func__, sm->n, n);
709 // write the VCF header
710 if (conf->flag & MPLP_GLF) {
712 bh = calloc(1, sizeof(bcf_hdr_t));
713 s.l = s.m = 0; s.s = 0;
714 bp = bcf_open("-", (conf->flag&MPLP_NO_COMP)? "wu" : "w");
715 for (i = 0; i < h->n_targets; ++i) {
716 kputs(h->target_name[i], &s);
720 bh->name = malloc(s.l);
721 memcpy(bh->name, s.s, s.l);
723 for (i = 0; i < sm->n; ++i) {
724 kputs(sm->smpl[i], &s); kputc('\0', &s);
727 bh->sname = malloc(s.l);
728 memcpy(bh->sname, s.s, s.l);
729 bh->txt = malloc(strlen(BAM_VERSION) + 64);
730 bh->l_txt = 1 + sprintf(bh->txt, "##samtoolsVersion=%s\n", BAM_VERSION);
733 bcf_hdr_write(bp, bh);
734 bca = bcf_call_init(-1., conf->min_baseQ);
735 bcr = calloc(sm->n, sizeof(bcf_callret1_t));
736 bca->rghash = rghash;
737 bca->openQ = conf->openQ, bca->extQ = conf->extQ, bca->tandemQ = conf->tandemQ;
738 bca->min_frac = conf->min_frac;
739 bca->min_support = conf->min_support;
741 ref_tid = -1; ref = 0;
742 iter = bam_mplp_init(n, mplp_func, (void**)data);
743 max_depth = conf->max_depth;
744 if (max_depth * sm->n > 1<<20)
745 fprintf(pysamerr, "(%s) Max depth is above 1M. Potential memory hog!\n", __func__);
746 if (max_depth * sm->n < 8000) {
747 max_depth = 8000 / sm->n;
748 fprintf(pysamerr, "<%s> Set max per-file depth to %d\n", __func__, max_depth);
750 max_indel_depth = conf->max_indel_depth * sm->n;
751 bam_mplp_set_maxcnt(iter, max_depth);
752 while (bam_mplp_auto(iter, &tid, &pos, n_plp, plp) > 0) {
753 if (conf->reg && (pos < beg0 || pos >= end0)) continue; // out of the region requested
754 if (conf->bed && tid >= 0 && !bed_overlap(conf->bed, h->target_name[tid], pos, pos+1)) continue;
755 if (tid != ref_tid) {
757 if (conf->fai) ref = fai_fetch(conf->fai, h->target_name[tid], &ref_len);
758 for (i = 0; i < n; ++i) data[i]->ref = ref, data[i]->ref_id = tid;
761 if (conf->flag & MPLP_GLF) {
762 int total_depth, _ref0, ref16;
763 bcf1_t *b = calloc(1, sizeof(bcf1_t));
764 for (i = total_depth = 0; i < n; ++i) total_depth += n_plp[i];
765 group_smpl(&gplp, sm, &buf, n, fn, n_plp, plp);
766 _ref0 = (ref && pos < ref_len)? ref[pos] : 'N';
767 ref16 = bam_nt16_table[_ref0];
768 for (i = 0; i < gplp.n; ++i)
769 bcf_call_glfgen(gplp.n_plp[i], gplp.plp[i], ref16, bca, bcr + i);
770 bcf_call_combine(gplp.n, bcr, ref16, &bc);
771 bcf_call2bcf(tid, pos, &bc, b, (conf->flag&(MPLP_FMT_DP|MPLP_FMT_SP))? bcr : 0,
772 (conf->flag&MPLP_FMT_SP), 0, 0);
773 bcf_write(bp, bh, b);
776 if (!(conf->flag&MPLP_NO_INDEL) && total_depth < max_indel_depth && bcf_call_gap_prep(gplp.n, gplp.n_plp, gplp.plp, pos, bca, ref, rghash) >= 0) {
777 for (i = 0; i < gplp.n; ++i)
778 bcf_call_glfgen(gplp.n_plp[i], gplp.plp[i], -1, bca, bcr + i);
779 if (bcf_call_combine(gplp.n, bcr, -1, &bc) >= 0) {
780 b = calloc(1, sizeof(bcf1_t));
781 bcf_call2bcf(tid, pos, &bc, b, (conf->flag&(MPLP_FMT_DP|MPLP_FMT_SP))? bcr : 0,
782 (conf->flag&MPLP_FMT_SP), bca, ref);
783 bcf_write(bp, bh, b);
788 printf("%s\t%d\t%c", h->target_name[tid], pos + 1, (ref && pos < ref_len)? ref[pos] : 'N');
789 for (i = 0; i < n; ++i) {
791 printf("\t%d\t", n_plp[i]);
792 if (n_plp[i] == 0) printf("*\t*");
794 for (j = 0; j < n_plp[i]; ++j)
795 pileup_seq(plp[i] + j, pos, ref_len, ref);
797 for (j = 0; j < n_plp[i]; ++j) {
798 const bam_pileup1_t *p = plp[i] + j;
799 int c = bam1_qual(p->b)[p->qpos] + 33;
800 if (c > 126) c = 126;
810 bam_smpl_destroy(sm); free(buf.s);
811 for (i = 0; i < gplp.n; ++i) free(gplp.plp[i]);
812 free(gplp.plp); free(gplp.n_plp); free(gplp.m_plp);
813 bcf_call_del_rghash(rghash);
814 bcf_hdr_destroy(bh); bcf_call_destroy(bca); free(bc.PL); free(bcr);
815 bam_mplp_destroy(iter);
816 bam_header_destroy(h);
817 for (i = 0; i < n; ++i) {
818 bam_close(data[i]->fp);
819 if (data[i]->iter) bam_iter_destroy(data[i]->iter);
822 free(data); free(plp); free(ref); free(n_plp);
826 #define MAX_PATH_LEN 1024
827 static int read_file_list(const char *file_list,int *n,char **argv[])
829 char buf[MAX_PATH_LEN];
833 FILE *fh = fopen(file_list,"r");
836 fprintf(pysamerr,"%s: %s\n", file_list,strerror(errno));
840 // Speed is not an issue here, determine the number of files by reading the file twice
842 while ( fgets(buf,MAX_PATH_LEN,fh) ) nfiles++;
844 if ( fseek(fh, 0L, SEEK_SET) )
846 fprintf(pysamerr,"%s: %s\n", file_list,strerror(errno));
850 files = calloc(nfiles,sizeof(char*));
852 while ( fgets(buf,MAX_PATH_LEN,fh) )
855 while ( len>0 && isspace(buf[len-1]) ) len--;
856 if ( !len ) continue;
858 files[nfiles] = malloc(sizeof(char)*(len+1));
859 strncpy(files[nfiles],buf,len);
860 files[nfiles][len] = 0;
866 fprintf(pysamerr,"No files read from %s\n", file_list);
875 int bam_mpileup(int argc, char *argv[])
878 const char *file_list = NULL;
880 int nfiles = 0, use_orphan = 0;
882 memset(&mplp, 0, sizeof(mplp_conf_t));
886 mplp.max_depth = 250; mplp.max_indel_depth = 250;
887 mplp.openQ = 40; mplp.extQ = 20; mplp.tandemQ = 100;
888 mplp.min_frac = 0.002; mplp.min_support = 1;
889 mplp.flag = MPLP_NO_ORPHAN | MPLP_REALN;
890 while ((c = getopt(argc, argv, "Agf:r:l:M:q:Q:uaRC:BDSd:L:b:P:o:e:h:Im:F:EG:6")) >= 0) {
893 mplp.fai = fai_load(optarg);
894 if (mplp.fai == 0) return 1;
896 case 'd': mplp.max_depth = atoi(optarg); break;
897 case 'r': mplp.reg = strdup(optarg); break;
898 case 'l': mplp.bed = bed_read(optarg); break;
899 case 'P': mplp.pl_list = strdup(optarg); break;
900 case 'g': mplp.flag |= MPLP_GLF; break;
901 case 'u': mplp.flag |= MPLP_NO_COMP | MPLP_GLF; break;
902 case 'a': mplp.flag |= MPLP_NO_ORPHAN | MPLP_REALN; break;
903 case 'B': mplp.flag &= ~MPLP_REALN; break;
904 case 'R': mplp.flag |= MPLP_REALN; break;
905 case 'D': mplp.flag |= MPLP_FMT_DP; break;
906 case 'S': mplp.flag |= MPLP_FMT_SP; break;
907 case 'I': mplp.flag |= MPLP_NO_INDEL; break;
908 case 'E': mplp.flag |= MPLP_EXT_BAQ; break;
909 case '6': mplp.flag |= MPLP_ILLUMINA13; break;
910 case 'C': mplp.capQ_thres = atoi(optarg); break;
911 case 'M': mplp.max_mq = atoi(optarg); break;
912 case 'q': mplp.min_mq = atoi(optarg); break;
913 case 'Q': mplp.min_baseQ = atoi(optarg); break;
914 case 'b': file_list = optarg; break;
915 case 'o': mplp.openQ = atoi(optarg); break;
916 case 'e': mplp.extQ = atoi(optarg); break;
917 case 'h': mplp.tandemQ = atoi(optarg); break;
918 case 'A': use_orphan = 1; break;
919 case 'F': mplp.min_frac = atof(optarg); break;
920 case 'm': mplp.min_support = atoi(optarg); break;
921 case 'L': mplp.max_indel_depth = atoi(optarg); break;
925 mplp.rghash = bcf_str2id_init();
926 if ((fp_rg = fopen(optarg, "r")) == 0)
927 fprintf(pysamerr, "(%s) Fail to open file %s. Continue anyway.\n", __func__, optarg);
928 while (!feof(fp_rg) && fscanf(fp_rg, "%s", buf) > 0) // this is not a good style, but forgive me...
929 bcf_str2id_add(mplp.rghash, strdup(buf));
935 if (use_orphan) mplp.flag &= ~MPLP_NO_ORPHAN;
937 fprintf(pysamerr, "\n");
938 fprintf(pysamerr, "Usage: samtools mpileup [options] in1.bam [in2.bam [...]]\n\n");
939 fprintf(pysamerr, "Input options:\n\n");
940 fprintf(pysamerr, " -6 assume the quality is in the Illumina-1.3+ encoding\n");
941 fprintf(pysamerr, " -A count anomalous read pairs\n");
942 fprintf(pysamerr, " -B disable BAQ computation\n");
943 fprintf(pysamerr, " -b FILE list of input BAM files [null]\n");
944 fprintf(pysamerr, " -d INT max per-BAM depth to avoid excessive memory usage [%d]\n", mplp.max_depth);
945 fprintf(pysamerr, " -E extended BAQ for higher sensitivity but lower specificity\n");
946 fprintf(pysamerr, " -f FILE faidx indexed reference sequence file [null]\n");
947 fprintf(pysamerr, " -G FILE exclude read groups listed in FILE [null]\n");
948 fprintf(pysamerr, " -l FILE list of positions (chr pos) or regions (BED) [null]\n");
949 fprintf(pysamerr, " -M INT cap mapping quality at INT [%d]\n", mplp.max_mq);
950 fprintf(pysamerr, " -r STR region in which pileup is generated [null]\n");
951 fprintf(pysamerr, " -q INT skip alignments with mapQ smaller than INT [%d]\n", mplp.min_mq);
952 fprintf(pysamerr, " -Q INT skip bases with baseQ/BAQ smaller than INT [%d]\n", mplp.min_baseQ);
953 fprintf(pysamerr, "\nOutput options:\n\n");
954 fprintf(pysamerr, " -D output per-sample DP in BCF (require -g/-u)\n");
955 fprintf(pysamerr, " -g generate BCF output (genotype likelihoods)\n");
956 fprintf(pysamerr, " -S output per-sample strand bias P-value in BCF (require -g/-u)\n");
957 fprintf(pysamerr, " -u generate uncompress BCF output\n");
958 fprintf(pysamerr, "\nSNP/INDEL genotype likelihoods options (effective with `-g' or `-u'):\n\n");
959 fprintf(pysamerr, " -e INT Phred-scaled gap extension seq error probability [%d]\n", mplp.extQ);
960 fprintf(pysamerr, " -F FLOAT minimum fraction of gapped reads for candidates [%g]\n", mplp.min_frac);
961 fprintf(pysamerr, " -h INT coefficient for homopolymer errors [%d]\n", mplp.tandemQ);
962 fprintf(pysamerr, " -I do not perform indel calling\n");
963 fprintf(pysamerr, " -L INT max per-sample depth for INDEL calling [%d]\n", mplp.max_indel_depth);
964 fprintf(pysamerr, " -m INT minimum gapped reads for indel candidates [%d]\n", mplp.min_support);
965 fprintf(pysamerr, " -o INT Phred-scaled gap open sequencing error probability [%d]\n", mplp.openQ);
966 fprintf(pysamerr, " -P STR comma separated list of platforms for indels [all]\n");
967 fprintf(pysamerr, "\n");
968 fprintf(pysamerr, "Notes: Assuming diploid individuals.\n\n");
972 if ( read_file_list(file_list,&nfiles,&fn) ) return 1;
973 mpileup(&mplp,nfiles,fn);
974 for (c=0; c<nfiles; c++) free(fn[c]);
976 } else mpileup(&mplp, argc - optind, argv + optind);
977 if (mplp.rghash) bcf_str2id_thorough_destroy(mplp.rghash);
978 free(mplp.reg); free(mplp.pl_list);
979 if (mplp.fai) fai_destroy(mplp.fai);
980 if (mplp.bed) bed_destroy(mplp.bed);