Debian Codegraph @

samtools/bedcov.c.pysam.c

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