Debian Codegraph @

bcftools/vcfquery.c.pysam.c

raw symbols SCIP
1 #include "bcftools.pysam.h"
2
3 /* vcfquery.c -- Extracts fields from VCF/BCF file.
4
5 Copyright (C) 2013-2023 Genome Research Ltd.
6
7 Author: Petr Danecek <[email protected]>
8
9 Permission is hereby granted, free of charge, to any person obtaining a copy
10 of this software and associated documentation files (the "Software"), to deal
11 in the Software without restriction, including without limitation the rights
12 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 copies of the Software, and to permit persons to whom the Software is
14 furnished to do so, subject to the following conditions:
15
16 The above copyright notice and this permission notice shall be included in
17 all copies or substantial portions of the Software.
18
19 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 THE SOFTWARE. */
26
27 #include <stdio.h>
28 #include <unistd.h>
29 #include <getopt.h>
30 #include <ctype.h>
31 #include <string.h>
32 #include <errno.h>
33 #include <sys/stat.h>
34 #include <sys/types.h>
35 #include <htslib/vcf.h>
36 #include <htslib/synced_bcf_reader.h>
37 #include <htslib/khash_str2int.h>
38 #include <htslib/vcfutils.h>
39 #include "bcftools.h"
40 #include "filter.h"
41 #include "convert.h"
42 #include "smpl_ilist.h"
43
44
45 // Logic of the filters: include or exclude sites which match the filters?
46 #define FLT_INCLUDE 1
47 #define FLT_EXCLUDE 2
48
49 typedef struct
50 {
51 filter_t *filter;
52 char *filter_str;
53 int filter_logic; // include or exclude sites which match the filters? One of FLT_INCLUDE/FLT_EXCLUDE
54 uint8_t *smpl_pass;
55 convert_t *convert;
56 bcf_srs_t *files;
57 bcf_hdr_t *header;
58 int sample_is_file;
59 char **argv, *format_str, *sample_list, *targets_list, *regions_list, *vcf_list, *fn_out;
60 char *print_filtered;
61 int argc, list_columns, print_header, allow_undef_tags, force_samples, force_newline;
62 FILE *out;
63 }
64 args_t;
65
66 static void destroy_list(char **list, int n)
67 {
68 int i;
69 for (i=0; i<n; i++)
70 free(list[i]);
71 free(list);
72 }
73
74 static void init_data(args_t *args)
75 {
76 args->header = args->files->readers[0].header;
77
78 int i, nsamples = 0, *samples = NULL;
79 if ( args->sample_list && strcmp("-",args->sample_list) )
80 {
81 for (i=0; i<args->files->nreaders; i++)
82 {
83 // This tells htslib to subset samples directly when reading. Also the header is modified to
84 // include only the requested samples
85 int ret = bcf_hdr_set_samples(args->files->readers[i].header,args->sample_list,args->sample_is_file);
86 if ( ret<0 ) error("Error parsing the sample list\n");
87 else if ( ret>0 && !args->force_samples )
88 error("Error: sample #%d not found in the header, user --force-samples to proceed anyway\n", ret);
89 }
90
91 int flags = SMPL_REORDER;
92 smpl_ilist_t *ilist = smpl_ilist_init(args->files->readers[0].header, args->sample_list, args->sample_is_file, flags);
93 nsamples = ilist->n;
94 samples = (int*) malloc(sizeof(int)*nsamples);
95 for (i=0; i<ilist->n; i++)
96 samples[i] = ilist->idx[i];
97 smpl_ilist_destroy(ilist);
98 }
99 args->convert = convert_init(args->header, samples, nsamples, args->format_str);
100 if ( args->force_newline ) convert_set_option(args->convert, force_newline, 1);
101 convert_set_option(args->convert, subset_samples, &args->smpl_pass);
102 if ( args->allow_undef_tags ) convert_set_option(args->convert, allow_undef_tags, 1);
103 if ( args->print_header>1 ) convert_set_option(args->convert, no_hdr_indices, 1);
104 free(samples);
105
106 int max_unpack = convert_max_unpack(args->convert);
107 if ( args->filter_str )
108 {
109 args->filter = filter_init(args->header, args->filter_str);
110 max_unpack |= filter_max_unpack(args->filter);
111 }
112 args->files->max_unpack = max_unpack;
113 if ( !args->filter || args->print_filtered || !(filter_max_unpack(args->filter) & BCF_UN_FMT) )
114 convert_set_option(args->convert, header_samples, 1);
115 if ( args->print_filtered ) convert_set_option(args->convert, print_filtered, args->print_filtered);
116 }
117
118 static void destroy_data(args_t *args)
119 {
120 convert_destroy(args->convert);
121 if ( args->filter )
122 filter_destroy(args->filter);
123 }
124
125 static void query_vcf(args_t *args)
126 {
127 kstring_t str = {0,0,0};
128
129 if ( args->print_header )
130 {
131 convert_header(args->convert,&str);
132 if ( fwrite(str.s, str.l, 1, args->out)!=1 ) error("[%s] Error: cannot write to %s\n", __func__,args->fn_out?args->fn_out:"standard output");
133 }
134
135 int i,max_convert_unpack = convert_max_unpack(args->convert);
136 int max_filter_unpack = args->filter ? filter_max_unpack(args->filter) : 0;
137 while ( bcf_sr_next_line(args->files) )
138 {
139 if ( !bcf_sr_has_line(args->files,0) ) continue;
140 bcf1_t *line = args->files->readers[0].buffer[0];
141 bcf_unpack(line, args->files->max_unpack);
142
143 if ( args->filter )
144 {
145 int pass = filter_test(args->filter, line, (const uint8_t**) &args->smpl_pass);
146 if ( args->filter_logic & FLT_EXCLUDE )
147 {
148 // This code addresses this problem:
149 // -i can include a site but exclude a sample
150 // -e exclude a site but include a sample
151
152 if ( pass )
153 {
154 if ( !args->smpl_pass ) continue;
155 if ( !(max_convert_unpack & BCF_UN_FMT) && !(max_filter_unpack & BCF_UN_FMT) ) continue;
156
157 pass = 0;
158 for (i=0; i<line->n_sample; i++)
159 {
160 if ( args->smpl_pass[i] ) args->smpl_pass[i] = 0;
161 else { args->smpl_pass[i] = 1; pass = 1; }
162 }
163 if ( !pass ) continue;
164 }
165 else if ( args->smpl_pass )
166 for (i=0; i<line->n_sample; i++) args->smpl_pass[i] = 1;
167 }
168 else if ( !pass ) continue;
169 }
170
171 str.l = 0;
172 convert_line(args->convert, line, &str);
173 if ( str.l && fwrite(str.s, str.l, 1, args->out)!=1 ) error("[%s] Error: cannot write to %s\n", __func__,args->fn_out?args->fn_out:"standard output");
174 }
175 if ( str.m ) free(str.s);
176 }
177
178 static void list_columns(args_t *args)
179 {
180 int negate = 0;
181 int i;
182 bcf_sr_t *reader = &args->files->readers[0];
183 void *has_sample = NULL;
184 if ( args->sample_list )
185 {
186 if ( args->sample_list[0]=='^' ) negate = 1;
187 has_sample = khash_str2int_init();
188 int i, nsmpl;
189 char **smpl = hts_readlist(negate ? args->sample_list+1 : args->sample_list, args->sample_is_file, &nsmpl);
190 if ( !smpl ) error("Error: failed to read %s\n", negate ? args->sample_list+1 : args->sample_list);
191 for (i=0; i<nsmpl; i++)
192 {
193 if ( bcf_hdr_id2int(reader->header,BCF_DT_SAMPLE,smpl[i])<0 && !args->force_samples )
194 error("Error: sample #%d not found in the header, user --force-samples to proceed anyway\n", i+1);
195 khash_str2int_inc(has_sample, smpl[i]);
196 }
197 free(smpl);
198 }
199
200 for (i=0; i<bcf_hdr_nsamples(reader->header); i++)
201 {
202 int skip = 0;
203 if ( negate )
204 {
205 if ( khash_str2int_has_key(has_sample, reader->header->samples[i]) ) skip = 1;
206 }
207 else if ( has_sample && !khash_str2int_has_key(has_sample, reader->header->samples[i]) ) skip = 1;
208 if ( skip ) continue;
209 fprintf(bcftools_stdout, "%s\n", reader->header->samples[i]);
210 }
211
212 if ( has_sample )
213 khash_str2int_destroy_free(has_sample);
214 }
215
216 static char **copy_header(bcf_hdr_t *hdr, char **src, int nsrc)
217 {
218 char **dst = (char**) malloc(sizeof(char*)*nsrc);
219 int i;
220 for (i=0; i<nsrc; i++) dst[i] = strdup(src[i]);
221 return dst;
222 }
223 static int compare_header(bcf_hdr_t *hdr, char **a, int na, char **b, int nb)
224 {
225 if ( na!=nb ) return na-nb;
226 int i;
227 for (i=0; i<na; i++)
228 if ( strcmp(a[i],b[i]) ) return 1;
229 return 0;
230 }
231
232
233 static void usage(void)
234 {
235 fprintf(bcftools_stderr, "\n");
236 fprintf(bcftools_stderr, "About: Extracts fields from VCF/BCF file and prints them in user-defined format\n");
237 fprintf(bcftools_stderr, "Usage: bcftools query [options] <A.vcf.gz> [<B.vcf.gz> [...]]\n");
238 fprintf(bcftools_stderr, "\n");
239 fprintf(bcftools_stderr, "Options:\n");
240 fprintf(bcftools_stderr, " -e, --exclude EXPR Exclude sites for which the expression is true (see man page for details)\n");
241 fprintf(bcftools_stderr, " --force-samples Only warn about unknown subset samples\n");
242 fprintf(bcftools_stderr, " -F, --print-filtered STR Output STR for samples failing the -i/-e filtering expression\n");
243 fprintf(bcftools_stderr, " -f, --format STRING See man page for details\n");
244 fprintf(bcftools_stderr, " -H, --print-header Print header, -HH to omit column indices\n");
245 fprintf(bcftools_stderr, " -i, --include EXPR Select sites for which the expression is true (see man page for details)\n");
246 fprintf(bcftools_stderr, " -l, --list-samples Print the list of samples and exit\n");
247 fprintf(bcftools_stderr, " -N, --disable-automatic-newline Disable automatic addition of newline character when not present\n");
248 fprintf(bcftools_stderr, " -o, --output FILE Output file name [bcftools_stdout]\n");
249 fprintf(bcftools_stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n");
250 fprintf(bcftools_stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n");
251 fprintf(bcftools_stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n");
252 fprintf(bcftools_stderr, " -s, --samples LIST List of samples to include\n");
253 fprintf(bcftools_stderr, " -S, --samples-file FILE File of samples to include\n");
254 fprintf(bcftools_stderr, " -t, --targets REGION Similar to -r but streams rather than index-jumps\n");
255 fprintf(bcftools_stderr, " -T, --targets-file FILE Similar to -R but streams rather than index-jumps\n");
256 fprintf(bcftools_stderr, " --targets-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [0]\n");
257 fprintf(bcftools_stderr, " -u, --allow-undef-tags Print \".\" for undefined tags\n");
258 fprintf(bcftools_stderr, " -v, --vcf-list FILE Process multiple VCFs listed in the file\n");
259 fprintf(bcftools_stderr, "\n");
260 fprintf(bcftools_stderr, "Examples:\n");
261 fprintf(bcftools_stderr, "\tbcftools query -f '%%CHROM\\t%%POS\\t%%REF\\t%%ALT[\\t%%SAMPLE=%%GT]\\n' file.vcf.gz\n");
262 fprintf(bcftools_stderr, "\t# For more examples see http://samtools.github.io/bcftools/bcftools.html#query\n");
263 fprintf(bcftools_stderr, "\n");
264 bcftools_exit(1);
265 }
266
267 int main_vcfquery(int argc, char *argv[])
268 {
269 int c, collapse = 0;
270 args_t *args = (args_t*) calloc(1,sizeof(args_t));
271 args->argc = argc; args->argv = argv;
272 args->force_newline = 1;
273 int regions_is_file = 0, targets_is_file = 0;
274 int regions_overlap = 1;
275 int targets_overlap = 0;
276
277 static struct option loptions[] =
278 {
279 {"help",0,0,'h'},
280 {"list-samples",0,0,'l'},
281 {"disable-automatic-newline",required_argument,NULL,'N'},
282 {"include",1,0,'i'},
283 {"exclude",1,0,'e'},
284 {"print-filtered",1,0,'F'},
285 {"format",1,0,'f'},
286 {"force-samples",0,0,3},
287 {"output-file",1,0,'o'},
288 {"output",1,0,'o'},
289 {"regions",1,0,'r'},
290 {"regions-file",1,0,'R'},
291 {"regions-overlap",required_argument,NULL,1},
292 {"targets",1,0,'t'},
293 {"targets-file",1,0,'T'},
294 {"targets-overlap",required_argument,NULL,2},
295 {"annots",1,0,'a'},
296 {"samples",1,0,'s'},
297 {"samples-file",1,0,'S'},
298 {"print-header",0,0,'H'},
299 {"collapse",1,0,'c'},
300 {"vcf-list",1,0,'v'},
301 {"allow-undef-tags",0,0,'u'},
302 {0,0,0,0}
303 };
304 while ((c = getopt_long(argc, argv, "hlr:R:F:f:a:s:S:Ht:T:c:v:i:e:o:uN",loptions,NULL)) >= 0) {
305 switch (c) {
306 case 'o': args->fn_out = optarg; break;
307 case 'F': args->print_filtered = optarg; break;
308 case 'f': args->format_str = strdup(optarg); break;
309 case 'N': args->force_newline = 0; break;
310 case 'H': args->print_header++; break;
311 case 'v': args->vcf_list = optarg; break;
312 case 'c':
313 error("The --collapse option is obsolete, pipe through `bcftools norm -c` instead.\n");
314 break;
315 case 'a':
316 {
317 kstring_t str = {0,0,0};
318 kputs("%CHROM\t%POS\t%MASK\t%REF\t%ALT\t%", &str);
319 char *p = optarg;
320 while ( *p )
321 {
322 if ( *p==',' )
323 kputs("\t%", &str);
324 else
325 kputc(*p, &str);
326 p++;
327 }
328 kputc('\n', &str);
329 args->format_str = str.s;
330 break;
331 }
332 case 'e':
333 if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n");
334 args->filter_str = optarg; args->filter_logic |= FLT_EXCLUDE; break;
335 case 'i':
336 if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n");
337 args->filter_str = optarg; args->filter_logic |= FLT_INCLUDE; break;
338 case 'r': args->regions_list = optarg; break;
339 case 'R': args->regions_list = optarg; regions_is_file = 1; break;
340 case 't': args->targets_list = optarg; break;
341 case 'T': args->targets_list = optarg; targets_is_file = 1; break;
342 case 'l': args->list_columns = 1; break;
343 case 'u': args->allow_undef_tags = 1; break;
344 case 's': args->sample_list = optarg; break;
345 case 'S': args->sample_list = optarg; args->sample_is_file = 1; break;
346 case 1 :
347 regions_overlap = parse_overlap_option(optarg);
348 if ( regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg);
349 break;
350 case 2 :
351 targets_overlap = parse_overlap_option(optarg);
352 if ( targets_overlap < 0 ) error("Could not parse: --targets-overlap %s\n",optarg);
353 break;
354 case 3 : args->force_samples = 1; break;
355 case 'h':
356 case '?': usage(); break;
357 default: error("Unknown argument: %s\n", optarg);
358 }
359 }
360
361 char *fname = NULL;
362 if ( optind>=argc )
363 {
364 if ( !isatty(fileno((FILE *)stdin)) ) fname = "-";
365 }
366 else fname = argv[optind];
367
368 if ( args->list_columns )
369 {
370 if ( !fname ) error("Missing the VCF file name\n");
371 args->files = bcf_sr_init();
372 if ( !bcf_sr_add_reader(args->files, fname) ) error("Failed to read from %s: %s\n", !strcmp("-",fname)?"standard input":fname,bcf_sr_strerror(args->files->errnum));
373 list_columns(args);
374 bcf_sr_destroy(args->files);
375 free(args);
376 return 0;
377 }
378
379 if ( !args->format_str )
380 {
381 if ( argc==1 && !fname ) usage();
382 error("Error: Missing the --format option\n");
383 }
384 args->out = args->fn_out ? fopen(args->fn_out, "w") : bcftools_stdout;
385 if ( !args->out ) error("%s: %s\n", args->fn_out,strerror(errno));
386
387 if ( !args->vcf_list )
388 {
389 if ( !fname ) usage();
390 args->files = bcf_sr_init();
391 if ( optind+1 < argc ) args->files->require_index = 1;
392 if ( args->regions_list )
393 {
394 bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,regions_overlap);
395 if ( bcf_sr_set_regions(args->files, args->regions_list, regions_is_file)<0 )
396 error("Failed to read the regions: %s\n", args->regions_list);
397 }
398 if ( args->targets_list )
399 {
400 bcf_sr_set_opt(args->files,BCF_SR_TARGETS_OVERLAP,targets_overlap);
401 if ( bcf_sr_set_targets(args->files, args->targets_list, targets_is_file, 0)<0 )
402 error("Failed to read the targets: %s\n", args->targets_list);
403 }
404 while ( fname )
405 {
406 if ( !bcf_sr_add_reader(args->files, fname) ) error("Failed to read from %s: %s\n", !strcmp("-",fname)?"standard input":fname,bcf_sr_strerror(args->files->errnum));
407 fname = ++optind < argc ? argv[optind] : NULL;
408 }
409 init_data(args);
410 query_vcf(args);
411 free(args->format_str);
412 destroy_data(args);
413 bcf_sr_destroy(args->files);
414 if ( fclose(args->out)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->fn_out);
415 free(args);
416 return 0;
417 }
418
419 // multiple VCFs
420 int i, k, nfiles, prev_nsamples = 0;
421 char **fnames, **prev_samples = NULL;
422 fnames = hts_readlist(args->vcf_list, 1, &nfiles);
423 if ( !fnames ) error("Error: failed to read %s\n", args->vcf_list);
424 if ( !nfiles ) error("No files in %s?\n", args->vcf_list);
425 for (i=0; i<nfiles; i++)
426 {
427 args->files = bcf_sr_init();
428 args->files->collapse = collapse;
429 if ( args->regions_list && bcf_sr_set_regions(args->files, args->regions_list, regions_is_file)<0 )
430 error("Failed to read the regions: %s\n", args->regions_list);
431 if ( optind < argc ) args->files->require_index = 1;
432 if ( args->targets_list )
433 {
434 if ( bcf_sr_set_targets(args->files, args->targets_list,targets_is_file, 0)<0 )
435 error("Failed to read the targets: %s\n", args->targets_list);
436 }
437 if ( !bcf_sr_add_reader(args->files, fnames[i]) ) error("Failed to open %s: %s\n", fnames[i],bcf_sr_strerror(args->files->errnum));
438 for (k=optind; k<argc; k++)
439 if ( !bcf_sr_add_reader(args->files, argv[k]) ) error("Failed to open %s: %s\n", argv[k],bcf_sr_strerror(args->files->errnum));
440 init_data(args);
441 if ( i==0 )
442 {
443 prev_samples = copy_header(args->header, args->files->readers[0].header->samples, bcf_hdr_nsamples(args->files->readers[0].header));
444 prev_nsamples = bcf_hdr_nsamples(args->files->readers[0].header);
445 }
446 else
447 {
448 args->print_header = 0;
449 if ( compare_header(args->header, args->files->readers[0].header->samples, bcf_hdr_nsamples(args->files->readers[0].header), prev_samples, prev_nsamples) )
450 error("Different samples in %s and %s\n", fnames[i-1],fnames[i]);
451 }
452 query_vcf(args);
453 destroy_data(args);
454 bcf_sr_destroy(args->files);
455 }
456 if ( fclose(args->out)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->fn_out);;
457 destroy_list(fnames, nfiles);
458 destroy_list(prev_samples, prev_nsamples);
459 free(args->format_str);
460 free(args);
461 return 0;
462 }
463
464