Debian Codegraph @

bcftools/vcfisec.c

raw symbols SCIP
1 /* vcfisec.c -- Create intersections, unions and complements of VCF files.
2
3 Copyright (C) 2012-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 <ctype.h>
29 #include <string.h>
30 #include <errno.h>
31 #include <sys/stat.h>
32 #include <sys/types.h>
33 #include <htslib/vcf.h>
34 #include <htslib/synced_bcf_reader.h>
35 #include <htslib/vcfutils.h>
36 #include <htslib/hts_os.h>
37 #include <htslib/hts_defs.h>
38 #include "bcftools.h"
39 #include "filter.h"
40
41 #define OP_PLUS 1
42 #define OP_MINUS 2
43 #define OP_EQUAL 3
44 #define OP_VENN 4
45 #define OP_COMPLEMENT 5
46 #define OP_EXACT 6
47
48 // Logic of the filters: include or exclude sites which match the filters?
49 #define FLT_INCLUDE 1
50 #define FLT_EXCLUDE 2
51
52 typedef struct
53 {
54 int isec_op, isec_n, *write, iwrite, nwrite, output_type, n_threads, clevel;
55 int nflt, *flt_logic;
56 filter_t **flt;
57 char **flt_expr;
58 bcf_srs_t *files;
59 FILE *fh_log, *fh_sites;
60 htsFile **fh_out;
61 char **argv, *prefix, *output_fname, **fnames, *write_files, *targets_list, *regions_list;
62 char *isec_exact, *file_list;
63 int argc, record_cmd_line;
64 char *index_fn;
65 int write_index;
66 }
67 args_t;
68
69 /**
70 * mkdir_p() - create new directory for a file $fname
71 * @fname: the file name to create the directory for, the part after last "/" is ignored
72 */
73 void HTS_FORMAT(HTS_PRINTF_FMT, 1, 2)
74 mkdir_p(const char *fmt, ...)
75 {
76 va_list ap;
77 va_start(ap, fmt);
78 int n = vsnprintf(NULL, 0, fmt, ap) + 2;
79 va_end(ap);
80
81 char *tmp = (char*)malloc(n);
82 if (!tmp) error("Couldn't allocate space for path: %s\n", strerror(errno));
83 va_start(ap, fmt);
84 vsnprintf(tmp, n, fmt, ap);
85 va_end(ap);
86
87 char *p = tmp+1;
88 while (*p)
89 {
90 while (*p && *p!='/') p++;
91 if ( !*p ) break;
92 char ctmp = *p;
93 *p = 0;
94 int ret = mkdir(tmp,S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
95 if ( ret!=0 && errno!=EEXIST ) error("Error creating directory %s: %s\n", tmp,strerror(errno));
96 *p = ctmp;
97 while ( *p && *p=='/' ) p++;
98 }
99 free(tmp);
100 }
101
102 /**
103 * open_file() - open new file creating the file name using vsnprintf
104 * @fname: if not NULL, on output will point to newly allocated fname string
105 * @mode: if NULL, only the file name string will be created
106 * @fmt: vsnprintf format and args
107 *
108 * Returns open file descriptor or NULL if mode is NULL.
109 */
110 FILE * HTS_FORMAT(HTS_PRINTF_FMT, 3, 4)
111 open_file(char **fname, const char *mode, const char *fmt, ...)
112 {
113 va_list ap;
114 va_start(ap, fmt);
115 int n = vsnprintf(NULL, 0, fmt, ap) + 2;
116 va_end(ap);
117
118 char *str = (char*)malloc(n);
119 va_start(ap, fmt);
120 vsnprintf(str, n, fmt, ap);
121 va_end(ap);
122
123 mkdir_p("%s", str);
124 if ( !mode )
125 {
126 if ( !fname ) error("Uh: expected fname or mode\n");
127 *fname = str;
128 return NULL;
129 }
130
131 FILE *fp = fopen(str,mode);
132 if ( fname ) *fname = str;
133 else free(str);
134 return fp;
135 }
136
137 void isec_vcf(args_t *args)
138 {
139 bcf_srs_t *files = args->files;
140 kstring_t str = {0,0,0};
141 htsFile *out_fh = NULL;
142
143 // When only one VCF is output, print VCF to stdout or -o file
144 int out_std = 0;
145 if ( args->nwrite==1 && !args->prefix ) out_std = 1;
146 if ( args->targets_list && files->nreaders==1 ) out_std = 1;
147 if ( out_std )
148 {
149 char wmode[8];
150 set_wmode(wmode,args->output_type,args->output_fname,args->clevel);
151 out_fh = hts_open(args->output_fname ? args->output_fname : "-", wmode);
152 if ( out_fh == NULL ) error("Can't write to %s: %s\n", args->output_fname? args->output_fname : "standard output", strerror(errno));
153 if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads);
154 if (args->record_cmd_line) bcf_hdr_append_version(files->readers[args->iwrite].header,args->argc,args->argv,"bcftools_isec");
155 if ( bcf_hdr_write(out_fh, files->readers[args->iwrite].header)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname?args->output_fname:"standard output");
156 if ( init_index2(out_fh,files->readers[args->iwrite].header,
157 args->output_fname,&args->index_fn,
158 args->write_index)<0 )
159 error("Error: failed to initialise index for %s\n",
160 args->output_fname?args->output_fname:"standard output");
161 }
162 if ( !args->nwrite && !out_std && !args->prefix )
163 fprintf(stderr,"Note: -w option not given, printing list of sites...\n");
164
165 int n;
166 while ( (n=bcf_sr_next_line(files)) )
167 {
168 bcf_sr_t *reader = NULL;
169 bcf1_t *line = NULL;
170 int i, ret = 0;
171 for (i=0; i<files->nreaders; i++)
172 {
173 if ( !bcf_sr_has_line(files,i) ) continue;
174
175 if ( args->nflt && args->flt[i] )
176 {
177 bcf1_t *rec = bcf_sr_get_line(files, i);
178 int pass = filter_test(args->flt[i], rec, NULL);
179 if ( args->flt_logic[i] & FLT_EXCLUDE ) pass = pass ? 0 : 1;
180 if ( !pass )
181 {
182 files->has_line[i] = 0;
183 n--;
184 continue;
185 }
186 }
187
188 if ( !line )
189 {
190 line = files->readers[i].buffer[0];
191 reader = &files->readers[i];
192 }
193 ret |= 1<<i; // this may overflow for many files, but will be used only with two (OP_VENN)
194 }
195 if ( !line ) continue; // the site has been filtered in all files
196
197 switch (args->isec_op)
198 {
199 case OP_COMPLEMENT: if ( n!=1 || !bcf_sr_has_line(files,0) ) continue; break;
200 case OP_EQUAL: if ( n != args->isec_n ) continue; break;
201 case OP_PLUS: if ( n < args->isec_n ) continue; break;
202 case OP_MINUS: if ( n > args->isec_n ) continue; break;
203 case OP_EXACT:
204 for (i=0; i<files->nreaders; i++)
205 if ( files->has_line[i] != args->isec_exact[i] ) break;
206 if ( i<files->nreaders ) continue;
207 break;
208 }
209
210 if ( out_std )
211 {
212 if ( bcf_sr_has_line(files,args->iwrite) && bcf_write1(out_fh, files->readers[args->iwrite].header, files->readers[args->iwrite].buffer[0])!=0 )
213 error("[%s] Error: cannot write to %s\n", __func__, args->output_fname ? args->output_fname : "standard output");
214 continue;
215 }
216 else if ( args->fh_sites )
217 {
218 str.l = 0;
219 kputs(reader->header->id[BCF_DT_CTG][line->rid].key, &str); kputc('\t', &str);
220 kputw(line->pos+1, &str); kputc('\t', &str);
221 if (line->n_allele > 0) kputs(line->d.allele[0], &str);
222 else kputc('.', &str);
223 kputc('\t', &str);
224 if (line->n_allele > 1) kputs(line->d.allele[1], &str);
225 else kputc('.', &str);
226 for (i=2; i<line->n_allele; i++)
227 {
228 kputc(',', &str);
229 kputs(line->d.allele[i], &str);
230 }
231 kputc('\t', &str);
232 for (i=0; i<files->nreaders; i++)
233 kputc(bcf_sr_has_line(files,i)?'1':'0', &str);
234 kputc('\n', &str);
235 if ( fwrite(str.s,sizeof(char),str.l,args->fh_sites)!=str.l )
236 error("[%s] Error: failed to write %d bytes to %s\n", __func__,(int)str.l,args->output_fname ? args->output_fname : "standard output");
237 }
238
239 if ( args->prefix )
240 {
241 if ( args->isec_op==OP_VENN && ret==3 )
242 {
243 if ( !args->nwrite || args->write[0] )
244 {
245 if ( bcf_write1(args->fh_out[2], bcf_sr_get_header(files,0), bcf_sr_get_line(files,0))!=0 )
246 error("[%s] Error: cannot write\n", __func__);
247 }
248 if ( !args->nwrite || args->write[1] )
249 {
250 if ( bcf_write1(args->fh_out[3], bcf_sr_get_header(files,1), bcf_sr_get_line(files,1))!=0 )
251 error("[%s] Error: cannot write\n", __func__);
252 }
253 }
254 else
255 {
256 for (i=0; i<files->nreaders; i++)
257 {
258 if ( !bcf_sr_has_line(files,i) ) continue;
259 if ( args->write && !args->write[i] ) continue;
260 if ( bcf_write1(args->fh_out[i], files->readers[i].header, files->readers[i].buffer[0])!=0 ) error("[%s] Error: cannot write\n", __func__);
261 }
262 }
263 }
264 }
265 if ( str.s ) free(str.s);
266 if ( out_fh )
267 {
268 if ( args->write_index )
269 {
270 if ( bcf_idx_save(out_fh)<0 )
271 {
272 if ( hts_close(out_fh)!=0 ) error("Error: close failed .. %s\n", args->output_fname?args->output_fname:"stdout");
273 error("Error: cannot write to index %s\n", args->index_fn);
274 }
275 free(args->index_fn);
276 }
277 if ( hts_close(out_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->output_fname? args->output_fname : "-");
278 }
279 }
280
281 static void add_filter(args_t *args, char *expr, int logic)
282 {
283 args->nflt++;
284 args->flt_expr = (char**) realloc(args->flt_expr,sizeof(char*)*args->nflt);
285 args->flt_logic = (int*) realloc(args->flt_logic,sizeof(int)*args->nflt);
286 args->flt = (filter_t**) realloc(args->flt,sizeof(filter_t*)*args->nflt);
287 if ( expr[0]=='-' && expr[1]==0 )
288 {
289 args->flt_expr[args->nflt-1] = NULL;
290 args->flt[args->nflt-1] = NULL;
291 }
292 else
293 args->flt_expr[args->nflt-1] = expr;
294 args->flt_logic[args->nflt-1] = logic;
295 }
296
297 static void destroy_data(args_t *args);
298 static void init_data(args_t *args)
299 {
300 int i;
301 if ( args->nflt )
302 {
303 if ( args->nflt > 1 && args->nflt!=args->files->nreaders )
304 error("Error: expected either one -i/-e option or as many as there are input files\n");
305 if ( args->nflt < args->files->nreaders )
306 {
307 if ( !args->flt_expr[0] ) error("Error: useless use of -i/-e\n");
308 args->nflt = args->files->nreaders;
309 args->flt_expr = (char**) realloc(args->flt_expr,sizeof(char*)*args->nflt);
310 args->flt_logic = (int*) realloc(args->flt_logic,sizeof(int)*args->nflt);
311 args->flt = (filter_t**) realloc(args->flt,sizeof(filter_t*)*args->nflt);
312 for (i=1; i<args->nflt; i++)
313 {
314 args->flt_expr[i] = args->flt_expr[0];
315 args->flt_logic[i] = args->flt_logic[0];
316 args->flt[i] = filter_init(args->files->readers[i].header,args->flt_expr[i]);
317 }
318 args->flt[0] = filter_init(args->files->readers[0].header,args->flt_expr[0]);
319 }
320 else
321 {
322 for (i=0; i<args->files->nreaders; i++)
323 {
324 if ( !args->flt_expr[i] ) continue;
325 args->flt[i] = filter_init(args->files->readers[i].header,args->flt_expr[i]);
326 }
327 }
328 }
329
330 if ( args->isec_op==OP_EXACT )
331 {
332 if ( strlen(args->isec_exact)!=args->files->nreaders )
333 error("The number of files does not match the bitmask: %d vs %s\n", args->files->nreaders,args->isec_exact);
334 for (i=0; i<args->files->nreaders; i++)
335 if ( args->isec_exact[i]!='0' && args->isec_exact[i]!='1' ) error("Unexpected bitmask: %s\n",args->isec_exact);
336 for (i=0; i<args->files->nreaders; i++)
337 args->isec_exact[i] -= '0';
338 }
339
340 // Which files to write: parse the string passed with -w
341 char *p = args->write_files;
342 while (p && *p)
343 {
344 if ( !args->write ) args->write = (int*) calloc(args->files->nreaders,sizeof(int));
345 if ( sscanf(p,"%d",&i)!=1 ) error("Could not parse --write %s\n", args->write_files);
346 if ( i<=0 || i>args->files->nreaders ) error("The index is out of range: %d (-w %s)\n", i, args->write_files);
347 args->write[i-1] = 1;
348 args->iwrite = i-1;
349 args->nwrite++;
350 while (*p && *p!=',') p++;
351 if ( *p==',' ) p++;
352 }
353 if ( args->nwrite>1 && !args->prefix ) error("Expected -p when multiple output files given: --write %s\n", args->write_files);
354 if ( args->isec_op==OP_COMPLEMENT && args->nwrite )
355 {
356 if ( args->nwrite>1 ) error("Multiple files to -w make no sense with -C\n");
357 if ( !args->write[0] ) error("Only -w1 makes sense with -C\n");
358 }
359
360 if ( args->prefix )
361 {
362 // Init output directory and create the readme file
363 args->fh_log = open_file(NULL,"w","%s/README.txt", args->prefix);
364 if ( !args->fh_log ) error("%s/README.txt: %s\n", args->prefix, strerror(errno));
365
366 fprintf(args->fh_log,"This file was produced by vcfisec.\n");
367 fprintf(args->fh_log,"The command line was:\tbcftools %s ", args->argv[0]);
368 int i;
369 for (i=1; i<args->argc; i++) fprintf(args->fh_log," %s",args->argv[i]);
370 fprintf(args->fh_log,"\n\nUsing the following file names:\n");
371
372 const char *suffix = "vcf";
373 if ( args->output_type & FT_BCF ) suffix = "bcf";
374 else if ( args->output_type & FT_GZ ) suffix = "vcf.gz";
375
376 // Open output files and write the legend
377 if ( args->isec_op==OP_VENN )
378 {
379 args->fh_out = (htsFile**) malloc(sizeof(htsFile*)*4);
380 args->fnames = (char**) calloc(4,sizeof(char*));
381
382 #define OPEN_FILE(i,j) { \
383 open_file(&args->fnames[i], NULL, "%s/%04d.%s", args->prefix, i, suffix); \
384 char wmode[8]; \
385 set_wmode(wmode,args->output_type,args->fnames[i],args->clevel); \
386 args->fh_out[i] = hts_open(args->fnames[i], wmode); \
387 if ( !args->fh_out[i] ) error("Could not open %s\n", args->fnames[i]); \
388 if ( args->n_threads ) hts_set_threads(args->fh_out[i], args->n_threads); \
389 if (args->record_cmd_line) bcf_hdr_append_version(args->files->readers[j].header,args->argc,args->argv,"bcftools_isec"); \
390 if ( bcf_hdr_write(args->fh_out[i], args->files->readers[j].header)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->fnames[i]); \
391 }
392 if ( !args->nwrite || args->write[0] )
393 {
394 OPEN_FILE(0,0);
395 fprintf(args->fh_log,"%s\tfor records private to\t%s\n", args->fnames[0], args->files->readers[0].fname);
396 }
397 if ( !args->nwrite || args->write[1] )
398 {
399 OPEN_FILE(1,1);
400 fprintf(args->fh_log,"%s\tfor records private to\t%s\n", args->fnames[1], args->files->readers[1].fname);
401 }
402 if ( !args->nwrite || args->write[0] )
403 {
404 OPEN_FILE(2,0);
405 fprintf(args->fh_log,"%s\tfor records from %s shared by both\t%s %s\n", args->fnames[2], args->files->readers[0].fname, args->files->readers[0].fname, args->files->readers[1].fname);
406 }
407 if ( !args->nwrite || args->write[1] )
408 {
409 OPEN_FILE(3,1);
410 fprintf(args->fh_log,"%s\tfor records from %s shared by both\t%s %s\n", args->fnames[3], args->files->readers[1].fname, args->files->readers[0].fname, args->files->readers[1].fname);
411 }
412 }
413 else
414 {
415 // Init one output file for each reader
416 args->fh_out = (htsFile**) calloc(args->files->nreaders, sizeof(htsFile*));
417 args->fnames = (char**) calloc(args->files->nreaders, sizeof(char*));
418
419 for (i=0; i<args->files->nreaders; i++)
420 {
421 if ( args->write && !args->write[i] ) continue;
422 if ( args->isec_op==OP_COMPLEMENT && i>0 ) break;
423 OPEN_FILE(i,i);
424 fprintf(args->fh_log,"%s\tfor stripped\t%s\n", args->fnames[i], args->files->readers[i].fname);
425 }
426 #undef OPEN_FILE
427 }
428 args->fh_sites = open_file(NULL, "w", "%s/sites.txt", args->prefix);
429 if ( !args->fh_sites ) error("%s/sites.txt: %s\n", args->prefix, strerror(errno));
430 }
431 else {
432 if (args->output_fname) {
433 args->fh_sites = fopen(args->output_fname, "w");
434 if ( args->fh_sites == NULL ) error("Can't write to \"%s\": %s\n", args->output_fname, strerror(errno));
435 }
436 else
437 args->fh_sites = stdout;
438 }
439 }
440
441 static void destroy_data(args_t *args)
442 {
443 int i;
444 if ( args->nflt )
445 {
446 for (i=0; i<args->nflt; i++)
447 {
448 if ( !args->flt[i] ) continue;
449 filter_destroy(args->flt[i]);
450 }
451 free(args->flt_expr);
452 free(args->flt);
453 free(args->flt_logic);
454 }
455 if ( args->prefix )
456 {
457 fclose(args->fh_log);
458 int n = args->isec_op==OP_VENN ? 4 : args->files->nreaders;
459 for (i=0; i<n; i++)
460 {
461 if ( !args->fnames[i] ) continue;
462 if ( hts_close(args->fh_out[i])!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->fnames[i]);
463 int is_tbi = !args->write_index
464 || (args->write_index&127) == HTS_FMT_TBI;
465 if ( args->output_type==FT_VCF_GZ && is_tbi )
466 {
467 tbx_conf_t conf = tbx_conf_vcf;
468 tbx_index_build(args->fnames[i], -1, &conf);
469 }
470 else if ( args->output_type==FT_BCF_GZ || !is_tbi )
471 {
472 if ( bcf_index_build(args->fnames[i],14) ) error("Could not index %s\n", args->fnames[i]);
473 }
474 free(args->fnames[i]);
475 }
476 free(args->fh_out);
477 free(args->fnames);
478 if ( args->fh_sites ) fclose(args->fh_sites);
479 if ( args->write ) free(args->write);
480 }
481 }
482
483 static void usage(void)
484 {
485 fprintf(stderr, "\n");
486 fprintf(stderr, "About: Create intersections, unions and complements of VCF files.\n");
487 fprintf(stderr, "Usage: bcftools isec [options] <A.vcf.gz> <B.vcf.gz> [...]\n");
488 fprintf(stderr, "\n");
489 fprintf(stderr, "Options:\n");
490 fprintf(stderr, " -c, --collapse STRING Treat as identical records with <snps|indels|both|all|some|none>, see man page for details [none]\n");
491 fprintf(stderr, " -C, --complement Output positions present only in the first file but missing in the others\n");
492 fprintf(stderr, " -e, --exclude EXPR Exclude sites for which the expression is true\n");
493 fprintf(stderr, " -f, --apply-filters LIST Require at least one of the listed FILTER strings (e.g. \"PASS,.\")\n");
494 fprintf(stderr, " -i, --include EXPR Include only sites for which the expression is true\n");
495 fprintf(stderr, " -l, --file-list FILE Read the input file names from the file\n");
496 fprintf(stderr, " --no-version Do not append version and command line to the header\n");
497 fprintf(stderr, " -n, --nfiles [+-=~]INT Output positions present in this many (=), this many or more (+), this many or fewer (-), the exact (~) files\n");
498 fprintf(stderr, " -o, --output FILE Write output to a file [standard output]\n");
499 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");
500 fprintf(stderr, " -p, --prefix DIR If given, subset each of the input files accordingly, see also -w\n");
501 fprintf(stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n");
502 fprintf(stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n");
503 fprintf(stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n");
504 fprintf(stderr, " -t, --targets REGION Similar to -r but streams rather than index-jumps\n");
505 fprintf(stderr, " -T, --targets-file FILE Similar to -R but streams rather than index-jumps\n");
506 fprintf(stderr, " --targets-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [0]\n");
507 fprintf(stderr, " --threads INT Use multithreading with <int> worker threads [0]\n");
508 fprintf(stderr, " -w, --write LIST List of files to write with -p given as 1-based indexes. By default, all files are written\n");
509 fprintf(stderr, " -W, --write-index[=FMT] Automatically index the output files [off]\n");
510 fprintf(stderr, "\n");
511 fprintf(stderr, "Examples:\n");
512 fprintf(stderr, " # Create intersection and complements of two sets saving the output in dir/*\n");
513 fprintf(stderr, " bcftools isec A.vcf.gz B.vcf.gz -p dir\n");
514 fprintf(stderr, "\n");
515 fprintf(stderr, " # Filter sites in A and B (but not in C) and create intersection\n");
516 fprintf(stderr, " bcftools isec -e'MAF<0.01' -i'dbSNP=1' -e - A.vcf.gz B.vcf.gz C.vcf.gz -p dir\n");
517 fprintf(stderr, "\n");
518 fprintf(stderr, " # Extract and write records from A shared by both A and B using exact allele match\n");
519 fprintf(stderr, " bcftools isec A.vcf.gz B.vcf.gz -p dir -n =2 -w 1\n");
520 fprintf(stderr, "\n");
521 fprintf(stderr, " # Extract and write records from C found in A and C but not in B\n");
522 fprintf(stderr, " bcftools isec A.vcf.gz B.vcf.gz C.vcf.gz -p dir -n~101 -w 3\n");
523 fprintf(stderr, "\n");
524 fprintf(stderr, " # Extract records private to A or B comparing by position only\n");
525 fprintf(stderr, " bcftools isec A.vcf.gz B.vcf.gz -p dir -n -1 -c all\n");
526 fprintf(stderr, "\n");
527 exit(1);
528 }
529
530 int main_vcfisec(int argc, char *argv[])
531 {
532 int c;
533 args_t *args = (args_t*) calloc(1,sizeof(args_t));
534 args->files = bcf_sr_init();
535 args->argc = argc; args->argv = argv;
536 args->output_fname = NULL;
537 args->output_type = FT_VCF;
538 args->n_threads = 0;
539 args->record_cmd_line = 1;
540 args->clevel = -1;
541 int targets_is_file = 0, regions_is_file = 0;
542 int regions_overlap = 1;
543 int targets_overlap = 0;
544
545 static struct option loptions[] =
546 {
547 {"help",no_argument,NULL,'h'},
548 {"exclude",required_argument,NULL,'e'},
549 {"include",required_argument,NULL,'i'},
550 {"collapse",required_argument,NULL,'c'},
551 {"complement",no_argument,NULL,'C'},
552 {"apply-filters",required_argument,NULL,'f'},
553 {"file-list",required_argument,NULL,'l'},
554 {"nfiles",required_argument,NULL,'n'},
555 {"prefix",required_argument,NULL,'p'},
556 {"write",required_argument,NULL,'w'},
557 {"targets",required_argument,NULL,'t'},
558 {"targets-file",required_argument,NULL,'T'},
559 {"targets-overlap",required_argument,NULL,4},
560 {"regions",required_argument,NULL,'r'},
561 {"regions-file",required_argument,NULL,'R'},
562 {"regions-overlap",required_argument,NULL,3},
563 {"output",required_argument,NULL,'o'},
564 {"output-type",required_argument,NULL,'O'},
565 {"threads",required_argument,NULL,9},
566 {"no-version",no_argument,NULL,8},
567 {"write-index",optional_argument,NULL,'W'},
568 {NULL,0,NULL,0}
569 };
570 char *tmp;
571 while ((c = getopt_long(argc, argv, "hc:r:R:p:n:w:t:T:Cf:o:O:i:e:l:W::",loptions,NULL)) >= 0) {
572 switch (c) {
573 case 'o': args->output_fname = optarg; break;
574 case 'O':
575 switch (optarg[0]) {
576 case 'b': args->output_type = FT_BCF_GZ; break;
577 case 'u': args->output_type = FT_BCF; break;
578 case 'z': args->output_type = FT_VCF_GZ; break;
579 case 'v': args->output_type = FT_VCF; break;
580 default:
581 {
582 args->clevel = strtol(optarg,&tmp,10);
583 if ( *tmp || args->clevel<0 || args->clevel>9 ) error("The output type \"%s\" not recognised\n", optarg);
584 }
585 }
586 if ( optarg[1] )
587 {
588 args->clevel = strtol(optarg+1,&tmp,10);
589 if ( *tmp || args->clevel<0 || args->clevel>9 ) error("Could not parse argument: --compression-level %s\n", optarg+1);
590 }
591 break;
592 case 'c':
593 if ( !strcmp(optarg,"snps") ) args->files->collapse |= COLLAPSE_SNPS;
594 else if ( !strcmp(optarg,"indels") ) args->files->collapse |= COLLAPSE_INDELS;
595 else if ( !strcmp(optarg,"both") ) args->files->collapse |= COLLAPSE_SNPS | COLLAPSE_INDELS;
596 else if ( !strcmp(optarg,"any") ) args->files->collapse |= COLLAPSE_ANY;
597 else if ( !strcmp(optarg,"all") ) args->files->collapse |= COLLAPSE_ANY;
598 else if ( !strcmp(optarg,"some") ) args->files->collapse |= COLLAPSE_SOME;
599 else if ( !strcmp(optarg,"none") ) args->files->collapse = COLLAPSE_NONE;
600 else error("The --collapse string \"%s\" not recognised.\n", optarg);
601 break;
602 case 'f': args->files->apply_filters = optarg; break;
603 case 'C':
604 if ( args->isec_op!=0 && args->isec_op!=OP_COMPLEMENT ) error("Error: either -C or -n should be given, not both.\n");
605 args->isec_op = OP_COMPLEMENT; break;
606 case 'l': args->file_list = optarg; break;
607 case 'r': args->regions_list = optarg; break;
608 case 'R': args->regions_list = optarg; regions_is_file = 1; break;
609 case 't': args->targets_list = optarg; break;
610 case 'T': args->targets_list = optarg; targets_is_file = 1; break;
611 case 'p': args->prefix = optarg; break;
612 case 'w':
613 if ( args->write_files ) error("The option -w accepts a list of indices and can be given only once\n");
614 args->write_files = optarg;
615 break;
616 case 'i': add_filter(args, optarg, FLT_INCLUDE); break;
617 case 'e': add_filter(args, optarg, FLT_EXCLUDE); break;
618 case 'n':
619 {
620 if ( args->isec_op!=0 && args->isec_op==OP_COMPLEMENT ) error("Error: either -C or -n should be given, not both.\n");
621 if ( args->isec_op!=0 ) error("Error: -n should be given only once.\n");
622 char *p = optarg;
623 if ( *p=='-' ) { args->isec_op = OP_MINUS; p++; }
624 else if ( *p=='+' ) { args->isec_op = OP_PLUS; p++; }
625 else if ( *p=='=' ) { args->isec_op = OP_EQUAL; p++; }
626 else if ( *p=='~' ) { args->isec_op = OP_EXACT; p++; }
627 else if ( isdigit(*p) ) args->isec_op = OP_EQUAL;
628 else error("Could not parse --nfiles %s\n", optarg);
629 if ( args->isec_op == OP_EXACT ) args->isec_exact = p;
630 else if ( sscanf(p,"%d",&args->isec_n)!=1 ) error("Could not parse --nfiles %s\n", optarg);
631 }
632 break;
633 case 3 :
634 regions_overlap = parse_overlap_option(optarg);
635 if ( regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg);
636 break;
637 case 4 :
638 targets_overlap = parse_overlap_option(optarg);
639 if ( targets_overlap < 0 ) error("Could not parse: --targets-overlap %s\n",optarg);
640 break;
641 case 9 : args->n_threads = strtol(optarg, 0, 0); break;
642 case 8 : args->record_cmd_line = 0; break;
643 case 'W':
644 if (!(args->write_index = write_index_parse(optarg)))
645 error("Unsupported index format '%s'\n", optarg);
646 break;
647 case 'h':
648 case '?': usage(); break;
649 default: error("Unknown argument: %s\n", optarg);
650 }
651 }
652 if ( argc-optind<1 && !args->file_list ) usage(); // no file given
653
654 int nfiles = 0,i;
655 char **files = NULL;
656 if ( args->file_list )
657 {
658 files = hts_readlines(args->file_list, &nfiles);
659 if ( !files ) error("Failed to read from %s\n", args->file_list);
660 }
661 if ( optind<argc )
662 {
663 int n = argc - optind;
664 files = (char**)realloc(files,sizeof(*files)*(n+nfiles));
665 for (i=nfiles; i>0; i--) files[n+i-1] = files[n+i-2];
666 for (i=0; i<n; i++) files[i] = strdup(argv[optind+i]);
667 nfiles += n;
668 }
669
670 if ( args->targets_list )
671 {
672 bcf_sr_set_opt(args->files,BCF_SR_TARGETS_OVERLAP,targets_overlap);
673 if ( bcf_sr_set_targets(args->files, args->targets_list, targets_is_file,0)<0 )
674 error("Failed to read the targets: %s\n", args->targets_list);
675 }
676 if ( args->regions_list )
677 {
678 bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,regions_overlap);
679 if ( bcf_sr_set_regions(args->files, args->regions_list, regions_is_file)<0 )
680 error("Failed to read the regions: %s\n", args->regions_list);
681 }
682 if ( nfiles==2 && !args->isec_op )
683 {
684 args->isec_op = OP_VENN;
685 if ( !args->prefix ) error("Expected the -p option\n");
686 }
687 if ( !args->isec_op )
688 {
689 args->isec_op = OP_PLUS;
690 args->isec_n = 1;
691 }
692 args->files->require_index = 1;
693 for (i=0; i<nfiles; i++)
694 {
695 if ( !bcf_sr_add_reader(args->files, files[i]) ) error("Failed to open %s: %s\n", files[i],bcf_sr_strerror(args->files->errnum));
696 free(files[i]);
697 }
698 free(files);
699
700 init_data(args);
701 isec_vcf(args);
702 destroy_data(args);
703 bcf_sr_destroy(args->files);
704 free(args);
705 return 0;
706 }
707