forked from vcflib/vcflib
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathVariant.cpp
2918 lines (2639 loc) · 105 KB
/
Variant.cpp
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
/*
vcflib C++ library for parsing and manipulating VCF files
Copyright © 2010-2023 Erik Garrison
Copyright © 2020-2023 Pjotr Prins
This software is published under the MIT License. See the LICENSE file.
*/
#include "Variant.h"
#include "cigar.hpp"
#include <utility>
namespace vcflib {
static char rev_arr [26] = {84, 66, 71, 68, 69, 70, 67, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 65,
85, 86, 87, 88, 89, 90};
std::string reverse_complement(const std::string& seq) {
// The old implementation of this function forgot to null-terminate its
// returned string. This implementation uses heavier-weight C++ stuff that
// may be slower but should ensure that that doesn't happen again.
if (seq.size() == 0) {
return seq;
}
string ret;
ret.reserve(seq.size());
std::transform(seq.rbegin(), seq.rend(), std::back_inserter(ret), [](char in) -> char {
bool lower_case = (in >= 'a' && in <= 'z');
if (lower_case) {
// Convert to upper case
in -= 32;
}
if (in < 'A' || in > 'Z') {
throw std::runtime_error("Out of range character " + std::to_string((uint8_t)in) + " in inverted sequence");
}
// Compute RC in terms of letter identity, and then lower-case if necessary.
return rev_arr[((int) in) - 'A'] + (lower_case ? 32 : 0);
});
return ret;
}
std::string toUpper(const std::string& seq) {
if (seq.size() == 0) {
return seq;
}
string ret;
ret.reserve(seq.size());
std::transform(seq.begin(), seq.end(), std::back_inserter(ret), [](char in) -> char {
// If it's lower-case, bring it down in value to upper-case.
return (in >= 'a' && in <= 'z') ? (in - 32) : in;
});
return ret;
}
bool allATGCN(const string& s, bool allowLowerCase){
if (allowLowerCase){
for (string::const_iterator i = s.begin(); i != s.end(); ++i){
char c = *i;
if (c != 'A' && c != 'a' &&
c != 'C' && c != 'c' &&
c != 'T' && c != 't' &&
c != 'G' && c != 'g' &&
c != 'N' && c != 'n'){
return false;
}
}
}
else{
for (string::const_iterator i = s.begin(); i != s.end(); ++i){
char c = *i;
if (c != 'A' && c != 'C' && c != 'T' && c != 'G' && c != 'N'){
return false;
}
}
}
return true;
}
/*
Main VCF record parser
*/
void Variant::parse(string& line, bool parseSamples) {
// clean up potentially variable data structures because the record may get reused(!)
infoOrderedKeys.clear();
info.clear();
infoFlags.clear();
format.clear();
alt.clear();
alleles.clear();
// #CHROM POS ID REF ALT QUAL FILTER INFO FORMAT [SAMPLE1 .. SAMPLEN]
vector<string> fields = split(line, '\t');
if (fields.size() < 7) {
cerr << "broken VCF record (less than 7 fields)" << endl
<< "Input line: " << line << endl;
exit(1);
}
sequenceName = fields.at(0);
char* end; // dummy variable for strtoll
position = strtoll(fields.at(1).c_str(), &end, 10);
id = fields.at(2);
ref = fields.at(3);
alt = split(fields.at(4), ","); // a comma-separated list of alternate alleles
// make a list of all (ref + alts) alleles, allele[0] = ref, alleles[1:] = alts
// add the ref allele ([0]), resize for the alt alleles, and then add the alt alleles
alleles.push_back(ref);
alleles.resize(alt.size()+1);
std::copy(alt.begin(), alt.end(), alleles.begin()+1);
// set up reverse lookup of allele index
altAlleleIndexes.clear();
int n = 0;
for (vector<string>::iterator a = alt.begin();
a != alt.end(); ++a, ++n) {
altAlleleIndexes[*a] = n;
}
convert(fields.at(5), quality);
filter = fields.at(6);
// Process the INFO fields
if (fields.size() > 7) {
vector<string> infofields = split(fields.at(7), ';');
for (auto field: infofields) {
if (field == ".") {
continue;
}
vector<string> kv = split(field, '='); // note that field gets split in place
auto key = kv.at(0);
if (kv.size() == 2) {
split(kv.at(1), ',', info[key]); // value gets split in place
infoOrderedKeys.push_back(key);
} else if (kv.size() == 1) {
infoFlags[key] = true;
infoOrderedKeys.push_back(key);
}
// malformed fields with double '=' are silently skipped
}
}
// check if we have samples specified
// and that we are supposed to parse them
if (parseSamples && fields.size() > 8) {
format = split(fields.at(8), ':');
// if the format changed, we have to rebuild the samples
if (fields.at(8) != lastFormat) {
samples.clear();
lastFormat = fields.at(8);
}
vector<string>::iterator sampleName = sampleNames.begin();
vector<string>::iterator sample = fields.begin() + 9;
for (; sample != fields.end() && sampleName != sampleNames.end();
++sample, ++sampleName) {
string& name = *sampleName;
vector<string> samplefields = split(*sample, ':');
vector<string>::iterator i = samplefields.begin();
for (vector<string>::iterator f = format.begin();
f != format.end(); ++f) {
if(i != samplefields.end()){
samples[name][*f] = split(*i, ',');
++i;
}
else{
std::vector<string> missing;
missing.push_back(".");
samples[name][*f] = missing;
}
}
}
if (sampleName != sampleNames.end()) {
cerr << "error: more sample names in header than sample fields" << endl;
cerr << "samples: " << join(sampleNames, " ") << endl;
cerr << "line: " << line << endl;
exit(1);
}
if (sample != fields.end()) {
cerr << "error: more sample fields than samples listed in header" << endl;
cerr << "samples: " << join(sampleNames, " ") << endl;
cerr << "line: " << line << endl;
cerr << *sample << endl;
exit(1);
}
} else if (!parseSamples) {
originalLine = line;
}
//return true; // we should be catching exceptions...
}
bool Variant::hasSVTags() const{
bool found_svtype = !getSVTYPE().empty();
bool found_len = this->info.find("SVLEN") != this->info.end() || this->info.find("END") != this->info.end() || this->info.find("SPAN") != this->info.end();
return found_svtype && found_len;
}
/*
According to the VCF spec the ALT field can be use to indicate 'imprecise' structural
variants.
*/
bool Variant::isSymbolicSV() const{
bool found_svtype = !getSVTYPE().empty();
bool ref_valid = allATGCN(this->ref);
bool alts_valid = true;
for (auto a : this->alt){
if (!allATGCN(a)){
alts_valid = false;
}
}
return (!ref_valid || !alts_valid) && (found_svtype);
}
string Variant::getSVTYPE(int altpos) const{
if (altpos > 0){
// TODO: Implement multi-alt SVs
return "";
}
if (this->info.find("SVTYPE") != this->info.end()){
if (altpos >= this->info.at("SVTYPE").size()) {
return "";
}
return this->info.at("SVTYPE")[altpos];
}
return "";
};
int Variant::getMaxReferencePos(){
if (this->canonical && this->info.find("END") != this->info.end()) {
// We are cannonicalized and must have a correct END
int end = 0;
for (auto s : this->info.at("END")){
// Get the latest one defined.
end = max(abs(stoi(s)), end);
}
// Convert to 0-based.
return end - 1;
}
if (!this->isSymbolicSV()){
// We don't necessarily have an END, but we don't need one
return this->zeroBasedPosition() + this->ref.length() - 1;
}
if (this->canonicalizable()){
// We aren't canonical, but we could be.
if (this->info.find("END") != this->info.end()){
// We have an END; blindly trust it
int end = 0;
for (auto s : this->info.at("END")){
// Get the latest one defined.
end = max(abs(stoi(s)), end);
}
// Convert to 0-based.
return end - 1;
}
else if (this->info.find("SVLEN") != this->info.end()){
// There's no endpoint, but we know an SVLEN.
// A negative SVLEN means a deletion, so if we find one we can say we delete that much.
int deleted = 0;
for (auto s : this->info.at("SVLEN")){
int alt_len = stoi(s);
if (alt_len > 0){
// Not a deletion, so doesn't affect any ref bases
continue;
}
deleted = max(-alt_len, deleted);
}
// The anchoring base at POS gets added in (because it isn't
// deleted) but then subtracted out (because we have to do that to
// match non-SV deletions). For insertions, deleted is 0 and we
// return 0-based POS. Inversions must have an END.
return this->zeroBasedPosition() + deleted;
}
else{
cerr << "Warning: insufficient length information for " << *this << endl;
return -1;
}
}
else {
cerr << "Warning: can't get end of non-canonicalizeable variant " << *this << endl;
}
return -1;
}
// To canonicalize a variant, we need either both REF and ALT seqs filled in
// or SVTYPE and SVLEN or END or SPAN or SEQ sufficient to define the variant.
bool Variant::canonicalizable(){
bool pre_canon = allATGCN(this->ref);
for (auto& a : this->alt){
if (!allATGCN(a)){
pre_canon = false;
}
}
if (pre_canon){
// It came in in a fully specified way.
// TODO: ideally, we'd check to make sure ref/alt lengths, svtypes, and ends line up right here.
return true;
}
string svtype = getSVTYPE();
if (svtype.empty()){
// We have no SV type, so we can't interpret things.
return false;
}
// Check the tags
bool has_len = this->info.count("SVLEN") && !this->info.at("SVLEN").empty();
bool has_seq = this->info.count("SEQ") && !this->info.at("SEQ").empty();
bool has_span = this->info.count("SPAN") && !this->info.at("SPAN").empty();
bool has_end = this->info.count("END") && !this->info.at("END").empty();
if (svtype == "INS"){
// Insertions need a SEQ, SVLEN, or SPAN
return has_seq || has_len || has_span;
}
else if (svtype == "DEL"){
// Deletions need an SVLEN, SPAN, or END
return has_len || has_span || has_end;
}
else if (svtype == "INV"){
// Inversions need a SPAN or END
return has_span || has_end;
}
else{
// Other SV types are unsupported
// TODO: DUP
return false;
}
}
bool Variant::canonicalize(FastaReference& fasta_reference, vector<FastaReference*> insertions, bool place_seq, int min_size){
// Nobody should call this without checking
assert(canonicalizable());
// Nobody should call this twice
assert(!this->canonical);
// Find where the inserted sequence can come from for insertions
bool do_external_insertions = !insertions.empty();
FastaReference* insertion_fasta;
if (do_external_insertions){
insertion_fasta = insertions[0];
}
bool ref_valid = allATGCN(ref);
if (!ref_valid && !place_seq){
// If the reference is invalid, and we aren't allowed to change the ref sequence,
// we can't canonicalize the variant.
return false;
}
// Check the alts to see if they are not symbolic
vector<bool> alt_i_atgcn (alt.size());
for (int i = 0; i < alt.size(); ++i){
alt_i_atgcn[i] = allATGCN(alt[i]);
}
// Only allow single-alt variants
bool single_alt = alt.size() == 1;
if (!single_alt){
// TODO: this will need to be remove before supporting multiple alleles
cerr << "Warning: multiple ALT alleles not yet allowed for SVs" << endl;
return false;
}
// Fill in the SV tags
string svtype = getSVTYPE();
bool has_len = this->info.count("SVLEN") && !this->info.at("SVLEN").empty();
bool has_seq = this->info.count("SEQ") && !this->info.at("SEQ").empty();
bool has_span = this->info.count("SPAN") && !this->info.at("SPAN").empty();
bool has_end = this->info.count("END") && !this->info.at("END").empty();
// Where is the end, or where should it be?
long info_end = 0;
if (has_end) {
// Get the END from the tag
info_end = stol(this->info.at("END")[0]);
}
else if(ref_valid && !place_seq) {
// Get the END from the reference sequence, which is ready.
info_end = this->position + this->ref.length() - 1;
}
else if ((svtype == "DEL" || svtype == "INV") && has_span) {
// For deletions and inversions, we can get the END from the SPAN
info_end = this->position + abs(stol(this->info.at("SPAN")[0]));
}
else if (svtype == "DEL" && has_len) {
// For deletions, we can get the END from the SVLEN
info_end = this->position + abs(stol(this->info.at("SVLEN")[0]));
}
else if (svtype == "INS"){
// For insertions, END is just POS if not specified
info_end = this->position;
}
else{
cerr << "Warning: could not set END info " << *this << endl;
return false;
}
// Commit back the END
this->info["END"].resize(1);
this->info["END"][0] = to_string(info_end);
has_end = true;
// What is the variant length change?
// We store it as absolute value
long info_len = 0;
if (has_len){
// Get the SVLEN from the tag
info_len = abs(stol(this->info.at("SVLEN")[0]));
}
else if ((svtype == "INS" || svtype == "DEL") && has_span){
info_len = abs(stol(this->info.at("SPAN")[0]));
}
else if (svtype == "DEL"){
// We always have the end by now
// Deletion ends give you length change
info_len = info_end - this->position;
}
else if (svtype == "INV"){
// Inversions have 0 length change unless otherwise specified.
info_len = 0;
}
else if (svtype == "INS" && has_seq) {
// Insertions can let us pick it up from the SEQ tag
info_len = this->info.at("SEQ").at(0).size();
}
else{
cerr << "Warning: could not set SVLEN info " << *this << endl;
return false;
}
// Commit the SVLEN back
if (svtype == "DEL"){
// Should be saved as negative
this->info["SVLEN"].resize(1);
this->info["SVLEN"][0] = to_string(-info_len);
}
else{
// Should be saved as positive
this->info["SVLEN"].resize(1);
this->info["SVLEN"][0] = to_string(info_len);
}
// Now the length change is known
has_len = true;
// We also compute a span
long info_span = 0;
if (has_span){
// Use the specified span
info_span = abs(stol(this->info.at("SVLEN")[0]));
}
else if (svtype == "INS" || svtype == "DEL"){
// has_len is always true here
// Insertions and deletions let us determine the span from the length change, unless they are complex.
info_span = info_len;
}
else if (svtype == "INV"){
// has_end is always true here
// Inversion span is start to end
info_span = info_end - this->position;
}
else{
cerr << "Warning: could not set SPAN info " << *this << endl;
return false;
}
// Commit the SPAN back
this->info["SPAN"].resize(1);
this->info["SPAN"][0] = to_string(info_span);
// Now the span change is known
has_span = true;
if (info_end < this->position) {
cerr << "Warning: SV END is before POS [canonicalize] " <<
*this << endl << "END: " << info_end << " " << "POS: " << this->position << endl;
return false;
}
if (has_seq) {
// Force the SEQ to upper case, if already present
this->info["SEQ"].resize(1);
this->info["SEQ"][0] = toUpper(this->info["SEQ"][0]);
}
// Set the other necessary SV Tags (SVTYPE, SEQ (if insertion))
// Also check for agreement in the position tags
if (svtype == "INS"){
if (info_end != this->position){
cerr << "Warning: insertion END and POS do not agree (complex insertions not canonicalizeable) [canonicalize] " <<
*this << endl << "END: " << info_end << " " << "POS: " << this->position << endl;
if (info_end == this->position + info_len) {
// We can probably guess what they meant here.
cerr << "Warning: VCF writer incorrecty produced END = POS + SVLEN for an insertion. Fixing END to POS." << endl;
info_end = this->position;
this->info["END"][0] = to_string(info_end);
} else {
return false;
}
}
if (info_len != info_span){
cerr << "Warning: insertion SVLEN and SPAN do not agree (complex insertions not canonicalizeable) [canonicalize] " <<
*this << endl << "SVLEN: " << info_len << " " << "SPAN: " << info_span << endl;
return false;
}
if (has_seq && allATGCN(this->info.at("SEQ")[0]) && this->info.at("SEQ")[0].size() != info_len){
cerr << "Warning: insertion SVLEN and SEQ do not agree (complex insertions not canonicalizeable) [canonicalize] " <<
*this << endl << "SVLEN: " << info_len << " " << "SEQ length: " << this->info.at("SEQ")[0].size() << endl;
return false;
}
// Set REF
string ref_base = toUpper(fasta_reference.getSubSequence(this->sequenceName, this->zeroBasedPosition(), 1));
if (place_seq){
this->ref.assign(ref_base);
}
if (has_seq &&
alt[0] != this->info.at("SEQ")[0] &&
allATGCN(this->info.at("SEQ")[0])){
// Try to remove prepended ref sequence, assuming it's left-aligned
string s = this->alt[0];
s = toUpper(s.substr(this->ref.length()));
if (s != this->info.at("SEQ")[0] && !place_seq){
cerr << "Warning: INS sequence in alt field does not match SEQ tag" << endl <<
this->alt[0] << " " << this->info.at("SEQ")[0] << endl;
return false;
}
if (place_seq){
this->alt[0].assign( ref_base + this->info.at("SEQ")[0] );
}
}
else if (alt_i_atgcn[0] && !has_seq){
string s = this->alt[0];
s = toUpper(s.substr(this->ref.length()));
this->info["SEQ"].resize(1);
this->info.at("SEQ")[0].assign(s);
if (s.size() != info_len){
cerr << "Warning: insertion SVLEN and added bases do not agree (complex insertions not canonicalizeable) [canonicalize] " <<
*this << endl << "SVLEN: " << info_len << " " << "added bases: " << s.size() << endl;
return false;
}
}
else if (alt[0][0] == '<' && do_external_insertions){
string ins_seq;
string seq_id = alt[0].substr(1, alt[0].size() - 2);
if (insertion_fasta->index->find(seq_id) != insertion_fasta->index->end()){
ins_seq = toUpper(insertion_fasta->getSequence(seq_id));
if (allATGCN(ins_seq)){
this->info["SEQ"].resize(1);
this->info["SEQ"][0].assign(ins_seq);
if (place_seq){
this->alt[0].assign(ref_base + ins_seq);
}
}
else {
cerr << "Warning: Loaded invalid alt sequence for: " << *this << endl;
return false;
}
if (ins_seq.size() != info_len){
cerr << "Warning: insertion SVLEN and FASTA do not agree (complex insertions not canonicalizeable) [canonicalize] " <<
*this << endl << "SVLEN: " << info_len << " " << "FASTA bases: " << ins_seq.size() << endl;
return false;
}
}
else{
cerr << "Warning: could not locate alt sequence for: " << *this << endl;
return false;
}
}
else{
cerr << "Warning: could not set SEQ [canonicalize]. " << *this << endl;
return false;
}
}
else if (svtype == "DEL"){
// Note that info_len has been abs'd and is always positive
if (this->position + info_len != info_end){
cerr << "Warning: deletion END and SVLEN do not agree [canonicalize] " << *this << endl <<
"END: " << info_end << " " << "SVLEN: " << info_len << endl;
return false;
}
if (this->position + info_span != info_end){
cerr << "Warning: deletion END and SPAN do not agree [canonicalize] " << *this << endl <<
"END: " << info_end << " " << "SPAN: " << info_span << endl;
return false;
}
if (info_end > fasta_reference.sequenceLength(this->sequenceName)) {
cerr << "Warning: deletion END is past end of sequence [canonicalize] " << *this << endl <<
"END: " << info_end << " " << "length: " << fasta_reference.sequenceLength(this->sequenceName) << endl;
return false;
}
// Set REF
if (place_seq){
string del_seq = toUpper(fasta_reference.getSubSequence(this->sequenceName, this->zeroBasedPosition(), info_len + 1));
string ref_base = toUpper(fasta_reference.getSubSequence(this->sequenceName, this->zeroBasedPosition(), 1));
this->ref.assign( del_seq );
this->alt[0].assign( ref_base );
}
}
else if (svtype == "INV"){
if (this->position + info_span != info_end){
cerr << "Warning: inversion END and SPAN do not agree [canonicalize] " << *this << endl <<
"END: " << info_end << " " << "SPAN: " << info_span << endl;
return false;
}
if (info_len != 0){
cerr << "Warning: inversion SVLEN specifies nonzero length change (complex inversions not canonicalizeable) [canonicalize] " <<
*this << endl << "SVLEN: " << info_len << endl;
if (info_end == this->position + info_len) {
// We can probably guess what they meant here.
cerr << "Warning: VCF writer incorrecty produced END = POS + SVLEN for an inversion. Fixing SVLEN to 0." << endl;
info_len = 0;
this->info["SVLEN"][0] = to_string(info_len);
} else {
return false;
}
}
if (info_end > fasta_reference.sequenceLength(this->sequenceName)) {
cerr << "Warning: inversion END is past end of sequence [canonicalize] " << *this << endl <<
"END: " << info_end << " " << "length: " << fasta_reference.sequenceLength(this->sequenceName) << endl;
return false;
}
if (place_seq){
string ref_seq = toUpper(fasta_reference.getSubSequence(this->sequenceName, this->zeroBasedPosition(), info_span + 1));
// Note that inversions still need an anchoring left base at POS
string inv_seq = ref_seq.substr(0, 1) + reverse_complement(ref_seq.substr(1));
this->ref.assign(ref_seq);
this->alt[0].assign(inv_seq);
}
}
else{
cerr << "Warning: invalid SV type [canonicalize]:" << *this << endl;
return false;
}
this->updateAlleleIndexes();
// Check for harmony between ref / alt / tags
if (this->position > stol(this->info.at("END").at(0))){
cerr << "Warning: position > END. Possible reference genome mismatch." << endl;
return false;
}
if (svtype == "INS"){
assert(!this->info.at("SEQ")[0].empty());
}
this->canonical = true;
return true;
}
void Variant::setVariantCallFile(VariantCallFile& v) {
sampleNames = v.sampleNames;
outputSampleNames = v.sampleNames;
vcf = &v;
}
void Variant::setVariantCallFile(VariantCallFile* v) {
sampleNames = v->sampleNames;
outputSampleNames = v->sampleNames;
vcf = v;
}
ostream& operator<<(ostream& out, VariantFieldType type) {
switch (type) {
case FIELD_INTEGER:
out << "integer";
break;
case FIELD_FLOAT:
out << "float";
break;
case FIELD_BOOL:
out << "bool";
break;
case FIELD_STRING:
out << "string";
break;
default:
out << "unknown";
break;
}
return out;
}
VariantFieldType typeStrToVariantFieldType(string& typeStr) {
if (typeStr == "Integer") {
return FIELD_INTEGER;
} else if (typeStr == "Float") {
return FIELD_FLOAT;
} else if (typeStr == "Flag") {
return FIELD_BOOL;
} else if (typeStr == "String") {
return FIELD_STRING;
} else {
return FIELD_UNKNOWN;
}
}
VariantFieldType Variant::infoType(const string& key) {
map<string, VariantFieldType>::iterator s = vcf->infoTypes.find(key);
if (s == vcf->infoTypes.end()) {
if (key == "FILTER") { // hack to use FILTER as an "info" field (why the hack?)
return FIELD_STRING;
}
if (key == "QUAL") { // hack to use QUAL as an "info" field
return FIELD_INTEGER;
}
cerr << "no info field " << key << endl;
exit(1);
} else {
return s->second;
}
}
VariantFieldType Variant::formatType(const string& key) {
map<string, VariantFieldType>::iterator s = vcf->formatTypes.find(key);
if (s == vcf->formatTypes.end()) {
cerr << "no format field " << key << endl;
exit(1);
} else {
return s->second;
}
}
bool Variant::getInfoValueBool(const string& key, int index) {
map<string, VariantFieldType>::iterator s = vcf->infoTypes.find(key);
if (s == vcf->infoTypes.end()) {
cerr << "no info field " << key << endl;
exit(1);
} else {
int count = vcf->infoCounts[key];
// XXX TODO, fix for Genotype variants...
if (count != ALLELE_NUMBER) {
index = 0;
}
if (index == INDEX_NONE) {
if (count != 1) {
cerr << "no field index supplied and field count != 1" << endl;
exit(1);
} else {
index = 0;
}
}
VariantFieldType type = s->second;
if (type == FIELD_BOOL) {
map<string, bool>::iterator b = infoFlags.find(key);
if (b == infoFlags.end())
return false;
else
return true;
} else {
cerr << "not flag type " << key << endl;
exit(1);
}
}
}
string Variant::getInfoValueString(const string& key, int index) {
map<string, VariantFieldType>::iterator s = vcf->infoTypes.find(key);
if (s == vcf->infoTypes.end()) {
if (key == "FILTER") {
return filter;
}
cerr << "no info field " << key << endl;
exit(1);
} else {
int count = vcf->infoCounts[key];
// XXX TODO, fix for Genotype variants...
if (count != ALLELE_NUMBER) {
index = 0;
}
if (index == INDEX_NONE) {
if (count != 1) {
cerr << "no field index supplied and field count != 1" << endl;
exit(1);
} else {
index = 0;
}
}
VariantFieldType type = s->second;
if (type == FIELD_STRING) {
map<string, vector<string> >::iterator b = info.find(key);
if (b == info.end())
return "";
return b->second.at(index);
} else {
cerr << "not string type " << key << endl;
return "";
}
}
}
double Variant::getInfoValueFloat(const string& key, int index) {
map<string, VariantFieldType>::iterator s = vcf->infoTypes.find(key);
if (s == vcf->infoTypes.end()) {
if (key == "QUAL") {
return quality;
}
cerr << "no info field " << key << endl;
exit(1);
} else {
int count = vcf->infoCounts[key];
// XXX TODO, fix for Genotype variants...
if (count != ALLELE_NUMBER) {
index = 0;
}
if (index == INDEX_NONE) {
if (count != 1) {
cerr << "no field index supplied and field count != 1" << endl;
exit(1);
} else {
index = 0;
}
}
VariantFieldType type = s->second;
if (type == FIELD_FLOAT || type == FIELD_INTEGER) {
map<string, vector<string> >::iterator b = info.find(key);
if (b == info.end())
return false;
double r;
if (!convert(b->second.at(index), r)) {
cerr << "could not convert field " << key << "=" << b->second.at(index) << " to " << type << endl;
exit(1);
}
return r;
} else {
cerr << "unsupported type for variant record " << type << endl;
exit(1);
}
}
}
int Variant::getNumSamples(void) {
return sampleNames.size();
}
int Variant::getNumValidGenotypes(void) {
int valid_genotypes = 0;
map<string, map<string, vector<string> > >::const_iterator s = samples.begin();
map<string, map<string, vector<string> > >::const_iterator sEnd = samples.end();
for (; s != sEnd; ++s) {
map<string, vector<string> > sample_info = s->second;
if (sample_info["GT"].front() != "./.") {
valid_genotypes++;
}
}
return valid_genotypes;
}
bool Variant::getSampleValueBool(const string& key, string& sample, int index) {
map<string, VariantFieldType>::iterator s = vcf->formatTypes.find(key);
if (s == vcf->infoTypes.end()) {
cerr << "no info field " << key << endl;
exit(1);
} else {
int count = vcf->formatCounts[key];
// XXX TODO, fix for Genotype variants...
if (count != ALLELE_NUMBER) {
index = 0;
}
if (index == INDEX_NONE) {
if (count != 1) {
cerr << "no field index supplied and field count != 1" << endl;
exit(1);
} else {
index = 0;
}
}
VariantFieldType type = s->second;
map<string, vector<string> >& sampleData = samples[sample];
if (type == FIELD_BOOL) {
map<string, vector<string> >::iterator b = sampleData.find(key);
if (b == sampleData.end())
return false;
else
return true;
} else {
cerr << "not bool type " << key << endl;
exit(1);
}
}
}
string Variant::getSampleValueString(const string& key, string& sample, int index) {
map<string, VariantFieldType>::iterator s = vcf->formatTypes.find(key);
if (s == vcf->infoTypes.end()) {
cerr << "no info field " << key << endl;
exit(1);
} else {
int count = vcf->formatCounts[key];
// XXX TODO, fix for Genotype variants...
if (count != ALLELE_NUMBER) {
index = 0;
}
if (index == INDEX_NONE) {
if (count != 1) {
cerr << "no field index supplied and field count != 1" << endl;
exit(1);
} else {
index = 0;
}
}
VariantFieldType type = s->second;
map<string, vector<string> >& sampleData = samples[sample];
if (type == FIELD_STRING) {
map<string, vector<string> >::iterator b = sampleData.find(key);
if (b == sampleData.end()) {
return "";
} else {
return b->second.at(index);
}
} else {
cerr << "not string type " << key << endl;
exit(1);
}
}
}
double Variant::getSampleValueFloat(const string& key, string& sample, int index) {
map<string, VariantFieldType>::iterator s = vcf->formatTypes.find(key);
if (s == vcf->infoTypes.end()) {
cerr << "no info field " << key << endl;
exit(1);
} else {
// XXX TODO wrap this with a function call
int count = vcf->formatCounts[key];
// XXX TODO, fix for Genotype variants...
if (count != ALLELE_NUMBER) {
index = 0;
}
if (index == INDEX_NONE) {
if (count != 1) {
cerr << "no field index supplied and field count != 1" << endl;
exit(1);
} else {
index = 0;
}
}
VariantFieldType type = s->second;
map<string, vector<string> >& sampleData = samples[sample];
if (type == FIELD_FLOAT || type == FIELD_INTEGER) {