-
Notifications
You must be signed in to change notification settings - Fork 447
/
vcf.c
4971 lines (4558 loc) · 166 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-2022 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'", sdup);
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 *hdr, const char *str)
{
const char *mandatory = "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO";
if ( strncmp(str,mandatory,strlen(mandatory)) )
{
hts_log_error("Could not parse the \"#CHROM..\" line, either the fields are incorrect or spaces are present instead of tabs:\n\t%s",str);
return -1;
}
const char *beg = str + strlen(mandatory), *end;
if ( !*beg || *beg=='\n' ) return 0;
if ( strncmp(beg,"\tFORMAT\t",8) )
{
hts_log_error("Could not parse the \"#CHROM..\" line, either FORMAT is missing or spaces are present instead of tabs:\n\t%s",str);
return -1;
}
beg += 8;
int ret = 0;
while ( *beg )
{
end = beg;
while ( *end && *end!='\t' && *end!='\n' ) end++;
if ( bcf_hdr_add_sample_len(hdr, beg, end-beg) < 0 ) ret = -1;
if ( !*end || *end=='\n' || ret<0 ) break;
beg = end + 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 void bcf_hrec_set_type(bcf_hrec_t *hrec)
{
if ( !strcmp(hrec->key, "contig") ) hrec->type = BCF_HL_CTG;
else 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;
else hrec->type = BCF_HL_GEN;
}
/**
The arrays were generated with
valid_ctg:
perl -le '@v = (split(//,q[!#$%&*+./:;=?@^_|~-]),"a"..."z","A"..."Z","0"..."9"); @a = (0) x 256; foreach $c (@v) { $a[ord($c)] = 1; } print join(", ",@a)' | fold -w 48
valid_tag:
perl -le '@v = (split(//,q[_.]),"a"..."z","A"..."Z","0"..."9"); @a = (0) x 256; foreach $c (@v) { $a[ord($c)] = 1; } print join(", ",@a)' | fold -w 48
*/
static const uint8_t valid_ctg[256] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1,
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
static const uint8_t valid_tag[256] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/**
bcf_hrec_check() - check the validity of structured header lines
Returns 0 on success or negative value on error.
Currently the return status is not checked by the caller
and only a warning is printed on stderr. This should be improved
to propagate the error all the way up to the caller and let it
decide what to do: throw an error or proceed anyway.
*/
static int bcf_hrec_check(bcf_hrec_t *hrec)
{
int i;
bcf_hrec_set_type(hrec);
if ( hrec->type==BCF_HL_CTG )
{
i = bcf_hrec_find_key(hrec,"ID");
if ( i<0 ) goto err_missing_id;
char *val = hrec->vals[i];
if ( val[0]=='*' || val[0]=='=' || !valid_ctg[(uint8_t)val[0]] ) goto err_invalid_ctg;
while ( *(++val) )
if ( !valid_ctg[(uint8_t)*val] ) goto err_invalid_ctg;
return 0;
}
if ( hrec->type==BCF_HL_INFO )
{
i = bcf_hrec_find_key(hrec,"ID");
if ( i<0 ) goto err_missing_id;
char *val = hrec->vals[i];
if ( !strcmp(val,"1000G") ) return 0;
if ( val[0]=='.' || (val[0]>='0' && val[0]<='9') || !valid_tag[(uint8_t)val[0]] ) goto err_invalid_tag;
while ( *(++val) )
if ( !valid_tag[(uint8_t)*val] ) goto err_invalid_tag;
return 0;
}
if ( hrec->type==BCF_HL_FMT )
{
i = bcf_hrec_find_key(hrec,"ID");
if ( i<0 ) goto err_missing_id;
char *val = hrec->vals[i];
if ( val[0]=='.' || (val[0]>='0' && val[0]<='9') || !valid_tag[(uint8_t)val[0]] ) goto err_invalid_tag;
while ( *(++val) )
if ( !valid_tag[(uint8_t)*val] ) goto err_invalid_tag;
return 0;
}
return 0;
err_missing_id:
hts_log_warning("Missing ID attribute in one or more header lines");
return -1;
err_invalid_ctg:
hts_log_warning("Invalid contig name: \"%s\"", hrec->vals[i]);
return -1;
err_invalid_tag:
hts_log_warning("Invalid tag name: \"%s\"", hrec->vals[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;
hrec->type = -1;
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 = 0;
char ending = '\0';
switch (*p) {
case '"':
quoted = 1;
ending = '"';
p++;
break;
case '[':
quoted = 1;
ending = ']';
break;
}
if ( quoted ) q++;
while ( *q && *q != '\n' )
{
if ( quoted ) { if ( *q==ending && !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;
if (quoted && ending == ']') {
if (*q == ending) {
r++;
q++;
quoted = 0;
} else {
char buffer[320];
hts_log_error("Missing ']' in header line %s",
hts_strprint(buffer, sizeof(buffer), '"',
line, q-line));
goto fail;
}
}
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==ending ) q++;
if ( *q=='>' )
{
if (nopen) nopen--; // this can happen with nested angle brackets <>
q++;
}
}
if ( nopen )
hts_log_warning("Incomplete header line, trying to proceed anyway:\n\t[%s]\n\t[%d]",line,q[0]);
// 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;
bcf_hrec_set_type(hrec);
if ( hrec->type==BCF_HL_CTG )
{
hts_pos_t len = 0;
// 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 ( hrec->type==BCF_HL_STR ) return 1;
if ( hrec->type!=BCF_HL_INFO && hrec->type!=BCF_HL_FLT && hrec->type!=BCF_HL_FMT ) 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;
}
if ( type==BCF_HT_FLAG && (var!=BCF_VL_FIXED || num!=0) )
{
hts_log_warning("The definition of Flag \"%s/%s\" is invalid, forcing Number=0", hrec->key,id);
var = BCF_VL_FIXED;
num = 0;
}
}
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;
bcf_hrec_check(hrec); // todo: check return status and propagate errors up
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 )
{
if (!str_class)
return NULL;
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;