Debian Codegraph @

bcftools/convert.c

raw symbols SCIP
1 /* convert.c -- functions for converting between VCF/BCF and related formats.
2
3 Copyright (C) 2013-2024 Genome Research Ltd.
4
5 Author: Petr Danecek <[email protected]>
6
7 Permission is hereby granted, free of charge, to any person obtaining a copy
8 of this software and associated documentation files (the "Software"), to deal
9 in the Software without restriction, including without limitation the rights
10 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 copies of the Software, and to permit persons to whom the Software is
12 furnished to do so, subject to the following conditions:
13
14 The above copyright notice and this permission notice shall be included in
15 all copies or substantial portions of the Software.
16
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 THE SOFTWARE. */
24
25 #include <stdio.h>
26 #include <unistd.h>
27 #include <getopt.h>
28 #include <assert.h>
29 #include <ctype.h>
30 #include <string.h>
31 #include <errno.h>
32 #include <sys/stat.h>
33 #include <sys/types.h>
34 #include <stdint.h>
35 #define __STDC_FORMAT_MACROS
36 #include <inttypes.h>
37 #include <math.h>
38 #include <htslib/vcf.h>
39 #include <htslib/synced_bcf_reader.h>
40 #include <htslib/vcfutils.h>
41 #include <htslib/kfunc.h>
42 #include <htslib/khash_str2int.h>
43 #include <htslib/hts_endian.h>
44 #include "bcftools.h"
45 #include "variantkey.h"
46 #include "convert.h"
47 #include "filter.h"
48
49 #define T_CHROM 1
50 #define T_POS 2
51 #define T_ID 3
52 #define T_REF 4
53 #define T_ALT 5
54 #define T_QUAL 6
55 #define T_FILTER 7
56 #define T_INFO 8
57 #define T_FORMAT 9
58 #define T_SAMPLE 10
59 #define T_SEP 11
60 #define T_IS_TS 12
61 #define T_TYPE 13
62 #define T_MASK 14
63 #define T_GT 15
64 #define T_TGT 16
65 #define T_LINE 17
66 #define T_CHROM_POS_ID 18 // not publicly advertised
67 #define T_GT_TO_PROB3 19 // not publicly advertised
68 #define T_PL_TO_PROB3 20 // not publicly advertised
69 #define T_GP_TO_PROB3 21 // not publicly advertised
70 #define T_FIRST_ALT 22 // not publicly advertised
71 #define T_IUPAC_GT 23
72 #define T_GT_TO_HAP 24 // not publicly advertised
73 #define T_GT_TO_HAP2 25 // not publicly advertised
74 #define T_TBCSQ 26
75 #define T_END 27
76 #define T_POS0 28
77 #define T_END0 29
78 #define T_RSX 30 // RSID HEX
79 #define T_VKX 31 // VARIANTKEY HEX
80 #define T_PBINOM 32
81 #define T_NPASS 33
82
83 typedef struct _fmt_t
84 {
85 int type, id, is_gt_field, ready, subscript;
86 char *key;
87 bcf_fmt_t *fmt;
88 void *usr; // user data (optional)
89 void (*handler)(convert_t *, bcf1_t *, struct _fmt_t *, int, kstring_t *);
90 void (*destroy)(void*); // clean user data (optional)
91 }
92 fmt_t;
93
94 struct _convert_t
95 {
96 fmt_t *fmt;
97 int nfmt, mfmt;
98 int nsamples, *samples;
99 bcf_hdr_t *header;
100 int max_unpack;
101 char *format_str;
102 bcf_srs_t *readers; // required only for %MASK
103 int nreaders;
104 void *dat;
105 int ndat;
106 char *undef_info_tag;
107 void *used_tags_hash;
108 char **used_tags_list;
109 char *print_filtered;
110 int nused_tags;
111 int allow_undef_tags;
112 int force_newline;
113 int header_samples;
114 int no_hdr_indices;
115 uint8_t **subset_samples;
116 };
117
118 typedef struct
119 {
120 kstring_t hap1,hap2;
121 char **str;
122 int n, m;
123 }
124 bcsq_t;
125
126 static void process_chrom(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str) { kputs(convert->header->id[BCF_DT_CTG][line->rid].key, str); }
127 static void process_pos(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str) { kputw(line->pos+1, str); }
128 static void process_pos0(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str) { kputw(line->pos, str); }
129 static void process_end(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str) { kputw(line->pos+line->rlen, str); }
130 static void process_end0(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str) { kputw(line->pos+line->rlen-1, str); }
131 static void process_id(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str) { kputs(line->d.id, str); }
132 static void process_ref(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str) { kputs(line->d.allele[0], str); }
133 static void process_alt(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
134 {
135 int i;
136 if ( line->n_allele==1 )
137 {
138 kputc('.', str);
139 return;
140 }
141 if ( fmt->subscript>=0 )
142 {
143 if ( line->n_allele > fmt->subscript+1 )
144 kputs(line->d.allele[fmt->subscript+1], str);
145 else
146 kputc('.', str);
147 return;
148 }
149 for (i=1; i<line->n_allele; i++)
150 {
151 if ( i>1 ) kputc(',', str);
152 kputs(line->d.allele[i], str);
153 }
154 }
155 static void process_first_alt(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
156 {
157 if ( line->n_allele==1 )
158 kputc('.', str);
159 else
160 kputs(line->d.allele[1], str);
161 }
162 static void process_qual(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
163 {
164 if ( bcf_float_is_missing(line->qual) ) kputc('.', str);
165 else kputd(line->qual, str);
166 }
167 static void process_filter(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
168 {
169 int i;
170 if ( line->d.n_flt )
171 {
172 for (i=0; i<line->d.n_flt; i++)
173 {
174 if (i) kputc(';', str);
175 kputs(convert->header->id[BCF_DT_ID][line->d.flt[i]].key, str);
176 }
177 }
178 else kputc('.', str);
179 }
180 static inline int32_t bcf_array_ivalue(uint8_t *bcf_array, int type, int idx)
181 {
182 if ( type==BCF_BT_INT8 )
183 {
184 int8_t val = le_to_i8(&bcf_array[idx * sizeof(val)]);
185 if ( val==bcf_int8_missing ) return bcf_int32_missing;
186 if ( val==bcf_int8_vector_end ) return bcf_int32_vector_end;
187 return val;
188 }
189 if ( type==BCF_BT_INT16 )
190 {
191 int16_t val = le_to_i16(&bcf_array[idx * sizeof(val)]);
192 if ( val==bcf_int16_missing ) return bcf_int32_missing;
193 if ( val==bcf_int16_vector_end ) return bcf_int32_vector_end;
194 return val;
195 }
196 return le_to_i32(&bcf_array[idx * sizeof(int32_t)]);
197 }
198 static inline void _copy_field(char *src, uint32_t len, int idx, kstring_t *str)
199 {
200 int n = 0, ibeg = 0;
201 while ( src[ibeg] && ibeg<len && n < idx )
202 {
203 if ( src[ibeg]==',' ) n++;
204 ibeg++;
205 }
206 if ( ibeg==len ) { kputc('.', str); return; }
207
208 int iend = ibeg;
209 while ( src[iend] && src[iend]!=',' && iend<len ) iend++;
210
211 if ( iend>ibeg )
212 kputsn(src+ibeg, iend-ibeg, str);
213 else
214 kputc('.', str);
215 }
216 static void process_info(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
217 {
218 int i;
219 if ( !fmt->key ) // the whole INFO column
220 {
221 int first = 1;
222 for (i=0; i<line->n_info; i++)
223 {
224 bcf_info_t *inf = &line->d.info[i];
225 if ( !inf->vptr ) continue;
226 if ( !first ) kputc(';', str);
227 first = 0;
228 if ( inf->key >= convert->header->n[BCF_DT_ID] ) continue;
229 kputs(convert->header->id[BCF_DT_ID][inf->key].key, str);
230 if ( inf->len <= 0 ) continue;
231 kputc('=', str);
232 if ( inf->len == 1 )
233 {
234 switch (inf->type)
235 {
236 case BCF_BT_INT8: if ( inf->v1.i==bcf_int8_missing ) kputc('.', str); else kputw(inf->v1.i, str); break;
237 case BCF_BT_INT16: if ( inf->v1.i==bcf_int16_missing ) kputc('.', str); else kputw(inf->v1.i, str); break;
238 case BCF_BT_INT32: if ( inf->v1.i==bcf_int32_missing ) kputc('.', str); else kputw(inf->v1.i, str); break;
239 case BCF_BT_FLOAT: if ( bcf_float_is_missing(inf->v1.f) ) kputc('.', str); else kputd(inf->v1.f, str); break;
240 case BCF_BT_CHAR: kputc(inf->v1.i, str); break;
241 default: error("Unexpected type %d", inf->type); break;
242 }
243 }
244 else bcf_fmt_array(str, inf->len, inf->type, inf->vptr);
245 }
246 if ( first ) kputc('.', str);
247 return;
248 }
249
250 if ( fmt->id<0 )
251 {
252 kputc('.', str);
253 return;
254 }
255
256 for (i=0; i<line->n_info; i++)
257 if ( line->d.info[i].key == fmt->id ) break;
258
259 // output "." if the tag is not present
260 if ( i==line->n_info )
261 {
262 kputc('.', str);
263 return;
264 }
265
266 bcf_info_t *info = &line->d.info[i];
267
268 // if this is a flag, output 1
269 if ( info->len <=0 )
270 {
271 kputc('1', str);
272 return;
273 }
274
275 if ( info->len == 1 )
276 {
277 switch (info->type)
278 {
279 case BCF_BT_INT8: if ( info->v1.i==bcf_int8_missing ) kputc('.', str); else kputw(info->v1.i, str); break;
280 case BCF_BT_INT16: if ( info->v1.i==bcf_int16_missing ) kputc('.', str); else kputw(info->v1.i, str); break;
281 case BCF_BT_INT32: if ( info->v1.i==bcf_int32_missing ) kputc('.', str); else kputw(info->v1.i, str); break;
282 case BCF_BT_FLOAT: if ( bcf_float_is_missing(info->v1.f) ) kputc('.', str); else kputd(info->v1.f, str); break;
283 case BCF_BT_CHAR: kputc(info->v1.i, str); break;
284 default: fprintf(stderr,"todo: type %d\n", info->type); exit(1); break;
285 }
286 }
287 else if ( fmt->subscript >=0 )
288 {
289 if ( info->len <= fmt->subscript )
290 {
291 kputc('.', str);
292 return;
293 }
294 #define BRANCH(type_t, convert, is_missing, is_vector_end, kprint) { \
295 type_t val = convert(&info->vptr[fmt->subscript * sizeof(type_t)]); \
296 if ( is_missing || is_vector_end ) kputc('.',str); \
297 else kprint; \
298 }
299 switch (info->type)
300 {
301 case BCF_BT_INT8: BRANCH(int8_t, le_to_i8, val==bcf_int8_missing, val==bcf_int8_vector_end, kputw(val, str)); break;
302 case BCF_BT_INT16: BRANCH(int16_t, le_to_i16, val==bcf_int16_missing, val==bcf_int16_vector_end, kputw(val, str)); break;
303 case BCF_BT_INT32: BRANCH(int32_t, le_to_i32, val==bcf_int32_missing, val==bcf_int32_vector_end, kputw(val, str)); break;
304 case BCF_BT_FLOAT: BRANCH(float, le_to_float, bcf_float_is_missing(val), bcf_float_is_vector_end(val), kputd(val, str)); break;
305 case BCF_BT_CHAR: _copy_field((char*)info->vptr, info->vptr_len, fmt->subscript, str); break;
306 default: fprintf(stderr,"todo: type %d\n", info->type); exit(1); break;
307 }
308 #undef BRANCH
309 }
310 else
311 bcf_fmt_array(str, info->len, info->type, info->vptr);
312 }
313 static void init_format(convert_t *convert, bcf1_t *line, fmt_t *fmt)
314 {
315 fmt->id = bcf_hdr_id2int(convert->header, BCF_DT_ID, fmt->key);
316 if ( !bcf_hdr_idinfo_exists(convert->header,BCF_HL_FMT,fmt->id) ) fmt->id = -1;
317 fmt->fmt = NULL;
318 if ( fmt->id >= 0 )
319 {
320 int i;
321 for (i=0; i<(int)line->n_fmt; i++)
322 if ( line->d.fmt[i].id==fmt->id ) { fmt->fmt = &line->d.fmt[i]; break; }
323 }
324 else if ( !convert->allow_undef_tags )
325 error("Error: no such tag defined in the VCF header: FORMAT/%s\n", fmt->key);
326
327 fmt->ready = 1;
328 }
329 static void process_complete_format(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
330 {
331 if ( convert->nsamples )
332 {
333 int i,j;
334 if ( line->n_fmt)
335 {
336 int gt_i = -1;
337 bcf_fmt_t *fmt = line->d.fmt;
338 int first = 1;
339 for (i=0; i<(int)line->n_fmt; i++)
340 {
341 if ( !fmt[i].p || fmt[i].id<0 ) continue;
342 if ( !first ) kputc(':', str);
343 first = 0;
344 kputs(convert->header->id[BCF_DT_ID][fmt[i].id].key, str);
345 if ( strcmp(convert->header->id[BCF_DT_ID][fmt[i].id].key, "GT") == 0) gt_i = i;
346 }
347 if ( first ) kputc('.', str);
348 for (j=0; j<convert->nsamples; j++)
349 {
350 kputc('\t', str);
351 first = 1;
352 for (i=0; i<(int)line->n_fmt; i++)
353 {
354 bcf_fmt_t *f = &fmt[i];
355 if ( !f->p ) continue;
356 if ( !first ) kputc(':', str);
357 first = 0;
358 if (gt_i == i)
359 bcf_format_gt(f,convert->samples[j],str);
360 else
361 bcf_fmt_array(str, f->n, f->type, f->p + convert->samples[j] * f->size);
362 }
363 if ( first ) kputc('.', str);
364 }
365 }
366 else
367 for (j=0; j<=line->n_sample; j++)
368 kputs("\t.", str);
369 }
370 else
371 kputc('.',str);
372 }
373 static void process_format(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
374 {
375 if ( !fmt->ready )
376 init_format(convert, line, fmt);
377
378 if ( fmt->fmt==NULL )
379 {
380 kputc('.', str);
381 return;
382 }
383 else if ( fmt->subscript >=0 )
384 {
385 if ( fmt->fmt->n <= fmt->subscript )
386 {
387 kputc('.', str);
388 return;
389 }
390 if ( fmt->fmt->type == BCF_BT_FLOAT )
391 {
392 uint8_t *ptr = fmt->fmt->p + isample*fmt->fmt->size;
393 float val = le_to_float(&ptr[fmt->subscript * sizeof(float)]);
394 if ( bcf_float_is_missing(val) || bcf_float_is_vector_end(val) )
395 kputc('.', str);
396 else
397 kputd(val, str);
398 }
399 else if ( fmt->fmt->type != BCF_BT_CHAR )
400 {
401 int32_t ival = bcf_array_ivalue(fmt->fmt->p+isample*fmt->fmt->size,fmt->fmt->type,fmt->subscript);
402 if ( ival==bcf_int32_missing || ival==bcf_int32_vector_end )
403 kputc('.', str);
404 else
405 kputw(ival, str);
406 }
407 else if ( fmt->fmt->type == BCF_BT_CHAR )
408 _copy_field((char*)(fmt->fmt->p + isample*fmt->fmt->size), fmt->fmt->size, fmt->subscript, str);
409 else error("TODO: %s:%d .. fmt->type=%d\n", __FILE__,__LINE__, fmt->fmt->type);
410 }
411 else
412 bcf_fmt_array(str, fmt->fmt->n, fmt->fmt->type, fmt->fmt->p + isample*fmt->fmt->size);
413 }
414 static void process_gt(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
415 {
416 if ( !fmt->ready )
417 init_format(convert, line, fmt);
418
419 if ( fmt->fmt==NULL )
420 {
421 kputc('.', str);
422 return;
423 }
424 bcf_format_gt(fmt->fmt, isample, str);
425 }
426 static void process_tgt(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
427 {
428 if ( !fmt->ready )
429 init_format(convert, line, fmt);
430
431 if ( fmt->fmt==NULL )
432 {
433 kputc('.', str);
434 return;
435 }
436
437 assert( fmt->fmt->type==BCF_BT_INT8 );
438
439 int l;
440 int8_t *x = (int8_t*)(fmt->fmt->p + isample*fmt->fmt->size); // FIXME: does not work with n_alt >= 64
441 for (l = 0; l < fmt->fmt->n && x[l] != bcf_int8_vector_end; ++l)
442 {
443 if (l) kputc("/|"[x[l]&1], str);
444 if (x[l]>>1)
445 {
446 int ial = (x[l]>>1) - 1;
447 kputs(line->d.allele[ial], str);
448 }
449 else
450 kputc('.', str);
451 }
452 if (l == 0) kputc('.', str);
453 }
454 static void destroy_tbcsq(void *usr)
455 {
456 if ( !usr ) return;
457 bcsq_t *csq = (bcsq_t*) usr;
458 free(csq->hap1.s);
459 free(csq->hap2.s);
460 if ( csq->n )
461 free(csq->str[0]);
462 free(csq->str);
463 free(csq);
464 }
465 static void process_tbcsq(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
466 {
467 if ( !fmt->ready )
468 {
469 init_format(convert, line, fmt);
470
471 bcsq_t *csq;
472 if ( fmt->usr )
473 {
474 csq = (bcsq_t*) fmt->usr;
475 if ( csq->n )
476 free(csq->str[0]);
477 csq->n = 0;
478 }
479 else
480 csq = (bcsq_t*) calloc(1,sizeof(bcsq_t));
481 fmt->usr = csq;
482
483 int i=0, len = 0;
484 char *tmp = NULL;
485 if ( bcf_get_info_string(convert->header,line,fmt->key,&tmp,&len)<0 )
486 {
487 csq->n = 0;
488 return;
489 }
490 do
491 {
492 csq->n++;
493 hts_expand(char*, csq->n, csq->m, csq->str);
494 csq->str[ csq->n-1 ] = tmp + i;
495 while ( i<len && tmp[i]!=',' ) i++;
496 if ( i<len && tmp[i]==',' ) tmp[i++] = 0;
497 }
498 while ( i<len );
499 }
500
501 bcsq_t *csq = (bcsq_t*)fmt->usr;
502
503 if ( fmt->fmt==NULL || !csq->n ) return;
504
505 csq->hap1.l = 0;
506 csq->hap2.l = 0;
507
508 int mask = fmt->subscript==0 ? 3 : 1; // merge both haplotypes if subscript==0
509
510 #define BRANCH(type_t, convert, nbits) { \
511 uint8_t *x = fmt->fmt->p + isample*fmt->fmt->size; \
512 int i,j; \
513 if ( fmt->subscript<=0 || fmt->subscript==1 ) \
514 { \
515 for (j=0; j < fmt->fmt->n; j++) \
516 { \
517 type_t val = convert(&x[j * sizeof(type_t)]); \
518 if ( !val ) continue; \
519 for (i=0; i<nbits; i+=2) \
520 if ( val & (mask<<i) ) { kputs(csq->str[(j*30+i)/2], &csq->hap1); kputc_(',', &csq->hap1); } \
521 } \
522 } \
523 if ( fmt->subscript<0 || fmt->subscript==2 ) \
524 { \
525 for (j=0; j < fmt->fmt->n; j++) \
526 { \
527 type_t val = convert(&x[j * sizeof(type_t)]); \
528 if ( !val ) continue; \
529 for (i=1; i<nbits; i+=2) \
530 if ( val & (1<<i) ) { kputs(csq->str[(j*30+i)/2], &csq->hap2); kputc_(',', &csq->hap2); } \
531 } \
532 } \
533 }
534 switch (fmt->fmt->type)
535 {
536 case BCF_BT_INT8: BRANCH(uint8_t, le_to_u8, 8); break;
537 case BCF_BT_INT16: BRANCH(uint16_t, le_to_u16, 16); break;
538 case BCF_BT_INT32: BRANCH(uint32_t, le_to_u32, 30); break; // 2 bits unused to account for the reserved BCF values
539 default: error("Unexpected type: %d\n", fmt->fmt->type); exit(1); break;
540 }
541 #undef BRANCH
542
543 if ( !csq->hap1.l && !csq->hap2.l ) return;
544
545 if ( csq->hap1.l ) csq->hap1.s[--csq->hap1.l] = 0;
546 if ( csq->hap2.l ) csq->hap2.s[--csq->hap2.l] = 0;
547
548 if ( fmt->subscript<0 )
549 {
550 kputs(csq->hap1.l?csq->hap1.s:".", str);
551 kputc_('\t', str);
552 kputs(csq->hap2.l?csq->hap2.s:".", str);
553 }
554 else if ( fmt->subscript<2 )
555 kputs(csq->hap1.l?csq->hap1.s:".", str);
556 else
557 kputs(csq->hap2.l?csq->hap2.s:".", str);
558 }
559 static void init_format_iupac(convert_t *convert, bcf1_t *line, fmt_t *fmt)
560 {
561 init_format(convert, line, fmt);
562 if ( fmt->fmt==NULL ) return;
563
564 // Init mapping between alleles and IUPAC table
565 hts_expand(uint8_t, line->n_allele, convert->ndat, convert->dat);
566 int8_t *dat = (int8_t*)convert->dat;
567 int i;
568 for (i=0; i<line->n_allele; i++)
569 {
570 if ( line->d.allele[i][1] ) dat[i] = -1;
571 else
572 {
573 switch (line->d.allele[i][0])
574 {
575 case 'A': dat[i] = 0; break;
576 case 'C': dat[i] = 1; break;
577 case 'G': dat[i] = 2; break;
578 case 'T': dat[i] = 3; break;
579 case 'a': dat[i] = 0; break;
580 case 'c': dat[i] = 1; break;
581 case 'g': dat[i] = 2; break;
582 case 't': dat[i] = 3; break;
583 default: dat[i] = -1;
584 }
585 }
586 }
587 }
588 static void process_iupac_gt(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
589 {
590 if ( !fmt->ready )
591 init_format_iupac(convert, line, fmt);
592
593 if ( fmt->fmt==NULL )
594 {
595 kputc('.', str);
596 return;
597 }
598
599 assert( fmt->fmt->type==BCF_BT_INT8 );
600
601 static const char iupac[4][4] = { {'A','M','R','W'},{'M','C','S','Y'},{'R','S','G','K'},{'W','Y','K','T'} };
602 int8_t *dat = (int8_t*)convert->dat;
603
604 int8_t *x = (int8_t*)(fmt->fmt->p + isample*fmt->fmt->size); // FIXME: does not work with n_alt >= 64
605 int l = 0;
606 while ( l<fmt->fmt->n && x[l]!=bcf_int8_vector_end && x[l]!=bcf_int8_missing ) l++;
607
608 if ( l==2 )
609 {
610 // diploid
611 int ia = (x[0]>>1) - 1, ib = (x[1]>>1) - 1;
612 if ( ia>=0 && ia<line->n_allele && ib>=0 && ib<line->n_allele && dat[ia]>=0 && dat[ib]>=0 )
613 {
614 kputc(iupac[dat[ia]][dat[ib]], str);
615 return;
616 }
617 }
618 for (l = 0; l < fmt->fmt->n && x[l] != bcf_int8_vector_end; ++l)
619 {
620 if (l) kputc("/|"[x[l]&1], str);
621 if (x[l]>>1)
622 {
623 int ial = (x[l]>>1) - 1;
624 kputs(line->d.allele[ial], str);
625 }
626 else
627 kputc('.', str);
628 }
629 if (l == 0) kputc('.', str);
630 }
631 static void process_sample(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
632 {
633 kputs(convert->header->samples[isample], str);
634 }
635 static void process_sep(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str) { if (fmt->key) kputs(fmt->key, str); }
636 static void process_is_ts(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
637 {
638 int is_ts = 0;
639 if ( bcf_get_variant_types(line) & (VCF_SNP|VCF_MNP) )
640 is_ts = abs(bcf_acgt2int(*line->d.allele[0])-bcf_acgt2int(*line->d.allele[1])) == 2 ? 1 : 0;
641 kputc(is_ts ? '1' : '0', str);
642 }
643 static void process_type(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
644 {
645 int line_type = bcf_get_variant_types(line);
646 int i = 0;
647 if ( line_type == VCF_REF ) { kputs("REF", str); i++; }
648 if ( line_type & VCF_SNP ) { if (i) kputc(',',str); kputs("SNP", str); i++; }
649 if ( line_type & VCF_MNP ) { if (i) kputc(',',str); kputs("MNP", str); i++; }
650 if ( line_type & VCF_INDEL ) { if (i) kputc(',',str); kputs("INDEL", str); i++; }
651 if ( line_type & VCF_OTHER ) { if (i) kputc(',',str); kputs("OTHER", str); i++; }
652 if ( line_type & VCF_BND ) { if (i) kputc(',',str); kputs("BND", str); i++; }
653 if ( line_type & VCF_OVERLAP ) { if (i) kputc(',',str); kputs("OVERLAP", str); i++; }
654 }
655 static void process_line(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
656 {
657 vcf_format1(convert->header, line, str);
658 if ( str->s[str->l-1]=='\n' ) str->l--;
659 }
660 static void process_chrom_pos_id(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
661 {
662 if ( line->d.id[0]!='.' || line->d.id[1] )
663 {
664 // ID is present
665 kputs(line->d.id, str);
666 }
667 else
668 {
669 // use CHROM:POS instead of ID
670 kputs(convert->header->id[BCF_DT_CTG][line->rid].key, str);
671 kputc(':', str);
672 kputw(line->pos+1, str);
673 }
674 }
675 static void process_gt_to_prob3(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
676 {
677 int m,n,i;
678
679 m = convert->ndat / sizeof(int32_t);
680 n = bcf_get_genotypes(convert->header,line,&convert->dat,&m);
681 convert->ndat = m * sizeof(int32_t);
682
683 if ( n<=0 )
684 {
685 // Throw an error or silently proceed?
686 //
687 // for (i=0; i<convert->nsamples; i++) kputs(" 0.33 0.33 0.33", str);
688 // return;
689
690 error("Error parsing GT tag at %s:%"PRId64"\n", bcf_seqname(convert->header,line),(int64_t) line->pos+1);
691 }
692
693 n /= convert->nsamples;
694 for (i=0; i<convert->nsamples; i++)
695 {
696 int32_t *ptr = (int32_t*)convert->dat + i*n;
697 int j;
698 for (j=0; j<n; j++)
699 if ( ptr[j]==bcf_int32_vector_end ) break;
700
701 if ( j==2 )
702 {
703 // diploid
704 if ( bcf_gt_is_missing(ptr[0]) )
705 kputs(" 0.33 0.33 0.33", str);
706 else if ( bcf_gt_allele(ptr[0])!=bcf_gt_allele(ptr[1]) )
707 kputs(" 0 1 0", str); // HET
708 else if ( bcf_gt_allele(ptr[0])==1 )
709 kputs(" 0 0 1", str); // ALT HOM, first ALT allele
710 else
711 kputs(" 1 0 0", str); // REF HOM or something else than first ALT
712 }
713 else if ( j==1 )
714 {
715 // haploid
716 if ( bcf_gt_is_missing(ptr[0]) )
717 kputs(" 0.5 0.0 0.5", str);
718 else if ( bcf_gt_allele(ptr[0])==1 )
719 kputs(" 0 0 1", str); // first ALT allele
720 else
721 kputs(" 1 0 0", str); // REF or something else than first ALT
722 }
723 else error("FIXME: not ready for ploidy %d\n", j);
724 }
725 }
726 static void process_pl_to_prob3(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
727 {
728 int m,n,i;
729
730 m = convert->ndat / sizeof(int32_t);
731 n = bcf_get_format_int32(convert->header,line,"PL",&convert->dat,&m);
732 convert->ndat = m * sizeof(int32_t);
733
734 if ( n<=0 )
735 {
736 // Throw an error or silently proceed?
737 //
738 // for (i=0; i<convert->nsamples; i++) kputs(" 0.33 0.33 0.33", str);
739 // return;
740
741 error("Error parsing PL tag at %s:%"PRId64"\n", bcf_seqname(convert->header,line),(int64_t) line->pos+1);
742 }
743
744 n /= convert->nsamples;
745 for (i=0; i<convert->nsamples; i++)
746 {
747 int32_t *ptr = (int32_t*)convert->dat + i*n;
748 int j;
749 float sum = 0;
750 for (j=0; j<n; j++)
751 {
752 if ( ptr[j]==bcf_int32_vector_end ) break;
753 sum += pow(10,-0.1*ptr[j]);
754 }
755 if ( j==line->n_allele )
756 {
757 // haploid
758 kputc(' ',str);
759 ksprintf(str,"%f",pow(10,-0.1*ptr[0])/sum);
760 kputs(" 0 ", str);
761 ksprintf(str,"%f",pow(10,-0.1*ptr[1])/sum);
762 }
763 else
764 {
765 // diploid
766 kputc(' ',str);
767 ksprintf(str,"%f",pow(10,-0.1*ptr[0])/sum);
768 kputc(' ',str);
769 ksprintf(str,"%f",pow(10,-0.1*ptr[1])/sum);
770 kputc(' ',str);
771 ksprintf(str,"%f",pow(10,-0.1*ptr[2])/sum);
772 }
773 }
774 }
775 static void process_gp_to_prob3(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
776 {
777 int m,n,i;
778
779 m = convert->ndat / sizeof(float);
780 n = bcf_get_format_float(convert->header,line,"GP",&convert->dat,&m);
781 convert->ndat = m * sizeof(float);
782
783 if ( n<=0 )
784 {
785 // Throw an error or silently proceed?
786 //
787 // for (i=0; i<convert->nsamples; i++) kputs(" 0.33 0.33 0.33", str);
788 // return;
789
790 error("Error parsing GP tag at %s:%"PRId64"\n", bcf_seqname(convert->header,line),(int64_t) line->pos+1);
791 }
792
793 n /= convert->nsamples;
794 for (i=0; i<convert->nsamples; i++)
795 {
796 float *ptr = (float*)convert->dat + i*n;
797 int j;
798 for (j=0; j<n; j++)
799 {
800 if ( bcf_float_is_vector_end(ptr[j]) ) break;
801 if ( bcf_float_is_missing(ptr[j]) ) { ptr[j]=0; continue; }
802 if ( ptr[j]<0 || ptr[j]>1 ) error("[%s:%"PRId64":%f] GP value outside range [0,1]; bcftools convert expects the VCF4.3+ spec for the GP field encoding genotype posterior probabilities", bcf_seqname(convert->header,line),(int64_t) line->pos+1,ptr[j]);
803 }
804 if ( j==line->n_allele )
805 ksprintf(str," %f %f %f",ptr[0],0.,ptr[1]); // haploid
806 else
807 ksprintf(str," %f %f %f",ptr[0],ptr[1],ptr[2]); // diploid
808 }
809 }
810
811 static void process_gt_to_hap(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
812 {
813 // https://mathgen.stats.ox.ac.uk/impute/impute_v2.html#-known_haps_g
814
815 // File containing known haplotypes for the study cohort. The format
816 // is the same as the output format from IMPUTE2's -phase option:
817 // five header columns (as in the -g file) followed by two columns
818 // (haplotypes) per individual. Allowed values in the haplotype
819 // columns are 0, 1, and ?.
820
821 // If your study dataset is fully phased, you can replace the -g file
822 // with a -known_haps_g file. This will cause IMPUTE2 to perform
823 // haploid imputation, although it will still report diploid imputation
824 // probabilities in the main output file. If any genotypes are missing,
825 // they can be marked as '? ?' (two question marks separated by one
826 // space) in the input file. (The program does not allow just one
827 // allele from a diploid genotype to be missing.) If the reference
828 // panels are also phased, IMPUTE2 will perform a single, fast
829 // imputation step rather than its standard MCMC module this is how
830 // the program imputes into pre-phased GWAS haplotypes.
831
832 // The -known_haps_g file can also be used to specify study
833 // genotypes that are "partially" phased, in the sense that some
834 // genotypes are phased relative to a fixed reference point while
835 // others are not. We anticipate that this will be most useful when
836 // trying to phase resequencing data onto a scaffold of known
837 // haplotypes. To mark a known genotype as unphased, place an
838 // asterisk immediately after each allele, with no space between
839 // the allele (0/1) and the asterisk (*); e.g., "0* 1*" for a
840 // heterozygous genotype of unknown phase.
841
842 int i, gt_id = bcf_hdr_id2int(convert->header, BCF_DT_ID, "GT");
843 if ( !bcf_hdr_idinfo_exists(convert->header,BCF_HL_FMT,gt_id) )
844 error("FORMAT/GT tag not present at %s:%"PRId64"\n", bcf_seqname(convert->header, line),(int64_t) line->pos+1);
845 if ( !(line->unpacked & BCF_UN_FMT) ) bcf_unpack(line, BCF_UN_FMT);
846 bcf_fmt_t *fmt_gt = NULL;
847 for (i=0; i<line->n_fmt; i++)
848 if ( line->d.fmt[i].id==gt_id ) { fmt_gt = &line->d.fmt[i]; break; }
849 if ( !fmt_gt )
850 error("FORMAT/GT tag not present at %s:%"PRId64"\n", bcf_seqname(convert->header, line),(int64_t) line->pos+1);
851
852 // Alloc all memory in advance to avoid kput routines. The biggest allowed allele index is 99
853 if ( line->n_allele > 100 )
854 error("Too many alleles (%d) at %s:%"PRId64"\n", line->n_allele, bcf_seqname(convert->header, line),(int64_t) line->pos+1);
855 if ( ks_resize(str, str->l+convert->nsamples*8) != 0 )
856 error("Could not alloc %" PRIu64 " bytes\n", (uint64_t)(str->l + convert->nsamples*8));
857
858 if ( fmt_gt->type!=BCF_BT_INT8 ) // todo: use BRANCH_INT if the VCF is valid
859 error("Uh, too many alleles (%d) or redundant BCF representation at %s:%"PRId64"\n", line->n_allele, bcf_seqname(convert->header, line),(int64_t) line->pos+1);
860 if ( fmt_gt->n!=1 && fmt_gt->n!=2 )
861 error("Uh, ploidy of %d not supported, see %s:%"PRId64"\n", fmt_gt->n, bcf_seqname(convert->header, line),(int64_t) line->pos+1);
862
863 int8_t *ptr = ((int8_t*) fmt_gt->p) - fmt_gt->n;
864 for (i=0; i<convert->nsamples; i++)
865 {
866 ptr += fmt_gt->n;
867 if ( fmt_gt->n==1 ) // haploid genotypes
868 {
869 if ( ptr[0]==2 ) /* 0 */
870 {
871 str->s[str->l++] = '0'; str->s[str->l++] = ' '; str->s[str->l++] = '-'; str->s[str->l++] = ' ';
872 }
873 else if ( ptr[0]==bcf_int8_missing ) /* . */
874 {
875 str->s[str->l++] = '?'; str->s[str->l++] = ' '; str->s[str->l++] = '?'; str->s[str->l++] = ' ';
876 }
877 else if ( ptr[0]==4 ) /* 1 */
878 {
879 str->s[str->l++] = '1'; str->s[str->l++] = ' '; str->s[str->l++] = '-'; str->s[str->l++] = ' ';
880 }
881 else
882 {
883 kputw(bcf_gt_allele(ptr[0]),str); str->s[str->l++] = ' '; str->s[str->l++] = '-'; str->s[str->l++] = ' ';
884 }
885 }
886 else if ( ptr[0]==2 )
887 {
888 if ( ptr[1]==3 ) /* 0|0 */
889 {
890 str->s[str->l++] = '0'; str->s[str->l++] = ' '; str->s[str->l++] = '0'; str->s[str->l++] = ' ';
891 }
892 else if ( ptr[1]==5 ) /* 0|1 */
893 {
894 str->s[str->l++] = '0'; str->s[str->l++] = ' '; str->s[str->l++] = '1'; str->s[str->l++] = ' ';
895 }
896 else if ( ptr[1]==bcf_int8_vector_end ) /* 0 */
897 {
898 str->s[str->l++] = '0'; str->s[str->l++] = ' '; str->s[str->l++] = '-'; str->s[str->l++] = ' ';
899 }
900 else if ( ptr[1]==2 ) /* 0/0 */
901 {
902 str->s[str->l++] = '0'; str->s[str->l++] = '*'; str->s[str->l++] = ' '; str->s[str->l++] = '0'; str->s[str->l++] = '*'; str->s[str->l++] = ' ';
903 }
904 else if ( ptr[1]==4 ) /* 0/1 */
905 {
906 str->s[str->l++] = '0'; str->s[str->l++] = '*'; str->s[str->l++] = ' '; str->s[str->l++] = '1'; str->s[str->l++] = '*'; str->s[str->l++] = ' ';
907 }
908 else if ( bcf_gt_is_missing(ptr[1]) ) /* 0/. */
909 {
910 str->s[str->l++] = '?'; str->s[str->l++] = ' '; str->s[str->l++] = '?'; str->s[str->l++] = ' ';
911 }
912 else if ( bcf_gt_is_phased(ptr[1]) ) /* 0|x */
913 {
914 str->s[str->l++] = '0'; str->s[str->l++] = ' ';
915 kputw(bcf_gt_allele(ptr[1]),str);
916 str->s[str->l++] = ' ';
917 }
918 else /* 0/x */
919 {
920 str->s[str->l++] = '0'; str->s[str->l++] = '*'; str->s[str->l++] = ' ';
921 kputw(bcf_gt_allele(ptr[1]),str);
922 str->s[str->l++] = '*'; str->s[str->l++] = ' ';
923 }
924 }
925 else if ( ptr[0]==4 )
926 {
927 if ( ptr[1]==3 ) /* 1|0 */
928 {
929 str->s[str->l++] = '1'; str->s[str->l++] = ' '; str->s[str->l++] = '0'; str->s[str->l++] = ' ';
930 }
931 else if ( ptr[1]==5 ) /* 1|1 */
932 {
933 str->s[str->l++] = '1'; str->s[str->l++] = ' '; str->s[str->l++] = '1'; str->s[str->l++] = ' ';
934 }
935 else if ( ptr[1]==bcf_int8_vector_end ) /* 1 */
936 {
937 str->s[str->l++] = '1'; str->s[str->l++] = ' '; str->s[str->l++] = '-'; str->s[str->l++] = ' ';
938 }
939 else if ( ptr[1]==2 ) /* 1/0 */
940 {
941 str->s[str->l++] = '1'; str->s[str->l++] = '*'; str->s[str->l++] = ' '; str->s[str->l++] = '0'; str->s[str->l++] = '*'; str->s[str->l++] = ' ';
942 }
943 else if ( ptr[1]==4 ) /* 1/1 */
944 {
945 str->s[str->l++] = '1'; str->s[str->l++] = '*'; str->s[str->l++] = ' '; str->s[str->l++] = '1'; str->s[str->l++] = '*'; str->s[str->l++] = ' ';
946 }
947 else if ( bcf_gt_is_missing(ptr[1]) ) /* 1/. */
948 {
949 str->s[str->l++] = '?'; str->s[str->l++] = ' '; str->s[str->l++] = '?'; str->s[str->l++] = ' ';
950 }
951 else if ( bcf_gt_is_phased(ptr[1]) ) /* 1|x */
952 {
953 str->s[str->l++] = '1'; str->s[str->l++] = ' ';
954 kputw(bcf_gt_allele(ptr[1]),str);
955 str->s[str->l++] = ' ';
956 }
957 else /* 1/x */
958 {
959 str->s[str->l++] = '1'; str->s[str->l++] = '*'; str->s[str->l++] = ' ';
960 kputw(bcf_gt_allele(ptr[1]),str);
961 str->s[str->l++] = '*'; str->s[str->l++] = ' ';
962 }
963 }
964 else if ( bcf_gt_is_missing(ptr[0]) )
965 {
966 if ( ptr[1]==bcf_int8_vector_end )
967 {
968 str->s[str->l++] = '?'; str->s[str->l++] = ' '; str->s[str->l++] = '-'; str->s[str->l++] = ' ';
969 }
970 else
971 {
972 str->s[str->l++] = '?'; str->s[str->l++] = ' '; str->s[str->l++] = '?'; str->s[str->l++] = ' ';
973 }
974 }
975 else if ( ptr[1]==bcf_int8_vector_end )
976 {
977 /* use REF for something else than first ALT */
978 str->s[str->l++] = '0'; str->s[str->l++] = ' '; str->s[str->l++] = '-'; str->s[str->l++] = ' ';
979 }
980 else
981 {
982 kputw(bcf_gt_allele(ptr[0]),str);
983 if ( bcf_gt_is_phased(ptr[1]) ) str->s[str->l++] = '*';
984 str->s[str->l++] = ' ';
985 kputw(bcf_gt_allele(ptr[1]),str);
986 if ( bcf_gt_is_phased(ptr[1]) ) str->s[str->l++] = '*';
987 str->s[str->l++] = ' ';
988 }
989 }
990 str->s[--str->l] = 0; // delete the last space
991 }
992 static void process_gt_to_hap2(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
993 {
994 // same as process_gt_to_hap but converts haploid genotypes into diploid
995
996 int i, gt_id = bcf_hdr_id2int(convert->header, BCF_DT_ID, "GT");
997 if ( !bcf_hdr_idinfo_exists(convert->header,BCF_HL_FMT,gt_id) )
998 error("FORMAT/GT tag not present at %s:%"PRId64"\n", bcf_seqname(convert->header, line),(int64_t) line->pos+1);
999 if ( !(line->unpacked & BCF_UN_FMT) ) bcf_unpack(line, BCF_UN_FMT);
1000 bcf_fmt_t *fmt_gt = NULL;
1001 for (i=0; i<line->n_fmt; i++)
1002 if ( line->d.fmt[i].id==gt_id ) { fmt_gt = &line->d.fmt[i]; break; }
1003 if ( !fmt_gt )
1004 error("FORMAT/GT tag not present at %s:%"PRId64"\n", bcf_seqname(convert->header, line),(int64_t) line->pos+1);
1005
1006 // Alloc all memory in advance to avoid kput routines. The biggest allowed allele index is 99
1007 if ( line->n_allele > 100 )
1008 error("Too many alleles (%d) at %s:%"PRId64"\n", line->n_allele, bcf_seqname(convert->header, line),(int64_t) line->pos+1);
1009 if ( ks_resize(str, str->l+convert->nsamples*8) != 0 )
1010 error("Could not alloc %" PRIu64 " bytes\n", (uint64_t)(str->l + convert->nsamples*8));
1011
1012 if ( fmt_gt->type!=BCF_BT_INT8 ) // todo: use BRANCH_INT if the VCF is valid
1013 error("Uh, too many alleles (%d) or redundant BCF representation at %s:%"PRId64"\n", line->n_allele, bcf_seqname(convert->header, line),(int64_t) line->pos+1);
1014
1015 int8_t *ptr = ((int8_t*) fmt_gt->p) - fmt_gt->n;
1016 for (i=0; i<convert->nsamples; i++)
1017 {
1018 ptr += fmt_gt->n;
1019 if ( ptr[0]==2 )
1020 {
1021 if ( ptr[1]==3 ) /* 0|0 */
1022 {
1023 str->s[str->l++] = '0'; str->s[str->l++] = ' '; str->s[str->l++] = '0'; str->s[str->l++] = ' ';
1024 }
1025 else if ( ptr[1]==5 ) /* 0|1 */
1026 {
1027 str->s[str->l++] = '0'; str->s[str->l++] = ' '; str->s[str->l++] = '1'; str->s[str->l++] = ' ';
1028 }
1029 else if ( ptr[1]==bcf_int8_vector_end ) /* 0 -> 0|0 */
1030 {
1031 str->s[str->l++] = '0'; str->s[str->l++] = ' '; str->s[str->l++] = '0'; str->s[str->l++] = ' ';
1032 }
1033 else if ( ptr[1]==2 ) /* 0/0 */
1034 {
1035 str->s[str->l++] = '0'; str->s[str->l++] = '*'; str->s[str->l++] = ' '; str->s[str->l++] = '0'; str->s[str->l++] = '*'; str->s[str->l++] = ' ';
1036 }
1037 else if ( ptr[1]==4 ) /* 0/1 */
1038 {
1039 str->s[str->l++] = '0'; str->s[str->l++] = '*'; str->s[str->l++] = ' '; str->s[str->l++] = '1'; str->s[str->l++] = '*'; str->s[str->l++] = ' ';
1040 }
1041 else if ( bcf_gt_is_missing(ptr[1]) ) /* 0/. */
1042 {
1043 str->s[str->l++] = '?'; str->s[str->l++] = ' '; str->s[str->l++] = '?'; str->s[str->l++] = ' ';
1044 }
1045 else if ( bcf_gt_is_phased(ptr[1]) ) /* 0|x */
1046 {
1047 str->s[str->l++] = '0'; str->s[str->l++] = ' ';
1048 kputw(bcf_gt_allele(ptr[1]),str);
1049 str->s[str->l++] = ' ';
1050 }
1051 else /* 0/x */
1052 {
1053 str->s[str->l++] = '0'; str->s[str->l++] = '*'; str->s[str->l++] = ' ';
1054 kputw(bcf_gt_allele(ptr[1]),str);
1055 str->s[str->l++] = '*'; str->s[str->l++] = ' ';
1056 }
1057 }
1058 else if ( ptr[0]==4 )
1059 {
1060 if ( ptr[1]==3 ) /* 1|0 */
1061 {
1062 str->s[str->l++] = '1'; str->s[str->l++] = ' '; str->s[str->l++] = '0'; str->s[str->l++] = ' ';
1063 }
1064 else if ( ptr[1]==5 ) /* 1|1 */
1065 {
1066 str->s[str->l++] = '1'; str->s[str->l++] = ' '; str->s[str->l++] = '1'; str->s[str->l++] = ' ';
1067 }
1068 else if ( ptr[1]==bcf_int8_vector_end ) /* 1 -> 1|1 */
1069 {
1070 str->s[str->l++] = '1'; str->s[str->l++] = ' '; str->s[str->l++] = '1'; str->s[str->l++] = ' ';
1071 }
1072 else if ( ptr[1]==2 ) /* 1/0 */
1073 {
1074 str->s[str->l++] = '1'; str->s[str->l++] = '*'; str->s[str->l++] = ' '; str->s[str->l++] = '0'; str->s[str->l++] = '*'; str->s[str->l++] = ' ';
1075 }
1076 else if ( ptr[1]==4 ) /* 1/1 */
1077 {
1078 str->s[str->l++] = '1'; str->s[str->l++] = '*'; str->s[str->l++] = ' '; str->s[str->l++] = '1'; str->s[str->l++] = '*'; str->s[str->l++] = ' ';
1079 }
1080 else if ( bcf_gt_is_missing(ptr[1]) ) /* 1/. */
1081 {
1082 str->s[str->l++] = '?'; str->s[str->l++] = ' '; str->s[str->l++] = '?'; str->s[str->l++] = ' ';
1083 }
1084 else if ( bcf_gt_is_phased(ptr[1]) ) /* 1|x */
1085 {
1086 str->s[str->l++] = '1'; str->s[str->l++] = ' ';
1087 kputw(bcf_gt_allele(ptr[1]),str);
1088 str->s[str->l++] = ' ';
1089 }
1090 else /* 1/x */
1091 {
1092 str->s[str->l++] = '1'; str->s[str->l++] = '*'; str->s[str->l++] = ' ';
1093 kputw(bcf_gt_allele(ptr[1]),str);
1094 str->s[str->l++] = '*'; str->s[str->l++] = ' ';
1095 }
1096 }
1097 else if ( bcf_gt_is_missing(ptr[0]) )
1098 {
1099 str->s[str->l++] = '?'; str->s[str->l++] = ' '; str->s[str->l++] = '?'; str->s[str->l++] = ' ';
1100 }
1101 else if ( ptr[1]==bcf_int8_vector_end )
1102 {
1103 /* use REF for something else than first ALT */
1104 str->s[str->l++] = '0'; str->s[str->l++] = ' '; str->s[str->l++] = '0'; str->s[str->l++] = ' ';
1105 }
1106 else
1107 {
1108 kputw(bcf_gt_allele(ptr[0]),str);
1109 if ( bcf_gt_is_phased(ptr[1]) ) str->s[str->l++] = '*';
1110 str->s[str->l++] = ' ';
1111 kputw(bcf_gt_allele(ptr[1]),str);
1112 if ( bcf_gt_is_phased(ptr[1]) ) str->s[str->l++] = '*';
1113 str->s[str->l++] = ' ';
1114 }
1115 }
1116 str->s[--str->l] = 0; // delete the last space
1117 }
1118
1119 static void process_rsid_hex(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
1120 {
1121 char *ptr = line->d.id;
1122 ptr += 2; // remove 'rs'
1123 ksprintf(str, "%08" PRIx32 "", (uint32_t)strtoul(ptr, NULL, 10));
1124 }
1125
1126 static void process_variantkey_hex(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
1127 {
1128 const char *alt = NULL;
1129 size_t sizealt = 0;
1130 if ( line->n_allele>1 )
1131 {
1132 alt = line->d.allele[1];
1133 sizealt = strlen(line->d.allele[1]);
1134 }
1135 uint64_t vk = variantkey(
1136 convert->header->id[BCF_DT_CTG][line->rid].key,
1137 strlen(convert->header->id[BCF_DT_CTG][line->rid].key),
1138 line->pos,
1139 line->d.allele[0],
1140 strlen(line->d.allele[0]),
1141 alt,
1142 sizealt);
1143 ksprintf(str, "%016" PRIx64 "", vk);
1144 }
1145
1146 static void process_npass(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
1147 {
1148 int i, nsmpl = 0;
1149 filter_t *flt = (filter_t*) fmt->usr;
1150 const uint8_t *smpl;
1151 filter_test(flt,line,&smpl);
1152 for (i=0; i<convert->nsamples; i++)
1153 if ( smpl[i] ) nsmpl++;
1154 kputd(nsmpl, str);
1155 }
1156 static void destroy_npass(void *usr)
1157 {
1158 filter_destroy((filter_t*)usr);
1159 }
1160
1161 static void process_pbinom(convert_t *convert, bcf1_t *line, fmt_t *fmt, int isample, kstring_t *str)
1162 {
1163 int i;
1164 if ( !fmt->ready )
1165 {
1166 fmt->fmt = NULL; // AD
1167 fmt->usr = NULL; // GT
1168
1169 for (i=0; i<(int)line->n_fmt; i++)
1170 if ( line->d.fmt[i].id==fmt->id ) { fmt->fmt = &line->d.fmt[i]; break; }
1171
1172 // Check that the first field is GT
1173 int gt_id = bcf_hdr_id2int(convert->header, BCF_DT_ID, "GT");
1174 if ( !bcf_hdr_idinfo_exists(convert->header, BCF_HL_FMT, fmt->id) ) error("Error: FORMAT/GT is not defined in the header\n");
1175 for (i=0; i<(int)line->n_fmt; i++)
1176 if ( line->d.fmt[i].id==gt_id ) { fmt->usr = &line->d.fmt[i]; break; } // it should always be first according to VCF spec, but...
1177
1178 if ( fmt->usr && line->d.fmt[i].type!=BCF_BT_INT8 ) // skip sites with many alleles
1179 fmt->usr = NULL;
1180
1181 fmt->ready = 1;
1182 }
1183 bcf_fmt_t *gt_fmt = (bcf_fmt_t*) fmt->usr;
1184 if ( !fmt->fmt || !gt_fmt || gt_fmt->n!=2 ) goto invalid;
1185
1186 int n[2] = {0,0};
1187 int8_t *gt = (int8_t*)(gt_fmt->p + isample*gt_fmt->size);
1188 for (i=0; i<2; i++)
1189 {
1190 if ( bcf_gt_is_missing(gt[i]) || gt[i] == bcf_int8_vector_end ) goto invalid;
1191 int al = bcf_gt_allele(gt[i]);
1192 if ( al > line->n_allele || al >= fmt->fmt->n ) goto invalid;
1193
1194 #define BRANCH(type_t, convert, missing, vector_end) { \
1195 type_t val = convert(&fmt->fmt->p[(al + isample*fmt->fmt->n)*sizeof(type_t)]); \
1196 if ( val==missing || val==vector_end ) goto invalid; \
1197 else n[i] = val; \
1198 }
1199 switch (fmt->fmt->type)
1200 {
1201 case BCF_BT_INT8: BRANCH(int8_t, le_to_i8, bcf_int8_missing, bcf_int8_vector_end); break;
1202 case BCF_BT_INT16: BRANCH(int16_t, le_to_i16, bcf_int16_missing, bcf_int16_vector_end); break;
1203 case BCF_BT_INT32: BRANCH(int32_t, le_to_i32, bcf_int32_missing, bcf_int32_vector_end); break;
1204 default: goto invalid; break;
1205 }
1206 #undef BRANCH
1207 }
1208
1209 if ( n[0]==n[1] ) kputc(n[0]==0 ? '.':'0', str);
1210 else
1211 {
1212 double pval = calc_binom_two_sided(n[0],n[1],0.5);
1213
1214 // convrt to phred
1215 if ( pval>=1 ) pval = 0;
1216 else pval = -4.34294481903*log(pval);
1217 kputd(pval, str);
1218 }
1219 return;
1220
1221 invalid:
1222 kputc('.', str);
1223 }
1224
1225 static void _used_tags_add(convert_t *convert, int type, char *key)
1226 {
1227 kstring_t str = {0,0,0};
1228 ksprintf(&str,"%s/%s",type==T_INFO?"INFO":"FORMAT",key);
1229 khash_str2int_inc(convert->used_tags_hash,str.s);
1230 convert->nused_tags++;
1231 convert->used_tags_list = (char**)realloc(convert->used_tags_list,sizeof(*convert->used_tags_list)*convert->nused_tags);
1232 convert->used_tags_list[convert->nused_tags-1] = str.s;
1233 }
1234
1235
1236 #define _SET_NON_FORMAT_TAGS(function,key,...) \
1237 if ( !strcmp("CHROM",key) ) { function(__VA_ARGS__, T_CHROM); } \
1238 else if ( !strcmp("POS",key) ) { function(__VA_ARGS__, T_POS); } \
1239 else if ( !strcmp("POS0",key) ) { function(__VA_ARGS__, T_POS0); } \
1240 else if ( !strcmp("END",key) ) { function(__VA_ARGS__, T_END); } \
1241 else if ( !strcmp("END0",key) ) { function(__VA_ARGS__, T_END0); } \
1242 else if ( !strcmp("ID",key) ) { function(__VA_ARGS__, T_ID); } \
1243 else if ( !strcmp("REF",key) ) { function(__VA_ARGS__, T_REF); } \
1244 else if ( !strcmp("FIRST_ALT",key) ) { function(__VA_ARGS__, T_FIRST_ALT); } \
1245 else if ( !strcmp("QUAL",key) ) { function(__VA_ARGS__, T_QUAL); } \
1246 else if ( !strcmp("TYPE",key) ) { function(__VA_ARGS__, T_TYPE); } \
1247 else if ( !strcmp("FILTER",key) ) { function(__VA_ARGS__, T_FILTER); } \
1248 else if ( !strcmp("IS_TS",key) ) { function(__VA_ARGS__, T_IS_TS); } \
1249 else if ( !strcmp("MASK",key) ) { function(__VA_ARGS__, T_MASK); } \
1250 else if ( !strcmp("LINE",key) ) { function(__VA_ARGS__, T_LINE); }
1251
1252 static void set_type(fmt_t *fmt, int type) { fmt->type = type; }
1253 static fmt_t *register_tag(convert_t *convert, char *key, int is_gtf, int type)
1254 {
1255 convert->nfmt++;
1256 if ( convert->nfmt > convert->mfmt )
1257 {
1258 convert->mfmt += 10;
1259 convert->fmt = (fmt_t*) realloc(convert->fmt, convert->mfmt*sizeof(fmt_t));
1260 }
1261 fmt_t *fmt = &convert->fmt[ convert->nfmt-1 ];
1262 fmt->type = type;
1263 fmt->key = key ? strdup(key) : NULL;
1264 fmt->is_gt_field = is_gtf;
1265 fmt->subscript = -1;
1266 fmt->usr = NULL;
1267 fmt->destroy = NULL;
1268
1269 // Allow non-format tags, such as CHROM, INFO, etc., to appear amongst the format tags.
1270 if ( key )
1271 {
1272 int id = bcf_hdr_id2int(convert->header, BCF_DT_ID, key);
1273 if ( fmt->type==T_FORMAT && !bcf_hdr_idinfo_exists(convert->header,BCF_HL_FMT,id) )
1274 {
1275 _SET_NON_FORMAT_TAGS(set_type,key,fmt)
1276 else if ( !strcmp("ALT",key) ) { fmt->type = T_ALT; }
1277 else if ( !strcmp("_CHROM_POS_ID",key) ) { fmt->type = T_CHROM_POS_ID; }
1278 else if ( !strcmp("RSX",key) ) { fmt->type = T_RSX; }
1279 else if ( !strcmp("VKX",key) ) { fmt->type = T_VKX; }
1280 else if ( id>=0 && bcf_hdr_idinfo_exists(convert->header,BCF_HL_INFO,id) )
1281 {
1282 fmt->type = T_INFO;
1283 _used_tags_add(convert,T_INFO,key);
1284 }
1285 }
1286 else if ( fmt->type==T_PBINOM )
1287 {
1288 fmt->id = bcf_hdr_id2int(convert->header, BCF_DT_ID, fmt->key);
1289 if ( !bcf_hdr_idinfo_exists(convert->header,BCF_HL_FMT, fmt->id) ) error("No such FORMAT tag defined in the header: %s\n", fmt->key);
1290 _used_tags_add(convert,T_FORMAT,key);
1291 }
1292 else if ( fmt->type==T_NPASS )
1293 {
1294 filter_t *flt = filter_init(convert->header,key);
1295 convert->max_unpack |= filter_max_unpack(flt);
1296 fmt->usr = (void*) flt;
1297 }
1298 }
1299
1300 switch (fmt->type)
1301 {
1302 case T_FIRST_ALT: fmt->handler = &process_first_alt; break;
1303 case T_CHROM_POS_ID: fmt->handler = &process_chrom_pos_id; break;
1304 case T_GT_TO_PROB3: fmt->handler = &process_gt_to_prob3; break;
1305 case T_PL_TO_PROB3: fmt->handler = &process_pl_to_prob3; break;
1306 case T_GP_TO_PROB3: fmt->handler = &process_gp_to_prob3; break;
1307 case T_CHROM: fmt->handler = &process_chrom; break;
1308 case T_POS: fmt->handler = &process_pos; break;
1309 case T_POS0: fmt->handler = &process_pos0; break;
1310 case T_END: fmt->handler = &process_end; convert->max_unpack |= BCF_UN_INFO; break;
1311 case T_END0: fmt->handler = &process_end0; convert->max_unpack |= BCF_UN_INFO; break;
1312 case T_ID: fmt->handler = &process_id; break;
1313 case T_REF: fmt->handler = &process_ref; break;
1314 case T_ALT: fmt->handler = &process_alt; break;
1315 case T_QUAL: fmt->handler = &process_qual; break;
1316 case T_FILTER: fmt->handler = &process_filter; convert->max_unpack |= BCF_UN_FLT; break;
1317 case T_INFO: fmt->handler = &process_info; convert->max_unpack |= BCF_UN_INFO; break;
1318 case T_FORMAT: fmt->handler = fmt->key ? &process_format : &process_complete_format; convert->max_unpack |= BCF_UN_FMT; break;
1319 case T_SAMPLE: fmt->handler = &process_sample; break;
1320 case T_SEP: fmt->handler = &process_sep; break;
1321 case T_IS_TS: fmt->handler = &process_is_ts; break;
1322 case T_TYPE: fmt->handler = &process_type; break;
1323 case T_MASK: fmt->handler = NULL; break;
1324 case T_GT: fmt->handler = &process_gt; convert->max_unpack |= BCF_UN_FMT; break;
1325 case T_TGT: fmt->handler = &process_tgt; convert->max_unpack |= BCF_UN_FMT; break;
1326 case T_IUPAC_GT: fmt->handler = &process_iupac_gt; convert->max_unpack |= BCF_UN_FMT; break;
1327 case T_GT_TO_HAP: fmt->handler = &process_gt_to_hap; convert->max_unpack |= BCF_UN_FMT; break;
1328 case T_GT_TO_HAP2: fmt->handler = &process_gt_to_hap2; convert->max_unpack |= BCF_UN_FMT; break;
1329 case T_TBCSQ: fmt->handler = &process_tbcsq; fmt->destroy = &destroy_tbcsq; convert->max_unpack |= BCF_UN_FMT; break;
1330 case T_LINE: fmt->handler = &process_line; convert->max_unpack |= BCF_UN_FMT; break;
1331 case T_RSX: fmt->handler = &process_rsid_hex; break;
1332 case T_VKX: fmt->handler = &process_variantkey_hex; break;
1333 case T_PBINOM: fmt->handler = &process_pbinom; convert->max_unpack |= BCF_UN_FMT; break;
1334 case T_NPASS: fmt->handler = &process_npass; fmt->destroy = &destroy_npass; break;
1335 default: error("TODO: handler for type %d\n", fmt->type);
1336 }
1337 if ( key && fmt->type==T_INFO )
1338 {
1339 fmt->id = bcf_hdr_id2int(convert->header, BCF_DT_ID, key);
1340 if ( !bcf_hdr_idinfo_exists(convert->header,BCF_HL_INFO,fmt->id) )
1341 {
1342 fmt->id = -1;
1343 convert->undef_info_tag = strdup(key);
1344 }
1345 }
1346 return fmt;
1347 }
1348
1349 static int parse_subscript(char **p)
1350 {
1351 char *q = *p;
1352 if ( *q!='{' ) return -1;
1353 q++;
1354 while ( *q && *q!='}' && isdigit(*q) ) q++;
1355 if ( *q!='}' ) return -1;
1356 int idx = atoi((*p)+1);
1357 *p = q+1;
1358 return idx;
1359 }
1360
1361 static char *parse_tag(convert_t *convert, char *p, int is_gtf)
1362 {
1363 char *q = ++p;
1364 while ( *q && (isalnum(*q) || *q=='_' || *q=='.') ) q++;
1365 kstring_t str = {0,0,0};
1366 if ( q-p==0 ) error("Could not parse format string: %s\n", convert->format_str);
1367 kputsn(p, q-p, &str);
1368 if ( is_gtf )
1369 {
1370 if ( !strcmp(str.s, "SAMPLE") ) register_tag(convert, "SAMPLE", is_gtf, T_SAMPLE);
1371 else if ( !strcmp(str.s, "GT") ) register_tag(convert, "GT", is_gtf, T_GT);
1372 else if ( !strcmp(str.s, "TGT") ) register_tag(convert, "GT", is_gtf, T_TGT);
1373 else if ( !strcmp(str.s, "TBCSQ") )
1374 {
1375 fmt_t *fmt = register_tag(convert, "BCSQ", is_gtf, T_TBCSQ);
1376 fmt->subscript = parse_subscript(&q);
1377 if ( fmt->subscript==-1 )
1378 {
1379 if ( !strncmp(q,"{*}",3) ) { fmt->subscript = 0; q += 3; }
1380 }
1381 else fmt->subscript++;
1382 }
1383 else if ( !strcmp(str.s, "IUPACGT") ) register_tag(convert, "GT", is_gtf, T_IUPAC_GT);
1384 else if ( !strcmp(str.s, "INFO") )
1385 {
1386 if ( *q!='/' )
1387 {
1388 int id = bcf_hdr_id2int(convert->header, BCF_DT_ID, str.s);
1389 if ( bcf_hdr_idinfo_exists(convert->header,BCF_HL_INFO,id) )
1390 error("Could not parse format string \"%s\". Did you mean %%INFO/%s?\n", convert->format_str,str.s);
1391 else
1392 error("Could not parse format string: %s\n", convert->format_str);
1393 }
1394 p = ++q;
1395 str.l = 0;
1396 while ( *q && (isalnum(*q) || *q=='_' || *q=='.') ) q++;
1397 if ( q-p==0 ) error("Could not parse format string: %s\n", convert->format_str);
1398 kputsn(p, q-p, &str);
1399 fmt_t *fmt = register_tag(convert, str.s, is_gtf, T_INFO);
1400 fmt->subscript = parse_subscript(&q);
1401 _used_tags_add(convert,T_INFO,str.s);
1402 }
1403 else if ( !strcmp(str.s,"PBINOM") )
1404 {
1405 if ( *q!='(' ) error("Could not parse the expression: %s\n", convert->format_str);
1406 p = ++q;
1407 str.l = 0;
1408 while ( *q && *q!=')' ) q++;
1409 if ( q-p==0 ) error("Could not parse format string: %s\n", convert->format_str);
1410 kputsn(p, q-p, &str);
1411 register_tag(convert, str.s, is_gtf, T_PBINOM);
1412 q++;
1413 }
1414 else if ( !strcmp(str.s,"N_PASS") )
1415 error("N_PASS() must be placed outside the square brackets\n");
1416 else
1417 {
1418 fmt_t *fmt = register_tag(convert, str.s, is_gtf, T_FORMAT);
1419 fmt->subscript = parse_subscript(&q);
1420 }
1421 }
1422 else
1423 {
1424 _SET_NON_FORMAT_TAGS(register_tag, str.s, convert, str.s, is_gtf)
1425 else if ( !strcmp(str.s, "ALT") )
1426 {
1427 fmt_t *fmt = register_tag(convert, str.s, is_gtf, T_ALT);
1428 fmt->subscript = parse_subscript(&q);
1429 }
1430 else if ( !strcmp(str.s, "_CHROM_POS_ID") ) register_tag(convert, str.s, is_gtf, T_CHROM_POS_ID);
1431 else if ( !strcmp(str.s, "_GT_TO_PROB3") ) register_tag(convert, str.s, is_gtf, T_GT_TO_PROB3);
1432 else if ( !strcmp(str.s, "_PL_TO_PROB3") ) register_tag(convert, str.s, is_gtf, T_PL_TO_PROB3);
1433 else if ( !strcmp(str.s, "_GP_TO_PROB3") ) register_tag(convert, str.s, is_gtf, T_GP_TO_PROB3);
1434 else if ( !strcmp(str.s, "_GT_TO_HAP") ) register_tag(convert, str.s, is_gtf, T_GT_TO_HAP);
1435 else if ( !strcmp(str.s, "_GT_TO_HAP2") ) register_tag(convert, str.s, is_gtf, T_GT_TO_HAP2);
1436 else if ( !strcmp(str.s, "RSX") ) register_tag(convert, str.s, is_gtf, T_RSX);
1437 else if ( !strcmp(str.s, "VKX") ) register_tag(convert, str.s, is_gtf, T_VKX);
1438 else if ( !strcmp(str.s,"PBINOM") ) error("Error: PBINOM() is currently supported only with FORMAT tags. (todo)\n");
1439 else if ( !strcmp(str.s, "INFO") )
1440 {
1441 if ( *q=='/' )
1442 {
1443 p = ++q;
1444 str.l = 0;
1445 while ( *q && (isalnum(*q) || *q=='_' || *q=='.') ) q++;
1446 if ( q-p==0 ) error("Could not parse format string: %s\n", convert->format_str);
1447 kputsn(p, q-p, &str);
1448 fmt_t *fmt = register_tag(convert, str.s, is_gtf, T_INFO);
1449 fmt->subscript = parse_subscript(&q);
1450 _used_tags_add(convert,T_INFO,str.s);
1451 }
1452 else
1453 register_tag(convert, NULL, is_gtf, T_INFO); // the whole INFO
1454 }
1455 else if ( !strcmp(str.s, "FORMAT") )
1456 register_tag(convert, NULL, 0, T_FORMAT);
1457 else if ( !strcmp(str.s,"N_PASS") )
1458 {
1459 if ( *q!='(' ) error("Could not parse the expression: %s\n", convert->format_str);
1460 p = ++q;
1461 str.l = 0;
1462 int nopen = 1;
1463 while ( *q && nopen )
1464 {
1465 if ( *q=='(' ) nopen++;
1466 else if ( *q==')' ) nopen--;
1467 q++;
1468 }
1469 if ( q-p==0 || nopen ) error("Could not parse format string: %s\n", convert->format_str);
1470 kputsn(p, q-p-1, &str);
1471 register_tag(convert, str.s, is_gtf, T_NPASS);
1472 }
1473 else
1474 {
1475 fmt_t *fmt = register_tag(convert, str.s, is_gtf, T_INFO);
1476 fmt->subscript = parse_subscript(&q);
1477 _used_tags_add(convert,T_INFO,str.s);
1478 }
1479 }
1480 free(str.s);
1481 return q;
1482 }
1483
1484 static char *parse_sep(convert_t *convert, char *p, int is_gtf)
1485 {
1486 char *q = p;
1487 kstring_t str = {0,0,0};
1488 while ( *q && *q!='[' && *q!=']' && *q!='%' )
1489 {
1490 if ( *q=='\\' )
1491 {
1492 q++;
1493 if ( *q=='n' ) kputc('\n', &str);
1494 else if ( *q=='t' ) kputc('\t', &str);
1495 else kputc(*q, &str);
1496 }
1497 else kputc(*q, &str);
1498 q++;
1499 }
1500 if ( !str.l ) error("Could not parse format string: %s\n", convert->format_str);
1501 register_tag(convert, str.s, is_gtf, T_SEP);
1502 free(str.s);
1503 return q;
1504 }
1505
1506 convert_t *convert_init(bcf_hdr_t *hdr, int *samples, int nsamples, const char *format_str)
1507 {
1508 convert_t *convert = (convert_t*) calloc(1,sizeof(convert_t));
1509 convert->header = hdr;
1510 convert->format_str = strdup(format_str);
1511 convert->max_unpack = BCF_UN_STR;
1512 convert->used_tags_hash = khash_str2int_init();
1513
1514 int i, is_gtf = 0;
1515 char *p = convert->format_str;
1516 while ( *p )
1517 {
1518 //fprintf(stderr,"<%s>\n", p);
1519 switch (*p)
1520 {
1521 case '[': is_gtf = 1; p++; break;
1522 case ']': is_gtf = 0; register_tag(convert, NULL, 0, T_SEP); p++; break;
1523 case '%': p = parse_tag(convert, p, is_gtf); break;
1524 default: p = parse_sep(convert, p, is_gtf); break;
1525 }
1526 }
1527 if ( is_gtf )
1528 error("Could not parse the format string, missing the square bracket \"]\": %s\n", convert->format_str);
1529
1530 if ( nsamples )
1531 {
1532 convert->nsamples = nsamples;
1533 convert->samples = (int*) malloc(sizeof(int)*nsamples);
1534 for (i=0; i<convert->nsamples; i++) convert->samples[i] = samples[i];
1535 }
1536 else
1537 {
1538 convert->nsamples = bcf_hdr_nsamples(convert->header);
1539 convert->samples = (int*) malloc(sizeof(int)*convert->nsamples);
1540 for (i=0; i<convert->nsamples; i++) convert->samples[i] = i;
1541 }
1542 return convert;
1543 }
1544
1545 void convert_destroy(convert_t *convert)
1546 {
1547 int i;
1548 for (i=0; i<convert->nfmt; i++)
1549 {
1550 if ( convert->fmt[i].destroy ) convert->fmt[i].destroy(convert->fmt[i].usr);
1551 free(convert->fmt[i].key);
1552 }
1553 if ( convert->nused_tags )
1554 {
1555 for (i=0; i<convert->nused_tags; i++) free(convert->used_tags_list[i]);
1556 free(convert->used_tags_list);
1557 }
1558 khash_str2int_destroy(convert->used_tags_hash);
1559 free(convert->print_filtered);
1560 free(convert->fmt);
1561 free(convert->undef_info_tag);
1562 free(convert->dat);
1563 free(convert->samples);
1564 free(convert->format_str);
1565 free(convert);
1566 }
1567
1568
1569 int convert_header(convert_t *convert, kstring_t *str)
1570 {
1571 int i, icol = 0, l_ori = str->l;
1572 bcf_hdr_t *hdr = convert->header;
1573
1574 // Suppress the header output if LINE is present
1575 for (i=0; i<convert->nfmt; i++)
1576 if ( convert->fmt[i].type == T_LINE ) break;
1577 if ( i!=convert->nfmt )
1578 return str->l - l_ori;
1579
1580 // Header formatting becomes problematic when the formatting expression contains a newline.
1581 // Simple cases like
1582 // -f'[%CHROM %POS %SAMPLE\n]'
1583 // can be handled quite easily with has_fmt_newline. Note this will not work if multiple newlines
1584 // are present.
1585 int has_fmt_newline = 0;
1586 kputc('#', str);
1587 for (i=0; i<convert->nfmt; i++)
1588 {
1589 // Genotype fields
1590 if ( convert->fmt[i].is_gt_field )
1591 {
1592 int j = i, js, k;
1593 while ( convert->fmt[j].is_gt_field ) j++;
1594 for (js=0; js<convert->nsamples; js++)
1595 {
1596 int ks = convert->samples[js];
1597 for (k=i; k<j; k++)
1598 {
1599 if ( convert->fmt[k].type == T_SEP )
1600 {
1601 if ( convert->fmt[k].key )
1602 {
1603 char *tmp = convert->fmt[k].key;
1604 while ( *tmp )
1605 {
1606 if ( *tmp=='\n' ) has_fmt_newline = 1;
1607 else kputc(*tmp,str);
1608 tmp++;
1609 }
1610 }
1611 }
1612 else if ( convert->header_samples )
1613 {
1614 icol++;
1615 if ( !convert->no_hdr_indices ) ksprintf(str,"[%d]",icol);
1616 ksprintf(str,"%s:%s", hdr->samples[ks], convert->fmt[k].key);
1617 }
1618 else
1619 {
1620 icol++;
1621 if ( !convert->no_hdr_indices ) ksprintf(str,"[%d]",icol);
1622 ksprintf(str,"%s", convert->fmt[k].key);
1623 }
1624 }
1625 if ( has_fmt_newline )
1626 {
1627 if ( !convert->header_samples ) break;
1628
1629 // this is unfortunate: the formatting expression breaks the per-sample output into separate lines,
1630 // therefore including a sample name in the header makes no sense anymore
1631 convert->header_samples = 0;
1632 str->l = l_ori;
1633 return convert_header(convert, str);
1634 }
1635 }
1636 i = j-1;
1637 continue;
1638 }
1639 // Fixed fields
1640 if ( convert->fmt[i].type == T_SEP )
1641 {
1642 if ( convert->fmt[i].key ) kputs(convert->fmt[i].key, str);
1643 continue;
1644 }
1645 icol++;
1646 if ( !convert->no_hdr_indices ) ksprintf(str,"[%d]",icol);
1647 ksprintf(str,"%s", convert->fmt[i].key);
1648 }
1649 if ( has_fmt_newline ) kputc('\n',str);
1650 return str->l - l_ori;
1651 }
1652
1653 int convert_line(convert_t *convert, bcf1_t *line, kstring_t *str)
1654 {
1655 if ( !convert->allow_undef_tags && convert->undef_info_tag )
1656 {
1657 kstring_t msg = {0,0,0};
1658 ksprintf(&msg,"Error: no such tag defined in the VCF header: INFO/%s", convert->undef_info_tag);
1659
1660 int hdr_id = bcf_hdr_id2int(convert->header,BCF_DT_ID,convert->undef_info_tag);
1661 if ( hdr_id>=0 && bcf_hdr_idinfo_exists(convert->header,BCF_HL_FMT,hdr_id) )
1662 ksprintf(&msg,". FORMAT fields must be enclosed in square brackets, e.g. \"[ %%%s]\"", convert->undef_info_tag);
1663 error("%s\n", msg.s);
1664 }
1665
1666 int l_ori = str->l;
1667 bcf_unpack(line, convert->max_unpack);
1668
1669 int i, ir;
1670 str->l = 0;
1671 for (i=0; i<convert->nfmt; i++)
1672 {
1673 // Genotype fields.
1674 if ( convert->fmt[i].is_gt_field )
1675 {
1676 int j = i, js, k;
1677 while ( j<convert->nfmt && convert->fmt[j].is_gt_field )
1678 {
1679 convert->fmt[j].ready = 0;
1680 j++;
1681 }
1682 for (js=0; js<convert->nsamples; js++)
1683 {
1684 // Skip samples when filtering was requested
1685 int ks = convert->samples[js];
1686 if ( convert->subset_samples && *convert->subset_samples && !(*convert->subset_samples)[ks] )
1687 {
1688 if ( !convert->print_filtered ) continue;
1689
1690 for (k=i; k<j; k++)
1691 if ( convert->fmt[k].type==T_SEP )
1692 convert->fmt[k].handler(convert, line, &convert->fmt[k], ks, str);
1693 else
1694 kputs(convert->print_filtered, str);
1695 continue;
1696 }
1697
1698 // Here comes a hack designed for TBCSQ. When running on large files,
1699 // such as 1000GP, there are too many empty fields in the output and
1700 // it's very very slow. Therefore in case the handler does not add
1701 // anything to the string, we trim all genotype fields enclosed in square
1702 // brackets here. This may be changed in future, time will show...
1703 size_t l_start = str->l;
1704
1705 for (k=i; k<j; k++)
1706 {
1707 if ( convert->fmt[k].type == T_MASK )
1708 {
1709 for (ir=0; ir<convert->nreaders; ir++)
1710 kputc(bcf_sr_has_line(convert->readers,ir)?'1':'0', str);
1711 }
1712 else if ( convert->fmt[k].handler )
1713 {
1714 size_t l = str->l;
1715 convert->fmt[k].handler(convert, line, &convert->fmt[k], ks, str);
1716 if ( l==str->l ) { str->l = l_start; break; } // only TBCSQ does this
1717 }
1718 }
1719 }
1720 i = j-1;
1721 continue;
1722 }
1723 // Fixed fields
1724 if ( convert->fmt[i].type == T_MASK )
1725 {
1726 for (ir=0; ir<convert->nreaders; ir++)
1727 kputc(bcf_sr_has_line(convert->readers,ir)?'1':'0', str);
1728 }
1729 else if ( convert->fmt[i].handler )
1730 convert->fmt[i].handler(convert, line, &convert->fmt[i], -1, str);
1731
1732 }
1733 return str->l - l_ori;
1734 }
1735
1736 static void force_newline_(convert_t *convert)
1737 {
1738 int i, has_newline = 0;
1739 for (i=0; i<convert->nfmt; i++)
1740 {
1741 if ( !convert->fmt[i].key ) continue;
1742 char *tmp = convert->fmt[i].key;
1743 while (*tmp)
1744 {
1745 if ( *tmp=='\n' ) { has_newline = 1; break; }
1746 tmp++;
1747 }
1748 if ( has_newline ) break;
1749 }
1750 if ( has_newline ) return;
1751
1752 // A newline is not present, force it. But where to add it? Always at the end.
1753 //
1754 // Briefly, in 1.18, we considered the following automatic behavior, which for
1755 // per-site output it would add it at the end of the expression and for per-sample
1756 // output it would add it inside the square brackets:
1757 // -f'%CHROM[ %SAMPLE]\n'
1758 // -f'[%CHROM %SAMPLE\n]'
1759 //
1760 // However, this is an annoyance for users, as it is not entirely clear what
1761 // will happen unless one understands the internals well (#1969)
1762
1763 register_tag(convert, "\n", 0, T_SEP);
1764 }
1765
1766 int convert_set_option(convert_t *convert, enum convert_option opt, ...)
1767 {
1768 int ret = 0;
1769 va_list args;
1770
1771 va_start(args, opt);
1772 switch (opt)
1773 {
1774 case allow_undef_tags:
1775 convert->allow_undef_tags = va_arg(args, int);
1776 break;
1777 case subset_samples:
1778 convert->subset_samples = va_arg(args, uint8_t**);
1779 break;
1780 case header_samples:
1781 convert->header_samples = va_arg(args, int);
1782 break;
1783 case print_filtered:
1784 convert->print_filtered = strdup(va_arg(args, char*));
1785 break;
1786 case force_newline:
1787 convert->force_newline = va_arg(args, int);
1788 if ( convert->force_newline ) force_newline_(convert);
1789 break;
1790 case no_hdr_indices:
1791 convert->no_hdr_indices = va_arg(args, int);
1792 break;
1793 default:
1794 ret = -1;
1795 }
1796 va_end(args);
1797 return ret;
1798 }
1799
1800 int convert_max_unpack(convert_t *convert)
1801 {
1802 return convert->max_unpack;
1803 }
1804
1805 int convert_is_tag_used(convert_t *convert, char *tag)
1806 {
1807 return khash_str2int_has_key(convert->used_tags_hash, tag);
1808 }
1809 const char **convert_list_used_tags(convert_t *convert, int *ntags)
1810 {
1811 *ntags = convert->nused_tags;
1812 return (const char **)convert->used_tags_list;
1813 }
1814