Debian Codegraph @

bcftools/mpileup.c

raw symbols SCIP
1 /* mpileup.c -- mpileup subcommand. Previously bam_plcmd.c from samtools
2
3 Copyright (C) 2008-2024 Genome Research Ltd.
4 Portions copyright (C) 2009-2012 Broad Institute.
5
6 Author: Heng Li <[email protected]>
7
8 Permission is hereby granted, free of charge, to any person obtaining a copy
9 of this software and associated documentation files (the "Software"), to deal
10 in the Software without restriction, including without limitation the rights
11 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 copies of the Software, and to permit persons to whom the Software is
13 furnished to do so, subject to the following conditions:
14
15 The above copyright notice and this permission notice shall be included in
16 all copies or substantial portions of the Software.
17
18 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 DEALINGS IN THE SOFTWARE. */
25
26 #include <math.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <unistd.h>
30 #include <ctype.h>
31 #include <string.h>
32 #include <strings.h>
33 #include <limits.h>
34 #include <inttypes.h>
35 #include <errno.h>
36 #include <sys/stat.h>
37 #include <getopt.h>
38 #include <htslib/sam.h>
39 #include <htslib/faidx.h>
40 #include <htslib/kstring.h>
41 #include <htslib/khash_str2int.h>
42 #include <htslib/hts_os.h>
43 #include <assert.h>
44 #include "regidx.h"
45 #include "bcftools.h"
46 #include "bam2bcf.h"
47 #include "bam_sample.h"
48 #include "gvcf.h"
49
50 #define MPLP_BCF 1
51 #define MPLP_VCF (1<<1)
52 #define MPLP_NO_COMP (1<<2)
53 #define MPLP_NO_ORPHAN (1<<3)
54 #define MPLP_REALN (1<<4)
55 #define MPLP_NO_INDEL (1<<5)
56 #define MPLP_REDO_BAQ (1<<6)
57 #define MPLP_ILLUMINA13 (1<<7)
58 #define MPLP_IGNORE_RG (1<<8)
59 #define MPLP_PRINT_POS (1<<9)
60 #define MPLP_PRINT_MAPQ (1<<10)
61 #define MPLP_PER_SAMPLE (1<<11)
62 #define MPLP_SMART_OVERLAPS (1<<12)
63 #define MPLP_REALN_PARTIAL (1<<13)
64
65 typedef struct _mplp_aux_t mplp_aux_t;
66 typedef struct _mplp_pileup_t mplp_pileup_t;
67
68 // Data shared by all bam files
69 typedef struct {
70 int min_mq, flag, min_baseQ, max_baseQ, delta_baseQ, capQ_thres, max_depth,
71 max_indel_depth, max_read_len, ambig_reads;
72 uint32_t fmt_flag;
73 int rflag_skip_any_unset, rflag_skip_all_unset, rflag_skip_any_set, rflag_skip_all_set, output_type;
74 int openQ, extQ, tandemQ, min_support, indel_win_size; // for indels
75 int seqQ_offset;
76 double min_frac; // for indels
77 double indel_bias, poly_mqual;
78 double del_bias; // compensate for diff deletion vs insertion error rates
79 double vs_ref;
80 char *reg_fname, *pl_list, *fai_fname, *output_fname;
81 int reg_is_file, record_cmd_line, n_threads, clevel;
82 faidx_t *fai;
83 regidx_t *bed, *reg; // bed: skipping regions, reg: index-jump to regions
84 regitr_t *bed_itr, *reg_itr;
85 int bed_logic; // 1: include region, 0: exclude region
86 gvcf_t *gvcf;
87
88 // auxiliary structures for calling
89 bcf_callaux_t *bca;
90 bcf_callret1_t *bcr;
91 bcf_call_t bc;
92 bam_mplp_t iter;
93 mplp_aux_t **mplp_data;
94 int nfiles;
95 char **files;
96 mplp_pileup_t *gplp;
97 int *n_plp;
98 const bam_pileup1_t **plp;
99 bam_smpl_t *bsmpl;
100 kstring_t buf;
101 bcf1_t *bcf_rec;
102 htsFile *bcf_fp;
103 bcf_hdr_t *bcf_hdr;
104 int indels_v20;
105 int edlib;
106 int argc;
107 char **argv;
108 int write_index;
109 char *index_fn;
110 } mplp_conf_t;
111
112 typedef struct {
113 char *ref[2];
114 int ref_id[2];
115 int ref_len[2];
116 } mplp_ref_t;
117
118 #define MPLP_REF_INIT {{NULL,NULL},{-1,-1},{0,0}}
119
120 // Data specific to each bam file
121 struct _mplp_aux_t {
122 samFile *fp;
123 hts_itr_t *iter;
124 bam_hdr_t *h;
125 mplp_ref_t *ref;
126 const mplp_conf_t *conf;
127 int bam_id;
128 hts_idx_t *idx; // maintained only with more than one -r regions
129 };
130
131 // Data passed to htslib/mpileup
132 struct _mplp_pileup_t {
133 int n;
134 int *n_plp, *m_plp;
135 bam_pileup1_t **plp;
136 };
137
138 static int mplp_get_ref(mplp_aux_t *ma, int tid, char **ref, int *ref_len) {
139 mplp_ref_t *r = ma->ref;
140
141 //printf("get ref %d {%d/%p, %d/%p}\n", tid, r->ref_id[0], r->ref[0], r->ref_id[1], r->ref[1]);
142
143 if (!r || !ma->conf->fai) {
144 *ref = NULL;
145 return 0;
146 }
147
148 // Do we need to reference count this so multiple mplp_aux_t can
149 // track which references are in use?
150 // For now we just cache the last two. Sufficient?
151 if (tid == r->ref_id[0]) {
152 *ref = r->ref[0];
153 *ref_len = r->ref_len[0];
154 return 1;
155 }
156 if (tid == r->ref_id[1]) {
157 // Last, swap over
158 int tmp;
159 tmp = r->ref_id[0]; r->ref_id[0] = r->ref_id[1]; r->ref_id[1] = tmp;
160 tmp = r->ref_len[0]; r->ref_len[0] = r->ref_len[1]; r->ref_len[1] = tmp;
161
162 char *tc;
163 tc = r->ref[0]; r->ref[0] = r->ref[1]; r->ref[1] = tc;
164 *ref = r->ref[0];
165 *ref_len = r->ref_len[0];
166 return 1;
167 }
168
169 // New, so migrate to old and load new
170 free(r->ref[1]);
171 r->ref[1] = r->ref[0];
172 r->ref_id[1] = r->ref_id[0];
173 r->ref_len[1] = r->ref_len[0];
174
175 r->ref_id[0] = tid;
176 r->ref[0] = faidx_fetch_seq(ma->conf->fai,
177 ma->h->target_name[r->ref_id[0]],
178 0,
179 INT_MAX,
180 &r->ref_len[0]);
181
182 if (!r->ref[0]) {
183 r->ref[0] = NULL;
184 r->ref_id[0] = -1;
185 r->ref_len[0] = 0;
186 *ref = NULL;
187 return 0;
188 }
189
190 *ref = r->ref[0];
191 *ref_len = r->ref_len[0];
192 return 1;
193 }
194
195 static int mplp_func(void *data, bam1_t *b)
196 {
197 char *ref;
198 mplp_aux_t *ma = (mplp_aux_t*)data;
199 int ret, ref_len;
200 while (1)
201 {
202 int has_ref;
203 ret = ma->iter? sam_itr_next(ma->fp, ma->iter, b) : sam_read1(ma->fp, ma->h, b);
204 if (ret < 0) break;
205 // The 'B' cigar operation is not part of the specification, considering as obsolete.
206 // bam_remove_B(b);
207 if (b->core.tid < 0 || (b->core.flag&BAM_FUNMAP)) continue; // exclude unmapped reads
208 if (ma->conf->rflag_skip_any_unset && (ma->conf->rflag_skip_any_unset&b->core.flag)!=ma->conf->rflag_skip_any_unset) continue;
209 if (ma->conf->rflag_skip_all_set && (ma->conf->rflag_skip_all_set&b->core.flag)==ma->conf->rflag_skip_all_set) continue;
210 if (ma->conf->rflag_skip_all_unset && !(ma->conf->rflag_skip_all_unset&b->core.flag)) continue;
211 if (ma->conf->rflag_skip_any_set && ma->conf->rflag_skip_any_set&b->core.flag) continue;
212 if (ma->conf->bed)
213 {
214 // test overlap
215 regitr_t *itr = ma->conf->bed_itr;
216 int beg = b->core.pos, end = bam_endpos(b)-1;
217 int overlap = regidx_overlap(ma->conf->bed, ma->h->target_name[b->core.tid],beg,end, itr);
218 if ( !ma->conf->bed_logic && !overlap )
219 {
220 // exclude only reads which are fully contained in the region
221 while ( regitr_overlap(itr) )
222 {
223 if ( beg < itr->beg ) { overlap = 1; break; }
224 if ( end > itr->end ) { overlap = 1; break; }
225 }
226 }
227 if ( !overlap ) continue;
228 }
229 if ( bam_smpl_get_sample_id(ma->conf->bsmpl,ma->bam_id,b)<0 ) continue;
230 if (ma->conf->flag & MPLP_ILLUMINA13) {
231 int i;
232 uint8_t *qual = bam_get_qual(b);
233 for (i = 0; i < b->core.l_qseq; ++i)
234 qual[i] = qual[i] > 31? qual[i] - 31 : 0;
235 }
236
237 if (ma->conf->fai && b->core.tid >= 0) {
238 has_ref = mplp_get_ref(ma, b->core.tid, &ref, &ref_len);
239 if (has_ref && ref_len <= b->core.pos) { // exclude reads outside of the reference sequence
240 fprintf(stderr,"[%s] Skipping because %"PRId64" is outside of %d [ref:%d]\n",
241 __func__, (int64_t) b->core.pos, ref_len, b->core.tid);
242 continue;
243 }
244 } else {
245 has_ref = 0;
246 }
247
248 // Allow sufficient room for bam_aux_append of ZQ tag without
249 // a realloc and consequent breakage of pileup's cached pointers.
250 if (has_ref && (ma->conf->flag &MPLP_REALN) && !bam_aux_get(b, "ZQ")) {
251 // Doing sam_prob_realn later is problematic as it adds to
252 // the tag list (ZQ or BQ), which causes a realloc of b->data.
253 // This happens after pileup has built a hash table on the
254 // read name. It's a deficiency in pileup IMO.
255
256 // We could implement a new sam_prob_realn that returns ZQ
257 // somewhere else and cache it ourselves (pileup clientdata),
258 // but for now we simply use a workaround.
259 //
260 // We create a fake tag of the correct length, which we remove
261 // just prior calling sam_prob_realn so we can guarantee there is
262 // room. (We can't just make room now as bam_copy1 removes it
263 // again).
264 if (b->core.l_qseq > 500) {
265 uint8_t *ZQ = malloc((uint32_t)b->core.l_qseq+1);
266 memset(ZQ, '@', b->core.l_qseq);
267 ZQ[b->core.l_qseq] = 0;
268 bam_aux_append(b, "_Q", 'Z', b->core.l_qseq+1, ZQ);
269 free(ZQ);
270 } else {
271 static uint8_t ZQ[501] =
272 "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
273 "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
274 "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
275 "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
276 "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
277 "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
278 "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
279 "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
280 "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
281 "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@";
282 ZQ[b->core.l_qseq] = 0;
283 bam_aux_append(b, "_Q", 'Z', b->core.l_qseq+1, ZQ);
284 ZQ[b->core.l_qseq] = '@';
285 }
286 }
287
288 if (has_ref && ma->conf->capQ_thres > 10) {
289 int q = sam_cap_mapq(b, ref, ref_len, ma->conf->capQ_thres);
290 if (q < 0) continue; // skip
291 else if (b->core.qual > q) b->core.qual = q;
292 }
293 if (b->core.qual < ma->conf->min_mq) continue;
294 else if ((ma->conf->flag&MPLP_NO_ORPHAN) && (b->core.flag&BAM_FPAIRED) && !(b->core.flag&BAM_FPROPER_PAIR)) continue;
295
296 return ret;
297 };
298 return ret;
299 }
300
301 // Called once per new bam added to the pileup.
302 // We cache sample information here so we don't have to keep recomputing this
303 // on each and every pileup column. If FMT/SCR annotation is requested, a flag
304 // is set to indicate the presence of a soft clip.
305 static int pileup_constructor(void *data, const bam1_t *b, bam_pileup_cd *cd)
306 {
307 cd->p = calloc(1,sizeof(plp_cd_t));
308
309 PLP_NM(cd) = PLP_NM_UNSET;
310
311 mplp_aux_t *ma = (mplp_aux_t *)data;
312 int n = bam_smpl_get_sample_id(ma->conf->bsmpl, ma->bam_id, (bam1_t *)b);
313 PLP_SET_SAMPLE_ID(cd, n);
314
315 // Whether read has a soft-clip is used in mplp_realn's heuristics.
316 // TODO: consider whether clip length is beneficial to use?
317 int i;
318 for (i=0; i<b->core.n_cigar; i++) {
319 int cig = bam_get_cigar(b)[i] & BAM_CIGAR_MASK;
320 if (cig == BAM_CSOFT_CLIP) {
321 PLP_SET_SOFT_CLIP(cd);
322 break;
323 }
324 }
325
326 if (ma->conf->flag & MPLP_REALN) {
327 int i;
328 // int tot_ins = 0;
329 // int p = 0;
330 uint32_t *cigar = bam_get_cigar(b);
331 for (i=0; i<b->core.n_cigar; i++) {
332 int cig = cigar[i] & BAM_CIGAR_MASK;
333 // if (bam_cigar_type(cig) & 2)
334 // p += cigar[i] >> BAM_CIGAR_SHIFT;
335 if (cig == BAM_CINS || cig == BAM_CDEL || cig == BAM_CREF_SKIP) {
336 // tot_ins += cigar[i] >> BAM_CIGAR_SHIFT;
337 // Possible further optimsation, check tot_ins==1 later
338 // (and remove break) so we can detect single bp indels.
339 // We may want to focus BAQ on more complex regions only.
340 PLP_SET_INDEL(cd);
341 break;
342 }
343
344 // TODO: proper p->cd struct and have cd->i as a size rather
345 // than a flag.
346
347 // Then aggregate together the sizes and if just 1 size for all
348 // reads or 2 sizes for approx 50/50 split in all reads, then
349 // treat this as a well-aligned variant and don't run BAQ.
350 }
351 }
352
353 return 0;
354 }
355 static int pileup_destructor(void *data, const bam1_t *b, bam_pileup_cd *cd)
356 {
357 free(cd->p);
358 return 0;
359 }
360
361 static void group_smpl(mplp_pileup_t *m, bam_smpl_t *bsmpl, int n, int *n_plp, const bam_pileup1_t **plp)
362 {
363 int i, j;
364 memset(m->n_plp, 0, m->n * sizeof(int));
365 for (i = 0; i < n; ++i) // iterate over all bams
366 {
367 for (j = 0; j < n_plp[i]; ++j) // iterate over all reads available at this position
368 {
369 const bam_pileup1_t *p = plp[i] + j;
370 int id = PLP_SAMPLE_ID(&(p->cd));
371 if (m->n_plp[id] == m->m_plp[id])
372 {
373 m->m_plp[id] = m->m_plp[id]? m->m_plp[id]<<1 : 8;
374 m->plp[id] = (bam_pileup1_t*) realloc(m->plp[id], sizeof(bam_pileup1_t) * m->m_plp[id]);
375 }
376 m->plp[id][m->n_plp[id]++] = *p;
377 }
378 }
379 }
380
381 static void flush_bcf_records(mplp_conf_t *conf, htsFile *fp, bcf_hdr_t *hdr, bcf1_t *rec)
382 {
383 if ( !conf->gvcf )
384 {
385 if ( rec && bcf_write1(fp, hdr, rec)!=0 ) error("[%s] Error: failed to write the record to %s\n", __func__,conf->output_fname?conf->output_fname:"standard output");
386 return;
387 }
388
389 if ( !rec )
390 {
391 gvcf_write(conf->gvcf, fp, hdr, NULL, 0);
392 return;
393 }
394
395 int is_ref = 0;
396 if ( rec->n_allele==1 ) is_ref = 1;
397 else if ( rec->n_allele==2 )
398 {
399 // second allele is mpileup's X, not a variant
400 if ( rec->d.allele[1][0]=='<' && rec->d.allele[1][1]=='*' && rec->d.allele[1][2]=='>' ) is_ref = 1;
401 }
402 rec = gvcf_write(conf->gvcf, fp, hdr, rec, is_ref);
403 if ( rec && bcf_write1(fp,hdr,rec)!=0 ) error("[%s] Error: failed to write the record to %s\n", __func__,conf->output_fname?conf->output_fname:"standard output");
404 }
405
406 /*
407 * Loops for an indel at this position.
408 *
409 * Only reads that overlap an indel loci get realigned. This considerably
410 * reduces the cost of running BAQ while keeping the main benefits.
411 *
412 * TODO: also consider only realigning reads that don't span the indel
413 * by more than a certain amount either-side. Ie focus BAQ only on reads
414 * ending adjacent to the indel, where the alignment is most likely to
415 * be wrong. (2nd TODO: do this based on sequence context; STRs bad, unique
416 * data good.)
417 *
418 * NB: this may sadly realign after we've already used the data. Hmm...
419 */
420 static void mplp_realn(int n, int *n_plp, const bam_pileup1_t **plp,
421 int flag, int max_read_len,
422 char *ref, int ref_len, int pos) {
423 int i, j, has_indel = 0, has_clip = 0, nt = 0;
424 int min_indel = INT_MAX, max_indel = INT_MIN;
425
426 // Is an indel present.
427 // NB: don't bother even checking if very long as almost guaranteed
428 // to have indel (and likely soft-clips too).
429 for (i = 0; i < n; i++) { // iterate over bams
430 nt += n_plp[i];
431 for (j = 0; j < n_plp[i]; j++) { // iterate over reads
432 bam_pileup1_t *p = (bam_pileup1_t *)plp[i] + j;
433 has_indel += (PLP_HAS_INDEL(&p->cd) || p->indel) ? 1 : 0;
434 // Has_clip is almost always true for very long reads
435 // (eg PacBio CCS), but these rarely matter as the clip
436 // is likely a long way from this indel.
437 has_clip += (PLP_HAS_SOFT_CLIP(&p->cd)) ? 1 : 0;
438 if (max_indel < p->indel)
439 max_indel = p->indel;
440 if (min_indel > p->indel)
441 min_indel = p->indel;
442 }
443 }
444
445 if (flag & MPLP_REALN_PARTIAL) {
446 if (has_indel == 0 ||
447 (has_clip < 0.2*nt && max_indel == min_indel &&
448 (has_indel < 0.1*nt /*|| has_indel > 0.9*nt*/ || has_indel == 1)))
449 return;
450 }
451
452 // Realign
453 for (i = 0; i < n; i++) { // iterate over bams
454 for (j = 0; j < n_plp[i]; j++) { // iterate over reads
455 const bam_pileup1_t *p = plp[i] + j;
456 bam1_t *b = p->b;
457
458 // Avoid doing multiple times.
459 //
460 // Note we cannot modify p->cd.i here with a PLP_SET macro
461 // because the cd item is held by mpileup in an lbnode_t
462 // struct and copied over to the pileup struct for each
463 // iteration, essentially making p->cd.i read only.
464 //
465 // We could use our own structure (p->cd.p), allocated during
466 // the constructor, but for simplicity we play dirty and
467 // abuse an unused flag bit instead.
468 if ( PLP_IS_REALN(&(p->cd)) ) continue;
469 PLP_SET_REALN(&(p->cd));
470
471 if (b->core.l_qseq > max_read_len)
472 continue;
473
474 // Check p->cigar_ind and see what cigar elements are before
475 // and after. How close is this location to the end of the
476 // read? Only realign if we don't span by more than X bases.
477 //
478 // Again, best only done on deeper data as BAQ helps
479 // disproportionately more on shallow data sets.
480 //
481 // This rescues some of the false negatives that are caused by
482 // systematic reduction in quality due to sample vs ref alignment.
483
484 // At deep coverage we skip realigning more reads as we have sufficient depth.
485 // This rescues for false negatives. At shallow depth we pay for this with
486 // more FP so are more stringent on spanning size.
487 #define REALN_DIST (40+10*(nt<40)+10*(nt<20))
488 uint32_t *cig = bam_get_cigar(b);
489 int ncig = b->core.n_cigar;
490
491 // Don't realign reads where indel is in middle?
492 // On long read data we don't care about soft-clips at the ends.
493 // For short read data, we always calc BAQ on these as they're
494 // a common source of false positives.
495 if ((flag & MPLP_REALN_PARTIAL) && nt > 15 && ncig > 1) {
496 // Left & right cigar op match.
497 int lr = b->core.l_qseq > 500;
498 int lm = 0, rm = 0, k, nm = 0;
499 for (k = 0; k < ncig; k++) {
500 int cop = bam_cigar_op(cig[k]);
501 if (lr && (cop == BAM_CHARD_CLIP || cop == BAM_CSOFT_CLIP))
502 continue;
503
504 if (cop == BAM_CMATCH || cop == BAM_CDIFF ||
505 cop == BAM_CEQUAL) {
506 lm += bam_cigar_oplen(cig[k]);
507 nm++;
508 } else {
509 break;
510 }
511 }
512
513 // if everything is a match (or sequence (mis)match) then move on
514 // because we don't have an indel in the middle
515 if (nm != ncig) {
516 for (k = ncig-1; k >= 0; k--) {
517 int cop = bam_cigar_op(cig[k]);
518 if (lr && (cop == BAM_CHARD_CLIP || cop == BAM_CSOFT_CLIP))
519 continue;
520
521 if (cop == BAM_CMATCH || cop == BAM_CDIFF ||
522 cop == BAM_CEQUAL)
523 rm += bam_cigar_oplen(cig[k]);
524 else
525 break;
526 }
527
528 if (lm >= REALN_DIST*4 && rm >= REALN_DIST*4)
529 continue;
530
531 if (lm >= REALN_DIST && rm >= REALN_DIST &&
532 has_clip < (0.15+0.05*(nt>20))*nt)
533 continue;
534 }
535 }
536
537 if (b->core.l_qseq > 500) {
538 // don't do BAQ on long-read data if it's going to
539 // cause us to have a large band-with and costly in CPU
540 int rl = bam_cigar2rlen(b->core.n_cigar, bam_get_cigar(b));
541 if (abs(rl - b->core.l_qseq) * b->core.l_qseq >= 500000)
542 continue;
543 }
544
545 // Fudge: make room for ZQ tag.
546 uint8_t *_Q = bam_aux_get(b, "_Q");
547 if (_Q) bam_aux_del(b, _Q);
548 sam_prob_realn(b, ref, ref_len, (flag & MPLP_REDO_BAQ) ? 7 : 3);
549 }
550 }
551
552 return;
553 }
554
555 static int mpileup_reg(mplp_conf_t *conf, uint32_t beg, uint32_t end)
556 {
557 bam_hdr_t *hdr = conf->mplp_data[0]->h; // header of first file in input list
558
559 int ret, i, tid, pos, ref_len;
560 char *ref;
561
562 while ( (ret=bam_mplp_auto(conf->iter, &tid, &pos, conf->n_plp, conf->plp)) > 0)
563 {
564 if ( pos<beg || pos>end ) continue;
565 if ( conf->bed && tid >= 0 )
566 {
567 int overlap = regidx_overlap(conf->bed, hdr->target_name[tid], pos, pos, NULL);
568 if ( !conf->bed_logic ) overlap = overlap ? 0 : 1;
569 if ( !overlap ) continue;
570 }
571 int has_ref = mplp_get_ref(conf->mplp_data[0], tid, &ref, &ref_len);
572 if (has_ref && (conf->flag & MPLP_REALN))
573 mplp_realn(conf->nfiles, conf->n_plp, conf->plp, conf->flag, conf->max_read_len, ref, ref_len, pos);
574
575 int total_depth, _ref0, ref16;
576 for (i = total_depth = 0; i < conf->nfiles; ++i) total_depth += conf->n_plp[i];
577 group_smpl(conf->gplp, conf->bsmpl, conf->nfiles, conf->n_plp, conf->plp);
578 _ref0 = (ref && pos < ref_len)? ref[pos] : 'N';
579 ref16 = seq_nt16_table[_ref0];
580 bcf_callaux_clean(conf->bca, &conf->bc);
581 for (i = 0; i < conf->gplp->n; ++i)
582 bcf_call_glfgen(conf->gplp->n_plp[i], conf->gplp->plp[i], ref16, conf->bca, conf->bcr + i);
583 conf->bc.tid = tid; conf->bc.pos = pos;
584 bcf_call_combine(conf->gplp->n, conf->bcr, conf->bca, ref16, &conf->bc);
585 bcf_clear1(conf->bcf_rec);
586 bcf_call2bcf(&conf->bc, conf->bcf_rec, conf->bcr, conf->fmt_flag, conf->bca, 0);
587 flush_bcf_records(conf, conf->bcf_fp, conf->bcf_hdr, conf->bcf_rec);
588
589 // call indels; todo: subsampling with total_depth>max_indel_depth instead of ignoring?
590 // check me: rghash in bcf_call_gap_prep() should have no effect, reads mplp_func already excludes them
591 if (!(conf->flag&MPLP_NO_INDEL) && total_depth < conf->max_indel_depth)
592 {
593 bcf_callaux_clean(conf->bca, &conf->bc);
594 conf->bca->chr = tid>=0 ? hdr->target_name[tid] : NULL;
595 int iret;
596 if (conf->edlib)
597 iret = bcf_edlib_gap_prep(conf->gplp->n, conf->gplp->n_plp, conf->gplp->plp, pos, conf->bca, ref, ref_len);
598 else if ( conf->indels_v20 )
599 iret = bcf_iaux_gap_prep(conf->gplp->n, conf->gplp->n_plp, conf->gplp->plp, pos, conf->bca, ref);
600 else
601 iret = bcf_call_gap_prep(conf->gplp->n, conf->gplp->n_plp, conf->gplp->plp, pos, conf->bca, ref);
602 if ( iret>=0 )
603 {
604 for (i = 0; i < conf->gplp->n; ++i)
605 bcf_call_glfgen(conf->gplp->n_plp[i], conf->gplp->plp[i], -1, conf->bca, conf->bcr + i);
606 if (bcf_call_combine(conf->gplp->n, conf->bcr, conf->bca, -1, &conf->bc) >= 0)
607 {
608 bcf_clear1(conf->bcf_rec);
609 bcf_call2bcf(&conf->bc, conf->bcf_rec, conf->bcr, conf->fmt_flag, conf->bca, ref);
610 flush_bcf_records(conf, conf->bcf_fp, conf->bcf_hdr, conf->bcf_rec);
611 }
612 }
613 }
614 }
615 return ret;
616 }
617
618 static int mpileup(mplp_conf_t *conf)
619 {
620 if (conf->nfiles == 0) {
621 fprintf(stderr,"[%s] no input file/data given\n", __func__);
622 exit(EXIT_FAILURE);
623 }
624
625 mplp_ref_t mp_ref = MPLP_REF_INIT;
626 conf->gplp = (mplp_pileup_t *) calloc(1,sizeof(mplp_pileup_t));
627 conf->mplp_data = (mplp_aux_t**) calloc(conf->nfiles, sizeof(mplp_aux_t*));
628 conf->plp = (const bam_pileup1_t**) calloc(conf->nfiles, sizeof(bam_pileup1_t*));
629 conf->n_plp = (int*) calloc(conf->nfiles, sizeof(int));
630
631 // Allow to run mpileup on multiple regions in one go. This comes at cost: the bai index
632 // must be kept in the memory for the whole time which can be a problem with many bams.
633 // Therefore if none or only one region is requested, we initialize the bam iterator as
634 // before and free the index. Only when multiple regions are queried, we keep the index.
635 int nregs = 0;
636 if ( conf->reg_fname )
637 {
638 if ( conf->reg_is_file )
639 {
640 conf->reg = regidx_init(conf->reg_fname,NULL,NULL,0,NULL);
641 if ( !conf->reg ) {
642 fprintf(stderr,"Could not parse the regions: %s\n", conf->reg_fname);
643 exit(EXIT_FAILURE);
644 }
645 }
646 else
647 {
648 conf->reg = regidx_init(NULL,regidx_parse_reg,NULL,sizeof(char*),NULL);
649 if ( regidx_insert_list(conf->reg,conf->reg_fname,',') !=0 ) {
650 fprintf(stderr,"Could not parse the regions: %s\n", conf->reg_fname);
651 exit(EXIT_FAILURE);
652 }
653 }
654 nregs = regidx_nregs(conf->reg);
655 if ( nregs )
656 {
657 // the regions list can be empty, see #2250
658 conf->reg_itr = regitr_init(conf->reg);
659 regitr_loop(conf->reg_itr); // region iterator now positioned at the first region
660 }
661 }
662
663 // read the header of each file in the list and initialize data
664 // beware: mpileup has always assumed that tid's are consistent in the headers, add sanity check at least!
665 bam_hdr_t *hdr = NULL; // header of first file in input list
666 int i;
667 for (i = 0; i < conf->nfiles; ++i) {
668 bam_hdr_t *h_tmp;
669 conf->mplp_data[i] = (mplp_aux_t*) calloc(1, sizeof(mplp_aux_t));
670 conf->mplp_data[i]->fp = sam_open(conf->files[i], "rb");
671 if ( !conf->mplp_data[i]->fp )
672 {
673 fprintf(stderr, "[%s] failed to open %s: %s\n", __func__, conf->files[i], strerror(errno));
674 exit(EXIT_FAILURE);
675 }
676 if (hts_set_opt(conf->mplp_data[i]->fp, CRAM_OPT_DECODE_MD, 1)) {
677 fprintf(stderr, "Failed to set CRAM_OPT_DECODE_MD value\n");
678 exit(EXIT_FAILURE);
679 }
680 if (conf->fai_fname && hts_set_fai_filename(conf->mplp_data[i]->fp, conf->fai_fname) != 0) {
681 fprintf(stderr, "[%s] failed to process %s: %s\n",
682 __func__, conf->fai_fname, strerror(errno));
683 exit(EXIT_FAILURE);
684 }
685 conf->mplp_data[i]->conf = conf;
686 conf->mplp_data[i]->ref = &mp_ref;
687 h_tmp = sam_hdr_read(conf->mplp_data[i]->fp);
688 if ( !h_tmp ) {
689 fprintf(stderr,"[%s] fail to read the header of %s\n", __func__, conf->files[i]);
690 exit(EXIT_FAILURE);
691 }
692 conf->mplp_data[i]->h = i ? hdr : h_tmp; // for j==0, "h" has not been set yet
693 conf->mplp_data[i]->bam_id = bam_smpl_add_bam(conf->bsmpl,h_tmp->text,conf->files[i]);
694 if ( conf->mplp_data[i]->bam_id<0 )
695 {
696 // no usable readgroups in this bam, it can be skipped
697 sam_close(conf->mplp_data[i]->fp);
698 free(conf->mplp_data[i]);
699 bam_hdr_destroy(h_tmp);
700 free(conf->files[i]);
701 if ( i+1<conf->nfiles ) memmove(&conf->files[i],&conf->files[i+1],sizeof(*conf->files)*(conf->nfiles-i-1));
702 conf->nfiles--;
703 i--;
704 continue;
705 }
706 if (conf->reg && nregs) {
707 hts_idx_t *idx = sam_index_load(conf->mplp_data[i]->fp, conf->files[i]);
708 if (idx == NULL) {
709 fprintf(stderr, "[%s] fail to load index for %s\n", __func__, conf->files[i]);
710 exit(EXIT_FAILURE);
711 }
712 conf->buf.l = 0;
713 ksprintf(&conf->buf,"%s:%u-%u",conf->reg_itr->seq,conf->reg_itr->beg+1,conf->reg_itr->end+1);
714 conf->mplp_data[i]->iter = sam_itr_querys(idx, conf->mplp_data[i]->h, conf->buf.s);
715 if ( !conf->mplp_data[i]->iter )
716 {
717 conf->mplp_data[i]->iter = sam_itr_querys(idx, conf->mplp_data[i]->h, conf->reg_itr->seq);
718 if ( conf->mplp_data[i]->iter ) {
719 fprintf(stderr,"[E::%s] fail to parse region '%s'\n", __func__, conf->buf.s);
720 exit(EXIT_FAILURE);
721 }
722 fprintf(stderr,"[E::%s] the sequence \"%s\" not found: %s\n",__func__,conf->reg_itr->seq,conf->files[i]);
723 exit(EXIT_FAILURE);
724 }
725 if ( nregs==1 ) // no need to keep the index in memory
726 hts_idx_destroy(idx);
727 else
728 conf->mplp_data[i]->idx = idx;
729 }
730
731 if ( !hdr ) hdr = h_tmp; /* save the header of first file in list */
732 else {
733 // FIXME: check consistency between h and h_tmp
734 bam_hdr_destroy(h_tmp);
735
736 // we store only the first file's header; it's (alleged to be)
737 // compatible with the i-th file's target_name lookup needs
738 conf->mplp_data[i]->h = hdr;
739 }
740 }
741 if ( !hdr ) {
742 fprintf(stderr, "[%s] failed to find a file header with usable read groups\n", __func__);
743 exit(EXIT_FAILURE);
744 }
745 // allocate data storage proportionate to number of samples being studied sm->n
746 bam_smpl_get_samples(conf->bsmpl, &conf->gplp->n);
747 conf->gplp->n_plp = (int*) calloc(conf->gplp->n, sizeof(int));
748 conf->gplp->m_plp = (int*) calloc(conf->gplp->n, sizeof(int));
749 conf->gplp->plp = (bam_pileup1_t**) calloc(conf->gplp->n, sizeof(bam_pileup1_t*));
750
751 fprintf(stderr, "[%s] %d samples in %d input files\n", __func__, conf->gplp->n, conf->nfiles);
752 // write the VCF header
753 char wmode[8];
754 set_wmode(wmode,conf->output_type,conf->output_fname,conf->clevel);
755 conf->bcf_fp = hts_open(conf->output_fname ? conf->output_fname : "-", wmode);
756 if (conf->bcf_fp == NULL) {
757 fprintf(stderr, "[%s] failed to write to %s: %s\n", __func__, conf->output_fname? conf->output_fname : "standard output", strerror(errno));
758 exit(EXIT_FAILURE);
759 }
760 if ( conf->n_threads ) hts_set_threads(conf->bcf_fp, conf->n_threads);
761
762 // BCF header creation
763 conf->bcf_hdr = bcf_hdr_init("w");
764 conf->buf.l = 0;
765
766 if (conf->record_cmd_line)
767 {
768 ksprintf(&conf->buf, "##bcftoolsVersion=%s+htslib-%s\n",bcftools_version(),hts_version());
769 bcf_hdr_append(conf->bcf_hdr, conf->buf.s);
770
771 conf->buf.l = 0;
772 ksprintf(&conf->buf, "##bcftoolsCommand=mpileup");
773 for (i=1; i<conf->argc; i++) ksprintf(&conf->buf, " %s", conf->argv[i]);
774 kputc('\n', &conf->buf);
775 bcf_hdr_append(conf->bcf_hdr, conf->buf.s);
776 }
777
778 if (conf->fai_fname)
779 {
780 conf->buf.l = 0;
781 ksprintf(&conf->buf, "##reference=file://%s\n", conf->fai_fname);
782 bcf_hdr_append(conf->bcf_hdr, conf->buf.s);
783 }
784
785 // Translate BAM @SQ tags to BCF ##contig tags
786 // todo: use/write new BAM header manipulation routines, fill also UR, M5
787 for (i=0; i<hdr->n_targets; i++)
788 {
789 conf->buf.l = 0;
790 ksprintf(&conf->buf, "##contig=<ID=%s,length=%d>", hdr->target_name[i], hdr->target_len[i]);
791 bcf_hdr_append(conf->bcf_hdr, conf->buf.s);
792 }
793 conf->buf.l = 0;
794
795 bcf_hdr_append(conf->bcf_hdr,"##ALT=<ID=*,Description=\"Represents allele(s) other than observed.\">");
796 bcf_hdr_append(conf->bcf_hdr,"##INFO=<ID=INDEL,Number=0,Type=Flag,Description=\"Indicates that the variant is an INDEL.\">");
797 if ( conf->fmt_flag&B2B_INFO_IDV )
798 bcf_hdr_append(conf->bcf_hdr,"##INFO=<ID=IDV,Number=1,Type=Integer,Description=\"Maximum number of raw reads supporting an indel\">");
799 if ( conf->fmt_flag&B2B_INFO_IMF )
800 bcf_hdr_append(conf->bcf_hdr,"##INFO=<ID=IMF,Number=1,Type=Float,Description=\"Maximum fraction of raw reads supporting an indel\">");
801 bcf_hdr_append(conf->bcf_hdr,"##INFO=<ID=DP,Number=1,Type=Integer,Description=\"Raw read depth\">");
802 if ( conf->fmt_flag&B2B_INFO_VDB )
803 bcf_hdr_append(conf->bcf_hdr,"##INFO=<ID=VDB,Number=1,Type=Float,Description=\"Variant Distance Bias for filtering splice-site artefacts in RNA-seq data (bigger is better)\",Version=\"3\">");
804
805 if ( conf->fmt_flag&B2B_INFO_RPBZ )
806 bcf_hdr_append(conf->bcf_hdr,"##INFO=<ID=RPBZ,Number=1,Type=Float,Description=\"Mann-Whitney U-z test of Read Position Bias (closer to 0 is better)\">");
807 if ( conf->fmt_flag&B2B_INFO_MQBZ )
808 bcf_hdr_append(conf->bcf_hdr,"##INFO=<ID=MQBZ,Number=1,Type=Float,Description=\"Mann-Whitney U-z test of Mapping Quality Bias (closer to 0 is better)\">");
809 if ( conf->fmt_flag&B2B_INFO_BQBZ )
810 bcf_hdr_append(conf->bcf_hdr,"##INFO=<ID=BQBZ,Number=1,Type=Float,Description=\"Mann-Whitney U-z test of Base Quality Bias (closer to 0 is better)\">");
811 if ( conf->fmt_flag&B2B_INFO_MQSBZ )
812 bcf_hdr_append(conf->bcf_hdr,"##INFO=<ID=MQSBZ,Number=1,Type=Float,Description=\"Mann-Whitney U-z test of Mapping Quality vs Strand Bias (closer to 0 is better)\">");
813 if ( conf->fmt_flag&B2B_INFO_MIN_PL_SUM )
814 bcf_hdr_append(conf->bcf_hdr,"##INFO=<ID=MIN_PL_SUM,Number=1,Type=Integer,Description=\"Sum of min PLs across all samples before normalization (experimental)\">");
815 if ( conf->fmt_flag&B2B_INFO_NM )
816 bcf_hdr_append(conf->bcf_hdr,"##INFO=<ID=NM,Number=2,Type=Float,Description=\"Average number of mismatches in ref and alt reads (approximate, experimental, make me localized?)\">");
817 if ( conf->fmt_flag&B2B_INFO_NMBZ )
818 bcf_hdr_append(conf->bcf_hdr,"##INFO=<ID=NMBZ,Number=1,Type=Float,Description=\"Mann-Whitney U-z test of Number of Mismatches within supporting reads (closer to 0 is better; approximate, experimental, make me localized?)\">");
819 if ( conf->fmt_flag&B2B_FMT_NMBZ )
820 bcf_hdr_append(conf->bcf_hdr,"##FORMAT=<ID=NMBZ,Number=1,Type=Float,Description=\"Mann-Whitney U-z test of Number of Mismatches within supporting reads (closer to 0 is better)\">");
821 if ( conf->fmt_flag&B2B_INFO_SCBZ )
822 bcf_hdr_append(conf->bcf_hdr,"##INFO=<ID=SCBZ,Number=1,Type=Float,Description=\"Mann-Whitney U-z test of Soft-Clip Length Bias (closer to 0 is better)\">");
823 if ( conf->fmt_flag&B2B_INFO_FS )
824 bcf_hdr_append(conf->bcf_hdr,"##INFO=<ID=FS,Number=1,Type=Float,Description=\"Fisher's exact test P-value to detect strand bias\">");
825 if ( conf->fmt_flag&B2B_INFO_SGB )
826 bcf_hdr_append(conf->bcf_hdr,"##INFO=<ID=SGB,Number=1,Type=Float,Description=\"Segregation based metric, http://samtools.github.io/bcftools/rd-SegBias.pdf\">");
827 if ( conf->fmt_flag&B2B_INFO_MQ0F )
828 bcf_hdr_append(conf->bcf_hdr,"##INFO=<ID=MQ0F,Number=1,Type=Float,Description=\"Fraction of MQ0 reads (smaller is better)\">");
829 bcf_hdr_append(conf->bcf_hdr,"##INFO=<ID=I16,Number=16,Type=Float,Description=\"Auxiliary tag used for calling, see description of bcf_callret1_t in bam2bcf.h\">");
830 bcf_hdr_append(conf->bcf_hdr,"##INFO=<ID=QS,Number=R,Type=Float,Description=\"Auxiliary tag used for calling\">");
831 bcf_hdr_append(conf->bcf_hdr,"##FORMAT=<ID=PL,Number=G,Type=Integer,Description=\"List of Phred-scaled genotype likelihoods\">");
832 if ( conf->fmt_flag&B2B_FMT_DP )
833 bcf_hdr_append(conf->bcf_hdr,"##FORMAT=<ID=DP,Number=1,Type=Integer,Description=\"Number of high-quality bases\">");
834 if ( conf->fmt_flag&B2B_FMT_DV )
835 bcf_hdr_append(conf->bcf_hdr,"##FORMAT=<ID=DV,Number=1,Type=Integer,Description=\"Number of high-quality non-reference bases\">");
836 if ( conf->fmt_flag&B2B_FMT_DPR )
837 bcf_hdr_append(conf->bcf_hdr,"##FORMAT=<ID=DPR,Number=R,Type=Integer,Description=\"Number of high-quality bases observed for each allele\">");
838 if ( conf->fmt_flag&B2B_INFO_DPR )
839 bcf_hdr_append(conf->bcf_hdr,"##INFO=<ID=DPR,Number=R,Type=Integer,Description=\"Number of high-quality bases observed for each allele\">");
840 if ( conf->fmt_flag&B2B_FMT_DP4 )
841 bcf_hdr_append(conf->bcf_hdr,"##FORMAT=<ID=DP4,Number=4,Type=Integer,Description=\"Number of high-quality ref-fwd, ref-reverse, alt-fwd and alt-reverse bases\">");
842 if ( conf->fmt_flag&B2B_FMT_SP )
843 bcf_hdr_append(conf->bcf_hdr,"##FORMAT=<ID=SP,Number=1,Type=Integer,Description=\"Phred-scaled strand bias P-value\">");
844 if ( conf->fmt_flag&B2B_FMT_AD )
845 bcf_hdr_append(conf->bcf_hdr,"##FORMAT=<ID=AD,Number=R,Type=Integer,Description=\"Allelic depths (high-quality bases)\">");
846 if ( conf->fmt_flag&B2B_FMT_ADF )
847 bcf_hdr_append(conf->bcf_hdr,"##FORMAT=<ID=ADF,Number=R,Type=Integer,Description=\"Allelic depths on the forward strand (high-quality bases)\">");
848 if ( conf->fmt_flag&B2B_FMT_ADR )
849 bcf_hdr_append(conf->bcf_hdr,"##FORMAT=<ID=ADR,Number=R,Type=Integer,Description=\"Allelic depths on the reverse strand (high-quality bases)\">");
850 if ( conf->fmt_flag&B2B_FMT_QS )
851 bcf_hdr_append(conf->bcf_hdr,"##FORMAT=<ID=QS,Number=R,Type=Integer,Description=\"Phred-score allele quality sum used by `call -mG` and `+trio-dnm`\">");
852 if ( conf->fmt_flag&B2B_INFO_AD )
853 bcf_hdr_append(conf->bcf_hdr,"##INFO=<ID=AD,Number=R,Type=Integer,Description=\"Total allelic depths (high-quality bases)\">");
854 if ( conf->fmt_flag&B2B_INFO_ADF )
855 bcf_hdr_append(conf->bcf_hdr,"##INFO=<ID=ADF,Number=R,Type=Integer,Description=\"Total allelic depths on the forward strand (high-quality bases)\">");
856 if ( conf->fmt_flag&B2B_INFO_SCR )
857 bcf_hdr_append(conf->bcf_hdr,"##INFO=<ID=SCR,Number=1,Type=Integer,Description=\"Number of soft-clipped reads (at high-quality bases)\">");
858 if ( conf->fmt_flag&B2B_FMT_SCR )
859 bcf_hdr_append(conf->bcf_hdr,"##FORMAT=<ID=SCR,Number=1,Type=Integer,Description=\"Per-sample number of soft-clipped reads (at high-quality bases)\">");
860 if ( conf->fmt_flag&B2B_INFO_ADR )
861 bcf_hdr_append(conf->bcf_hdr,"##INFO=<ID=ADR,Number=R,Type=Integer,Description=\"Total allelic depths on the reverse strand (high-quality bases)\">");
862 if ( conf->gvcf )
863 gvcf_update_header(conf->gvcf, conf->bcf_hdr);
864
865 int nsmpl;
866 const char **smpl = bam_smpl_get_samples(conf->bsmpl, &nsmpl);
867 for (i=0; i<nsmpl; i++)
868 bcf_hdr_add_sample(conf->bcf_hdr, smpl[i]);
869 if ( bcf_hdr_write(conf->bcf_fp, conf->bcf_hdr)!=0 ) error("[%s] Error: failed to write the header to %s\n",__func__,conf->output_fname?conf->output_fname:"standard output");
870 if ( init_index2(conf->bcf_fp,conf->bcf_hdr,conf->output_fname,
871 &conf->index_fn, conf->write_index) < 0 )
872 error("Error: failed to initialise index for %s\n",conf->output_fname);
873
874 conf->bca = bcf_call_init(-1., conf->min_baseQ, conf->max_baseQ,
875 conf->delta_baseQ);
876 conf->bcr = (bcf_callret1_t*) calloc(nsmpl, sizeof(bcf_callret1_t));
877 conf->bca->openQ = conf->openQ, conf->bca->extQ = conf->extQ, conf->bca->tandemQ = conf->tandemQ;
878 conf->bca->indel_bias = conf->indel_bias;
879 conf->bca->del_bias = conf->del_bias;
880 conf->bca->min_frac = conf->min_frac;
881 conf->bca->min_support = conf->min_support;
882 conf->bca->per_sample_flt = conf->flag & MPLP_PER_SAMPLE;
883 conf->bca->fmt_flag = conf->fmt_flag;
884 conf->bca->ambig_reads = conf->ambig_reads;
885 conf->bca->indel_win_size = conf->indel_win_size;
886 conf->bca->indels_v20 = conf->indels_v20;
887 conf->bca->edlib = conf->edlib;
888 conf->bca->seqQ_offset = conf->seqQ_offset;
889 conf->bca->poly_mqual = conf->poly_mqual;
890 conf->bca->vs_ref = conf->vs_ref;
891
892 conf->bc.bcf_hdr = conf->bcf_hdr;
893 conf->bc.n = nsmpl;
894 conf->bc.PL = (int32_t*) malloc(15 * nsmpl * sizeof(*conf->bc.PL));
895 conf->bc.QS = (int32_t*) malloc(nsmpl*sizeof(*conf->bc.QS)*B2B_MAX_ALLELES);
896 for (i=0; i<nsmpl; i++)
897 conf->bcr[i].QS = conf->bc.QS + i*B2B_MAX_ALLELES;
898 if (conf->fmt_flag)
899 {
900 assert( sizeof(float)==sizeof(int32_t) );
901 conf->bc.DP4 = (int32_t*) malloc(nsmpl * sizeof(int32_t) * 4);
902 conf->bc.fmt_arr = (uint8_t*) malloc(nsmpl * sizeof(float)); // all fmt_flag fields, float and int32
903 if ( conf->fmt_flag&(B2B_INFO_DPR|B2B_FMT_DPR|B2B_INFO_AD|B2B_INFO_ADF|B2B_INFO_ADR|B2B_FMT_AD|B2B_FMT_ADF|B2B_FMT_ADR) )
904 {
905 // first B2B_MAX_ALLELES fields for total numbers, the rest per-sample
906 conf->bc.ADR = (int32_t*) malloc((nsmpl+1)*B2B_MAX_ALLELES*sizeof(int32_t));
907 conf->bc.ADF = (int32_t*) malloc((nsmpl+1)*B2B_MAX_ALLELES*sizeof(int32_t));
908 for (i=0; i<nsmpl; i++)
909 {
910 conf->bcr[i].ADR = conf->bc.ADR + (i+1)*B2B_MAX_ALLELES;
911 conf->bcr[i].ADF = conf->bc.ADF + (i+1)*B2B_MAX_ALLELES;
912 }
913 }
914 if ( conf->fmt_flag&(B2B_INFO_SCR|B2B_FMT_SCR) )
915 conf->bc.SCR = (int32_t*) malloc((nsmpl+1)*sizeof(*conf->bc.SCR));
916 }
917 int nnmbz = (conf->fmt_flag&B2B_FMT_NMBZ) ? nsmpl + 1 : 1;
918 conf->bc.ref_nm = (int32_t*) malloc(sizeof(*conf->bc.ref_nm) * nnmbz * B2B_N_NM);
919 conf->bc.alt_nm = (int32_t*) malloc(sizeof(*conf->bc.alt_nm) * nnmbz * B2B_N_NM);
920 conf->bc.mwu_nm = (float*) malloc((nsmpl+1)*sizeof(*conf->bc.mwu_nm));
921 conf->bca->ref_nm = conf->bc.ref_nm; // this is just to make the arrays available in bcf_call_glfgen()
922 conf->bca->alt_nm = conf->bc.alt_nm;
923 if ( conf->fmt_flag&B2B_FMT_NMBZ )
924 {
925 for (i=0; i<nsmpl; i++) conf->bcr[i].ref_nm = conf->bc.ref_nm + (i+1)*B2B_N_NM;
926 for (i=0; i<nsmpl; i++) conf->bcr[i].alt_nm = conf->bc.alt_nm + (i+1)*B2B_N_NM;
927 }
928
929 // init mpileup
930 conf->iter = bam_mplp_init(conf->nfiles, mplp_func, (void**)conf->mplp_data);
931 if ( conf->flag & MPLP_SMART_OVERLAPS ) bam_mplp_init_overlaps(conf->iter);
932 fprintf(stderr, "[%s] maximum number of reads per input file set to -d %d\n", __func__, conf->max_depth);
933 if ( (double)conf->max_depth * conf->nfiles > 1<<20)
934 fprintf(stderr, "Warning: Potential memory hog, up to %.0fM reads in the pileup!\n", (double)conf->max_depth*conf->nfiles);
935 if ( (double)conf->max_depth * conf->nfiles / nsmpl < 250 )
936 fprintf(stderr, "Note: The maximum per-sample depth with -d %d is %.1fx\n", conf->max_depth,(double)conf->max_depth * conf->nfiles / nsmpl);
937 bam_mplp_set_maxcnt(conf->iter, conf->max_depth);
938 conf->max_indel_depth = conf->max_indel_depth * nsmpl;
939 conf->bcf_rec = bcf_init1();
940 bam_mplp_constructor(conf->iter, pileup_constructor);
941 bam_mplp_destructor(conf->iter, pileup_destructor);
942
943
944 // Run mpileup for multiple regions
945 int ret = 0;
946 if ( nregs )
947 {
948 int ireg = 0;
949 do
950 {
951 // first region is already positioned
952 if ( ireg++ > 0 )
953 {
954 conf->buf.l = 0;
955 ksprintf(&conf->buf,"%s:%u-%u",conf->reg_itr->seq,conf->reg_itr->beg+1,conf->reg_itr->end+1);
956
957 for (i=0; i<conf->nfiles; i++)
958 {
959 hts_itr_destroy(conf->mplp_data[i]->iter);
960 conf->mplp_data[i]->iter = sam_itr_querys(conf->mplp_data[i]->idx, conf->mplp_data[i]->h, conf->buf.s);
961 if ( !conf->mplp_data[i]->iter )
962 {
963 conf->mplp_data[i]->iter = sam_itr_querys(conf->mplp_data[i]->idx, conf->mplp_data[i]->h, conf->reg_itr->seq);
964 if ( conf->mplp_data[i]->iter ) {
965 fprintf(stderr,"[E::%s] fail to parse region '%s'\n", __func__, conf->buf.s);
966 exit(EXIT_FAILURE);
967 }
968 fprintf(stderr,"[E::%s] the sequence \"%s\" not found: %s\n",__func__,conf->reg_itr->seq,conf->files[i]);
969 exit(EXIT_FAILURE);
970 }
971 bam_mplp_reset(conf->iter);
972 }
973 }
974 ret = mpileup_reg(conf,conf->reg_itr->beg,conf->reg_itr->end);
975 if ( ret<0 ) break;
976 }
977 while ( regitr_loop(conf->reg_itr) );
978 }
979 else if ( !conf->reg )
980 ret = mpileup_reg(conf,0,UINT32_MAX);
981 if ( ret<0 )
982 {
983 fprintf(stderr, "[%s] failed to read from input file\n", __func__);
984 exit(EXIT_FAILURE);
985 }
986
987 flush_bcf_records(conf, conf->bcf_fp, conf->bcf_hdr, NULL);
988
989 // clean up
990 free(conf->bc.tmp.s);
991 bcf_destroy1(conf->bcf_rec);
992 if (conf->bcf_fp)
993 {
994 if ( conf->write_index )
995 {
996 if ( bcf_idx_save(conf->bcf_fp)<0 )
997 {
998 if ( hts_close(conf->bcf_fp)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,conf->output_fname);
999 error("Error: cannot write to index %s\n",conf->index_fn);
1000 }
1001 free(conf->index_fn);
1002 }
1003 if ( hts_close(conf->bcf_fp)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,conf->output_fname);
1004 bcf_hdr_destroy(conf->bcf_hdr);
1005 bcf_call_destroy(conf->bca);
1006 free(conf->bc.PL);
1007 free(conf->bc.DP4);
1008 free(conf->bc.ADR);
1009 free(conf->bc.ADF);
1010 free(conf->bc.SCR);
1011 free(conf->bc.QS);
1012 free(conf->bc.ref_nm);
1013 free(conf->bc.alt_nm);
1014 free(conf->bc.fmt_arr);
1015 free(conf->bc.mwu_nm);
1016 free(conf->bcr);
1017 }
1018 if ( conf->gvcf ) gvcf_destroy(conf->gvcf);
1019 free(conf->buf.s);
1020 for (i = 0; i < conf->gplp->n; ++i) free(conf->gplp->plp[i]);
1021 free(conf->gplp->plp); free(conf->gplp->n_plp); free(conf->gplp->m_plp); free(conf->gplp);
1022 bam_mplp_destroy(conf->iter);
1023 bam_hdr_destroy(hdr);
1024 for (i = 0; i < conf->nfiles; ++i) {
1025 if ( nregs>1 ) hts_idx_destroy(conf->mplp_data[i]->idx);
1026 sam_close(conf->mplp_data[i]->fp);
1027 if ( conf->mplp_data[i]->iter) hts_itr_destroy(conf->mplp_data[i]->iter);
1028 free(conf->mplp_data[i]);
1029 }
1030 if ( conf->reg_itr ) regitr_destroy(conf->reg_itr);
1031 free(conf->mplp_data); free(conf->plp); free(conf->n_plp);
1032 free(mp_ref.ref[0]);
1033 free(mp_ref.ref[1]);
1034 return 0;
1035 }
1036
1037 static int is_url(const char *s)
1038 {
1039 static const char uri_scheme_chars[] =
1040 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+.-";
1041 return s[strspn(s, uri_scheme_chars)] == ':';
1042 }
1043
1044 #define MAX_PATH_LEN 1024
1045 int read_file_list(const char *file_list,int *n,char **argv[])
1046 {
1047 char buf[MAX_PATH_LEN];
1048 int len, nfiles = 0;
1049 char **files = NULL;
1050 struct stat sb;
1051
1052 *n = 0;
1053 *argv = NULL;
1054
1055 FILE *fh = fopen(file_list,"r");
1056 if ( !fh )
1057 {
1058 fprintf(stderr,"%s: %s\n", file_list,strerror(errno));
1059 return 1;
1060 }
1061
1062 files = (char**) calloc(nfiles,sizeof(char*));
1063 nfiles = 0;
1064 while ( fgets(buf,MAX_PATH_LEN,fh) )
1065 {
1066 // allow empty lines and trailing spaces
1067 len = strlen(buf);
1068 while ( len>0 && isspace(buf[len-1]) ) len--;
1069 if ( !len ) continue;
1070
1071 // check sanity of the file list
1072 buf[len] = 0;
1073 if (! (is_url(buf) || stat(buf, &sb) == 0))
1074 {
1075 // no such file, check if it is safe to print its name
1076 int i, safe_to_print = 1;
1077 for (i=0; i<len; i++)
1078 if (!isprint(buf[i])) { safe_to_print = 0; break; }
1079 if ( safe_to_print )
1080 fprintf(stderr,"The file list \"%s\" appears broken, could not locate: %s\n", file_list,buf);
1081 else
1082 fprintf(stderr,"Does the file \"%s\" really contain a list of files and do all exist?\n", file_list);
1083 return 1;
1084 }
1085
1086 nfiles++;
1087 files = (char**) realloc(files,nfiles*sizeof(char*));
1088 files[nfiles-1] = strdup(buf);
1089 }
1090 if ( fclose(fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,file_list);
1091 if ( !nfiles )
1092 {
1093 fprintf(stderr,"No files read from %s\n", file_list);
1094 return 1;
1095 }
1096 *argv = files;
1097 *n = nfiles;
1098 return 0;
1099 }
1100 #undef MAX_PATH_LEN
1101
1102 #define SET_FMT_FLAG(str,bit,msg) \
1103 if (!strcasecmp(tag,str) || !strcasecmp(tag,"FMT/"str) || !strcasecmp(tag,"FORMAT/"str)) \
1104 { \
1105 if ( *msg ) fprintf(stderr,"%s",msg); \
1106 if ( exclude ) \
1107 *flag &= ~bit; \
1108 else \
1109 *flag |= bit; \
1110 free(tags[i]); \
1111 continue; \
1112 }
1113 #define SET_INFO_FLAG(str,bit,msg) if (!strcasecmp(tag,"INFO/"str)) \
1114 { \
1115 if ( exclude ) \
1116 *flag &= ~bit; \
1117 else \
1118 *flag |= bit; \
1119 free(tags[i]); \
1120 continue; \
1121 }
1122
1123 void parse_format_flag(uint32_t *flag, const char *str)
1124 {
1125 int i, n_tags;
1126 char **tags = hts_readlist(str, 0, &n_tags);
1127 for(i=0; i<n_tags; i++)
1128 {
1129 int exclude = tags[i][0]=='-' ? 1 : 0;
1130 char *tag = exclude ? tags[i]+1 : tags[i];
1131 SET_FMT_FLAG("AD", B2B_FMT_AD, "");
1132 SET_FMT_FLAG("ADF", B2B_FMT_ADF, "");
1133 SET_FMT_FLAG("ADR", B2B_FMT_ADR, "");
1134 SET_FMT_FLAG("DP", B2B_FMT_DP, "");
1135 SET_FMT_FLAG("DP4", B2B_FMT_DP4, "[warning] tag DP4 functional, but deprecated. Please switch to `ADF` and `ADR` in future.\n");
1136 SET_FMT_FLAG("DPR", B2B_FMT_DPR, "[warning] tag DPR functional, but deprecated. Please switch to `AD` in future.\n");
1137 SET_FMT_FLAG("DV", B2B_FMT_DV, "[warning] tag DV functional, but deprecated. Please switch to `AD` in future.\n");
1138 SET_FMT_FLAG("NMBZ", B2B_FMT_NMBZ, "");
1139 SET_FMT_FLAG("QS", B2B_FMT_QS, "");
1140 SET_FMT_FLAG("SP", B2B_FMT_SP, "");
1141 SET_FMT_FLAG("SCR", B2B_FMT_SCR, "");
1142 SET_INFO_FLAG("DPR", B2B_INFO_DPR, "[warning] tag INFO/DPR functional, but deprecated. Please switch to `INFO/AD` in future.\n");
1143 SET_INFO_FLAG("AD", B2B_INFO_AD, "");
1144 SET_INFO_FLAG("ADF", B2B_INFO_ADF, "");
1145 SET_INFO_FLAG("ADR", B2B_INFO_ADR, "");
1146 SET_INFO_FLAG("BQBZ", B2B_INFO_BQBZ, "");
1147 SET_INFO_FLAG("FS", B2B_INFO_FS, "");
1148 SET_INFO_FLAG("IDV", B2B_INFO_IDV, "");
1149 SET_INFO_FLAG("IMF", B2B_INFO_IMF, "");
1150 SET_INFO_FLAG("MIN_PL_SUM", B2B_INFO_MIN_PL_SUM, "");
1151 SET_INFO_FLAG("MQ0F", B2B_INFO_MQ0F, "");
1152 SET_INFO_FLAG("MQBZ", B2B_INFO_MQBZ, "");
1153 SET_INFO_FLAG("NM", B2B_INFO_NM, "");
1154 SET_INFO_FLAG("NMBZ", B2B_INFO_NMBZ, "");
1155 SET_INFO_FLAG("RPBZ", B2B_INFO_RPBZ, "");
1156 SET_INFO_FLAG("SCBZ", B2B_INFO_SCBZ, "");
1157 SET_INFO_FLAG("SCR", B2B_INFO_SCR, "");
1158 SET_INFO_FLAG("SGB", B2B_INFO_SGB, "");
1159 SET_INFO_FLAG("VDB", B2B_INFO_VDB, "");
1160 fprintf(stderr,"Could not parse tag \"%s\" in \"%s\"\n", tag, str);
1161 exit(EXIT_FAILURE);
1162 }
1163 if (n_tags) free(tags);
1164 }
1165
1166 // todo: make it possible to turn off some annotations or change the defaults,
1167 // specifically RPB, VDB, MWU, SGB tests. It would be good to do some
1168 // benchmarking first to see if it's worth it.
1169 static void list_annotations(FILE *fp)
1170 {
1171 fprintf(fp,
1172 "Annotations added by default are in this list prefixed with \"*\". To suppress their output, run with\n"
1173 "e.g. \"-a -FORMAT/AD\".\n"
1174 "\n"
1175 "FORMAT annotation tags available (\"FORMAT/\" prefix is optional):\n"
1176 "\n"
1177 "* FORMAT/AD .. Allelic depth (Number=R,Type=Integer)\n"
1178 " FORMAT/ADF .. Allelic depths on the forward strand (Number=R,Type=Integer)\n"
1179 " FORMAT/ADR .. Allelic depths on the reverse strand (Number=R,Type=Integer)\n"
1180 " FORMAT/DP .. Number of high-quality bases (Number=1,Type=Integer)\n"
1181 " FORMAT/NMBZ .. Mann-Whitney U-z test of Number of Mismatches within supporting reads (Number=1,Type=Float)\n"
1182 " FORMAT/QS .. Allele phred-score quality sum for use with `call -mG` and +trio-dnm (Number=R,Type=Integer)\n"
1183 " FORMAT/SP .. Phred-scaled strand bias P-value (Number=1,Type=Integer)\n"
1184 " FORMAT/SCR .. Number of soft-clipped reads (Number=1,Type=Integer)\n"
1185 "\n"
1186 "INFO annotation tags available:\n"
1187 "\n"
1188 " INFO/AD .. Total allelic depth (Number=R,Type=Integer)\n"
1189 " INFO/ADF .. Total allelic depths on the forward strand (Number=R,Type=Integer)\n"
1190 " INFO/ADR .. Total allelic depths on the reverse strand (Number=R,Type=Integer)\n"
1191 "* INFO/BQBZ .. Mann-Whitney U test of Base Quality Bias (Number=1,Type=Float)\n"
1192 " INFO/FS .. Fisher's exact test P-value to detect strand bias (Number=1,Type=Float)\n"
1193 "* INFO/IDV .. Maximum number of raw reads supporting an indel (Number=1,Type=Integer)\n"
1194 "* INFO/IMF .. Maximum fraction of raw reads supporting an indel (Number=1,Type=Float)\n"
1195 " INFO/MIN_PL_SUM\n"
1196 " .. Sum of min PL across all samples before normalization, experimental (Number=1,Type=Integer)\n"
1197 "* INFO/MQ0F .. Fraction of reads with zero mapping quality (Number=1,Type=Float)\n"
1198 "* INFO/MQBZ .. Mann-Whitney U test of Mapping Quality Bias (Number=1,Type=Float)\n"
1199 "* INFO/MQSBZ .. Mann-Whitney U-z test of Mapping Quality vs Strand Bias (Number=1,Type=Float)\n"
1200 " INFO/NM .. Approximate average number of mismatches in ref and alt reads, experimental (Number=2,Type=Float)\n"
1201 " INFO/NMBZ .. Mann-Whitney U-z test of Number of Mismatches within supporting reads (Number=1,Type=Float)\n"
1202 "* INFO/RPBZ .. Mann-Whitney U test of Read Position Bias (Number=1,Type=Float)\n"
1203 "* INFO/SCBZ .. Mann-Whitney U-z test of Soft-Clip Length Bias (Number=1,Type=Float)\n"
1204 " INFO/SCR .. Number of soft-clipped reads (Number=1,Type=Integer)\n"
1205 "* INFO/SGB .. Segregation based metric, http://samtools.github.io/bcftools/rd-SegBias.pdf (Number=1,Type=Float)\n"
1206 "* INFO/VDB .. Variant Distance Bias for filtering splice-site artefacts in RNA-seq data (Number=1,Type=Float)\n"
1207 "\n");
1208 }
1209
1210 static void print_usage(FILE *fp, const mplp_conf_t *mplp)
1211 {
1212 char *tmp_skip_all_set = bam_flag2str(mplp->rflag_skip_all_set);
1213 char *tmp_skip_any_unset = bam_flag2str(mplp->rflag_skip_any_unset);
1214 char *tmp_skip_all_unset = bam_flag2str(mplp->rflag_skip_all_unset);
1215 char *tmp_skip_any_set = bam_flag2str(mplp->rflag_skip_any_set);
1216
1217 // Display usage information, formatted for the standard 80 columns.
1218 // (The unusual string formatting here aids the readability of this
1219 // source code in 80 columns, to the extent that's possible.)
1220
1221 fprintf(fp,
1222 "\n"
1223 "Usage: bcftools mpileup [options] in1.bam [in2.bam [...]]\n"
1224 "\n"
1225 "Input options:\n"
1226 " -6, --illumina1.3+ Quality is in the Illumina-1.3+ encoding\n"
1227 " -A, --count-orphans Include anomalous read pairs, with flag PAIRED but not PROPER_PAIR set\n"
1228 " -b, --bam-list FILE List of input BAM filenames, one per line\n"
1229 " -B, --no-BAQ Disable BAQ (per-Base Alignment Quality)\n"
1230 " -C, --adjust-MQ INT Adjust mapping quality [0]\n"
1231 " -D, --full-BAQ Apply BAQ everywhere, not just in problematic regions\n"
1232 " -d, --max-depth INT Max raw per-file depth; avoids excessive memory usage [%d]\n", mplp->max_depth);
1233 fprintf(fp,
1234 " -E, --redo-BAQ Recalculate BAQ on the fly, ignore existing BQs\n"
1235 " -f, --fasta-ref FILE Faidx indexed reference sequence file\n"
1236 " --no-reference Do not require fasta reference file\n"
1237 " -G, --read-groups FILE Select or exclude read groups listed in the file\n"
1238 " -q, --min-MQ INT Skip alignments with mapQ smaller than INT [%d]\n", mplp->min_mq);
1239 fprintf(fp,
1240 " -Q, --min-BQ INT Skip bases with baseQ/BAQ smaller than INT [%d]\n", mplp->min_baseQ);
1241 fprintf(fp,
1242 " --max-BQ INT Limit baseQ/BAQ to no more than INT [%d]\n", mplp->max_baseQ);
1243 fprintf(fp,
1244 " --delta-BQ INT Use neighbour_qual + INT if less than qual [%d]\n", mplp->delta_baseQ);
1245 fprintf(fp,
1246 " -r, --regions REG[,...] Comma separated list of regions in which pileup is generated\n"
1247 " -R, --regions-file FILE Restrict to regions listed in a file\n"
1248 " --ignore-RG Ignore RG tags (one BAM = one sample)\n"
1249 " --ls, --skip-all-set STR|INT Skip reads with all of the bits set []\n");
1250 fprintf(fp,
1251 " --ns, --skip-any-set STR|INT Skip reads with any of the bits set [%s]\n", tmp_skip_any_set);
1252 fprintf(fp,
1253 " --lu, --skip-all-unset STR|INT Skip reads with all of the bits unset []\n"
1254 " --nu, --skip-any-unset STR|INT Skip reads with any of the bits unset []\n");
1255 fprintf(fp,
1256 " -s, --samples LIST Comma separated list of samples to include\n"
1257 " -S, --samples-file FILE File of samples to include\n"
1258 " -t, --targets REG[,...] Similar to -r but streams rather than index-jumps\n"
1259 " -T, --targets-file FILE Similar to -R but streams rather than index-jumps\n"
1260 " -x, --ignore-overlaps Disable read-pair overlap detection\n"
1261 " --seed INT Random number seed used for sampling deep regions [0]\n"
1262 "\n"
1263 "Output options:\n"
1264 " -a, --annotate LIST Optional tags to output; '\\?' to list available tags []\n"
1265 " -g, --gvcf INT[,...] Group non-variant sites into gVCF blocks according\n"
1266 " To minimum per-sample DP\n"
1267 " --no-version Do not append version and command line to the header\n"
1268 " -o, --output FILE Write output to FILE [standard output]\n"
1269 " -O, --output-type TYPE 'b' compressed BCF; 'u' uncompressed BCF;\n"
1270 " 'z' compressed VCF; 'v' uncompressed VCF; 0-9 compression level [v]\n"
1271 " --threads INT Use multithreading with INT worker threads [0]\n"
1272 " -W, --write-index[=FMT] Automatically index the output files [off]\n"
1273 "\n"
1274 "SNP/INDEL genotype likelihoods options:\n"
1275 " -X, --config STR Specify platform profile (use \"-X list\" for details)\n"
1276 " -e, --ext-prob INT Phred-scaled gap extension seq error probability [%d]\n", mplp->extQ);
1277 fprintf(fp,
1278 " -F, --gap-frac FLOAT Minimum fraction of gapped reads [%g]\n", mplp->min_frac);
1279 fprintf(fp,
1280 " -h, --tandem-qual INT Coefficient for homopolymer errors [%d]\n", mplp->tandemQ);
1281 fprintf(fp,
1282 " -I, --skip-indels Do not perform indel calling\n"
1283 " -L, --max-idepth INT Maximum per-file depth for INDEL calling [%d]\n", mplp->max_indel_depth);
1284 fprintf(fp,
1285 " -m, --min-ireads INT Minimum number gapped reads for indel candidates [%d]\n", mplp->min_support);
1286 fprintf(fp,
1287 " -M, --max-read-len INT Maximum length of read to pass to BAQ algorithm [%d]\n", mplp->max_read_len);
1288 fprintf(fp,
1289 " -o, --open-prob INT Phred-scaled gap open seq error probability [%d]\n", mplp->openQ);
1290 fprintf(fp,
1291 " -p, --per-sample-mF Apply -m and -F per-sample for increased sensitivity\n"
1292 " -P, --platforms STR Comma separated list of platforms for indels [all]\n"
1293 " --ar, --ambig-reads STR What to do with ambiguous indel reads: drop,incAD,incAD0 [drop]\n");
1294 fprintf(fp,
1295 " --indel-bias FLOAT Raise to favour recall over precision [%.2f]\n", mplp->indel_bias);
1296 fprintf(fp,
1297 " --del-bias FLOAT Relative likelihood of insertion to deletion [%.2f]\n", mplp->del_bias);
1298 fprintf(fp,
1299 " --score-vs-ref FLOAT\n"
1300 " Ratio of score vs ref (1) or 2nd-best allele (0) [%.2f]\n", mplp->vs_ref);
1301 fprintf(fp,
1302 " --indel-size INT Approximate maximum indel size considered [%d]\n", mplp->indel_win_size);
1303 fprintf(fp,
1304 " --indels-2.0 New EXPERIMENTAL indel calling model (diploid reference consensus)\n"
1305 " --indels-cns New EXPERIMENTAL indel calling model with edlib\n"
1306 " --seqq-offset Indel-cns tuning for indel seq-qual scores [120]\n"
1307 " --no-indels-cns Disable CNS mode, to use after a -X profile\n"
1308 " --poly-mqual (Edlib mode) Use minimum quality within homopolymers\n");
1309 fprintf(fp,"\n");
1310 fprintf(fp,
1311 "Notes: Assuming diploid individuals.\n\n"
1312 "Example:\n"
1313 " # See also http://samtools.github.io/bcftools/howtos/variant-calling.html\n"
1314 " bcftools mpileup -Ou -f reference.fa alignments.bam | bcftools call -mv -Ob -o calls.bcf\n"
1315 "\n");
1316
1317 free(tmp_skip_all_set);
1318 free(tmp_skip_any_unset);
1319 free(tmp_skip_all_unset);
1320 free(tmp_skip_any_set);
1321 }
1322
1323 static void print_profiles(void) {
1324 printf(
1325 "Configuration profiles activated with -X, --config:\n\n"
1326 "1.12\n"
1327 " -Q13 -h100 -m1 -F0.002\n\n"
1328 "bgi, bgi-1.20\n"
1329 " --indels-cns -B --indel-size 80 -F0.1 --indel-bias 0.9 --seqq-offset 120\n\n"
1330 "illumina-1.18\n"
1331 " --indel-size 110\n\n"
1332 "illumina\n"
1333 "illumina-1.20\n"
1334 " --indels-cns --indel-size 110\n\n"
1335 "ont\n"
1336 " -B -Q5 --max-BQ 30 -I\n\n"
1337 "ont-sup, ont-sup-1.20\n"
1338 " --indels-cns -B -Q1 --max-BQ 35 -F0.2 -o15 -e1 -h110 --delta-BQ 99\\\n"
1339 " --del-bias 0.4 --indel-bias 0.7 --poly-mqual --seqq-offset 130\\\n"
1340 " --indel-size 80\n\n"
1341 "pacbio-ccs-1.18\n"
1342 " -D -Q5 --max-BQ 50 -F0.1 -o25 -e1 --delta-BQ 10 \\\n"
1343 " -M99999 --indel-size 110\n\n"
1344 "pacbio-ccs, pacbio-ccs-1.20\n"
1345 " --indels-cns -B -Q5 --max-BQ 50 -F0.1 -o25 -e1 -h300 --delta-BQ 10 \\\n"
1346 " --del-bias 0.4 --poly-mqual --indel-bias 0.9 --seqq-offset 118\\\n"
1347 " --indel-size 80 --score-vs-ref 0.7\n\n"
1348 "ultima, ultima-1.20\n"
1349 " --indels-cns -B -Q1 --max-BQ 30 -F0.15 -o20 -e10 -h250 --delta-BQ 10 \\\n"
1350 " --del-bias 0.3 --indel-bias 0.7 --poly-mqual --seqq-offset 140 \\\n"
1351 " --indel-size 80 --score-vs-ref 0.3\n\n"
1352 "\n");
1353 }
1354
1355 int main_mpileup(int argc, char *argv[])
1356 {
1357 int c, i, ret = 1;
1358 const char *file_list = NULL;
1359 char **fn = NULL;
1360 int nfiles = 0, use_orphan = 0, noref = 0;
1361 mplp_conf_t mplp;
1362 memset(&mplp, 0, sizeof(mplp_conf_t));
1363 mplp.min_baseQ = 1;
1364 mplp.max_baseQ = 60;
1365 mplp.delta_baseQ = 30;
1366 mplp.capQ_thres = 0;
1367 mplp.max_depth = 250; mplp.max_indel_depth = 250;
1368 mplp.openQ = 40; mplp.extQ = 20; mplp.tandemQ = 500;
1369 mplp.min_frac = 0.05; mplp.indel_bias = 1.0; mplp.min_support = 2;
1370 mplp.vs_ref = 0;
1371 mplp.flag = MPLP_NO_ORPHAN | MPLP_REALN | MPLP_REALN_PARTIAL
1372 | MPLP_SMART_OVERLAPS;
1373 mplp.argc = argc; mplp.argv = argv;
1374 mplp.rflag_skip_any_set = BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP;
1375 mplp.output_fname = NULL;
1376 mplp.output_type = FT_VCF;
1377 mplp.record_cmd_line = 1;
1378 mplp.n_threads = 0;
1379 mplp.bsmpl = bam_smpl_init();
1380 // the default to be changed in future, see also parse_format_flag()
1381 mplp.fmt_flag = B2B_INFO_BQBZ|B2B_INFO_IDV|B2B_INFO_IMF|B2B_INFO_MQ0F|B2B_INFO_MQBZ|B2B_INFO_MQSBZ|B2B_INFO_RPBZ|B2B_INFO_SCBZ|B2B_INFO_SGB|B2B_INFO_VDB|B2B_FMT_AD;
1382 mplp.max_read_len = 500;
1383 mplp.ambig_reads = B2B_DROP;
1384 mplp.indel_win_size = 110;
1385 mplp.poly_mqual = 0;
1386 mplp.seqQ_offset = 120;
1387 mplp.clevel = -1;
1388 mplp.del_bias = 0; // even insertion and deletion likelhoods.
1389 hts_srand48(0);
1390
1391 static const struct option lopts[] =
1392 {
1393 {"nu", required_argument, NULL, 16},
1394 {"lu", required_argument, NULL, 17},
1395 {"rf", required_argument, NULL, 17}, // old --rf, --incl-flags = --lu, --skip-all-unset
1396 {"ns", required_argument, NULL, 18},
1397 {"ff", required_argument, NULL, 18}, // old --ff, --excl-flags = --ns, --skip-any-set
1398 {"ls", required_argument, NULL, 19},
1399 {"skip-any-unset", required_argument, NULL, 16},
1400 {"skip-all-unset", required_argument, NULL, 17},
1401 {"skip-any-set", required_argument, NULL, 18},
1402 {"skip-all-set", required_argument, NULL, 19},
1403 {"output", required_argument, NULL, 3},
1404 {"open-prob", required_argument, NULL, 4},
1405 {"ignore-RG", no_argument, NULL, 5},
1406 {"ignore-rg", no_argument, NULL, 5},
1407 {"gvcf", required_argument, NULL, 'g'},
1408 {"no-reference", no_argument, NULL, 7},
1409 {"no-version", no_argument, NULL, 8},
1410 {"threads",required_argument,NULL,9},
1411 {"illumina1.3+", no_argument, NULL, '6'},
1412 {"count-orphans", no_argument, NULL, 'A'},
1413 {"bam-list", required_argument, NULL, 'b'},
1414 {"no-BAQ", no_argument, NULL, 'B'},
1415 {"no-baq", no_argument, NULL, 'B'},
1416 {"full-BAQ", no_argument, NULL, 'D'},
1417 {"full-baq", no_argument, NULL, 'D'},
1418 {"adjust-MQ", required_argument, NULL, 'C'},
1419 {"adjust-mq", required_argument, NULL, 'C'},
1420 {"max-depth", required_argument, NULL, 'd'},
1421 {"redo-BAQ", no_argument, NULL, 'E'},
1422 {"redo-baq", no_argument, NULL, 'E'},
1423 {"fasta-ref", required_argument, NULL, 'f'},
1424 {"read-groups", required_argument, NULL, 'G'},
1425 {"region", required_argument, NULL, 'r'},
1426 {"regions", required_argument, NULL, 'r'},
1427 {"regions-file", required_argument, NULL, 'R'},
1428 {"targets", required_argument, NULL, 't'},
1429 {"targets-file", required_argument, NULL, 'T'},
1430 {"min-MQ", required_argument, NULL, 'q'},
1431 {"min-mq", required_argument, NULL, 'q'},
1432 {"min-BQ", required_argument, NULL, 'Q'},
1433 {"min-bq", required_argument, NULL, 'Q'},
1434 {"max-bq", required_argument, NULL, 11},
1435 {"max-BQ", required_argument, NULL, 11},
1436 {"delta-BQ", required_argument, NULL, 12},
1437 {"ignore-overlaps", no_argument, NULL, 'x'},
1438 {"output-type", required_argument, NULL, 'O'},
1439 {"samples", required_argument, NULL, 's'},
1440 {"samples-file", required_argument, NULL, 'S'},
1441 {"annotate", required_argument, NULL, 'a'},
1442 {"ext-prob", required_argument, NULL, 'e'},
1443 {"gap-frac", required_argument, NULL, 'F'},
1444 {"indel-bias", required_argument, NULL, 10},
1445 {"indel-size", required_argument, NULL, 15},
1446 {"indels-2.0", no_argument, NULL, 20},
1447 {"indels-cns", no_argument, NULL, 22},
1448 {"no-indels-cns", no_argument, NULL, 25},
1449 {"tandem-qual", required_argument, NULL, 'h'},
1450 {"skip-indels", no_argument, NULL, 'I'},
1451 {"max-idepth", required_argument, NULL, 'L'},
1452 {"min-ireads", required_argument, NULL, 'm'},
1453 {"per-sample-mF", no_argument, NULL, 'p'},
1454 {"per-sample-mf", no_argument, NULL, 'p'},
1455 {"platforms", required_argument, NULL, 'P'},
1456 {"max-read-len", required_argument, NULL, 'M'},
1457 {"config", required_argument, NULL, 'X'},
1458 {"seed", required_argument, NULL, 13},
1459 {"ambig-reads", required_argument, NULL, 14},
1460 {"ar", required_argument, NULL, 14},
1461 {"write-index",optional_argument,NULL,'W'},
1462 {"del-bias", required_argument, NULL, 23},
1463 {"poly-mqual", no_argument, NULL, 24},
1464 {"no-poly-mqual", no_argument, NULL, 26},
1465 {"score-vs-ref",required_argument, NULL, 27},
1466 {"seqq-offset", required_argument, NULL, 28},
1467 {NULL, 0, NULL, 0}
1468 };
1469 while ((c = getopt_long(argc, argv, "Ag:f:r:R:q:Q:C:BDd:L:b:P:po:e:h:Im:F:EG:6O:xa:s:S:t:T:M:X:UW::",lopts,NULL)) >= 0) {
1470 switch (c) {
1471 case 'x': mplp.flag &= ~MPLP_SMART_OVERLAPS; break;
1472 case 16 :
1473 mplp.rflag_skip_any_unset = bam_str2flag(optarg);
1474 if ( mplp.rflag_skip_any_unset <0 ) {
1475 fprintf(stderr,"Could not parse --nf %s\n", optarg);
1476 goto err;
1477 }
1478 break;
1479 case 17 :
1480 mplp.rflag_skip_all_unset = bam_str2flag(optarg);
1481 if ( mplp.rflag_skip_all_unset<0 ) {
1482 fprintf(stderr,"Could not parse --if %s\n", optarg);
1483 goto err;
1484 }
1485 break;
1486 case 18 :
1487 mplp.rflag_skip_any_set = bam_str2flag(optarg);
1488 if ( mplp.rflag_skip_any_set <0 ) {
1489 fprintf(stderr,"Could not parse --ef %s\n", optarg);
1490 goto err;
1491 }
1492 break;
1493 case 19 :
1494 mplp.rflag_skip_all_set = bam_str2flag(optarg);
1495 if ( mplp.rflag_skip_all_set <0 ) {
1496 fprintf(stderr,"Could not parse --df %s\n", optarg);
1497 goto err;
1498 }
1499 break;
1500 case 3 : mplp.output_fname = optarg; break;
1501 case 4 : mplp.openQ = atoi(optarg); break;
1502 case 5 : bam_smpl_ignore_readgroups(mplp.bsmpl); break;
1503 case 'g':
1504 mplp.gvcf = gvcf_init(optarg);
1505 if ( !mplp.gvcf ) error("Could not parse: --gvcf %s\n", optarg);
1506 break;
1507 case 'f':
1508 mplp.fai = fai_load(optarg);
1509 if (mplp.fai == NULL)
1510 goto err;
1511 mplp.fai_fname = optarg;
1512 break;
1513 case 7 : noref = 1; break;
1514 case 8 : mplp.record_cmd_line = 0; break;
1515 case 9 : mplp.n_threads = strtol(optarg, 0, 0); break;
1516 case 'd': mplp.max_depth = atoi(optarg); break;
1517 case 'r': mplp.reg_fname = strdup(optarg); break;
1518 case 'R': mplp.reg_fname = strdup(optarg); mplp.reg_is_file = 1; break;
1519 case 't':
1520 // In the original version the whole BAM was streamed which is inefficient
1521 // with few BED intervals and big BAMs. Todo: devise a heuristic to determine
1522 // best strategy, that is streaming or jumping.
1523 if ( optarg[0]=='^' ) optarg++;
1524 else mplp.bed_logic = 1;
1525 mplp.bed = regidx_init(NULL,regidx_parse_reg,NULL,0,NULL);
1526 mplp.bed_itr = regitr_init(mplp.bed);
1527 if ( regidx_insert_list(mplp.bed,optarg,',') !=0 )
1528 {
1529 fprintf(stderr,"Could not parse the targets: %s\n", optarg);
1530 exit(EXIT_FAILURE);
1531 }
1532 break;
1533 case 'T':
1534 if ( optarg[0]=='^' ) optarg++;
1535 else mplp.bed_logic = 1;
1536 mplp.bed = regidx_init(optarg,NULL,NULL,0,NULL);
1537 if (!mplp.bed) {
1538 fprintf(stderr, "bcftools mpileup: Could not read file \"%s\"", optarg);
1539 goto err;
1540 }
1541 break;
1542 case 'P': mplp.pl_list = strdup(optarg); break;
1543 case 'p': mplp.flag |= MPLP_PER_SAMPLE; break;
1544 case 'B': mplp.flag &= ~MPLP_REALN; break;
1545 case 'D': mplp.flag &= ~MPLP_REALN_PARTIAL; break;
1546 case 'I': mplp.flag |= MPLP_NO_INDEL; break;
1547 case 'E': mplp.flag |= MPLP_REDO_BAQ; break;
1548 case '6': mplp.flag |= MPLP_ILLUMINA13; break;
1549 case 's': if ( bam_smpl_add_samples(mplp.bsmpl,optarg,0)<0 ) error("Could not read samples: %s\n",optarg); break;
1550 case 'S': if ( bam_smpl_add_samples(mplp.bsmpl,optarg,1)<0 ) error("Could not read samples: %s\n",optarg); break;
1551 case 'O':
1552 switch (optarg[0]) {
1553 case 'b': mplp.output_type = FT_BCF_GZ; break;
1554 case 'u': mplp.output_type = FT_BCF; break;
1555 case 'z': mplp.output_type = FT_VCF_GZ; break;
1556 case 'v': mplp.output_type = FT_VCF; break;
1557 default:
1558 {
1559 char *tmp;
1560 mplp.clevel = strtol(optarg,&tmp,10);
1561 if ( *tmp || mplp.clevel<0 || mplp.clevel>9 ) error("The output type \"%s\" not recognised\n", optarg);
1562 }
1563 }
1564 if ( optarg[1] )
1565 {
1566 char *tmp;
1567 mplp.clevel = strtol(optarg+1,&tmp,10);
1568 if ( *tmp || mplp.clevel<0 || mplp.clevel>9 ) error("Could not parse argument: --output-type %s\n", optarg+1);
1569 }
1570 break;
1571 case 'C': mplp.capQ_thres = atoi(optarg); break;
1572 case 'q': mplp.min_mq = atoi(optarg); break;
1573 case 'Q': mplp.min_baseQ = atoi(optarg); break;
1574 case 11: mplp.max_baseQ = atoi(optarg); break;
1575 case 12: mplp.delta_baseQ = atoi(optarg); break;
1576 case 'b': file_list = optarg; break;
1577 case 'o': {
1578 char *end;
1579 long value = strtol(optarg, &end, 10);
1580 // Distinguish between -o INT and -o FILE (a bit of a hack!)
1581 if (*end == '\0') mplp.openQ = value;
1582 else mplp.output_fname = optarg;
1583 }
1584 break;
1585 case 'e': mplp.extQ = atoi(optarg); break;
1586 case 'h': mplp.tandemQ = atoi(optarg); break;
1587 case 10: // --indel-bias (inverted so higher => more indels called)
1588 if (atof(optarg) < 1e-2)
1589 mplp.indel_bias = 1/1e2;
1590 else
1591 mplp.indel_bias = 1/atof(optarg);
1592 break;
1593 case 27:
1594 mplp.vs_ref = atof(optarg);
1595 //if (mplp.vs_ref < 0) mplp.vs_ref = 0;
1596 if (mplp.vs_ref > 1) mplp.vs_ref = 1;
1597 break;
1598 case 15: {
1599 char *tmp;
1600 mplp.indel_win_size = strtol(optarg,&tmp,10);
1601 if ( *tmp ) error("Could not parse argument: --indel-size %s\n", optarg);
1602 if ( mplp.indel_win_size < 20 )
1603 {
1604 mplp.indel_win_size = 20;
1605 fprintf(stderr,"Warning: running with --indel-size %d, the requested value is too small\n",mplp.indel_win_size);
1606 }
1607 }
1608 break;
1609 case 20: mplp.indels_v20 = 1; mplp.edlib = 0; break;
1610 case 'W':
1611 if (!(mplp.write_index = write_index_parse(optarg)))
1612 error("Unsupported index format '%s'\n", optarg);
1613 break;
1614 case 22: mplp.edlib = 1; mplp.indels_v20 = 0; break;
1615 case 25: mplp.edlib = 0; break;
1616 case 28:
1617 mplp.seqQ_offset = atoi(optarg);
1618 if (mplp.seqQ_offset < 100)
1619 mplp.seqQ_offset = 100;
1620 if (mplp.seqQ_offset > 200)
1621 mplp.seqQ_offset = 200;
1622 break;
1623 case 23: mplp.del_bias = atof(optarg); break;
1624 case 24: mplp.poly_mqual = 1; break;
1625 case 26: mplp.poly_mqual = 0; break;
1626 case 'A': use_orphan = 1; break;
1627 case 'F': mplp.min_frac = atof(optarg); break;
1628 case 'm': mplp.min_support = atoi(optarg); break;
1629 case 'L': mplp.max_indel_depth = atoi(optarg); break;
1630 case 'G': bam_smpl_add_readgroups(mplp.bsmpl, optarg, 1); break;
1631 case 'a':
1632 if (optarg[0]=='?') {
1633 list_annotations(stderr);
1634 goto err;
1635 }
1636 parse_format_flag(&mplp.fmt_flag,optarg);
1637 break;
1638 case 'M': mplp.max_read_len = atoi(optarg); break;
1639 case 'X':
1640 if (strcasecmp(optarg, "pacbio-ccs-1.18") == 0) {
1641 mplp.min_frac = 0.1;
1642 mplp.min_baseQ = 5;
1643 mplp.max_baseQ = 50;
1644 mplp.delta_baseQ = 10;
1645 mplp.openQ = 25;
1646 mplp.extQ = 1;
1647 mplp.flag |= MPLP_REALN_PARTIAL;
1648 mplp.max_read_len = 99999;
1649
1650 } else if (strcasecmp(optarg, "pacbio-ccs") == 0 ||
1651 strcasecmp(optarg, "pacbio-ccs-1.20") == 0) {
1652 mplp.min_frac = 0.1;
1653 mplp.min_baseQ = 5;
1654 mplp.max_baseQ = 50;
1655 mplp.delta_baseQ = 10;
1656 mplp.tandemQ = 300;
1657 mplp.openQ = 25;
1658 mplp.extQ = 1;
1659 mplp.flag &= ~MPLP_REALN;
1660 mplp.del_bias = 0.4;
1661 mplp.indel_bias = 1/.9;
1662 mplp.seqQ_offset = 118;
1663 mplp.poly_mqual = 1;
1664 mplp.edlib = 1;
1665 mplp.vs_ref = 0.7;
1666 mplp.indel_win_size = 80;
1667
1668 } else if (strcasecmp(optarg, "ont") == 0) {
1669 fprintf(stderr, "With old ONT data may be beneficial to also run bcftools call with "
1670 "a higher -P, eg -P0.01 or -P 0.1\n");
1671 mplp.min_baseQ = 5;
1672 mplp.max_baseQ = 30;
1673 mplp.flag &= ~MPLP_REALN;
1674 mplp.flag |= MPLP_NO_INDEL;
1675
1676 } else if (strcasecmp(optarg, "ont-sup") == 0 ||
1677 strcasecmp(optarg, "ont-sup-1.20") == 0) {
1678 mplp.min_frac = 0.2;
1679 mplp.min_baseQ = 1;
1680 mplp.max_baseQ = 35;
1681 mplp.delta_baseQ = 99;
1682 mplp.openQ = 15;
1683 mplp.extQ = 1;
1684 mplp.flag &= ~MPLP_REALN;
1685 mplp.max_read_len = 9999999;
1686 mplp.del_bias = 0.4;
1687 mplp.poly_mqual = 1;
1688 mplp.edlib = 1;
1689 // If we increase -h then we can increase bias denominator too
1690 mplp.tandemQ = 110;
1691 mplp.indel_bias = 1/0.7;
1692 mplp.seqQ_offset = 130;
1693 mplp.indel_win_size = 80;
1694
1695 } else if (strcasecmp(optarg, "ultima") == 0 ||
1696 strcasecmp(optarg, "ultima-1.20") == 0) {
1697 mplp.min_frac = 0.15;
1698 mplp.min_baseQ = 1;
1699 mplp.max_baseQ = 30;
1700 mplp.delta_baseQ = 10;
1701 mplp.openQ = 20;
1702 mplp.extQ = 10;
1703 mplp.tandemQ = 250;
1704 mplp.flag &= ~MPLP_REALN;
1705 mplp.del_bias = 0.3;
1706 mplp.poly_mqual = 1;
1707 mplp.edlib = 1;
1708 mplp.indel_bias = 1/0.7;
1709 mplp.seqQ_offset = 140;
1710 mplp.vs_ref = 0.3;
1711 mplp.indel_win_size = 80;
1712
1713 } else if (strcasecmp(optarg, "1.12") == 0) {
1714 // 1.12 and earlier
1715 mplp.min_frac = 0.002;
1716 mplp.min_support = 1;
1717 mplp.min_baseQ = 13;
1718 mplp.tandemQ = 100;
1719 mplp.flag &= ~MPLP_REALN_PARTIAL;
1720 mplp.flag |= MPLP_REALN;
1721
1722 } else if (strcasecmp(optarg, "illumina-1.18") == 0) {
1723 mplp.indel_win_size = 110;
1724 mplp.flag |= MPLP_REALN_PARTIAL;
1725
1726 } else if (strcasecmp(optarg, "illumina") == 0 ||
1727 strcasecmp(optarg, "illumina-1.20") == 0) {
1728 mplp.edlib = 1;
1729 mplp.indel_win_size = 110;
1730 mplp.flag |= MPLP_REALN_PARTIAL;
1731 mplp.indel_bias = 1;
1732 mplp.seqQ_offset = 125;
1733 //mplp.indel_win_size = 80; TEST?
1734
1735 } else if (strcasecmp(optarg, "bgi") == 0 ||
1736 strcasecmp(optarg, "bgi-1.20") == 0) {
1737 mplp.min_frac = 0.1;
1738 mplp.edlib = 1;
1739 mplp.indel_bias = 1;
1740 mplp.seqQ_offset = 120;
1741 mplp.flag |= MPLP_REALN_PARTIAL;
1742 mplp.indel_win_size = 80;
1743
1744 } else if (strcasecmp(optarg, "list") == 0 ||
1745 strcasecmp(optarg, "help") == 0) {
1746 print_profiles();
1747 goto err;
1748 } else {
1749 fprintf(stderr, "Unknown configuration name '%s'\n"
1750 "Please use '-X list' to show available choices.\n",
1751 optarg);
1752 goto err;
1753 }
1754 break;
1755 case 13: hts_srand48(atoi(optarg)); break;
1756 case 14:
1757 if ( !strcasecmp(optarg,"drop") ) mplp.ambig_reads = B2B_DROP;
1758 else if ( !strcasecmp(optarg,"incAD") ) mplp.ambig_reads = B2B_INC_AD;
1759 else if ( !strcasecmp(optarg,"incAD0") ) mplp.ambig_reads = B2B_INC_AD0;
1760 else error("The option to --ambig-reads not recognised: %s\n",optarg);
1761 break;
1762 default:
1763 fprintf(stderr,"Invalid option: '%c'\n", c);
1764 goto err;
1765 }
1766 }
1767
1768 if ( mplp.gvcf && !(mplp.fmt_flag&B2B_FMT_DP) )
1769 {
1770 fprintf(stderr,"[warning] The -a DP option is required with --gvcf, switching on.\n");
1771 mplp.fmt_flag |= B2B_FMT_DP;
1772 }
1773 if ( mplp.flag&(MPLP_BCF|MPLP_VCF|MPLP_NO_COMP) )
1774 {
1775 if ( mplp.flag&MPLP_VCF )
1776 {
1777 if ( mplp.flag&MPLP_NO_COMP ) mplp.output_type = FT_VCF;
1778 else mplp.output_type = FT_VCF_GZ;
1779 }
1780 else if ( mplp.flag&MPLP_BCF )
1781 {
1782 if ( mplp.flag&MPLP_NO_COMP ) mplp.output_type = FT_BCF;
1783 else mplp.output_type = FT_BCF_GZ;
1784 }
1785 }
1786 if ( !(mplp.flag&MPLP_REALN) && mplp.flag&MPLP_REDO_BAQ )
1787 {
1788 fprintf(stderr,"Error: The -B option cannot be combined with -E\n");
1789 goto err;
1790 }
1791 if (use_orphan) mplp.flag &= ~MPLP_NO_ORPHAN;
1792 if (argc == 1)
1793 {
1794 print_usage(stderr, &mplp);
1795 goto err;
1796 }
1797 if (!mplp.fai && !noref) {
1798 fprintf(stderr,"Error: mpileup requires the --fasta-ref option by default; use --no-reference to run without a fasta reference\n");
1799 goto err;
1800 }
1801
1802 if (file_list)
1803 {
1804 if ( read_file_list(file_list,&nfiles,&fn) )
1805 goto err;
1806 mplp.files = fn;
1807 mplp.nfiles = nfiles;
1808 }
1809 else
1810 {
1811 mplp.nfiles = argc - optind;
1812 mplp.files = (char**) malloc(mplp.nfiles*sizeof(char*));
1813 for (i=0; i<mplp.nfiles; i++) mplp.files[i] = strdup(argv[optind+i]);
1814 }
1815 ret = mpileup(&mplp);
1816
1817 for (i=0; i<mplp.nfiles; i++) free(mplp.files[i]);
1818 free(mplp.files);
1819 free(mplp.reg_fname); free(mplp.pl_list);
1820 if (mplp.fai) fai_destroy(mplp.fai);
1821 if (mplp.bed) regidx_destroy(mplp.bed);
1822 if (mplp.bed_itr) regitr_destroy(mplp.bed_itr);
1823 if (mplp.reg) regidx_destroy(mplp.reg);
1824
1825 err:
1826 bam_smpl_destroy(mplp.bsmpl);
1827
1828 return ret;
1829 }