Debian Codegraph @

samtools/bam2depth.c.pysam.c

raw symbols SCIP
1 #include "samtools.pysam.h"
2
3 /* bam2depth.c -- depth subcommand.
4
5 Copyright (C) 2011, 2012 Broad Institute.
6 Copyright (C) 2012-2016, 2018, 2019-2022, 2024 Genome Research Ltd.
7
8 Author: Heng Li <[email protected]> (to 2020)
9 Author: James Bonfield <[email protected]> (2021 rewrite)
10
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in
20 all copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
25 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
27 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
28 DEALINGS IN THE SOFTWARE. */
29
30 /* This program demonstrates how to generate pileup from multiple BAMs
31 * simultaneously, to achieve random access and to use the BED interface.
32 * To compile this program separately, you may:
33 *
34 * gcc -g -O2 -Wall -o bam2depth -D_MAIN_BAM2DEPTH bam2depth.c -lhts -lz
35 */
36
37 #include <config.h>
38
39 #include <stdlib.h>
40 #include <string.h>
41 #include <stdio.h>
42 #include <limits.h>
43 #include <unistd.h>
44 #include "htslib/sam.h"
45 #include "samtools.h"
46 #include "bedidx.h"
47 #include "sam_opts.h"
48 #include "htslib/khash.h"
49
50 // From bam_plcmd.c
51 int read_file_list(const char *file_list, int *n, char **argv[]);
52
53 // We accumulate to hist[pos & (size-1)]. This is a ring-buffer.
54 // We track where we last got to in output and what the biggest value
55 // we've written to so far (in absolute unmasked coordinates) in
56 // "last_output" and "end_pos" respectively.
57 // For each new record we just flush anything we haven't written yet
58 // already, between "last_output" and this read's start position, and
59 // initialise any newly seen positions between "end_pos" and this read's
60 // end position.
61 typedef struct {
62 size_t size;
63 int **hist; // hist[nfiles][size]
64 hts_pos_t *end_pos; // end_pos[nfiles]
65 hts_pos_t last_output;
66 int last_ref;
67 int nfiles;
68 const char *ref;
69 kstring_t ks;
70 hts_pos_t beg, end; // limit to region
71 int tid;
72 } depth_hist;
73
74 typedef struct {
75 int header;
76 int flag;
77 int incl_flag;
78 int require_flag;
79 int min_qual;
80 int min_mqual;
81 int min_len;
82 int skip_del;
83 int all_pos;
84 int remove_overlaps;
85 FILE *out;
86 char *reg;
87 void *bed;
88 } depth_opt;
89
90 static void zero_region(depth_opt *opt, depth_hist *dh,
91 const char *name, hts_pos_t start, hts_pos_t end) {
92 hts_pos_t i;
93 kstring_t *ks = &dh->ks;
94
95 kputs(name, ks_clear(ks));
96 kputc('\t', ks);
97 size_t cur_l = ks->l;
98 if (dh->beg >= 0 && start < dh->beg)
99 start = dh->beg;
100 if (dh->end >= 0 && end > dh->end)
101 end = dh->end;
102
103 for (i = start; i < end; i++) {
104 // Could be optimised, but needs better API to skip to next
105 // bed region.
106 if (opt->bed && bed_overlap(opt->bed, name, i, i+1) == 0)
107 continue;
108
109 ks->l = cur_l;
110 kputll(i+1, ks);
111 int n;
112 for (n = 0; n < dh->nfiles; n++) {
113 kputc_('\t', ks);
114 kputc_('0', ks);
115 }
116 kputc('\n', ks);
117 fputs(ks->s, opt->out);
118 }
119 ks->l = cur_l;
120 }
121
122 // A variation of bam_cigar2qlen which doesn't count soft-clips in to the
123 // equation. Basically it's the number of bases in query that are aligned
124 // in some way to the reference (including insertions, which are considered
125 // to be aligned by dint of being anchored either side).
126 hts_pos_t qlen_used(bam1_t *b) {
127 int n_cigar = b->core.n_cigar;
128 const uint32_t *cigar = bam_get_cigar(b);
129
130 hts_pos_t l;
131
132 if (b->core.l_qseq) {
133 // Known SEQ permits of short cut of l_qseq minus CSOFT_CLIPs.
134 // Full scan not needed, which helps on excessively long CIGARs.
135 l = b->core.l_qseq;
136 int kl, kr;
137 for (kl = 0; kl < n_cigar; kl++)
138 if (bam_cigar_op(cigar[kl]) == BAM_CSOFT_CLIP)
139 l -= bam_cigar_oplen(cigar[kl]);
140 else
141 break;
142
143 for (kr = n_cigar-1; kr > kl; kr--)
144 if (bam_cigar_op(cigar[kr]) == BAM_CSOFT_CLIP)
145 l -= bam_cigar_oplen(cigar[kr]);
146 else
147 break;
148 } else {
149 // Unknown SEQ ("*") needs a full scan through the CIGAR string.
150 static int query[16] = {
151 //M I D N S H P = X B ? ? ? ? ? ?
152 1,1,0,0, 0,0,0,1, 1,0,0,0, 0,0,0,0
153 };
154 int k;
155 for (k = l = 0; k < n_cigar; k++)
156 if (query[bam_cigar_op(cigar[k])])
157 l += bam_cigar_oplen(cigar[k]);
158 }
159 return l;
160
161 }
162
163 // Without HTS_OPT3 gcc11 and earlier don't vectorize this, nor even
164 // unroll it. By adding HTS_OPT3 we can force a better level of optimization.
165 // On an Illumina BAM with gcc11 -O2, with HTS_OPT3 is 9% quicker for the
166 // entire process (ie decompress, iterator, aggregate & report)
167 static inline void HTS_OPT3 incr_hist(int *hist, int oplen) {
168 const int N = 16;
169 int k;
170 for (k = 0; k < (oplen & ~(N-1)); k+=N) {
171 for (int i = 0; i < N; i++)
172 hist[k+i]++;
173 }
174 for (; k < oplen; k++)
175 hist[k]++;
176 }
177
178 static inline void HTS_OPT3
179 incr_hist_qual(int *hist, uint8_t *qual, int min_qual, int oplen) {
180 if (!min_qual) {
181 incr_hist(hist, oplen);
182 return;
183 }
184
185 int k;
186 for (k = 0; k < (oplen & ~31); k+=32) {
187 int pass[32];
188 // Two separate loops helps clang to vectorize
189 for (int i = 0; i < 32; i++)
190 pass[i]=qual[k+i]>=min_qual;
191
192 for (int i = 0; i < 32; i++)
193 hist[k+i]+=pass[i];
194 }
195 for (; k < oplen; k++)
196 hist[k]+=qual[k]>=min_qual;
197 }
198
199 // Adds the depth for a single read to a depth_hist struct.
200 // For just one file, this is easy. We just have a circular buffer
201 // where we increment values for bits that overlap existing data
202 // and initialise values for coordinates which we're seeing for the first
203 // time. This is tracked by "end_pos" to know where we've got to.
204 //
205 // As the input is sorted, we can flush output from "last_output" to
206 // b->core.pos.
207 //
208 // With multiple files, we must feed data in sorted order as if all files
209 // are merged, but track depth per file. This also means "end_pos" is per
210 // file too, but "last_output" is global as it corresponds to rows printed.
211 static int add_depth(depth_opt *opt, depth_hist *dh, sam_hdr_t *h, bam1_t *b,
212 int overlap_clip, int file) {
213 hts_pos_t i;
214 size_t hmask = dh->size-1;
215 int n;
216
217 if (!b || b->core.tid != dh->last_ref) {
218 // New ref
219 if (dh->last_ref >= 0) {
220 // do end
221 size_t cur_l = dh->ks.l;
222 int nf = dh->nfiles;
223 i = dh->last_output;
224 for (i = dh->last_output; nf; i++) {
225 nf = 0;
226 for (n = 0; n < dh->nfiles; n++) {
227 if (i < dh->end_pos[n])
228 nf++;
229 }
230 if (!nf)
231 break;
232
233 if (opt->bed && bed_overlap(opt->bed, dh->ref, i, i+1) == 0)
234 continue;
235
236 dh->ks.l = cur_l;
237 kputll(i+1, &dh->ks);
238 for (n = 0; n < dh->nfiles; n++) {
239 kputc_('\t', &dh->ks);
240 int d = i < dh->end_pos[n]
241 ? dh->hist[n][i & hmask]
242 : 0;
243 kputuw(d, &dh->ks);
244 }
245 kputc('\n', &dh->ks);
246 fputs(dh->ks.s, opt->out);
247 }
248 if (opt->all_pos) {
249 // End of last ref
250 zero_region(opt, dh,
251 sam_hdr_tid2name(h, dh->last_ref),
252 i, sam_hdr_tid2len(h, dh->last_ref));
253 }
254 dh->ks.l = cur_l;
255 }
256
257 if (opt->all_pos > 1 && !opt->reg) {
258 // Any previous unused refs
259 int lr = dh->last_ref < 0 ? 0 : dh->last_ref+1;
260 int rr = b ? b->core.tid : sam_hdr_nref(h), r;
261 for (r = lr; r < rr; r++)
262 zero_region(opt, dh,
263 sam_hdr_tid2name(h, r),
264 0, sam_hdr_tid2len(h, r));
265 }
266
267 if (!b) {
268 // we're just flushing to end of file
269 if (opt->all_pos && opt->reg && dh->last_ref < 0)
270 // -a or -aa without a single read being output yet
271 zero_region(opt, dh, sam_hdr_tid2name(h, dh->tid), dh->beg,
272 MIN(dh->end, sam_hdr_tid2len(h, dh->tid)));
273
274 return 0;
275 }
276
277 for (n = 0; dh->end_pos && n < dh->nfiles; n++)
278 dh->end_pos[n] = 0;
279 dh->last_output = dh->beg >= 0
280 ? MAX(b->core.pos, dh->beg)
281 : b->core.pos;
282 dh->last_ref = b->core.tid;
283 dh->ref = sam_hdr_tid2name(h, b->core.tid);
284 kputs(dh->ref, ks_clear(&dh->ks));
285 kputc('\t', &dh->ks);
286
287 if (opt->all_pos)
288 // Start of ref
289 zero_region(opt, dh, dh->ref, 0, b->core.pos);
290 } else {
291 if (dh->last_output < b->core.pos) {
292 // Flush any depth outputs up to start of new read
293 size_t cur_l = dh->ks.l;
294 int nf = dh->nfiles;
295 for (i = dh->last_output; i < b->core.pos; i++) {
296 nf = 0;
297 for (n = 0; n < dh->nfiles; n++) {
298 if (i < dh->end_pos[n])
299 nf++;
300 }
301 if (!nf)
302 break;
303
304 if (opt->bed && bed_overlap(opt->bed, dh->ref, i, i+1) == 0)
305 continue;
306
307 dh->ks.l = cur_l;
308 kputll(i+1, &dh->ks);
309 for (n = 0; n < dh->nfiles; n++) {
310 kputc_('\t', &dh->ks);
311 int d = i < dh->end_pos[n]
312 ? dh->hist[n][i & hmask]
313 : 0;
314 kputuw(d, &dh->ks);
315 }
316 kputc('\n', &dh->ks);
317 fputs(dh->ks.s, opt->out);
318 }
319 if (opt->all_pos && i < b->core.pos)
320 // Hole in middle of ref
321 zero_region(opt, dh, dh->ref, i, b->core.pos);
322
323 dh->ks.l = cur_l;
324 dh->last_output = b->core.pos;
325 }
326 }
327
328 hts_pos_t end_pos = bam_endpos(b); // 0 based, 1 past end.
329 //printf("%d %d\n", (int)b->core.pos+1, (int)end_pos);
330
331 if (b->core.tid < dh->last_ref ||
332 (dh->last_ref == b->core.tid && end_pos < dh->last_output)) {
333 print_error_errno("depth", "Data is not position sorted");
334 return -1;
335 }
336
337 // If needed, grow the circular buffer.
338 if (end_pos+1 - b->core.pos >= dh->size) {
339 size_t old_size = dh->size;
340 size_t old_hmask = hmask;
341 while (end_pos+1 - b->core.pos >= dh->size)
342 dh->size = dh->size ? 2*dh->size : 2048;
343 hmask = dh->size-1;
344 if (!dh->hist) {
345 dh->hist = calloc(dh->nfiles, sizeof(*dh->hist));
346 dh->end_pos = calloc(dh->nfiles, sizeof(*dh->end_pos));
347 if (!dh->hist || !dh->end_pos)
348 return -1;
349 }
350 for (n = 0; n < dh->nfiles; n++) {
351 int *hist = calloc(dh->size, sizeof(*dh->hist[n]));
352 if (!hist)
353 return -1;
354
355 // Simple approach for now; copy over old histogram verbatim.
356 for (i = dh->last_output; i < dh->last_output + old_size; i++)
357 hist[i & hmask] = dh->hist[n][i & old_hmask];
358 free(dh->hist[n]);
359 dh->hist[n] = hist;
360 }
361 }
362
363 // Accumulate depth, based on CIGAR
364 uint32_t *cig = bam_get_cigar(b);
365 int ncig = b->core.n_cigar, j, k, spos = 0;
366
367 // Zero new (previously unseen) coordinates so increment works later.
368 hts_pos_t end = MAX(dh->end_pos[file], b->core.pos);
369 if (end_pos > end && (end & hmask) < (end_pos & hmask)) {
370 memset(&dh->hist[file][end & hmask], 0,
371 sizeof(**dh->hist) * (end_pos - end));
372 } else {
373 for (i = end; i < end_pos; i++)
374 dh->hist[file][i & hmask] = 0;
375 }
376
377 i = b->core.pos;
378 uint8_t *qual = bam_get_qual(b);
379 int min_qual = opt->min_qual;
380 for (j = 0; j < ncig; j++) {
381 int op = bam_cigar_op(cig[j]);
382 int oplen = bam_cigar_oplen(cig[j]);
383
384 switch (op) {
385 case BAM_CDEL:
386 case BAM_CREF_SKIP:
387 if (op != BAM_CDEL || opt->skip_del) {
388 // don't increment reference location
389 if (i + oplen >= dh->end_pos[file]) {
390 for (k = 0; k < oplen; k++, i++) {
391 if (i >= dh->end_pos[file])
392 // redundant due to zero new elements above?
393 dh->hist[file][i & hmask] = 0;
394 }
395 } else {
396 i += oplen;
397 }
398 } else { // op == BAM_CDEL and we count them (-J option),
399 // We don't incr spos here, but we still use qual.
400 // This doesn't make much sense, but it's for compatibility
401 // with the old code. Arguably DEL shouldn't have a min
402 // qual and should always pass (as we've explicitly asked to
403 // include them).
404 int *hist = dh->hist[file];
405 k = 0;
406 if (overlap_clip) {
407 if (i+oplen < overlap_clip) {
408 i += oplen;
409 break;
410 } else if (i < overlap_clip) {
411 k = overlap_clip - i;
412 i = overlap_clip;
413 }
414 }
415
416 // Question: should we even check quality values for DEL?
417 // We've explicitly asked to include them, and the quality
418 // is wrong anyway (it's the neighbouring base). We do this
419 // for now for compatibility with the old depth command.
420 if (spos < b->core.l_qseq)
421 for (; k < oplen; k++, i++)
422 hist[i & hmask]+=qual[spos]>=min_qual;
423 else
424 for (; k < oplen; k++, i++)
425 hist[i & hmask]++;
426 }
427 break;
428
429 case BAM_CMATCH:
430 case BAM_CEQUAL:
431 case BAM_CDIFF: {
432 int *hist = dh->hist[file];
433 k = 0;
434 if (overlap_clip) {
435 if (i+oplen < overlap_clip) {
436 i += oplen;
437 break;
438 } else if (i < overlap_clip) {
439 oplen -= overlap_clip - i;
440 spos += overlap_clip - i;
441 i = overlap_clip;
442 }
443 }
444
445 int len = (i & hmask) < ((i+oplen) & hmask)
446 ? oplen // doesn't wrap around
447 : dh->size - (i&hmask); // does wrap around
448 incr_hist_qual(&hist[i & hmask], &qual[spos], min_qual, len);
449 if (oplen > len)
450 incr_hist_qual(hist, &qual[spos+len], min_qual, oplen-len);
451 spos += oplen;
452 i += oplen;
453 break;
454 }
455
456 case BAM_CINS:
457 case BAM_CSOFT_CLIP:
458 spos += oplen;
459 break;
460
461 case BAM_CPAD:
462 case BAM_CHARD_CLIP:
463 // ignore
464 break;
465
466 default:
467 print_error("depth", "Unsupported cigar op '%d'", op);
468 return -1;
469 }
470 }
471
472 if (dh->end >= 0 && end_pos > dh->end)
473 end_pos = dh->end;
474 if (dh->end_pos[file] < end_pos)
475 dh->end_pos[file] = end_pos;
476
477 return 0;
478 }
479
480 // Hash on name -> alignment end pos. This permits a naive overlap removal.
481 // Note it cannot analyse the overlapping sequence and qualities, so the
482 // interaction of basecalls/qualities and the -Q parameter cannot be
483 // applied here (unlike the full mpileup algorithm).
484 KHASH_MAP_INIT_STR(olap_hash, hts_pos_t)
485 typedef khash_t(olap_hash) olap_hash_t;
486
487 static int fastdepth_core(depth_opt *opt, uint32_t nfiles, char **fn,
488 samFile **fp, hts_itr_t **itr, sam_hdr_t **h) {
489 int ret = -1, err = 1, i;
490 olap_hash_t **overlaps = NULL;
491 depth_hist dh = {0};
492
493 // An array of bam structs, one per input file, to hold the next entry
494 bam1_t **b = calloc(nfiles, sizeof(*b));
495 int *finished = calloc(nfiles, sizeof(*finished)), to_go = nfiles;
496 if (!b || !finished)
497 goto err;
498
499 for (i = 0; i < nfiles; i++)
500 if (!(b[i] = bam_init1()))
501 goto err;
502
503 // Do we need one overlap hash per file? Or shared?
504 if (opt->remove_overlaps) {
505 if (!(overlaps = calloc(nfiles, sizeof(*overlaps))))
506 return -1;
507 for (i = 0; i < nfiles; i++) {
508 if (!(overlaps[i] = kh_init(olap_hash)))
509 return -1;
510 }
511 }
512
513 // Create the initial histogram
514 dh.nfiles = nfiles;
515 dh.size = 0;
516 dh.hist = NULL;
517 dh.last_ref = -99;
518 dh.end_pos = NULL;
519 dh.last_output = itr && itr[0] ? itr[0]->beg : 0;
520 ks_initialize(&dh.ks);
521
522 // Clip results to region if specified
523 dh.beg = -1;
524 dh.end = -1;
525 dh.tid = 0;
526 if (itr && itr[0]) {
527 dh.tid = itr[0]->tid;
528 dh.beg = itr[0]->beg;
529 dh.end = itr[0]->end;
530 }
531
532 if (opt->header) {
533 fprintf(opt->out, "#CHROM\tPOS");
534 for (i = 0; i < nfiles; i++)
535 fprintf(opt->out, "\t%s", fn[i]);
536 fputc('\n', opt->out);
537 }
538
539 // Populate first record per file
540 for (i = 0; i < nfiles; i++) {
541 for(;;) {
542 ret = itr && itr[i]
543 ? sam_itr_next(fp[i], itr[i], b[i])
544 : sam_read1(fp[i], h[i], b[i]);
545 if (ret < -1)
546 goto err;
547 if (ret == -1) {
548 to_go--;
549 finished[i] = 1;
550 break;
551 }
552
553 if (b[i]->core.tid < 0)
554 continue;
555 if (b[i]->core.flag & opt->flag)
556 continue; // must have none of the flags set
557 if (opt->incl_flag && (b[i]->core.flag & opt->incl_flag) == 0)
558 continue; // must have at least one flag set
559 if ((b[i]->core.flag & opt->require_flag) != opt->require_flag)
560 continue; // must have all lags set
561 if (b[i]->core.qual < opt->min_mqual)
562 continue;
563
564 // Original samtools depth used the total sequence (l_qseq)
565 // including soft-clips. This doesn't feel like a useful metric
566 // to be filtering on. We now only count sequence bases that
567 // form the used part of the alignment.
568 if (opt->min_len) {
569 if (qlen_used(b[i]) < opt->min_len)
570 continue;
571 }
572
573 break;
574 }
575 }
576
577 // Loop through input files, merging in order so we're
578 // always adding the next record in sequence
579 while (to_go) {
580 // Find next record in file list
581 int best_tid = INT_MAX, best_file = 0;
582 hts_pos_t best_pos = HTS_POS_MAX;
583
584 for (i = 0; i < nfiles; i++) {
585 if (finished[i])
586 continue;
587 if (best_tid > b[i]->core.tid) {
588 best_tid = b[i]->core.tid;
589 best_pos = b[i]->core.pos;
590 best_file = i;
591 } else if (best_tid == b[i]->core.tid &&
592 best_pos > b[i]->core.pos) {
593 best_pos = b[i]->core.pos;
594 best_file = i;
595 }
596 }
597 i = best_file;
598
599 hts_pos_t clip = 0;
600 if (overlaps && (b[i]->core.flag & BAM_FPAIRED) &&
601 !(b[i]->core.flag & BAM_FMUNMAP)) {
602 khiter_t k = kh_get(olap_hash, overlaps[i], bam_get_qname(b[i]));
603 if (k == kh_end(overlaps[i])) {
604 // not seen before
605 hts_pos_t endpos = bam_endpos(b[i]);
606
607 // Don't add if mate location is known and can't overlap.
608 if (b[i]->core.mpos == -1 ||
609 (b[i]->core.tid == b[i]->core.mtid &&
610 b[i]->core.mpos <= endpos)) {
611 k = kh_put(olap_hash, overlaps[i], bam_get_qname(b[i]),
612 &ret);
613 if (ret < 0)
614 return -1;
615 kh_key(overlaps[i], k) = strdup(bam_get_qname(b[i]));
616 kh_value(overlaps[i], k) = endpos;
617 }
618 } else {
619 // seen before
620 clip = kh_value(overlaps[i], k);
621 free((char *)kh_key(overlaps[i], k));
622 kh_del(olap_hash, overlaps[i], k);
623 }
624 }
625
626 // Add the next merged BAM record to the depth plot
627 if ((ret = add_depth(opt, &dh, h[i], b[i], clip, i)) < 0) {
628 ret = -1;
629 goto err;
630 }
631
632 // Populate next record from this file
633 for(;!finished[i];) {
634 ret = itr && itr[i]
635 ? sam_itr_next(fp[i], itr[i], b[i])
636 : sam_read1(fp[i], h[i], b[i]);
637 if (ret < -1) {
638 ret = -1;
639 goto err;
640 }
641 if (ret == -1) {
642 to_go--;
643 finished[i] = 1;
644 break;
645 }
646
647 if (b[i]->core.tid < 0)
648 continue;
649 if (b[i]->core.flag & opt->flag)
650 continue; // must have none of the flags set
651 if (opt->incl_flag && (b[i]->core.flag & opt->incl_flag) == 0)
652 continue; // must have at least one flag set
653 if ((b[i]->core.flag & opt->require_flag) != opt->require_flag)
654 continue; // must have all lags set
655 if (b[i]->core.qual < opt->min_mqual)
656 continue;
657
658 if (opt->min_len) {
659 if (qlen_used(b[i]) < opt->min_len)
660 continue;
661 }
662
663 break;
664 }
665 }
666
667 // Tidy up end.
668 ret = add_depth(opt, &dh, h[0], NULL, 0, 0);
669 err = 0;
670
671 err:
672 if (ret == 0 && err)
673 ret = -1;
674
675 for (i = 0; i < nfiles; i++) {
676 if (b[i])
677 bam_destroy1(b[i]);
678 if (dh.hist && dh.hist[i])
679 free(dh.hist[i]);
680 }
681 free(b);
682 free(finished);
683 ks_free(&dh.ks);
684 free(dh.hist);
685 free(dh.end_pos);
686 if (overlaps) {
687 khiter_t k;
688 for (i = 0; i < nfiles; i++) {
689 if (!overlaps[i])
690 continue;
691 for (k = kh_begin(overlaps[i]); k < kh_end(overlaps[i]); k++)
692 if (kh_exist(overlaps[i], k))
693 free((char *)kh_key(overlaps[i], k));
694 kh_destroy(olap_hash, overlaps[i]);
695 }
696 free(overlaps);
697 }
698
699 return ret;
700 }
701
702 static void usage_exit(FILE *fp, int exit_status)
703 {
704 fprintf(fp, "Usage: samtools depth [options] in.bam [in.bam ...]\n");
705 fprintf(fp, "\nOptions:\n");
706 fprintf(fp, " -a Output all positions (including zero depth)\n");
707 fprintf(fp, " -a -a, -aa Output absolutely all positions, including unused ref seqs\n");
708 fprintf(fp, " -r REG Specify a region in chr or chr:from-to syntax\n");
709 fprintf(fp, " -b FILE Use bed FILE for list of regions\n");
710 fprintf(fp, " -f FILE Specify list of input BAM/SAM/CRAM filenames\n");
711 fprintf(fp, " -X Use custom index files (in -X *.bam *.bam.bai order)\n");
712 fprintf(fp, " -g INT Remove specified flags from default filter-out flag list\n");
713 fprintf(fp, " -G, --excl-flags FLAGS\n");
714 fprintf(fp, " Add specified flags to the default filter-out flag list\n");
715 fprintf(fp, " [UNMAP,SECONDARY,QCFAIL,DUP]\n");
716 fprintf(fp, " --incl-flags FLAGS\n");
717 fprintf(fp, " Only include records with at least one the FLAGs present [0]\n");
718 fprintf(fp, " --require-flags FLAGS\n");
719 fprintf(fp, " Only include records with all of the FLAGs present [0]\n");
720 fprintf(fp, " -H Print a file header line\n");
721 fprintf(fp, " -l INT Minimum read length [0]\n");
722 fprintf(fp, " -o FILE Write output to FILE [samtools_stdout]\n");
723 fprintf(fp, " -q, --min-BQ INT\n"
724 " Filter bases with base quality smaller than INT [0]\n");
725 fprintf(fp, " -Q, --min-MQ INT\n"
726 " Filter alignments with mapping quality smaller than INT [0]\n");
727 fprintf(fp, " -J Include reads with deletions in depth computation\n");
728 fprintf(fp, " -s Do not count overlapping reads within a template\n");
729 sam_global_opt_help(fp, "-.--.@-.");
730 samtools_exit(exit_status);
731 }
732
733 int main_depth(int argc, char *argv[])
734 {
735 int nfiles, i, tmp_flag;
736 samFile **fp;
737 sam_hdr_t **header;
738 int c, has_index_file = 0;
739 char *file_list = NULL, **fn = NULL;
740 char *out_file = NULL;
741 depth_opt opt = {
742 .flag = BAM_FUNMAP | BAM_FSECONDARY | BAM_FDUP | BAM_FQCFAIL,
743 .incl_flag = 0,
744 .require_flag = 0,
745 .min_qual = 0,
746 .min_mqual = 0,
747 .skip_del = 1,
748 .header = 0,
749 .min_len = 0,
750 .out = samtools_stdout,
751 .all_pos = 0,
752 .remove_overlaps = 0,
753 .reg = NULL,
754 .bed = NULL,
755 };
756
757 sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
758 static const struct option lopts[] = {
759 {"min-MQ", required_argument, NULL, 'Q'},
760 {"min-mq", required_argument, NULL, 'Q'},
761 {"min-BQ", required_argument, NULL, 'q'},
762 {"min-bq", required_argument, NULL, 'q'},
763 {"excl-flags", required_argument, NULL, 'G'},
764 {"incl-flags", required_argument, NULL, 1},
765 {"require-flags", required_argument, NULL, 2},
766 SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', 0, '@'),
767 {NULL, 0, NULL, 0}
768 };
769
770 while ((c = getopt_long(argc, argv, "@:q:Q:JHd:m:l:g:G:o:ar:Xf:b:s",
771 lopts, NULL)) >= 0) {
772 switch (c) {
773 case 'a':
774 opt.all_pos++;
775 break;
776
777 case 'b':
778 opt.bed = bed_read(optarg);
779 if (!opt.bed) {
780 print_error_errno("depth", "Could not read file \"%s\"",
781 optarg);
782 return 1;
783 }
784 break;
785
786 case 'f':
787 file_list = optarg;
788 break;
789
790 case 'd':
791 case 'm':
792 // depth limit - now ignored
793 break;
794
795 case 'g':
796 tmp_flag = bam_str2flag(optarg);
797
798 if (tmp_flag < 0) {
799 print_error("depth", "Unknown flag '%s'", optarg);
800 return 1;
801 }
802
803 opt.flag &= ~tmp_flag;
804 break;
805 case 'G': // reject if any set
806 tmp_flag = bam_str2flag(optarg);
807
808 if (tmp_flag < 0) {
809 print_error("depth", "Unknown flag '%s'", optarg);
810 return 1;
811 }
812
813 opt.flag |= tmp_flag;
814 break;
815 case 1: // reject unless at least one set (0 means ignore option)
816 tmp_flag = bam_str2flag(optarg);
817
818 if (tmp_flag < 0) {
819 print_error("depth", "Unknown flag '%s'", optarg);
820 return 1;
821 }
822
823 opt.incl_flag |= tmp_flag;
824 break;
825 case 2: // reject unless all set
826 tmp_flag = bam_str2flag(optarg);
827
828 if (tmp_flag < 0) {
829 print_error("depth", "Unknown flag '%s'", optarg);
830 return 1;
831 }
832
833 opt.require_flag |= tmp_flag;
834 break;
835
836 case 'l':
837 opt.min_len = atoi(optarg);
838 break;
839
840 case 'H':
841 opt.header = 1;
842 break;
843
844 case 'q':
845 opt.min_qual = atoi(optarg);
846 break;
847 case 'Q':
848 opt.min_mqual = atoi(optarg);
849 break;
850
851 case 'J':
852 opt.skip_del = 0;
853 break;
854
855 case 'o':
856 if (opt.out != samtools_stdout)
857 break;
858 opt.out = fopen(out_file = optarg, "w");
859 if (!opt.out) {
860 print_error_errno("depth", "Cannot open \"%s\" for writing.",
861 optarg);
862 return EXIT_FAILURE;
863 }
864 break;
865
866 case 'r':
867 opt.reg = optarg;
868 break;
869
870 case 's':
871 opt.remove_overlaps = 1;
872 break;
873
874 case 'X':
875 has_index_file = 1;
876 break;
877
878 default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
879 /* else fall-through */
880 case '?':
881 usage_exit(samtools_stderr, EXIT_FAILURE);
882 }
883 }
884
885 if (argc < optind+1 && !file_list) {
886 if (argc == optind)
887 usage_exit(samtools_stdout, EXIT_SUCCESS);
888 else
889 usage_exit(samtools_stderr, EXIT_FAILURE);
890 }
891
892 if (file_list) {
893 if (has_index_file) {
894 print_error("depth", "The -f option cannot be combined with -X");
895 return 1;
896 }
897 if (read_file_list(file_list, &nfiles, &fn))
898 return 1;
899 argv = fn;
900 argc = nfiles;
901 optind = 0;
902 } else {
903 nfiles = argc - optind;
904 }
905
906 if (has_index_file) {
907 if (nfiles%1) {
908 print_error("depth", "-X needs one index specified per bam file");
909 return 1;
910 }
911 nfiles /= 2;
912 }
913 fp = malloc(nfiles * sizeof(*fp));
914 header = malloc(nfiles * sizeof(*header));
915 if (!fp || !header) {
916 print_error_errno("depth", "Out of memory");
917 return 1;
918 }
919
920 hts_itr_t **itr = NULL;
921 if (opt.reg) {
922 itr = calloc(nfiles, sizeof(*itr));
923 if (!itr)
924 return 1;
925 }
926
927 for (i = 0; i < nfiles; i++, optind++) {
928 fp[i] = sam_open_format(argv[optind], "r", &ga.in);
929 if (fp[i] == NULL) {
930 print_error_errno("depth",
931 "Cannot open input file \"%s\"", argv[optind]);
932 return 1;
933 }
934
935 if (ga.nthreads > 0)
936 hts_set_threads(fp[i], ga.nthreads);
937
938 if (hts_set_opt(fp[i], CRAM_OPT_REQUIRED_FIELDS,
939 SAM_FLAG | SAM_RNAME | SAM_POS | SAM_CIGAR
940 | (opt.remove_overlaps ? SAM_QNAME|SAM_RNEXT|SAM_PNEXT
941 : 0)
942 | (opt.min_mqual ? SAM_MAPQ : 0)
943 | (opt.min_len ? SAM_SEQ : 0)
944 | (opt.min_qual ? SAM_QUAL : 0))) {
945 fprintf(samtools_stderr, "Failed to set CRAM_OPT_REQUIRED_FIELDS value\n");
946 return 1;
947 }
948
949 if (hts_set_opt(fp[i], CRAM_OPT_DECODE_MD, 0)) {
950 fprintf(samtools_stderr, "Failed to set CRAM_OPT_DECODE_MD value\n");
951 return 1;
952 }
953
954 // FIXME: what if headers differ?
955 header[i] = sam_hdr_read(fp[i]);
956 if (header == NULL) {
957 fprintf(samtools_stderr, "Failed to read header for \"%s\"\n",
958 argv[optind]);
959 return 1;
960 }
961
962 if (opt.reg) {
963 hts_idx_t *idx = has_index_file
964 ? sam_index_load2(fp[i], argv[optind], argv[optind+nfiles])
965 : sam_index_load(fp[i], argv[optind]);
966 if (!idx) {
967 print_error("depth", "cannot load index for \"%s\"",
968 argv[optind]);
969 return 1;
970 }
971 if (!(itr[i] = sam_itr_querys(idx, header[i], opt.reg))) {
972 print_error("depth", "cannot parse region \"%s\"", opt.reg);
973 return 1;
974 }
975 hts_idx_destroy(idx);
976 }
977 }
978
979 int ret = fastdepth_core(&opt, nfiles, &argv[argc-nfiles], fp, itr, header)
980 ? 1 : 0;
981
982 for (i = 0; i < nfiles; i++) {
983 sam_hdr_destroy(header[i]);
984 sam_close(fp[i]);
985 if (itr && itr[i])
986 hts_itr_destroy(itr[i]);
987 }
988 free(header);
989 free(fp);
990 free(itr);
991 if (file_list) {
992 for (i=0; i<nfiles; i++)
993 free(fn[i]);
994 free(fn);
995 }
996 if (opt.bed)
997 bed_destroy(opt.bed);
998 sam_global_args_free(&ga);
999 if (opt.out != samtools_stdout) {
1000 if (fclose(opt.out) != 0 && ret == 0) {
1001 print_error_errno("depth", "error on closing \"%s\"", out_file);
1002 ret = 1;
1003 }
1004 }
1005
1006 return ret;
1007 }
1008
1009 #ifdef _MAIN_BAM2DEPTH
1010 int samtools_bam2depth_main(int argc, char *argv[])
1011 {
1012 return main_depth(argc, argv);
1013 }
1014 #endif