Debian Codegraph @

bcftools/vcffilter.c

raw symbols SCIP
1 /* vcffilter.c -- Apply fixed-threshold filters.
2
3 Copyright (C) 2013-2023 Genome Research Ltd.
4
5 Author: Petr Danecek <[email protected]>
6
7 Permission is hereby granted, free of charge, to any person obtaining a copy
8 of this software and associated documentation files (the "Software"), to deal
9 in the Software without restriction, including without limitation the rights
10 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 copies of the Software, and to permit persons to whom the Software is
12 furnished to do so, subject to the following conditions:
13
14 The above copyright notice and this permission notice shall be included in
15 all copies or substantial portions of the Software.
16
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 THE SOFTWARE. */
24
25 #include <stdio.h>
26 #include <unistd.h>
27 #include <getopt.h>
28 #include <assert.h>
29 #include <ctype.h>
30 #include <string.h>
31 #include <strings.h>
32 #include <errno.h>
33 #include <sys/stat.h>
34 #include <sys/types.h>
35 #include <math.h>
36 #include <htslib/vcf.h>
37 #include <htslib/synced_bcf_reader.h>
38 #include <htslib/vcfutils.h>
39 #include "bcftools.h"
40 #include "filter.h"
41 #include "rbuf.h"
42 #include "regidx.h"
43
44 // Logic of the filters: include or exclude sites which match the filters?
45 #define FLT_INCLUDE 1
46 #define FLT_EXCLUDE 2
47
48 // FILTER columns annotation: replace or add to existing FILTERs; set FILTER to PASS at good sites?
49 #define ANNOT_ADD 1
50 #define ANNOT_RESET 2
51
52 // Set genotypes of filtered samples
53 #define SET_GTS_MISSING 1
54 #define SET_GTS_REF 2
55
56 typedef struct _args_t
57 {
58 filter_t *filter;
59 char *filter_str;
60 int filter_logic; // include or exclude sites which match the filters? One of FLT_INCLUDE/FLT_EXCLUDE
61 const uint8_t *smpl_pass;
62 int set_gts;
63 char *soft_filter; // drop failed sites or annotate FILTER column?
64 int annot_mode; // add to existing FILTER annotation or replace? Otherwise reset FILTER to PASS or leave as it is?
65 int flt_fail, flt_pass; // BCF ids of fail and pass filters
66 int snp_gap, snp_gap_type, indel_gap, IndelGap_id, SnpGap_id;
67 char *snp_gap_str;
68 int32_t ntmpi, *tmpi, ntmp_ac, *tmp_ac;
69 rbuf_t rbuf;
70 bcf1_t **rbuf_lines;
71
72 bcf_srs_t *files;
73 bcf_hdr_t *hdr;
74 htsFile *out_fh;
75 int output_type, n_threads, clevel;
76
77 char **argv, *output_fname, *targets_list, *regions_list, *mask_list;
78 int argc, record_cmd_line, mask_is_file, mask_overlap, mask_negate;
79 regidx_t *mask;
80 char *index_fn;
81 int write_index;
82 }
83 args_t;
84
85 static void init_data(args_t *args)
86 {
87 char wmode[8];
88 set_wmode(wmode,args->output_type,args->output_fname,args->clevel);
89 args->out_fh = hts_open(args->output_fname ? args->output_fname : "-", wmode);
90 if ( args->out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->output_fname, strerror(errno));
91 if ( args->n_threads ) hts_set_threads(args->out_fh, args->n_threads);
92
93 if ( args->mask_list )
94 {
95 if ( args->mask_list[0]=='^' ) args->mask_negate = 1;
96 if ( args->mask_is_file )
97 args->mask = regidx_init(args->mask_negate?args->mask_list+1:args->mask_list,NULL,NULL,0,NULL);
98 else
99 {
100 char *rmme = strdup(args->mask_negate?args->mask_list+1:args->mask_list), *tmp = rmme;
101 while ( *tmp )
102 {
103 if ( *tmp==',' ) *tmp = '\n';
104 tmp++;
105 }
106 args->mask = regidx_init_string(rmme, regidx_parse_reg, NULL, 0, NULL);
107 free(rmme);
108 }
109 if ( !args->mask )
110 error("Could not initialize the mask: %s\n",args->mask_list);
111 }
112
113 args->hdr = args->files->readers[0].header;
114 args->flt_pass = bcf_hdr_id2int(args->hdr,BCF_DT_ID,"PASS"); assert( !args->flt_pass ); // sanity check: required by BCF spec
115
116 if ( args->soft_filter && (args->filter_logic || args->mask_list) )
117 {
118 kstring_t flt_name = {0,0,0};
119 if ( strcmp(args->soft_filter,"+") )
120 kputs(args->soft_filter, &flt_name);
121 else
122 {
123 // Make up a filter name
124 int i = 0, id = -1;
125 do
126 {
127 ksprintf(&flt_name,"Filter%d", ++i);
128 id = bcf_hdr_id2int(args->hdr,BCF_DT_ID,flt_name.s);
129 }
130 while ( bcf_hdr_idinfo_exists(args->hdr,BCF_HL_FLT,id) );
131 }
132
133 kstring_t tmp = {0,0,0};
134 if ( args->filter_logic )
135 {
136 // -i or -e: append FILTER line
137 ksprintf(&tmp,"Set if %s: ",args->filter_logic & FLT_INCLUDE ? "not true" : "true");
138
139 // escape quotes
140 char *t = args->filter_str;
141 while ( *t )
142 {
143 if ( *t=='"' ) kputc('\\',&tmp);
144 kputc(*t,&tmp);
145 t++;
146 }
147 }
148 else if ( args->mask_list )
149 ksprintf(&tmp,"Record masked by region");
150
151 int ret = bcf_hdr_printf(args->hdr, "##FILTER=<ID=%s,Description=\"%s\">", flt_name.s,tmp.s);
152 if ( ret!=0 )
153 error("Failed to append header line: ##FILTER=<ID=%s,Description=\"%s\">\n", flt_name.s,tmp.s);
154 args->flt_fail = bcf_hdr_id2int(args->hdr,BCF_DT_ID,flt_name.s); assert( args->flt_fail>=0 );
155 free(flt_name.s);
156 free(tmp.s);
157 }
158
159 if ( args->snp_gap || args->indel_gap )
160 {
161 if ( !args->filter_logic && args->soft_filter && strcmp(args->soft_filter,"+") )
162 {
163 kstring_t tmp = {0,0,0};
164 if ( args->snp_gap ) kputs("\"SnpGap\"", &tmp);
165 if ( args->indel_gap )
166 {
167 if ( tmp.s ) kputs(" and ", &tmp);
168 kputs("\"IndelGap\"", &tmp);
169 }
170 if ( strncmp(tmp.s+1,args->soft_filter,tmp.l-2) )
171 fprintf(stderr,"Warning: using %s filter name instead of \"%s\"\n", tmp.s,args->soft_filter);
172 free(tmp.s);
173 }
174
175 rbuf_init(&args->rbuf, 64);
176 args->rbuf_lines = (bcf1_t**) calloc(args->rbuf.m, sizeof(bcf1_t*));
177 if ( args->snp_gap )
178 {
179 bcf_hdr_printf(args->hdr, "##FILTER=<ID=SnpGap,Description=\"SNP within %d bp of %s\">", args->snp_gap,args->snp_gap_str);
180 args->SnpGap_id = bcf_hdr_id2int(args->hdr, BCF_DT_ID, "SnpGap");
181 assert( args->SnpGap_id>=0 );
182 }
183 if ( args->indel_gap )
184 {
185 bcf_hdr_printf(args->hdr, "##FILTER=<ID=IndelGap,Description=\"Indel within %d bp of an indel\">", args->indel_gap);
186 args->IndelGap_id = bcf_hdr_id2int(args->hdr, BCF_DT_ID, "IndelGap");
187 assert( args->IndelGap_id>=0 );
188 }
189 }
190
191 if (args->record_cmd_line) bcf_hdr_append_version(args->hdr, args->argc, args->argv, "bcftools_filter");
192
193 if ( args->filter_str )
194 args->filter = filter_init(args->hdr, args->filter_str);
195 }
196
197 static void destroy_data(args_t *args)
198 {
199 if ( args->rbuf_lines )
200 {
201 int i;
202 for (i=0; i<args->rbuf.m; i++)
203 if ( args->rbuf_lines[i] ) bcf_destroy1(args->rbuf_lines[i]);
204 free(args->rbuf_lines);
205 }
206 if ( args->filter )
207 filter_destroy(args->filter);
208 free(args->tmpi);
209 free(args->tmp_ac);
210 if ( args->mask ) regidx_destroy(args->mask);
211 }
212
213 static void flush_buffer(args_t *args, int n)
214 {
215 int i, j;
216 for (i=0; i<n; i++)
217 {
218 int k = rbuf_shift(&args->rbuf);
219 bcf1_t *rec = args->rbuf_lines[k];
220
221 int pass = 1;
222 if ( !args->soft_filter )
223 {
224 for (j=0; j<rec->d.n_flt; j++)
225 {
226 if ( args->indel_gap && rec->d.flt[j]==args->IndelGap_id ) { pass = 0; break; }
227 if ( args->snp_gap && rec->d.flt[j]==args->SnpGap_id ) { pass = 0; break; }
228 }
229 }
230 if ( pass && bcf_write1(args->out_fh, args->hdr, rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname);
231 }
232 }
233
234 #define SWAP(type_t, a, b) { type_t t = a; a = b; b = t; }
235 static void buffered_filters(args_t *args, bcf1_t *line)
236 {
237 /**
238 * The logic of SnpGap=3. The SNPs at positions 1 and 7 are filtered,
239 * positions 0 and 8 are not:
240 * 0123456789
241 * ref .G.GT..G..
242 * del .A.G-..A..
243 * Here the positions 1 and 6 are filtered, 0 and 7 are not:
244 * 0123-456789
245 * ref .G.G-..G..
246 * ins .A.GT..A..
247 *
248 * The logic of IndelGap=2. The second indel is filtered:
249 * 012345678901
250 * ref .GT.GT..GT..
251 * del .G-.G-..G-..
252 * And similarly here, the second is filtered:
253 * 01 23 456 78
254 * ref .A-.A-..A-..
255 * ins .AT.AT..AT..
256 */
257
258 // To avoid additional data structure, we abuse bcf1_t's var and var_type records.
259 const int SnpGap_set = 1 << (8*sizeof(int)/2);
260 const int IndelGap_set = 1 << (8*sizeof(int)/2-1);
261 const int IndelGap_flush = 1 << (8*sizeof(int)/2-2);
262
263 int var_type = 0, i;
264 if ( line )
265 {
266 // Still on the same chromosome?
267 int ilast = rbuf_last(&args->rbuf);
268 if ( ilast>=0 && line->rid != args->rbuf_lines[ilast]->rid )
269 flush_buffer(args, args->rbuf.n); // new chromosome, flush everything
270
271 rbuf_expand0(&args->rbuf,bcf1_t*,args->rbuf.n,args->rbuf_lines);
272
273 // Insert the new record in the buffer. The line would be overwritten in
274 // the next bcf_sr_next_line call, therefore we need to swap it with an
275 // unused one
276 ilast = rbuf_append(&args->rbuf);
277 if ( !args->rbuf_lines[ilast] ) args->rbuf_lines[ilast] = bcf_init1();
278 SWAP(bcf1_t*, args->files->readers[0].buffer[0], args->rbuf_lines[ilast]);
279
280 var_type = bcf_get_variant_types(line);
281
282 // Find out the size of an indel. The indel boundaries are based on REF
283 // (POS+1,POS+rlen-1). This is not entirely correct: mpileup likes to
284 // output REF=CAGAGAGAGA, ALT=CAGAGAGAGAGA where REF=C,ALT=CGA could be
285 // used. This filter is therefore more strict and may remove some valid
286 // SNPs.
287 // Set the REF allele's length to max deletion length or to 1 if a SNP or an insertion.
288 line->d.var[0].n = line->rlen;
289 }
290
291 int k_flush = 1;
292 if ( args->indel_gap )
293 {
294 k_flush = 0;
295 // Find indels which are too close to each other
296 int last_to = -1;
297 for (i=-1; rbuf_next(&args->rbuf,&i); )
298 {
299 bcf1_t *rec = args->rbuf_lines[i];
300 int rec_from = rec->pos;
301 if ( last_to!=-1 && last_to < rec_from ) break;
302
303 k_flush++;
304 if ( !(rec->d.var_type & VCF_INDEL) ) continue;
305
306 rec->d.var_type |= IndelGap_set;
307 last_to = args->indel_gap + rec->pos + rec->d.var[0].n - 1;
308 }
309 if ( i==args->rbuf.f && line && last_to!=-1 ) k_flush = 0;
310 if ( k_flush || !line )
311 {
312 // Select the best indel from the cluster of k_flush indels
313 int k = 0, max_ac = -1, imax_ac = -1, max_qual = -1, imax_qual = -1;
314 for (i=-1; rbuf_next(&args->rbuf,&i) && k<k_flush; )
315 {
316 k++;
317 bcf1_t *rec = args->rbuf_lines[i];
318 if ( !(rec->d.var_type & IndelGap_set) ) continue;
319 hts_expand(int, rec->n_allele, args->ntmpi, args->tmpi);
320 int ret = bcf_calc_ac(args->hdr, rec, args->tmpi, BCF_UN_ALL);
321 if ( imax_ac==-1 || (ret && max_ac < args->tmpi[1]) ) { max_ac = args->tmpi[1]; imax_ac = i; }
322 if ( imax_qual==-1 || max_qual < rec->qual ) { max_qual = rec->qual; imax_qual = i; }
323 }
324
325 // Filter all but the best indel (with the best QUAL, bigger AC, or take the first if neither QUAL nor AC are available)
326 k = 0;
327 for (i=-1; rbuf_next(&args->rbuf,&i) && k<k_flush; )
328 {
329 k++;
330 bcf1_t *rec = args->rbuf_lines[i];
331 if ( !(rec->d.var_type & IndelGap_set) ) continue;
332 rec->d.var_type |= IndelGap_flush;
333
334 int do_filter = 0;
335 if ( max_qual>0 )
336 {
337 if ( i!=imax_qual ) do_filter = 1;
338 }
339 else if ( i!=imax_ac ) do_filter = 1;
340 if ( do_filter ) bcf_add_filter(args->hdr, args->rbuf_lines[i], args->IndelGap_id);
341 }
342 }
343 }
344
345 if ( !line )
346 {
347 // Finished: flush everything
348 flush_buffer(args, args->rbuf.n);
349 return;
350 }
351
352 int j_flush = 1;
353 if ( args->snp_gap )
354 {
355 j_flush = 0;
356 int last_from = line->pos;
357 for (i=-1; rbuf_next(&args->rbuf,&i); )
358 {
359 bcf1_t *rec = args->rbuf_lines[i];
360 int rec_to = rec->pos + rec->d.var[0].n - 1; // last position affected by the variant
361 if ( rec_to + args->snp_gap < last_from )
362 j_flush++;
363 else if ( (var_type & args->snp_gap_type) && (rec->d.var_type & VCF_SNP) && !(rec->d.var_type & SnpGap_set) )
364 {
365 // this SNP has not been SnpGap-filtered yet
366 rec->d.var_type |= SnpGap_set;
367 bcf_add_filter(args->hdr, rec, args->SnpGap_id);
368 }
369 else if ( (var_type & VCF_SNP) && (rec->d.var_type & args->snp_gap_type) )
370 {
371 // the line which we are adding is a SNP and needs to be filtered
372 line->d.var_type |= SnpGap_set;
373 bcf_add_filter(args->hdr, line, args->SnpGap_id);
374 break;
375 }
376 }
377 }
378 flush_buffer(args, j_flush < k_flush ? j_flush : k_flush);
379 }
380
381 static void set_genotypes(args_t *args, bcf1_t *line, int pass_site)
382 {
383 int i,j;
384 if ( !bcf_hdr_nsamples(args->hdr) ) return;
385 if ( args->smpl_pass )
386 {
387 int npass = 0;
388 for (i=0; i<bcf_hdr_nsamples(args->hdr); i++) npass += args->smpl_pass[i];
389
390 // return if all samples pass
391 if ( npass==bcf_hdr_nsamples(args->hdr) && (args->filter_logic & FLT_INCLUDE) ) return;
392 if ( npass==0 && (args->filter_logic & FLT_EXCLUDE) ) return;
393 }
394 else if ( pass_site ) return;
395
396 int an = 0, has_an = bcf_get_info_int32(args->hdr, line, "AN", &args->tmp_ac, &args->ntmp_ac);
397 if ( has_an==1 ) an = args->tmp_ac[0];
398 else has_an = 0;
399
400 int has_ac = bcf_get_info_int32(args->hdr, line, "AC", &args->tmp_ac, &args->ntmp_ac);
401 has_ac = has_ac==line->n_allele-1 ? 1 : 0;
402
403 int new_gt = 0, ngts = bcf_get_format_int32(args->hdr, line, "GT", &args->tmpi, &args->ntmpi);
404 ngts /= bcf_hdr_nsamples(args->hdr);
405 if ( args->set_gts==SET_GTS_MISSING ) new_gt = bcf_gt_missing;
406 else if ( args->set_gts==SET_GTS_REF ) new_gt = bcf_gt_unphased(0);
407 else error("todo: set_gts=%d\n", args->set_gts);
408 for (i=0; i<bcf_hdr_nsamples(args->hdr); i++)
409 {
410 if ( args->smpl_pass )
411 {
412 int pass = args->smpl_pass[i];
413 if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1;
414 if ( pass ) continue;
415 }
416 int32_t *gts = args->tmpi + ngts*i;
417 for (j=0; j<ngts; j++)
418 {
419 if ( gts[j]==bcf_int32_vector_end ) break;
420 if ( args->set_gts==SET_GTS_MISSING && !bcf_gt_is_missing(gts[j]) )
421 {
422 int ial = bcf_gt_allele(gts[j]);
423 if ( has_ac && ial>0 && ial<=line->n_allele ) args->tmp_ac[ ial-1 ]--;
424 an--;
425 }
426 else if ( args->set_gts==SET_GTS_REF )
427 {
428 int ial = bcf_gt_allele(gts[j]);
429 if ( bcf_gt_is_missing(gts[j]) ) an++;
430 else if ( has_ac && ial>0 && ial<=line->n_allele ) args->tmp_ac[ ial-1 ]--;
431 }
432 gts[j] = new_gt;
433 }
434 }
435 bcf_update_genotypes(args->hdr,line,args->tmpi,ngts*bcf_hdr_nsamples(args->hdr));
436 if ( has_an ) bcf_update_info_int32(args->hdr,line,"AN",&an,1);
437 if ( has_ac ) bcf_update_info_int32(args->hdr,line,"AC",args->tmp_ac,line->n_allele-1);
438 }
439
440 static void _set_variant_boundaries(bcf1_t *rec, hts_pos_t *beg, hts_pos_t *end)
441 {
442 hts_pos_t off;
443 if ( rec->n_allele )
444 {
445 off = rec->rlen;
446 bcf_unpack(rec, BCF_UN_STR);
447 int i;
448 for (i=1; i<rec->n_allele; i++)
449 {
450 // Make symbolic alleles start at POS, although this is not strictly true for
451 // <DEL>,<INS> where POS should be the position BEFORE the deletion/insertion.
452 // However, since arbitrary symbolic alleles can be defined by the user, we
453 // will simplify the interpretation of --targets-overlap and --region-overlap.
454 int j = 0;
455 char *ref = rec->d.allele[0];
456 char *alt = rec->d.allele[i];
457 while ( ref[j] && alt[j] && ref[j]==alt[j] ) j++;
458 if ( off > j ) off = j;
459 if ( !off ) break;
460 }
461 }
462 else
463 off = 0;
464
465 *beg = rec->pos + off;
466 *end = rec->pos + rec->rlen - 1;
467 }
468
469 static void usage(args_t *args)
470 {
471 fprintf(stderr, "\n");
472 fprintf(stderr, "About: Apply fixed-threshold filters.\n");
473 fprintf(stderr, "Usage: bcftools filter [options] <in.vcf.gz>\n");
474 fprintf(stderr, "\n");
475 fprintf(stderr, "Options:\n");
476 fprintf(stderr, " -e, --exclude EXPR Exclude sites for which the expression is true (see man page for details)\n");
477 fprintf(stderr, " -g, --SnpGap INT[:TYPE] Filter SNPs within <int> base pairs of an indel (the default) or any combination of indel,mnp,bnd,other,overlap\n");
478 fprintf(stderr, " -G, --IndelGap INT Filter clusters of indels separated by <int> or fewer base pairs allowing only one to pass\n");
479 fprintf(stderr, " -i, --include EXPR Include only sites for which the expression is true (see man page for details\n");
480 fprintf(stderr, " --mask [^]REGION Soft filter regions, \"^\" to negate\n");
481 fprintf(stderr, " -M, --mask-file [^]FILE Soft filter regions listed in a file, \"^\" to negate\n");
482 fprintf(stderr, " --mask-overlap 0|1|2 Mask if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n");
483 fprintf(stderr, " -m, --mode [+x] \"+\": do not replace but add to existing FILTER; \"x\": reset filters at sites which pass\n");
484 fprintf(stderr, " --no-version Do not append version and command line to the header\n");
485 fprintf(stderr, " -o, --output FILE Write output to a file [standard output]\n");
486 fprintf(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");
487 fprintf(stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n");
488 fprintf(stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n");
489 fprintf(stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n");
490 fprintf(stderr, " -s, --soft-filter STRING Annotate FILTER column with <string> or unique filter name (\"Filter%%d\") made up by the program (\"+\")\n");
491 fprintf(stderr, " -S, --set-GTs .|0 Set genotypes of failed samples to missing (.) or ref (0)\n");
492 fprintf(stderr, " -t, --targets REGION Similar to -r but streams rather than index-jumps\n");
493 fprintf(stderr, " -T, --targets-file FILE Similar to -R but streams rather than index-jumps\n");
494 fprintf(stderr, " --targets-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [0]\n");
495 fprintf(stderr, " --threads INT Use multithreading with <int> worker threads [0]\n");
496 fprintf(stderr, " -W, --write-index[=FMT] Automatically index the output files [off]\n");
497 fprintf(stderr, "\n");
498 exit(1);
499 }
500
501 int main_vcffilter(int argc, char *argv[])
502 {
503 int c;
504 args_t *args = (args_t*) calloc(1,sizeof(args_t));
505 args->argc = argc; args->argv = argv;
506 args->files = bcf_sr_init();
507 args->output_fname = "-";
508 args->output_type = FT_VCF;
509 args->n_threads = 0;
510 args->record_cmd_line = 1;
511 args->clevel = -1;
512 int regions_is_file = 0, targets_is_file = 0;
513 int regions_overlap = 1;
514 int targets_overlap = 0;
515 args->mask_overlap = 1;
516
517 static struct option loptions[] =
518 {
519 {"set-GTs",required_argument,NULL,'S'},
520 {"mode",required_argument,NULL,'m'},
521 {"mask",required_argument,NULL,10},
522 {"mask-file",required_argument,NULL,'M'},
523 {"mask-overlap",required_argument,NULL,11},
524 {"soft-filter",required_argument,NULL,'s'},
525 {"exclude",required_argument,NULL,'e'},
526 {"include",required_argument,NULL,'i'},
527 {"targets",required_argument,NULL,'t'},
528 {"targets-file",required_argument,NULL,'T'},
529 {"targets-overlap",required_argument,NULL,4},
530 {"regions",required_argument,NULL,'r'},
531 {"regions-file",required_argument,NULL,'R'},
532 {"regions-overlap",required_argument,NULL,3},
533 {"output",required_argument,NULL,'o'},
534 {"output-type",required_argument,NULL,'O'},
535 {"threads",required_argument,NULL,9},
536 {"SnpGap",required_argument,NULL,'g'},
537 {"IndelGap",required_argument,NULL,'G'},
538 {"no-version",no_argument,NULL,8},
539 {"write-index",optional_argument,NULL,'W'},
540 {NULL,0,NULL,0}
541 };
542 char *tmp;
543 while ((c = getopt_long(argc, argv, "e:i:t:T:r:R:h?s:m:M:o:O:g:G:S:W::",loptions,NULL)) >= 0) {
544 switch (c) {
545 case 'g':
546 args->snp_gap = strtol(optarg,&tmp,10);
547 if ( *tmp && *tmp!=':' ) error("Could not parse argument: --SnpGap %s\n", optarg);
548 if ( *tmp==':' )
549 {
550 args->snp_gap_str = tmp+1;
551 int i,n;
552 char **keys = hts_readlist(tmp+1,0,&n);
553 for(i=0; i<n; i++)
554 {
555 if ( !strcasecmp(keys[i],"indel") ) args->snp_gap_type |= VCF_INDEL;
556 else if ( !strcasecmp(keys[i],"mnp") ) args->snp_gap_type |= VCF_MNP;
557 else if ( !strcasecmp(keys[i],"bnd") ) args->snp_gap_type |= VCF_BND;
558 else if ( !strcasecmp(keys[i],"other") ) args->snp_gap_type |= VCF_OTHER;
559 else if ( !strcasecmp(keys[i],"overlap") ) args->snp_gap_type |= VCF_OVERLAP;
560 else error("Could not parse \"%s\" in \"--SnpGap %s\"\n", keys[i], optarg);
561 free(keys[i]);
562 }
563 if ( n ) free(keys);
564 }
565 else
566 {
567 args->snp_gap_type = VCF_INDEL;
568 args->snp_gap_str = "indel";
569 }
570 break;
571 case 'G':
572 args->indel_gap = strtol(optarg,&tmp,10);
573 if ( *tmp ) error("Could not parse argument: --IndelGap %s\n", optarg);
574 break;
575 case 'o': args->output_fname = optarg; break;
576 case 'O':
577 switch (optarg[0]) {
578 case 'b': args->output_type = FT_BCF_GZ; break;
579 case 'u': args->output_type = FT_BCF; break;
580 case 'z': args->output_type = FT_VCF_GZ; break;
581 case 'v': args->output_type = FT_VCF; break;
582 default:
583 {
584 args->clevel = strtol(optarg,&tmp,10);
585 if ( *tmp || args->clevel<0 || args->clevel>9 ) error("The output type \"%s\" not recognised\n", optarg);
586 }
587 }
588 if ( optarg[1] )
589 {
590 args->clevel = strtol(optarg+1,&tmp,10);
591 if ( *tmp || args->clevel<0 || args->clevel>9 ) error("Could not parse argument: --compression-level %s\n", optarg+1);
592 }
593 break;
594 case 's': args->soft_filter = optarg; break;
595 case 'm':
596 if ( strchr(optarg,'x') ) args->annot_mode |= ANNOT_RESET;
597 if ( strchr(optarg,'+') ) args->annot_mode |= ANNOT_ADD;
598 break;
599 case 't': args->targets_list = optarg; break;
600 case 'T': args->targets_list = optarg; targets_is_file = 1; break;
601 case 'r': args->regions_list = optarg; break;
602 case 'R': args->regions_list = optarg; regions_is_file = 1; break;
603 case 'e':
604 if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n");
605 args->filter_str = optarg; args->filter_logic |= FLT_EXCLUDE; break;
606 case 'i':
607 if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n");
608 args->filter_str = optarg; args->filter_logic |= FLT_INCLUDE; break;
609 case 'S':
610 if ( !strcmp(".",optarg) ) args->set_gts = SET_GTS_MISSING;
611 else if ( !strcmp("0",optarg) ) args->set_gts = SET_GTS_REF;
612 else error("The argument to -S not recognised: %s\n", optarg);
613 break;
614 case 9 : args->n_threads = strtol(optarg, 0, 0); break;
615 case 8 : args->record_cmd_line = 0; break;
616 case 3 :
617 regions_overlap = parse_overlap_option(optarg);
618 if ( regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg);
619 break;
620 case 4 :
621 targets_overlap = parse_overlap_option(optarg);
622 if ( targets_overlap < 0 ) error("Could not parse: --targets-overlap %s\n",optarg);
623 break;
624 case 10 : args->mask_list = optarg; break;
625 case 'M' : args->mask_list = optarg; args->mask_is_file = 1; break;
626 case 11 :
627 if ( !strcasecmp(optarg,"0") ) args->mask_overlap = 0;
628 else if ( !strcasecmp(optarg,"1") ) args->mask_overlap = 1;
629 else if ( !strcasecmp(optarg,"2") ) args->mask_overlap = 2;
630 else error("Could not parse: --mask-overlap %s\n",optarg);
631 break;
632 case 'W':
633 if (!(args->write_index = write_index_parse(optarg)))
634 error("Unsupported index format '%s'\n", optarg);
635 break;
636 case 'h':
637 case '?': usage(args); break;
638 default: error("Unknown argument: %s\n", optarg);
639 }
640 }
641
642 if ( args->filter_logic == (FLT_EXCLUDE|FLT_INCLUDE) ) error("Only one of -i or -e can be given.\n");
643 char *fname = NULL;
644 if ( optind>=argc )
645 {
646 if ( !isatty(fileno((FILE *)stdin)) ) fname = "-"; // reading from stdin
647 else usage(args);
648 }
649 else fname = argv[optind];
650
651 if ( args->mask_list && !args->soft_filter ) error("The option --soft-filter is required with --mask and --mask-file options\n");
652
653 // read in the regions from the command line
654 if ( args->regions_list )
655 {
656 args->files->require_index = 1;
657 bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,regions_overlap);
658 if ( bcf_sr_set_regions(args->files, args->regions_list, regions_is_file)<0 )
659 error("Failed to read the regions: %s\n", args->regions_list);
660 }
661 else if ( optind+1 < argc )
662 {
663 int i;
664 kstring_t tmp = {0,0,0};
665 kputs(argv[optind+1],&tmp);
666 for (i=optind+2; i<argc; i++) { kputc(',',&tmp); kputs(argv[i],&tmp); }
667 args->files->require_index = 1;
668 bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,regions_overlap);
669 if ( bcf_sr_set_regions(args->files, tmp.s, regions_is_file)<0 )
670 error("Failed to read the regions: %s\n", args->regions_list);
671 free(tmp.s);
672 }
673 if ( args->targets_list )
674 {
675 bcf_sr_set_opt(args->files,BCF_SR_TARGETS_OVERLAP,targets_overlap);
676 if ( bcf_sr_set_targets(args->files, args->targets_list,targets_is_file, 0)<0 )
677 error("Failed to read the targets: %s\n", args->targets_list);
678 }
679 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));
680
681 init_data(args);
682 if ( bcf_hdr_write(args->out_fh, args->hdr)!=0 ) error("[%s] Error: cannot write the header to %s\n", __func__,args->output_fname);
683 if ( init_index2(args->out_fh,args->hdr,args->output_fname,&args->index_fn,
684 args->write_index)<0 )
685 error("Error: failed to initialise index for %s\n",args->output_fname);
686 while ( bcf_sr_next_line(args->files) )
687 {
688 bcf1_t *line = bcf_sr_get_line(args->files, 0);
689 int pass = 1;
690 if ( args->filter )
691 {
692 pass = filter_test(args->filter, line, &args->smpl_pass);
693 if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1;
694 }
695 if ( args->mask )
696 {
697 hts_pos_t beg, end;
698 if ( args->mask_overlap==0 ) beg = end = line->pos;
699 else if ( args->mask_overlap==1 ) beg = line->pos, end = line->pos + line->rlen - 1;
700 else _set_variant_boundaries(line,&beg,&end);
701 int mpass = regidx_overlap(args->mask,bcf_seqname(args->hdr,line),beg,end,NULL) ? 0 : 1;
702 if ( args->mask_negate ) mpass = mpass ? 0 : 1;
703 pass &= mpass;
704 }
705 if ( args->soft_filter || args->set_gts || pass )
706 {
707 if ( pass )
708 {
709 bcf_unpack(line,BCF_UN_FLT);
710 if ( args->annot_mode & ANNOT_RESET || !line->d.n_flt ) bcf_add_filter(args->hdr, line, args->flt_pass);
711 }
712 else if ( args->soft_filter )
713 {
714 if ( (args->annot_mode & ANNOT_ADD) ) bcf_add_filter(args->hdr, line, args->flt_fail);
715 else bcf_update_filter(args->hdr, line, &args->flt_fail, 1);
716 }
717 if ( args->set_gts ) set_genotypes(args, line, pass);
718 if ( !args->rbuf_lines )
719 {
720 if ( bcf_write1(args->out_fh, args->hdr, line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname);
721 }
722 else
723 buffered_filters(args, line);
724 }
725 }
726 buffered_filters(args, NULL);
727 if ( args->write_index )
728 {
729 if ( bcf_idx_save(args->out_fh)<0 )
730 {
731 if ( hts_close(args->out_fh)!=0 ) error("Error: close failed .. %s\n", args->output_fname?args->output_fname:"stdout");
732 error("Error: cannot write to index %s\n", args->index_fn);
733 }
734 free(args->index_fn);
735 }
736 if ( hts_close(args->out_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->output_fname);
737 destroy_data(args);
738 bcf_sr_destroy(args->files);
739 free(args);
740 return 0;
741 }