This repository has been archived by the owner on Jun 3, 2021. It is now read-only.
forked from SelfHacked/htslib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vcf.c
4754 lines (4361 loc) · 158 KB
/
vcf.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* vcf.c -- VCF/BCF API functions.
Copyright (C) 2012, 2013 Broad Institute.
Copyright (C) 2012-2020 Genome Research Ltd.
Portions copyright (C) 2014 Intel Corporation.
Author: Heng Li <lh3@sanger.ac.uk>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE. */
#define HTS_BUILDING_LIBRARY // Enables HTSLIB_EXPORT, see htslib/hts_defs.h
#include <config.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <limits.h>
#include <stdint.h>
#include <inttypes.h>
#include <errno.h>
#include "htslib/vcf.h"
#include "htslib/bgzf.h"
#include "htslib/tbx.h"
#include "htslib/hfile.h"
#include "hts_internal.h"
#include "htslib/hts_endian.h"
#include "htslib/khash_str2int.h"
#include "htslib/kstring.h"
#include "htslib/sam.h"
#include "htslib/khash.h"
KHASH_MAP_INIT_STR(vdict, bcf_idinfo_t)
typedef khash_t(vdict) vdict_t;
#include "htslib/kseq.h"
HTSLIB_EXPORT
uint32_t bcf_float_missing = 0x7F800001;
HTSLIB_EXPORT
uint32_t bcf_float_vector_end = 0x7F800002;
HTSLIB_EXPORT
uint8_t bcf_type_shift[] = { 0, 0, 1, 2, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
static bcf_idinfo_t bcf_idinfo_def = { .info = { 15, 15, 15 }, .hrec = { NULL, NULL, NULL}, .id = -1 };
/*
Partial support for 64-bit POS and Number=1 INFO tags.
Notes:
- the support for 64-bit values is motivated by POS and INFO/END for large genomes
- the use of 64-bit values does not conform to the specification
- cannot output 64-bit BCF and if it does, it is not compatible with anything
- experimental, use at your risk
*/
#ifdef VCF_ALLOW_INT64
#define BCF_MAX_BT_INT64 (0x7fffffffffffffff) /* INT64_MAX, for internal use only */
#define BCF_MIN_BT_INT64 -9223372036854775800LL /* INT64_MIN + 8, for internal use only */
#endif
#define BCF_IS_64BIT (1<<30)
static char *find_chrom_header_line(char *s)
{
char *nl;
if (strncmp(s, "#CHROM\t", 7) == 0) return s;
else if ((nl = strstr(s, "\n#CHROM\t")) != NULL) return nl+1;
else return NULL;
}
/*************************
*** VCF header parser ***
*************************/
static int bcf_hdr_add_sample_len(bcf_hdr_t *h, const char *s, size_t len)
{
if ( !s ) return 0;
if (len == 0) len = strlen(s);
const char *ss = s;
while ( *ss && isspace_c(*ss) && ss - s < len) ss++;
if ( !*ss || ss - s == len)
{
hts_log_error("Empty sample name: trailing spaces/tabs in the header line?");
return -1;
}
vdict_t *d = (vdict_t*)h->dict[BCF_DT_SAMPLE];
int ret;
char *sdup = malloc(len + 1);
if (!sdup) return -1;
memcpy(sdup, s, len);
sdup[len] = 0;
// Ensure space is available in h->samples
size_t n = kh_size(d);
char **new_samples = realloc(h->samples, sizeof(char*) * (n + 1));
if (!new_samples) {
free(sdup);
return -1;
}
h->samples = new_samples;
int k = kh_put(vdict, d, sdup, &ret);
if (ret < 0) {
free(sdup);
return -1;
}
if (ret) { // absent
kh_val(d, k) = bcf_idinfo_def;
kh_val(d, k).id = n;
} else {
hts_log_error("Duplicated sample name '%s'", s);
free(sdup);
return -1;
}
h->samples[n] = sdup;
h->dirty = 1;
return 0;
}
int bcf_hdr_add_sample(bcf_hdr_t *h, const char *s)
{
return bcf_hdr_add_sample_len(h, s, 0);
}
int HTS_RESULT_USED bcf_hdr_parse_sample_line(bcf_hdr_t *h, const char *str)
{
int ret = 0;
int i = 0;
const char *p, *q;
// add samples
for (p = q = str;; ++q) {
if (*q > '\n') continue;
if (++i > 9) {
if ( bcf_hdr_add_sample_len(h, p, q - p) < 0 ) ret = -1;
}
if (*q == 0 || *q == '\n' || ret < 0) break;
p = q + 1;
}
return ret;
}
int bcf_hdr_sync(bcf_hdr_t *h)
{
int i;
for (i = 0; i < 3; i++)
{
vdict_t *d = (vdict_t*)h->dict[i];
khint_t k;
if ( h->n[i] < kh_size(d) )
{
bcf_idpair_t *new_idpair;
// this should be true only for i=2, BCF_DT_SAMPLE
new_idpair = (bcf_idpair_t*) realloc(h->id[i], kh_size(d)*sizeof(bcf_idpair_t));
if (!new_idpair) return -1;
h->n[i] = kh_size(d);
h->id[i] = new_idpair;
}
for (k=kh_begin(d); k<kh_end(d); k++)
{
if (!kh_exist(d,k)) continue;
h->id[i][kh_val(d,k).id].key = kh_key(d,k);
h->id[i][kh_val(d,k).id].val = &kh_val(d,k);
}
}
h->dirty = 0;
return 0;
}
void bcf_hrec_destroy(bcf_hrec_t *hrec)
{
if (!hrec) return;
free(hrec->key);
if ( hrec->value ) free(hrec->value);
int i;
for (i=0; i<hrec->nkeys; i++)
{
free(hrec->keys[i]);
free(hrec->vals[i]);
}
free(hrec->keys);
free(hrec->vals);
free(hrec);
}
// Copies all fields except IDX.
bcf_hrec_t *bcf_hrec_dup(bcf_hrec_t *hrec)
{
int save_errno;
bcf_hrec_t *out = (bcf_hrec_t*) calloc(1,sizeof(bcf_hrec_t));
if (!out) return NULL;
out->type = hrec->type;
if ( hrec->key ) {
out->key = strdup(hrec->key);
if (!out->key) goto fail;
}
if ( hrec->value ) {
out->value = strdup(hrec->value);
if (!out->value) goto fail;
}
out->nkeys = hrec->nkeys;
out->keys = (char**) malloc(sizeof(char*)*hrec->nkeys);
if (!out->keys) goto fail;
out->vals = (char**) malloc(sizeof(char*)*hrec->nkeys);
if (!out->vals) goto fail;
int i, j = 0;
for (i=0; i<hrec->nkeys; i++)
{
if ( hrec->keys[i] && !strcmp("IDX",hrec->keys[i]) ) continue;
if ( hrec->keys[i] ) {
out->keys[j] = strdup(hrec->keys[i]);
if (!out->keys[j]) goto fail;
}
if ( hrec->vals[i] ) {
out->vals[j] = strdup(hrec->vals[i]);
if (!out->vals[j]) goto fail;
}
j++;
}
if ( i!=j ) out->nkeys -= i-j; // IDX was omitted
return out;
fail:
save_errno = errno;
hts_log_error("%s", strerror(errno));
bcf_hrec_destroy(out);
errno = save_errno;
return NULL;
}
void bcf_hrec_debug(FILE *fp, bcf_hrec_t *hrec)
{
fprintf(fp, "key=[%s] value=[%s]", hrec->key, hrec->value?hrec->value:"");
int i;
for (i=0; i<hrec->nkeys; i++)
fprintf(fp, "\t[%s]=[%s]", hrec->keys[i],hrec->vals[i]);
fprintf(fp, "\n");
}
void bcf_header_debug(bcf_hdr_t *hdr)
{
int i, j;
for (i=0; i<hdr->nhrec; i++)
{
if ( !hdr->hrec[i]->value )
{
fprintf(stderr, "##%s=<", hdr->hrec[i]->key);
fprintf(stderr,"%s=%s", hdr->hrec[i]->keys[0], hdr->hrec[i]->vals[0]);
for (j=1; j<hdr->hrec[i]->nkeys; j++)
fprintf(stderr,",%s=%s", hdr->hrec[i]->keys[j], hdr->hrec[i]->vals[j]);
fprintf(stderr,">\n");
}
else
fprintf(stderr,"##%s=%s\n", hdr->hrec[i]->key,hdr->hrec[i]->value);
}
}
int bcf_hrec_add_key(bcf_hrec_t *hrec, const char *str, size_t len)
{
char **tmp;
size_t n = hrec->nkeys + 1;
assert(len > 0 && len < SIZE_MAX);
tmp = realloc(hrec->keys, sizeof(char*)*n);
if (!tmp) return -1;
hrec->keys = tmp;
tmp = realloc(hrec->vals, sizeof(char*)*n);
if (!tmp) return -1;
hrec->vals = tmp;
hrec->keys[hrec->nkeys] = (char*) malloc((len+1)*sizeof(char));
if (!hrec->keys[hrec->nkeys]) return -1;
memcpy(hrec->keys[hrec->nkeys],str,len);
hrec->keys[hrec->nkeys][len] = 0;
hrec->vals[hrec->nkeys] = NULL;
hrec->nkeys = n;
return 0;
}
int bcf_hrec_set_val(bcf_hrec_t *hrec, int i, const char *str, size_t len, int is_quoted)
{
if ( hrec->vals[i] ) {
free(hrec->vals[i]);
hrec->vals[i] = NULL;
}
if ( !str ) return 0;
if ( is_quoted )
{
if (len >= SIZE_MAX - 3) {
errno = ENOMEM;
return -1;
}
hrec->vals[i] = (char*) malloc((len+3)*sizeof(char));
if (!hrec->vals[i]) return -1;
hrec->vals[i][0] = '"';
memcpy(&hrec->vals[i][1],str,len);
hrec->vals[i][len+1] = '"';
hrec->vals[i][len+2] = 0;
}
else
{
if (len == SIZE_MAX) {
errno = ENOMEM;
return -1;
}
hrec->vals[i] = (char*) malloc((len+1)*sizeof(char));
if (!hrec->vals[i]) return -1;
memcpy(hrec->vals[i],str,len);
hrec->vals[i][len] = 0;
}
return 0;
}
int hrec_add_idx(bcf_hrec_t *hrec, int idx)
{
int n = hrec->nkeys + 1;
char **tmp = (char**) realloc(hrec->keys, sizeof(char*)*n);
if (!tmp) return -1;
hrec->keys = tmp;
tmp = (char**) realloc(hrec->vals, sizeof(char*)*n);
if (!tmp) return -1;
hrec->vals = tmp;
hrec->keys[hrec->nkeys] = strdup("IDX");
if (!hrec->keys[hrec->nkeys]) return -1;
kstring_t str = {0,0,0};
if (kputw(idx, &str) < 0) {
free(hrec->keys[hrec->nkeys]);
return -1;
}
hrec->vals[hrec->nkeys] = str.s;
hrec->nkeys = n;
return 0;
}
int bcf_hrec_find_key(bcf_hrec_t *hrec, const char *key)
{
int i;
for (i=0; i<hrec->nkeys; i++)
if ( !strcasecmp(key,hrec->keys[i]) ) return i;
return -1;
}
static inline int is_escaped(const char *min, const char *str)
{
int n = 0;
while ( --str>=min && *str=='\\' ) n++;
return n%2;
}
bcf_hrec_t *bcf_hdr_parse_line(const bcf_hdr_t *h, const char *line, int *len)
{
bcf_hrec_t *hrec = NULL;
const char *p = line;
if (p[0] != '#' || p[1] != '#') { *len = 0; return NULL; }
p += 2;
const char *q = p;
while ( *q && *q!='=' && *q != '\n' ) q++;
ptrdiff_t n = q-p;
if ( *q!='=' || !n ) // wrong format
goto malformed_line;
hrec = (bcf_hrec_t*) calloc(1,sizeof(bcf_hrec_t));
if (!hrec) { *len = -1; return NULL; }
hrec->key = (char*) malloc(sizeof(char)*(n+1));
if (!hrec->key) goto fail;
memcpy(hrec->key,p,n);
hrec->key[n] = 0;
p = ++q;
if ( *p!='<' ) // generic field, e.g. ##samtoolsVersion=0.1.18-r579
{
while ( *q && *q!='\n' ) q++;
hrec->value = (char*) malloc((q-p+1)*sizeof(char));
if (!hrec->value) goto fail;
memcpy(hrec->value, p, q-p);
hrec->value[q-p] = 0;
*len = q - line + (*q ? 1 : 0); // Skip \n but not \0
return hrec;
}
// structured line, e.g.
// ##INFO=<ID=PV1,Number=1,Type=Float,Description="P-value for baseQ bias">
// ##PEDIGREE=<Name_0=G0-ID,Name_1=G1-ID,Name_3=GN-ID>
int nopen = 1;
while ( *q && *q!='\n' && nopen>0 )
{
p = ++q;
while ( *q && *q==' ' ) { p++; q++; }
// ^[A-Za-z_][0-9A-Za-z_.]*$
if (p==q && *q && (isalpha_c(*q) || *q=='_'))
{
q++;
while ( *q && (isalnum_c(*q) || *q=='_' || *q=='.') ) q++;
}
n = q-p;
int m = 0;
while ( *q && *q==' ' ) { q++; m++; }
if ( *q!='=' || !n )
goto malformed_line;
if (bcf_hrec_add_key(hrec, p, q-p-m) < 0) goto fail;
p = ++q;
while ( *q && *q==' ' ) { p++; q++; }
int quoted = *p=='"' ? 1 : 0;
if ( quoted ) p++, q++;
while ( *q && *q != '\n' )
{
if ( quoted ) { if ( *q=='"' && !is_escaped(p,q) ) break; }
else
{
if ( *q=='<' ) nopen++;
if ( *q=='>' ) nopen--;
if ( !nopen ) break;
if ( *q==',' && nopen==1 ) break;
}
q++;
}
const char *r = q;
while ( r > p && r[-1] == ' ' ) r--;
if (bcf_hrec_set_val(hrec, hrec->nkeys-1, p, r-p, quoted) < 0)
goto fail;
if ( quoted && *q=='"' ) q++;
if ( *q=='>' ) { nopen--; q++; }
}
// Skip to end of line
int nonspace = 0;
p = q;
while ( *q && *q!='\n' ) { nonspace |= !isspace_c(*q); q++; }
if (nonspace) {
char buffer[320];
hts_log_warning("Dropped trailing junk from header line '%s'",
hts_strprint(buffer, sizeof(buffer),
'"', line, q - line));
}
*len = q - line + (*q ? 1 : 0);
return hrec;
fail:
*len = -1;
bcf_hrec_destroy(hrec);
return NULL;
malformed_line:
{
char buffer[320];
while ( *q && *q!='\n' ) q++; // Ensure *len includes full line
hts_log_error("Could not parse the header line: %s",
hts_strprint(buffer, sizeof(buffer),
'"', line, q - line));
*len = q - line + (*q ? 1 : 0);
bcf_hrec_destroy(hrec);
return NULL;
}
}
static int bcf_hdr_set_idx(bcf_hdr_t *hdr, int dict_type, const char *tag, bcf_idinfo_t *idinfo)
{
size_t new_n;
// If available, preserve existing IDX
if ( idinfo->id==-1 )
idinfo->id = hdr->n[dict_type];
else if ( idinfo->id < hdr->n[dict_type] && hdr->id[dict_type][idinfo->id].key )
{
hts_log_error("Conflicting IDX=%d lines in the header dictionary, the new tag is %s",
idinfo->id, tag);
errno = EINVAL;
return -1;
}
new_n = idinfo->id >= hdr->n[dict_type] ? idinfo->id+1 : hdr->n[dict_type];
if (hts_resize(bcf_idpair_t, new_n, &hdr->m[dict_type],
&hdr->id[dict_type], HTS_RESIZE_CLEAR)) {
return -1;
}
hdr->n[dict_type] = new_n;
// NB: the next kh_put call can invalidate the idinfo pointer, therefore
// we leave it unassigned here. It must be set explicitly in bcf_hdr_sync.
hdr->id[dict_type][idinfo->id].key = tag;
return 0;
}
// returns: 1 when hdr needs to be synced, -1 on error, 0 otherwise
static int bcf_hdr_register_hrec(bcf_hdr_t *hdr, bcf_hrec_t *hrec)
{
// contig
int i, ret, replacing = 0;
khint_t k;
char *str = NULL;
if ( !strcmp(hrec->key, "contig") )
{
hts_pos_t len = 0;
hrec->type = BCF_HL_CTG;
// Get the contig ID ($str) and length ($j)
i = bcf_hrec_find_key(hrec,"length");
if ( i<0 ) len = 0;
else {
char *end = hrec->vals[i];
len = strtoll(hrec->vals[i], &end, 10);
if (end == hrec->vals[i] || len < 0) return 0;
}
i = bcf_hrec_find_key(hrec,"ID");
if ( i<0 ) return 0;
str = strdup(hrec->vals[i]);
if (!str) return -1;
// Register in the dictionary
vdict_t *d = (vdict_t*)hdr->dict[BCF_DT_CTG];
khint_t k = kh_get(vdict, d, str);
if ( k != kh_end(d) ) { // already present
free(str); str=NULL;
if (kh_val(d, k).hrec[0] != NULL) // and not removed
return 0;
replacing = 1;
} else {
k = kh_put(vdict, d, str, &ret);
if (ret < 0) { free(str); return -1; }
}
int idx = bcf_hrec_find_key(hrec,"IDX");
if ( idx!=-1 )
{
char *tmp = hrec->vals[idx];
idx = strtol(hrec->vals[idx], &tmp, 10);
if ( *tmp || idx < 0 || idx >= INT_MAX - 1)
{
if (!replacing) {
kh_del(vdict, d, k);
free(str);
}
hts_log_warning("Error parsing the IDX tag, skipping");
return 0;
}
}
kh_val(d, k) = bcf_idinfo_def;
kh_val(d, k).id = idx;
kh_val(d, k).info[0] = len;
kh_val(d, k).hrec[0] = hrec;
if (bcf_hdr_set_idx(hdr, BCF_DT_CTG, kh_key(d,k), &kh_val(d,k)) < 0) {
if (!replacing) {
kh_del(vdict, d, k);
free(str);
}
return -1;
}
if ( idx==-1 ) {
if (hrec_add_idx(hrec, kh_val(d,k).id) < 0) {
return -1;
}
}
return 1;
}
if ( !strcmp(hrec->key, "INFO") ) hrec->type = BCF_HL_INFO;
else if ( !strcmp(hrec->key, "FILTER") ) hrec->type = BCF_HL_FLT;
else if ( !strcmp(hrec->key, "FORMAT") ) hrec->type = BCF_HL_FMT;
else if ( hrec->nkeys>0 ) { hrec->type = BCF_HL_STR; return 1; }
else return 0;
// INFO/FILTER/FORMAT
char *id = NULL;
uint32_t type = UINT32_MAX, var = UINT32_MAX;
int num = -1, idx = -1;
for (i=0; i<hrec->nkeys; i++)
{
if ( !strcmp(hrec->keys[i], "ID") ) id = hrec->vals[i];
else if ( !strcmp(hrec->keys[i], "IDX") )
{
char *tmp = hrec->vals[i];
idx = strtol(hrec->vals[i], &tmp, 10);
if ( *tmp || idx < 0 || idx >= INT_MAX - 1)
{
hts_log_warning("Error parsing the IDX tag, skipping");
return 0;
}
}
else if ( !strcmp(hrec->keys[i], "Type") )
{
if ( !strcmp(hrec->vals[i], "Integer") ) type = BCF_HT_INT;
else if ( !strcmp(hrec->vals[i], "Float") ) type = BCF_HT_REAL;
else if ( !strcmp(hrec->vals[i], "String") ) type = BCF_HT_STR;
else if ( !strcmp(hrec->vals[i], "Character") ) type = BCF_HT_STR;
else if ( !strcmp(hrec->vals[i], "Flag") ) type = BCF_HT_FLAG;
else
{
hts_log_warning("The type \"%s\" is not supported, assuming \"String\"", hrec->vals[i]);
type = BCF_HT_STR;
}
}
else if ( !strcmp(hrec->keys[i], "Number") )
{
if ( !strcmp(hrec->vals[i],"A") ) var = BCF_VL_A;
else if ( !strcmp(hrec->vals[i],"R") ) var = BCF_VL_R;
else if ( !strcmp(hrec->vals[i],"G") ) var = BCF_VL_G;
else if ( !strcmp(hrec->vals[i],".") ) var = BCF_VL_VAR;
else
{
sscanf(hrec->vals[i],"%d",&num);
var = BCF_VL_FIXED;
}
if (var != BCF_VL_FIXED) num = 0xfffff;
}
}
if (hrec->type == BCF_HL_INFO || hrec->type == BCF_HL_FMT) {
if (type == -1) {
hts_log_warning("%s %s field has no Type defined. Assuming String",
*hrec->key == 'I' ? "An" : "A", hrec->key);
type = BCF_HT_STR;
}
if (var == -1) {
hts_log_warning("%s %s field has no Number defined. Assuming '.'",
*hrec->key == 'I' ? "An" : "A", hrec->key);
var = BCF_VL_VAR;
}
}
uint32_t info = ((((uint32_t)num) & 0xfffff)<<12 |
(var & 0xf) << 8 |
(type & 0xf) << 4 |
(((uint32_t) hrec->type) & 0xf));
if ( !id ) return 0;
str = strdup(id);
if (!str) return -1;
vdict_t *d = (vdict_t*)hdr->dict[BCF_DT_ID];
k = kh_get(vdict, d, str);
if ( k != kh_end(d) )
{
// already present
free(str);
if ( kh_val(d, k).hrec[info&0xf] ) return 0;
kh_val(d, k).info[info&0xf] = info;
kh_val(d, k).hrec[info&0xf] = hrec;
if ( idx==-1 ) {
if (hrec_add_idx(hrec, kh_val(d, k).id) < 0) {
return -1;
}
}
return 1;
}
k = kh_put(vdict, d, str, &ret);
if (ret < 0) {
free(str);
return -1;
}
kh_val(d, k) = bcf_idinfo_def;
kh_val(d, k).info[info&0xf] = info;
kh_val(d, k).hrec[info&0xf] = hrec;
kh_val(d, k).id = idx;
if (bcf_hdr_set_idx(hdr, BCF_DT_ID, kh_key(d,k), &kh_val(d,k)) < 0) {
kh_del(vdict, d, k);
free(str);
return -1;
}
if ( idx==-1 ) {
if (hrec_add_idx(hrec, kh_val(d,k).id) < 0) {
return -1;
}
}
return 1;
}
int bcf_hdr_add_hrec(bcf_hdr_t *hdr, bcf_hrec_t *hrec)
{
int res;
if ( !hrec ) return 0;
hrec->type = BCF_HL_GEN;
res = bcf_hdr_register_hrec(hdr,hrec);
if (res < 0) return -1;
if ( !res )
{
// If one of the hashed field, then it is already present
if ( hrec->type != BCF_HL_GEN )
{
bcf_hrec_destroy(hrec);
return 0;
}
// Is one of the generic fields and already present?
int i;
for (i=0; i<hdr->nhrec; i++)
{
if ( hdr->hrec[i]->type!=BCF_HL_GEN ) continue;
if ( !strcmp(hdr->hrec[i]->key,hrec->key) && !strcmp(hrec->key,"fileformat") ) break;
if ( !strcmp(hdr->hrec[i]->key,hrec->key) && !strcmp(hdr->hrec[i]->value,hrec->value) ) break;
}
if ( i<hdr->nhrec )
{
bcf_hrec_destroy(hrec);
return 0;
}
}
// New record, needs to be added
int n = hdr->nhrec + 1;
bcf_hrec_t **new_hrec = realloc(hdr->hrec, n*sizeof(bcf_hrec_t*));
if (!new_hrec) return -1;
hdr->hrec = new_hrec;
hdr->hrec[hdr->nhrec] = hrec;
hdr->dirty = 1;
hdr->nhrec = n;
return hrec->type==BCF_HL_GEN ? 0 : 1;
}
/*
* Note that while querying of FLT,INFO,FMT,CTG lines is fast (the keys are hashed),
* the STR,GEN lines are searched for linearly in a linked list of all header lines.
* This may become a problem for VCFs with huge headers, we might need to build a
* dictionary for these lines as well.
*/
bcf_hrec_t *bcf_hdr_get_hrec(const bcf_hdr_t *hdr, int type, const char *key, const char *value, const char *str_class)
{
int i;
if ( type==BCF_HL_GEN )
{
for (i=0; i<hdr->nhrec; i++)
{
if ( hdr->hrec[i]->type!=type ) continue;
if ( strcmp(hdr->hrec[i]->key,key) ) continue;
if ( !value || !strcmp(hdr->hrec[i]->value,value) ) return hdr->hrec[i];
}
return NULL;
}
else if ( type==BCF_HL_STR )
{
for (i=0; i<hdr->nhrec; i++)
{
if ( hdr->hrec[i]->type!=type ) continue;
if ( strcmp(hdr->hrec[i]->key,str_class) ) continue;
int j = bcf_hrec_find_key(hdr->hrec[i],key);
if ( j>=0 && !strcmp(hdr->hrec[i]->vals[j],value) ) return hdr->hrec[i];
}
return NULL;
}
vdict_t *d = type==BCF_HL_CTG ? (vdict_t*)hdr->dict[BCF_DT_CTG] : (vdict_t*)hdr->dict[BCF_DT_ID];
khint_t k = kh_get(vdict, d, value);
if ( k == kh_end(d) ) return NULL;
return kh_val(d, k).hrec[type==BCF_HL_CTG?0:type];
}
void bcf_hdr_check_sanity(bcf_hdr_t *hdr)
{
static int PL_warned = 0, GL_warned = 0;
if ( !PL_warned )
{
int id = bcf_hdr_id2int(hdr, BCF_DT_ID, "PL");
if ( bcf_hdr_idinfo_exists(hdr,BCF_HL_FMT,id) && bcf_hdr_id2length(hdr,BCF_HL_FMT,id)!=BCF_VL_G )
{
hts_log_warning("PL should be declared as Number=G");
PL_warned = 1;
}
}
if ( !GL_warned )
{
int id = bcf_hdr_id2int(hdr, BCF_DT_ID, "GL");
if ( bcf_hdr_idinfo_exists(hdr,BCF_HL_FMT,id) && bcf_hdr_id2length(hdr,BCF_HL_FMT,id)!=BCF_VL_G )
{
hts_log_warning("GL should be declared as Number=G");
GL_warned = 1;
}
}
}
int bcf_hdr_parse(bcf_hdr_t *hdr, char *htxt)
{
int len, done = 0;
char *p = htxt;
// Check sanity: "fileformat" string must come as first
bcf_hrec_t *hrec = bcf_hdr_parse_line(hdr,p,&len);
if ( !hrec || !hrec->key || strcasecmp(hrec->key,"fileformat") )
hts_log_warning("The first line should be ##fileformat; is the VCF/BCF header broken?");
if (bcf_hdr_add_hrec(hdr, hrec) < 0) {
bcf_hrec_destroy(hrec);
return -1;
}
// The filter PASS must appear first in the dictionary
hrec = bcf_hdr_parse_line(hdr,"##FILTER=<ID=PASS,Description=\"All filters passed\">",&len);
if (!hrec || bcf_hdr_add_hrec(hdr, hrec) < 0) {
bcf_hrec_destroy(hrec);
return -1;
}
// Parse the whole header
do {
while (NULL != (hrec = bcf_hdr_parse_line(hdr, p, &len))) {
if (bcf_hdr_add_hrec(hdr, hrec) < 0) {
bcf_hrec_destroy(hrec);
return -1;
}
p += len;
}
assert(hrec == NULL);
if (len < 0) {
// len < 0 indicates out-of-memory, or similar error
hts_log_error("Could not parse header line: %s", strerror(errno));
return -1;
} else if (len > 0) {
// Bad header line. bcf_hdr_parse_line() will have logged it.
// Skip and try again on the next line (p + len will be the start
// of the next one).
p += len;
continue;
}
// Next should be the sample line. If not, it was a malformed
// header, in which case print a warning and skip (many VCF
// operations do not really care about a few malformed lines).
// In the future we may want to add a strict mode that errors in
// this case.
if ( strncmp("#CHROM\tPOS",p,10) != 0 ) {
char *eol = strchr(p, '\n');
if (*p != '\0') {
char buffer[320];
hts_log_warning("Could not parse header line: %s",
hts_strprint(buffer, sizeof(buffer),
'"', p,
eol ? (eol - p) : SIZE_MAX));
}
if (eol) {
p = eol + 1; // Try from the next line.
} else {
done = -1; // No more lines left, give up.
}
} else {
done = 1; // Sample line found
}
} while (!done);
if (done < 0) {
// No sample line is fatal.
hts_log_error("Could not parse the header, sample line not found");
return -1;
}
if (bcf_hdr_parse_sample_line(hdr,p) < 0)
return -1;
if (bcf_hdr_sync(hdr) < 0)
return -1;
bcf_hdr_check_sanity(hdr);
return 0;
}
int bcf_hdr_append(bcf_hdr_t *hdr, const char *line)
{
int len;
bcf_hrec_t *hrec = bcf_hdr_parse_line(hdr, (char*) line, &len);
if ( !hrec ) return -1;
if (bcf_hdr_add_hrec(hdr, hrec) < 0)
return -1;
return 0;
}
void bcf_hdr_remove(bcf_hdr_t *hdr, int type, const char *key)
{
int i = 0;
bcf_hrec_t *hrec;
if ( !key )
{
while ( i<hdr->nhrec )
{
if ( hdr->hrec[i]->type!=type ) { i++; continue; }
hrec = hdr->hrec[i];
if ( type==BCF_HL_FLT || type==BCF_HL_INFO || type==BCF_HL_FMT || type== BCF_HL_CTG )
{
int j = bcf_hrec_find_key(hdr->hrec[i], "ID");
if ( j>=0 )
{
vdict_t *d = type==BCF_HL_CTG ? (vdict_t*)hdr->dict[BCF_DT_CTG] : (vdict_t*)hdr->dict[BCF_DT_ID];
khint_t k = kh_get(vdict, d, hdr->hrec[i]->vals[j]);
kh_val(d, k).hrec[type==BCF_HL_CTG?0:type] = NULL;
}
}
hdr->dirty = 1;
hdr->nhrec--;
if ( i < hdr->nhrec )
memmove(&hdr->hrec[i],&hdr->hrec[i+1],(hdr->nhrec-i)*sizeof(bcf_hrec_t*));
bcf_hrec_destroy(hrec);
}
return;
}
while (1)
{
if ( type==BCF_HL_FLT || type==BCF_HL_INFO || type==BCF_HL_FMT || type== BCF_HL_CTG )
{
hrec = bcf_hdr_get_hrec(hdr, type, "ID", key, NULL);
if ( !hrec ) return;
for (i=0; i<hdr->nhrec; i++)
if ( hdr->hrec[i]==hrec ) break;
assert( i<hdr->nhrec );
vdict_t *d = type==BCF_HL_CTG ? (vdict_t*)hdr->dict[BCF_DT_CTG] : (vdict_t*)hdr->dict[BCF_DT_ID];
khint_t k = kh_get(vdict, d, key);
kh_val(d, k).hrec[type==BCF_HL_CTG?0:type] = NULL;
}
else
{
for (i=0; i<hdr->nhrec; i++)
{
if ( hdr->hrec[i]->type!=type ) continue;
if ( type==BCF_HL_GEN )
{
if ( !strcmp(hdr->hrec[i]->key,key) ) break;
}
else
{
// not all structured lines have ID, we could be more sophisticated as in bcf_hdr_get_hrec()
int j = bcf_hrec_find_key(hdr->hrec[i], "ID");
if ( j>=0 && !strcmp(hdr->hrec[i]->vals[j],key) ) break;
}
}
if ( i==hdr->nhrec ) return;
hrec = hdr->hrec[i];
}
hdr->nhrec--;
if ( i < hdr->nhrec )
memmove(&hdr->hrec[i],&hdr->hrec[i+1],(hdr->nhrec-i)*sizeof(bcf_hrec_t*));
bcf_hrec_destroy(hrec);
hdr->dirty = 1;
}
}
int bcf_hdr_printf(bcf_hdr_t *hdr, const char *fmt, ...)
{
char tmp[256], *line = tmp;
va_list ap;
va_start(ap, fmt);
int n = vsnprintf(line, sizeof(tmp), fmt, ap);
va_end(ap);
if (n >= sizeof(tmp)) {
n++; // For trailing NUL
line = (char*)malloc(n);
if (!line)
return -1;
va_start(ap, fmt);
vsnprintf(line, n, fmt, ap);
va_end(ap);
}
int ret = bcf_hdr_append(hdr, line);
if (line != tmp) free(line);
return ret;
}
/**********************
*** BCF header I/O ***
**********************/
const char *bcf_hdr_get_version(const bcf_hdr_t *hdr)
{
bcf_hrec_t *hrec = bcf_hdr_get_hrec(hdr, BCF_HL_GEN, "fileformat", NULL, NULL);
if ( !hrec )
{