Debian Codegraph @

bcftools/convert.c.pysam.c

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