forked from samtools/htslib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vcf.c
3249 lines (2996 loc) · 108 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-2015 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. */
#include <config.h>
#include <zlib.h>
#include <stdio.h>
#include <ctype.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include "htslib/kstring.h"
#include "htslib/bgzf.h"
#include "htslib/vcf.h"
#include "htslib/tbx.h"
#include "htslib/hfile.h"
#include "htslib/khash_str2int.h"
#include "htslib/khash.h"
KHASH_MAP_INIT_STR(vdict, bcf_idinfo_t)
typedef khash_t(vdict) vdict_t;
#include "htslib/kseq.h"
KSTREAM_DECLARE(gzFile, gzread)
uint32_t bcf_float_missing = 0x7F800001;
uint32_t bcf_float_vector_end = 0x7F800002;
uint8_t bcf_type_shift[] = { 0, 0, 1, 2, 0, 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 };
/*************************
*** VCF header parser ***
*************************/
int bcf_hdr_sync(bcf_hdr_t *h);
int bcf_hdr_add_sample(bcf_hdr_t *h, const char *s)
{
if ( !s ) return 0;
const char *ss = s;
while ( !*ss && isspace(*ss) ) ss++;
if ( !*ss )
{
fprintf(stderr,"[E::%s] Empty sample name: trailing spaces/tabs in the header line?\n", __func__);
abort();
}
vdict_t *d = (vdict_t*)h->dict[BCF_DT_SAMPLE];
int ret;
char *sdup = strdup(s);
int k = kh_put(vdict, d, sdup, &ret);
if (ret) { // absent
kh_val(d, k) = bcf_idinfo_def;
kh_val(d, k).id = kh_size(d) - 1;
} else {
if (hts_verbose >= 2)
{
fprintf(stderr, "[E::%s] Duplicated sample name '%s'\n", __func__, s);
abort();
}
free(sdup);
return -1;
}
int n = kh_size(d);
h->samples = (char**) realloc(h->samples,sizeof(char*)*n);
h->samples[n-1] = sdup;
h->dirty = 1;
return 0;
}
int 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 != '\t' && *q != 0 && *q != '\n') continue;
if (++i > 9) {
char *s = (char*)malloc(q - p + 1);
strncpy(s, p, q - p);
s[q - p] = 0;
if ( bcf_hdr_add_sample(h,s) < 0 ) ret = -1;
free(s);
}
if (*q == 0 || *q == '\n') break;
p = q + 1;
}
bcf_hdr_add_sample(h,NULL);
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;
// find out the largest id, there may be holes because of IDX
int max_id = -1;
for (k=kh_begin(d); k<kh_end(d); k++)
{
if (!kh_exist(d,k)) continue;
if ( max_id < kh_val(d,k).id ) max_id = kh_val(d,k).id;
}
if ( max_id >= h->n[i] )
{
h->id[i] = (bcf_idpair_t*)realloc(h->id[i], (max_id+1)*sizeof(bcf_idpair_t));
for (k=h->n[i]; k<=max_id; k++)
{
h->id[i][k].key = NULL;
h->id[i][k].val = NULL;
}
h->n[i] = max_id+1;
}
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)
{
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)
{
bcf_hrec_t *out = (bcf_hrec_t*) calloc(1,sizeof(bcf_hrec_t));
out->type = hrec->type;
if ( hrec->key ) out->key = strdup(hrec->key);
if ( hrec->value ) out->value = strdup(hrec->value);
out->nkeys = hrec->nkeys;
out->keys = (char**) malloc(sizeof(char*)*hrec->nkeys);
out->vals = (char**) malloc(sizeof(char*)*hrec->nkeys);
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 ( hrec->vals[i] ) out->vals[j] = strdup(hrec->vals[i]);
j++;
}
if ( i!=j ) out->nkeys -= i-j; // IDX was omitted
return out;
}
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);
}
}
void bcf_hrec_add_key(bcf_hrec_t *hrec, const char *str, int len)
{
int n = ++hrec->nkeys;
hrec->keys = (char**) realloc(hrec->keys, sizeof(char*)*n);
hrec->vals = (char**) realloc(hrec->vals, sizeof(char*)*n);
assert( len );
hrec->keys[n-1] = (char*) malloc((len+1)*sizeof(char));
memcpy(hrec->keys[n-1],str,len);
hrec->keys[n-1][len] = 0;
hrec->vals[n-1] = NULL;
}
void bcf_hrec_set_val(bcf_hrec_t *hrec, int i, const char *str, int len, int is_quoted)
{
if ( !str ) { hrec->vals[i] = NULL; return; }
if ( hrec->vals[i] ) free(hrec->vals[i]);
if ( is_quoted )
{
hrec->vals[i] = (char*) malloc((len+3)*sizeof(char));
hrec->vals[i][0] = '"';
memcpy(&hrec->vals[i][1],str,len);
hrec->vals[i][len+1] = '"';
hrec->vals[i][len+2] = 0;
}
else
{
hrec->vals[i] = (char*) malloc((len+1)*sizeof(char));
memcpy(hrec->vals[i],str,len);
hrec->vals[i][len] = 0;
}
}
void hrec_add_idx(bcf_hrec_t *hrec, int idx)
{
int n = ++hrec->nkeys;
hrec->keys = (char**) realloc(hrec->keys, sizeof(char*)*n);
hrec->vals = (char**) realloc(hrec->vals, sizeof(char*)*n);
hrec->keys[n-1] = strdup("IDX");
kstring_t str = {0,0,0};
kputw(idx, &str);
hrec->vals[n-1] = str.s;
}
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)
{
const char *p = line;
if (p[0] != '#' || p[1] != '#') { *len = 0; return NULL; }
p += 2;
const char *q = p;
while ( *q && *q!='=' ) q++;
int n = q-p;
if ( *q!='=' || !n ) { *len = q-line+1; return NULL; } // wrong format
bcf_hrec_t *hrec = (bcf_hrec_t*) calloc(1,sizeof(bcf_hrec_t));
hrec->key = (char*) malloc(sizeof(char)*(n+1));
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));
memcpy(hrec->value, p, q-p);
hrec->value[q-p] = 0;
*len = q-line+1;
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 )
{
p = ++q;
// ^[A-Za-z_][0-9A-Za-z_.]*$
if (p==q && *q && (isalpha(*q) || *q=='_'))
{
q++;
while ( *q && (isalnum(*q) || *q=='_' || *q=='.') ) q++;
}
n = q-p;
if ( *q!='=' || !n )
{
// wrong format
while ( *q && *q!='\n' ) q++;
kstring_t tmp = {0,0,0};
kputsn(line,q-line,&tmp);
fprintf(stderr,"Could not parse the header line: \"%s\"\n", tmp.s);
free(tmp.s);
*len = q-line+1;
bcf_hrec_destroy(hrec);
return NULL;
}
bcf_hrec_add_key(hrec, p, q-p);
p = ++q;
int quoted = *p=='"' ? 1 : 0;
if ( quoted ) p++, q++;
while (1)
{
if ( !*q ) break;
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++;
}
bcf_hrec_set_val(hrec, hrec->nkeys-1, p, q-p, quoted);
if ( quoted ) q++;
if ( *q=='>' ) { nopen--; q++; }
}
*len = q-line+1;
return hrec;
}
// returns: 1 when hdr needs to be synced, 0 otherwise
int bcf_hdr_register_hrec(bcf_hdr_t *hdr, bcf_hrec_t *hrec)
{
// contig
int i,j,k, ret;
char *str;
if ( !strcmp(hrec->key, "contig") )
{
hrec->type = BCF_HL_CTG;
// Get the contig ID ($str) and length ($j)
i = bcf_hrec_find_key(hrec,"length");
if ( i<0 ) j = 0;
else if ( sscanf(hrec->vals[i],"%d",&j)!=1 ) return 0;
i = bcf_hrec_find_key(hrec,"ID");
if ( i<0 ) return 0;
str = strdup(hrec->vals[i]);
// Register in the dictionary
vdict_t *d = (vdict_t*)hdr->dict[BCF_DT_CTG];
k = kh_put(vdict, d, str, &ret);
if ( !ret ) { free(str); return 0; } // already present
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 )
{
fprintf(stderr,"[%s:%d %s] Error parsing the IDX tag, skipping.\n", __FILE__,__LINE__,__FUNCTION__);
return 0;
}
}
else
{
idx = kh_size(d) - 1;
hrec_add_idx(hrec, idx);
}
kh_val(d, k) = bcf_idinfo_def;
kh_val(d, k).id = idx;
kh_val(d, k).info[0] = j;
kh_val(d, k).hrec[0] = hrec;
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;
int type = -1, num = -1, var = -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 )
{
fprintf(stderr,"[%s:%d %s] Error parsing the IDX tag, skipping.\n", __FILE__,__LINE__,__FUNCTION__);
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
{
if (hts_verbose >= 2) fprintf(stderr, "[E::%s] The type \"%s\" is not supported, assuming \"String\"\n", __func__, 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;
}
}
uint32_t info = (uint32_t)num<<12 | var<<8 | type<<4 | hrec->type;
if ( !id ) return 0;
str = strdup(id);
vdict_t *d = (vdict_t*)hdr->dict[BCF_DT_ID];
k = kh_put(vdict, d, str, &ret);
if ( !ret )
{
// 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 ) hrec_add_idx(hrec, kh_val(d, k).id);
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==-1 ? kh_size(d) - 1 : idx;
if ( idx==-1 ) hrec_add_idx(hrec, kh_val(d, k).id);
return 1;
}
int bcf_hdr_add_hrec(bcf_hdr_t *hdr, bcf_hrec_t *hrec)
{
if ( !hrec ) return 0;
hrec->type = BCF_HL_GEN;
if ( !bcf_hdr_register_hrec(hdr,hrec) )
{
// 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;
hdr->hrec = (bcf_hrec_t**) realloc(hdr->hrec, n*sizeof(bcf_hrec_t*));
hdr->hrec[n-1] = hrec;
hdr->dirty = 1;
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 )
{
if (hts_verbose >= 2) fprintf(stderr,"[W::%s] PL should be declared as Number=G\n", __func__);
PL_warned = 1;
}
}
if ( !GL_warned )
{
int id = bcf_hdr_id2int(hdr, BCF_HL_FMT, "GL");
if ( bcf_hdr_idinfo_exists(hdr,BCF_HL_FMT,id) && bcf_hdr_id2length(hdr,BCF_HL_FMT,id)!=BCF_VL_G )
{
if (hts_verbose >= 2) fprintf(stderr,"[W::%s] GL should be declared as Number=G\n", __func__);
GL_warned = 1;
}
}
}
int bcf_hdr_parse(bcf_hdr_t *hdr, char *htxt)
{
int len, needs_sync = 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") )
fprintf(stderr, "[W::%s] The first line should be ##fileformat; is the VCF/BCF header broken?\n", __func__);
needs_sync += bcf_hdr_add_hrec(hdr, hrec);
// The filter PASS must appear first in the dictionary
hrec = bcf_hdr_parse_line(hdr,"##FILTER=<ID=PASS,Description=\"All filters passed\">",&len);
needs_sync += bcf_hdr_add_hrec(hdr, hrec);
// Parse the whole header
while ( (hrec=bcf_hdr_parse_line(hdr,p,&len)) )
{
needs_sync += bcf_hdr_add_hrec(hdr, hrec);
p += len;
}
int ret = bcf_hdr_parse_sample_line(hdr,p);
bcf_hdr_sync(hdr);
bcf_hdr_check_sanity(hdr);
return ret;
}
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;
bcf_hdr_add_hrec(hdr, hrec);
return 0;
}
void bcf_hdr_remove(bcf_hdr_t *hdr, int type, const char *key)
{
int i;
bcf_hrec_t *hrec;
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, ...)
{
va_list ap;
va_start(ap, fmt);
int n = vsnprintf(NULL, 0, fmt, ap) + 2;
va_end(ap);
char *line = (char*)malloc(n);
va_start(ap, fmt);
vsnprintf(line, n, fmt, ap);
va_end(ap);
int ret = bcf_hdr_append(hdr, line);
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 )
{
fprintf(stderr,"No version string found, assuming VCFv4.2\n");
return "VCFv4.2";
}
return hrec->value;
}
void bcf_hdr_set_version(bcf_hdr_t *hdr, const char *version)
{
bcf_hrec_t *hrec = bcf_hdr_get_hrec(hdr, BCF_HL_GEN, "fileformat", NULL, NULL);
if ( !hrec )
{
int len;
kstring_t str = {0,0,0};
ksprintf(&str,"##fileformat=%s", version);
hrec = bcf_hdr_parse_line(hdr, str.s, &len);
free(str.s);
}
else
{
free(hrec->value);
hrec->value = strdup(version);
}
hdr->dirty = 1;
}
bcf_hdr_t *bcf_hdr_init(const char *mode)
{
int i;
bcf_hdr_t *h;
h = (bcf_hdr_t*)calloc(1, sizeof(bcf_hdr_t));
for (i = 0; i < 3; ++i)
h->dict[i] = kh_init(vdict);
if ( strchr(mode,'w') )
{
bcf_hdr_append(h, "##fileformat=VCFv4.2");
// The filter PASS must appear first in the dictionary
bcf_hdr_append(h, "##FILTER=<ID=PASS,Description=\"All filters passed\">");
}
return h;
}
void bcf_hdr_destroy(bcf_hdr_t *h)
{
int i;
khint_t k;
for (i = 0; i < 3; ++i) {
vdict_t *d = (vdict_t*)h->dict[i];
if (d == 0) continue;
for (k = kh_begin(d); k != kh_end(d); ++k)
if (kh_exist(d, k)) free((char*)kh_key(d, k));
kh_destroy(vdict, d);
free(h->id[i]);
}
for (i=0; i<h->nhrec; i++)
bcf_hrec_destroy(h->hrec[i]);
if (h->nhrec) free(h->hrec);
if (h->samples) free(h->samples);
free(h->keep_samples);
free(h->transl[0]); free(h->transl[1]);
free(h->mem.s);
free(h);
}
bcf_hdr_t *bcf_hdr_read(htsFile *hfp)
{
if (hfp->format.format == vcf)
return vcf_hdr_read(hfp);
BGZF *fp = hfp->fp.bgzf;
uint8_t magic[5];
bcf_hdr_t *h;
h = bcf_hdr_init("r");
if ( bgzf_read(fp, magic, 5)<0 )
{
fprintf(stderr,"[%s:%d %s] Failed to read the header (reading BCF in text mode?)\n", __FILE__,__LINE__,__FUNCTION__);
return NULL;
}
if (strncmp((char*)magic, "BCF\2\2", 5) != 0)
{
if (!strncmp((char*)magic, "BCF", 3))
fprintf(stderr,"[%s:%d %s] invalid BCF2 magic string: only BCFv2.2 is supported.\n", __FILE__,__LINE__,__FUNCTION__);
else if (hts_verbose >= 2)
fprintf(stderr, "[E::%s] invalid BCF2 magic string\n", __func__);
bcf_hdr_destroy(h);
return 0;
}
int hlen;
char *htxt;
bgzf_read(fp, &hlen, 4);
htxt = (char*)malloc(hlen);
bgzf_read(fp, htxt, hlen);
bcf_hdr_parse(h, htxt);
free(htxt);
return h;
}
int bcf_hdr_write(htsFile *hfp, bcf_hdr_t *h)
{
if ( h->dirty ) bcf_hdr_sync(h);
if (hfp->format.format == vcf || hfp->format.format == text_format)
return vcf_hdr_write(hfp, h);
int hlen;
char *htxt = bcf_hdr_fmt_text(h, 1, &hlen);
hlen++; // include the \0 byte
BGZF *fp = hfp->fp.bgzf;
if ( bgzf_write(fp, "BCF\2\2", 5) !=5 ) return -1;
if ( bgzf_write(fp, &hlen, 4) !=4 ) return -1;
if ( bgzf_write(fp, htxt, hlen) != hlen ) return -1;
free(htxt);
return 0;
}
/********************
*** BCF site I/O ***
********************/
bcf1_t *bcf_init1()
{
bcf1_t *v;
v = (bcf1_t*)calloc(1, sizeof(bcf1_t));
return v;
}
void bcf_clear(bcf1_t *v)
{
int i;
for (i=0; i<v->d.m_info; i++)
{
if ( v->d.info[i].vptr_free )
{
free(v->d.info[i].vptr - v->d.info[i].vptr_off);
v->d.info[i].vptr_free = 0;
}
}
for (i=0; i<v->d.m_fmt; i++)
{
if ( v->d.fmt[i].p_free )
{
free(v->d.fmt[i].p - v->d.fmt[i].p_off);
v->d.fmt[i].p_free = 0;
}
}
v->rid = v->pos = v->rlen = v->unpacked = 0;
bcf_float_set_missing(v->qual);
v->n_info = v->n_allele = v->n_fmt = v->n_sample = 0;
v->shared.l = v->indiv.l = 0;
v->d.var_type = -1;
v->d.shared_dirty = 0;
v->d.indiv_dirty = 0;
v->d.n_flt = 0;
v->errcode = 0;
if (v->d.m_als) v->d.als[0] = 0;
if (v->d.m_id) v->d.id[0] = 0;
}
void bcf_empty1(bcf1_t *v)
{
bcf_clear1(v);
free(v->d.id);
free(v->d.als);
free(v->d.allele); free(v->d.flt); free(v->d.info); free(v->d.fmt);
if (v->d.var ) free(v->d.var);
free(v->shared.s); free(v->indiv.s);
}
void bcf_destroy1(bcf1_t *v)
{
bcf_empty1(v);
free(v);
}
static inline int bcf_read1_core(BGZF *fp, bcf1_t *v)
{
uint32_t x[8];
int ret;
if ((ret = bgzf_read(fp, x, 32)) != 32) {
if (ret == 0) return -1;
return -2;
}
bcf_clear1(v);
x[0] -= 24; // to exclude six 32-bit integers
ks_resize(&v->shared, x[0]);
ks_resize(&v->indiv, x[1]);
memcpy(v, x + 2, 16);
v->n_allele = x[6]>>16; v->n_info = x[6]&0xffff;
v->n_fmt = x[7]>>24; v->n_sample = x[7]&0xffffff;
v->shared.l = x[0], v->indiv.l = x[1];
// silent fix of broken BCFs produced by earlier versions of bcf_subset, prior to and including bd6ed8b4
if ( (!v->indiv.l || !v->n_sample) && v->n_fmt ) v->n_fmt = 0;
bgzf_read(fp, v->shared.s, v->shared.l);
bgzf_read(fp, v->indiv.s, v->indiv.l);
return 0;
}
#define bit_array_size(n) ((n)/8+1)
#define bit_array_set(a,i) ((a)[(i)/8] |= 1 << ((i)%8))
#define bit_array_clear(a,i) ((a)[(i)/8] &= ~(1 << ((i)%8)))
#define bit_array_test(a,i) ((a)[(i)/8] & (1 << ((i)%8)))
static inline uint8_t *bcf_unpack_fmt_core1(uint8_t *ptr, int n_sample, bcf_fmt_t *fmt);
int bcf_subset_format(const bcf_hdr_t *hdr, bcf1_t *rec)
{
if ( !hdr->keep_samples ) return 0;
if ( !bcf_hdr_nsamples(hdr) )
{
rec->indiv.l = rec->n_sample = 0;
return 0;
}
int i, j;
uint8_t *ptr = (uint8_t*)rec->indiv.s, *dst = NULL, *src;
bcf_dec_t *dec = &rec->d;
hts_expand(bcf_fmt_t, rec->n_fmt, dec->m_fmt, dec->fmt);
for (i=0; i<dec->m_fmt; ++i) dec->fmt[i].p_free = 0;
for (i=0; i<rec->n_fmt; i++)
{
ptr = bcf_unpack_fmt_core1(ptr, rec->n_sample, &dec->fmt[i]);
src = dec->fmt[i].p - dec->fmt[i].size;
if ( dst )
{
memmove(dec->fmt[i-1].p + dec->fmt[i-1].p_len, dec->fmt[i].p - dec->fmt[i].p_off, dec->fmt[i].p_off);
dec->fmt[i].p = dec->fmt[i-1].p + dec->fmt[i-1].p_len + dec->fmt[i].p_off;
}
dst = dec->fmt[i].p;
for (j=0; j<hdr->nsamples_ori; j++)
{
src += dec->fmt[i].size;
if ( !bit_array_test(hdr->keep_samples,j) ) continue;
memmove(dst, src, dec->fmt[i].size);
dst += dec->fmt[i].size;
}
rec->indiv.l -= dec->fmt[i].p_len - (dst - dec->fmt[i].p);
dec->fmt[i].p_len = dst - dec->fmt[i].p;
}
rec->unpacked |= BCF_UN_FMT;
rec->n_sample = bcf_hdr_nsamples(hdr);
return 0;
}
int bcf_read(htsFile *fp, const bcf_hdr_t *h, bcf1_t *v)
{
if (fp->format.format == vcf) return vcf_read(fp,h,v);
int ret = bcf_read1_core(fp->fp.bgzf, v);
if ( ret!=0 || !h->keep_samples ) return ret;
return bcf_subset_format(h,v);
}
int bcf_readrec(BGZF *fp, void *null, void *vv, int *tid, int *beg, int *end)
{
bcf1_t *v = (bcf1_t *) vv;
int ret;
if ((ret = bcf_read1_core(fp, v)) >= 0)
*tid = v->rid, *beg = v->pos, *end = v->pos + v->rlen;
return ret;
}
static inline void bcf1_sync_id(bcf1_t *line, kstring_t *str)
{
// single typed string
if ( line->d.id && strcmp(line->d.id, ".") ) bcf_enc_vchar(str, strlen(line->d.id), line->d.id);
else bcf_enc_size(str, 0, BCF_BT_CHAR);
}
static inline void bcf1_sync_alleles(bcf1_t *line, kstring_t *str)
{
// list of typed strings
int i;
for (i=0; i<line->n_allele; i++)
bcf_enc_vchar(str, strlen(line->d.allele[i]), line->d.allele[i]);
if ( !line->rlen && line->n_allele ) line->rlen = strlen(line->d.allele[0]);
}
static inline void bcf1_sync_filter(bcf1_t *line, kstring_t *str)
{
// typed vector of integers
if ( line->d.n_flt ) bcf_enc_vint(str, line->d.n_flt, line->d.flt, -1);
else bcf_enc_vint(str, 0, 0, -1);
}
static inline void bcf1_sync_info(bcf1_t *line, kstring_t *str)
{
// pairs of typed vectors
int i, irm = -1;
for (i=0; i<line->n_info; i++)
{
bcf_info_t *info = &line->d.info[i];
if ( !info->vptr )
{
// marked for removal
if ( irm < 0 ) irm = i;
continue;
}
kputsn_(info->vptr - info->vptr_off, info->vptr_len + info->vptr_off, str);
if ( irm >=0 )
{
bcf_info_t tmp = line->d.info[irm]; line->d.info[irm] = line->d.info[i]; line->d.info[i] = tmp;
while ( irm<=i && line->d.info[irm].vptr ) irm++;
}
}
if ( irm>=0 ) line->n_info = irm;
}
static int bcf1_sync(bcf1_t *line)
{
char *shared_ori = line->shared.s;
size_t prev_len;
kstring_t tmp = {0,0,0};