Debian Codegraph @

samtools/coverage.c.pysam.c

raw symbols SCIP
1 #include "samtools.pysam.h"
2
3 /* coverage.c -- samtools coverage subcommand
4
5 Copyright (C) 2018,2019 Florian Breitwieser
6 Portions copyright (C) 2019-2021, 2023-2024 Genome Research Ltd.
7
8 Author: Florian P Breitwieser <[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 /* This program calculates coverage from multiple BAMs
29 * simultaneously, to achieve random access and to use the BED interface.
30 * To compile this program separately, you may:
31 *
32 * gcc -g -O2 -Wall -o bamcov -D_MAIN_BAMCOV coverage.c -lhts -lz
33 */
34
35 // C headers
36 #include <config.h>
37
38 #include <ctype.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <stdarg.h> // variadic functions
42 #include <limits.h> // INT_MAX
43 #include <math.h> // round
44 #include <stdbool.h>
45 #include <string.h>
46 #include <unistd.h>
47 #include <assert.h>
48
49 #ifdef _WIN32
50 #include <windows.h>
51 #else
52 #include <sys/ioctl.h>
53 #endif
54
55 #include "htslib/sam.h"
56 #include "htslib/hts.h"
57 #include "samtools.h"
58 #include "sam_opts.h"
59
60 typedef struct { // auxiliary data structure to hold stats on coverage
61 unsigned long long n_covered_bases;
62 unsigned long long summed_coverage;
63 unsigned long long summed_baseQ;
64 unsigned long long summed_mapQ;
65 unsigned long long quality_bases;
66 unsigned int n_reads;
67 unsigned int n_selected_reads;
68 bool covered;
69 hts_pos_t beg;
70 hts_pos_t end;
71 int64_t bin_width;
72 } stats_aux_t;
73
74 typedef struct { // auxiliary data structure to hold a BAM file
75 samFile *fp; // file handle
76 sam_hdr_t *hdr; // file header
77 hts_itr_t *iter; // iterator to a region - NULL for us by default
78 int min_mapQ; // mapQ filter
79 int min_len; // length filter
80 int fail_flags;
81 int required_flags;
82 stats_aux_t *stats;
83 } bam_aux_t;
84
85 #if __STDC_VERSION__ >= 199901L
86 #define VERTICAL_LINE "\u2502" // BOX DRAWINGS LIGHT VERTICAL
87
88 // UTF8 specifies block characters in eights going from \u2581 (lower one eight block) to \u2588 (full block)
89 // https://en.wikipedia.org/wiki/Block_Elements
90 // LOWER ONE EIGHTH BLOCK … FULL BLOCK
91 static const char *const BLOCK_CHARS8[8] = {"\u2581", "\u2582", "\u2583", "\u2584", "\u2585", "\u2586", "\u2587", "\u2588"};
92 // In some terminals / with some fonts not all UTF8 block characters are supported (e.g. Putty). Use only half and full block for those
93 static const char *const BLOCK_CHARS2[2] = {".", ":"};
94
95 #else
96
97 // Fall back to explicit UTF-8 encodings of the same characters
98 #define VERTICAL_LINE "\xE2\x94\x82"
99
100 static const char *const BLOCK_CHARS8[8] = {
101 "\xE2\x96\x81", "\xE2\x96\x82", "\xE2\x96\x83", "\xE2\x96\x84",
102 "\xE2\x96\x85", "\xE2\x96\x86", "\xE2\x96\x87", "\xE2\x96\x88" };
103
104 static const char *const BLOCK_CHARS2[2] = {".", ":"};
105
106 #endif
107
108 // in bam_plcmd.c
109 int read_file_list(const char *file_list, int *n, char **argv[]);
110
111 static int usage(void) {
112 fprintf(samtools_stdout, "Usage: samtools coverage [options] in1.bam [in2.bam [...]]\n\n"
113 "Input options:\n"
114 " -b, --bam-list FILE list of input BAM filenames, one per line\n"
115 " -l, --min-read-len INT ignore reads shorter than INT bp [0]\n"
116 " -q, --min-MQ INT mapping quality threshold [0]\n"
117 " -Q, --min-BQ INT base quality threshold [0]\n"
118 " --rf <int|str> required flags: skip reads with mask bits unset []\n"
119 " --ff <int|str> filter flags: skip reads with mask bits set \n"
120 " [UNMAP,SECONDARY,QCFAIL,DUP]\n"
121 " -d, --depth INT maximum allowed coverage depth [1000000].\n"
122 " If 0, depth is set to the maximum integer value,\n"
123 " effectively removing any depth limit.\n"
124 "Output options:\n"
125 " -m, --histogram show histogram instead of tabular output\n"
126 " -D, --plot-depth plot depth instead of tabular output\n"
127 " -A, --ascii show only ASCII characters in histogram\n"
128 " -o, --output FILE write output to FILE [samtools_stdout]\n"
129 " -H, --no-header don't print a header in tabular mode\n"
130 " -w, --n-bins INT number of bins in histogram [terminal width - 40]\n"
131 " -r, --region REG show specified region. Format: chr:start-end. \n"
132 " -h, --help help (this page)\n");
133
134 fprintf(samtools_stdout, "\nGeneric options:\n");
135 sam_global_opt_help(samtools_stdout, "-.--.--.");
136
137 fprintf(samtools_stdout,
138 "\nSee manpage for additional details.\n"
139 " rname Reference name / chromosome\n"
140 " startpos Start position\n"
141 " endpos End position (or sequence length)\n"
142 " numreads Number reads aligned to the region (after filtering)\n"
143 " covbases Number of covered bases with depth >= 1\n"
144 " coverage Percentage of covered bases [0..100]\n"
145 " meandepth Mean depth of coverage\n"
146 " meanbaseq Mean baseQ in covered region\n"
147 " meanmapq Mean mapQ of selected reads\n"
148 );
149
150 return EXIT_SUCCESS;
151 }
152
153 static char* center_text(char *text, char *buf, int width) {
154 int len = strlen(text);
155 assert(len <= width);
156 int padding = (width - len) / 2;
157 int padding_ex = (width - len) % 2;
158 if (padding >= 1)
159 sprintf(buf, " %*s%*s", len+padding, text, padding-1+padding_ex, " ");
160 else
161 sprintf(buf, "%s", text);
162
163 return buf;
164 }
165
166 static char* readable_bps(double base_pairs, char *buf) {
167 const char* units[] = {"", "K", "M", "G", "T"};
168 int i = 0;
169 while (base_pairs >= 1000 && i < (sizeof(units)/sizeof(units[0]) - 1)) {
170 base_pairs /= 1000;
171 i++;
172 }
173 sprintf(buf, "%.*f%s", i, base_pairs, units[i]);
174 return buf;
175 }
176
177 // read one alignment from one BAM file
178 static int read_bam(void *data, bam1_t *b) {
179 bam_aux_t *aux = (bam_aux_t*)data; // data in fact is a pointer to an auxiliary structure
180 int nref = sam_hdr_nref(aux->hdr);
181 int ret;
182 while (1) {
183 if((ret = aux->iter? sam_itr_next(aux->fp, aux->iter, b) : sam_read1(aux->fp, aux->hdr, b)) < 0) break;
184 if (b->core.tid >= 0 && b->core.tid < nref)
185 aux->stats[b->core.tid].n_reads++;
186
187 if ( aux->fail_flags && (b->core.flag & aux->fail_flags) ) continue;
188 if ( aux->required_flags && !(b->core.flag & aux->required_flags) ) continue;
189 if ( b->core.qual < aux->min_mapQ ) continue;
190 if ( aux->min_len && bam_cigar2qlen(b->core.n_cigar, bam_get_cigar(b)) < aux->min_len ) continue;
191 if (b->core.tid >= 0 && b->core.tid < nref) {
192 aux->stats[b->core.tid].n_selected_reads++;
193 aux->stats[b->core.tid].summed_mapQ += b->core.qual;
194 }
195 break;
196 }
197 return ret;
198 }
199
200 void print_tabular_line(FILE *file_out, const sam_hdr_t *h, const stats_aux_t *stats, int tid) {
201 fputs(sam_hdr_tid2name(h, tid), file_out);
202 double region_len = (double) stats[tid].end - stats[tid].beg;
203 fprintf(file_out, "\t%"PRId64"\t%"PRId64"\t%u\t%llu\t%g\t%g\t%.3g\t%.3g\n",
204 stats[tid].beg+1,
205 stats[tid].end,
206 stats[tid].n_selected_reads,
207 stats[tid].n_covered_bases,
208 100.0 * stats[tid].n_covered_bases / region_len,
209 stats[tid].summed_coverage / region_len,
210 stats[tid].quality_bases > 0? stats[tid].summed_baseQ/(double) stats[tid].quality_bases : 0,
211 stats[tid].n_selected_reads > 0? stats[tid].summed_mapQ/(double) stats[tid].n_selected_reads : 0
212 );
213 }
214
215 void print_hist(FILE *file_out, const sam_hdr_t *h, const stats_aux_t *stats, int tid, const uint32_t *hist,
216 const int hist_size, const bool full_utf, const bool plot_coverage) {
217 int i, col;
218 bool show_percentiles = false;
219 const int n_rows = 10;
220 const char * const * BLOCK_CHARS = full_utf? BLOCK_CHARS8 : BLOCK_CHARS2;
221 const int blockchar_len = full_utf? 8 : 2;
222 double region_len = stats[tid].end - stats[tid].beg;
223
224 // Calculate histogram that contains percent covered
225 double hist_data[hist_size];
226 double max_val = 0.0;
227 for (i = 0; i < hist_size; ++i) {
228 hist_data[i] = (plot_coverage?1:100) * hist[i] / (double) stats[tid].bin_width;
229 if (hist_data[i] > max_val) max_val = hist_data[i];
230 }
231
232 char buf[30];
233 fprintf(file_out, "%s (%sbp)\n", sam_hdr_tid2name(h, tid), readable_bps(sam_hdr_tid2len(h, tid), buf));
234
235 double row_bin_size = max_val / (double) n_rows;
236 for (i = n_rows-1; i >= 0; --i) {
237 double current_bin = row_bin_size * i;
238 if (plot_coverage) {
239 fprintf(file_out, ">%8.1f ",i*row_bin_size);
240 } else if (show_percentiles) {
241 fprintf(file_out, ">%3i%% ", i*10);
242 } else {
243 fprintf(file_out, ">%7.2f%% ", current_bin);
244 }
245 fprintf(file_out, full_utf ? VERTICAL_LINE : "|");
246 for (col = 0; col < hist_size; ++col) {
247 // get the difference in eights, or halfs when full UTF8 is not supported
248 int cur_val_diff = round(blockchar_len * (hist_data[col] - current_bin) / row_bin_size) - 1;
249 if (cur_val_diff < 0) {
250 fputc(' ', file_out);
251 } else {
252 if (cur_val_diff >= blockchar_len)
253 cur_val_diff = blockchar_len - 1;
254
255 fprintf(file_out, "%s", BLOCK_CHARS[cur_val_diff]);
256 }
257 }
258 fprintf(file_out, full_utf ? VERTICAL_LINE : "|");
259 fputc(' ', file_out);
260 switch (i) {
261 case 9: fprintf(file_out, "Number of reads: %u", stats[tid].n_selected_reads); break;
262 case 8: if (stats[tid].n_reads - stats[tid].n_selected_reads > 0) fprintf(file_out, " (%i filtered)", stats[tid].n_reads - stats[tid].n_selected_reads); break;
263 case 7: fprintf(file_out, "Covered bases: %sbp", readable_bps(stats[tid].n_covered_bases, buf)); break;
264 case 6: fprintf(file_out, "Percent covered: %.4g%%",
265 100.0 * stats[tid].n_covered_bases / region_len); break;
266 case 5: fprintf(file_out, "Mean coverage: %.3gx",
267 stats[tid].summed_coverage / region_len); break;
268 case 4: fprintf(file_out, "Mean baseQ: %.3g",
269 stats[tid].quality_bases > 0? stats[tid].summed_baseQ/(double) stats[tid].quality_bases : 0); break;
270 case 3: fprintf(file_out, "Mean mapQ: %.3g",
271 stats[tid].summed_mapQ/(double) stats[tid].n_selected_reads); break;
272 case 1: fprintf(file_out, "Histo bin width: %sbp",
273 readable_bps(stats[tid].bin_width, buf)); break;
274 case 0: if (plot_coverage) {
275 fprintf(file_out, "Histo max cov: %.5g", max_val);
276 } else {
277 fprintf(file_out, "Histo max bin: %.5g%%", max_val);
278 }
279 break;
280
281 };
282 fputc('\n', file_out);
283 }
284
285 // print x axis. Could be made pretty for widths that are not divisible
286 // by 10 by variable spacing of the labels, instead of placing a label every 10 characters
287 char buf2[50];
288 fprintf(file_out, " %s", center_text(readable_bps(stats[tid].beg + 1, buf), buf2, 10));
289 int rest;
290 for (rest = 10; rest < 10*(hist_size/10); rest += 10) {
291 fprintf(file_out, "%s", center_text(readable_bps(stats[tid].beg + stats[tid].bin_width*rest, buf), buf2, 10));
292 }
293 int last_padding = hist_size%10;
294 fprintf(file_out, "%*s%s", last_padding, " ", center_text(readable_bps(stats[tid].end, buf), buf2, 10));
295 fprintf(file_out, "\n");
296 }
297
298 int main_coverage(int argc, char *argv[]) {
299 int status = EXIT_SUCCESS;
300
301 int ret, tid = -1, old_tid = -1, pos, i, j;
302
303 int max_depth = 1000000;
304 int opt_min_baseQ = 0;
305 int opt_min_mapQ = 0;
306 int opt_min_len = 0;
307 int opt_n_bins = 50;
308 bool opt_full_width = true;
309 char *opt_output_file = NULL;
310 bam_aux_t **data = NULL;
311 bam_mplp_t mplp = NULL;
312 const bam_pileup1_t **plp = NULL;
313 uint32_t *hist = NULL;
314 stats_aux_t *stats = NULL;
315 char *opt_reg = 0; // specified region
316 char *opt_file_list = NULL;
317 int n_bam_files = 0;
318 char **fn = NULL;
319 int fail_flags = (BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP); // Default fail flags
320 int required_flags = 0;
321 int print_value_warning = 0;
322
323 int *n_plp = NULL;
324 sam_hdr_t *h = NULL; // BAM header of the 1st input
325
326 bool opt_print_header = true;
327 bool opt_print_tabular = true;
328 bool opt_print_histogram = false;
329 bool opt_plot_coverage = false;
330 bool opt_full_utf = true;
331
332 FILE *file_out = samtools_stdout;
333
334 sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
335 static const struct option lopts[] = {
336 SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', 0, '-'),
337 {"rf", required_argument, NULL, 1}, // require flag
338 {"ff", required_argument, NULL, 2}, // filter flag
339 {"incl-flags", required_argument, NULL, 1}, // require flag
340 {"excl-flags", required_argument, NULL, 2}, // filter flag
341 {"bam-list", required_argument, NULL, 'b'},
342 {"min-read-len", required_argument, NULL, 'l'},
343 {"min-MQ", required_argument, NULL, 'q'},
344 {"min-mq", required_argument, NULL, 'q'},
345 {"min-BQ", required_argument, NULL, 'Q'},
346 {"min-bq", required_argument, NULL, 'Q'},
347 {"histogram", no_argument, NULL, 'm'},
348 {"ascii", no_argument, NULL, 'A'},
349 {"plot-depth", no_argument, NULL, 'D'},
350 {"output", required_argument, NULL, 'o'},
351 {"no-header", no_argument, NULL, 'H'},
352 {"n-bins", required_argument, NULL, 'w'},
353 {"region", required_argument, NULL, 'r'},
354 {"help", no_argument, NULL, 'h'},
355 {"depth", required_argument, NULL, 'd'},
356 { NULL, 0, NULL, 0 }
357 };
358
359 // parse the command line
360 int c;
361 opterr = 0;
362 while ((c = getopt_long(argc, argv, "Ao:l:q:Q:hHw:r:b:md:D", lopts, NULL)) != -1) {
363 switch (c) {
364 case 1:
365 if ((required_flags = bam_str2flag(optarg)) < 0) {
366 fprintf(samtools_stderr,"Could not parse --rf %s\n", optarg); return EXIT_FAILURE;
367 }; break;
368 case 2:
369 if ((fail_flags = bam_str2flag(optarg)) < 0) {
370 fprintf(samtools_stderr,"Could not parse --ff %s\n", optarg); return EXIT_FAILURE;
371 }; break;
372 case 'o': opt_output_file = optarg; opt_full_width = false; break;
373 case 'l': opt_min_len = atoi(optarg); break;
374 case 'q': opt_min_mapQ = atoi(optarg); break;
375 case 'Q': opt_min_baseQ = atoi(optarg); break;
376 case 'd': max_depth = atoi(optarg); break; // maximum coverage depth
377 case 'w': opt_n_bins = atoi(optarg); opt_full_width = false;
378 opt_print_histogram = true; opt_print_tabular = false;
379 break;
380 case 'r': opt_reg = optarg; break; // parsing a region requires a BAM header (strdup unnecessary)
381 case 'b': opt_file_list = optarg; break;
382 case 'm': opt_print_histogram = true; opt_print_tabular = false; break;
383 case 'A': opt_full_utf = false;
384 opt_print_histogram = true; opt_print_tabular = false;
385 break;
386 case 'D': opt_print_histogram = true;
387 opt_print_tabular = false;
388 opt_plot_coverage = true;
389 break;
390 case 'H': opt_print_header = false; break;
391 case 'h': return usage();
392 default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
393 /* else fall-through */
394 case '?':
395 if (optopt != '?') { // '-?' appeared on command line
396 if (optopt) { // Bad short option
397 print_error("coverage", "invalid option -- '%c'", optopt);
398 } else { // Bad long option
399 // Do our best. There is no good solution to finding
400 // out what the bad option was.
401 // See, e.g. https://stackoverflow.com/questions/2723888/where-does-getopt-long-store-an-unrecognized-option
402 if (optind > 0 && strncmp(argv[optind - 1], "--", 2) == 0) {
403 print_error("coverage", "unrecognised option '%s'",
404 argv[optind - 1]);
405 }
406 }
407 }
408 return usage();
409 }
410 }
411 if (optind == argc && !opt_file_list)
412 return usage();
413
414 // output file provided by user
415 if (opt_output_file != NULL && strcmp(opt_output_file,"-")!=0) {
416 file_out = fopen( opt_output_file, "w" );
417 if (file_out == NULL) {
418 print_error_errno("coverage", "Cannot open \"%s\" for writing.", opt_output_file);
419 return EXIT_FAILURE;
420 }
421 }
422
423 if (opt_n_bins <= 0 || opt_full_width) {
424 // get number of columns of terminal
425 const char* env_columns = getenv("COLUMNS");
426 int columns = 0;
427 if (env_columns == NULL) {
428 #ifdef _WIN32
429 CONSOLE_SCREEN_BUFFER_INFO csbi;
430 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) {
431 columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
432 }
433 #elif defined TIOCGWINSZ
434 struct winsize w;
435 if (ioctl(2, TIOCGWINSZ, &w) == 0)
436 columns = w.ws_col;
437 #endif
438 } else {
439 columns = atoi(env_columns); // atoi(NULL) returns 0
440 }
441
442 if (columns > 60) {
443 opt_n_bins = columns - 40;
444 } else {
445 opt_n_bins = 40;
446 }
447 }
448
449 // setvbuf(file_out, NULL, _IONBF, 0); //turn off buffering
450
451 // Open all BAM files
452 if (opt_file_list) {
453 // Read file names from opt_file_list into argv, and record the number of files in n_bam_files
454 if (read_file_list(opt_file_list, &n_bam_files, &fn)) {
455 print_error_errno("coverage", "Cannot open file list \"%s\".", opt_file_list);
456 return EXIT_FAILURE;
457 }
458 argv = fn;
459 optind = 0;
460 } else {
461 n_bam_files = argc - optind; // the number of BAMs on the command line
462 }
463
464 data = (bam_aux_t **)calloc(n_bam_files, sizeof(bam_aux_t*)); // data[i] for the i-th BAM file
465 if (!data) {
466 print_error_errno("coverage", "Failed to allocate memory");
467 status = EXIT_FAILURE;
468 goto coverage_end;
469 }
470
471 for (i = 0; i < n_bam_files; ++i) {
472 int rf;
473 data[i] = (bam_aux_t *) calloc(1, sizeof(bam_aux_t));
474 if (!data[i]) {
475 print_error_errno("coverage", "Failed to allocate memory");
476 status = EXIT_FAILURE;
477 goto coverage_end;
478 }
479 data[i]->fp = sam_open_format(argv[optind+i], "r", &ga.in); // open BAM
480
481 if (data[i]->fp == NULL) {
482 print_error_errno("coverage", "Could not open \"%s\"", argv[optind+i]);
483 status = EXIT_FAILURE;
484 goto coverage_end;
485 }
486 rf = SAM_FLAG | SAM_RNAME | SAM_POS | SAM_MAPQ | SAM_CIGAR | SAM_SEQ;
487 if (opt_min_baseQ) rf |= SAM_QUAL;
488
489 // Set CRAM options on file handle - returns 0 on success
490 if (hts_set_opt(data[i]->fp, CRAM_OPT_REQUIRED_FIELDS, rf)) {
491 print_error("coverage", "Failed to set CRAM_OPT_REQUIRED_FIELDS value");
492 status = EXIT_FAILURE;
493 goto coverage_end;
494 }
495 if (hts_set_opt(data[i]->fp, CRAM_OPT_DECODE_MD, 0)) {
496 print_error("coverage", "Failed to set CRAM_OPT_DECODE_MD value");
497 status = EXIT_FAILURE;
498 goto coverage_end;
499 }
500 data[i]->min_mapQ = opt_min_mapQ; // set the mapQ filter
501 data[i]->min_len = opt_min_len; // set the qlen filter
502 data[i]->hdr = sam_hdr_read(data[i]->fp); // read the BAM header
503 data[i]->fail_flags = fail_flags;
504 data[i]->required_flags = required_flags;
505 if (data[i]->hdr == NULL) {
506 print_error_errno("coverage", "Could not read header for \"%s\"", argv[optind+i]);
507 status = EXIT_FAILURE;
508 goto coverage_end;
509 }
510
511 // Lookup region if specified
512 if (opt_reg) { // if a region is specified
513 hts_idx_t *idx = sam_index_load(data[i]->fp, argv[optind+i]); // load the index
514 if (idx == NULL) {
515 print_error_errno("coverage", "Failed to load index for \"%s\"", argv[optind+i]);
516 status = EXIT_FAILURE;
517 goto coverage_end;
518 }
519 data[i]->iter = sam_itr_querys(idx, data[i]->hdr, opt_reg); // set the iterator
520 hts_idx_destroy(idx); // the index is not needed any more; free the memory
521 if (data[i]->iter == NULL) {
522 print_error("coverage", "Failed to parse region \"%s\". Check the region format or region name presence in the file \"%s\"", opt_reg, argv[optind+i]);
523 status = EXIT_FAILURE;
524 goto coverage_end;
525 }
526 }
527 }
528
529 if (opt_print_tabular && opt_print_header)
530 fputs("#rname\tstartpos\tendpos\tnumreads\tcovbases\tcoverage\tmeandepth\tmeanbaseq\tmeanmapq\n", file_out);
531
532 h = data[0]->hdr; // easy access to the header of the 1st BAM
533 int n_targets = sam_hdr_nref(h);
534 stats = calloc(n_targets, sizeof(stats_aux_t));
535 if (!stats) {
536 print_error_errno("coverage", "Failed to allocate memory");
537 status = EXIT_FAILURE;
538 goto coverage_end;
539 }
540
541 int64_t n_bins = opt_n_bins;
542 if (opt_reg) {
543 stats_aux_t *s = stats + data[0]->iter->tid;
544 s->beg = data[0]->iter->beg; // and to the parsed region coordinates
545 s->end = data[0]->iter->end;
546 if (s->end == HTS_POS_MAX) {
547 s->end = sam_hdr_tid2len(h, data[0]->iter->tid);
548 }
549 if (opt_n_bins > s->end - s->beg) {
550 n_bins = s->end - s->beg;
551 }
552 s->bin_width = (s->end-s->beg) / (n_bins > 0 ? n_bins : 1);
553 }
554
555 for (i=0; i<n_bam_files; i++)
556 data[i]->stats = stats;
557
558 int64_t current_bin = 0;
559
560 // the core multi-pileup loop
561 mplp = bam_mplp_init(n_bam_files, read_bam, (void**)data); // initialization
562 if (max_depth > 0)
563 bam_mplp_set_maxcnt(mplp, max_depth); // set maximum coverage depth
564 else if (!max_depth)
565 bam_mplp_set_maxcnt(mplp, INT_MAX);
566
567
568 // Extra info for histogram and coverage counting
569 hist = (uint32_t*) calloc(opt_n_bins, sizeof(uint32_t));
570 n_plp = (int*) calloc(n_bam_files, sizeof(int*)); // n_plp[i] is the number of covering reads from the i-th BAM
571 plp = (const bam_pileup1_t**) calloc(n_bam_files, sizeof(bam_pileup1_t*)); // plp[i] points to the array of covering reads (internal in mplp)
572 if (!hist || !n_plp || !plp) {
573 print_error_errno("coverage", "Failed to allocate memory");
574 status = EXIT_FAILURE;
575 goto coverage_end;
576 }
577
578 while ((ret=bam_mplp_auto(mplp, &tid, &pos, n_plp, plp)) > 0) { // come to the next covered position
579
580 if (tid != old_tid) { // Next target sequence
581 if (old_tid >= 0) {
582 if (opt_print_histogram) {
583 print_hist(file_out, h, stats, old_tid, hist, n_bins, opt_full_utf, opt_plot_coverage);
584 fputc('\n', file_out);
585 } else if (opt_print_tabular) {
586 print_tabular_line(file_out, h, stats, old_tid);
587 }
588
589 if (opt_print_histogram)
590 memset(hist, 0, n_bins*sizeof(uint32_t));
591 }
592
593 stats[tid].covered = true;
594 if (!opt_reg)
595 stats[tid].end = sam_hdr_tid2len(h, tid);
596
597 if (opt_print_histogram) {
598 n_bins = opt_n_bins > stats[tid].end-stats[tid].beg? stats[tid].end-stats[tid].beg : opt_n_bins;
599 stats[tid].bin_width = (stats[tid].end-stats[tid].beg) / n_bins;
600 }
601
602 old_tid = tid;
603 }
604 if (pos < stats[tid].beg || pos >= stats[tid].end) continue; // out of range; skip
605 if (tid >= n_targets) continue; // diff number of @SQ lines per file?
606
607 if (opt_print_histogram) {
608 current_bin = (pos - stats[tid].beg) / stats[tid].bin_width;
609 }
610
611 bool count_base = false;
612 for (i = 0; i < n_bam_files; ++i) { // base level filters have to go here
613 int depth_at_pos = n_plp[i];
614 for (j = 0; j < n_plp[i]; ++j) {
615 const bam_pileup1_t *p = plp[i] + j; // DON'T modify plp[][] unless you really know
616
617 if (p->is_del || p->is_refskip) {
618 --depth_at_pos; // having dels or refskips at tid:pos
619 } else if (p->qpos < p->b->core.l_qseq) {
620 if (bam_get_qual(p->b)[p->qpos] < opt_min_baseQ) {
621 --depth_at_pos; // low base quality
622 } else {
623 stats[tid].summed_baseQ += bam_get_qual(p->b)[p->qpos];
624 stats[tid].quality_bases++;
625 }
626 } else {
627 print_value_warning = 1; // no quality at position
628 }
629 }
630
631 if (depth_at_pos > 0) {
632 count_base = true;
633 stats[tid].summed_coverage += depth_at_pos;
634 }
635
636 if(current_bin < n_bins && opt_plot_coverage) {
637 hist[current_bin] += depth_at_pos;
638 }
639 }
640 if (count_base) {
641 stats[tid].n_covered_bases++;
642 if (opt_print_histogram && current_bin < n_bins && !opt_plot_coverage)
643 ++(hist[current_bin]); // Histogram based on breadth of coverage
644 }
645 }
646
647 if (tid == -1 && opt_reg && *opt_reg != '*')
648 // Region specified but no data covering it.
649 tid = data[0]->iter->tid;
650
651 if (tid < n_targets && tid >=0) {
652 if (opt_print_histogram) {
653 print_hist(file_out, h, stats, tid, hist, n_bins, opt_full_utf, opt_plot_coverage);
654 } else if (opt_print_tabular) {
655 print_tabular_line(file_out, h, stats, tid);
656 }
657 }
658
659
660 if (!opt_reg && opt_print_tabular) {
661 for (i = 0; i < n_targets; ++i) {
662 if (!stats[i].covered) {
663 stats[i].end = sam_hdr_tid2len(h, i);
664 print_tabular_line(file_out, h, stats, i);
665 }
666 }
667 }
668
669 if (print_value_warning) {
670 print_error("coverage", "Warning: Missing quality values in alignments. Mean base quality calculated only on available values.");
671 }
672
673 if (ret < 0) status = EXIT_FAILURE;
674
675 coverage_end:
676 if (n_plp) free(n_plp);
677 if (plp) free(plp);
678 if (mplp) bam_mplp_destroy(mplp);
679
680 if (hist) free(hist);
681 if (stats) free(stats);
682
683 // Close files and free data structures
684 if (!(file_out == samtools_stdout || fclose(file_out) == 0)) {
685 if (status == EXIT_SUCCESS) {
686 print_error_errno("coverage", "error on closing \"%s\"",
687 (opt_output_file && strcmp(opt_output_file, "-") != 0?
688 opt_output_file : "samtools_stdout"));
689 status = EXIT_FAILURE;
690 }
691 }
692
693 if (data) {
694 for (i = 0; i < n_bam_files && data[i]; ++i) {
695 sam_hdr_destroy(data[i]->hdr);
696 if (data[i]->fp) sam_close(data[i]->fp);
697 hts_itr_destroy(data[i]->iter);
698 free(data[i]);
699 }
700 free(data);
701 }
702
703 if (opt_file_list && fn) {
704 for (i = 0; i < n_bam_files; ++i)
705 free(fn[i]);
706 free(fn);
707 }
708 sam_global_args_free(&ga);
709
710 return status;
711 }
712
713 #ifdef _MAIN_BAMCOV
714 int samtools_coverage_main(int argc, char *argv[]) {
715 return main_coverage(argc, argv);
716 }
717 #endif