-
Notifications
You must be signed in to change notification settings - Fork 219
/
Variant.cpp
2465 lines (2245 loc) · 88.6 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>
#include "multichoose.h"
#include <SmithWatermanGotoh.h>
#include "ssw_cpp.hpp"
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 "";
};
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) {
map<string, vector<string> >::iterator b = sampleData.find(key);
if (b == sampleData.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 sample " << type << endl;
exit(1);
}
}
}
bool Variant::getValueBool(const string& key, string& sample, int index) {
if (sample.empty()) { // an empty sample name means
return getInfoValueBool(key, index);
} else {
return getSampleValueBool(key, sample, index);
}
}
double Variant::getValueFloat(const string& key, string& sample, int index) {
if (sample.empty()) { // an empty sample name means
return getInfoValueFloat(key, index);
} else {
return getSampleValueFloat(key, sample, index);
}
}
string Variant::getValueString(const string& key, string& sample, int index) {
if (sample.empty()) { // an empty sample name means
return getInfoValueString(key, index);
} else {
return getSampleValueString(key, sample, index);
}
}
int Variant::getAltAlleleIndex(const string& allele) {
map<string, int>::iterator f = altAlleleIndexes.find(allele);
if (f == altAlleleIndexes.end()) {
cerr << "no such allele \'" << allele << "\' in record " << sequenceName << ":" << position << endl;
exit(1);
} else {
return f->second;
}
}
void Variant::addFilter(const string& tag) {
if (filter == "" || filter == ".")
filter = tag;
else
filter += "," + tag;
}
void Variant::addFormatField(const string& key) {
bool hasTag = false;
for (vector<string>::iterator t = format.begin(); t != format.end(); ++t) {
if (*t == key) {
hasTag = true;
break;
}
}
if (!hasTag) {
format.push_back(key);
}
}
void Variant::printAlt(ostream& out) {
for (vector<string>::iterator i = alt.begin(); i != alt.end(); ++i) {
out << *i;
// add a comma for all but the last alternate allele
if (i != (alt.end() - 1)) out << ",";
}
}
void Variant::printAlleles(ostream& out) {
for (vector<string>::iterator i = alleles.begin(); i != alleles.end(); ++i) {
out << *i;
// add a comma for all but the last alternate allele
if (i != (alleles.end() - 1)) out << ",";
}
}
/*
This is the main outputter of VCF records/lines
*/
ostream& operator<<(ostream& out, Variant& var) {
// ensure there are no empty fields
if (var.sequenceName.empty()) var.sequenceName = ".";
if (var.id.empty()) var.id = ".";
if (var.ref.empty()) var.ref = ".";
if (var.alt.empty()) var.alt.push_back(".");
if (var.filter.empty()) var.filter = ".";
out << var.sequenceName << "\t"
<< var.position << "\t"
<< var.id << "\t"
<< var.ref << "\t";
// report the list of alternate alleles.
var.printAlt(out);
out << "\t"
<< var.quality << "\t"
<< var.filter << "\t";
if (var.info.empty() && var.infoFlags.empty()) {
out << ".";
} else {
// We want to display the info fields in the original
// order. Because the actual info list may have been
// modified since the record was read, we need to recreate
// a valid ordered key list.
map<string,bool> lookup_keys; // for quick lookup in 2nd step
vector<string> ordered_keys, missing_keys; // the output list
// first lookup the keys that appear both in infoOrdered keys
// and the info field:
for (auto name: var.infoOrderedKeys)
{
lookup_keys[name] = true;
if (!var.info[name].empty()) ordered_keys.push_back(name);
if (var.infoFlags[name]) ordered_keys.push_back(name);
};
// next add the keys that are not in the original list:
for (const auto& [name1, value]: var.info)
if (!lookup_keys[name1]) missing_keys.push_back(name1);
for (const auto& [name2, value]: var.infoFlags)
if (lookup_keys[name2] == false) missing_keys.push_back(name2);
// append sorted missing keys
std::sort(missing_keys.begin(), missing_keys.end());
ordered_keys.insert(ordered_keys.end(), missing_keys.begin(), missing_keys.end());
// output the ordered info fields
string s = "";
for (auto name: ordered_keys) {
auto value = var.info[name];
if (!value.empty()) {
s += name + "=" + join(value, ",") + ";" ;
} else {
auto infoflag = var.infoFlags[name];
if (infoflag == true)
s += name + ";";
}
}
auto len = s.length();
if (len)
out << s.substr(0, len-1); // chop s1.substr(0, i-1);
}
if (!var.format.empty()) {
out << "\t";
string format = "";
for (auto f: var.format) {
format += f + ":";
}
auto len = format.length();
if (len)
out << format.substr(0, len-1); // chop s1.substr(0, i-1);
for (auto s: var.outputSampleNames) {
out << "\t";
map<string, map<string, vector<string> > >::iterator sampleItr = var.samples.find(s);
if (sampleItr == var.samples.end()) {
out << ".";
} else {
map<string, vector<string> >& sample = sampleItr->second;
if (sample.size() == 0) {
out << ".";
} else {
for (vector<string>::iterator f = var.format.begin(); f != var.format.end(); ++f) {
map<string, vector<string> >::iterator g = sample.find(*f);
out << ((f == var.format.begin()) ? "" : ":");
if (g != sample.end() && !g->second.empty()) {
out << join(g->second, ",");
} else {
out << ".";
}
}
}
}
}
}
return out;
}
void Variant::setOutputSampleNames(vector<string>& samplesToOutput) {
outputSampleNames = samplesToOutput;
}
// shunting yard algorithm
void infixToPrefix(queue<RuleToken> tokens, queue<RuleToken>& prefixtokens) {
stack<RuleToken> ops;
while (!tokens.empty()) {
RuleToken& token = tokens.front();
if (isOperator(token)) {
//cerr << "found operator " << token.value << endl;
while (ops.size() > 0 && isOperator(ops.top())
&& ( (isLeftAssociative(token) && priority(token) <= priority(ops.top()))
|| (isRightAssociative(token) && priority(token) < priority(ops.top())))) {
prefixtokens.push(ops.top());
ops.pop();
}
ops.push(token);
} else if (isLeftParenthesis(token)) {
//cerr << "found paran " << token.value << endl;
ops.push(token);
} else if (isRightParenthesis(token)) {
//cerr << "found paran " << token.value << endl;
while (ops.size() > 0 && !isLeftParenthesis(ops.top())) {
prefixtokens.push(ops.top());
ops.pop();
}
if (ops.size() == 0) {
cerr << "error: mismatched parentheses" << endl;
exit(1);
}
if (isLeftParenthesis(ops.top())) {
ops.pop();
}
} else {
//cerr << "found operand " << token.value << endl;
prefixtokens.push(token);
}
tokens.pop();
}
while (ops.size() > 0) {
if (isRightParenthesis(ops.top()) || isLeftParenthesis(ops.top())) {
cerr << "error: mismatched parentheses" << endl;
exit(1);
}
prefixtokens.push(ops.top());
ops.pop();
}
}
RuleToken::RuleToken(string tokenstr, map<string, VariantFieldType>& variables) {
isVariable = false;
if (tokenstr == "!") {
type = RuleToken::NOT_OPERATOR;
} else if (tokenstr == "&") {
type = RuleToken::AND_OPERATOR;
} else if (tokenstr == "|") {
type = RuleToken::OR_OPERATOR;
} else if (tokenstr == "+") {
type = RuleToken::ADD_OPERATOR;
} else if (tokenstr == "-") {
type = RuleToken::SUBTRACT_OPERATOR;
} else if (tokenstr == "*") {
type = RuleToken::MULTIPLY_OPERATOR;
} else if (tokenstr == "/") {
type = RuleToken::DIVIDE_OPERATOR;
} else if (tokenstr == "=") {
type = RuleToken::EQUAL_OPERATOR;
} else if (tokenstr == ">") {
type = RuleToken::GREATER_THAN_OPERATOR;
} else if (tokenstr == "<") {
type = RuleToken::LESS_THAN_OPERATOR;
} else if (tokenstr == "(") {
type = RuleToken::LEFT_PARENTHESIS;
} else if (tokenstr == ")") {
type = RuleToken::RIGHT_PARENTHESIS;
} else { // operand
type = RuleToken::OPERAND;
if (variables.find(tokenstr) == variables.end()) {
if (convert(tokenstr, number)) {
type = RuleToken::NUMBER;
} else if (tokenstr == "QUAL") {
isVariable = true;
} else if (tokenstr == "FILTER") {
isVariable = true;
} else {
type = RuleToken::STRING_VARIABLE;
}
} else {
isVariable = true;
}
}
value = tokenstr;
}
void tokenizeFilterSpec(string& filterspec, queue<RuleToken>& tokens, map<string, VariantFieldType>& variables) {
string lastToken = "";
bool inToken = false;
for (unsigned int i = 0; i < filterspec.size(); ++i) {
char c = filterspec.at(i);
if (c == ' ' || c == '\n') {
inToken = false;
if (!inToken && lastToken.size() > 0) {
tokens.push(RuleToken(lastToken, variables));
lastToken = "";
}
} else if (!inToken && (isOperatorChar(c) || isParanChar(c))) {
inToken = false;
if (lastToken.size() > 0) {
tokens.push(RuleToken(lastToken, variables));
lastToken = "";
}
tokens.push(RuleToken(filterspec.substr(i,1), variables));
} else {
inToken = true;
lastToken += c;
}
}
// get the last token
if (inToken) {
tokens.push(RuleToken(lastToken, variables));
}
}
// class which evaluates filter expressions
// allow filters to be defined using boolean infix expressions e.g.:
//
// "GQ > 10 & (DP < 3 | DP > 5) & SAMPLE = NA12878"
// or
// "GT = 1/1 | GT = 0/0"
//
// on initialization, tokenizes the input sequence, and converts it from infix to postfix
// on call to
//
VariantFilter::VariantFilter(string filterspec, VariantFilterType filtertype, map<string, VariantFieldType>& variables) {
type = filtertype;
spec = filterspec;
tokenizeFilterSpec(filterspec, tokens, variables);
infixToPrefix(tokens, rules);
/*while (!rules.empty()) {
cerr << " " << rules.front().value << ((isNumeric(rules.front())) ? "f" : "");
rules.pop();
}
*/
//cerr << endl;
//cerr << join(" ", tokens) << endl;
}
// all alts pass
bool VariantFilter::passes(Variant& var, string& sample) {
for (vector<string>::iterator a = var.alt.begin(); a != var.alt.end(); ++a) {
string& allele = *a;
if (!passes(var, sample, allele)) {
return false;
}
}
return true;
}
bool VariantFilter::passes(Variant& var, string& sample, string& allele) {
// to evaluate a rpn boolean queue with embedded numbers and variables
// make a result stack, use float to allow comparison of floating point
// numbers, booleans, and integers
stack<RuleToken> results;
queue<RuleToken> rulesCopy = rules; // copy
int index;
if (allele.empty()) {
index = 0; // apply to the whole record
} else {
// apply to a specific allele
index = var.getAltAlleleIndex(allele);
}
while (!rulesCopy.empty()) {
RuleToken token = rulesCopy.front();
rulesCopy.pop();
// pop operands from the front of the queue and push them onto the stack
if (isOperand(token)) {
//cout << "is operand: " << token.value << endl;
// if the token is variable, i.e. not evaluated in this context, we
// must evaluate it before pushing it onto the stack
if (token.isVariable) {
//cout << "is variable" << endl;
// look up the variable using the Variant, depending on our filter type
//cout << "token.value " << token.value << endl;
VariantFieldType vtype;
if (sample.empty()) { // means we are record-specific
vtype = var.infoType(token.value);
} else {
vtype = var.formatType(token.value);
//cout << "type = " << type << endl;
}
//cout << "type: " << type << endl;
if (vtype == FIELD_INTEGER || vtype == FIELD_FLOAT) {
token.type = RuleToken::NUMERIC_VARIABLE;
token.number = var.getValueFloat(token.value, sample, index);
//cerr << "number: " << token.number << endl;
} else if (vtype == FIELD_BOOL) {
token.type = RuleToken::BOOLEAN_VARIABLE;
token.state = var.getValueBool(token.value, sample, index);
//cerr << "state: " << token.state << endl;
} else if (vtype == FIELD_STRING) {
//cout << "token.value = " << token.value << endl;
token.type = RuleToken::STRING_VARIABLE;
token.str = var.getValueString(token.value, sample, index);
} else if (isString(token)) {
token.type = RuleToken::STRING_VARIABLE;
token.str = var.getValueString(token.value, sample, index);
//cerr << "string: " << token.str << endl;
}
} else {
double f;
string s;
//cerr << "parsing operand" << endl;
if (convert(token.value, f)) {
token.type = RuleToken::NUMERIC_VARIABLE;
token.number = f;
//cerr << "number: " << token.number << endl;
} else if (convert(token.value, s)) {
token.type = RuleToken::STRING_VARIABLE;
token.str = s;
//cerr << "string: " << token.str << endl;
} else {
cerr << "could not parse non-variable operand " << token.value << endl;
exit(1);
}
}
results.push(token);
}
// apply operators to the first n elements on the stack and push the result back onto the stack
else if (isOperator(token)) {
//cerr << "is operator: " << token.value << endl;
RuleToken a, b, r;
// is it a not-operator?
switch (token.type) {
case ( RuleToken::NOT_OPERATOR ):
a = results.top();
results.pop();
if (!isBoolean(a)) {
cerr << "cannot negate a non-boolean" << endl;
} else {
a.state = !a.state;
results.push(a);
}
break;
case ( RuleToken::EQUAL_OPERATOR ):
a = results.top(); results.pop();
b = results.top(); results.pop();
if (a.type == b.type) {
switch (a.type) {
case (RuleToken::STRING_VARIABLE):
r.state = (a.str == b.str);
break;
case (RuleToken::NUMERIC_VARIABLE):
r.state = (a.number == b.number);
break;
case (RuleToken::BOOLEAN_VARIABLE):
r.state = (a.state == b.state);
break;
default:
cerr << "should not get here" << endl; exit(1);