Debian Codegraph @

bcftools/vcfview.c.pysam.c

raw symbols SCIP
1 #include "bcftools.pysam.h"
2
3 /* vcfview.c -- VCF/BCF conversion, view, subset and filter VCF/BCF files.
4
5 Copyright (C) 2013-2023 Genome Research Ltd.
6
7 Author: Shane McCarthy <[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 <strings.h>
29 #include <unistd.h>
30 #include <getopt.h>
31 #include <ctype.h>
32 #include <string.h>
33 #include <errno.h>
34 #include <sys/stat.h>
35 #include <sys/types.h>
36 #include <math.h>
37 #include <inttypes.h>
38 #include <htslib/vcf.h>
39 #include <htslib/synced_bcf_reader.h>
40 #include <htslib/vcfutils.h>
41 #include <htslib/kbitset.h>
42 #include "bcftools.h"
43 #include "filter.h"
44 #include "htslib/khash_str2int.h"
45
46 #define FLT_INCLUDE 1
47 #define FLT_EXCLUDE 2
48
49 #define ALLELE_NONREF 1
50 #define ALLELE_MINOR 2
51 #define ALLELE_ALT1 3
52 #define ALLELE_MAJOR 4
53 #define ALLELE_NONMAJOR 5
54
55 #define GT_NEED_HOM 1
56 #define GT_NEED_HET 2
57 #define GT_NO_HOM 3
58 #define GT_NO_HET 4
59 #define GT_NEED_MISSING 5
60 #define GT_NO_MISSING 6
61
62 typedef struct _args_t
63 {
64 filter_t *filter;
65 char *filter_str;
66 int filter_logic; // one of FLT_INCLUDE/FLT_EXCLUDE (-i or -e)
67
68 bcf_srs_t *files;
69 bcf_hdr_t *hdr, *hnull, *hsub; // original header, sites-only header, subset header
70 char **argv, *format, *sample_names, *subset_fname, *targets_list, *regions_list;
71 int regions_overlap, targets_overlap;
72 int argc, clevel, n_threads, output_type, print_header, update_info, header_only, n_samples, *imap, calc_ac;
73 int trim_alts, sites_only, known, novel, min_alleles, max_alleles, private_vars, uncalled, phased;
74 int min_ac, min_ac_type, max_ac, max_ac_type, min_af_type, max_af_type, gt_type;
75 int *ac, mac;
76 float min_af, max_af;
77 char *fn_ref, *fn_out, **samples;
78 int sample_is_file, force_samples;
79 char *include_types, *exclude_types;
80 int include, exclude;
81 int record_cmd_line;
82 char *index_fn;
83 int write_index;
84 int trim_star_allele;
85 htsFile *out;
86 }
87 args_t;
88
89 static void init_data(args_t *args)
90 {
91 int i;
92 args->hdr = args->files->readers[0].header;
93
94 if (args->calc_ac && args->update_info)
95 {
96 if (bcf_hdr_append(args->hdr,"##INFO=<ID=AC,Number=A,Type=Integer,Description=\"Allele count in genotypes\">") < 0)
97 error_errno("[%s] Failed to add \"AC\" INFO header", __func__);
98 if (bcf_hdr_append(args->hdr,"##INFO=<ID=AN,Number=1,Type=Integer,Description=\"Total number of alleles in called genotypes\">") < 0)
99 error_errno("[%s] Failed to add \"AN\" INFO header", __func__);
100 }
101 if (args->record_cmd_line) bcf_hdr_append_version(args->hdr, args->argc, args->argv, "bcftools_view");
102 else if (bcf_hdr_sync(args->hdr) < 0)
103 error_errno("[%s] Failed to update header", __func__);
104
105 // setup sample data
106 if (args->sample_names)
107 {
108 void *hdr_samples = khash_str2int_init();
109 for (i=0; i<bcf_hdr_nsamples(args->hdr); i++)
110 khash_str2int_inc(hdr_samples, bcf_hdr_int2id(args->hdr,BCF_DT_SAMPLE,i));
111
112 void *exclude = (args->sample_names[0]=='^') ? khash_str2int_init() : NULL;
113 int nsmpl;
114 char **smpl = NULL;
115 args->samples = NULL; args->n_samples = 0;
116 smpl = hts_readlist(exclude ? &args->sample_names[1] : args->sample_names, args->sample_is_file, &nsmpl);
117 if ( !smpl )
118 {
119 error("Could not read the list: \"%s\"\n", exclude ? &args->sample_names[1] : args->sample_names);
120 }
121
122 if ( exclude )
123 {
124 for (i=0; i<nsmpl; i++) {
125 if (!khash_str2int_has_key(hdr_samples,smpl[i])) {
126 if (args->force_samples) {
127 fprintf(bcftools_stderr, "Warn: exclude called for sample that does not exist in header: \"%s\"... skipping\n", smpl[i]);
128 } else {
129 error("Error: exclude called for sample that does not exist in header: \"%s\". Use \"--force-samples\" to ignore this error.\n", smpl[i]);
130 }
131 }
132 khash_str2int_inc(exclude, smpl[i]);
133 }
134
135 for (i=0; i<bcf_hdr_nsamples(args->hdr); i++)
136 {
137 if ( exclude && khash_str2int_has_key(exclude,bcf_hdr_int2id(args->hdr,BCF_DT_SAMPLE,i)) ) continue;
138 args->samples = (char**) realloc(args->samples, (args->n_samples+1)*sizeof(const char*));
139 args->samples[args->n_samples++] = strdup(bcf_hdr_int2id(args->hdr,BCF_DT_SAMPLE,i));
140 }
141 khash_str2int_destroy(exclude);
142 }
143 else
144 {
145 for (i=0; i<nsmpl; i++) {
146 if (!khash_str2int_has_key(hdr_samples,smpl[i])) {
147 if (args->force_samples) {
148 fprintf(bcftools_stderr, "Warn: subset called for sample that does not exist in header: \"%s\"... skipping\n", smpl[i]);
149 continue;
150 } else {
151 error("Error: subset called for sample that does not exist in header: \"%s\". Use \"--force-samples\" to ignore this error.\n", smpl[i]);
152 }
153 }
154 args->samples = (char**) realloc(args->samples, (args->n_samples+1)*sizeof(const char*));
155 args->samples[args->n_samples++] = strdup(smpl[i]);
156 }
157 }
158 for (i=0; i<nsmpl; i++) free(smpl[i]);
159 free(smpl);
160 khash_str2int_destroy(hdr_samples);
161 if (args->n_samples == 0) {
162 fprintf(bcftools_stderr, "Warn: subsetting has removed all samples\n");
163 args->sites_only = 1;
164 }
165 }
166
167 if (args->n_samples)
168 args->imap = (int*)malloc(args->n_samples * sizeof(int));
169
170 // determine variant types to include/exclude
171 if (args->include_types || args->exclude_types) {
172 if (args->include_types && args->exclude_types) {
173 fprintf(bcftools_stderr, "Error: only supply one of --include-types, --exclude-types options\n");
174 bcftools_exit(1);
175 }
176 char **type_list = 0;
177 int m = 0, n = 0;
178 const char *q, *p;
179 for (q = p = args->include_types ? args->include_types : args->exclude_types;; ++p) {
180 if (*p == ',' || *p == 0) {
181 if (m == n) {
182 m = m? m<<1 : 16;
183 type_list = (char**)realloc(type_list, m * sizeof(char*));
184 }
185 type_list[n] = (char*)calloc(p - q + 1, 1);
186 strncpy(type_list[n++], q, p - q);
187 q = p + 1;
188 if (*p == 0) break;
189 }
190 }
191 type_list = (char**)realloc(type_list, n * sizeof(char*));
192
193 if (args->include_types) {
194 args->include = 0;
195 for (i = 0; i < n; ++i) {
196 if (strcmp(type_list[i], "snps") == 0) args->include |= VCF_SNP<<1;
197 else if (strcmp(type_list[i], "indels") == 0) args->include |= VCF_INDEL<<1;
198 else if (strcmp(type_list[i], "mnps") == 0) args->include |= VCF_MNP<<1;
199 else if (strcmp(type_list[i], "other") == 0) args->include |= VCF_OTHER<<1;
200 else if (strcmp(type_list[i], "ref") == 0) args->include |= VCF_OTHER<<1;
201 else if (strcmp(type_list[i], "bnd") == 0) args->include |= VCF_BND<<1;
202 else {
203 fprintf(bcftools_stderr, "[E::%s] unknown type\n", type_list[i]);
204 fprintf(bcftools_stderr, "Accepted types are snps, indels, mnps, other\n");
205 bcftools_exit(1);
206 }
207 }
208 }
209 if (args->exclude_types) {
210 args->exclude = 0;
211 for (i = 0; i < n; ++i) {
212 if (strcmp(type_list[i], "snps") == 0) args->exclude |= VCF_SNP<<1;
213 else if (strcmp(type_list[i], "indels") == 0) args->exclude |= VCF_INDEL<<1;
214 else if (strcmp(type_list[i], "mnps") == 0) args->exclude |= VCF_MNP<<1;
215 else if (strcmp(type_list[i], "other") == 0) args->exclude |= VCF_OTHER<<1;
216 else if (strcmp(type_list[i], "ref") == 0) args->exclude |= VCF_OTHER<<1;
217 else if (strcmp(type_list[i], "bnd") == 0) args->exclude |= VCF_BND<<1;
218 else {
219 fprintf(bcftools_stderr, "[E::%s] unknown type\n", type_list[i]);
220 fprintf(bcftools_stderr, "Accepted types are snps, indels, mnps, other\n");
221 bcftools_exit(1);
222 }
223 }
224 }
225 for (i = 0; i < n; ++i)
226 free(type_list[i]);
227 free(type_list);
228 }
229
230 char wmode[8];
231 set_wmode(wmode,args->output_type,args->fn_out,args->clevel);
232 args->out = hts_open(args->fn_out ? args->fn_out : "-", wmode);
233 if ( !args->out ) error("%s: %s\n", args->fn_out,strerror(errno));
234 if ( args->n_threads > 0)
235 hts_set_opt(args->out, HTS_OPT_THREAD_POOL, args->files->p);
236
237 // headers: hdr=full header, hsub=subset header, hnull=sites only header
238 if (args->sites_only){
239 args->hnull = bcf_hdr_subset(args->hdr, 0, 0, 0);
240 bcf_hdr_remove(args->hnull, BCF_HL_FMT, NULL);
241 }
242 if (args->n_samples > 0)
243 {
244 args->hsub = bcf_hdr_subset(args->hdr, args->n_samples, args->samples, args->imap);
245 if ( !args->hsub ) error("Error occurred while subsetting samples\n");
246 if ( args->n_samples != bcf_hdr_nsamples(args->hsub) )
247 {
248 int i;
249 for (i=0; i<args->n_samples; i++)
250 if ( args->imap[i]<0 ) error("Error: No such sample: \"%s\"\n", args->samples[i]);
251 }
252 }
253
254 if ( args->filter_str )
255 args->filter = filter_init(args->hdr, args->filter_str);
256 }
257
258 static void destroy_data(args_t *args)
259 {
260 int i;
261 if ( args->imap ) {
262 for (i = 0; i < args->n_samples; ++i)
263 free(args->samples[i]);
264 free(args->samples);
265 free(args->imap);
266 }
267 if (args->hnull) bcf_hdr_destroy(args->hnull);
268 if (args->hsub) bcf_hdr_destroy(args->hsub);
269 if ( args->filter )
270 filter_destroy(args->filter);
271 free(args->ac);
272 }
273
274 // true if all samples are phased.
275 // haploid genotypes are considered phased
276 // ./. => not phased, .|. => phased
277 int bcf_all_phased(const bcf_hdr_t *header, bcf1_t *line)
278 {
279 bcf_unpack(line, BCF_UN_FMT);
280 bcf_fmt_t *fmt_ptr = bcf_get_fmt(header, line, "GT");
281 int all_phased = 1;
282 if ( fmt_ptr )
283 {
284 int i, isample;
285 for (isample=0; isample<line->n_sample; isample++)
286 {
287 int sample_phased = 0;
288 #define BRANCH_INT(type_t,vector_end) { \
289 type_t *p = (type_t*) (fmt_ptr->p + isample*fmt_ptr->size); \
290 for (i=0; i<fmt_ptr->n; i++) \
291 { \
292 if (fmt_ptr->n == 1 || (p[i] == vector_end && i == 1)) { sample_phased = 1; break; } /* haploid phased by definition */ \
293 if ( p[i] == vector_end ) { break; }; /* smaller ploidy */ \
294 if ( bcf_gt_is_missing(p[i]) ) continue; /* missing allele */ \
295 if ((p[i])&1) { \
296 sample_phased = 1; \
297 break; \
298 } \
299 } \
300 }
301 switch (fmt_ptr->type) {
302 case BCF_BT_INT8: BRANCH_INT(int8_t, bcf_int8_vector_end); break;
303 case BCF_BT_INT16: BRANCH_INT(int16_t, bcf_int16_vector_end); break;
304 case BCF_BT_INT32: BRANCH_INT(int32_t, bcf_int32_vector_end); break;
305 default: fprintf(bcftools_stderr, "[E::%s] todo: fmt_type %d\n", __func__, fmt_ptr->type); bcftools_exit(1); break;
306 }
307 #undef BRANCH_INT
308 if (!sample_phased) {
309 all_phased = 0;
310 break;
311 }
312 }
313 }
314 return all_phased;
315 }
316
317 int subset_vcf(args_t *args, bcf1_t *line)
318 {
319 if ( args->min_alleles && line->n_allele < args->min_alleles ) return 0; // min alleles
320 if ( args->max_alleles && line->n_allele > args->max_alleles ) return 0; // max alleles
321 if (args->novel || args->known)
322 {
323 if ( args->novel && (line->d.id[0]!='.' || line->d.id[1]!=0) ) return 0; // skip sites which are known, ID != '.'
324 if ( args->known && line->d.id[0]=='.' && line->d.id[1]==0 ) return 0; // skip sites which are novel, ID == '.'
325 }
326
327 if (args->include || args->exclude)
328 {
329 int line_type = bcf_get_variant_types(line);
330 if ( args->include && !((line_type<<1) & args->include) ) return 0; // include only given variant types
331 if ( args->exclude && (line_type<<1) & args->exclude ) return 0; // exclude given variant types
332 }
333
334 if ( args->filter )
335 {
336 int ret = filter_test(args->filter, line, NULL);
337 if ( args->filter_logic==FLT_INCLUDE ) { if ( !ret ) return 0; }
338 else if ( ret ) return 0;
339 }
340
341 hts_expand(int, line->n_allele, args->mac, args->ac);
342 int i, an = 0, non_ref_ac = 0;
343 if (args->calc_ac) {
344 bcf_calc_ac(args->hdr, line, args->ac, BCF_UN_INFO|BCF_UN_FMT); // get original AC and AN values from INFO field if available, otherwise calculate
345 for (i=1; i<line->n_allele; i++)
346 non_ref_ac += args->ac[i];
347 for (i=0; i<line->n_allele; i++)
348 an += args->ac[i];
349 }
350
351 int update_ac = args->calc_ac;
352 if (args->n_samples)
353 {
354 int non_ref_ac_sub = 0, *ac_sub = (int*) calloc(line->n_allele,sizeof(int));
355 bcf_subset(args->hdr, line, args->n_samples, args->imap);
356 if ( args->calc_ac && !bcf_get_fmt(args->hdr,line,"GT") ) update_ac = 0;
357 if ( update_ac )
358 {
359 bcf_calc_ac(args->hsub, line, ac_sub, BCF_UN_FMT); // recalculate AC and AN
360 an = 0;
361 for (i=0; i<line->n_allele; i++) {
362 args->ac[i] = ac_sub[i];
363 an += ac_sub[i];
364 }
365 for (i=1; i<line->n_allele; i++)
366 non_ref_ac_sub += ac_sub[i];
367 if (args->private_vars) {
368 if (args->private_vars == FLT_INCLUDE && !(non_ref_ac_sub > 0 && non_ref_ac == non_ref_ac_sub)) { free(ac_sub); return 0; } // select private sites
369 if (args->private_vars == FLT_EXCLUDE && non_ref_ac_sub > 0 && non_ref_ac == non_ref_ac_sub) { free(ac_sub); return 0; } // exclude private sites
370 }
371 non_ref_ac = non_ref_ac_sub;
372 }
373 free(ac_sub);
374 }
375
376 bcf_fmt_t *gt_fmt;
377 if ( args->gt_type && (gt_fmt=bcf_get_fmt(args->hdr,line,"GT")) )
378 {
379 int nhet = 0, nhom = 0, nmiss = 0;
380 for (i=0; i<bcf_hdr_nsamples(args->hdr); i++)
381 {
382 int type = bcf_gt_type(gt_fmt,i,NULL,NULL);
383 if ( type==GT_HET_RA || type==GT_HET_AA )
384 {
385 if ( args->gt_type==GT_NO_HET ) return 0;
386 nhet = 1;
387 }
388 else if ( type==GT_UNKN )
389 {
390 if ( args->gt_type==GT_NO_MISSING ) return 0;
391 nmiss = 1;
392 }
393 else
394 {
395 if ( args->gt_type==GT_NO_HOM ) return 0;
396 nhom = 1;
397 }
398 }
399 if ( args->gt_type==GT_NEED_HOM && !nhom ) return 0;
400 else if ( args->gt_type==GT_NEED_HET && !nhet ) return 0;
401 else if ( args->gt_type==GT_NEED_MISSING && !nmiss ) return 0;
402 }
403
404 int minor_ac = 0;
405 int major_ac = 0;
406 if ( args->calc_ac )
407 {
408 minor_ac = args->ac[0];
409 major_ac = args->ac[0];
410 for (i=1; i<line->n_allele; i++){
411 if (args->ac[i] < minor_ac) { minor_ac = args->ac[i]; }
412 if (args->ac[i] > major_ac) { major_ac = args->ac[i]; }
413 }
414 }
415
416 if (args->min_ac!=-1)
417 {
418 if (args->min_ac_type == ALLELE_NONREF && args->min_ac>non_ref_ac) return 0; // min AC
419 else if (args->min_ac_type == ALLELE_MINOR && args->min_ac>minor_ac) return 0; // min minor AC
420 else if (args->min_ac_type == ALLELE_ALT1 && args->min_ac>args->ac[1]) return 0; // min 1st alternate AC
421 else if (args->min_ac_type == ALLELE_MAJOR && args->min_ac > major_ac) return 0; // min major AC
422 else if (args->min_ac_type == ALLELE_NONMAJOR && args->min_ac > an-major_ac) return 0; // min non-major AC
423 }
424 if (args->max_ac!=-1)
425 {
426 if (args->max_ac_type == ALLELE_NONREF && args->max_ac<non_ref_ac) return 0; // max AC
427 else if (args->max_ac_type == ALLELE_MINOR && args->max_ac<minor_ac) return 0; // max minor AC
428 else if (args->max_ac_type == ALLELE_ALT1 && args->max_ac<args->ac[1]) return 0; // max 1st alternate AC
429 else if (args->max_ac_type == ALLELE_MAJOR && args->max_ac < major_ac) return 0; // max major AC
430 else if (args->max_ac_type == ALLELE_NONMAJOR && args->max_ac < an-major_ac) return 0; // max non-major AC
431 }
432 if (args->min_af!=-1)
433 {
434 if (an == 0) return 0; // freq not defined, skip site
435 if (args->min_af_type == ALLELE_NONREF && args->min_af>non_ref_ac/(double)an) return 0; // min AF
436 else if (args->min_af_type == ALLELE_MINOR && args->min_af>minor_ac/(double)an) return 0; // min minor AF
437 else if (args->min_af_type == ALLELE_ALT1 && args->min_af>args->ac[1]/(double)an) return 0; // min 1st alternate AF
438 else if (args->min_af_type == ALLELE_MAJOR && args->min_af > major_ac/(double)an) return 0; // min major AF
439 else if (args->min_af_type == ALLELE_NONMAJOR && args->min_af > (an-major_ac)/(double)an) return 0; // min non-major AF
440 }
441 if (args->max_af!=-1)
442 {
443 if (an == 0) return 0; // freq not defined, skip site
444 if (args->max_af_type == ALLELE_NONREF && args->max_af<non_ref_ac/(double)an) return 0; // max AF
445 else if (args->max_af_type == ALLELE_MINOR && args->max_af<minor_ac/(double)an) return 0; // max minor AF
446 else if (args->max_af_type == ALLELE_ALT1 && args->max_af<args->ac[1]/(double)an) return 0; // max 1st alternate AF
447 else if (args->max_af_type == ALLELE_MAJOR && args->max_af < major_ac/(double)an) return 0; // max major AF
448 else if (args->max_af_type == ALLELE_NONMAJOR && args->max_af < (an-major_ac)/(double)an) return 0; // max non-major AF
449 }
450 if (args->uncalled) {
451 if (args->uncalled == FLT_INCLUDE && an > 0) return 0; // select uncalled
452 if (args->uncalled == FLT_EXCLUDE && an == 0) return 0; // skip if uncalled
453 }
454 if (update_ac && args->update_info) {
455 bcf_update_info_int32(args->hdr, line, "AC", &args->ac[1], line->n_allele-1);
456 bcf_update_info_int32(args->hdr, line, "AN", &an, 1);
457 }
458 if (args->trim_alts)
459 {
460 int ret = bcf_trim_alleles(args->hsub ? args->hsub : args->hdr, line);
461 if ( ret<0 ) error("Error: Could not trim alleles at %s:%"PRId64"\n", bcf_seqname(args->hsub ? args->hsub : args->hdr, line), (int64_t) line->pos+1);
462 }
463 if (args->trim_star_allele)
464 {
465 int iunseen;
466 if ( args->trim_star_allele && (line->n_allele > 2 || args->trim_star_allele > 1) && (iunseen=get_unseen_allele(line)) && iunseen>0 )
467 {
468 // the unobserved star allele should be trimmed, either it is variant site or trimming of all sites was requested
469 kbitset_t *rm_set = kbs_init(line->n_allele);
470 kbs_insert(rm_set, iunseen);
471 if ( bcf_remove_allele_set(args->hdr,line,rm_set) )
472 error("[%s] Error: failed to trim the unobserved allele at %s:%"PRIhts_pos"\n",__func__,bcf_seqname(args->hdr,line),line->pos+1);
473 kbs_destroy(rm_set);
474 }
475 }
476 if (args->phased) {
477 int phased = bcf_all_phased(args->hdr, line);
478 if (args->phased == FLT_INCLUDE && !phased) { return 0; } // skip unphased
479 if (args->phased == FLT_EXCLUDE && phased) { return 0; } // skip phased
480 }
481 if (args->sites_only) bcf_subset(args->hsub ? args->hsub : args->hdr, line, 0, 0);
482 return 1;
483 }
484
485 void set_allele_type (int *atype, char *atype_string)
486 {
487 *atype = ALLELE_NONREF;
488 if (strcmp(atype_string, "minor") == 0) {
489 *atype = ALLELE_MINOR;
490 }
491 else if (strcmp(atype_string, "alt1") == 0) {
492 *atype = ALLELE_ALT1;
493 }
494 else if (strcmp(atype_string, "nref") == 0) {
495 *atype = ALLELE_NONREF;
496 }
497 else if (strcmp(atype_string, "major") == 0) {
498 *atype = ALLELE_MAJOR;
499 }
500 else if (strcmp(atype_string, "nonmajor") == 0) {
501 *atype = ALLELE_NONMAJOR;
502 }
503 else {
504 error("Error: allele type not recognised. Expected one of nref|alt1|minor|major|nonmajor, got \"%s\".\n", atype_string);
505 }
506 }
507
508 static void usage(args_t *args)
509 {
510 fprintf(bcftools_stderr, "\n");
511 fprintf(bcftools_stderr, "About: VCF/BCF conversion, view, subset and filter VCF/BCF files.\n");
512 fprintf(bcftools_stderr, "Usage: bcftools view [options] <in.vcf.gz> [region1 [...]]\n");
513 fprintf(bcftools_stderr, "\n");
514 fprintf(bcftools_stderr, "Output options:\n");
515 fprintf(bcftools_stderr, " -G, --drop-genotypes Drop individual genotype information (after subsetting if -s option set)\n");
516 fprintf(bcftools_stderr, " -h, --header-only Print only the header in VCF output (equivalent to bcftools head)\n");
517 fprintf(bcftools_stderr, " -H, --no-header Suppress the header in VCF output\n");
518 fprintf(bcftools_stderr, " --with-header Print both header and records in VCF output [default]\n");
519 fprintf(bcftools_stderr, " -l, --compression-level [0-9] Compression level: 0 uncompressed, 1 best speed, 9 best compression [%d]\n", args->clevel);
520 fprintf(bcftools_stderr, " --no-version Do not append version and command line to the header\n");
521 fprintf(bcftools_stderr, " -o, --output FILE Output file name [bcftools_stdout]\n");
522 fprintf(bcftools_stderr, " -O, --output-type u|b|v|z[0-9] u/b: un/compressed BCF, v/z: un/compressed VCF, 0-9: compression level [v]\n");
523 fprintf(bcftools_stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n");
524 fprintf(bcftools_stderr, " -R, --regions-file FILE Restrict to regions listed in FILE\n");
525 fprintf(bcftools_stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n");
526 fprintf(bcftools_stderr, " -t, --targets [^]REGION Similar to -r but streams rather than index-jumps. Exclude regions with \"^\" prefix\n");
527 fprintf(bcftools_stderr, " -T, --targets-file [^]FILE Similar to -R but streams rather than index-jumps. Exclude regions with \"^\" prefix\n");
528 fprintf(bcftools_stderr, " --targets-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [0]\n");
529 fprintf(bcftools_stderr, " --threads INT Use multithreading with INT worker threads [0]\n");
530 fprintf(bcftools_stderr, "\n");
531 fprintf(bcftools_stderr, "Subset options:\n");
532 fprintf(bcftools_stderr, " -A, --trim-unseen-allele Remove '<*>' or '<NON_REF>' at variant (-A) or at all (-AA) sites\n");
533 fprintf(bcftools_stderr, " -a, --trim-alt-alleles Trim ALT alleles not seen in the genotype fields (or their subset with -s/-S)\n");
534 fprintf(bcftools_stderr, " -I, --no-update Do not (re)calculate INFO fields for the subset (currently INFO/AC and INFO/AN)\n");
535 fprintf(bcftools_stderr, " -s, --samples [^]LIST Comma separated list of samples to include (or exclude with \"^\" prefix). Be careful\n");
536 fprintf(bcftools_stderr, " when combining filtering with sample subsetting as filtering comes (usually) first.\n");
537 fprintf(bcftools_stderr, " If unsure, split sample subsetting and filtering in two commands, using -Ou when piping.\n");
538 fprintf(bcftools_stderr, " -S, --samples-file [^]FILE File of samples to include (or exclude with \"^\" prefix)\n");
539 fprintf(bcftools_stderr, " --force-samples Only warn about unknown subset samples\n");
540 fprintf(bcftools_stderr, "\n");
541 fprintf(bcftools_stderr, "Filter options:\n");
542 fprintf(bcftools_stderr, " -c/C, --min-ac/--max-ac INT[:TYPE] Minimum/maximum count for non-reference (nref), 1st alternate (alt1), least frequent\n");
543 fprintf(bcftools_stderr, " (minor), most frequent (major) or sum of all but most frequent (nonmajor) alleles [nref]\n");
544 fprintf(bcftools_stderr, " -f, --apply-filters LIST Require at least one of the listed FILTER strings (e.g. \"PASS,.\")\n");
545 fprintf(bcftools_stderr, " -g, --genotype [^]hom|het|miss Require one or more hom/het/missing genotype or, if prefixed with \"^\", exclude such sites\n");
546 fprintf(bcftools_stderr, " -i/e, --include/--exclude EXPR Select/exclude sites for which the expression is true (see man page for details)\n");
547 fprintf(bcftools_stderr, " -k/n, --known/--novel Select known/novel sites only (ID is not/is '.')\n");
548 fprintf(bcftools_stderr, " -m/M, --min-alleles/--max-alleles INT Minimum/maximum number of alleles listed in REF and ALT (e.g. -m2 -M2 for biallelic sites)\n");
549 fprintf(bcftools_stderr, " -p/P, --phased/--exclude-phased Select/exclude sites where all samples are phased\n");
550 fprintf(bcftools_stderr, " -q/Q, --min-af/--max-af FLOAT[:TYPE] Minimum/maximum frequency for non-reference (nref), 1st alternate (alt1), least frequent\n");
551 fprintf(bcftools_stderr, " (minor), most frequent (major) or sum of all but most frequent (nonmajor) alleles [nref]\n");
552 fprintf(bcftools_stderr, " -u/U, --uncalled/--exclude-uncalled Select/exclude sites without a called genotype\n");
553 fprintf(bcftools_stderr, " -v/V, --types/--exclude-types LIST Select/exclude comma-separated list of variant types: snps,indels,mnps,ref,bnd,other [null]\n");
554 fprintf(bcftools_stderr, " -x/X, --private/--exclude-private Select/exclude sites where the non-reference alleles are exclusive (private) to the subset samples\n");
555 fprintf(bcftools_stderr, " -W, --write-index[=FMT] Automatically index the output files [off]\n");
556 fprintf(bcftools_stderr, "\n");
557 bcftools_exit(1);
558 }
559
560 int main_vcfview(int argc, char *argv[])
561 {
562 int c;
563 args_t *args = (args_t*) calloc(1,sizeof(args_t));
564 args->argc = argc; args->argv = argv;
565 args->files = bcf_sr_init();
566 args->clevel = -1;
567 args->print_header = 1;
568 args->update_info = 1;
569 args->output_type = FT_VCF;
570 args->n_threads = 0;
571 args->record_cmd_line = 1;
572 args->write_index = 0;
573 args->min_ac = args->max_ac = args->min_af = args->max_af = -1;
574 args->regions_overlap = 1;
575 args->targets_overlap = 0;
576 int targets_is_file = 0, regions_is_file = 0;
577
578 static struct option loptions[] =
579 {
580 {"genotype",required_argument,NULL,'g'},
581 {"compression-level",required_argument,NULL,'l'},
582 {"threads",required_argument,NULL,9},
583 {"header-only",no_argument,NULL,'h'},
584 {"no-header",no_argument,NULL,'H'},
585 {"with-header",no_argument,NULL,4},
586 {"exclude",required_argument,NULL,'e'},
587 {"include",required_argument,NULL,'i'},
588 {"trim-alt-alleles",no_argument,NULL,'a'},
589 {"trim-unseen-allele",no_argument,NULL,'A'},
590 {"no-update",no_argument,NULL,'I'},
591 {"drop-genotypes",no_argument,NULL,'G'},
592 {"private",no_argument,NULL,'x'},
593 {"exclude-private",no_argument,NULL,'X'},
594 {"uncalled",no_argument,NULL,'u'},
595 {"exclude-uncalled",no_argument,NULL,'U'},
596 {"apply-filters",required_argument,NULL,'f'},
597 {"known",no_argument,NULL,'k'},
598 {"novel",no_argument,NULL,'n'},
599 {"min-alleles",required_argument,NULL,'m'},
600 {"max-alleles",required_argument,NULL,'M'},
601 {"samples",required_argument,NULL,'s'},
602 {"samples-file",required_argument,NULL,'S'},
603 {"force-samples",no_argument,NULL,1},
604 {"output-type",required_argument,NULL,'O'},
605 {"output-file",required_argument,NULL,'o'},
606 {"output",required_argument,NULL,'o'},
607 {"types",required_argument,NULL,'v'},
608 {"exclude-types",required_argument,NULL,'V'},
609 {"targets",required_argument,NULL,'t'},
610 {"targets-file",required_argument,NULL,'T'},
611 {"targets-overlap",required_argument,NULL,2},
612 {"regions",required_argument,NULL,'r'},
613 {"regions-file",required_argument,NULL,'R'},
614 {"regions-overlap",required_argument,NULL,3},
615 {"min-ac",required_argument,NULL,'c'},
616 {"max-ac",required_argument,NULL,'C'},
617 {"min-af",required_argument,NULL,'q'},
618 {"max-af",required_argument,NULL,'Q'},
619 {"phased",no_argument,NULL,'p'},
620 {"exclude-phased",no_argument,NULL,'P'},
621 {"no-version",no_argument,NULL,8},
622 {"write-index",optional_argument,NULL,'W'},
623 {NULL,0,NULL,0}
624 };
625 char *tmp;
626 while ((c = getopt_long(argc, argv, "l:t:T:r:R:o:O:s:S:Gf:knv:V:m:M:aAuUhHc:C:Ii:e:xXpPq:Q:g:W::",loptions,NULL)) >= 0)
627 {
628 char allele_type[9] = "nref";
629 switch (c)
630 {
631 case 'O':
632 switch (optarg[0]) {
633 case 'b': args->output_type = FT_BCF_GZ; break;
634 case 'u': args->output_type = FT_BCF; break;
635 case 'z': args->output_type = FT_VCF_GZ; break;
636 case 'v': args->output_type = FT_VCF; break;
637 default:
638 {
639 args->clevel = strtol(optarg,&tmp,10);
640 if ( *tmp || args->clevel<0 || args->clevel>9 ) error("The output type \"%s\" not recognised\n", optarg);
641 }
642 };
643 if ( optarg[1] )
644 {
645 args->clevel = strtol(optarg+1,&tmp,10);
646 if ( *tmp || args->clevel<0 || args->clevel>9 ) error("Could not parse argument: --compression-level %s\n", optarg+1);
647 }
648 break;
649 case 'l':
650 args->clevel = strtol(optarg,&tmp,10);
651 if ( *tmp ) error("Could not parse argument: --compression-level %s\n", optarg);
652 args->output_type |= FT_GZ;
653 break;
654 case 'o': args->fn_out = optarg; break;
655 case 'H': args->print_header = 0; break;
656 case 'h': args->header_only = 1; break;
657 case 4 : args->print_header = 1; args->header_only = 0; break;
658
659 case 't': args->targets_list = optarg; break;
660 case 'T': args->targets_list = optarg; targets_is_file = 1; break;
661 case 'r': args->regions_list = optarg; break;
662 case 'R': args->regions_list = optarg; regions_is_file = 1; break;
663
664 case 's': args->sample_names = optarg; break;
665 case 'S': args->sample_names = optarg; args->sample_is_file = 1; break;
666 case 1 : args->force_samples = 1; break;
667 case 'a': args->trim_alts = 1; args->calc_ac = 1; break;
668 case 'A': args->trim_star_allele++; break;
669 case 'I': args->update_info = 0; break;
670 case 'G': args->sites_only = 1; break;
671
672 case 'f': args->files->apply_filters = optarg; break;
673 case 'k': args->known = 1; break;
674 case 'n': args->novel = 1; break;
675 case 'm':
676 args->min_alleles = strtol(optarg,&tmp,10);
677 if ( *tmp ) error("Could not parse argument: --min-alleles %s\n", optarg);
678 break;
679 case 'M':
680 args->max_alleles = strtol(optarg,&tmp,10);
681 if ( *tmp ) error("Could not parse argument: --max-alleles %s\n", optarg);
682 break;
683 case 'v': args->include_types = optarg; break;
684 case 'V': args->exclude_types = optarg; break;
685 case 'e':
686 if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n");
687 args->filter_str = optarg; args->filter_logic |= FLT_EXCLUDE; break;
688 case 'i':
689 if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n");
690 args->filter_str = optarg; args->filter_logic |= FLT_INCLUDE; break;
691 case 'c':
692 {
693 args->min_ac_type = ALLELE_NONREF;
694 if ( sscanf(optarg,"%d:%8s",&args->min_ac, allele_type)!=2 && sscanf(optarg,"%d",&args->min_ac)!=1 )
695 error("Error: Could not parse --min-ac %s\n", optarg);
696 set_allele_type(&args->min_ac_type, allele_type);
697 args->calc_ac = 1;
698 break;
699 }
700 case 'C':
701 {
702 args->max_ac_type = ALLELE_NONREF;
703 if ( sscanf(optarg,"%d:%8s",&args->max_ac, allele_type)!=2 && sscanf(optarg,"%d",&args->max_ac)!=1 )
704 error("Error: Could not parse --max-ac %s\n", optarg);
705 set_allele_type(&args->max_ac_type, allele_type);
706 args->calc_ac = 1;
707 break;
708 }
709 case 'q':
710 {
711 args->min_af_type = ALLELE_NONREF;
712 if ( sscanf(optarg,"%f:%8s",&args->min_af, allele_type)!=2 && sscanf(optarg,"%f",&args->min_af)!=1 )
713 error("Error: Could not parse --min-af %s\n", optarg);
714 set_allele_type(&args->min_af_type, allele_type);
715 args->calc_ac = 1;
716 break;
717 }
718 case 'Q':
719 {
720 args->max_af_type = ALLELE_NONREF;
721 if ( sscanf(optarg,"%f:%8s",&args->max_af, allele_type)!=2 && sscanf(optarg,"%f",&args->max_af)!=1 )
722 error("Error: Could not parse --max-af %s\n", optarg);
723 set_allele_type(&args->max_af_type, allele_type);
724 args->calc_ac = 1;
725 break;
726 }
727
728 case 'x': args->private_vars |= FLT_INCLUDE; args->calc_ac = 1; break;
729 case 'X': args->private_vars |= FLT_EXCLUDE; args->calc_ac = 1; break;
730 case 'u': args->uncalled |= FLT_INCLUDE; args->calc_ac = 1; break;
731 case 'U': args->uncalled |= FLT_EXCLUDE; args->calc_ac = 1; break;
732 case 'p': args->phased |= FLT_INCLUDE; break; // phased
733 case 'P': args->phased |= FLT_EXCLUDE; break; // exclude-phased
734 case 'g':
735 {
736 if ( !strcasecmp(optarg,"hom") ) args->gt_type = GT_NEED_HOM;
737 else if ( !strcasecmp(optarg,"het") ) args->gt_type = GT_NEED_HET;
738 else if ( !strcasecmp(optarg,"miss") ) args->gt_type = GT_NEED_MISSING;
739 else if ( !strcasecmp(optarg,"^hom") ) args->gt_type = GT_NO_HOM;
740 else if ( !strcasecmp(optarg,"^het") ) args->gt_type = GT_NO_HET;
741 else if ( !strcasecmp(optarg,"^miss") ) args->gt_type = GT_NO_MISSING;
742 else error("The argument to -g not recognised. Expected one of hom/het/miss/^hom/^het/^miss, got \"%s\".\n", optarg);
743 break;
744 }
745 case 2 :
746 args->targets_overlap = parse_overlap_option(optarg);
747 if ( args->targets_overlap < 0 ) error("Could not parse: --targets-overlap %s\n",optarg);
748 break;
749 case 3 :
750 args->regions_overlap = parse_overlap_option(optarg);
751 if ( args->regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg);
752 break;
753 case 9 : args->n_threads = strtol(optarg, 0, 0); break;
754 case 8 : args->record_cmd_line = 0; break;
755 case 'W':
756 if (!(args->write_index = write_index_parse(optarg)))
757 error("Unsupported index format '%s'\n", optarg);
758 break;
759 case '?': usage(args); break;
760 default: error("Unknown argument: %s\n", optarg);
761 }
762 }
763
764 if ( args->filter_logic == (FLT_EXCLUDE|FLT_INCLUDE) ) error("Only one of -i or -e can be given.\n");
765 if ( args->private_vars > FLT_EXCLUDE ) error("Only one of -x or -X can be given.\n");
766 if ( args->uncalled > FLT_EXCLUDE ) error("Only one of -u or -U can be given.\n");
767 if ( args->phased > FLT_EXCLUDE ) error("Only one of -p or -P can be given.\n");
768
769 if ( args->sample_names && args->update_info) args->calc_ac = 1;
770
771 char *fname = NULL;
772 if ( optind>=argc )
773 {
774 if ( !isatty(fileno((FILE *)stdin)) ) fname = "-"; // reading from stdin
775 else usage(args);
776 }
777 else fname = argv[optind];
778
779 // read in the regions from the command line
780 if ( args->regions_list )
781 {
782 bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,args->regions_overlap);
783 if ( bcf_sr_set_regions(args->files, args->regions_list, regions_is_file)<0 )
784 error("Failed to read the regions: %s\n", args->regions_list);
785 }
786 else if ( optind+1 < argc )
787 {
788 int i;
789 kstring_t tmp = {0,0,0};
790 kputs(argv[optind+1],&tmp);
791 for (i=optind+2; i<argc; i++) { kputc(',',&tmp); kputs(argv[i],&tmp); }
792 if ( bcf_sr_set_regions(args->files, tmp.s, 0)<0 )
793 error("Failed to read the regions: %s\n", tmp.s);
794 free(tmp.s);
795 }
796 if ( args->targets_list )
797 {
798 bcf_sr_set_opt(args->files,BCF_SR_TARGETS_OVERLAP,args->targets_overlap);
799 if ( bcf_sr_set_targets(args->files, args->targets_list, targets_is_file, 0)<0 )
800 error("Failed to read the targets: %s\n", args->targets_list);
801 }
802
803 if ( bcf_sr_set_threads(args->files, args->n_threads)<0 ) error("Failed to create threads\n");
804 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));
805
806 init_data(args);
807 bcf_hdr_t *out_hdr = args->hnull ? args->hnull : (args->hsub ? args->hsub : args->hdr);
808 if (args->print_header)
809 {
810 if ( bcf_hdr_write(args->out, out_hdr)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->fn_out);
811 }
812 else if ( args->output_type & FT_BCF )
813 error("BCF output requires header, cannot proceed with -H\n");
814
815 if ( init_index2(args->out,out_hdr,args->fn_out, &args->index_fn,
816 args->write_index) < 0 )
817 error("Error: failed to initialise index for %s\n",args->fn_out);
818
819 int ret = 0;
820 if (!args->header_only)
821 {
822 while ( bcf_sr_next_line(args->files) )
823 {
824 bcf1_t *line = args->files->readers[0].buffer[0];
825 if ( line->errcode && out_hdr!=args->hdr ) error("Undefined tags in the header, cannot proceed in the sample subset mode.\n");
826 if ( subset_vcf(args, line) && bcf_write1(args->out, out_hdr, line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->fn_out);
827 }
828 ret = args->files->errnum;
829 if ( ret ) fprintf(bcftools_stderr,"Error: %s\n", bcf_sr_strerror(args->files->errnum));
830 }
831
832 if (args->write_index)
833 {
834 if (bcf_idx_save(args->out) < 0)
835 {
836 if ( hts_close(args->out)!=0 ) error("Error: close failed %s\n", args->fn_out?args->fn_out:"bcftools_stdout");
837 error("Error: cannot write to index %s\n", args->index_fn);
838 }
839 free(args->index_fn);
840 }
841
842 if ( hts_close(args->out)!=0 ) error("Error: close failed %s\n", args->fn_out?args->fn_out:"bcftools_stdout");
843 destroy_data(args);
844 bcf_sr_destroy(args->files);
845 free(args);
846 return ret;
847 }