Debian Codegraph @

bcftools/vcfconvert.c

raw symbols SCIP
1 /* vcfconvert.c -- convert between VCF/BCF and related formats.
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 <strings.h>
27 #include <unistd.h>
28 #include <getopt.h>
29 #include <ctype.h>
30 #include <string.h>
31 #include <errno.h>
32 #include <sys/stat.h>
33 #include <sys/types.h>
34 #include <stdint.h>
35 #include <inttypes.h>
36 #include <htslib/faidx.h>
37 #include <htslib/vcf.h>
38 #include <htslib/bgzf.h>
39 #include <htslib/synced_bcf_reader.h>
40 #include <htslib/vcfutils.h>
41 #include <htslib/kseq.h>
42 #include <htslib/hts_endian.h>
43 #include "bcftools.h"
44 #include "filter.h"
45 #include "convert.h"
46 #include "tsv2vcf.h"
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 _args_t args_t;
53 struct _args_t
54 {
55 faidx_t *ref;
56 filter_t *filter;
57 char *filter_str;
58 int filter_logic; // include or exclude sites which match the filters? One of FLT_INCLUDE/FLT_EXCLUDE
59 convert_t *convert;
60 bcf_srs_t *files;
61 bcf_hdr_t *header;
62 void (*convert_func)(struct _args_t *);
63 struct {
64 int total, skipped, hom_rr, het_ra, hom_aa, het_aa, missing, written;
65 } n;
66 kstring_t str;
67 int32_t *gts;
68 float *flt;
69 int rev_als, output_vcf_ids, hap2dip, gen_3N6;
70 int nsamples, *samples, sample_is_file, targets_is_file, regions_is_file, output_type;
71 int regions_overlap, targets_overlap;
72 char **argv, *sample_list, *targets_list, *regions_list, *tag, *columns;
73 char *outfname, *infname, *ref_fname, *sex_fname;
74 int argc, n_threads, record_cmd_line, keep_duplicates, clevel;
75 char *index_fn;
76 int write_index;
77 struct {
78 kstring_t ref,alt,refalt;
79 } tsv;
80 };
81
82 static void destroy_data(args_t *args)
83 {
84 if ( args->ref ) fai_destroy(args->ref);
85 if ( args->convert) convert_destroy(args->convert);
86 if ( args->filter ) filter_destroy(args->filter);
87 free(args->samples);
88 if ( args->files ) bcf_sr_destroy(args->files);
89 }
90
91 static void open_vcf(args_t *args, const char *format_str)
92 {
93 args->files = bcf_sr_init();
94 if ( args->n_threads && bcf_sr_set_threads(args->files, args->n_threads)!=0 )
95 error("Could not initialize --threads %d\n", args->n_threads);
96
97 if ( args->regions_list )
98 {
99 bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,args->regions_overlap);
100 if ( bcf_sr_set_regions(args->files, args->regions_list, args->regions_is_file)<0 )
101 error("Failed to read the regions: %s\n", args->regions_list);
102 }
103 if ( args->targets_list )
104 {
105 bcf_sr_set_opt(args->files,BCF_SR_TARGETS_OVERLAP,args->targets_overlap);
106 if ( bcf_sr_set_targets(args->files, args->targets_list, args->targets_is_file, 0)<0 )
107 error("Failed to read the targets: %s\n", args->targets_list);
108 }
109 if ( !bcf_sr_add_reader(args->files, args->infname) )
110 error("Failed to open %s: %s\n", args->infname,bcf_sr_strerror(args->files->errnum));
111
112 args->header = args->files->readers[0].header;
113
114 if ( args->filter_str )
115 args->filter = filter_init(args->header, args->filter_str);
116
117 int i, nsamples = 0, *samples = NULL;
118 if ( args->sample_list && strcmp("-",args->sample_list) )
119 {
120 for (i=0; i<args->files->nreaders; i++)
121 {
122 int ret = bcf_hdr_set_samples(args->files->readers[i].header,args->sample_list,args->sample_is_file);
123 if ( ret<0 ) error("Error parsing the sample list\n");
124 else if ( ret>0 ) error("Sample name mismatch: sample #%d not found in the header\n", ret);
125 }
126
127 if ( args->sample_list[0]!='^' )
128 {
129 // the sample ordering may be different if not negated
130 int n;
131 char **smpls = hts_readlist(args->sample_list, args->sample_is_file, &n);
132 if ( !smpls ) error("Could not parse %s\n", args->sample_list);
133 if ( n!=bcf_hdr_nsamples(args->files->readers[0].header) )
134 error("The number of samples does not match, perhaps some are present multiple times?\n");
135 nsamples = bcf_hdr_nsamples(args->files->readers[0].header);
136 samples = (int*) malloc(sizeof(int)*nsamples);
137 for (i=0; i<n; i++)
138 {
139 samples[i] = bcf_hdr_id2int(args->files->readers[0].header, BCF_DT_SAMPLE,smpls[i]);
140 free(smpls[i]);
141 }
142 free(smpls);
143 }
144 }
145 if ( format_str ) args->convert = convert_init(args->header, samples, nsamples, format_str);
146 free(samples);
147 }
148
149 static int _set_ref_alt(args_t *args, bcf1_t *rec)
150 {
151 args->tsv.refalt.l = 0;
152 kputs(args->tsv.ref.s, &args->tsv.refalt);
153 if ( strcmp(".",args->tsv.alt.s) && strcmp(args->tsv.ref.s,args->tsv.alt.s) )
154 {
155 kputc(',', &args->tsv.refalt);
156 kputs(args->tsv.alt.s, &args->tsv.refalt);
157 }
158 bcf_update_alleles_str(args->header, rec, args->tsv.refalt.s);
159 args->tsv.ref.l = 0;
160 args->tsv.alt.l = 0;
161 args->tsv.refalt.l = 0;
162 return 0;
163 }
164 static int tsv_setter_ref(tsv_t *tsv, bcf1_t *rec, void *usr)
165 {
166 args_t *args = (args_t*) usr;
167 kputsn(tsv->ss,tsv->se - tsv->ss,&args->tsv.ref);
168 if ( args->tsv.alt.l ) return _set_ref_alt(args,rec);
169 return 0;
170 }
171 static int tsv_setter_alt(tsv_t *tsv, bcf1_t *rec, void *usr)
172 {
173 args_t *args = (args_t*) usr;
174 kputsn(tsv->ss,tsv->se - tsv->ss,&args->tsv.alt);
175 if ( args->tsv.ref.l ) return _set_ref_alt(args,rec);
176 return 0;
177 }
178
179 // Try to set CHROM:POS_REF_ALT[_END]. Return 0 on success, -1 on error
180 static int _set_chrom_pos_ref_alt(tsv_t *tsv, bcf1_t *rec, void *usr)
181 {
182 args_t *args = (args_t*) usr;
183
184 char tmp, *se = tsv->ss, *ss = tsv->ss;
185 while ( se < tsv->se && *se!=':' ) se++;
186 if ( *se!=':' ) return -1;
187 tmp = *se; *se = 0;
188 int rid = bcf_hdr_name2id(args->header,ss);
189 *se = tmp;
190 if ( rid<0 ) return -1;
191
192 // POS
193 hts_pos_t pos = strtol(se+1,&ss,10);
194 if ( ss==se+1 ) return -1;
195 pos--;
196
197 // REF,ALT
198 args->str.l = 0;
199 se = ++ss;
200 while ( se < tsv->se && *se!='_' ) se++;
201 if ( *se!='_' ) return -1;
202 kputsn(ss,se-ss,&args->str);
203 ss = ++se;
204 while ( se < tsv->se && *se!='_' && isspace(*tsv->se) ) se++;
205 if ( se < tsv->se && *se!='_' && isspace(*tsv->se) ) return -1;
206 kputc(',',&args->str);
207 kputsn(ss,se-ss,&args->str);
208
209 // END - optional
210 if (*se && *se=='_')
211 {
212 long end = strtol(se+1,&ss,10);
213 if ( ss==se+1 ) return -1;
214 if (end < 1 || end > INT32_MAX)
215 return -1;
216 int32_t e = end; // bcf_update_info_int32 needs an int32_t pointer
217 bcf_update_info_int32(args->header, rec, "END", &e, 1);
218 }
219
220 rec->rid = rid;
221 rec->pos = pos;
222 bcf_update_alleles_str(args->header, rec, args->str.s);
223
224 return 0;
225 }
226 static int tsv_setter_chrom_pos_ref_alt_or_chrom(tsv_t *tsv, bcf1_t *rec, void *usr)
227 {
228 args_t *args = (args_t*)usr;
229 int ret = _set_chrom_pos_ref_alt(tsv,rec,usr);
230 if ( !ret ) return ret;
231 return tsv_setter_chrom(tsv,rec,args->header);
232 }
233 static int tsv_setter_chrom_pos_ref_alt(tsv_t *tsv, bcf1_t *rec, void *usr)
234 {
235 int ret = _set_chrom_pos_ref_alt(tsv,rec,usr);
236 if ( ret!=0 ) error("Could not parse the CHROM:POS_REF_ALT[_END] string: %s\n", tsv->ss);
237 return ret;
238 }
239 // This function must be called first, then tsv_setter_chrom_pos_ref_alt_id_or_die.
240 // One of them is expected to find the CHROM:POS_REF_ALT[_END] string, if not, die.
241 static int tsv_setter_chrom_pos_ref_alt_or_id(tsv_t *tsv, bcf1_t *rec, void *usr)
242 {
243 args_t *args = (args_t*)usr;
244 if ( _set_chrom_pos_ref_alt(tsv,rec,usr)==0 ) return 0;
245 rec->pos = -1; // mark the record as unset
246 if ( !args->output_vcf_ids) return 0;
247 return tsv_setter_id(tsv,rec,usr);
248 }
249 static int tsv_setter_chrom_pos_ref_alt_id_or_die(tsv_t *tsv, bcf1_t *rec, void *usr)
250 {
251 args_t *args = (args_t*)usr;
252 if ( rec->pos!=-1 )
253 {
254 if ( !args->output_vcf_ids ) return 0;
255 return tsv_setter_id(tsv,rec,usr);
256 }
257 return tsv_setter_chrom_pos_ref_alt(tsv,rec,usr);
258 }
259 static int tsv_setter_verify_pos(tsv_t *tsv, bcf1_t *rec, void *usr)
260 {
261 char *se;
262 int pos = strtol(tsv->ss,&se,10);
263 if ( tsv->ss==se ) error("Could not parse POS: %s\n", tsv->ss);
264 if ( rec->pos != pos-1 ) error("POS mismatch: %s\n", tsv->ss);
265 return 0;
266 }
267 static int tsv_setter_verify_ref_alt(tsv_t *tsv, bcf1_t *rec, void *usr)
268 {
269 args_t *args = (args_t*) usr;
270 args->rev_als = 0;
271 char tmp = *tsv->se; *tsv->se = 0;
272 if ( strcmp(tsv->ss,rec->d.allele[0]) )
273 {
274 if ( strcmp(tsv->ss,rec->d.allele[1]) ) { *tsv->se = tmp; error("REF/ALT mismatch: [%s][%s]\n", tsv->ss,rec->d.allele[1]); }
275 args->rev_als = 1;
276 }
277 *tsv->se = tmp;
278 while ( *tsv->se && isspace(*tsv->se) ) tsv->se++;
279 tsv->ss = tsv->se;
280 while ( *tsv->se && !isspace(*tsv->se) ) tsv->se++;
281 tmp = *tsv->se; *tsv->se = 0;
282 if ( !args->rev_als && strcmp(tsv->ss,rec->d.allele[1]) ) { *tsv->se = tmp; error("REF/ALT mismatch: [%s][%s]\n", tsv->ss,rec->d.allele[1]); }
283 else if ( args->rev_als && strcmp(tsv->ss,rec->d.allele[0]) ) { *tsv->se = tmp; error("REF/ALT mismatch: [%s][%s]\n", tsv->ss,rec->d.allele[0]); }
284 *tsv->se = tmp;
285 return 0;
286 }
287 static int tsv_setter_gt_gp(tsv_t *tsv, bcf1_t *rec, void *usr)
288 {
289 args_t *args = (args_t*) usr;
290 int i, nsamples = bcf_hdr_nsamples(args->header);
291 for (i=0; i<nsamples; i++)
292 {
293 float aa,ab,bb;
294 aa = strtod(tsv->ss, &tsv->se);
295 if ( tsv->ss==tsv->se ) { fprintf(stderr,"Could not parse first value of %d-th sample\n", i+1); return -1; }
296 tsv->ss = tsv->se+1;
297 ab = strtod(tsv->ss, &tsv->se);
298 if ( tsv->ss==tsv->se ) { fprintf(stderr,"Could not parse second value of %d-th sample\n", i+1); return -1; }
299 tsv->ss = tsv->se+1;
300 bb = strtod(tsv->ss, &tsv->se);
301 if ( tsv->ss==tsv->se ) { fprintf(stderr,"Could not parse third value of %d-th sample\n", i+1); return -1; }
302 tsv->ss = tsv->se+1;
303
304 if ( args->rev_als ) { float tmp = bb; bb = aa; aa = tmp; }
305 args->flt[3*i+0] = aa;
306 args->flt[3*i+1] = ab;
307 args->flt[3*i+2] = bb;
308
309 if ( aa >= ab )
310 {
311 if ( aa >= bb ) args->gts[2*i+0] = args->gts[2*i+1] = bcf_gt_unphased(0);
312 else args->gts[2*i+0] = args->gts[2*i+1] = bcf_gt_unphased(1);
313 }
314 else if ( ab >= bb )
315 {
316 args->gts[2*i+0] = bcf_gt_unphased(0);
317 args->gts[2*i+1] = bcf_gt_unphased(1);
318 }
319 else args->gts[2*i+0] = args->gts[2*i+1] = bcf_gt_unphased(1);
320 }
321 if ( *tsv->se ) error("Could not parse: %s\n", tsv->ss);
322 if ( bcf_update_genotypes(args->header,rec,args->gts,nsamples*2) ) error("Could not update GT field\n");
323 if ( bcf_update_format_float(args->header,rec,"GP",args->flt,nsamples*3) ) error("Could not update GP field\n");
324 return 0;
325 }
326 static int tsv_setter_haps(tsv_t *tsv, bcf1_t *rec, void *usr)
327 {
328 args_t *args = (args_t*) usr;
329 int i, nsamples = bcf_hdr_nsamples(args->header);
330
331 int32_t a0, a1;
332 if ( args->rev_als ) { a0 = bcf_gt_phased(1); a1 = bcf_gt_phased(0); }
333 else { a0 = bcf_gt_phased(0); a1 = bcf_gt_phased(1); }
334
335 // up is short for "unphased"
336 int nup = 0;
337 for (i=0; i<nsamples; i++)
338 {
339 char *ss = tsv->ss + 4*i + nup;
340 int up = 0, all;
341
342 for (all=0; all < 2; all++){
343 // checking for premature ending
344 if ( !ss[0] || !ss[1] || !ss[2] ||
345 (up && (!ss[3] || !ss[4]) ) )
346 {
347 fprintf(stderr,"Wrong number of fields at %d-th sample ([%c][%c][%c]). ",i+1,ss[0],ss[1],ss[2]);
348 return -1;
349 }
350
351 switch(ss[all*2+up]){
352 case '0':
353 args->gts[2*i+all] = a0;
354 break;
355 case '1' :
356 args->gts[2*i+all] = a1;
357 break;
358 case '?' :
359 // there is no macro to express phased missing allele
360 args->gts[2*i+all] = bcf_gt_phased(-1);
361 break;
362 case '-' :
363 args->gts[2*i+all] = bcf_int32_vector_end;
364 break;
365 default :
366 fprintf(stderr,"Could not parse: [%c][%s]\n", ss[all*2+up],tsv->ss);
367 return -1;
368 }
369 if( ss[all*2+up+1]=='*' ) up = up + 1;
370 }
371
372 if(up && up != 2)
373 {
374 fprintf(stderr,"Missing unphased marker '*': [%c][%s]", ss[2+up], tsv->ss);
375 return -1;
376 }
377
378 // change alleles to unphased if the alleles are unphased
379 if ( up )
380 {
381 args->gts[2*i] = bcf_gt_unphased(bcf_gt_allele(args->gts[2*i]));
382 args->gts[2*i+1] = bcf_gt_unphased(bcf_gt_allele(args->gts[2*i+1]));
383 }
384 nup = nup + up;
385 }
386 if ( tsv->ss[(nsamples-1)*4+3+nup] )
387 {
388 fprintf(stderr,"nup: %d", nup);
389 fprintf(stderr,"Wrong number of fields (%d-th column = [%c]). ", nsamples*2,tsv->ss[(nsamples-1)*4+nup]);
390 return -1;
391 }
392
393 if ( bcf_update_genotypes(args->header,rec,args->gts,nsamples*2) ) error("Could not update GT field\n");
394 return 0;
395 }
396 static void gensample_to_vcf(args_t *args)
397 {
398 /*
399 * Inpute: IMPUTE2 output (indentation changed here for clarity):
400 *
401 * 20:62116619_C_T 20:62116619 62116619 C T 0.969 0.031 0 ...
402 * --- 20:62116698_C_A 62116698 C A 1 0 0 ...
403 *
404 * Second column is expected in the form of CHROM:POS_REF_ALT. We use second
405 * column because the first can be empty ("--") when filling sites from reference
406 * panel. When the option --vcf-ids is given, the first column is used to set the
407 * VCF ID.
408 *
409 * Output: VCF with filled GT,GP
410 *
411 */
412 kstring_t line = {0,0,0};
413
414 char *gen_fname = NULL, *sample_fname = NULL;
415 sample_fname = strchr(args->infname,',');
416 if ( !sample_fname )
417 {
418 args->str.l = 0;
419 ksprintf(&args->str,"%s.gen.gz", args->infname);
420 gen_fname = strdup(args->str.s);
421 args->str.l = 0;
422 ksprintf(&args->str,"%s.samples", args->infname);
423 sample_fname = strdup(args->str.s);
424 }
425 else
426 {
427 *sample_fname = 0;
428 gen_fname = strdup(args->infname);
429 sample_fname = strdup(sample_fname+1);
430 }
431 htsFile *gen_fh = hts_open(gen_fname, "r");
432 if ( !gen_fh ) error("Could not read: %s\n", gen_fname);
433 if ( hts_getline(gen_fh, KS_SEP_LINE, &line) <= 0 ) error("Empty file: %s\n", gen_fname);
434
435 // Find out the chromosome name, depending on the format variant (--3N6 or plain) and the ordering
436 // of the columns (CHROM:POS_REF_ALT comes first or second)
437 args->str.l = 0;
438 char *sb = line.s, *se = line.s;
439 while ( *se && !isspace(*se) ) se++;
440 if ( !*se ) error("Could not determine CHROM in %s: %s\n", gen_fname,line.s);
441 if ( args->gen_3N6 ) // first column, just CHROM
442 kputsn(sb, se-sb, &args->str);
443 else // first or second column, part of CHROM:POS_REF_ALT
444 {
445 char *sc = strchr(sb,':');
446 if ( !sc || sc > se )
447 {
448 while ( *se && !isspace(*se) ) se++;
449 if ( !*se ) error("Could not determine CHROM in %s: %s\n", gen_fname,line.s);
450 sb = ++se;
451 sc = strchr(sb,':');
452 if ( !sc ) error("Could not determine CHROM in %s: %s\n", gen_fname,line.s);
453 }
454 kputsn(sb, sc-sb, &args->str);
455 }
456
457 // Initialize and print the VCF header, args->str.s contains the chr name
458 args->header = bcf_hdr_init("w");
459 bcf_hdr_append(args->header, "##INFO=<ID=END,Number=1,Type=Integer,Description=\"End position of the variant described in this record\">");
460 bcf_hdr_append(args->header, "##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">");
461 bcf_hdr_append(args->header, "##FORMAT=<ID=GP,Number=G,Type=Float,Description=\"Genotype Probabilities\">");
462 bcf_hdr_printf(args->header, "##contig=<ID=%s,length=%d>", args->str.s,0x7fffffff); // MAX_CSI_COOR
463 if (args->record_cmd_line) bcf_hdr_append_version(args->header, args->argc, args->argv, "bcftools_convert");
464
465 tsv_t *tsv;
466 if ( args->gen_3N6 )
467 {
468 tsv = tsv_init("CHROM,CHROM_POS_REF_ALT,ID,POS,REF_ALT,GT_GP");
469 tsv_register(tsv, "CHROM", tsv_setter_chrom, args->header);
470 }
471 else
472 tsv = tsv_init("CHROM_POS_REF_ALT,ID,POS,REF_ALT,GT_GP");
473 tsv_register(tsv, "CHROM_POS_REF_ALT", tsv_setter_chrom_pos_ref_alt_or_id, args);
474 tsv_register(tsv, "ID", tsv_setter_chrom_pos_ref_alt_id_or_die, args);
475 tsv_register(tsv, "POS", tsv_setter_verify_pos, NULL);
476 tsv_register(tsv, "REF_ALT", tsv_setter_verify_ref_alt, args);
477 tsv_register(tsv, "GT_GP", tsv_setter_gt_gp, args);
478
479 // Find out sample names
480 int i, nsamples;
481 char **samples = hts_readlist(sample_fname, 1, &nsamples);
482 if ( !samples ) error("Could not read %s\n", sample_fname);
483 for (i=2; i<nsamples; i++)
484 {
485 se = samples[i]; while ( *se && !isspace(*se) ) se++;
486 *se = 0;
487 bcf_hdr_add_sample(args->header,samples[i]);
488 }
489 for (i=0; i<nsamples; i++) free(samples[i]);
490 free(samples);
491
492 char wmode[8];
493 set_wmode(wmode,args->output_type,args->outfname,args->clevel);
494 htsFile *out_fh = hts_open(args->outfname ? args->outfname : "-", wmode);
495 if ( out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->outfname, strerror(errno));
496 if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads);
497 if ( bcf_hdr_write(out_fh,args->header)!=0 ) error("[%s] Error: cannot write the header to %s\n", __func__,args->outfname);
498 if ( init_index2(out_fh,args->header,args->outfname,&args->index_fn,
499 args->write_index)<0 )
500 error("Error: failed to initialise index for %s\n",args->outfname);
501 bcf1_t *rec = bcf_init();
502
503 nsamples -= 2;
504 args->gts = (int32_t *) malloc(sizeof(int32_t)*nsamples*2);
505 args->flt = (float *) malloc(sizeof(float)*nsamples*3);
506
507 do
508 {
509 bcf_clear(rec);
510 args->n.total++;
511 if ( !tsv_parse(tsv, rec, line.s) )
512 {
513 if ( bcf_write(out_fh, args->header, rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
514 }
515 else
516 error("Error occurred while parsing: %s\n", line.s);
517 }
518 while ( hts_getline(gen_fh, KS_SEP_LINE, &line)>0 );
519
520 if ( args->write_index )
521 {
522 if ( bcf_idx_save(out_fh)<0 )
523 {
524 if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname);
525 error("Error: cannot write to index %s\n", args->index_fn);
526 }
527 free(args->index_fn);
528 }
529 if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname);
530 if ( hts_close(gen_fh) ) error("Close failed: %s\n", gen_fname);
531 bcf_hdr_destroy(args->header);
532 bcf_destroy(rec);
533 free(sample_fname);
534 free(gen_fname);
535 free(args->str.s);
536 free(line.s);
537 free(args->gts);
538 free(args->flt);
539 tsv_destroy(tsv);
540
541 fprintf(stderr,"Number of processed rows: \t%d\n", args->n.total);
542 }
543
544 static void haplegendsample_to_vcf(args_t *args)
545 {
546 /*
547 * Convert from IMPUTE2 hap/legend/sample output files to VCF
548 *
549 * hap:
550 * 0 1 0 1
551 * legend:
552 * id position a0 a1
553 * 1:186946386_G_T 186946386 G T
554 * sample:
555 * sample population group sex
556 * sample1 sample1 sample1 2
557 * sample2 sample2 sample2 2
558 *
559 * Output: VCF with filled GT
560 */
561 kstring_t line = {0,0,0};
562
563 if ( args->output_vcf_ids )
564 error(
565 "The option --haplegendsample2vcf cannot be combined with --vcf-ids. This is because the\n"
566 "ID column must be formatted as \"CHROM:POS_REF_ALT\" to check sanity of the operation\n");
567
568 char *hap_fname = NULL, *leg_fname = NULL, *sample_fname = NULL;
569 sample_fname = strchr(args->infname,',');
570 if ( !sample_fname )
571 {
572 args->str.l = 0;
573 ksprintf(&args->str,"%s.hap.gz", args->infname);
574 hap_fname = strdup(args->str.s);
575 args->str.l = 0;
576 ksprintf(&args->str,"%s.samples", args->infname);
577 sample_fname = strdup(args->str.s);
578 args->str.l = 0;
579 ksprintf(&args->str,"%s.legend.gz", args->infname);
580 leg_fname = strdup(args->str.s);
581 }
582 else
583 {
584 char *ss = sample_fname, *se = strchr(ss+1,',');
585 if ( !se ) error("Could not parse hap/legend/sample file names: %s\n", args->infname);
586 *ss = 0;
587 *se = 0;
588 hap_fname = strdup(args->infname);
589 leg_fname = strdup(ss+1);
590 sample_fname = strdup(se+1);
591 }
592 htsFile *hap_fh = hts_open(hap_fname, "r");
593 if ( !hap_fh ) error("Could not read: %s\n", hap_fname);
594
595 htsFile *leg_fh = hts_open(leg_fname,"r");
596 if ( !leg_fh ) error("Could not read: %s\n", leg_fname);
597
598 // Eat up first legend line, then determine chromosome name
599 if ( hts_getline(leg_fh, KS_SEP_LINE, &line) <= 0 ) error("Empty file: %s\n", leg_fname);
600 if ( hts_getline(leg_fh, KS_SEP_LINE, &line) <= 0 ) error("Empty file: %s\n", leg_fname);
601
602 // Find out the chromosome name, sample names, init and print the VCF header
603 args->str.l = 0;
604 char *se = strchr(line.s,':');
605 if ( !se ) error("Expected CHROM:POS_REF_ALT in first column of %s\n", leg_fname);
606 kputsn(line.s, se-line.s, &args->str);
607
608 tsv_t *leg_tsv = tsv_init("CHROM_POS_REF_ALT,POS,REF_ALT");
609 tsv_register(leg_tsv, "CHROM_POS_REF_ALT", tsv_setter_chrom_pos_ref_alt, args);
610 tsv_register(leg_tsv, "POS", tsv_setter_verify_pos, NULL);
611 tsv_register(leg_tsv, "REF_ALT", tsv_setter_verify_ref_alt, args);
612 tsv_t *hap_tsv = tsv_init("HAPS");
613 tsv_register(hap_tsv, "HAPS", tsv_setter_haps, args);
614
615 args->header = bcf_hdr_init("w");
616 bcf_hdr_append(args->header, "##INFO=<ID=END,Number=1,Type=Integer,Description=\"End position of the variant described in this record\">");
617 bcf_hdr_append(args->header, "##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">");
618 bcf_hdr_printf(args->header, "##contig=<ID=%s,length=%d>", args->str.s,0x7fffffff); // MAX_CSI_COOR
619 if (args->record_cmd_line) bcf_hdr_append_version(args->header, args->argc, args->argv, "bcftools_convert");
620
621 int i, nrows, nsamples;
622 char **samples = hts_readlist(sample_fname, 1, &nrows);
623 if ( !samples ) error("Could not read %s\n", sample_fname);
624 nsamples = nrows - 1;
625
626 // sample_fname should contain a header line, so need to ignore first row
627 // returned from hts_readlist (i=1, and not i=0)
628 for (i=1; i<nrows; i++)
629 {
630 se = samples[i]; while ( *se && !isspace(*se) ) se++;
631 *se = 0;
632 bcf_hdr_add_sample(args->header,samples[i]);
633 }
634 bcf_hdr_add_sample(args->header,NULL);
635 for (i=0; i<nrows; i++) free(samples[i]);
636 free(samples);
637
638 char wmode[8];
639 set_wmode(wmode,args->output_type,args->outfname,args->clevel);
640 htsFile *out_fh = hts_open(args->outfname ? args->outfname : "-", wmode);
641 if ( out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->outfname, strerror(errno));
642 if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads);
643 if ( bcf_hdr_write(out_fh,args->header)!=0 ) error("[%s] Error: cannot write the header to %s\n", __func__,args->outfname);
644 if ( init_index2(out_fh,args->header,args->outfname,&args->index_fn,
645 args->write_index)<0 )
646 error("Error: failed to initialise index for %s\n",args->outfname);
647 bcf1_t *rec = bcf_init();
648
649 args->gts = (int32_t *) malloc(sizeof(int32_t)*nsamples*2);
650
651 while (1)
652 {
653 bcf_clear(rec);
654 args->n.total++;
655 if ( tsv_parse(leg_tsv, rec, line.s) )
656 error("Error occurred while parsing %s: %s\n", leg_fname,line.s);
657
658 if ( hts_getline(hap_fh, KS_SEP_LINE, &line)<=0 )
659 error("Different number of records in %s and %s?\n", leg_fname,hap_fname);
660
661 if ( tsv_parse(hap_tsv, rec, line.s) )
662 error("Error occurred while parsing %s: %s\n", hap_fname,line.s);
663
664 if ( bcf_write(out_fh, args->header, rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
665
666 if ( hts_getline(leg_fh, KS_SEP_LINE, &line)<=0 )
667 {
668 if ( hts_getline(hap_fh, KS_SEP_LINE, &line)>0 )
669 error("Different number of records in %s and %s?\n", leg_fname,hap_fname);
670 break;
671 }
672 }
673
674 if ( args->write_index )
675 {
676 if ( bcf_idx_save(out_fh)<0 )
677 {
678 if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname);
679 error("Error: cannot write to index %s\n", args->index_fn);
680 }
681 free(args->index_fn);
682 }
683 if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname);
684 if ( hts_close(hap_fh) ) error("Close failed: %s\n", hap_fname);
685 if ( hts_close(leg_fh) ) error("Close failed: %s\n", leg_fname);
686 bcf_hdr_destroy(args->header);
687 bcf_destroy(rec);
688 free(sample_fname);
689 free(hap_fname);
690 free(leg_fname);
691 free(args->str.s);
692 free(line.s);
693 free(args->gts);
694 tsv_destroy(hap_tsv);
695 tsv_destroy(leg_tsv);
696
697 fprintf(stderr,"Number of processed rows: \t%d\n", args->n.total);
698 }
699
700 static void hapsample_to_vcf(args_t *args)
701 {
702 /*
703 * Input: SHAPEIT output
704 *
705 * 20:19995888_A_G rsid1 19995888 A G 0 0 0 0 ...
706 * 20 20:19995888_A_G 19995888 A G 0 0 0 0 ...
707 *
708 * First column is expected in the form of CHROM:POS_REF_ALT
709 *
710 * Output: VCF with filled GT
711 *
712 */
713 kstring_t line = {0,0,0};
714
715 char *hap_fname = NULL, *sample_fname = NULL;
716 sample_fname = strchr(args->infname,',');
717 if ( !sample_fname )
718 {
719 args->str.l = 0;
720 ksprintf(&args->str,"%s.hap.gz", args->infname);
721 hap_fname = strdup(args->str.s);
722 args->str.l = 0;
723 ksprintf(&args->str,"%s.samples", args->infname);
724 sample_fname = strdup(args->str.s);
725 }
726 else
727 {
728 *sample_fname = 0;
729 hap_fname = strdup(args->infname);
730 sample_fname = strdup(sample_fname+1);
731 }
732 htsFile *hap_fh = hts_open(hap_fname, "r");
733 if ( !hap_fh ) error("Could not read: %s\n", hap_fname);
734 if ( hts_getline(hap_fh, KS_SEP_LINE, &line) <= 0 ) error("Empty file: %s\n", hap_fname);
735
736 // Find out the chromosome name, it can be either in the first or second column
737 args->str.l = 0;
738 char *sb = line.s, *se = line.s;
739 while ( *se && !isspace(*se) ) se++;
740 if ( !*se ) error("Could not determine CHROM in %s: %s\n", hap_fname,line.s);
741 if ( !args->output_vcf_ids )
742 {
743 // first column should be just CHROM, but the second must be CHROM:POS_REF_ALT, use that
744 sb = ++se;
745 while ( *se && !isspace(*se) ) se++;
746 if ( !*se ) error("Could not determine CHROM in %s: %s\n", hap_fname,line.s);
747 if ( !strchr(sb,':') )
748 error("Could not determine CHROM in the second column of %s: %s\n", hap_fname,line.s);
749 }
750 // Parse CHROM:POS_REF_ALT
751 char *sc = strchr(sb,':');
752 if ( !sc || sc > se )
753 error("Could not determine CHROM in %s: %s\n", hap_fname,line.s);
754 kputsn(sb, sc-sb, &args->str);
755
756 // Initialize and print the VCF header, args->str.s contains the chr name
757 args->header = bcf_hdr_init("w");
758 bcf_hdr_append(args->header, "##INFO=<ID=END,Number=1,Type=Integer,Description=\"End position of the variant described in this record\">");
759 bcf_hdr_append(args->header, "##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">");
760 bcf_hdr_printf(args->header, "##contig=<ID=%s,length=%d>", args->str.s,0x7fffffff); // MAX_CSI_COOR
761 if (args->record_cmd_line) bcf_hdr_append_version(args->header, args->argc, args->argv, "bcftools_convert");
762
763 tsv_t *tsv;
764 if ( args->output_vcf_ids )
765 {
766 tsv = tsv_init("CHROM_POS_REF_ALT,ID,POS,REF_ALT,HAPS");
767 tsv_register(tsv, "ID", tsv_setter_id, args);
768 }
769 else
770 {
771 tsv = tsv_init("CHROM,CHROM_POS_REF_ALT,POS,REF_ALT,HAPS");
772 tsv_register(tsv, "CHROM", tsv_setter_chrom_pos_ref_alt_or_chrom, args);
773 }
774 tsv_register(tsv, "CHROM_POS_REF_ALT", tsv_setter_chrom_pos_ref_alt, args);
775 tsv_register(tsv, "POS", tsv_setter_verify_pos, NULL);
776 tsv_register(tsv, "REF_ALT", tsv_setter_verify_ref_alt, args);
777 tsv_register(tsv, "HAPS", tsv_setter_haps, args);
778
779 int i, nsamples;
780 char **samples = hts_readlist(sample_fname, 1, &nsamples);
781 if ( !samples ) error("Could not read %s\n", sample_fname);
782 for (i=2; i<nsamples; i++)
783 {
784 se = samples[i]; while ( *se && !isspace(*se) ) se++;
785 *se = 0;
786 bcf_hdr_add_sample(args->header,samples[i]);
787 }
788 bcf_hdr_add_sample(args->header,NULL);
789 for (i=0; i<nsamples; i++) free(samples[i]);
790 free(samples);
791
792 char wmode[8];
793 set_wmode(wmode,args->output_type,args->outfname,args->clevel);
794 htsFile *out_fh = hts_open(args->outfname ? args->outfname : "-", wmode);
795 if ( out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->outfname, strerror(errno));
796 if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads);
797 if ( bcf_hdr_write(out_fh,args->header)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
798 if ( init_index2(out_fh,args->header,args->outfname,&args->index_fn,
799 args->write_index)<0 )
800 error("Error: failed to initialise index for %s\n",args->outfname);
801 bcf1_t *rec = bcf_init();
802
803 nsamples -= 2;
804 args->gts = (int32_t *) malloc(sizeof(int32_t)*nsamples*2);
805
806 do
807 {
808 bcf_clear(rec);
809 args->n.total++;
810 if ( !tsv_parse(tsv, rec, line.s) )
811 {
812 if ( bcf_write(out_fh, args->header, rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
813 }
814 else
815 error("Error occurred while parsing: %s\n", line.s);
816 }
817 while ( hts_getline(hap_fh, KS_SEP_LINE, &line)>0 );
818
819 if ( args->write_index )
820 {
821 if ( bcf_idx_save(out_fh)<0 )
822 {
823 if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname);
824 error("Error: cannot write to index %s\n", args->index_fn);
825 }
826 free(args->index_fn);
827 }
828 if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname);
829 if ( hts_close(hap_fh) ) error("Close failed: %s\n", hap_fname);
830 bcf_hdr_destroy(args->header);
831 bcf_destroy(rec);
832 free(sample_fname);
833 free(hap_fname);
834 free(args->str.s);
835 free(line.s);
836 free(args->gts);
837 tsv_destroy(tsv);
838
839 fprintf(stderr,"Number of processed rows: \t%d\n", args->n.total);
840 }
841
842 char *init_sample2sex(bcf_hdr_t *hdr, char *sex_fname)
843 {
844 int i, nlines;
845 char *sample2sex = (char*) calloc(bcf_hdr_nsamples(hdr),1);
846 char **lines = hts_readlist(sex_fname, 1, &nlines);
847 if ( !lines ) error("Could not read %s\n", sex_fname);
848 for (i=0; i<nlines; i++)
849 {
850 char *se = lines[i]; while ( *se && !isspace(*se) ) se++;
851 char tmp = *se;
852 *se = 0;
853 int id = bcf_hdr_id2int(hdr, BCF_DT_SAMPLE, lines[i]);
854 *se = tmp;
855 if ( id<0 ) continue;
856 while ( *se && isspace(*se) ) se++;
857 if ( *se=='M' ) sample2sex[id] = '1';
858 else if ( *se=='F' ) sample2sex[id] = '2';
859 else error("Could not parse %s: %s\n", sex_fname,lines[i]);
860 }
861 for (i=0; i<nlines; i++) free(lines[i]);
862 free(lines);
863 for (i=0; i<bcf_hdr_nsamples(hdr); i++)
864 if ( !sample2sex[i] ) error("Missing sex for sample %s in %s\n", bcf_hdr_int2id(hdr, BCF_DT_SAMPLE, i),sex_fname);
865 return sample2sex;
866 }
867
868 static void vcf_to_gensample(args_t *args)
869 {
870 kstring_t str = {0,0,0};
871
872 // insert chrom as first column if needed
873 if ( args->gen_3N6 )
874 kputs("%CHROM ", &str);
875
876 kputs("%CHROM:%POS\\_%REF\\_%FIRST_ALT ", &str);
877
878 // insert rsid as second column if needed
879 if ( args->output_vcf_ids )
880 kputs("%ID ", &str);
881 else
882 kputs("%CHROM:%POS\\_%REF\\_%FIRST_ALT ", &str);
883
884 kputs("%POS %REF %FIRST_ALT", &str);
885 if ( !args->tag || !strcmp(args->tag,"GT") ) kputs("%_GT_TO_PROB3",&str);
886 else if ( !strcmp(args->tag,"PL") ) kputs("%_PL_TO_PROB3",&str);
887 else if ( !strcmp(args->tag,"GP") ) kputs("%_GP_TO_PROB3",&str);
888 else error("todo: --tag %s\n", args->tag);
889 kputs("\n", &str);
890 open_vcf(args,str.s);
891
892 int ret, gen_compressed = 1, sample_compressed = 0;
893 char *gen_fname = NULL, *sample_fname = NULL;
894 str.l = 0;
895 kputs(args->outfname,&str);
896 int n_files = 0, i;
897 char **files = hts_readlist(str.s, 0, &n_files);
898 if ( n_files==1 )
899 {
900 int l = str.l;
901 kputs(".samples",&str);
902 sample_fname = strdup(str.s);
903 str.l = l;
904 kputs(".gen.gz",&str);
905 gen_fname = strdup(str.s);
906 }
907 else if ( n_files==2 )
908 {
909 if (strlen(files[0]) && strcmp(files[0],".")!=0) gen_fname = strdup(files[0]);
910 if (strlen(files[1]) && strcmp(files[1],".")!=0) sample_fname = strdup(files[1]);
911 }
912 else
913 {
914 error("Error parsing --gensample filenames: %s\n", args->outfname);
915 }
916 for (i=0; i<n_files; i++) free(files[i]);
917 free(files);
918
919 if ( gen_fname && (strlen(gen_fname)<3 || strcasecmp(".gz",gen_fname+strlen(gen_fname)-3)) ) gen_compressed = 0;
920 if ( sample_fname && strlen(sample_fname)>3 && strcasecmp(".gz",sample_fname+strlen(sample_fname)-3)==0 ) sample_compressed = 0;
921
922 if (gen_fname) fprintf(stderr, "Gen file: %s\n", gen_fname);
923 if (sample_fname) fprintf(stderr, "Sample file: %s\n", sample_fname);
924
925 // write samples file
926 if (sample_fname)
927 {
928 char *sample2sex = NULL;
929 if ( args->sex_fname ) sample2sex = init_sample2sex(args->header,args->sex_fname);
930
931 int i;
932 BGZF *sout = bgzf_open(sample_fname, sample_compressed ? "wg" : "wu");
933 str.l = 0;
934 kputs(sample2sex ? "ID_1 ID_2 missing sex\n0 0 0 0\n" : "ID_1 ID_2 missing\n0 0 0\n", &str);
935 ret = bgzf_write(sout, str.s, str.l);
936 if ( ret != str.l ) error("Error writing %s: %s\n", sample_fname, strerror(errno));
937 for (i=0; i<bcf_hdr_nsamples(args->header); i++)
938 {
939 str.l = 0;
940 if ( sample2sex )
941 ksprintf(&str, "%s %s 0 %c\n", args->header->samples[i],args->header->samples[i],sample2sex[i]);
942 else
943 ksprintf(&str, "%s %s 0\n", args->header->samples[i],args->header->samples[i]);
944 ret = bgzf_write(sout, str.s, str.l);
945 if ( ret != str.l ) error("Error writing %s: %s\n", sample_fname, strerror(errno));
946 }
947 if ( bgzf_close(sout)!=0 ) error("Error closing %s: %s\n", sample_fname, strerror(errno));
948 free(sample_fname);
949 free(sample2sex);
950 }
951 if (!gen_fname) {
952 if ( str.m ) free(str.s);
953 return;
954 }
955
956 int prev_rid = -1, prev_pos = -1;
957 int no_alt = 0, non_biallelic = 0, filtered = 0, ndup = 0, nok = 0;
958 BGZF *gout = bgzf_open(gen_fname, gen_compressed ? "wg" : "wu");
959 while ( bcf_sr_next_line(args->files) )
960 {
961 bcf1_t *line = bcf_sr_get_line(args->files,0);
962 if ( args->filter )
963 {
964 int pass = filter_test(args->filter, line, NULL);
965 if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1;
966 if ( !pass ) { filtered++; continue; }
967 }
968
969 // ALT allele is required
970 if ( line->n_allele<2 ) { no_alt++; continue; }
971
972 // biallelic required
973 if ( line->n_allele>2 ) {
974 if (!non_biallelic)
975 fprintf(stderr, "Warning: non-biallelic records are skipped. Consider splitting multi-allelic records into biallelic records using 'bcftools norm -m-'.\n");
976 non_biallelic++;
977 continue;
978 }
979
980 // skip duplicate lines, or otherwise shapeit complains
981 if ( !args->keep_duplicates && prev_rid==line->rid && prev_pos==line->pos ) { ndup++; continue; }
982 prev_rid = line->rid;
983 prev_pos = line->pos;
984
985 str.l = 0;
986 convert_line(args->convert, line, &str);
987 if ( str.l )
988 {
989 int ret = bgzf_write(gout, str.s, str.l);
990 if ( ret!= str.l ) error("Error writing %s: %s\n", gen_fname,strerror(errno));
991 nok++;
992 }
993 }
994 fprintf(stderr, "%d records written, %d skipped: %d/%d/%d/%d no-ALT/non-biallelic/filtered/duplicated\n",
995 nok, no_alt+non_biallelic+filtered+ndup, no_alt, non_biallelic, filtered, ndup);
996
997 if ( str.m ) free(str.s);
998 if ( bgzf_close(gout)!=0 ) error("Error closing %s: %s\n", gen_fname,strerror(errno));
999 free(gen_fname);
1000 }
1001
1002 static void vcf_to_haplegendsample(args_t *args)
1003 {
1004 kstring_t str = {0,0,0};
1005 if ( args->hap2dip )
1006 kputs("%_GT_TO_HAP2\n", &str);
1007 else
1008 kputs("%_GT_TO_HAP\n", &str);
1009 open_vcf(args,str.s);
1010
1011 int ret, hap_compressed = 1, legend_compressed = 1, sample_compressed = 0;
1012 char *hap_fname = NULL, *legend_fname = NULL, *sample_fname = NULL;
1013 str.l = 0;
1014 kputs(args->outfname,&str);
1015 int n_files = 0, i;
1016 char **files = hts_readlist(str.s, 0, &n_files);
1017 if ( n_files==1 )
1018 {
1019 int l = str.l;
1020 kputs(".samples",&str);
1021 sample_fname = strdup(str.s);
1022 str.l = l;
1023 kputs(".legend.gz",&str);
1024 legend_fname = strdup(str.s);
1025 str.l = l;
1026 kputs(".hap.gz",&str);
1027 hap_fname = strdup(str.s);
1028 }
1029 else if ( n_files==3 )
1030 {
1031 if (strlen(files[0]) && strcmp(files[0],".")!=0) hap_fname = strdup(files[0]);
1032 if (strlen(files[1]) && strcmp(files[1],".")!=0) legend_fname = strdup(files[1]);
1033 if (strlen(files[2]) && strcmp(files[2],".")!=0) sample_fname = strdup(files[2]);
1034 }
1035 else
1036 {
1037 error("Error parsing --hapslegendsample filenames: %s\n", args->outfname);
1038 }
1039 for (i=0; i<n_files; i++) free(files[i]);
1040 free(files);
1041
1042 if ( hap_fname && (strlen(hap_fname)<3 || strcasecmp(".gz",hap_fname+strlen(hap_fname)-3)) ) hap_compressed = 0;
1043 if ( legend_fname && (strlen(legend_fname)<3 || strcasecmp(".gz",legend_fname+strlen(legend_fname)-3)) ) legend_compressed = 0;
1044 if ( sample_fname && strlen(sample_fname)>3 && strcasecmp(".gz",sample_fname+strlen(sample_fname)-3)==0 ) sample_compressed = 0;
1045
1046 if (hap_fname) fprintf(stderr, "Hap file: %s\n", hap_fname);
1047 if (legend_fname) fprintf(stderr, "Legend file: %s\n", legend_fname);
1048 if (sample_fname) fprintf(stderr, "Sample file: %s\n", sample_fname);
1049
1050 // write samples file
1051 if (sample_fname)
1052 {
1053 char *sample2sex = NULL;
1054 if ( args->sex_fname ) sample2sex = init_sample2sex(args->header,args->sex_fname);
1055
1056 int i;
1057 BGZF *sout = bgzf_open(sample_fname, sample_compressed ? "wg" : "wu");
1058 str.l = 0;
1059 kputs("sample population group sex\n", &str);
1060 ret = bgzf_write(sout, str.s, str.l);
1061 if ( ret != str.l ) error("Error writing %s: %s\n", sample_fname, strerror(errno));
1062 for (i=0; i<bcf_hdr_nsamples(args->header); i++)
1063 {
1064 str.l = 0;
1065 ksprintf(&str, "%s %s %s %c\n", args->header->samples[i], args->header->samples[i], args->header->samples[i], sample2sex ? sample2sex[i] : '2');
1066 ret = bgzf_write(sout, str.s, str.l);
1067 if ( ret != str.l ) error("Error writing %s: %s\n", sample_fname, strerror(errno));
1068 }
1069 if ( bgzf_close(sout)!=0 ) error("Error closing %s: %s\n", sample_fname, strerror(errno));
1070 free(sample_fname);
1071 free(sample2sex);
1072 }
1073 if (!hap_fname && !legend_fname) {
1074 if ( str.m ) free(str.s);
1075 return;
1076 }
1077
1078 // open haps and legend outputs
1079 BGZF *hout = hap_fname ? bgzf_open(hap_fname, hap_compressed ? "wg" : "wu") : NULL;
1080 if ( hap_compressed && args->n_threads ) bgzf_thread_pool(hout, args->files->p->pool, args->files->p->qsize);
1081 BGZF *lout = legend_fname ? bgzf_open(legend_fname, legend_compressed ? "wg" : "wu") : NULL;
1082 if (legend_fname) {
1083 str.l = 0;
1084 kputs("id position a0 a1\n", &str);
1085 ret = bgzf_write(lout, str.s, str.l);
1086 if ( ret != str.l ) error("Error writing %s: %s\n", legend_fname, strerror(errno));
1087 }
1088
1089 int no_alt = 0, non_biallelic = 0, filtered = 0, nok = 0;
1090 while ( bcf_sr_next_line(args->files) )
1091 {
1092 bcf1_t *line = bcf_sr_get_line(args->files,0);
1093 if ( args->filter )
1094 {
1095 int pass = filter_test(args->filter, line, NULL);
1096 if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1;
1097 if ( !pass ) { filtered++; continue; }
1098 }
1099
1100 // ALT allele is required
1101 if ( line->n_allele<2 ) { no_alt++; continue; }
1102 // biallelic required
1103 if ( line->n_allele>2 ) {
1104 if (!non_biallelic)
1105 fprintf(stderr, "Warning: non-biallelic records are skipped. Consider splitting multi-allelic records into biallelic records using 'bcftools norm -m-'.\n");
1106 non_biallelic++;
1107 continue;
1108 }
1109
1110 str.l = 0;
1111 convert_line(args->convert, line, &str);
1112 if ( !str.l ) continue;
1113
1114 // write haps file
1115 if (hap_fname) {
1116 ret = bgzf_write(hout, str.s, str.l); // write hap file
1117 if ( ret != str.l ) error("Error writing %s: %s\n", hap_fname, strerror(errno));
1118 }
1119 if (legend_fname) {
1120 str.l = 0;
1121 if ( args->output_vcf_ids && (line->d.id[0]!='.' || line->d.id[1]!=0) )
1122 ksprintf(&str, "%s %"PRId64" %s %s\n", line->d.id, (int64_t) line->pos+1, line->d.allele[0], line->d.allele[1]);
1123 else
1124 ksprintf(&str, "%s:%"PRId64"_%s_%s %"PRId64" %s %s\n", bcf_seqname(args->header, line), (int64_t) line->pos+1, line->d.allele[0], line->d.allele[1], (int64_t) line->pos+1, line->d.allele[0], line->d.allele[1]);
1125
1126 // write legend file
1127 ret = bgzf_write(lout, str.s, str.l);
1128 if ( ret != str.l ) error("Error writing %s: %s\n", legend_fname, strerror(errno));
1129 }
1130 nok++;
1131 }
1132 fprintf(stderr, "%d records written, %d skipped: %d/%d/%d no-ALT/non-biallelic/filtered\n", nok,no_alt+non_biallelic+filtered, no_alt, non_biallelic, filtered);
1133 if ( str.m ) free(str.s);
1134 if ( hout && bgzf_close(hout)!=0 ) error("Error closing %s: %s\n", hap_fname, strerror(errno));
1135 if ( lout && bgzf_close(lout)!=0 ) error("Error closing %s: %s\n", legend_fname, strerror(errno));
1136 if (hap_fname) free(hap_fname);
1137 if (legend_fname) free(legend_fname);
1138 }
1139
1140 static void vcf_to_hapsample(args_t *args)
1141 {
1142 /*
1143 * WTCCC style haplotypes file
1144 * see https://mathgen.stats.ox.ac.uk/genetics_software/shapeit/shapeit.html#hapsample
1145 *
1146 * These are essentially the haplotypes from the impute2 format with some
1147 * legend info tacked on to the first 5 columns
1148 *
1149 */
1150 kstring_t str = {0,0,0};
1151
1152 // print ID instead of CHROM:POS_REF_ALT1
1153 if ( args->output_vcf_ids )
1154 kputs("%CHROM:%POS\\_%REF\\_%FIRST_ALT %ID %POS %REF %FIRST_ALT ", &str);
1155 else
1156 kputs("%CHROM %CHROM:%POS\\_%REF\\_%FIRST_ALT %POS %REF %FIRST_ALT ", &str);
1157
1158 if ( args->hap2dip )
1159 kputs("%_GT_TO_HAP2\n", &str);
1160 else
1161 kputs("%_GT_TO_HAP\n", &str);
1162 open_vcf(args,str.s);
1163
1164 int ret, hap_compressed = 1, sample_compressed = 0;
1165 char *hap_fname = NULL, *sample_fname = NULL;
1166 str.l = 0;
1167 kputs(args->outfname,&str);
1168 int n_files = 0, i;
1169 char **files = hts_readlist(str.s, 0, &n_files);
1170 if ( n_files==1 )
1171 {
1172 int l = str.l;
1173 kputs(".samples",&str);
1174 sample_fname = strdup(str.s);
1175 str.l = l;
1176 kputs(".hap.gz",&str);
1177 hap_fname = strdup(str.s);
1178 }
1179 else if ( n_files==2 )
1180 {
1181 if (strlen(files[0]) && strcmp(files[0],".")!=0) hap_fname = strdup(files[0]);
1182 if (strlen(files[1]) && strcmp(files[1],".")!=0) sample_fname = strdup(files[1]);
1183 }
1184 else
1185 {
1186 error("Error parsing --hapsample filenames: %s\n", args->outfname);
1187 }
1188 for (i=0; i<n_files; i++) free(files[i]);
1189 free(files);
1190
1191 if ( hap_fname && (strlen(hap_fname)<3 || strcasecmp(".gz",hap_fname+strlen(hap_fname)-3)) ) hap_compressed = 0;
1192 if ( sample_fname && strlen(sample_fname)>3 && strcasecmp(".gz",sample_fname+strlen(sample_fname)-3)==0 ) sample_compressed = 0;
1193
1194 if (hap_fname) fprintf(stderr, "Hap file: %s\n", hap_fname);
1195 if (sample_fname) fprintf(stderr, "Sample file: %s\n", sample_fname);
1196
1197 // write samples file
1198 if (sample_fname)
1199 {
1200 char *sample2sex = NULL;
1201 if ( args->sex_fname ) sample2sex = init_sample2sex(args->header,args->sex_fname);
1202
1203 int i;
1204 BGZF *sout = bgzf_open(sample_fname, sample_compressed ? "wg" : "wu");
1205 str.l = 0;
1206 kputs(sample2sex ? "ID_1 ID_2 missing sex\n0 0 0 0\n" : "ID_1 ID_2 missing\n0 0 0\n", &str);
1207 ret = bgzf_write(sout, str.s, str.l);
1208 if ( ret != str.l ) error("Error writing %s: %s\n", sample_fname, strerror(errno));
1209 for (i=0; i<bcf_hdr_nsamples(args->header); i++)
1210 {
1211 str.l = 0;
1212 if ( sample2sex )
1213 ksprintf(&str, "%s %s 0 %c\n", args->header->samples[i],args->header->samples[i],sample2sex[i]);
1214 else
1215 ksprintf(&str, "%s %s 0\n", args->header->samples[i],args->header->samples[i]);
1216 ret = bgzf_write(sout, str.s, str.l);
1217 if ( ret != str.l ) error("Error writing %s: %s\n", sample_fname, strerror(errno));
1218 }
1219 if ( bgzf_close(sout)!=0 ) error("Error closing %s: %s\n", sample_fname, strerror(errno));
1220 free(sample_fname);
1221 free(sample2sex);
1222 }
1223 if (!hap_fname) {
1224 if ( str.m ) free(str.s);
1225 return;
1226 }
1227
1228 // open haps output
1229 BGZF *hout = hap_fname ? bgzf_open(hap_fname, hap_compressed ? "wg" : "wu") : NULL;
1230 if ( hap_compressed && args->n_threads ) bgzf_thread_pool(hout, args->files->p->pool, args->files->p->qsize);
1231
1232 int no_alt = 0, non_biallelic = 0, filtered = 0, nok = 0;
1233 while ( bcf_sr_next_line(args->files) )
1234 {
1235 bcf1_t *line = bcf_sr_get_line(args->files,0);
1236 if ( args->filter )
1237 {
1238 int pass = filter_test(args->filter, line, NULL);
1239 if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1;
1240 if ( !pass ) { filtered++; continue; }
1241 }
1242
1243 // ALT allele is required
1244 if ( line->n_allele<2 ) { no_alt++; continue; }
1245 // biallelic required
1246 if ( line->n_allele>2 ) {
1247 if (!non_biallelic)
1248 fprintf(stderr, "Warning: non-biallelic records are skipped. Consider splitting multi-allelic records into biallelic records using 'bcftools norm -m-'.\n");
1249 non_biallelic++;
1250 continue;
1251 }
1252
1253 str.l = 0;
1254 convert_line(args->convert, line, &str);
1255 if ( !str.l ) continue;
1256
1257 // write haps file
1258 if (hap_fname) {
1259 ret = bgzf_write(hout, str.s, str.l); // write hap file
1260 if ( ret != str.l ) error("Error writing %s: %s\n", hap_fname, strerror(errno));
1261 }
1262 nok++;
1263 }
1264 fprintf(stderr, "%d records written, %d skipped: %d/%d/%d no-ALT/non-biallelic/filtered\n", nok, no_alt+non_biallelic+filtered, no_alt, non_biallelic, filtered);
1265 if ( str.m ) free(str.s);
1266 if ( hout && bgzf_close(hout)!=0 ) error("Error closing %s: %s\n", hap_fname, strerror(errno));
1267 if (hap_fname) free(hap_fname);
1268 }
1269
1270 static void bcf_hdr_set_chrs(bcf_hdr_t *hdr, faidx_t *fai)
1271 {
1272 int i, n = faidx_nseq(fai);
1273 for (i=0; i<n; i++)
1274 {
1275 const char *seq = faidx_iseq(fai,i);
1276 int len = faidx_seq_len(fai, seq);
1277 bcf_hdr_printf(hdr, "##contig=<ID=%s,length=%d>", seq,len);
1278 }
1279 }
1280 static inline int acgt_to_5(char base)
1281 {
1282 if ( base=='A' ) return 0;
1283 if ( base=='C' ) return 1;
1284 if ( base=='G' ) return 2;
1285 if ( base=='T' ) return 3;
1286 return 4;
1287 }
1288 static inline int tsv_setter_aa1(args_t *args, char *ss, char *se, int alleles[], int *nals, int ref, int32_t *gts)
1289 {
1290 if ( se - ss > 2 ) return -1; // currently only SNPs
1291
1292 if ( ss[0]=='-' || ss[0]=='.' )
1293 {
1294 // missing GT
1295 gts[0] = bcf_gt_missing;
1296 gts[1] = bcf_gt_missing;
1297 args->n.missing++;
1298 return 0;
1299 }
1300 if ( ss[0]=='I' ) return -2; // skip insertions/deletions for now
1301 if ( ss[0]=='D' ) return -2;
1302
1303 int a0 = acgt_to_5(toupper(ss[0]));
1304 int a1 = ss[1] ? acgt_to_5(toupper(ss[1])) : a0;
1305 if ( alleles[a0]<0 ) alleles[a0] = (*nals)++;
1306 if ( alleles[a1]<0 ) alleles[a1] = (*nals)++;
1307
1308 gts[0] = bcf_gt_unphased(alleles[a0]);
1309 gts[1] = ss[1] ? bcf_gt_unphased(alleles[a1]) : bcf_int32_vector_end;
1310
1311 if ( ref==a0 && ref==a1 ) args->n.hom_rr++; // hom ref: RR
1312 else if ( ref==a0 ) args->n.het_ra++; // het: RA
1313 else if ( ref==a1 ) args->n.het_ra++; // het: AR
1314 else if ( a0==a1 ) args->n.hom_aa++; // hom-alt: AA
1315 else args->n.het_aa++; // non-ref het: AA
1316
1317 return 0;
1318 }
1319 static int tsv_setter_aa(tsv_t *tsv, bcf1_t *rec, void *usr)
1320 {
1321 args_t *args = (args_t*) usr;
1322
1323 int len;
1324 char *ref = faidx_fetch_seq(args->ref, (char*)bcf_hdr_id2name(args->header,rec->rid), rec->pos, rec->pos, &len);
1325 if ( !ref ) error("faidx_fetch_seq failed at %s:%"PRId64"\n", bcf_hdr_id2name(args->header,rec->rid),(int64_t) rec->pos+1);
1326
1327 int nals = 1, alleles[5] = { -1, -1, -1, -1, -1 }; // a,c,g,t,n
1328 ref[0] = toupper(ref[0]);
1329 int iref = acgt_to_5(ref[0]);
1330 alleles[iref] = 0;
1331
1332 rec->n_sample = bcf_hdr_nsamples(args->header);
1333
1334 int i, ret;
1335 for (i=0; i<rec->n_sample; i++)
1336 {
1337 if ( i>0 )
1338 {
1339 ret = tsv_next(tsv);
1340 if ( ret==-1 ) error("Too few columns for %d samples at %s:%"PRId64"\n", rec->n_sample,bcf_hdr_id2name(args->header,rec->rid),(int64_t) rec->pos+1);
1341 }
1342 ret = tsv_setter_aa1(args, tsv->ss, tsv->se, alleles, &nals, iref, args->gts+i*2);
1343 if ( ret==-1 ) error("Error parsing the site %s:%"PRId64", expected two characters\n", bcf_hdr_id2name(args->header,rec->rid),(int64_t) rec->pos+1);
1344 if ( ret==-2 )
1345 {
1346 // something else than a SNP
1347 free(ref);
1348 return -1;
1349 }
1350 }
1351
1352 args->str.l = 0;
1353 kputc(ref[0], &args->str);
1354 for (i=0; i<5; i++)
1355 {
1356 if ( alleles[i]>0 )
1357 {
1358 kputc(',', &args->str);
1359 kputc("ACGTN"[i], &args->str);
1360 }
1361 }
1362 bcf_update_alleles_str(args->header, rec, args->str.s);
1363 if ( bcf_update_genotypes(args->header,rec,args->gts,rec->n_sample*2) ) error("Could not update the GT field\n");
1364
1365 free(ref);
1366 return 0;
1367 }
1368
1369 static void tsv_to_vcf(args_t *args)
1370 {
1371 if ( !args->ref_fname ) error("--tsv2vcf requires the --fasta-ref option\n");
1372
1373 args->ref = fai_load(args->ref_fname);
1374 if ( !args->ref ) error("Could not load the reference %s\n", args->ref_fname);
1375
1376 args->header = bcf_hdr_init("w");
1377 bcf_hdr_set_chrs(args->header, args->ref);
1378 bcf_hdr_append(args->header, "##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">");
1379 if (args->record_cmd_line) bcf_hdr_append_version(args->header, args->argc, args->argv, "bcftools_convert");
1380
1381 int i, nsmpl;
1382 char **smpl;
1383 if ( args->sample_list )
1384 {
1385 smpl = hts_readlist(args->sample_list, args->sample_is_file, &nsmpl);
1386 if ( !smpl ) error("Could not parse %s\n", args->sample_list);
1387 for (i=0; i<nsmpl; i++)
1388 {
1389 bcf_hdr_add_sample(args->header, smpl[i]);
1390 free(smpl[i]);
1391 }
1392 free(smpl);
1393 bcf_hdr_add_sample(args->header, NULL);
1394 args->gts = (int32_t *) malloc(sizeof(int32_t)*nsmpl*2);
1395 }
1396
1397 char wmode[8];
1398 set_wmode(wmode,args->output_type,args->outfname,args->clevel);
1399 htsFile *out_fh = hts_open(args->outfname ? args->outfname : "-", wmode);
1400 if ( out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->outfname, strerror(errno));
1401 if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads);
1402 if ( bcf_hdr_write(out_fh,args->header)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
1403 if ( init_index2(out_fh,args->header,args->outfname,&args->index_fn,
1404 args->write_index)<0 )
1405 error("Error: failed to initialise index for %s\n",args->outfname);
1406
1407 tsv_t *tsv = tsv_init(args->columns ? args->columns : "ID,CHROM,POS,AA");
1408 if ( tsv_register(tsv, "CHROM", tsv_setter_chrom, args->header) < 0 ) error("Expected CHROM column\n");
1409 if ( tsv_register(tsv, "POS", tsv_setter_pos, NULL) < 0 ) error("Expected POS column\n");
1410 if ( tsv_register(tsv, "ID", tsv_setter_id, args->header) < 0 && !args->columns ) error("Expected ID column\n");
1411 if ( tsv_register(tsv, "AA", tsv_setter_aa, args) < 0 )
1412 {
1413 if ( args->sample_list ) error("Expected AA column with -s/-S\n");
1414 if ( tsv_register(tsv, "REF", tsv_setter_ref, args) < 0 || tsv_register(tsv, "ALT", tsv_setter_alt, args) < 0 )
1415 error("Expected REF and ALT columns when AA was not given\n");
1416 }
1417
1418 bcf1_t *rec = bcf_init();
1419 bcf_float_set_missing(rec->qual);
1420
1421 kstring_t line = {0,0,0};
1422 htsFile *in_fh = hts_open(args->infname, "r");
1423 if ( !in_fh ) error("Could not read: %s\n", args->infname);
1424 while ( hts_getline(in_fh, KS_SEP_LINE, &line) > 0 )
1425 {
1426 if ( line.s[0]=='#' ) continue; // skip comments
1427 bcf_clear(rec);
1428
1429 args->n.total++;
1430 if ( !tsv_parse(tsv, rec, line.s) )
1431 {
1432 if ( bcf_write(out_fh, args->header, rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
1433 args->n.written++;
1434 }
1435 else
1436 args->n.skipped++;
1437 }
1438 if ( hts_close(in_fh) ) error("Close failed: %s\n", args->infname);
1439 free(line.s);
1440
1441 if ( args->write_index )
1442 {
1443 if ( bcf_idx_save(out_fh)<0 )
1444 {
1445 if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname);
1446 error("Error: cannot write to index %s\n", args->index_fn);
1447 }
1448 free(args->index_fn);
1449 }
1450 bcf_hdr_destroy(args->header);
1451 if ( hts_close(out_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->outfname);
1452 tsv_destroy(tsv);
1453 bcf_destroy(rec);
1454 free(args->str.s);
1455 free(args->gts);
1456 free(args->tsv.ref.s);
1457 free(args->tsv.alt.s);
1458 free(args->tsv.refalt.s);
1459
1460 fprintf(stderr,"Rows total: \t%d\n", args->n.total);
1461 fprintf(stderr,"Rows skipped: \t%d\n", args->n.skipped);
1462 fprintf(stderr,"Sites written: \t%d\n", args->n.written);
1463 if ( args->sample_list )
1464 {
1465 fprintf(stderr,"Missing GTs: \t%d\n", args->n.missing);
1466 fprintf(stderr,"Hom RR: \t%d\n", args->n.hom_rr);
1467 fprintf(stderr,"Het RA: \t%d\n", args->n.het_ra);
1468 fprintf(stderr,"Hom AA: \t%d\n", args->n.hom_aa);
1469 fprintf(stderr,"Het AA: \t%d\n", args->n.het_aa);
1470 }
1471 }
1472
1473 static void vcf_to_vcf(args_t *args)
1474 {
1475 open_vcf(args,NULL);
1476 char wmode[8];
1477 set_wmode(wmode,args->output_type,args->outfname,args->clevel);
1478 htsFile *out_fh = hts_open(args->outfname ? args->outfname : "-", wmode);
1479 if ( out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->outfname, strerror(errno));
1480 if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads);
1481
1482 bcf_hdr_t *hdr = bcf_sr_get_header(args->files,0);
1483 if ( bcf_hdr_write(out_fh,hdr)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
1484 if ( init_index2(out_fh,args->header,args->outfname,&args->index_fn,
1485 args->write_index)<0 )
1486 error("Error: failed to initialise index for %s\n",args->outfname);
1487
1488 while ( bcf_sr_next_line(args->files) )
1489 {
1490 bcf1_t *line = bcf_sr_get_line(args->files,0);
1491 if ( args->filter )
1492 {
1493 int pass = filter_test(args->filter, line, NULL);
1494 if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1;
1495 if ( !pass ) continue;
1496 }
1497 if ( bcf_write(out_fh,hdr,line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
1498 }
1499 if ( args->write_index )
1500 {
1501 if ( bcf_idx_save(out_fh)<0 )
1502 {
1503 if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname);
1504 error("Error: cannot write to index %s\n", args->index_fn);
1505 }
1506 free(args->index_fn);
1507 }
1508 if ( hts_close(out_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->outfname);
1509 }
1510
1511 static void gvcf_to_vcf(args_t *args)
1512 {
1513 if ( !args->ref_fname ) error("--gvcf2vcf requires the --fasta-ref option\n");
1514
1515 args->ref = fai_load(args->ref_fname);
1516 if ( !args->ref ) error("Could not load the fai index for reference %s\n", args->ref_fname);
1517
1518 open_vcf(args,NULL);
1519 char wmode[8];
1520 set_wmode(wmode,args->output_type,args->outfname,args->clevel);
1521 htsFile *out_fh = hts_open(args->outfname ? args->outfname : "-", wmode);
1522 if ( out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->outfname, strerror(errno));
1523 if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads);
1524
1525 bcf_hdr_t *hdr = bcf_sr_get_header(args->files,0);
1526 if (args->record_cmd_line) bcf_hdr_append_version(hdr, args->argc, args->argv, "bcftools_convert");
1527 if ( bcf_hdr_write(out_fh,hdr)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
1528 if ( init_index2(out_fh,hdr,args->outfname,&args->index_fn,
1529 args->write_index)<0 )
1530 error("Error: failed to initialise index for %s\n",args->outfname);
1531
1532 int32_t *itmp = NULL, nitmp = 0;
1533
1534 while ( bcf_sr_next_line(args->files) )
1535 {
1536 bcf1_t *line = bcf_sr_get_line(args->files,0);
1537 if ( args->filter )
1538 {
1539 int pass = filter_test(args->filter, line, NULL);
1540 if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1;
1541 if ( !pass )
1542 {
1543 if ( bcf_write(out_fh,hdr,line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
1544 continue;
1545 }
1546 }
1547
1548 // check if alleles compatible with being a gVCF record
1549 // ALT must be one of ., <*>, <X>, <NON_REF>
1550 // check for INFO/END is below
1551 int i, gallele = -1;
1552 if (line->n_allele==1)
1553 gallele = 0; // illumina/bcftools-call gvcf (if INFO/END present)
1554 else if ( line->d.allele[1][0]=='<' )
1555 {
1556 for (i=1; i<line->n_allele; i++)
1557 {
1558 if ( line->d.allele[i][1]=='*' && line->d.allele[i][2]=='>' && line->d.allele[i][3]=='\0' ) { gallele = i; break; } // mpileup/spec compliant gVCF
1559 if ( line->d.allele[i][1]=='X' && line->d.allele[i][2]=='>' && line->d.allele[i][3]=='\0' ) { gallele = i; break; } // old mpileup gVCF
1560 if ( strcmp(line->d.allele[i],"<NON_REF>")==0 ) { gallele = i; break; } // GATK gVCF
1561 }
1562 }
1563
1564 // no gVCF compatible alleles
1565 if (gallele<0)
1566 {
1567 if ( bcf_write(out_fh,hdr,line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
1568 continue;
1569 }
1570
1571 int nend = bcf_get_info_int32(hdr,line,"END",&itmp,&nitmp);
1572 if ( nend!=1 )
1573 {
1574 // No INFO/END => not gVCF record
1575 if ( bcf_write(out_fh,hdr,line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
1576 continue;
1577 }
1578 bcf_update_info_int32(hdr,line,"END",NULL,0);
1579 int pos, len;
1580 for (pos=line->pos; pos<itmp[0]; pos++)
1581 {
1582 line->pos = pos;
1583 char *ref = faidx_fetch_seq(args->ref, (char*)bcf_hdr_id2name(hdr,line->rid), line->pos, line->pos, &len);
1584 if ( !ref ) error("faidx_fetch_seq failed at %s:%"PRId64"\n", bcf_hdr_id2name(hdr,line->rid),(int64_t) line->pos+1);
1585 strncpy(line->d.allele[0],ref,len);
1586 if ( bcf_write(out_fh,hdr,line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname);
1587 free(ref);
1588 }
1589 }
1590 free(itmp);
1591 if ( args->write_index )
1592 {
1593 if ( bcf_idx_save(out_fh)<0 )
1594 {
1595 if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname);
1596 error("Error: cannot write to index %s\n", args->index_fn);
1597 }
1598 free(args->index_fn);
1599 }
1600 if ( hts_close(out_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->outfname);
1601 }
1602
1603 static void usage(void)
1604 {
1605 fprintf(stderr, "\n");
1606 fprintf(stderr, "About: Converts VCF/BCF to other formats and back. See man page for file\n");
1607 fprintf(stderr, " formats details. When specifying output files explicitly instead\n");
1608 fprintf(stderr, " of with PREFIX, one can use '-' for stdout and '.' to suppress.\n");
1609 fprintf(stderr, "Usage: bcftools convert [OPTIONS] INPUT_FILE\n");
1610 fprintf(stderr, "\n");
1611 fprintf(stderr, "VCF input options:\n");
1612 fprintf(stderr, " -e, --exclude EXPR Exclude sites for which the expression is true\n");
1613 fprintf(stderr, " -i, --include EXPR Select sites for which the expression is true\n");
1614 fprintf(stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n");
1615 fprintf(stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n");
1616 fprintf(stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n");
1617 fprintf(stderr, " -s, --samples LIST List of samples to include\n");
1618 fprintf(stderr, " -S, --samples-file FILE File of samples to include\n");
1619 fprintf(stderr, " -t, --targets REGION Similar to -r but streams rather than index-jumps\n");
1620 fprintf(stderr, " -T, --targets-file FILE Similar to -R but streams rather than index-jumps\n");
1621 fprintf(stderr, " --targets-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [0]\n");
1622 fprintf(stderr, "\n");
1623 fprintf(stderr, "VCF output options:\n");
1624 fprintf(stderr, " --no-version Do not append version and command line to the header\n");
1625 fprintf(stderr, " -o, --output FILE Output file name [stdout]\n");
1626 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");
1627 fprintf(stderr, " --threads INT Use multithreading with INT worker threads [0]\n");
1628 fprintf(stderr, " -W, --write-index[=FMT] Automatically index the output files [off]\n");
1629 fprintf(stderr, "\n");
1630 fprintf(stderr, "GEN/SAMPLE conversion (input/output from IMPUTE2):\n");
1631 fprintf(stderr, " -G, --gensample2vcf ... <PREFIX>|<GEN-FILE>,<SAMPLE-FILE>\n");
1632 fprintf(stderr, " -g, --gensample ... <PREFIX>|<GEN-FILE>,<SAMPLE-FILE>\n");
1633 fprintf(stderr, " --3N6 Use 3*N+6 column format instead of the old 3*N+5 column format\n");
1634 fprintf(stderr, " --tag STRING Tag to take values for .gen file: GT,PL,GL,GP [GT]\n");
1635 fprintf(stderr, " --chrom Output chromosome in first column instead of CHROM:POS_REF_ALT\n");
1636 fprintf(stderr, " --keep-duplicates Keep duplicate positions\n");
1637 fprintf(stderr, " --sex FILE Output sex column in the sample-file, input format is: Sample\\t[MF]\n");
1638 fprintf(stderr, " --vcf-ids Output VCF IDs in second column instead of CHROM:POS_REF_ALT\n");
1639 fprintf(stderr, "\n");
1640 fprintf(stderr, "gVCF conversion:\n");
1641 fprintf(stderr, " --gvcf2vcf Expand gVCF reference blocks\n");
1642 fprintf(stderr, " -f, --fasta-ref FILE Reference sequence in fasta format\n");
1643 fprintf(stderr, "\n");
1644 fprintf(stderr, "HAP/SAMPLE conversion (output from SHAPEIT):\n");
1645 fprintf(stderr, " --hapsample2vcf ... <PREFIX>|<HAP-FILE>,<SAMPLE-FILE>\n");
1646 fprintf(stderr, " --hapsample ... <PREFIX>|<HAP-FILE>,<SAMPLE-FILE>\n");
1647 fprintf(stderr, " --haploid2diploid Convert haploid genotypes to diploid homozygotes\n");
1648 fprintf(stderr, " --sex FILE Output sex column in the sample-file, input format is: Sample\\t[MF]\n");
1649 fprintf(stderr, " --vcf-ids Output VCF IDs instead of CHROM:POS_REF_ALT\n");
1650 fprintf(stderr, "\n");
1651 fprintf(stderr, "HAP/LEGEND/SAMPLE conversion:\n");
1652 fprintf(stderr, " -H, --haplegendsample2vcf ... <PREFIX>|<HAP-FILE>,<LEGEND-FILE>,<SAMPLE-FILE>\n");
1653 fprintf(stderr, " -h, --haplegendsample ... <PREFIX>|<HAP-FILE>,<LEGEND-FILE>,<SAMPLE-FILE>\n");
1654 fprintf(stderr, " --haploid2diploid Convert haploid genotypes to diploid homozygotes\n");
1655 fprintf(stderr, " --sex FILE Output sex column in the sample-file, input format is: Sample\\t[MF]\n");
1656 fprintf(stderr, " --vcf-ids Output VCF IDs instead of CHROM:POS_REF_ALT\n");
1657 fprintf(stderr, "\n");
1658 fprintf(stderr, "TSV conversion:\n");
1659 fprintf(stderr, " --tsv2vcf FILE\n");
1660 fprintf(stderr, " -c, --columns STRING Columns of the input tsv file, see man page for details [ID,CHROM,POS,AA]\n");
1661 fprintf(stderr, " -f, --fasta-ref FILE Reference sequence in fasta format\n");
1662 fprintf(stderr, " -s, --samples LIST List of sample names\n");
1663 fprintf(stderr, " -S, --samples-file FILE File of sample names\n");
1664 fprintf(stderr, "\n");
1665 // fprintf(stderr, "PLINK options:\n");
1666 // fprintf(stderr, " -p, --plink <prefix>|<ped>,<map>,<fam>|<bed>,<bim>,<fam>|<tped>,<tfam>\n");
1667 // fprintf(stderr, " --tped make tped file instead\n");
1668 // fprintf(stderr, " --bin make binary bed/fam/bim files\n");
1669 // fprintf(stderr, "\n");
1670 // fprintf(stderr, "PBWT options:\n");
1671 // fprintf(stderr, " -b, --pbwt <prefix> or <pbwt>,<sites>,<sample>,<missing>\n");
1672 // fprintf(stderr, "\n");
1673 exit(1);
1674 }
1675
1676 int main_vcfconvert(int argc, char *argv[])
1677 {
1678 int c;
1679 args_t *args = (args_t*) calloc(1,sizeof(args_t));
1680 args->argc = argc; args->argv = argv;
1681 args->outfname = "-";
1682 args->output_type = FT_VCF;
1683 args->n_threads = 0;
1684 args->record_cmd_line = 1;
1685 args->regions_overlap = 1;
1686 args->targets_overlap = 0;
1687 args->clevel = -1;
1688
1689 static struct option loptions[] =
1690 {
1691 {"include",required_argument,NULL,'i'},
1692 {"exclude",required_argument,NULL,'e'},
1693 {"output",required_argument,NULL,'o'},
1694 {"output-type",required_argument,NULL,'O'},
1695 {"threads",required_argument,NULL,9},
1696 {"regions",required_argument,NULL,'r'},
1697 {"regions-file",required_argument,NULL,'R'},
1698 {"regions-overlap",required_argument,NULL,13},
1699 {"targets",required_argument,NULL,'t'},
1700 {"targets-file",required_argument,NULL,'T'},
1701 {"targets-overlap",required_argument,NULL,14},
1702 {"samples",required_argument,NULL,'s'},
1703 {"samples-file",required_argument,NULL,'S'},
1704 {"sex",required_argument,NULL,11},
1705 {"gensample",required_argument,NULL,'g'},
1706 {"gensample2vcf",required_argument,NULL,'G'},
1707 {"tag",required_argument,NULL,1},
1708 {"chrom",no_argument,NULL,8},
1709 {"3N6",no_argument,NULL,15},
1710 {"tsv2vcf",required_argument,NULL,2},
1711 {"hapsample",required_argument,NULL,7},
1712 {"hapsample2vcf",required_argument,NULL,3},
1713 {"vcf-ids",no_argument,NULL,4},
1714 {"haploid2diploid",no_argument,NULL,5},
1715 {"gvcf2vcf",no_argument,NULL,6},
1716 {"haplegendsample",required_argument,NULL,'h'},
1717 {"haplegendsample2vcf",required_argument,NULL,'H'},
1718 {"columns",required_argument,NULL,'c'},
1719 {"fasta-ref",required_argument,NULL,'f'},
1720 {"no-version",no_argument,NULL,10},
1721 {"keep-duplicates",no_argument,NULL,12},
1722 {"write-index",optional_argument,NULL,'W'},
1723 {NULL,0,NULL,0}
1724 };
1725 char *tmp;
1726 while ((c = getopt_long(argc, argv, "?h:r:R:s:S:t:T:i:e:g:G:o:O:c:f:H:W::",loptions,NULL)) >= 0) {
1727 switch (c) {
1728 case 'e':
1729 if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n");
1730 args->filter_str = optarg; args->filter_logic |= FLT_EXCLUDE; break;
1731 case 'i':
1732 if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n");
1733 args->filter_str = optarg; args->filter_logic |= FLT_INCLUDE; break;
1734 case 'r': args->regions_list = optarg; break;
1735 case 'R': args->regions_list = optarg; args->regions_is_file = 1; break;
1736 case 't': args->targets_list = optarg; break;
1737 case 'T': args->targets_list = optarg; args->targets_is_file = 1; break;
1738 case 's': args->sample_list = optarg; break;
1739 case 'S': args->sample_list = optarg; args->sample_is_file = 1; break;
1740 case 'g': args->convert_func = vcf_to_gensample; args->outfname = optarg; break;
1741 case 'G': args->convert_func = gensample_to_vcf; args->infname = optarg; break;
1742 case 1 : args->tag = optarg; break;
1743 case 2 : args->convert_func = tsv_to_vcf; args->infname = optarg; break;
1744 case 3 : args->convert_func = hapsample_to_vcf; args->infname = optarg; break;
1745 case 4 : args->output_vcf_ids = 1; break;
1746 case 5 : args->hap2dip = 1; break;
1747 case 6 : args->convert_func = gvcf_to_vcf; break;
1748 case 7 : args->convert_func = vcf_to_hapsample; args->outfname = optarg; break;
1749 case 8 : error("The --chrom option has been deprecated, please use --3N6 instead\n"); break;
1750 case 15 : args->gen_3N6 = 1; break;
1751 case 'W':
1752 if (!(args->write_index = write_index_parse(optarg)))
1753 error("Unsupported index format '%s'\n", optarg);
1754 break;
1755 case 'H': args->convert_func = haplegendsample_to_vcf; args->infname = optarg; break;
1756 case 'f': args->ref_fname = optarg; break;
1757 case 'c': args->columns = optarg; break;
1758 case 'o': args->outfname = optarg; break;
1759 case 'O':
1760 switch (optarg[0]) {
1761 case 'b': args->output_type = FT_BCF_GZ; break;
1762 case 'u': args->output_type = FT_BCF; break;
1763 case 'z': args->output_type = FT_VCF_GZ; break;
1764 case 'v': args->output_type = FT_VCF; break;
1765 default:
1766 {
1767 args->clevel = strtol(optarg,&tmp,10);
1768 if ( *tmp || args->clevel<0 || args->clevel>9 ) error("The output type \"%s\" not recognised\n", optarg);
1769 }
1770 }
1771 if ( optarg[1] )
1772 {
1773 args->clevel = strtol(optarg+1,&tmp,10);
1774 if ( *tmp || args->clevel<0 || args->clevel>9 ) error("Could not parse argument: --compression-level %s\n", optarg+1);
1775 }
1776 break;
1777 case 'h': args->convert_func = vcf_to_haplegendsample; args->outfname = optarg; break;
1778 case 9 : args->n_threads = strtol(optarg, 0, 0); break;
1779 case 10 : args->record_cmd_line = 0; break;
1780 case 11 : args->sex_fname = optarg; break;
1781 case 12 : args->keep_duplicates = 1; break;
1782 case 13 :
1783 args->regions_overlap = parse_overlap_option(optarg);
1784 if ( args->regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg);
1785 break;
1786 case 14 :
1787 args->targets_overlap = parse_overlap_option(optarg);
1788 if ( args->targets_overlap < 0 ) error("Could not parse: --targets-overlap %s\n",optarg);
1789 break;
1790 case '?': usage(); break;
1791 default: error("Unknown argument: %s\n", optarg);
1792 }
1793 }
1794
1795 if ( !args->infname )
1796 {
1797 if ( optind>=argc )
1798 {
1799 if ( !isatty(fileno((FILE *)stdin)) ) args->infname = "-";
1800 }
1801 else args->infname = argv[optind];
1802 }
1803 if ( !args->infname ) usage();
1804
1805 if ( args->convert_func ) args->convert_func(args);
1806 else vcf_to_vcf(args);
1807
1808 destroy_data(args);
1809 free(args);
1810 return 0;
1811 }