-
Notifications
You must be signed in to change notification settings - Fork 3
/
vcfpp.h
1958 lines (1803 loc) · 62.2 KB
/
vcfpp.h
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
/*******************************************************************************
* @file https://github.com/Zilong-Li/vcfpp/vcfpp.h
* @author Zilong Li
* @email zilong.dk@gmail.com
* @version v0.6.0
* @breif a single C++ file for manipulating VCF
* Copyright (C) 2022-2023.The use of this code is governed by the LICENSE file.
******************************************************************************/
/*! \mainpage The documentation of the single C++ file *vcfpp.h* for manipulating VCF/BCF
*
* \section intro_sec Introduction
*
* This project https://github.com/Zilong-Li/vcfpp introduces a single C++ file as interface to the basic
* htslib, which can be easily included in a C++ program for scripting high-performance genomic analyses.
*
* - vcfpp.BcfHeader keeps track of the header information in VCF/BCF
* - vcfpp.BcfRecord keeps track of the variants information in VCF/BCF
* - vcfpp.BcfReader streams in variants from VCF/BCF file or stdin
* - vcfpp.BcfWriter streams out variants to VCF/BCF file or stdout
*
* \section install_sec Installation
*
* - <EM> include "vcfpp.h" </EM> to your program and compile it by <EM> g++ my.cpp -std=c++11 -Wall -I. -lhts
* - </EM>
* - make sure you have https://github.com/samtools/htslib installed on your system and the it is in your
* environment.
*
*
* \copyright Copyright (C) 2022 Zilong Li . This project is governed by the LICENSE file in
* https://github.com/Zilong-Li/vcfpp.
*
*
*/
#pragma once
#include <cstddef>
#include <stdexcept>
#ifndef VCFPP_H_
# define VCFPP_H_
# include <iostream>
# include <memory>
# include <string>
# include <type_traits>
# include <vector>
// make sure you have htslib installed
extern "C"
{
# include <htslib/hts.h>
# include <htslib/kstring.h>
# include <htslib/tbx.h>
# include <htslib/vcf.h>
# include <htslib/vcfutils.h>
}
namespace vcfpp
{
template<typename T>
using isValidFMT =
typename std::enable_if<std::is_same<T, std::string>::value || std::is_same<T, std::vector<char>>::value
|| std::is_same<T, std::vector<int>>::value
|| std::is_same<T, std::vector<float>>::value,
bool>::type;
template<typename T>
using isValidInfo =
typename std::enable_if<std::is_same<T, std::string>::value || std::is_same<T, std::vector<int>>::value
|| std::is_same<T, std::vector<float>>::value,
bool>::type;
template<typename T>
using isInfoVector = typename std::enable_if<std::is_same<T, std::vector<int>>::value
|| std::is_same<T, std::vector<float>>::value,
bool>::type;
template<typename T>
using isScalar = typename std::enable_if<std::is_same<T, int>::value || std::is_same<T, float>::value
|| std::is_same<T, double>::value,
bool>::type;
template<typename T>
using isString = typename std::enable_if<std::is_same<T, std::string>::value, bool>::type;
template<typename T>
using isValidGT = typename std::enable_if<std::is_same<T, std::vector<bool>>::value
|| std::is_same<T, std::vector<char>>::value,
bool>::type;
template<typename T>
using isFormatVector = typename std::enable_if<std::is_same<T, std::vector<float>>::value
|| std::is_same<T, std::vector<char>>::value
|| std::is_same<T, std::vector<int>>::value,
bool>::type;
namespace details
{
template<typename T>
isScalar<T> isMissing(T const & v)
{
if(std::is_same<T, float>::value)
{
return bcf_float_is_missing(v);
}
else if(std::is_same<T, int>::value)
{
return bcf_int32_missing(v);
}
}
// test if a string is end with another string
inline bool isEndWith(std::string const & s, std::string const & e)
{
if(s.length() >= e.length())
{
return (0 == s.compare(s.length() - e.length(), e.length(), e));
}
else
{
return false;
}
}
// determinate the mode for read/write the compressed/uncompressed VCF/BCF
inline std::string getMode(std::string const & fname, std::string mode = "r")
{
if(isEndWith(fname, "bcf.gz")) mode += "b";
if(isEndWith(fname, "bcf")) mode += "bu";
if(isEndWith(fname, "vcf.gz")) mode += "z";
return mode;
}
// string split by separator
inline std::vector<std::string> split_string(const std::string & s, const std::string & separators)
{
std::vector<std::string> ret;
bool is_seperator[256] = {false};
for(auto & ch : separators)
{
is_seperator[(unsigned int)ch] = true;
}
int begin = 0;
for(int i = 0; i <= (int)s.size(); i++)
{
if(is_seperator[(uint8_t)s[i]] || i == (int)s.size())
{
ret.push_back(std::string(s.begin() + begin, s.begin() + i));
begin = i + 1;
}
}
return ret;
}
// deleter for htsFile
struct hts_file_close
{
void operator()(htsFile * x)
{
if(x) hts_close(x);
}
};
// deleter for hts iterator
struct hts_iter_close
{
void operator()(hts_itr_t * x)
{
if(x) hts_itr_destroy(x);
}
};
// deleter for hts idx
struct hts_idx_close
{
void operator()(hts_idx_t * x)
{
if(x) hts_idx_destroy(x);
}
};
// deleter for tabix idx
struct tabix_idx_close
{
void operator()(tbx_t * x)
{
if(x) tbx_destroy(x);
}
};
// deleter for variant
struct bcf_line_close
{
void operator()(bcf1_t * x)
{
if(x) bcf_destroy(x);
}
};
// deleter for bcf header
struct bcf_hdr_close
{
void operator()(bcf_hdr_t * x)
{
if(x) bcf_hdr_destroy(x);
}
};
} // namespace details
/**
* @class BcfHeader
* @brief Object represents header of the VCF, offering methods to access and modify the tags
* @note BcfHeader has 3 friends, BcfReader, BcfWriter and BcfRecord.
**/
class BcfHeader
{
friend class BcfRecord;
friend class BcfReader;
friend class BcfWriter;
private:
bcf_hdr_t * hdr = NULL; // bcf header
bcf_hrec_t * hrec = NULL; // populate header
public:
BcfHeader() {}
~BcfHeader()
{
if(hrec) bcf_hrec_destroy(hrec);
if(hdr) bcf_hdr_destroy(hdr);
}
/** @brief stream out the header */
friend std::ostream & operator<<(std::ostream & out, const BcfHeader & h)
{
out << h.asString();
return out;
}
// TODO: check if the value is valid for vcf specification
/** @brief add INFO field to header
* @param id tag name in INFO field
* @param number Number of elements
* @param type Integer, Floast or String
* @param description Description of the tag
* */
inline void addINFO(const std::string & id,
const std::string & number,
const std::string & type,
const std::string & description)
{
addLine("##INFO=<ID=" + id + ",Number=" + number + ",Type=" + type + ",Description=\"" + description
+ "\">");
}
/** @brief add FORMAT field to header
* @param id tag name in FORMAT field
* @param number Number of elements
* @param type Integer, Floast or String
* @param description Description of the tag
* */
inline void addFORMAT(const std::string & id,
const std::string & number,
const std::string & type,
const std::string & description)
{
addLine("##FORMAT=<ID=" + id + ",Number=" + number + ",Type=" + type + ",Description=\"" + description
+ "\">");
}
/**
* @brief add one FILTER line to header
* @param id FILTER name
* @param description Description of the FILTER
* */
inline void addFILTER(const std::string & id, const std::string & description)
{
addLine("##FILTER=<ID=" + id + ",Description=\"" + description + "\">");
}
/** @brief add contig to header
* @param id contig or chromosome name
* */
inline void addContig(const std::string & id)
{
addLine("##contig=<ID=" + id + ">");
}
/**
* @brief add one line to header
* */
inline void addLine(const std::string & str)
{
int ret = 0;
ret = bcf_hdr_append(hdr, str.c_str());
if(ret != 0) throw std::runtime_error("could not add " + str + " to header\n");
ret = bcf_hdr_sync(hdr);
if(ret != 0) throw std::runtime_error("could not add " + str + " to header\n");
}
/** @brief add one sample name to header */
inline void addSample(const std::string & sample) const
{
bcf_hdr_add_sample(hdr, sample.c_str());
if(bcf_hdr_sync(hdr) != 0)
{
throw std::runtime_error("couldn't add the sample.\n");
}
}
/** @brief return header as a string */
inline std::string asString() const
{
kstring_t s = {0, 0, NULL}; // kstring
if(bcf_hdr_format(hdr, 0, &s) == 0) // append header string to s.s! append!
{
std::string out(s.s, s.l);
free(s.s);
return out;
}
else
{
throw std::runtime_error("failed to convert formatted header to string");
}
}
/** @brief return all samples in a string vector */
std::vector<std::string> getSamples() const
{
std::vector<std::string> vec;
for(int i = 0; i < bcf_hdr_nsamples(hdr); i++)
{
vec.push_back(std::string(hdr->samples[i]));
}
return vec;
}
/** @brief return all contig/chromosome names in a string vector */
std::vector<std::string> getSeqnames() const
{
int ret = 0;
const char ** seqs = bcf_hdr_seqnames(hdr, &ret);
if(ret == 0) printf("there is no contig id in the header!\n");
std::vector<std::string> vec;
for(int i = 0; i < ret; i++)
{
vec.push_back(std::string(seqs[i]));
}
free(seqs);
return vec;
}
/**
* @brief get the type of a given tag
* @param tag in the FORMAT
* @return 1: int; 2: float; 3: string; 0: error;
*/
inline int getFormatType(std::string tag) const
{
int tag_id = bcf_hdr_id2int(hdr, BCF_DT_ID, tag.c_str());
if(tag_id < 0) return 0;
if(bcf_hdr_id2type(hdr, BCF_HL_FMT, tag_id) == (BCF_HT_INT & 0xff))
{
return 1;
}
else if(bcf_hdr_id2type(hdr, BCF_HL_FMT, tag_id) == (BCF_HT_REAL & 0xff))
{
return 2;
}
else if(bcf_hdr_id2type(hdr, BCF_HL_FMT, tag_id) == (BCF_HT_STR & 0xff))
{
return 3;
}
else
{
return 0;
}
}
/** @brief remove a contig tag from header */
inline void removeContig(std::string tag) const
{
bcf_hdr_remove(hdr, BCF_HL_CTG, tag.c_str());
}
/** @brief remove a INFO tag from header */
inline void removeInfo(std::string tag) const
{
bcf_hdr_remove(hdr, BCF_HL_INFO, tag.c_str());
}
/** @brief remove a FORMAT tag from header */
inline void removeFormat(std::string tag) const
{
bcf_hdr_remove(hdr, BCF_HL_FMT, tag.c_str());
}
/** @brief remove a FILTER tag from header */
inline void removeFilter(std::string tag) const
{
bcf_hdr_remove(hdr, BCF_HL_FLT, tag.c_str());
}
/**
* @brief update the sample id in the header
* @param samples a comma-separated string for multiple new samples
* @note this only update the samples name in a given sequential order
* */
void updateSamples(const std::string & samples)
{
auto ss = details::split_string(samples, ",");
const int nsamples = nSamples();
if(nsamples != (int)ss.size())
throw std::runtime_error("You provide either too few or too many samples");
kstring_t htxt = {0, 0, 0};
bcf_hdr_format(hdr, 1, &htxt);
// Find the beginning of the #CHROM line
int i = htxt.l - 2, ncols = 0;
while(i >= 0 && htxt.s[i] != '\n')
{
if(htxt.s[i] == '\t') ncols++;
i--;
}
if(i < 0 || strncmp(htxt.s + i + 1, "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT", 45))
{
if(i > 0 && !strncmp(htxt.s + i + 1, "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO", 38))
throw std::runtime_error("Error: missing FORMAT fields, cowardly refusing to add samples\n");
throw std::runtime_error("Could not parse the header: " + std::string(htxt.s));
}
ncols = 0;
while(ncols != 9)
{
i++;
if(htxt.s[i] == '\t') ncols++;
}
htxt.l = i;
// Replace all samples
for(i = 0; i < nsamples; i++)
{
kputc('\t', &htxt);
kputs(ss[i].c_str(), &htxt);
}
kputc('\n', &htxt);
// destroy the old and make new header
bcf_hdr_destroy(hdr);
hdr = bcf_hdr_init("r");
if(bcf_hdr_parse(hdr, htxt.s) < 0)
throw std::runtime_error("An error occurred while parsing the header\n");
// free everything
free(htxt.s);
}
/**
* @brief explicitly set samples to be extracted
* @param samples samples to include or exclude as a comma-separated string
* */
inline void setSamples(const std::string & samples) const
{
int ret = 0;
ret = bcf_hdr_set_samples(hdr, samples.c_str(), 0);
if(ret != 0)
{
throw std::runtime_error("the " + std::to_string(ret)
+ "-th sample are not in the VCF.\nparameter samples:" + samples);
}
}
/** @brief set the VCF version */
inline void setVersion(const std::string & version) const
{
bcf_hdr_set_version(hdr, version.c_str());
}
/** @brief return the number of samples in the VCF */
inline int nSamples() const
{
return bcf_hdr_nsamples(hdr);
}
};
/**
* @class BcfRecord
* @brief Object represents a variant record in the VCF, offering methods to access and modify fields.
* @note BcfRecord has to be associated with a BcfHeader object and needs to be filled in by calling
*BcfReader.getNextVariant function.
**/
class BcfRecord
{
friend class BcfReader;
friend class BcfWriter;
private:
BcfHeader * header;
std::shared_ptr<bcf1_t> line = std::shared_ptr<bcf1_t>(bcf_init(), details::bcf_line_close()); // variant
bcf_hdr_t * hdr_d = NULL; // a dup header by bcf_hdr_dup(header->hdr)
bcf_fmt_t * fmt = NULL;
bcf_info_t * info = NULL;
int32_t * gts = NULL;
int ndst, ret, nsamples;
bool noneMissing = true; // whenever parsing a tag have to reset this variable
bool isAllPhased = false;
int nploidy = 0; // the number of ploidy
int nvalues = 0; // the number of values for a tag in FORMAT
public:
/// if there is "." in GT for the sample, then it's coded as missing (TRUE)
std::vector<char> isGenoMissing;
public:
/// empty constructor. call init() afterwards
BcfRecord() {}
/// constructor with a given BcfHeader object
BcfRecord(BcfHeader & h)
{
initHeader(h);
}
~BcfRecord()
{
if(gts) free(gts);
if(hdr_d) bcf_hdr_destroy(hdr_d);
}
/// initilize the header associated with BcfRecord object by pointing to another BcfHeader object
void initHeader(BcfHeader & h)
{
header = &h;
if(!header->hdr) throw std::runtime_error("please initial header first\n");
nsamples = header->nSamples();
typeOfGT.resize(nsamples);
gtPhase.resize(nsamples, 0);
}
/// reset the header associated with BcfRecord object by pointing to another BcfHeader object
void resetHeader(BcfHeader & h)
{
header = &h;
}
/** @brief stream out the variant */
friend std::ostream & operator<<(std::ostream & out, const BcfRecord & v)
{
out << v.asString();
return out;
}
/** @brief return current variant as raw string */
inline std::string asString() const
{
kstring_t s = {0, 0, NULL}; // kstring
if(vcf_format(header->hdr, line.get(), &s) == 0)
{
std::string out(s.s, s.l);
free(s.s);
return out;
}
else
{
throw std::runtime_error("couldn't format current record into a string.\n");
}
}
/**
* @brief fill in the input vector with genotypes of 0 and 1. only works for ploidy<=2. Genotypes with
* missing allele is coded as heterozygous
* @param v valid input includes vector<bool> and vector<char> type
* @return bool
* @note use isNoneMissing() to check if all genotypes are with no missingness. Alternatively, one can
* use vector<int> as the input type as noted in the other overloading function getGenotypes().
* */
template<typename T>
isValidGT<T> getGenotypes(T & v)
{
ndst = 0;
ret = bcf_get_genotypes(header->hdr, line.get(), >s, &ndst);
if(ret <= 0)
{
# if defined(VERBOSE)
std::cerr << "GT not present for current site. did you initilize the variant object?\n";
# endif
return false;
}
// if nploidy is not set manually. find the max nploidy using the first variant (eg. 2) resize v as
// max(nploidy)
// * nsamples (ret) NOTE: if ret == nsamples and only one sample then haploid
if(ret != nploidy * nsamples && nploidy > 0)
{
// rare case if nploidy is set manually. eg. only one sample. the first variant is '1' but the
// second is '1/0'. ret = 1 but nploidy should be 2
v.resize(nploidy * nsamples);
}
else
{
v.resize(ret);
nploidy = ret / nsamples;
}
// work with nploidy == 1, haploid?
isGenoMissing.assign(nsamples, 0);
int i, j, nphased = 0;
noneMissing = true;
fmt = bcf_get_fmt(header->hdr, line.get(), "GT");
int nploidy_cur = ret / nsamples; // requires nploidy_cur <= nploidy
for(i = 0; i < nsamples; i++)
{
// check and fill in typeOfGT; only supports SNPs now. check vcfstats.c for inspiration
typeOfGT[i] = bcf_gt_type(fmt, i, NULL, NULL);
if(typeOfGT[i] == GT_UNKN)
{
noneMissing = false; // set missing as het, user should check if isNoneMissing();
isGenoMissing[i] = 1;
v[i * nploidy + 0] = 1;
for(j = 1; j < nploidy_cur; j++) v[i * nploidy + j] = 0;
continue;
}
for(j = 0; j < nploidy_cur; j++)
{
// TODO: right now only parse 0 and 1, ie max(nploidy)=2; other values 2,3... will be set to 1
v[i * nploidy + j] = bcf_gt_allele(gts[j + i * nploidy_cur]) != 0;
}
if(nploidy == 2)
{
gtPhase[i] = (gts[1 + i * nploidy_cur] & 1) == 1;
nphased += gtPhase[i];
}
}
if(nphased == nsamples)
{
isAllPhased = true;
}
else
{
isAllPhased = false;
}
return true;
}
/**
* @brief fill in the input vector with genotype values, 0, 1 or -9 (missing).
* @param v valid input is vector<int> type
* @return bool
* @note this function provides full capability to handle all kinds of genotypes
* in multi-ploidy data costing more spae than the other function. missing allele is set as -9.
* */
bool getGenotypes(std::vector<int> & v)
{
ndst = 0;
ret = bcf_get_genotypes(header->hdr, line.get(), >s, &ndst);
if(ret <= 0)
{
# if defined(VERBOSE)
std::cerr << "GT not present for current site. did you initilize the variant object?\n";
# endif
return false;
}
v.resize(ret);
isGenoMissing.assign(nsamples, 0);
nploidy = ret / nsamples;
int i, j, nphased = 0;
noneMissing = true;
for(i = 0; i < nsamples; i++)
{
int32_t * ptr = gts + i * nploidy;
int is_phased = 0;
for(j = 0; j < nploidy; j++)
{
// if true, the sample has smaller ploidy
if(ptr[j] == bcf_int32_vector_end) break;
// missing allele
if(bcf_gt_is_missing(ptr[j]))
{
noneMissing = false;
isGenoMissing[i] = 1;
v[i * nploidy + j] = -9;
continue;
}
v[i * nploidy + j] = bcf_gt_allele(ptr[j]);
is_phased += bcf_gt_is_phased(ptr[j]);
}
if(nploidy == is_phased)
{
gtPhase[i] = true;
nphased += gtPhase[i];
}
}
if(nphased == nsamples)
{
isAllPhased = true;
}
else
{
isAllPhased = false;
}
return true;
}
/**
* @brief get tag value in FORMAT
* @param tag valid tag name in FORMAT column declared in the VCF header
* @param v valid input include vector of float, char, int type
* @return bool
* */
template<typename T, typename S = typename T::value_type>
isFormatVector<T> getFORMAT(std::string tag, T & v)
{
fmt = bcf_get_fmt(header->hdr, line.get(), tag.c_str());
if(!fmt)
{
throw std::invalid_argument("no FORMAT=" + tag + " in the VCF header.\n");
}
nvalues = fmt->n;
ndst = 0;
S * dst = NULL;
int tagid = header->getFormatType(tag);
if(tagid == 1)
{
ret = bcf_get_format_int32(header->hdr, line.get(), tag.c_str(), &dst, &ndst);
}
else if(tagid == 2)
{
ret = bcf_get_format_float(header->hdr, line.get(), tag.c_str(), &dst, &ndst);
}
else if(tagid == 3)
{
ret = bcf_get_format_char(header->hdr, line.get(), tag.c_str(), &dst, &ndst);
}
else
{
ret = -1;
}
if(ret >= 0)
{
// user have to check if there is missing in the return v;
v = std::vector<S>(dst, dst + ret);
free(dst);
return true;
}
else
{
free(dst);
return false;
}
}
/**
* @brief get tag value in FORMAT
* @param tag valid tag name in FORMAT column declared in the VCF header
* @param v vector of string
* @return bool
* */
bool getFORMAT(std::string tag, std::vector<std::string> & v)
{
fmt = bcf_get_fmt(header->hdr, line.get(), tag.c_str());
if(!fmt)
{
throw std::invalid_argument("no FORMAT=" + tag + " in the VCF header.\n");
}
nvalues = fmt->n;
// if ndst < (fmt->n+1)*nsmpl; then realloc is involved
ret = -1, ndst = 0;
char ** dst = NULL;
if(header->getFormatType(tag) == 3)
ret = bcf_get_format_string(header->hdr, line.get(), tag.c_str(), &dst, &ndst);
if(ret > 0)
{
v.clear();
for(int i = 0; i < nsamples; i++)
{
// Ugly: GT field is considered to be a string by the VCF header but BCF represents it as INT.
v.emplace_back(dst[i]);
};
free(dst[0]);
free(dst);
return true;
}
else
{
free(dst[0]);
free(dst);
return false;
}
}
/**
* @brief get tag value in INFO
* @param tag valid tag name in INFO column declared in the VCF header
* @param v valid input include vector of float, int type
* @return bool
* */
template<typename T, typename S = typename T::value_type>
isInfoVector<T> getINFO(std::string tag, T & v)
{
info = bcf_get_info(header->hdr, line.get(), tag.c_str());
if(!info)
{
throw std::invalid_argument("no INFO=" + tag + " in the VCF header.\n");
}
S * dst = NULL;
ndst = 0;
ret = -1;
if(info->type == BCF_BT_INT8 || info->type == BCF_BT_INT16 || info->type == BCF_BT_INT32)
{
ret = bcf_get_info_int32(header->hdr, line.get(), tag.c_str(), &dst, &ndst);
}
else if(info->type == BCF_BT_FLOAT)
{
ret = bcf_get_info_float(header->hdr, line.get(), tag.c_str(), &dst, &ndst);
}
if(ret >= 0)
{
v = std::vector<S>(dst, dst + ret); // user have to check if there is missing in the return v;
free(dst);
return true;
}
else
{
free(dst);
return false;
}
}
/**
* @brief get tag value in INFO
* @param tag valid tag name in INFO column declared in the VCF header
* @param v valid input include scalar value of float or int type
* @return bool
* */
template<typename T>
isScalar<T> getINFO(std::string tag, T & v)
{
info = bcf_get_info(header->hdr, line.get(), tag.c_str());
if(!info)
{
throw std::invalid_argument("no INFO=" + tag + " in the VCF header.\n");
}
// scalar value
if(info->len == 1)
{
if(info->type == BCF_BT_INT8 || info->type == BCF_BT_INT16 || info->type == BCF_BT_INT32)
{
v = info->v1.i;
}
else if(info->type == BCF_BT_FLOAT)
{
v = info->v1.f;
}
return true;
}
else
{
# if defined(VERBOSE)
std::cerr << "there are multiple values for " + tag
+ " in INFO for current site. please use vector instead\n";
# endif
return false;
}
}
/**
* @brief get tag value in INFO
* @param tag valid tag name in INFO column declared in the VCF header
* @param v valid input is std::string
* @return bool
* */
template<typename T>
isString<T> getINFO(std::string tag, T & v)
{
info = bcf_get_info(header->hdr, line.get(), tag.c_str());
if(!info)
{
throw std::invalid_argument("no INFO=" + tag + " in the VCF header.\n");
}
if(info->type == BCF_BT_CHAR)
{
v = std::string(reinterpret_cast<char *>(info->vptr), info->vptr_len);
return true;
}
else
{
return false;
}
}
/**
* @brief set tag value for INFO
* @param tag valid tag name in INFO column declared in the VCF header
* @param v valid input include scalar value of float or int type
* @return bool
* */
template<typename T>
isScalar<T> setINFO(std::string tag, const T & v)
{
// bcf_hrec_set_val
// bcf_update_info_flag(header.hdr, line, tag.c_str(), NULL, 1);
int tag_id = bcf_hdr_id2int(header->hdr, BCF_DT_ID, tag.c_str());
if(bcf_hdr_id2type(header->hdr, BCF_HL_INFO, tag_id) == (BCF_HT_INT & 0xff))
{
ret = bcf_update_info_int32(header->hdr, line.get(), tag.c_str(), &v, 1);
}
else if(bcf_hdr_id2type(header->hdr, BCF_HL_INFO, tag_id) == (BCF_HT_REAL & 0xff))
{
float v2 = static_cast<float>(v);
ret = bcf_update_info_float(header->hdr, line.get(), tag.c_str(), &v2, 1);
}
else
{
ret = -1;
}
if(ret < 0)
{
# if defined(VERBOSE)
std::cerr << "couldn't set " + tag + " for this variant.\nplease add the tag in headerfirst.\n";
# endif
return false;
}
return true;
}
/**
* @brief set tag value for INFO
* @param tag valid tag name in INFO column declared in the VCF header
* @param v valid input include vector<int> vector<float> std::string
* @return bool
* */
template<typename T>
isValidInfo<T> setINFO(std::string tag, const T & v)
{
// bcf_update_info_flag(header.hdr, line, tag.c_str(), NULL, 1);
int tag_id = bcf_hdr_id2int(header->hdr, BCF_DT_ID, tag.c_str());
if(bcf_hdr_id2type(header->hdr, BCF_HL_INFO, tag_id) == (BCF_HT_INT & 0xff))
{
ret = bcf_update_info_int32(header->hdr, line.get(), tag.c_str(), v.data(), v.size());
}
else if(bcf_hdr_id2type(header->hdr, BCF_HL_INFO, tag_id) == (BCF_HT_REAL & 0xff))
{
ret = bcf_update_info_float(header->hdr, line.get(), tag.c_str(), v.data(), v.size());
}
else if(bcf_hdr_id2type(header->hdr, BCF_HL_INFO, tag_id) == (BCF_HT_STR & 0xff))
{
ret = bcf_update_info_string(header->hdr, line.get(), tag.c_str(), v.data());
}
else
{
ret = -1;
}
if(ret < 0)
{
# if defined(VERBOSE)
std::cerr << "couldn't set " + tag + " for this variant.\nplease add the tag in headerfirst.\n";
# endif
return false;
}
return true;
}
/// remove the given tag from INFO of the variant
void removeINFO(std::string tag)
{
int tag_id = bcf_hdr_id2int(header->hdr, BCF_DT_ID, tag.c_str());
if(bcf_hdr_id2type(header->hdr, BCF_HL_INFO, tag_id) == (BCF_HT_INT & 0xff))
{
ret = bcf_update_info_int32(header->hdr, line.get(), tag.c_str(), NULL, 0);
}
else if(bcf_hdr_id2type(header->hdr, BCF_HL_INFO, tag_id) == (BCF_HT_REAL & 0xff))
{
ret = bcf_update_info_float(header->hdr, line.get(), tag.c_str(), NULL, 0);
}
else if(bcf_hdr_id2type(header->hdr, BCF_HL_INFO, tag_id) == (BCF_HT_STR & 0xff))
{
ret = bcf_update_info_string(header->hdr, line.get(), tag.c_str(), NULL);
}
else
{
ret = -1;
}
if(ret < 0)
{
throw std::runtime_error("couldn't remove " + tag + " for this variant.\n");
}
}
/**
* @brief set genotypes from scratch even if genotypes not present
* @param v the genotypes of vector<int> type
* @return bool
* */
bool setGenotypes(const std::vector<int> & v)
{