Debian Codegraph @

bcftools/vcfconvert.c.pysam.c

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