-
Notifications
You must be signed in to change notification settings - Fork 80
/
Copy pathVcfEntry.java
1619 lines (1343 loc) · 45.3 KB
/
VcfEntry.java
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
package org.snpeff.vcf;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.snpeff.align.VcfRefAltAlign;
import org.snpeff.fileIterator.VcfFileIterator;
import org.snpeff.interval.Cds;
import org.snpeff.interval.Chromosome;
import org.snpeff.interval.Marker;
import org.snpeff.interval.Variant;
import org.snpeff.interval.Variant.VariantType;
import org.snpeff.interval.VariantBnd;
import org.snpeff.snpEffect.LossOfFunction;
import org.snpeff.util.Gpr;
/**
* A VCF entry (a line) in a VCF file
* @author pablocingolani
*/
public class VcfEntry extends Marker implements Iterable<VcfGenotype> {
public enum AlleleFrequencyType {
Common, LowFrequency, Rare
}
public static final String FILTER_PASS = "PASS";
public static final char WITHIN_FIELD_SEP = ',';
public static final String SUB_FIELD_SEP = ";";
public static final String[] EMPTY_STRING_ARRAY = new String[0];
public static final double ALLELE_FEQUENCY_COMMON = 0.05;
public static final double ALLELE_FEQUENCY_LOW = 0.01;
public static final Pattern INFO_KEY_PATTERN = Pattern.compile("[\\p{Alpha}_][\\p{Alnum}._]*");
public static final String VCF_INFO_END = "END"; // Imprecise variants
// In order to report sequencing data evidence for both variant and non-variant positions in the genome, the VCF
// specification allows to represent blocks of reference-only calls in a single record using the END INFO tag, an idea
// originally introduced by the gVCF file format. The convention adopted here is to represent reference evidence as
// likelihoods against an unknown alternate allele. Think of this as the likelihood for reference as compared to any
// other possible alternate allele (both SNP, indel, or otherwise). A symbolic alternate allele <*> is used to represent
// this unspecified alternate allele
public static final String VCF_ALT_NON_REF = "<*>"; // See VCF 4.2 section "5.5 Representing unspecified alleles and REF-only blocks (gVCF)"
public static final String VCF_ALT_NON_REF_gVCF = "<NON_REF>"; // NON_REF tag for ALT field (only in gVCF fields)
public static final String VCF_ALT_MISSING_REF = "*"; // The '*' allele is reserved to indicate that the allele is missing due to a upstream deletion (see VCF 4.3 spec., ALT definition)
public static final String[] VCF_ALT_NON_REF_gVCF_ARRAY = { VCF_ALT_NON_REF_gVCF };
public static final String[] VCF_ALT_NON_REF_ARRAY = { VCF_ALT_NON_REF };
public static final String[] VCF_ALT_MISSING_REF_ARRAY = { VCF_ALT_MISSING_REF };
public static final String VCF_INFO_HOMS = "HO";
public static final String VCF_INFO_HETS = "HE";
public static final String VCF_INFO_NAS = "NA";
public static final String VCF_INFO_PRIVATE = "Private";
private static final Map<String, String> INFO_VALUE_ENCODE;
private static final long serialVersionUID = 4226374412681243433L;
static {
// Initialize VCF value encoding table
INFO_VALUE_ENCODE = new HashMap<>();
// INFO_VALUE_ENCODE.put("%3A", ":"); // This is used in genotype entries, not INFO entries.
INFO_VALUE_ENCODE.put("%3B", ";");
INFO_VALUE_ENCODE.put("%3D", "=");
// INFO_VALUE_ENCODE.put("%25", "%");
INFO_VALUE_ENCODE.put("%2C", ",");
INFO_VALUE_ENCODE.put("%0D", "\n");
INFO_VALUE_ENCODE.put("%0A", "\r");
INFO_VALUE_ENCODE.put("%09", "\t");
}
protected String[] alts;
protected String altStr;
protected String chromosomeName; // Original chromosome name
protected String filter;
protected String format;
protected String formatFields[];
protected String genotypeFields[]; // Raw fields from VCF file
protected String genotypeFieldsStr; // Raw fields from VCF file (one string, tab separated)
protected byte genotypeScores[];
protected HashMap<String, String> info;
protected String infoStr = "";
protected String line; // Line from VCF file
protected int lineNum; // Line number
protected Double quality;
protected String ref;
protected LinkedList<Variant> variants;
protected List<VcfEffect> vcfEffects;
protected VcfFileIterator vcfFileIterator; // Iterator where this entry was red from
protected ArrayList<VcfGenotype> vcfGenotypes = null;
/**
* Does 'value' represent an EMPTY / MISSING value in a VCF field?
* (or multiple MISSING comma-separated values)
*/
public static boolean isEmpty(String value) {
if (value == null || value.isEmpty() || value.equals(VcfFileIterator.MISSING)) return true;
if (value.indexOf(',') >= 0) {
// Multiple values, all of them MISSING?
String values[] = value.split(",");
for (String val : values)
if (!(val.isEmpty() || val.equals(VcfFileIterator.MISSING))) return false;
return true;
}
return false;
}
/**
* Make sure the INFO key matches the regular
* expression (as specified in VCF spec 4.3)
*/
public static boolean isValidInfoKey(String key) {
Matcher m = INFO_KEY_PATTERN.matcher(key);
return m.matches();
}
/**
* Check that this value can be added to an INFO field
* @return true if OK, false if invalid value
*/
public static boolean isValidInfoValue(String value) {
boolean invalid = ((value != null) && ((value.indexOf(' ') >= 0) || (value.indexOf(';') >= 0) || (value.indexOf('=') >= 0) || (value.indexOf('\t') >= 0) || (value.indexOf('\n') >= 0)));
return !invalid;
}
/**
* Decode INFO value
*/
public static String vcfInfoDecode(String str) {
if (str == null || str.isEmpty() || str.equals(".")) return str;
for (String encoded : INFO_VALUE_ENCODE.keySet())
str = str.replace(encoded, INFO_VALUE_ENCODE.get(encoded));
return str;
}
/**
* Encode a string to be used in an 'INFO' field value
* From the VCF 4.3 specification
* Characters with special meaning (such as field delimiters ';' in INFO or ':' FORMAT
* fields) must be represented using the capitalized percent encoding:
* %3A : (colon)
* %3B ; (semicolon)
* %3D = (equal sign)
* %25 % (percent sign)
* %2C , (comma)
* %0D CR
* %0A LF
* %09 TAB
*/
public static String vcfInfoEncode(String str) {
if (str == null || str.isEmpty() || str.equals(".")) return str;
for (String encoded : INFO_VALUE_ENCODE.keySet())
str = str.replace(INFO_VALUE_ENCODE.get(encoded), encoded);
return str.replaceAll(" ", "_"); // Transform spaces, if any
}
/**
* Return a string safe to be used in an 'INFO' field key
*/
public static String vcfInfoKeySafe(String str) {
if (str == null) return str;
str = str.replaceAll("[^a-zA-Z0-9_.]", "_");
char c0 = str.charAt(0);
if (c0 != '_' && !Character.isAlphabetic(c0)) str = '_' + str;
return str;
}
/**
* Return a string safe to be used in an 'INFO' field value
*/
public static String vcfInfoValueSafe(String str) {
if (str == null) return str;
return str.replaceAll("[ ,;|=()\t]", "_");
}
public VcfEntry(VcfFileIterator vcfFileIterator, Marker parent, String chromosomeName, int start, String id, String ref, String altsStr, double quality, String filterPass, String infoStr, String format) {
super(parent, start, start + ref.length() - 1, false, id);
this.chromosomeName = chromosomeName;
this.ref = ref;
parseAlts(altsStr);
this.quality = quality;
filter = filterPass;
this.infoStr = infoStr;
parseInfo();
this.format = format;
parseEnd(altsStr);
}
/**
* Create a line form a file iterator
*/
public VcfEntry(VcfFileIterator vcfFileIterator, String line, int lineNum, boolean parseNow) {
super(null, 0, 0, false, "");
this.vcfFileIterator = vcfFileIterator;
this.lineNum = lineNum;
this.line = line;
if (parseNow) parse();
}
/**
* Add string to FILTER field
*/
public void addFilter(String filterStr) {
// Get current value
if (filter.equals(".") || filter.equals(VcfEntry.FILTER_PASS)) filter = ""; // Empty?
// Append new value
filter += (!filter.isEmpty() ? ";" : "") + filterStr; // Add this filter to the not-passed list
}
/**
* Add a 'FORMAT' field
*/
public void addFormat(String formatName) {
if (format == null) format = "";
if (format.indexOf(formatName) >= 0) throw new RuntimeException("Format field '" + formatName + "' already exists!");
// Add to format
format += (format.endsWith(":") ? "" : ":") + formatName;
}
/**
* Add a genotype as a string
*/
public void addGenotype(String vcfGenotypeStr) {
if (vcfGenotypes == null) vcfGenotypes = new ArrayList<>();
if (format == null) format = "";
vcfGenotypes.add(new VcfGenotype(this, format, vcfGenotypeStr));
genotypeScores = null; // Reset or invalidate scores
}
/**
* Add a "key=value" tuple the info field
*
* @param key : INFO key name
* @param value : Can be null if it is a boolean field.
*/
public void addInfo(String key, String value) {
if (!isValidInfoKey(key)) throw new RuntimeException("Illegal INFO key / name. Key: \"" + key + "\" does not match regular expression ^[A-Za-z_][0-9A-Za-z_.]*$");
if (!isValidInfoValue(value)) throw new RuntimeException("No white-space, semi-colons, or equals-signs are permitted in INFO field values. Name:\"" + key + "\" Value:\"" + value + "\"");
// Remove previous 'key' for INFO field?
removeInfo(key);
// Is this a 'flag'?
boolean isFlag = false;
VcfHeader vcfHeader = vcfFileIterator.getVcfHeader();
if (vcfHeader != null) {
VcfHeaderInfo vcfHeaderInfo = vcfFileIterator.getVcfHeader().getVcfHeaderInfo(key);
isFlag = (vcfHeaderInfo != null) && (vcfHeaderInfo.getVcfInfoType() == VcfInfoType.Flag);
}
// Add to info hash (if available)
if (info != null) info.put(key, value);
// Append value to infoStr
String addInfoStr = key + (value != null && !isFlag ? "=" + value : ""); // String to append
if ((infoStr == null) || infoStr.isEmpty()) infoStr = addInfoStr;
else {
if (!infoStr.endsWith(SUB_FIELD_SEP)) infoStr += SUB_FIELD_SEP; // Do we need to add a semicolon?
infoStr += addInfoStr; // Add info string
}
}
/**
* Categorization by allele frequency
*/
public AlleleFrequencyType alleleFrequencyType() {
double maf = maf();
if (maf <= ALLELE_FEQUENCY_LOW) return AlleleFrequencyType.Rare;
if (maf <= ALLELE_FEQUENCY_COMMON) return AlleleFrequencyType.LowFrequency;
return AlleleFrequencyType.Common;
}
/**
* Is this entry heterozygous?
*
* Infer Hom/Her if there is only one sample in the file.
* Ohtherwise the field is null.
*/
public Boolean calcHetero() {
// No genotyping information? => Use number of ALT field
if (genotypeFieldsStr == null) return isMultiallelic();
Boolean isHetero = null;
// No genotype fields => Parse fields (we only parse them if there is only one GT field)
if (genotypeFields == null) {
// Are there more than two tabs? (i.e. more than one format field + one genotype field)
int countFields, fromIndex;
for (countFields = 0, fromIndex = 0; (fromIndex >= 0) && (countFields < 1); countFields++, fromIndex++)
fromIndex = genotypeFieldsStr.indexOf('\t', fromIndex);
// OK only one genotype field => Parse it in order to extract homo info.
if (countFields == 1) parseGenotypes();
}
// OK only one genotype field => calculate if it is heterozygous
if ((genotypeFields != null) && (genotypeFields.length == 1)) isHetero = getVcfGenotype(0).isHeterozygous();
return isHetero;
}
/**
* Perform several simple checks and report problems (if any).
*/
public String check() {
StringBuilder sb = new StringBuilder();
// Check REF
if (ref.indexOf(",") >= 0) sb.append("REF field has multiple entries (this is not allowed)\n");
// Check INFO fields
for (String infoName : getInfoKeys()) {
String err = checkInfo(infoName);
if (!err.isEmpty()) sb.append(err + "\n");
}
// Check genotypes
sb.append(checkGenotypes());
return sb.toString();
}
/**
* Check genotypes
*/
String checkGenotypes() {
StringBuilder err = new StringBuilder();
if (getVcfFileIterator() != null && getVcfFileIterator().getVcfHeader() != null) {
int numGt = getVcfGenotypes().size();
int numSamples = getVcfFileIterator().getVcfHeader().getNumberOfSamples();
if (numGt != numSamples) err.append("Number of genotypes (" + numGt + ") differs form the number of samples (" + numSamples + ")\n");
}
// Check that each genotype matches the number of alleles
int numAlts = getAlts().length;
int gtNum = 1;
for (VcfGenotype vgt : getVcfGenotypes()) {
int gts[] = vgt.getGenotype();
if (gts != null) {
for (int i = 0; i < gts.length; i++)
if (gts[i] > numAlts) err.append("Genotype number " + gtNum + " has genotype number '" + gts[i] + "', but there are only '" + numAlts + "' ALTs.\n");
}
gtNum++;
}
return err.toString();
}
/**
* Check info field
* Note: We report the first error we find
*/
String checkInfo(String infoName) {
if (infoName.isEmpty()) return "";
VcfHeaderInfo vcfInfo = getVcfInfo(infoName);
if (vcfInfo == null) return "Cannot find header for INFO field '" + infoName + "'";
// Split INFO value and match it to allele
String valsStr = getInfo(infoName);
if (valsStr == null) return ""; // INFO field not present, nothing to do
// Check values
String values[] = valsStr.split(",");
for (String val : values)
if (!VcfEntry.isValidInfoValue(val)) return "INFO field '" + infoName + "' has an invalid value '" + val + "' (no spaces, tabs, '=' or ';' are allowed)";
// Check number of INFO elements
if (vcfInfo.isNumberNumber() && vcfInfo.getNumber() != values.length) {
VcfInfoType type = vcfInfo.getVcfInfoType();
if (type == VcfInfoType.Flag && values.length == 1) ; // OK, flags must have one or zero values
else return "INFO filed '" + infoName + "' has 'Number=" + vcfInfo.getNumber() + "' in header, but it contains '" + values.length + "' elements.";
}
if (vcfInfo.isNumberAllAlleles() && values.length != (alts.length + 1)) return "INFO filed '" + infoName + "' has 'Number=R' in header, but it contains '" + values.length + "' elements when there are '" + alts.length + "' alleles (it should have '" + (alts.length + 1) + "' elements).";
if (vcfInfo.isNumberAllAlleles() && values.length != alts.length) return "INFO filed '" + infoName + "' has 'Number=A' in header, but it contains '" + values.length + "' elements when there are '" + alts.length + "' alleles.";
return "";
}
@Override
public Cds cloneShallow() {
throw new RuntimeException("Unimplemented!");
}
/**
* Compress genotypes into "HO/HE/NA" INFO fields
*/
public boolean compressGenotypes() {
if (getAlts().length > 1) return false;
StringBuilder homs = new StringBuilder();
StringBuilder hets = new StringBuilder();
StringBuilder nas = new StringBuilder();
// Add all genotype codes
int idx = 0;
for (VcfGenotype gen : getVcfGenotypes()) {
int score = gen.getGenotypeCode();
if (score == 0) {
; //Nothing to do
} else if (score < 0) nas.append((nas.length() > 0 ? "," : "") + idx);
else if (score == 1) hets.append((hets.length() > 0 ? "," : "") + idx);
else if (score == 2) homs.append((homs.length() > 0 ? "," : "") + idx);
else return false; // Cannot compress
idx++;
}
// Update INFO fields
if (homs.length() > 0) addInfo(VCF_INFO_HOMS, homs.toString());
if (hets.length() > 0) addInfo(VCF_INFO_HETS, hets.toString());
if (nas.length() > 0) addInfo(VCF_INFO_NAS, nas.toString());
// Nothing added? Add 'NAS' (as an indicator that it was compressed
if ((homs.length() == 0) && (hets.length() == 0) && (nas.length() == 0)) addInfo(VCF_INFO_NAS, null);
return true;
}
/**
* Remove a string from FILTER field
* @returns true if the value is removed
*/
public boolean delFilter(String filterStr) {
// Get current value
StringBuilder sbFilter = new StringBuilder();
// Split by semicolon and filter out the undesired values
boolean removed = false;
for (String f : filter.split(";")) {
if (!f.equals(filterStr)) sbFilter.append((sbFilter.length() > 0 ? ";" : "") + f); // Append if it does not match filterStr
else removed = true;
}
// Changed? Set new value
if (removed) filter = sbFilter.toString();
return removed;
}
/**
* Get index of matching ALT entry
* @return -1 if not found
*/
public int getAltIndex(String alt) {
for (int i = 0; i < alts.length; i++)
if (alts[i].equalsIgnoreCase(alt)) return i;
return -1;
}
public String[] getAlts() {
return alts;
}
/**
* Create a comma separated ALTS string
*/
public String getAltsStr() {
if (altStr != null) {
if (altStr.isEmpty()) return ".";
return altStr;
}
if (alts == null) return "";
StringBuilder sb = new StringBuilder();
for (String alt : alts)
sb.append(alt + " ");
altStr = sb.toString().trim().replace(' ', ',');
return altStr;
}
/**
* Original chromosome name (as it appeared in the VCF file)
*/
@Override
public String getChromosomeNameOri() {
return chromosomeName;
}
public String getFilter() {
return filter;
}
public String getFormat() {
return format;
}
public String[] getFormatFields() {
if (formatFields == null) {
if (format == null) formatFields = new String[0];
else formatFields = format.split(":");
}
return formatFields;
}
/**
* Return genotypes parsed as an array of codes
*/
public synchronized byte[] getGenotypesScores() {
if (genotypeScores != null) return genotypeScores;
// Not compressed? Parse codes
if (!isCompressedGenotypes()) {
List<VcfGenotype> vcfGts = getVcfGenotypes();
int numSamples = vcfGts.size();
genotypeScores = new byte[numSamples];
int idx = 0;
for (VcfGenotype vcfGt : vcfGts)
genotypeScores[idx++] = (byte) vcfGt.getGenotypeCode();
return genotypeScores;
}
//---
// Uncompress (HO/HE/NA in info fields)
//---
// Get 'sparse' matrix entries
String hoStr = getInfo(VCF_INFO_HOMS);
String heStr = getInfo(VCF_INFO_HETS);
String naStr = getInfo(VCF_INFO_NAS);
// Parse 'sparse' entries
int numSamples = getNumberOfSamples();
genotypeScores = new byte[numSamples];
parseSparseGt(naStr, genotypeScores, -1);
parseSparseGt(heStr, genotypeScores, 1);
parseSparseGt(hoStr, genotypeScores, 2);
return genotypeScores;
}
/**
* Get info string
*/
public String getInfo(String key) {
if (info == null) parseInfo();
return info.get(key);
}
/**
* Get info string for a specific allele
*/
public String getInfo(String key, String allele) {
if (info == null) parseInfo();
// Get INFO value
String infoStr = info.get(key);
if (infoStr == null) return null;
// Split INFO value and match it to allele
String infos[] = infoStr.split(",");
// INFO fields having number type 'R' (all alleles) should have one value for reference as well.
// So in those cases we must skip the first value
int firstAltIndex = 0;
VcfHeaderInfo vcfInfo = getVcfInfo(key);
if (vcfInfo != null && vcfInfo.isNumberAllAlleles()) {
firstAltIndex = 1;
// Are we looking for 'REF' information?
if (ref.equalsIgnoreCase(allele)) return infos[0];
}
// Find ALT matching allele
for (int i = 0, j = firstAltIndex; (i < alts.length) && (j < infos.length); i++, j++)
if (alts[i].equalsIgnoreCase(allele)) return infos[j];
return null;
}
/**
* Get an INFO field matching a variant
* @returns Field value (string) or null if there is no match
*/
public String getInfo(String key, Variant var) {
if (info == null) parseInfo();
// Get INFO value
String infoStr = info.get(key);
if (infoStr == null) return null;
// Split INFO value and match it to allele
String infos[] = infoStr.split(",");
// INFO fields having number type 'R' (all alleles) should have one value for reference as well.
// So in those cases we must skip the first value
int firstAltIndex = 0;
VcfHeaderInfo vcfInfo = getVcfInfo(key);
if (vcfInfo != null && vcfInfo.isNumberAllAlleles()) {
firstAltIndex = 1;
// Are we looking for 'REF' information? I.e. variant is not a variant)
if (!var.isVariant()) return infos[0];
}
// Look for genotype matching 'var'
int i = firstAltIndex;
String gtPrev = "";
for (Variant v : variants()) {
if (i >= infos.length) break;
if (var.equals(v)) return infos[i];
if (!v.getGenotype().equals(gtPrev)) i++; // Advance genotype counter
}
return null;
}
/**
* Does the entry exists?
*/
public boolean getInfoFlag(String key) {
if (info == null) parseInfo();
return info.containsKey(key);
}
/**
* Get info field as a 'double' number
* The norm specifies data type as 'FLOAT', that is why the name of this method might be not intuitive
*/
public double getInfoFloat(String key) {
if (info == null) parseInfo();
String f = info.get(key);
if (f == null) return Double.NaN;
return Gpr.parseDoubleSafe(f);
}
/**
* Get info field as an long number
* The norm specifies data type as 'INT', that is why the name of this method might be not intuitive
*/
public long getInfoInt(String key) {
if (info == null) parseInfo();
String i = info.get(key);
if (i == null) return 0;
return Gpr.parseLongSafe(i);
}
/**
* Get all keys available in the info field
*/
public Set<String> getInfoKeys() {
if (info == null) parseInfo();
return info.keySet();
}
/**
* Get the full (unparsed) INFO field
*/
public String getInfoStr() {
return infoStr;
}
/**
* Original VCF line (from file)
*/
public String getLine() {
return line;
}
public int getLineNum() {
return lineNum;
}
/**
* number of samples in this VCF file
*/
public int getNumberOfSamples() {
if (vcfFileIterator == null) return 0;
VcfHeader vh = vcfFileIterator.getVcfHeader();
if (vh == null) return 0;
return vh.getNumberOfSamples();
}
public double getQuality() {
return (quality != null ? quality : 0);
}
public String getRef() {
return ref;
}
public String getStr() {
return getChromosomeName() //
+ ":" + (start + 1) //
+ "_" + ref //
+ "/" + getAltsStr();
}
public List<VcfEffect> getVcfEffects() {
return getVcfEffects(null);
}
/**
* Parse 'EFF' info field and get a list of effects
*/
public synchronized List<VcfEffect> getVcfEffects(EffFormatVersion formatVersion) {
if (vcfEffects != null) return vcfEffects;
String effStr = null;
if (formatVersion == null) {
// Guess which INFO field could be
effStr = getInfo(EffFormatVersion.VCF_INFO_ANN_NAME);
if (effStr != null) {
formatVersion = EffFormatVersion.FORMAT_ANN; // Unspecied 'ANN' version
} else {
effStr = getInfo(EffFormatVersion.VCF_INFO_EFF_NAME);
if (effStr != null) formatVersion = EffFormatVersion.FORMAT_EFF; // Unspecied 'EFF' version
}
} else {
// Use corresponding INFO field
String effFieldName = VcfEffect.infoFieldName(formatVersion);
effStr = getInfo(effFieldName); // Get effect string from INFO field
}
// Create a list of effect
vcfEffects = new ArrayList<>();
// Note: An empty "EFF" string can be viewed as a FLAG type and transformed to a "true" value
if ((effStr == null) || effStr.isEmpty() || effStr.equals("true")) return vcfEffects;
// Add each effect
String effs[] = effStr.split(",");
for (String eff : effs) {
VcfEffect veff = new VcfEffect(eff, formatVersion); // Create and parse this effect
vcfEffects.add(veff);
}
return vcfEffects;
}
public VcfFileIterator getVcfFileIterator() {
return vcfFileIterator;
}
public VcfGenotype getVcfGenotype(int index) {
return getVcfGenotypes().get(index);
}
public List<VcfGenotype> getVcfGenotypes() {
if (vcfGenotypes == null) parseGenotypes();
return vcfGenotypes;
}
/**
* Get VcfInfo type for a given ID
*/
public VcfHeaderInfo getVcfInfo(String id) {
return vcfFileIterator.getVcfHeader().getVcfHeaderInfo(id);
}
/**
* Get Info number for a given ID
*/
public VcfInfoType getVcfInfoNumber(String id) {
VcfHeaderInfo vcfInfo = vcfFileIterator.getVcfHeader().getVcfHeaderInfo(id);
if (vcfInfo == null) return null;
return vcfInfo.getVcfInfoType();
}
public boolean hasField(String filedName) {
return vcfFileIterator.getVcfHeader().getVcfHeaderInfo(filedName) != null;
}
public boolean hasGenotypes() {
return ((vcfGenotypes != null) && (vcfGenotypes.size() > 0)) || (genotypeFieldsStr != null);
}
public boolean hasInfo(String infoFieldName) {
if (info == null) parseInfo();
return info.containsKey(infoFieldName);
}
public boolean hasQuality() {
return quality != null;
}
/**
* Is this bi-allelic (based ONLY on the number of ALTs)
* WARINIG: You should use 'calcHetero()' method for a more precise calculation.
*/
public boolean isBiAllelic() {
if (alts == null) return false;
return alts.length == 1; // Only one ALT option? => homozygous
}
/**
* Do we have compressed genotypes in "HO,HE,NA" INFO fields?
*/
public boolean isCompressedGenotypes() {
return !hasGenotypes() && (getNumberOfSamples() > 0) && (hasInfo(VCF_INFO_HOMS) || hasInfo(VCF_INFO_HETS) || hasInfo(VCF_INFO_NAS));
}
public boolean isFilterPass() {
return filter.equals("PASS");
}
/**
* Is this multi-allelic (based ONLY on the number of ALTs)
* WARINIG: You should use 'calcHetero()' method for a more precise calculation.
*/
public boolean isMultiallelic() {
if (alts == null) return false;
return alts.length > 1; // More than one ALT option? => not homozygous
}
@Override
protected boolean isShowWarningIfParentDoesNotInclude() {
return false;
}
/**
* Is thins a VCF entry with a single SNP?
*/
public boolean isSingleSnp() {
return ref != null //
&& altStr != null //
&& ref.length() == 1 //
&& altStr.length() == 1 //
&& !ref.equalsIgnoreCase(altStr) //
;
}
/**
* Is this variant a singleton (appears only in one genotype)
*/
public boolean isSingleton() {
int count = 0;
for (VcfGenotype gen : this) {
if (gen.isVariant()) count++;
if (count > 1) return false;
}
return count == 1;
}
/**
* Is this a change or are the ALTs actually the same as the reference
*/
public boolean isVariant() {
if (alts == null || alts.length == 0) return false;
// Is any ALT is variant?
for (String alt : alts)
if (isVariant(alt)) return true;
return false;
}
/**
* Is this ALT string a variant?
*/
public boolean isVariant(String alt) {
return alt != null //
&& !alt.isEmpty() //
&& !alt.equals(VcfFileIterator.MISSING) // Missing ALT (".")?
&& !alt.equals(VCF_ALT_NON_REF) // '*'
&& !alt.equals(VCF_ALT_NON_REF_gVCF) // '<NON_REF>'
&& !alt.equals(VCF_ALT_MISSING_REF) // '<*>'
&& !alt.equals(ref) // Is ALT different than REF?
;
}
@Override
public Iterator<VcfGenotype> iterator() {
return getVcfGenotypes().iterator();
}
/**
* Calculate Minor allele count
*/
public int mac() {
long ac = -1;
// Do we have it annotated as AF or MAF?
if (hasField("MAC")) return (int) getInfoInt("MAC");
else if (hasField("AC")) ac = getInfoInt("AC");
// AC not found (or doesn't make sense)
if (ac <= 0) {
// We have to calculate
ac = 0;
for (byte genCode : getGenotypesScores())
if (genCode > 0) ac += genCode; // Don't count '-1' (i.e. missing genotypes)
}
// How many samples (alleles) do we have?
int numSamples = 0;
List<String> sampleNames = vcfFileIterator.getVcfHeader().getSampleNames();
if (sampleNames != null) numSamples = sampleNames.size();
else numSamples = getVcfGenotypes().size();
// Always use the Minor Allele Count
if ((numSamples > 1) && (ac > numSamples)) ac = 2 * numSamples - ac;
return (int) ac;
}
/**
* Calculate Minor allele frequency
*/
public double maf() {
double maf = -1;
// Do we have it annotated as AF or MAF?
if (hasField("AF")) maf = getInfoFloat("AF");
else if (hasField("MAF")) maf = getInfoFloat("MAF");
else {
// No annotations, we have to calculate
int ac = 0, count = 0;
for (VcfGenotype gen : this) {
count += 2;
int genCode = gen.getGenotypeCode();
if (genCode > 0) ac += genCode;
}
maf = ((double) ac) / count;
}
// Always use the Minor Allele Frequency
if (maf > 0.5) maf = 1.0 - maf;
return maf;
}
/**
* Parse a 'line' from a 'vcfFileIterator'
*/
public void parse() {
// Parse line
String fields[] = line.split("\t", 10); // Only pare the fist 9 fields (i.e. do not parse genotypes)
// Is line OK?
if (fields.length >= 4) {
// Chromosome and position. VCF files are one-base, so inOffset should be 1.
chromosomeName = fields[0].trim();
// Chromosome
Chromosome chromo = vcfFileIterator.getChromosome(chromosomeName);
parent = chromo;
vcfFileIterator.sanityCheckChromo(chromosomeName, chromo); // Sanity check
// Start
start = vcfFileIterator.parsePosition(vcfFileIterator.readField(fields, 1));
// ID (e.g. might indicate dbSnp)
id = vcfFileIterator.readField(fields, 2);
// REF
ref = vcfFileIterator.readField(fields, 3).toUpperCase(); // Reference and change
strandMinus = false; // Strand is always positive (defined in VCF spec.)
// ALT
altStr = vcfFileIterator.readField(fields, 4).toUpperCase();
parseAlts(altStr);
// Quality
String qStr = vcfFileIterator.readField(fields, 5);
if (!qStr.isEmpty()) quality = Gpr.parseDoubleSafe(qStr);
else quality = null;
// Filter
filter = vcfFileIterator.readField(fields, 6); // Filter parameters
// INFO fields
infoStr = vcfFileIterator.readField(fields, 7);
info = null;
// Start & End coordinates are anchored to the reference genome, thus based on REF field (ALT is not taken into account)
parseEnd(altStr);