Debian Codegraph @

samtools/bedcov.c

raw symbols SCIP
1 /* bedcov.c -- bedcov subcommand.
2
3 Copyright (C) 2012 Broad Institute.
4 Copyright (C) 2013-2014, 2018-2022, 2024 Genome Research Ltd.
5
6 Author: Heng Li <[email protected]>
7
8 Permission is hereby granted, free of charge, to any person obtaining a copy
9 of this software and associated documentation files (the "Software"), to deal
10 in the Software without restriction, including without limitation the rights
11 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 copies of the Software, and to permit persons to whom the Software is
13 furnished to do so, subject to the following conditions:
14
15 The above copyright notice and this permission notice shall be included in
16 all copies or substantial portions of the Software.
17
18 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 DEALINGS IN THE SOFTWARE. */
25
26 #include <config.h>
27
28 #include <zlib.h>
29 #include <stdio.h>
30 #include <ctype.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <unistd.h>
34 #include "htslib/kstring.h"
35 #include "htslib/sam.h"
36 #include "htslib/thread_pool.h"
37 #include "samtools.h"
38 #include "sam_opts.h"
39
40 #include "htslib/kseq.h"
41 KSTREAM_INIT(gzFile, gzread, 16384)
42
43 #define DEFAULT_DEPTH INT_MAX
44
45 typedef struct {
46 htsFile *fp;
47 sam_hdr_t *header;
48 hts_itr_t *iter;
49 int min_mapQ;
50 uint32_t flags; // read filtering flags
51 int64_t rcnt;
52 } aux_t;
53
54 static int read_bam(void *data, bam1_t *b)
55 {
56 aux_t *aux = (aux_t*)data; // data in fact is a pointer to an auxiliary structure
57 int ret;
58 while (1)
59 {
60 ret = aux->iter? sam_itr_next(aux->fp, aux->iter, b) : sam_read1(aux->fp, aux->header, b);
61 if ( ret<0 ) break;
62 if ( b->core.flag & aux->flags ) continue;
63 if ( (int)b->core.qual < aux->min_mapQ ) continue;
64 break;
65 }
66 return ret;
67 }
68
69 static int incr_rcnt(void *data, const bam1_t *b, bam_pileup_cd *cd) {
70 aux_t *aux = (aux_t *)data;
71 aux->rcnt++;
72 return 0;
73 }
74
75 int main_bedcov(int argc, char *argv[])
76 {
77 gzFile fp;
78 kstring_t str;
79 kstream_t *ks;
80 hts_idx_t **idx;
81 aux_t **aux;
82 int *n_plp, dret, i, j, m, n, c, ret, status = 0, min_mapQ = 0;
83 int skip_DN = 0, do_rcount = 0;
84 int64_t *cnt, *pcov = NULL;
85 const bam_pileup1_t **plp;
86 int usage = 0, has_index_file = 0;
87 uint32_t flags = (BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP);
88 int tflags = 0, min_depth = -1, max_depth = DEFAULT_DEPTH, print_header=0;
89
90 sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
91 static const struct option lopts[] = {
92 {"min-MQ", required_argument, NULL, 'Q'},
93 {"min-mq", required_argument, NULL, 'Q'},
94 {"max-depth", required_argument, NULL, 'd'+1000},
95 SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', 0, '-'),
96 { NULL, 0, NULL, 0 }
97 };
98
99 while ((c = getopt_long(argc, argv, "Q:Xg:G:jd:Hc", lopts, NULL)) >= 0) {
100 switch (c) {
101 case 'Q': min_mapQ = atoi(optarg); break;
102 case 'X': has_index_file = 1; break;
103 case 'c': do_rcount = 1; break;
104 case 'H': print_header = 1; break;
105 case 'g':
106 tflags = bam_str2flag(optarg);
107 if (tflags < 0 || tflags > ((BAM_FSUPPLEMENTARY << 1) - 1)) {
108 print_error("bedcov", "Flag value \"%s\" is not supported", optarg);
109 return 1;
110 }
111 flags &= ~tflags;
112 break;
113 case 'G':
114 tflags = bam_str2flag(optarg);
115 if (tflags < 0 || tflags > ((BAM_FSUPPLEMENTARY << 1) - 1)) {
116 print_error("bedcov", "Flag value \"%s\" is not supported", optarg);
117 return 1;
118 }
119 flags |= tflags;
120 break;
121 case 'j': skip_DN = 1; break;
122 case 'd': min_depth = atoi(optarg); break;
123 case 'd'+1000: max_depth = atoi(optarg); break;
124 default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
125 /* else fall-through */
126 case '?': usage = 1; break;
127 }
128 if (usage) break;
129 }
130 if (usage || optind + 2 > argc) {
131 fprintf(stderr, "Usage: samtools bedcov [options] <in.bed> <in1.bam> [...]\n\n");
132 fprintf(stderr, "Options:\n");
133 fprintf(stderr, " -Q, --min-MQ <int> mapping quality threshold [0]\n");
134 fprintf(stderr, " -X use customized index files\n");
135 fprintf(stderr, " -g <flags> remove the specified flags from the set used to filter out reads\n");
136 fprintf(stderr, " -G <flags> add the specified flags to the set used to filter out reads\n"
137 " The default set is UNMAP,SECONDARY,QCFAIL,DUP or 0x704\n");
138 fprintf(stderr, " -j do not include deletions (D) and ref skips (N) in bedcov computation\n");
139 fprintf(stderr, " --max-depth <int> sets the maximum depth used in the mpileup algorithm\n");
140 fprintf(stderr, " -d <int> depth threshold. Number of reference bases with coverage above and\n"
141 " including this value will be displayed in a separate column\n");
142 fprintf(stderr, " -c add an additional column showing read count\n");
143 fprintf(stderr, " -H print a comment/header line with column information.\n");
144 sam_global_opt_help(stderr, "-.--.--.");
145 return 1;
146 }
147 if (has_index_file) {
148 if ((argc - optind - 1) % 2 != 0) { // Calculate # of input BAM files
149 fprintf(stderr, "ERROR: odd number of filenames detected! Each BAM file should have an index file\n");
150 return 1;
151 }
152 n = (argc - optind - 1) / 2;
153 } else {
154 n = argc - optind - 1;
155 }
156
157 memset(&str, 0, sizeof(kstring_t));
158 aux = calloc(n, sizeof(aux_t*));
159 idx = calloc(n, sizeof(hts_idx_t*));
160 for (i = 0; i < n; ++i) {
161 aux[i] = calloc(1, sizeof(aux_t));
162 aux[i]->min_mapQ = min_mapQ;
163 aux[i]->fp = sam_open_format(argv[i+optind+1], "r", &ga.in);
164 if (aux[i]->fp) {
165 // If index filename has not been specfied, look in BAM folder
166 if (has_index_file) {
167 idx[i] = sam_index_load2(aux[i]->fp, argv[i+optind+1], argv[i+optind+n+1]);
168 } else {
169 idx[i] = sam_index_load(aux[i]->fp, argv[i+optind+1]);
170 }
171 }
172 if (aux[i]->fp == 0 || idx[i] == 0) {
173 fprintf(stderr, "ERROR: fail to open index BAM file '%s'\n", argv[i+optind+1]);
174 return 2;
175 }
176 // TODO bgzf_set_cache_size(aux[i]->fp, 20);
177 aux[i]->header = sam_hdr_read(aux[i]->fp);
178 if (aux[i]->header == NULL) {
179 fprintf(stderr, "ERROR: failed to read header for '%s'\n",
180 argv[i+optind+1]);
181 return 2;
182 }
183 aux[i]->flags = flags;
184 }
185 cnt = calloc(n, sizeof(*cnt));
186
187 if (min_depth >= 0) pcov = calloc(n, sizeof(*pcov));
188 if (!cnt || (min_depth >= 0 && !pcov)) {
189 print_error_errno("bedcov", "failed to allocate memory");
190 return 2;
191 }
192
193 fp = gzopen(argv[optind], "rb");
194 if (fp == NULL) {
195 print_error_errno("bedcov", "can't open BED file '%s'", argv[optind]);
196 return 2;
197 }
198
199 if (print_header) {
200 printf("#chrom\tstart\tend");
201 for (i = 0; i < n; ++i) {
202 printf("\t%s_cov", argv[i+optind+1]);
203 }
204 if (min_depth >= 0) {
205 for (i = 0; i < n; ++i)
206 printf("\t%s_depth", argv[i+optind+1]);
207 }
208 if (do_rcount) {
209 for (i = 0; i < n; ++i)
210 printf("\t%s_count", argv[i+optind+1]);
211 }
212 putchar('\n');
213 }
214
215 ks = ks_init(fp);
216 n_plp = calloc(n, sizeof(int));
217 plp = calloc(n, sizeof(bam_pileup1_t*));
218 while (ks_getuntil(ks, KS_SEP_LINE, &str, &dret) >= 0) {
219 char *p, *q;
220 int tid, pos, num = 0;
221 int64_t beg = 0, end = 0;
222 bam_mplp_t mplp;
223
224 if (str.l == 0 || *str.s == '#') continue; /* empty or comment line */
225 /* Track and browser lines. Also look for a trailing *space* in
226 case someone has badly-chosen a chromosome name (it would
227 be followed by a tab in that case). */
228 if (strncmp(str.s, "track ", 6) == 0) continue;
229 if (strncmp(str.s, "browser ", 8) == 0) continue;
230 for (p = q = str.s; *p && !isspace(*p); ++p);
231 if (*p == 0) goto bed_error;
232 char c = *p;
233 *p = 0; tid = bam_name2id(aux[0]->header, q); *p = c;
234 if (tid < 0) goto bed_error;
235 num = sscanf(p + 1, "%"SCNd64" %"SCNd64, &beg, &end);
236 if (num < 2 || end < beg) goto bed_error;
237
238 for (i = 0; i < n; ++i) {
239 if (aux[i]->iter) hts_itr_destroy(aux[i]->iter);
240 aux[i]->iter = sam_itr_queryi(idx[i], tid, beg, end);
241 aux[i]->rcnt = 0;
242 }
243
244 mplp = bam_mplp_init(n, read_bam, (void**)aux);
245 if (min_depth > max_depth)
246 // NB: never happens given current DEFAULT_DEPTH of INT_MAX
247 bam_mplp_set_maxcnt(mplp, min_depth);
248 else
249 bam_mplp_set_maxcnt(mplp, max_depth);
250
251 memset(cnt, 0, sizeof(*cnt) * n);
252 if (min_depth >= 0) memset(pcov, 0, sizeof(*pcov) * n);
253
254 if (do_rcount)
255 bam_mplp_constructor(mplp, incr_rcnt);
256
257 while ((ret = bam_mplp_auto(mplp, &tid, &pos, n_plp, plp)) > 0)
258 if (pos >= beg && pos < end) {
259 for (i = 0; i < n; ++i) {
260 m = 0;
261 if (skip_DN || min_depth >= 0) {
262 for (j = 0; j < n_plp[i]; ++j) {
263 const bam_pileup1_t *pi = plp[i] + j;
264 if (pi->is_del || pi->is_refskip) ++m;
265 }
266 }
267 int pd = n_plp[i] - m;
268 cnt[i] += pd;
269 if (min_depth >= 0 && pd >= min_depth) pcov[i]++;
270 }
271 }
272
273 if (ret < 0) {
274 print_error("bedcov", "error reading from input file");
275 status = 2;
276 bam_mplp_destroy(mplp);
277 break;
278 }
279
280 for (i = 0; i < n; ++i) {
281 kputc('\t', &str);
282 kputl(cnt[i], &str);
283 }
284 if (min_depth >= 0) {
285 for (i = 0; i < n; ++i) {
286 kputc('\t', &str);
287 kputl(pcov[i], &str);
288 }
289 }
290 if (do_rcount) {
291 for (i = 0; i < n; ++i) {
292 kputc('\t', &str);
293 kputl(aux[i]->rcnt, &str);
294 }
295 }
296 puts(str.s);
297 bam_mplp_destroy(mplp);
298 continue;
299
300 bed_error:
301 fprintf(stderr, "Errors in BED line '%s'\n", str.s);
302 status = 2;
303 }
304 free(n_plp); free(plp);
305 ks_destroy(ks);
306 gzclose(fp);
307
308 free(cnt);
309 free(pcov);
310 for (i = 0; i < n; ++i) {
311 if (aux[i]->iter) hts_itr_destroy(aux[i]->iter);
312 hts_idx_destroy(idx[i]);
313 sam_hdr_destroy(aux[i]->header);
314 sam_close(aux[i]->fp);
315 free(aux[i]);
316 }
317 free(aux); free(idx);
318 free(str.s);
319 sam_global_args_free(&ga);
320 return status;
321 }