Debian Codegraph @

samtools/bam_plcmd.c.pysam.c

raw symbols SCIP
1 #include "samtools.pysam.h"
2
3 /* bam_plcmd.c -- mpileup subcommand.
4
5 Copyright (C) 2008-2015, 2019-2021, 2023-2024 Genome Research Ltd.
6 Portions copyright (C) 2009-2012 Broad Institute.
7
8 Author: Heng Li <[email protected]>
9
10 Permission is hereby granted, free of charge, to any person obtaining a copy
11 of this software and associated documentation files (the "Software"), to deal
12 in the Software without restriction, including without limitation the rights
13 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 copies of the Software, and to permit persons to whom the Software is
15 furnished to do so, subject to the following conditions:
16
17 The above copyright notice and this permission notice shall be included in
18 all copies or substantial portions of the Software.
19
20 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
25 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
26 DEALINGS IN THE SOFTWARE. */
27
28 #include <config.h>
29
30 #include <math.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <unistd.h>
34 #include <ctype.h>
35 #include <string.h>
36 #include <strings.h>
37 #include <limits.h>
38 #include <errno.h>
39 #include <sys/stat.h>
40 #include <getopt.h>
41 #include <inttypes.h>
42 #include <htslib/sam.h>
43 #include <htslib/faidx.h>
44 #include <htslib/kstring.h>
45 #include <htslib/klist.h>
46 #include <htslib/khash_str2int.h>
47 #include <htslib/cram.h>
48 #include "samtools.h"
49 #include "bedidx.h"
50 #include "sam_opts.h"
51 #include "bam_plbuf.h"
52
53 #define dummy_free(p)
54 KLIST_INIT(auxlist, char *, dummy_free)
55
56 int pileup_seq(kstring_t *ks_seq, const bam_pileup1_t *p, hts_pos_t pos,
57 hts_pos_t ref_len, const char *ref, kstring_t *ks_mod,
58 int rev_del, int no_ins, int no_ins_mods,
59 int no_del, int no_ends)
60 {
61 no_ins_mods |= no_ins;
62 int j, err = 0;
63 hts_base_mod_state *m = p->cd.p;
64 if (!no_ends && p->is_head) {
65 err |= kputc_('^', ks_seq) < 0;
66 err |= kputc_(p->b->core.qual > 93 ? 126 : p->b->core.qual + 33,
67 ks_seq) < 0;
68 }
69 if (!p->is_del) {
70 // See seq_nt16_str in htslib/hts.c
71 const char seq_nt_str_lc[] = ",acmgrsvtwyhkdbn"; // reverse strand
72 const char seq_nt_str_uc[] = ".ACMGRSVTWYHKDBN";
73 int c = p->qpos < p->b->core.l_qseq
74 ? bam_seqi(bam_get_seq(p->b), p->qpos)
75 : 15 /*N*/;
76 if (ref) {
77 int rb = pos < ref_len
78 ? seq_nt16_table[(uint8_t)(ref[pos])]
79 : 15/*N*/;
80 if (c == rb)
81 c = 0; // "=", which becomes . or ,
82 }
83 c = bam_is_rev(p->b)
84 ? seq_nt_str_lc[c]
85 : seq_nt_str_uc[c];
86 err |= kputc_(c, ks_seq) < 0;
87
88 if (m) {
89 int nm;
90 hts_base_mod mod[256];
91 if ((nm = bam_mods_at_qpos(p->b, p->qpos, m, mod, 256)) > 0) {
92 err |= kputc_('[', ks_seq) < 0;
93 int j;
94 for (j = 0; j < nm && j < 256; j++) {
95 char qual[20];
96 if (mod[j].qual >= 0)
97 sprintf(qual, "%d", mod[j].qual);
98 else
99 *qual = 0;
100 if (mod[j].modified_base < 0)
101 // ChEBI
102 err |= ksprintf(ks_seq, "%c(%d)%s",
103 "+-"[mod[j].strand],
104 -mod[j].modified_base, qual) < 0;
105 else
106 err |= ksprintf(ks_seq, "%c%c%s", "+-"[mod[j].strand],
107 mod[j].modified_base, qual) < 0;
108 }
109 err |= kputc_(']', ks_seq) < 0;
110 }
111 }
112 } else {
113 err |= kputc_(p->is_refskip
114 ? (bam_is_rev(p->b)? '<' : '>')
115 : ((bam_is_rev(p->b) && rev_del) ? '#' : '*'),
116 ks_seq) < 0;
117 }
118
119 int del_len = -p->indel;
120 if (p->indel > 0) {
121 int len = bam_plp_insertion_mod(p, m && !no_ins_mods ? m : NULL,
122 ks_mod, &del_len);
123 if (len < 0) {
124 print_error("mpileup", "bam_plp_insertion() failed");
125 return -1;
126 }
127 if (no_ins < 2) {
128 err |= kputc_('+', ks_seq) < 0;
129 err |= kputuw(len, ks_seq) < 0;
130 }
131 if (!no_ins) {
132 kstring_t *ks = ks_mod;
133 if (bam_is_rev(p->b)) {
134 char pad = rev_del ? '#' : '*';
135 int in_mod = 0;
136 for (j = 0; j < ks->l; j++) {
137 if (ks->s[j] == '[') in_mod = 1;
138 else if (ks->s[j] == ']') in_mod = 0;
139 err |= kputc_(ks->s[j] != '*'
140 ? (in_mod ? ks->s[j] : tolower(ks->s[j]))
141 : pad, ks_seq) < 0;
142 }
143 } else {
144 int in_mod = 0;
145 for (j = 0; j < ks->l; j++) {
146 if (ks->s[j] == '[') in_mod = 1;
147 if (ks->s[j] == ']') in_mod = 0;
148 err |= kputc_(in_mod ? ks->s[j] : toupper(ks->s[j]),
149 ks_seq) < 0;
150 }
151 }
152 }
153 }
154
155 if (del_len > 0) {
156 if (no_del < 2)
157 err |= kputw(-del_len, ks_seq) < 0;
158 if (!no_del) {
159 for (j = 1; j <= del_len; ++j) {
160 int c = (ref && (int)pos+j < ref_len)? ref[pos+j] : 'N';
161 err |= kputc_(bam_is_rev(p->b)? tolower(c) : toupper(c),
162 ks_seq) < 0;
163 }
164 }
165 }
166
167 if (!no_ends && p->is_tail)
168 err |= kputc_('$', ks_seq) < 0;
169
170 return -err;
171 }
172
173 #include "sample.h"
174
175 #define MPLP_NO_COMP (1<<2)
176 #define MPLP_NO_ORPHAN (1<<3)
177 #define MPLP_REALN (1<<4)
178 #define MPLP_NO_INDEL (1<<5)
179 #define MPLP_REDO_BAQ (1<<6)
180 #define MPLP_ILLUMINA13 (1<<7)
181 #define MPLP_IGNORE_RG (1<<8)
182 #define MPLP_SMART_OVERLAPS (1<<10)
183
184 #define MPLP_PRINT_MAPQ_CHAR (1<<11)
185 #define MPLP_PRINT_QPOS (1<<12)
186 // Start of struct active_cols elements
187 #define MPLP_PRINT_QNAME (1<<13)
188 #define MPLP_PRINT_FLAG (1<<14)
189 #define MPLP_PRINT_RNAME (1<<15)
190 #define MPLP_PRINT_POS (1<<16)
191 #define MPLP_PRINT_MAPQ (1<<17)
192 #define MPLP_PRINT_CIGAR (1<<18)
193 #define MPLP_PRINT_RNEXT (1<<19)
194 #define MPLP_PRINT_PNEXT (1<<20)
195 #define MPLP_PRINT_TLEN (1<<21)
196 #define MPLP_PRINT_SEQ (1<<22)
197 #define MPLP_PRINT_QUAL (1<<23)
198 #define MPLP_PRINT_RLEN (1<<24)
199 // Must occur after struct active_cols element list
200 #define MPLP_PRINT_MODS (1<<25)
201 #define MPLP_PRINT_QPOS5 (1<<26)
202
203 #define MPLP_PRINT_LAST (1<<27) // terminator for loop
204
205 #define MPLP_MAX_DEPTH 8000
206 #define MPLP_MAX_INDEL_DEPTH 250
207
208 typedef struct {
209 int min_mq, flag, min_baseQ, capQ_thres, max_depth, max_indel_depth, all, rev_del;
210 int rflag_require, rflag_filter;
211 char *reg, *pl_list, *fai_fname, *output_fname;
212 faidx_t *fai;
213 void *bed, *rghash, *auxlist;
214 int argc;
215 char **argv;
216 char sep, empty, no_ins, no_ins_mods, no_del, no_ends;
217 sam_global_args ga;
218 } mplp_conf_t;
219
220 typedef struct {
221 char *ref[2];
222 int ref_id[2];
223 hts_pos_t ref_len[2];
224 } mplp_ref_t;
225
226 #define MPLP_REF_INIT {{NULL,NULL},{-1,-1},{0,0}}
227
228 typedef struct {
229 samFile *fp;
230 hts_itr_t *iter;
231 sam_hdr_t *h;
232 mplp_ref_t *ref;
233 const mplp_conf_t *conf;
234 } mplp_aux_t;
235
236 typedef struct {
237 int n;
238 int *n_plp, *m_plp;
239 bam_pileup1_t **plp;
240 } mplp_pileup_t;
241
242 static int build_auxlist(mplp_conf_t *conf, char *optstring) {
243 if (!optstring)
244 return 0;
245
246 void *colhash = khash_str2int_init();
247 if (!colhash)
248 return 1;
249
250 struct active_cols {
251 char *name;
252 int supported;
253 };
254
255 const struct active_cols colnames[12] = {
256 {"QNAME", 1}, {"FLAG", 1}, {"RNAME", 1}, {"POS", 1}, {"MAPQ", 1},
257 {"CIGAR", 0}, {"RNEXT", 1}, {"PNEXT", 1}, {"TLEN", 0}, {"SEQ", 0},
258 {"QUAL", 0}, {"RLEN", 1},
259 };
260
261 int i, f = MPLP_PRINT_QNAME, colno = sizeof(colnames)/sizeof(*colnames);
262 for (i = 0; i < colno; i++, f <<= 1)
263 if (colnames[i].supported)
264 khash_str2int_set(colhash, colnames[i].name, f);
265
266 conf->auxlist = kl_init(auxlist);
267 if (!conf->auxlist)
268 return 1;
269
270 char *save_p;
271 char *tag = strtok_r(optstring, ",", &save_p);
272 while (tag) {
273 if (khash_str2int_get(colhash, tag, &f) == 0) {
274 conf->flag |= f;
275 } else {
276 if (strlen(tag) != 2) {
277 fprintf(samtools_stderr, "[%s] tag '%s' has more than two characters or not supported\n", __func__, tag);
278 } else {
279 char **tag_p = kl_pushp(auxlist, conf->auxlist);
280 *tag_p = tag;
281 }
282 }
283 tag = strtok_r(NULL, ",", &save_p);
284 }
285
286 khash_str2int_destroy(colhash);
287
288 return 0;
289 }
290
291 static int mplp_get_ref(mplp_aux_t *ma, int tid, char **ref, hts_pos_t *ref_len) {
292 mplp_ref_t *r = ma->ref;
293
294 //printf("get ref %d {%d/%p, %d/%p}\n", tid, r->ref_id[0], r->ref[0], r->ref_id[1], r->ref[1]);
295
296 if (!r || !ma->conf->fai) {
297 *ref = NULL;
298 return 0;
299 }
300
301 // Do we need to reference count this so multiple mplp_aux_t can
302 // track which references are in use?
303 // For now we just cache the last two. Sufficient?
304 if (tid == r->ref_id[0]) {
305 *ref = r->ref[0];
306 *ref_len = r->ref_len[0];
307 return 1;
308 }
309 if (tid == r->ref_id[1]) {
310 // Last, swap over
311 int tmp_id;
312 hts_pos_t tmp_len;
313 tmp_id = r->ref_id[0]; r->ref_id[0] = r->ref_id[1]; r->ref_id[1] = tmp_id;
314 tmp_len = r->ref_len[0]; r->ref_len[0] = r->ref_len[1]; r->ref_len[1] = tmp_len;
315
316 char *tc;
317 tc = r->ref[0]; r->ref[0] = r->ref[1]; r->ref[1] = tc;
318 *ref = r->ref[0];
319 *ref_len = r->ref_len[0];
320 return 1;
321 }
322
323 // New, so migrate to old and load new
324 free(r->ref[1]);
325 r->ref[1] = r->ref[0];
326 r->ref_id[1] = r->ref_id[0];
327 r->ref_len[1] = r->ref_len[0];
328
329 r->ref_id[0] = tid;
330 r->ref[0] = faidx_fetch_seq64(ma->conf->fai,
331 sam_hdr_tid2name(ma->h, r->ref_id[0]),
332 0,
333 HTS_POS_MAX,
334 &r->ref_len[0]);
335
336 if (!r->ref[0]) {
337 r->ref[0] = NULL;
338 r->ref_id[0] = -1;
339 r->ref_len[0] = 0;
340 *ref = NULL;
341 return 0;
342 }
343
344 *ref = r->ref[0];
345 *ref_len = r->ref_len[0];
346 return 1;
347 }
348
349 // Initialise and destroy the base modifier state data. This is called
350 // as each new read is added or removed from the pileups.
351 static
352 int pileup_cd_create(void *data, const bam1_t *b, bam_pileup_cd *cd) {
353 int ret;
354 hts_base_mod_state *m = hts_base_mod_state_alloc();
355 ret = bam_parse_basemod(b, m);
356 cd->p = m;
357 return ret;
358 }
359
360 static
361 int pileup_cd_destroy(void *data, const bam1_t *b, bam_pileup_cd *cd) {
362 hts_base_mod_state_free(cd->p);
363 return 0;
364 }
365
366 static void
367 print_empty_pileup(FILE *fp, const mplp_conf_t *conf, const char *tname,
368 hts_pos_t pos, int n, const char *ref, hts_pos_t ref_len)
369 {
370 int i;
371 fprintf(fp, "%s\t%"PRIhts_pos"\t%c", tname, pos+1, (ref && pos < ref_len)? ref[pos] : 'N');
372 for (i = 0; i < n; ++i) {
373 fputs("\t0\t*\t*", fp);
374 int flag_value = MPLP_PRINT_MAPQ_CHAR;
375 while(flag_value < MPLP_PRINT_LAST) {
376 if (flag_value != MPLP_PRINT_MODS && (conf->flag & flag_value))
377 fputs("\t*", fp);
378 flag_value <<= 1;
379 }
380 if (conf->auxlist) {
381 int t = 0;
382 while(t++ < ((klist_t(auxlist) *)conf->auxlist)->size)
383 fputs("\t*", fp);
384 }
385 }
386 putc('\n', fp);
387 }
388
389 static int mplp_func(void *data, bam1_t *b)
390 {
391 char *ref;
392 mplp_aux_t *ma = (mplp_aux_t*)data;
393 int ret, skip = 0;
394 hts_pos_t ref_len;
395
396 do {
397 int has_ref;
398 ret = ma->iter? sam_itr_next(ma->fp, ma->iter, b) : sam_read1(ma->fp, ma->h, b);
399 if (ret < 0) break;
400 // The 'B' cigar operation is not part of the specification, considering as obsolete.
401 // bam_remove_B(b);
402 if (b->core.tid < 0 || (b->core.flag&BAM_FUNMAP)) { // exclude unmapped reads
403 skip = 1;
404 continue;
405 }
406 if (ma->conf->rflag_require && !(ma->conf->rflag_require&b->core.flag)) { skip = 1; continue; }
407 if (ma->conf->rflag_filter && ma->conf->rflag_filter&b->core.flag) { skip = 1; continue; }
408 if (ma->conf->bed && ma->conf->all == 0) { // test overlap
409 skip = !bed_overlap(ma->conf->bed, sam_hdr_tid2name(ma->h, b->core.tid), b->core.pos, bam_endpos(b));
410 if (skip) continue;
411 }
412 if (ma->conf->rghash) { // exclude read groups
413 uint8_t *rg = bam_aux_get(b, "RG");
414 skip = (rg && khash_str2int_get(ma->conf->rghash, (const char*)(rg+1), NULL)==0);
415 if (skip) continue;
416 }
417 if (ma->conf->flag & MPLP_ILLUMINA13) {
418 int i;
419 uint8_t *qual = bam_get_qual(b);
420 for (i = 0; i < b->core.l_qseq; ++i)
421 qual[i] = qual[i] > 31? qual[i] - 31 : 0;
422 }
423
424 if (ma->conf->fai && b->core.tid >= 0) {
425 has_ref = mplp_get_ref(ma, b->core.tid, &ref, &ref_len);
426 if (has_ref && ref_len <= b->core.pos) { // exclude reads outside of the reference sequence
427 fprintf(samtools_stderr,"[%s] Skipping because %"PRIhts_pos" is outside of %"PRIhts_pos" [ref:%d]\n",
428 __func__, (int64_t) b->core.pos, ref_len, b->core.tid);
429 skip = 1;
430 continue;
431 }
432 } else {
433 has_ref = 0;
434 }
435
436 skip = 0;
437 if (has_ref && (ma->conf->flag&MPLP_REALN)) sam_prob_realn(b, ref, ref_len, (ma->conf->flag & MPLP_REDO_BAQ)? 7 : 3);
438 if (has_ref && ma->conf->capQ_thres > 10) {
439 int q = sam_cap_mapq(b, ref, ref_len, ma->conf->capQ_thres);
440 if (q < 0) skip = 1;
441 else if (b->core.qual > q) b->core.qual = q;
442 }
443 if (b->core.qual < ma->conf->min_mq) skip = 1;
444 else if ((ma->conf->flag&MPLP_NO_ORPHAN) && (b->core.flag&BAM_FPAIRED) && !(b->core.flag&BAM_FPROPER_PAIR)) skip = 1;
445 } while (skip);
446 return ret;
447 }
448
449 /*
450 * Performs pileup
451 * @param conf configuration for this pileup
452 * @param n number of files specified in fn
453 * @param fn filenames
454 * @param fn_idx index filenames
455 */
456 static int mpileup(mplp_conf_t *conf, int nfn, char **fn, char **fn_idx)
457 {
458 mplp_aux_t **data;
459 int i, tid, *n_plp, tid0 = 0, max_depth;
460 hts_pos_t pos, beg0 = 0, end0 = HTS_POS_MAX, ref_len;
461 const bam_pileup1_t **plp;
462 mplp_ref_t mp_ref = MPLP_REF_INIT;
463 bam_mplp_t iter;
464 sam_hdr_t *h = NULL; /* header of first file in input list */
465 char *ref;
466 FILE *pileup_fp = NULL;
467
468 bam_sample_t *sm = NULL;
469 kstring_t buf;
470 mplp_pileup_t gplp;
471
472 memset(&gplp, 0, sizeof(mplp_pileup_t));
473 memset(&buf, 0, sizeof(kstring_t));
474 data = calloc(nfn, sizeof(mplp_aux_t*));
475 plp = calloc(nfn, sizeof(bam_pileup1_t*));
476 n_plp = calloc(nfn, sizeof(int));
477 sm = bam_smpl_init();
478
479 if (nfn == 0) {
480 fprintf(samtools_stderr,"[%s] no input file/data given\n", __func__);
481 samtools_exit(EXIT_FAILURE);
482 }
483
484 // read the header of each file in the list and initialize data
485 refs_t *refs = NULL;
486 for (i = 0; i < nfn; ++i) {
487 sam_hdr_t *h_tmp;
488 data[i] = calloc(1, sizeof(mplp_aux_t));
489 data[i]->fp = sam_open_format(fn[i], "rb", &conf->ga.in);
490 if ( !data[i]->fp )
491 {
492 fprintf(samtools_stderr, "[%s] failed to open %s: %s\n", __func__, fn[i], strerror(errno));
493 samtools_exit(EXIT_FAILURE);
494 }
495 if (hts_set_opt(data[i]->fp, CRAM_OPT_DECODE_MD, 0)) {
496 fprintf(samtools_stderr, "Failed to set CRAM_OPT_DECODE_MD value\n");
497 samtools_exit(EXIT_FAILURE);
498 }
499
500 if (!refs && conf->fai_fname) {
501 if (hts_set_fai_filename(data[i]->fp, conf->fai_fname) != 0) {
502 fprintf(samtools_stderr, "[%s] failed to process %s: %s\n",
503 __func__, conf->fai_fname, strerror(errno));
504 samtools_exit(EXIT_FAILURE);
505 }
506 refs = cram_get_refs(data[i]->fp);
507 } else if (conf->fai_fname) {
508 if (hts_set_opt(data[i]->fp, CRAM_OPT_SHARED_REF, refs) != 0) {
509 fprintf(samtools_stderr, "[%s] failed to process %s: %s\n",
510 __func__, conf->fai_fname, strerror(errno));
511 samtools_exit(EXIT_FAILURE);
512 }
513 }
514
515 data[i]->conf = conf;
516 data[i]->ref = &mp_ref;
517 h_tmp = sam_hdr_read(data[i]->fp);
518 if ( !h_tmp ) {
519 fprintf(samtools_stderr,"[%s] fail to read the header of %s\n", __func__, fn[i]);
520 samtools_exit(EXIT_FAILURE);
521 }
522 bam_smpl_add(sm, fn[i], (conf->flag&MPLP_IGNORE_RG)? 0 : sam_hdr_str(h_tmp));
523 if (conf->reg) {
524 hts_idx_t *idx = NULL;
525 // If index filename has not been specfied, look in BAM folder
526 if (fn_idx != NULL) {
527 idx = sam_index_load2(data[i]->fp, fn[i], fn_idx[i]);
528 } else {
529 idx = sam_index_load(data[i]->fp, fn[i]);
530 }
531
532 if (idx == NULL) {
533 fprintf(samtools_stderr, "[%s] fail to load index for %s\n", __func__, fn[i]);
534 samtools_exit(EXIT_FAILURE);
535 }
536 if ( (data[i]->iter=sam_itr_querys(idx, h_tmp, conf->reg)) == 0) {
537 fprintf(samtools_stderr, "[E::%s] fail to parse region '%s' with %s\n", __func__, conf->reg, fn[i]);
538 samtools_exit(EXIT_FAILURE);
539 }
540 if (i == 0) beg0 = data[i]->iter->beg, end0 = data[i]->iter->end, tid0 = data[i]->iter->tid;
541 hts_idx_destroy(idx);
542 }
543 else
544 data[i]->iter = NULL;
545
546 if (i == 0) h = data[i]->h = h_tmp; // save the header of the first file
547 else {
548 // FIXME: check consistency between h and h_tmp
549 sam_hdr_destroy(h_tmp);
550
551 // we store only the first file's header; it's (alleged to be)
552 // compatible with the i-th file's target_name lookup needs
553 data[i]->h = h;
554 }
555 }
556 fprintf(samtools_stderr, "[%s] %d samples in %d input files\n",
557 __func__, sm->n, nfn);
558
559 pileup_fp = conf->output_fname? fopen(conf->output_fname, "w") : samtools_stdout;
560
561 if (pileup_fp == NULL) {
562 fprintf(samtools_stderr, "[%s] failed to write to %s: %s\n", __func__, conf->output_fname, strerror(errno));
563 samtools_exit(EXIT_FAILURE);
564 }
565
566 // init pileup
567 iter = bam_mplp_init(nfn, mplp_func, (void**)data);
568 if (conf->flag & MPLP_PRINT_MODS) {
569 bam_mplp_constructor(iter, pileup_cd_create);
570 bam_mplp_destructor(iter, pileup_cd_destroy);
571 }
572 if ( conf->flag & MPLP_SMART_OVERLAPS ) bam_mplp_init_overlaps(iter);
573 if ( !conf->max_depth ) {
574 max_depth = INT_MAX;
575 fprintf(samtools_stderr, "[%s] Max depth set to maximum value (%d)\n", __func__, INT_MAX);
576 } else {
577 max_depth = conf->max_depth;
578 if ( max_depth * nfn > 1<<20 )
579 fprintf(samtools_stderr, "[%s] Combined max depth is above 1M. Potential memory hog!\n", __func__);
580 }
581
582
583 bam_mplp_set_maxcnt(iter, max_depth);
584 int ret;
585 int last_tid = -1;
586 hts_pos_t last_pos = -1;
587 int one_seq = 0;
588
589 // begin pileup
590 kstring_t ks_seq = KS_INITIALIZE;
591 kstring_t ks_mod = KS_INITIALIZE;
592 kstring_t ks_qual = KS_INITIALIZE;
593 while ( (ret=bam_mplp64_auto(iter, &tid, &pos, n_plp, plp)) > 0) {
594 one_seq = 1; // at least 1 output
595 if (conf->reg && (pos < beg0 || pos >= end0)) continue; // out of the region requested
596 if (conf->all) {
597 // Deal with missing portions of previous tids
598 while (tid > last_tid) {
599 if (last_tid >= 0 && !conf->reg) {
600 while (++last_pos < sam_hdr_tid2len(h, last_tid)) {
601 if (conf->bed && bed_overlap(conf->bed, sam_hdr_tid2name(h, last_tid), last_pos, last_pos + 1) == 0)
602 continue;
603 print_empty_pileup(pileup_fp, conf, sam_hdr_tid2name(h, last_tid), last_pos, nfn, ref, ref_len);
604 }
605 }
606 last_tid++;
607 last_pos = -1;
608 if (conf->all < 2)
609 break;
610 if (tid > last_tid)
611 // multiple missing references and -aa used
612 mplp_get_ref(data[0], last_tid, &ref, &ref_len);
613 }
614 }
615 mplp_get_ref(data[0], tid, &ref, &ref_len);
616
617 if (conf->all) {
618 // Deal with missing portion of current tid
619 while (++last_pos < pos) {
620 if (conf->reg && last_pos < beg0) continue; // out of range; skip
621 if (conf->bed && bed_overlap(conf->bed, sam_hdr_tid2name(h, tid), last_pos, last_pos + 1) == 0)
622 continue;
623 print_empty_pileup(pileup_fp, conf, sam_hdr_tid2name(h, tid), last_pos, nfn, ref, ref_len);
624 }
625 last_tid = tid;
626 last_pos = pos;
627 }
628 if (conf->bed && tid >= 0 && !bed_overlap(conf->bed, sam_hdr_tid2name(h, tid), pos, pos+1)) continue;
629
630 fprintf(pileup_fp, "%s\t%"PRIhts_pos"\t%c", sam_hdr_tid2name(h, tid), pos + 1, (ref && pos < ref_len)? ref[pos] : 'N');
631 for (i = 0; i < nfn; ++i) {
632 int j, cnt, err = 0;
633 ks_clear(&ks_seq);
634 ks_clear(&ks_qual);
635 ks_clear(&ks_mod);
636 for (j = cnt = 0; j < n_plp[i]; ++j) {
637 const bam_pileup1_t *p = plp[i] + j;
638 int c = p->qpos < p->b->core.l_qseq
639 ? bam_get_qual(p->b)[p->qpos]
640 : 0;
641 if (c >= conf->min_baseQ) {
642 // Build up seq
643 err |= pileup_seq(&ks_seq, plp[i] + j, pos, ref_len,
644 ref, &ks_mod, conf->rev_del,
645 conf->no_ins, conf->no_ins_mods,
646 conf->no_del, conf->no_ends) < 0;
647
648 // Build up qual
649 err |= kputc_(c+33 < 126 ? c+33 : 126, &ks_qual) < 0;
650 cnt++;
651 }
652 }
653 if (err) {
654 ret = 1;
655 goto fail;
656 }
657 fprintf(pileup_fp, "\t%d\t", cnt);
658
659 if (n_plp[i] == 0) {
660 fputs("*\t*", pileup_fp);
661 int flag_value = MPLP_PRINT_MAPQ_CHAR;
662 while(flag_value < MPLP_PRINT_LAST) {
663 if (flag_value != MPLP_PRINT_MODS
664 && (conf->flag & flag_value))
665 fputs("\t*", pileup_fp);
666 flag_value <<= 1;
667 }
668 if (conf->auxlist) {
669 int t = 0;
670 while(t++ < ((klist_t(auxlist) *)conf->auxlist)->size)
671 fputs("\t*", pileup_fp);
672 }
673 } else {
674 if (ks_seq.l) {
675 fwrite(ks_seq.s, 1, ks_seq.l, pileup_fp);
676 } else {
677 putc('*', pileup_fp);
678 }
679 putc('\t', pileup_fp);
680
681 if (ks_qual.l) {
682 fwrite(ks_qual.s, 1, ks_qual.l, pileup_fp);
683 } else {
684 putc('*', pileup_fp);
685 }
686
687 /* Print selected columns */
688 int flag_value = MPLP_PRINT_MAPQ_CHAR;
689 while(flag_value < MPLP_PRINT_LAST) {
690 if (flag_value != MPLP_PRINT_MODS
691 && (conf->flag & flag_value)) {
692 int n = 0;
693 putc('\t', pileup_fp);
694 for (j = 0; j < n_plp[i]; ++j) {
695 const bam_pileup1_t *p = &plp[i][j];
696 int c = p->qpos < p->b->core.l_qseq
697 ? bam_get_qual(p->b)[p->qpos]
698 : 0;
699 if ( c < conf->min_baseQ ) continue;
700 if (n > 0 && flag_value != MPLP_PRINT_MAPQ_CHAR) putc(',', pileup_fp);
701 n++;
702
703 switch (flag_value) {
704 case MPLP_PRINT_MAPQ_CHAR:
705 c = p->b->core.qual + 33;
706 if (c > 126) c = 126;
707 putc(c, pileup_fp);
708 break;
709 case MPLP_PRINT_QPOS:
710 // query position in current orientation
711 fprintf(pileup_fp, "%d", p->qpos + 1);
712 break;
713 case MPLP_PRINT_QPOS5: {
714 // query position in 5' to 3' orientation
715 int pos5 = bam_is_rev(p->b)
716 ? p->b->core.l_qseq-p->qpos + p->is_del
717 : p->qpos + 1;
718 fprintf(pileup_fp, "%d", pos5);
719 break;
720 }
721 case MPLP_PRINT_QNAME:
722 fputs(bam_get_qname(p->b), pileup_fp);
723 break;
724 case MPLP_PRINT_FLAG:
725 fprintf(pileup_fp, "%d", p->b->core.flag);
726 break;
727 case MPLP_PRINT_RNAME:
728 if (p->b->core.tid >= 0)
729 fputs(sam_hdr_tid2name(h, p->b->core.tid), pileup_fp);
730 else
731 putc('*', pileup_fp);
732 break;
733 case MPLP_PRINT_POS:
734 fprintf(pileup_fp, "%"PRId64, (int64_t) p->b->core.pos + 1);
735 break;
736 case MPLP_PRINT_MAPQ:
737 fprintf(pileup_fp, "%d", p->b->core.qual);
738 break;
739 case MPLP_PRINT_RNEXT:
740 if (p->b->core.mtid >= 0)
741 fputs(sam_hdr_tid2name(h, p->b->core.mtid), pileup_fp);
742 else
743 putc('*', pileup_fp);
744 break;
745 case MPLP_PRINT_PNEXT:
746 fprintf(pileup_fp, "%"PRId64, (int64_t) p->b->core.mpos + 1);
747 break;
748 case MPLP_PRINT_RLEN:
749 fprintf(pileup_fp, "%d", p->b->core.l_qseq);
750 break;
751 }
752 }
753 if (!n) putc('*', pileup_fp);
754 }
755 flag_value <<= 1;
756 }
757
758 /* Print selected tags */
759 klist_t(auxlist) *auxlist_p = ((klist_t(auxlist) *)conf->auxlist);
760 if (auxlist_p && auxlist_p->size) {
761 kliter_t(auxlist) *aux;
762 for (aux = kl_begin(auxlist_p); aux != kl_end(auxlist_p); aux = kl_next(aux)) {
763 int n = 0; // NB shadows outer loop
764 putc('\t', pileup_fp);
765 for (j = 0; j < n_plp[i]; ++j) {
766 const bam_pileup1_t *p = &plp[i][j];
767 int c = p->qpos < p->b->core.l_qseq
768 ? bam_get_qual(p->b)[p->qpos]
769 : 0;
770 if ( c < conf->min_baseQ ) continue;
771
772 if (n > 0) putc(conf->sep, pileup_fp);
773 n++;
774 uint8_t* tag_u = bam_aux_get(p->b, kl_val(aux));
775 if (!tag_u) {
776 putc(conf->empty , pileup_fp);
777 continue;
778 }
779
780 int tag_supported = 0;
781
782 /* Tag value is string */
783 if (*tag_u == 'Z' || *tag_u == 'H') {
784 char *tag_s = bam_aux2Z(tag_u);
785 if (!tag_s) continue;
786 fputs(tag_s, pileup_fp);
787 tag_supported = 1;
788 }
789
790 /* Tag value is integer */
791 if (*tag_u == 'I' || *tag_u == 'i' || *tag_u == 'C' || *tag_u == 'c' || *tag_u == 'S' || *tag_u == 's') {
792 int64_t tag_i = bam_aux2i(tag_u);
793 fprintf(pileup_fp, "%" PRId64 "", tag_i);
794 tag_supported = 1;
795 }
796
797 /* Tag value is float */
798 if (*tag_u == 'd' || *tag_u == 'f') {
799 double tag_f = bam_aux2f(tag_u);
800 fprintf(pileup_fp, "%lf", tag_f);
801 tag_supported = 1;
802 }
803
804 /* Tag value is character */
805 if (*tag_u == 'A') {
806 char tag_c = bam_aux2A(tag_u);
807 putc(tag_c, pileup_fp);
808 tag_supported = 1;
809 }
810
811 if (!tag_supported) putc('*', pileup_fp);
812 }
813 if (!n) putc('*', pileup_fp);
814 }
815 }
816 }
817 }
818 putc('\n', pileup_fp);
819 }
820
821 ks_free(&ks_seq);
822 ks_free(&ks_mod);
823 ks_free(&ks_qual);
824
825 if (ret < 0) {
826 print_error("mpileup", "error reading from input file");
827 ret = EXIT_FAILURE;
828 goto fail;
829 }
830
831 if (conf->all) {
832 // Handle terminating region
833 if (last_tid < 0 && conf->reg && conf->all > 1) {
834 last_tid = tid0;
835 last_pos = beg0-1;
836 mplp_get_ref(data[0], tid0, &ref, &ref_len);
837 } else if (last_tid < 0 && !one_seq && conf->all > 1) {
838 last_tid = 0; // --aa on a blank file
839 }
840 while (last_tid >= 0 && last_tid < sam_hdr_nref(h)) {
841 mplp_get_ref(data[0], last_tid, &ref, &ref_len);
842 while (++last_pos < sam_hdr_tid2len(h, last_tid)) {
843 if (last_pos >= end0) break;
844 if (conf->bed && bed_overlap(conf->bed, sam_hdr_tid2name(h, last_tid), last_pos, last_pos + 1) == 0)
845 continue;
846 print_empty_pileup(pileup_fp, conf, sam_hdr_tid2name(h, last_tid), last_pos, nfn, ref, ref_len);
847 }
848 last_tid++;
849 last_pos = -1;
850 if (conf->all < 2 || conf->reg)
851 break;
852 }
853 }
854
855 fail:
856 // clean up
857 if (pileup_fp && conf->output_fname) fclose(pileup_fp);
858 bam_smpl_destroy(sm); free(buf.s);
859 for (i = 0; i < gplp.n; ++i) free(gplp.plp[i]);
860 free(gplp.plp); free(gplp.n_plp); free(gplp.m_plp);
861 bam_mplp_destroy(iter);
862 sam_hdr_destroy(h);
863 for (i = 0; i < nfn; ++i) {
864 sam_close(data[i]->fp);
865 if (data[i]->iter) hts_itr_destroy(data[i]->iter);
866 free(data[i]);
867 }
868 free(data); free(plp); free(n_plp);
869 free(mp_ref.ref[0]);
870 free(mp_ref.ref[1]);
871 return ret;
872 }
873
874 static int is_url(const char *s)
875 {
876 static const char uri_scheme_chars[] =
877 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+.-";
878 return s[strspn(s, uri_scheme_chars)] == ':';
879 }
880
881 #define MAX_PATH_LEN 1024
882 int read_file_list(const char *file_list,int *n,char **argv[])
883 {
884 char buf[MAX_PATH_LEN];
885 int len, nfiles = 0;
886 char **files = NULL;
887 struct stat sb;
888
889 *n = 0;
890 *argv = NULL;
891
892 FILE *fh = fopen(file_list,"r");
893 if ( !fh )
894 {
895 fprintf(samtools_stderr,"%s: %s\n", file_list,strerror(errno));
896 return 1;
897 }
898
899 files = calloc(nfiles,sizeof(char*));
900 nfiles = 0;
901 while ( fgets(buf,MAX_PATH_LEN,fh) )
902 {
903 // allow empty lines and trailing spaces
904 len = strlen(buf);
905 while ( len>0 && isspace(buf[len-1]) ) len--;
906 if ( !len ) continue;
907
908 // check sanity of the file list
909 buf[len] = 0;
910 if (! (is_url(buf) || stat(buf, &sb) == 0))
911 {
912 // no such file, check if it is safe to print its name
913 int i, safe_to_print = 1;
914 for (i=0; i<len; i++)
915 if (!isprint(buf[i])) { safe_to_print = 0; break; }
916 if ( safe_to_print )
917 fprintf(samtools_stderr,"The file list \"%s\" appears broken, could not locate: %s\n", file_list,buf);
918 else
919 fprintf(samtools_stderr,"Does the file \"%s\" really contain a list of files and do all exist?\n", file_list);
920 return 1;
921 }
922
923 nfiles++;
924 files = realloc(files,nfiles*sizeof(char*));
925 files[nfiles-1] = strdup(buf);
926 }
927 fclose(fh);
928 if ( !nfiles )
929 {
930 fprintf(samtools_stderr,"No files read from %s\n", file_list);
931 return 1;
932 }
933 *argv = files;
934 *n = nfiles;
935 return 0;
936 }
937 #undef MAX_PATH_LEN
938
939 static void print_usage(FILE *fp, const mplp_conf_t *mplp)
940 {
941 char *tmp_require = bam_flag2str(mplp->rflag_require);
942 char *tmp_filter = bam_flag2str(mplp->rflag_filter);
943
944 // Display usage information, formatted for the standard 80 columns.
945 // (The unusual string formatting here aids the readability of this
946 // source code in 80 columns, to the extent that's possible.)
947
948 fprintf(fp,
949 "\n"
950 "Usage: samtools mpileup [options] in1.bam [in2.bam [...]]\n"
951 "\n"
952 "Input options:\n"
953 " -6, --illumina1.3+ quality is in the Illumina-1.3+ encoding\n"
954 " -A, --count-orphans do not discard anomalous read pairs\n"
955 " -b, --bam-list FILE list of input BAM filenames, one per line\n"
956 " -B, --no-BAQ disable BAQ (per-Base Alignment Quality)\n"
957 " -C, --adjust-MQ INT adjust mapping quality; recommended:50, disable:0 [0]\n"
958 " -d, --max-depth INT max per-file depth; avoids excessive memory usage [%d]\n", mplp->max_depth);
959 fprintf(fp,
960 " -E, --redo-BAQ recalculate BAQ on the fly, ignore existing BQs\n"
961 " -f, --fasta-ref FILE faidx indexed reference sequence file\n"
962 " -G, --exclude-RG FILE exclude read groups listed in FILE\n"
963 " -l, --positions FILE skip unlisted positions (chr pos) or regions (BED)\n"
964 " -q, --min-MQ INT skip alignments with mapQ smaller than INT [%d]\n", mplp->min_mq);
965 fprintf(fp,
966 " -Q, --min-BQ INT skip bases with baseQ/BAQ smaller than INT [%d]\n", mplp->min_baseQ);
967 fprintf(fp,
968 " -r, --region REG region in which pileup is generated\n"
969 " -R, --ignore-RG ignore RG tags (one BAM = one sample)\n"
970 " --rf, --incl-flags STR|INT\n"
971 " required flags: only include reads with any of\n"
972 " the mask bits set [%s]\n", tmp_require);
973 fprintf(fp,
974 " --ff, --excl-flags STR|INT\n"
975 " filter flags: skip reads with any of the mask bits set\n"
976 " [%s]\n", tmp_filter);
977 fprintf(fp,
978 " -x, --ignore-overlaps-removal, --disable-overlap-removal\n"
979 " disable read-pair overlap detection and removal\n"
980 " -X, --customized-index use customized index files\n" // -X flag for index filename
981 "\n"
982 "Output options:\n"
983 " -o, --output FILE write output to FILE [standard output]\n"
984 " -O, --output-BP output base positions on reads, current orientation\n"
985 " --output-BP-5 output base positions on reads, 5' to 3' orientation\n"
986 " -M, --output-mods output base modifications\n"
987 " -s, --output-MQ output mapping quality\n"
988 " --output-QNAME output read names\n"
989 " --output-extra STR output extra read fields and read tag values\n"
990 " --output-sep CHAR set the separator character for tag lists [,]\n"
991 " --output-empty CHAR set the no value character for tag lists [*]\n"
992 " --no-output-ins skip insertion sequence after +NUM\n"
993 " Use twice for complete insertion removal\n"
994 " --no-output-ins-mods don't display base modifications within insertions\n"
995 " --no-output-del skip deletion sequence after -NUM\n"
996 " Use twice for complete deletion removal\n"
997 " --no-output-ends remove ^MQUAL and $ markup in sequence column\n"
998 " --reverse-del use '#' character for deletions on the reverse strand\n"
999 " -a output all positions (including zero depth)\n"
1000 " -a -a (or -aa) output absolutely all positions, including unused ref. sequences\n"
1001 "\n"
1002 "Generic options:\n");
1003 sam_global_opt_help(fp, "-.--.--.");
1004
1005 fprintf(fp, "\n"
1006 "Note that using \"samtools mpileup\" to generate BCF or VCF files has been\n"
1007 "removed. To output these formats, please use \"bcftools mpileup\" instead.\n");
1008
1009 free(tmp_require);
1010 free(tmp_filter);
1011 }
1012
1013 int bam_mpileup(int argc, char *argv[])
1014 {
1015 int c;
1016 const char *file_list = NULL;
1017 char **fn = NULL;
1018 int nfiles = 0, use_orphan = 0, has_index_file = 0;
1019 mplp_conf_t mplp;
1020 memset(&mplp, 0, sizeof(mplp_conf_t));
1021 mplp.min_baseQ = 13;
1022 mplp.capQ_thres = 0;
1023 mplp.max_depth = MPLP_MAX_DEPTH;
1024 mplp.flag = MPLP_NO_ORPHAN | MPLP_REALN | MPLP_SMART_OVERLAPS;
1025 mplp.argc = argc; mplp.argv = argv;
1026 mplp.rflag_filter = BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP;
1027 mplp.output_fname = NULL;
1028 mplp.all = 0;
1029 mplp.rev_del = 0;
1030 mplp.sep = ',';
1031 mplp.empty = '*';
1032 sam_global_args_init(&mplp.ga);
1033
1034 static const struct option lopts[] =
1035 {
1036 SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', 0, '-'),
1037 {"rf", required_argument, NULL, 1}, // require flag
1038 {"ff", required_argument, NULL, 2}, // filter flag
1039 {"incl-flags", required_argument, NULL, 1},
1040 {"excl-flags", required_argument, NULL, 2},
1041 {"output", required_argument, NULL, 3},
1042 {"output-QNAME", no_argument, NULL, 5},
1043 {"output-qname", no_argument, NULL, 5},
1044 {"illumina1.3+", no_argument, NULL, '6'},
1045 {"count-orphans", no_argument, NULL, 'A'},
1046 {"bam-list", required_argument, NULL, 'b'},
1047 {"no-BAQ", no_argument, NULL, 'B'},
1048 {"no-baq", no_argument, NULL, 'B'},
1049 {"adjust-MQ", required_argument, NULL, 'C'},
1050 {"adjust-mq", required_argument, NULL, 'C'},
1051 {"max-depth", required_argument, NULL, 'd'},
1052 {"redo-BAQ", no_argument, NULL, 'E'},
1053 {"redo-baq", no_argument, NULL, 'E'},
1054 {"fasta-ref", required_argument, NULL, 'f'},
1055 {"exclude-RG", required_argument, NULL, 'G'},
1056 {"exclude-rg", required_argument, NULL, 'G'},
1057 {"positions", required_argument, NULL, 'l'},
1058 {"region", required_argument, NULL, 'r'},
1059 {"ignore-RG", no_argument, NULL, 'R'},
1060 {"ignore-rg", no_argument, NULL, 'R'},
1061 {"min-MQ", required_argument, NULL, 'q'},
1062 {"min-mq", required_argument, NULL, 'q'},
1063 {"min-BQ", required_argument, NULL, 'Q'},
1064 {"min-bq", required_argument, NULL, 'Q'},
1065 // NB: old "--ignore-overlaps" auto-completes to this
1066 {"ignore-overlaps-removal", no_argument, NULL, 'x'},
1067 {"disable-overlap-removal", no_argument, NULL, 'x'},
1068 {"output-mods", no_argument, NULL, 'M'},
1069 {"output-BP", no_argument, NULL, 'O'},
1070 {"output-bp", no_argument, NULL, 'O'},
1071 {"output-BP-5", no_argument, NULL, 14},
1072 {"output-bp-5", no_argument, NULL, 14},
1073 {"output-MQ", no_argument, NULL, 's'},
1074 {"output-mq", no_argument, NULL, 's'},
1075 {"ext-prob", required_argument, NULL, 'e'},
1076 {"gap-frac", required_argument, NULL, 'F'},
1077 {"tandem-qual", required_argument, NULL, 'h'},
1078 {"skip-indels", no_argument, NULL, 'I'},
1079 {"max-idepth", required_argument, NULL, 'L'},
1080 {"min-ireads ", required_argument, NULL, 'm'},
1081 {"per-sample-mF", no_argument, NULL, 'p'},
1082 {"per-sample-mf", no_argument, NULL, 'p'},
1083 {"platforms", required_argument, NULL, 'P'},
1084 {"customized-index", no_argument, NULL, 'X'},
1085 {"reverse-del", no_argument, NULL, 6},
1086 {"output-extra", required_argument, NULL, 7},
1087 {"output-sep", required_argument, NULL, 8},
1088 {"output-empty", required_argument, NULL, 9},
1089 {"no-output-ins", no_argument, NULL, 10},
1090 {"no-output-ins-mods", no_argument, NULL, 11},
1091 {"no-output-del", no_argument, NULL, 12},
1092 {"no-output-ends", no_argument, NULL, 13},
1093 {NULL, 0, NULL, 0}
1094 };
1095
1096 while ((c = getopt_long(argc, argv, "Af:r:l:q:Q:RC:Bd:b:o:EG:6OsxXaM",lopts,NULL)) >= 0) {
1097 switch (c) {
1098 case 'x': mplp.flag &= ~MPLP_SMART_OVERLAPS; break;
1099 case 1 :
1100 mplp.rflag_require = bam_str2flag(optarg);
1101 if ( mplp.rflag_require<0 ) { fprintf(samtools_stderr,"Could not parse --rf %s\n", optarg); return 1; }
1102 break;
1103 case 2 :
1104 mplp.rflag_filter = bam_str2flag(optarg);
1105 if ( mplp.rflag_filter<0 ) { fprintf(samtools_stderr,"Could not parse --ff %s\n", optarg); return 1; }
1106 break;
1107 case 3 : mplp.output_fname = optarg; break;
1108 case 5 : mplp.flag |= MPLP_PRINT_QNAME; break;
1109 case 6 : mplp.rev_del = 1; break;
1110 case 7 :
1111 if (build_auxlist(&mplp, optarg) != 0) {
1112 fprintf(samtools_stderr,"Could not build aux list using '%s'\n", optarg);
1113 return 1;
1114 }
1115 break;
1116 case 8: mplp.sep = optarg[0]; break;
1117 case 9: mplp.empty = optarg[0]; break;
1118 case 10: mplp.no_ins++; break;
1119 case 11: mplp.no_ins_mods = 1; break;
1120 case 12: mplp.no_del++; break;
1121 case 13: mplp.no_ends = 1; break;
1122 case 'f':
1123 mplp.fai = fai_load(optarg);
1124 if (mplp.fai == NULL) return 1;
1125 mplp.fai_fname = optarg;
1126 break;
1127 case 'd': mplp.max_depth = atoi(optarg); break;
1128 case 'r': mplp.reg = strdup(optarg); break;
1129 case 'l':
1130 // In the original version the whole BAM was streamed which is inefficient
1131 // with few BED intervals and big BAMs. Todo: devise a heuristic to determine
1132 // best strategy, that is streaming or jumping.
1133 mplp.bed = bed_read(optarg);
1134 if (!mplp.bed) { print_error_errno("mpileup", "Could not read file \"%s\"", optarg); return 1; }
1135 break;
1136 case 'B': mplp.flag &= ~MPLP_REALN; break;
1137 case 'X': has_index_file = 1; break;
1138 case 'E': mplp.flag |= MPLP_REDO_BAQ; break;
1139 case '6': mplp.flag |= MPLP_ILLUMINA13; break;
1140 case 'R': mplp.flag |= MPLP_IGNORE_RG; break;
1141 case 's': mplp.flag |= MPLP_PRINT_MAPQ_CHAR; break;
1142 case 'O': mplp.flag |= MPLP_PRINT_QPOS; break;
1143 case 14: mplp.flag |= MPLP_PRINT_QPOS5; break;
1144 case 'M': mplp.flag |= MPLP_PRINT_MODS; break;
1145 case 'C': mplp.capQ_thres = atoi(optarg); break;
1146 case 'q': mplp.min_mq = atoi(optarg); break;
1147 case 'Q': mplp.min_baseQ = atoi(optarg); break;
1148 case 'b': file_list = optarg; break;
1149 case 'o': mplp.output_fname = optarg; break;
1150 case 'A': use_orphan = 1; break;
1151 case 'G': {
1152 FILE *fp_rg;
1153 char buf[1024];
1154 mplp.rghash = khash_str2int_init();
1155 if ((fp_rg = fopen(optarg, "r")) == NULL)
1156 fprintf(samtools_stderr, "[%s] Fail to open file %s. Continue anyway.\n", __func__, optarg);
1157 while (!feof(fp_rg) && fscanf(fp_rg, "%s", buf) > 0) // this is not a good style, but forgive me...
1158 khash_str2int_inc(mplp.rghash, strdup(buf));
1159 fclose(fp_rg);
1160 }
1161 break;
1162 case 'a': mplp.all++; break;
1163 default:
1164 if (parse_sam_global_opt(c, optarg, lopts, &mplp.ga) == 0) break;
1165 /* else fall-through */
1166 case '?':
1167 print_usage(samtools_stderr, &mplp);
1168 return 1;
1169 }
1170 }
1171 if (!mplp.fai && mplp.ga.reference) {
1172 mplp.fai_fname = mplp.ga.reference;
1173 mplp.fai = fai_load(mplp.fai_fname);
1174 if (mplp.fai == NULL) return 1;
1175 }
1176
1177 if ( !(mplp.flag&MPLP_REALN) && mplp.flag&MPLP_REDO_BAQ )
1178 {
1179 fprintf(samtools_stderr,"Error: The -B option cannot be combined with -E\n");
1180 return 1;
1181 }
1182 if (use_orphan) mplp.flag &= ~MPLP_NO_ORPHAN;
1183 if (argc == 1)
1184 {
1185 print_usage(samtools_stderr, &mplp);
1186 return 1;
1187 }
1188 int ret;
1189 if (file_list) {
1190 if (has_index_file) {
1191 fprintf(samtools_stderr,"Error: The -b option cannot be combined with -X\n"); // No customize index loc in file list mode
1192 return 1;
1193 }
1194 if ( read_file_list(file_list,&nfiles,&fn) ) return 1;
1195 ret = mpileup(&mplp,nfiles,fn,NULL);
1196 for (c=0; c<nfiles; c++) free(fn[c]);
1197 free(fn);
1198 }
1199 else {
1200 if (has_index_file) {
1201 if ((argc - optind)%2 !=0) { // Calculate # of input BAM files
1202 fprintf(samtools_stderr, "Odd number of filenames detected! Each BAM file should have an index file\n");
1203 return 1;
1204 }
1205 nfiles = (argc - optind)/2;
1206 ret = mpileup(&mplp, nfiles, argv + optind, argv + nfiles + optind);
1207 } else {
1208 nfiles = argc - optind;
1209 ret = mpileup(&mplp, nfiles, argv + optind, NULL);
1210 }
1211 }
1212 if (mplp.rghash) khash_str2int_destroy_free(mplp.rghash);
1213 free(mplp.reg); free(mplp.pl_list);
1214 if (mplp.fai) fai_destroy(mplp.fai);
1215 if (mplp.bed) bed_destroy(mplp.bed);
1216 if (mplp.auxlist) kl_destroy(auxlist, (klist_t(auxlist) *)mplp.auxlist);
1217 return ret;
1218 }