-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpicovcf.hpp
2048 lines (1873 loc) · 83.9 KB
/
picovcf.hpp
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
#ifndef PICOVCF_HPP
#define PICOVCF_HPP
#include <array>
#include <cassert>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <iterator>
#include <limits>
#include <memory>
#include <ostream>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <fcntl.h>
#if VCF_GZ_SUPPORT
#include <zlib.h>
#endif
namespace picovcf {
// With these type sizes, we support up to 4 billion samples, and trillions of
// variants.
/** Represents the index of an individual or sample. */
using SampleT = uint32_t;
static constexpr size_t MAX_SAMPLES = std::numeric_limits<SampleT>::max() - 1;
static constexpr SampleT SAMPLE_INDEX_NOT_SET = std::numeric_limits<SampleT>::max();
/** Represents the index of a variant. */
using VariantT = uint64_t;
/** Pair of integers that define a range */
using RangePair = std::pair<VariantT, VariantT>;
/** Pair of integers that define a non-reference allele (mutation) value:
* variant row index and alt allele index (0-based, so 0 is the first
* non-reference allele value). */
using MutationPair = std::pair<VariantT, VariantT>;
/** When processing pairs of alleles, this is used for the second item for
* haploids */
static constexpr VariantT NOT_DIPLOID = std::numeric_limits<VariantT>::max();
/** Represents a missing allele value (e.g., "." in VCF nomenclature) */
static constexpr VariantT MISSING_VALUE = std::numeric_limits<VariantT>::max() - 1;
static constexpr size_t INTERNAL_VALUE_NOT_SET = std::numeric_limits<size_t>::max();
/** IGD can only store up to ploidy = 8 */
static constexpr size_t MAX_PLOIDY = 8;
/**
* Exception thrown when there is a problem reading the underlying file.
*/
class FileReadError : public std::runtime_error {
public:
explicit FileReadError(char const* const message)
: std::runtime_error(message) {}
};
/**
* Exception thrown when the VCF file is not well formed according to the spec.
*/
class MalformedFile : public std::runtime_error {
public:
explicit MalformedFile(char const* const message)
: std::runtime_error(message) {}
};
/**
* Exception thrown when the API is misused (bad arguments, using iterators
* incorrectly).
*/
class ApiMisuse : public std::runtime_error {
public:
explicit ApiMisuse(char const* const message)
: std::runtime_error(message) {}
};
#if FUZZING
#define PICOVCF_THROW_ERROR(excType, msgOp) \
do { \
std::cout << msgOp; \
exit(0); \
} while (0)
#define PICOVCF_ASSERT_OR_MALFORMED(condition, msgOp) \
do { \
if (!(condition)) { \
std::cout << msgOp; \
exit(0); \
} \
} while (0)
#else
#define PICOVCF_THROW_ERROR(excType, msgOp) \
do { \
std::stringstream _ssErrMsg; \
_ssErrMsg << msgOp; \
throw excType(_ssErrMsg.str().c_str()); \
} while (0)
#define PICOVCF_ASSERT_OR_MALFORMED(condition, msgOp) \
do { \
if (!(condition)) { \
std::stringstream _ssErrMsg; \
_ssErrMsg << msgOp; \
throw MalformedFile(_ssErrMsg.str().c_str()); \
} \
} while (0)
#endif
#define PICOVCF_RELEASE_ASSERT(condition) \
do { \
if (!(condition)) { \
std::cerr << "PICOVCF_RELEASE_ASSERT(" #condition ") failed at " << __FILE__ << ":" << __LINE__ \
<< std::endl; \
abort(); \
} \
} while (0)
#define PICOVCF_GOOD_OR_READ_ERROR(fstream, filename) \
do { \
if (!(fstream).good()) { \
PICOVCF_THROW_ERROR(FileReadError, "Failure to read input file " << (filename)); \
} \
} while (0)
#define PICOVCF_GOOD_OR_MALFORMED_FILE(fstream) \
do { \
if (!(fstream).good()) { \
PICOVCF_THROW_ERROR(MalformedFile, \
"Unexpected file error reading input file (position " << (fstream).tellg() << ")"); \
} \
} while (0)
#define PICOVCF_GOOD_OR_API_MISUSE(fstream) \
do { \
if (!(fstream).good()) { \
PICOVCF_THROW_ERROR(ApiMisuse, \
"File error when seeking to user-supplied location " << (fstream).tellg() << ")"); \
} \
} while (0)
// Divide by TO and take the ceiling. E.g., for converting bits to the number of
// bytes that will be needed to store those bits (ceiling because bits may not
// be divisible by 8).
template <typename T, size_t TO> inline T picovcf_div_ceiling(T value) { return (value + (TO - 1)) / TO; }
inline void picovcf_split(const std::string& theString, const char token, std::vector<std::string>& result) {
size_t position = 0;
do {
const size_t nextPosition = theString.find_first_of(token, position);
if (nextPosition == std::string::npos) {
result.push_back(theString.substr(position));
position = nextPosition;
} else {
result.push_back(theString.substr(position, nextPosition - position));
position = nextPosition + 1;
}
} while (position != std::string::npos);
}
inline std::string picovcf_getKey(const std::string& line, const size_t start) {
size_t position = line.find_first_of('=', start);
if (position != std::string::npos) {
return line.substr(start, position - start);
}
return {};
}
inline std::string picovcf_getValue(const std::string& line, const size_t start) {
size_t position = line.find_first_of('=', start);
if (position != std::string::npos) {
return line.substr(position + 1);
}
return {};
}
using FileOffset = std::pair<size_t, size_t>;
/**
* PRIVATE: File reader that reads a block at a time under-the-hood.
*/
class BufferedReader {
public:
BufferedReader(const std::string& filename, size_t bufferedByteCt)
: m_file(std::fopen(filename.c_str(), "rb")),
m_capacity(bufferedByteCt),
m_position(0) {
#if HAVE_POSIX_FADVISE
posix_fadvise(fileno(m_file), 0, 0, POSIX_FADV_SEQUENTIAL);
#endif
}
virtual ~BufferedReader() { fclose(m_file); }
virtual void seek(const FileOffset& offset) {
std::fseek(m_file, offset.first, SEEK_SET);
readBuffered();
}
virtual FileOffset tell() { return {std::ftell(m_file) - (m_buffer.size() - m_position), 0}; }
size_t readline(std::string& buffer) {
if (m_buffer.empty()) {
readBuffered();
}
if (m_buffer.empty()) {
buffer.resize(0);
return 0;
}
assert(m_position < m_buffer.size());
bool found = false;
size_t lineBytes = 0;
while (!found) {
const uint8_t* bufPtr = &m_buffer.data()[m_position];
const size_t bufAvail = m_buffer.size() - m_position;
char* p = (char*)memchr(bufPtr, '\n', bufAvail);
size_t bytesFound;
if (nullptr == p) {
bytesFound = bufAvail;
m_position = m_buffer.size();
} else {
assert(p <= (const char*)(m_buffer.data() + m_buffer.size()));
assert(*p == '\n');
bytesFound = p - (const char*)bufPtr;
m_position += (bytesFound + 1); // +1 to skip newline
found = true;
}
if (buffer.size() - lineBytes < bytesFound) {
buffer.resize(lineBytes + bytesFound);
}
std::memcpy(&((char*)buffer.c_str())[lineBytes], bufPtr, bytesFound);
lineBytes += bytesFound;
if (m_position == m_buffer.size()) {
if (!readBuffered()) {
found = true; // EOF
}
} else {
assert(m_position < m_buffer.size());
found = true;
}
}
buffer.resize(lineBytes);
return lineBytes;
}
virtual bool eof() {
if (m_buffer.empty()) {
readBuffered();
}
return std::feof(m_file) && (m_position == m_buffer.size());
}
virtual bool peek_eof() {
if (m_buffer.empty()) {
readBuffered();
}
if (m_position == m_buffer.size()) {
return readBuffered();
}
return false;
}
protected:
// Return false if EOF
virtual bool readBuffered() {
m_position = 0;
if (std::feof(m_file)) {
m_buffer.resize(0);
return false;
} else if (m_buffer.size() < m_capacity) {
m_buffer.clear();
m_buffer.resize(m_capacity);
}
size_t bytesRead = std::fread(m_buffer.data(), 1, m_buffer.size(), m_file);
if (std::ferror(m_file)) {
PICOVCF_THROW_ERROR(FileReadError, "Failed to read input file");
}
if (bytesRead < m_buffer.size()) {
m_buffer.resize(bytesRead);
}
return true;
}
FILE* m_file;
std::vector<uint8_t> m_buffer;
size_t m_capacity;
size_t m_position;
};
#if VCF_GZ_SUPPORT
/**
* PRIVATE: Buffered file reader that decompresses input via zlib.
*/
class ZBufferedReader : public BufferedReader {
public:
ZBufferedReader(const std::string& filename, size_t bufferedByteCt)
: BufferedReader(filename, bufferedByteCt),
m_compressed(bufferedByteCt),
m_lastFileRead(0) {
constexpr int GZIP = 31;
m_zlibStream.zalloc = Z_NULL;
m_zlibStream.zfree = Z_NULL;
m_zlibStream.opaque = Z_NULL;
m_zlibStream.avail_in = 0;
m_zlibStream.next_in = Z_NULL;
if (Z_OK != inflateInit2(&m_zlibStream, GZIP)) {
PICOVCF_THROW_ERROR(FileReadError, "Failed to init zlib stream.");
}
}
virtual ~ZBufferedReader() { inflateEnd(&m_zlibStream); }
void resetStream() { PICOVCF_RELEASE_ASSERT(Z_OK == inflateReset(&m_zlibStream)); }
// Seek is not a constant operation in .gz files. We could do something like
// the zran.c example from zlib, but I'd like to avoid that complexity unless
// we really need it. Generally, seeking around a VCF file is going to be
// slow, so avoid it!
void seek(const FileOffset& offset) override {
PICOVCF_RELEASE_ASSERT(offset.first % m_compressed.size() == 0);
std::fseek(m_file, 0, SEEK_SET);
resetStream();
for (size_t i = 0; i <= offset.first; i += m_compressed.size()) {
readBuffered();
}
PICOVCF_RELEASE_ASSERT(m_lastFileRead == offset.first);
m_position = offset.second;
}
FileOffset tell() override {
if (m_buffer.empty()) {
readBuffered();
}
// The file offset is the block that we decompressed, and we also provide
// the position within that block (_after_ decompression).
PICOVCF_RELEASE_ASSERT(m_lastFileRead % m_compressed.size() == 0);
return {m_lastFileRead, m_position};
}
bool eof() override {
if (m_buffer.empty()) {
readBuffered();
}
return std::feof(m_file) && (m_position == m_buffer.size());
}
bool peek_eof() override {
if (m_buffer.empty()) {
readBuffered();
}
if (m_position == m_buffer.size()) {
return readBuffered();
}
return false;
}
private:
static constexpr size_t EST_COMPRESSION_FACTOR = 20;
// Return false if EOF
bool readBuffered() override {
m_position = 0;
if (std::feof(m_file)) {
m_buffer.resize(0);
return false;
} else if (m_buffer.size() < m_capacity) {
m_buffer.clear();
m_buffer.resize(m_capacity);
}
const size_t bytesRead = zReadBuffered();
if (bytesRead < m_buffer.size()) {
m_buffer.resize(bytesRead);
}
return true;
}
// Read m_compressed.size() bytes from the file stream, and then decompress
// that into the regular buffer. This means that the regular buffer is now
// variable-sized, and will be as big as necessary to hold all of the
// uncompressed data from that block.
size_t zReadBuffered() {
m_buffer.clear();
m_buffer.resize(m_compressed.size() * EST_COMPRESSION_FACTOR);
m_lastFileRead = std::ftell(m_file);
m_zlibStream.avail_in = std::fread(m_compressed.data(), 1, m_compressed.size(), m_file);
if (std::ferror(m_file)) {
PICOVCF_THROW_ERROR(FileReadError, "Failed to read input file @ " << m_lastFileRead);
}
if (m_zlibStream.avail_in == 0)
return 0;
m_zlibStream.next_in = m_compressed.data();
size_t readOffset = 0;
// Consume all of our input data and decompress it, resizing our output
// buffer as necessary. Note this assumes that ALL the data is compressed,
// it does not support trailing data in the file that is uncompressed.
do {
PICOVCF_RELEASE_ASSERT(readOffset < m_buffer.size());
m_zlibStream.avail_out = (m_buffer.size() - readOffset);
m_zlibStream.next_out = (m_buffer.data() + readOffset);
const size_t startOut = m_zlibStream.avail_out;
int ret = inflate(&m_zlibStream, Z_NO_FLUSH);
if (ret == Z_STREAM_END) {
resetStream();
} else {
PICOVCF_ASSERT_OR_MALFORMED(ret == Z_OK, "inflate() error: " << ret);
}
const size_t have = startOut - m_zlibStream.avail_out;
readOffset += have;
if (m_zlibStream.avail_out == 0) {
m_buffer.resize(2 * m_buffer.size());
}
} while (m_zlibStream.avail_in > 0);
return readOffset;
}
std::vector<uint8_t> m_compressed;
size_t m_lastFileRead;
z_stream m_zlibStream;
};
#endif
// See if the current or next character we read will be EOF
inline bool picovcf_peek_eof(BufferedReader* instream) { return instream->eof() || instream->peek_eof(); }
inline bool isMutation(VariantT alleleIndex) { return (alleleIndex != MISSING_VALUE) && (alleleIndex != 0); }
/**
* Iterate over individuals' genotype data only (skipping other data).
*
* This is a common use-case that needs to be fast and incremental.
*/
class IndividualIteratorGT {
public:
/** The VCF diploid separator that indicates the data is phased */
static constexpr const char PHASED_SEPARATOR = '|';
/**
* Are there more individuals?
*
* @returns true If there is another individual -- if this returns false, then
* you cannot call getAlleles() (it will throw an exception).
*/
bool hasNext() const { return m_currentPosition != std::string::npos; }
/**
* Get the allele values associated with the current individual, and (by
* default) increment the iterator to the next individual.
*
* @param[out] allele1 The first (perhaps only) allele index, populated as an
* output parameter.
* @param[out] allele2 The second allele index, populated as an output
* parameter. Will be set to NOT_DIPLOID as appropriate.
* @param[in] moveNext Pass false to stay at the current individual; by
* default it will move to the next one.
* @returns true if the aleles are phased, false if they are not (or it is a
* haploid).
*/
bool getAlleles(VariantT& allele1, VariantT& allele2, bool moveNext = true) {
if (m_currentPosition == std::string::npos) {
PICOVCF_THROW_ERROR(ApiMisuse, "Iterator is at end of individuals");
}
size_t stopAt = m_currentLine.find_first_of(":\t\r", m_currentPosition);
size_t length = 0;
if (stopAt == std::string::npos) {
length = m_currentLine.size() - m_currentPosition;
} else {
length = stopAt - m_currentPosition;
}
// These are the two fast paths (haploid + diploid)
bool isPhased = true;
if (length == 1) {
allele1 = singleCharToVariantT(m_currentLine[m_currentPosition]);
allele2 = NOT_DIPLOID;
} else if (length == 3) {
allele1 = singleCharToVariantT(m_currentLine[m_currentPosition]);
allele2 = singleCharToVariantT(m_currentLine[m_currentPosition + 2]);
;
isPhased = m_currentLine[m_currentPosition + 1] == PHASED_SEPARATOR;
} else {
std::string alleles = m_currentLine.substr(m_currentPosition, length);
size_t splitPos = alleles.find_first_of("|/", 0);
PICOVCF_ASSERT_OR_MALFORMED(splitPos != std::string::npos,
"Invalid allele string: " << alleles << "\nAt line: " << m_currentLine);
char splitChar = alleles[splitPos];
std::vector<std::string> alleleStrings;
picovcf_split(alleles, splitChar, alleleStrings);
PICOVCF_ASSERT_OR_MALFORMED(alleleStrings.size() == 2,
"Invalid allele string: " << alleles << "\nAt line: " << m_currentLine);
allele1 = stringToVariantT(alleleStrings[0]);
allele2 = stringToVariantT(alleleStrings[1]);
isPhased = (splitChar == PHASED_SEPARATOR);
}
if (moveNext) {
next();
}
return isPhased;
}
/**
* Move this iterator to the next individual.
*/
void next() {
if (m_currentPosition == std::string::npos) {
PICOVCF_THROW_ERROR(ApiMisuse, "Iterator is at end of individuals");
}
m_individualIndex++;
m_currentPosition = m_currentLine.find_first_of('\t', m_currentPosition + 1);
if (m_currentPosition != std::string::npos) {
m_currentPosition++; // Move past separator.
}
}
private:
IndividualIteratorGT(const std::string& currentLine, const size_t currentPosition)
: m_currentLine(currentLine),
m_currentPosition(currentPosition),
m_individualIndex(0) {}
static inline VariantT singleCharToVariantT(char c) {
switch (c) {
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
case '.': return MISSING_VALUE;
}
PICOVCF_THROW_ERROR(MalformedFile, "Invalid allele value: " << c);
}
static inline VariantT stringToVariantT(const std::string& str) {
if (str == ".") {
return MISSING_VALUE;
}
char* endPtr = nullptr;
VariantT result = static_cast<uint32_t>(std::strtoull(str.c_str(), &endPtr, 10));
if (endPtr != (str.c_str() + str.size())) {
PICOVCF_THROW_ERROR(MalformedFile, "Invalid allele value: " << str);
}
return result;
}
// Position in the line of the first individual.
const std::string& m_currentLine;
size_t m_currentPosition;
// The 0-based index of the current individual.
SampleT m_individualIndex;
friend class VCFVariantView;
};
/**
* Pre-parsed information from a Variant, minus any individual data.
*/
struct VCFVariantInfo {
std::string chromosome;
size_t position;
std::string identifier;
std::string referenceAllele;
std::vector<std::string> alternativeAlleles;
double quality;
std::string filter;
std::unordered_map<std::string, std::string> information;
std::vector<std::string> format;
};
/**
* A subset of the VCF that has been rotated to go from sample (haplotype index)
* to variant/mutation, excluding samples that map to the reference allele.
*
* VCF is ordered by variant, making it easy to go from variant/mutation to a
* list of individuals/samples affected. This datastructure captures the inverse
* relationship: individuals/samples mapped to the variant/mutation.
*
* This data structure probably doesn't make much sense for diploid unphased
* datasets, since it is rotating per-sample (however, the resulting data could
* still be useful, if you iterate the samples in pairs and collect all
* mutations from both samples per pair).
*/
struct VCFRotatedWindow {
/** The variants associated with this window */
std::vector<VCFVariantInfo> parsedVariants;
/** The 0-based index of the first individual in the window */
size_t firstIndividual;
/** The map from individual (index 0 is firstIndividual) to sets
* of indexes into the parseVariants vector */
std::vector<std::set<MutationPair>> sampleToMutation;
/** The file position _after_ the last variant that was parsed - can be used
* as an "iterator" */
FileOffset posAfterLastVariant;
/** Is the data diploid */
bool isDiploid;
};
/**
* A class that lazily interprets the data for a single variant.
*
* This does not "parse" the whole row associated with the variant, it locates
* the positions of required fields and then parses those fields on demand. The
* individual genotype data is accessed through another lazy view (iterator).
*/
class VCFVariantView {
public:
/** Genotype format string identifier. */
static constexpr const char* const FORMAT_GT = "GT";
/**
* Parse and make a copy of the non-genotype data in this variant row. This
* can be expensive, especially without basicInfoOnly set, but does allow you
* to capture the information from this view and not lose it when you move to
* the next variant.
*
* @param[in] basicInfoOnly True by default, this only populates the
* chromosome, position, id, ref allele, and alt allele fields. Set to false
* to get the additional fields.
*/
inline VCFVariantInfo parseToVariantInfo(bool basicInfoOnly = true) {
VCFVariantInfo result = {this->getChrom(),
this->getPosition(),
this->getID(),
this->getRefAllele(),
this->getAltAlleles(),
std::numeric_limits<double>::quiet_NaN()};
if (!basicInfoOnly) {
result.quality = this->getQuality();
result.filter = this->getFilter();
result.information = this->getInfo();
result.format = this->getFormat();
}
return result;
}
/**
* Get the chromosome identifier.
* @returns String of the chromosome identifier.
*/
std::string getChrom() const { return m_currentLine.substr(0, m_nonGTPositions[POS_CHROM_END]); }
/**
* Get the genome position.
* @returns Integer of the genome position.
*/
size_t getPosition() const {
const size_t posSize = m_nonGTPositions[POS_POS_END] - m_nonGTPositions[POS_CHROM_END];
assert(posSize > 0);
std::string posStr = m_currentLine.substr(m_nonGTPositions[POS_CHROM_END] + 1, posSize - 1);
char* endPtr = nullptr;
auto result = static_cast<size_t>(strtoull(posStr.c_str(), &endPtr, 10));
if (endPtr != (posStr.c_str() + posStr.size())) {
PICOVCF_THROW_ERROR(MalformedFile, "Invalid position (cannot parse): " << posStr);
}
return result;
}
/**
* Get the ID for this variant.
* @returns String of the ID.
*/
std::string getID() const { return stringForPosition(POS_ID_END); }
/**
* Get the reference allele for this variant.
* @returns String of the reference allele.
*/
std::string getRefAllele() const { return stringForPosition(POS_REF_END); }
/**
* Get the alternative alleles for this variant.
* @returns Vector of strings for all the alternative alleles. The allele
* index associated with each individual can be used to lookup the actual
* allele in this vector.
*/
std::vector<std::string> getAltAlleles() const {
const std::string alleleStr = stringForPosition(POS_ALT_END);
// Optimize for a common case for genotype data.
if (alleleStr.size() == 1) {
if (alleleStr == ".") {
return {};
}
return {alleleStr};
}
std::vector<std::string> result;
picovcf_split(alleleStr, ',', result);
return result;
}
/**
* Get the quality value.
* @returns The numeric value for the quality.
*/
double getQuality() const {
std::string qualString = stringForPosition(POS_QUAL_END);
char* endPtr = nullptr;
double result = strtod(qualString.c_str(), &endPtr);
if (endPtr != (qualString.c_str() + qualString.size())) {
PICOVCF_THROW_ERROR(MalformedFile, "Invalid quality number (cannot parse): " << qualString);
}
return result;
}
/**
* Get the filter value.
* @returns The string value for the filter.
*/
std::string getFilter() const { return stringForPosition(POS_FILTER_END); }
/**
* Get the info key/value pairs.
* @returns The information as a map from key to value.
*/
std::unordered_map<std::string, std::string> getInfo() const {
std::string infoString = stringForPosition(POS_INFO_END);
std::vector<std::string> infoPairs;
picovcf_split(infoString, ';', infoPairs);
std::unordered_map<std::string, std::string> result;
for (auto pair : infoPairs) {
result.emplace(picovcf_getKey(pair, 0), picovcf_getValue(pair, 0));
}
return result;
}
/**
* @returns true if this VCF file contains genotype data.
*/
bool hasGenotypeData() const { return INTERNAL_VALUE_NOT_SET != m_nonGTPositions[POS_FORMAT_END]; }
/**
* Gets the list of formats.
*
* Enforces that "GT" must be the first FORMAT. If the resulting vector is
* empty then there is no FORMAT and thus there is no genotype data.
*
* @returns A vector the format strings.
*/
std::vector<std::string> getFormat() const {
if (!hasGenotypeData()) {
return {};
}
std::string formatString = stringForPosition(POS_FORMAT_END);
if (formatString.size() == 2) {
if (formatString != FORMAT_GT) {
PICOVCF_THROW_ERROR(MalformedFile, "The first item in FORMAT _must_ be " << FORMAT_GT);
}
return {formatString};
}
std::vector<std::string> result;
picovcf_split(formatString, ':', result);
if (result.empty() || result[0] != FORMAT_GT) {
PICOVCF_THROW_ERROR(MalformedFile, "The first item in FORMAT _must_ be " << FORMAT_GT);
}
return result;
}
/**
* Get an iterator for traversing over the individual genotype data.
* @returns An IndividualIteratorGT for efficiently accessing the genotype
* data.
*/
IndividualIteratorGT getIndividualIterator() const {
if (!hasGenotypeData()) {
PICOVCF_THROW_ERROR(ApiMisuse, "Cannot iterate individuals when there is no genotype data");
}
return IndividualIteratorGT(m_currentLine, m_nonGTPositions[POS_FORMAT_END] + 1);
}
// TODO we should have another (more general) iterator that can be used for
// non-GT data.
private:
enum {
POS_CHROM_END = 0,
POS_POS_END = 1,
POS_ID_END = 2,
POS_REF_END = 3,
POS_ALT_END = 4,
POS_QUAL_END = 5,
POS_FILTER_END = 6,
POS_INFO_END = 7,
POS_FORMAT_END = 8,
};
inline std::string stringForPosition(const size_t curEnd) const {
assert(curEnd > 0);
const size_t prevEnd = curEnd - 1;
const size_t strSize = m_nonGTPositions[curEnd] - m_nonGTPositions[prevEnd];
return m_currentLine.substr(m_nonGTPositions[prevEnd] + 1, strSize - 1);
}
void parseNonGenotypePositions() {
size_t position = 0;
for (size_t i = 0; i < m_nonGTPositions.size(); i++) {
position = m_currentLine.find_first_of("\t", position);
if (position == std::string::npos) {
if (i < REQUIRED_FIELDS) {
PICOVCF_THROW_ERROR(MalformedFile,
"Invalid line (missing required fields) at " << m_currentLine.substr(0, 100));
} else {
m_nonGTPositions[i] = INTERNAL_VALUE_NOT_SET;
}
} else {
m_nonGTPositions[i] = position;
}
position++;
}
}
explicit VCFVariantView(const std::string& currentLine)
: m_currentLine(currentLine) {}
void reset() { parseNonGenotypePositions(); }
// FORMAT and genotype data is not required.
static constexpr size_t REQUIRED_FIELDS = 8;
const std::string& m_currentLine;
std::array<size_t, 9> m_nonGTPositions;
friend class VCFFile;
};
/**
* A lazy parser for VCF files.
*
* Loads the data into memory a line at a time. Does not parse the entire line,
* as users often only need certain pieces of information.
*/
class VCFFile {
public:
static constexpr const char* const SUPPORTED_PREFIX = "VCFv4";
static constexpr const char* const META_FILE_FORMAT = "fileformat";
// 128kb for reading compressed data from the file, note this is likely to
// result in an uncompressed buffer of a few megabytes.
static constexpr size_t COMPRESSED_BUFFER_SIZE = 128 * 1024;
// 1MB buffer for reading uncompressed data. Larger is faster, to a point.
static constexpr size_t UNCOMPRESSED_BUFFER_SIZE = 1024 * 1024;
explicit VCFFile(const std::string& filename)
: m_variants(INTERNAL_VALUE_NOT_SET),
m_genomeRange({INTERNAL_VALUE_NOT_SET, INTERNAL_VALUE_NOT_SET}),
m_posVariants({INTERNAL_VALUE_NOT_SET, INTERNAL_VALUE_NOT_SET}),
m_currentVariant(m_currentLine) {
if (filename.size() > 3 && filename.substr(filename.size() - 3) == ".gz") {
#if VCF_GZ_SUPPORT
m_infile = std::unique_ptr<BufferedReader>(new ZBufferedReader(filename, COMPRESSED_BUFFER_SIZE));
#else
PICOVCF_THROW_ERROR(ApiMisuse, "picovcf was not compiled with zlib support (VCF_GZ_SUPPORT)");
#endif
} else {
m_infile = std::unique_ptr<BufferedReader>(new BufferedReader(filename, UNCOMPRESSED_BUFFER_SIZE));
}
parseHeader();
std::string version = getMetaInfo(VCFFile::META_FILE_FORMAT);
if (version.substr(0, 5) == SUPPORTED_PREFIX) {
if (version.size() > 6 && !(version[6] != '0' || version[6] == '1' || version[6] == '2')) {
PICOVCF_THROW_ERROR(MalformedFile, "Unsupported VCF version: " << version);
}
} else {
PICOVCF_THROW_ERROR(MalformedFile, "Unsupported VCF version: " << version);
}
}
/**
* Compute the number of variants in the file: expensive!
* This is not a constant time operation, it involves scanning the entire
* file.
*
* @return The number of variants.
*/
size_t numVariants() {
if (m_variants == INTERNAL_VALUE_NOT_SET) {
scanVariants();
}
return m_variants;
}
/**
* Compute the range of positions for variants in the file.
* This is not a constant time operation, it involves scanning the entire
* file.
*
* @return A pair of the minimum and maximum variant positions present in the
* file.
*/
RangePair getGenomeRange() {
if (m_genomeRange.first == INTERNAL_VALUE_NOT_SET) {
scanVariants();
}
return m_genomeRange;
}
/**
* Get the number of individuals with labels in the VCF file.
* @return number of individuals.
*/
size_t numIndividuals() { return m_individualLabels.size(); }
/**
* Get a list of the labels for the individuals in the VCF file.
* @return vector of strings, where the 0th is the 0th individuals label, etc.
*/
std::vector<std::string>& getIndividualLabels() { return m_individualLabels; }
/**
* Get a metadata value from the VCF header rows.
* @param[in] key The metadata key name.
* @return the string associated with the given key, or empty string.
*/
std::string getMetaInfo(const char* const key) const {
const auto metaIt = m_metaInformation.find(key);
if (metaIt != m_metaInformation.end()) {
return metaIt->second;
}
return {};
}
/**
* Get an opaque handle describing the current file position of the parser.
* @return Current FileOffset.
*/
FileOffset getFilePosition() { return m_infile->tell(); }
/**
* Use an opaque handle to return to a previously-recorded file position.
* @param[in] position A FileOffset saved via getFilePosition().
*/
void setFilePosition(const FileOffset& position) { m_infile->seek(position); }
/**
* Change the parser position to be immediately _before_ the first variant.
*/
void seekBeforeVariants() {
PICOVCF_ASSERT_OR_MALFORMED(m_posVariants.first != INTERNAL_VALUE_NOT_SET, "File has no variant data");
setFilePosition(m_posVariants);
}
/**
* Is there a variant at the current file position?
* @returns true if calling nextVariant() will place us at a valid variant.
*/
bool hasNextVariant() { return !picovcf_peek_eof(m_infile.get()); }
/**
* Read the variant at the current file position and move the file position to
* the following variant.
*/
void nextVariant() {
if (picovcf_peek_eof(m_infile.get())) {
PICOVCF_THROW_ERROR(ApiMisuse, "Tried to move to next variant when there aren't any");
}
m_infile->readline(m_currentLine);
m_currentVariant.reset();
}
/**
* Get a parseable view of the variant that we last encountered with
* nextVariant().
* @return A VCFVariantView that can be queried for variant information.
*/
VCFVariantView& currentVariant() { return m_currentVariant; }
/**
* Get a VCFRotatedWindow for the given rectange defined by individualRange
* and genomeRange.
*
* The most efficient way to use this function is from left-to-right
* (individuals) first, and then top-to-bottom (variants). E.g. if you have a
* VCF laid out like this: xyzw XYZW Then ask for the windows in this order:
* x,y,z,w,X,Y,Z,W. This allows use of posAfterLastVariant for efficiency.
*
* Assumptions:
* 1. The VCF rows are ordered by genome position (ascending).
* 2. The genotype data is uniform in ploidy and phased-ness.
*
* @param[in] individualRange The range [start, end) of individual indexes to
* include. For example, [0, 10) will only include individuals 0-9.
* @param[in] genomeRange The range [start, end) of genome positions to
* include. For example, [100, 1000) will include any variants that have
* position 100-999.