-
Notifications
You must be signed in to change notification settings - Fork 309
/
VariantContextConverter.scala
2426 lines (2149 loc) · 79.6 KB
/
VariantContextConverter.scala
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
/**
* Licensed to Big Data Genomics (BDG) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The BDG licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bdgenomics.adam.converters
import com.google.common.collect.ImmutableList
import grizzled.slf4j.Logging
import htsjdk.samtools.ValidationStringency
import htsjdk.variant.variantcontext.{
Allele,
GenotypeBuilder,
GenotypeLikelihoods,
VariantContextBuilder,
Genotype => HtsjdkGenotype,
VariantContext => HtsjdkVariantContext
}
import htsjdk.variant.vcf.{
VCFCompoundHeaderLine,
VCFConstants,
VCFFormatHeaderLine,
VCFHeader,
VCFHeaderLine,
VCFHeaderLineCount,
VCFHeaderLineType,
VCFInfoHeaderLine
}
import java.util.Collections
import org.apache.hadoop.conf.Configuration
import org.bdgenomics.adam.models.{
SequenceDictionary,
VariantContext => ADAMVariantContext
}
import org.bdgenomics.adam.util.PhredUtils
import org.bdgenomics.formats.avro._
import org.slf4j.Logger
import scala.annotation.tailrec
import scala.collection.JavaConversions._
import scala.collection.mutable
/**
* Object for converting between htsjdk and ADAM VariantContexts.
*
* Handles Variant, Genotype, Allele, and various genotype annotation
* conversions. Does not handle Variant annotations. Genotype annotations are
* annotations in the VCF GT field while Variant annotations are annotations
* contained in the VCF INFO field.
*/
object VariantContextConverter {
/**
* If set to true, this property will ensure that the variant.annotation field
* in the Genotype record is populated after conversion from an htsjdk
* VariantContext. By default, this property is false.
*/
val nestAnnotationInGenotypesProperty = "org.bdgenomics.adam.converters.VariantContextConverter.NEST_ANN_IN_GENOTYPES"
/**
* Sets the value of the nest annotation in genotypes property.
*
* @param conf Hadoop configuration to set the property in.
* @param populateNestedAnn If true, the nested field is populated.
*/
def setNestAnnotationInGenotypesProperty(conf: Configuration,
populateNestedAnn: Boolean) {
conf.setBoolean(nestAnnotationInGenotypesProperty, populateNestedAnn)
}
/**
* Gets the value of the nest annotation in genotypes property.
*
* @param conf Hadoop configuration to set the property in.
* @return Returns whether or not to nest the variant annotation under each
* genotype record.
*/
private[adam] def getNestAnnotationInGenotypesProperty(
conf: Configuration): Boolean = {
conf.getBoolean(nestAnnotationInGenotypesProperty, false)
}
/**
* Representation for an unknown non-ref/symbolic allele in VCF.
*/
private val NON_REF_ALLELE = Allele.create("<NON_REF>", false /* !Reference */ )
/**
* The index in the Avro genotype record for the splitFromMultiAllelec field.
*
* This field is true if the VCF site was not biallelic.
*/
private lazy val splitFromMultiAllelicField = Genotype.SCHEMA$.getField("splitFromMultiAllelic")
/**
* One conversion method for each way of representing an Allele
*
* An htsjdk Allele can represent a reference or alternate allele call, or a
* site where no call could be made. If the allele is an alternate allele, we
* check to see if this matches the primary alt allele at the site before
* deciding to tag it as a primary alt (Alt) or a secondary alt (OtherAlt).
*
* @param vc The underlying VariantContext for the site.
* @param allele The allele we are converting.
* @return The Avro representation for this allele.
*/
private def convertAllele(vc: HtsjdkVariantContext, allele: Allele): GenotypeAllele = {
if (allele.isNoCall) GenotypeAllele.NO_CALL
else if (allele.isReference) GenotypeAllele.REF
else if (allele == NON_REF_ALLELE || !vc.hasAlternateAllele(allele)) GenotypeAllele.OTHER_ALT
else GenotypeAllele.ALT
}
/**
* Converts an allele string from an avro Variant into an htsjdk Allele.
*
* @param allele String representation of the allele. If null, we return an
* empty option (None).
* @param isRef True if this allele is the reference allele. Default is false.
* @return If the allele is defined, returns a wrapped allele. Else, returns
* a None.
*/
private def convertAlleleOpt(allele: String, isRef: Boolean = false): Option[Allele] = {
if (allele == null) {
None
} else {
Some(Allele.create(allele, isRef))
}
}
private val OPT_NON_REF = Some(Allele.create("<NON_REF>", false))
private def optNonRef(v: Variant, hasNonRefModel: Boolean): Option[Allele] = {
if (hasNonRefModel || v.getAlternateAllele == null) {
OPT_NON_REF
} else {
None
}
}
/**
* Converts the alleles in a variant into a Java collection of htsjdk alleles.
*
* @param v Avro model of the variant at a site.
* @param hasNonRefModel Does this site have non-reference model likelihoods
* attached?
* @return Returns a Java collection representing the reference allele and any
* alternate allele at the site.
*/
private def convertAlleles(v: Variant, hasNonRefModel: Boolean): java.util.Collection[Allele] = {
val asSeq = Seq(convertAlleleOpt(v.getReferenceAllele, true),
convertAlleleOpt(v.getAlternateAllele),
optNonRef(v, hasNonRefModel)).flatten
asSeq
}
/**
* Emits a list of htsjdk alleles for the alleles present at a genotyped site.
*
* Given an avro description of a Genotype, returns the variants called at the
* site as a Java List of htsjdk alleles. This maps over all of the called
* alleles at the site and returns their htsjdk representation.
*
* @param g The genotype call at a site for a single sample.
* @return Returns the called alleles at this site.
*/
private def convertAlleles(g: Genotype): java.util.List[Allele] = {
var alleles = g.getAlleles
if (alleles == null) return Collections.emptyList[Allele]
else g.getAlleles.map {
case GenotypeAllele.NO_CALL | GenotypeAllele.OTHER_ALT => Allele.NO_CALL
case GenotypeAllele.REF => Allele.create(g.getVariant.getReferenceAllele, true)
case GenotypeAllele.ALT => Allele.create(g.getVariant.getAlternateAllele)
}
}
def cleanAndMixInSupportedLines(
headerLines: Seq[VCFHeaderLine],
stringency: ValidationStringency,
log: Logger): Seq[VCFHeaderLine] = {
// dedupe
val deduped = headerLines.distinct
def auditLine(line: VCFCompoundHeaderLine,
defaultLine: VCFCompoundHeaderLine,
replaceFn: (String, VCFCompoundHeaderLine) => VCFCompoundHeaderLine): Option[VCFCompoundHeaderLine] = {
if (line.getType != defaultLine.getType) {
val msg = "Field type for provided header line (%s) does not match supported line (%s)".format(
line, defaultLine)
if (stringency == ValidationStringency.STRICT) {
throw new IllegalArgumentException(msg)
} else {
if (stringency == ValidationStringency.LENIENT) {
log.warn(msg)
}
Some(replaceFn("BAD_%s".format(line.getID), line))
}
} else {
None
}
}
// remove our supported header lines
deduped.flatMap(line => line match {
case fl: VCFFormatHeaderLine => {
val key = fl.getID
DefaultHeaderLines.formatHeaderLines
.find(_.getID == key)
.fold(Some(fl).asInstanceOf[Option[VCFCompoundHeaderLine]])(defaultLine => {
auditLine(fl, defaultLine, (newId, oldLine) => {
if (oldLine.getCountType == VCFHeaderLineCount.INTEGER) {
new VCFFormatHeaderLine(newId,
oldLine.getCount,
oldLine.getType,
oldLine.getDescription)
} else {
new VCFFormatHeaderLine(newId,
oldLine.getCountType,
oldLine.getType,
oldLine.getDescription)
}
})
})
}
case il: VCFInfoHeaderLine => {
val key = il.getID
DefaultHeaderLines.infoHeaderLines
.find(_.getID == key)
.fold(Some(il).asInstanceOf[Option[VCFCompoundHeaderLine]])(defaultLine => {
auditLine(il, defaultLine, (newId, oldLine) => {
if (oldLine.getCountType == VCFHeaderLineCount.INTEGER) {
new VCFInfoHeaderLine(newId,
oldLine.getCount,
oldLine.getType,
oldLine.getDescription)
} else {
new VCFInfoHeaderLine(newId,
oldLine.getCountType,
oldLine.getType,
oldLine.getDescription)
}
})
})
}
case l => {
Some(l)
}
}) ++ DefaultHeaderLines.allHeaderLines
}
/**
* Return the header lines in the specified VCF file header.
*
* @param header VCF file header
* @return the header lines in the specified VCF file header
*/
def headerLines(header: VCFHeader): Seq[VCFHeaderLine] = {
(header.getFilterLines ++
header.getFormatHeaderLines ++
header.getInfoHeaderLines ++
header.getOtherHeaderLines)
}
/**
* Return the references in the specified VCF file header.
*
* @param header VCF file header
* @return the references in the specified VCF file header
*/
def references(header: VCFHeader): SequenceDictionary = {
SequenceDictionary.fromVCFHeader(header)
}
/**
* Return the samples in the specified VCF file header.
*
* @param header VCF file header
* @return the samples in the specified VCF file header
*/
def samples(header: VCFHeader): Seq[Sample] = {
asScalaBuffer(header.getGenotypeSamples)
.map(s => {
Sample.newBuilder()
.setId(s)
.build()
})
}
def apply(headerLines: Seq[VCFHeaderLine],
stringency: ValidationStringency,
conf: Configuration): VariantContextConverter = {
new VariantContextConverter(headerLines,
stringency,
getNestAnnotationInGenotypesProperty(conf))
}
}
/**
* This class converts VCF data to and from ADAM. This translation occurs at the
* abstraction level of the htsjdk VariantContext which represents VCF data, and
* at the ADAMVariantContext level, which aggregates ADAM
* variant/genotype/annotation data together.
*
* If a genotype annotation has a corresponding set of fields in the VCF standard,
* a conversion to/from the htsjdk VariantContext should be implemented in this
* class.
*/
class VariantContextConverter(
headerLines: Seq[VCFHeaderLine],
stringency: ValidationStringency,
setNestedAnnotationInGenotype: Boolean) extends Serializable with Logging {
import VariantContextConverter._
// format fns htsjdk --> bdg, extract fns bdg --> htsjdk
private val variantFormatFn = makeVariantFormatFn(headerLines, stringency)
private val variantExtractFn = makeVariantExtractFn(headerLines)
private val genotypeFormatFn = makeGenotypeFormatFn(headerLines)
private val genotypeExtractFn = makeGenotypeExtractFn(headerLines)
/**
* Converts a Scala float to a Java float.
*
* @param f Scala floating point value.
* @return Java floating point value.
*/
private def jFloat(f: Float): java.lang.Float = f
/**
* Converts a Scala double to a Java double.
*
* @param f Scala double precision floating point value.
* @return Java double precision floating point value.
*/
private def jDouble(f: Double): java.lang.Double = f
private def genotypeVariant(coreVariant: Variant,
fullVariant: Variant): Variant = {
if (setNestedAnnotationInGenotype) {
fullVariant
} else {
coreVariant
}
}
/**
* Converts a htsjdk variant context into one or more ADAM variant context(s).
*
* @param vc htsjdk variant context to convert.
* @return The specified htsjdk variant context converted into one or more ADAM variant context(s)
*/
def convert(
vc: HtsjdkVariantContext): Seq[ADAMVariantContext] = {
try {
vc.getAlternateAlleles.toList match {
case List(NON_REF_ALLELE) | List() => {
val (coreVariant, variant) = variantFormatFn(vc, None, 0, false)
val v = genotypeVariant(coreVariant, variant)
val genotypes = vc.getGenotypes.map(g => {
genotypeFormatFn(g, v, NON_REF_ALLELE, 0, Some(1), false)
})
return Seq(ADAMVariantContext(variant, genotypes))
}
case List(allele) => {
require(
allele.isNonReference,
"Assertion failed when converting: " + vc.toString
)
val (coreVariant, variant) = variantFormatFn(vc, Some(allele.getDisplayString), 0, false)
val v = genotypeVariant(coreVariant, variant)
val genotypes = vc.getGenotypes.map(g => {
genotypeFormatFn(g, v, allele, 1, None, false)
})
return Seq(ADAMVariantContext(variant, genotypes))
}
case List(allele, NON_REF_ALLELE) => {
require(
allele.isNonReference,
"Assertion failed when converting: " + vc.toString
)
val (coreVariant, variant) = variantFormatFn(vc, Some(allele.getDisplayString), 0, false)
val v = genotypeVariant(coreVariant, variant)
val genotypes = vc.getGenotypes.map(g => {
genotypeFormatFn(g, v, allele, 1, Some(2), false)
})
return Seq(ADAMVariantContext(variant, genotypes))
}
case _ => {
val vcb = new VariantContextBuilder(vc)
// is the last allele the non-ref allele?
val alleles = vc.getAlternateAlleles.toSeq
val referenceModelIndex = if (alleles.nonEmpty && alleles.last == NON_REF_ALLELE) {
Some(alleles.length)
} else {
None
}
val altAlleles = if (referenceModelIndex.isDefined) {
alleles.dropRight(1)
} else {
alleles
}
return altAlleles.map(allele => {
val idx = vc.getAlleleIndex(allele)
require(idx >= 1, "Unexpected index for alternate allele: " + vc.toString)
// variant annotations only contain values for alternate alleles so
// we need to subtract one from real index
val variantIdx = idx - 1
val (coreVariant, variant) = variantFormatFn(vc,
Some(allele.getDisplayString),
variantIdx,
true)
val v = genotypeVariant(coreVariant, variant)
val genotypes = vc.getGenotypes.map(g => {
genotypeFormatFn(g, v, allele, idx, referenceModelIndex, true)
})
ADAMVariantContext(variant, genotypes)
})
}
}
} catch {
case t: Throwable => {
if (stringency == ValidationStringency.STRICT) {
throw t
} else {
if (stringency == ValidationStringency.LENIENT) {
logger.warn("Caught exception %s when converting %s.".format(t, vc))
}
Seq.empty
}
}
}
}
/**
* Split the htsjdk variant context ID field into an array of names.
*
* @param vc htsjdk variant context
* @return Returns an Option wrapping an array of names split from the htsjdk
* variant context ID field
*/
private def splitIds(vc: HtsjdkVariantContext): Option[java.util.List[String]] = {
if (vc.hasID()) {
Some(ImmutableList.copyOf(vc.getID().split(VCFConstants.ID_FIELD_SEPARATOR)))
} else {
None
}
}
/**
* Join the array of variant names into a string for the htsjdk variant context ID field.
*
* @param variant variant
* @return Returns an Option wrapping a string for the htsjdk variant context ID field joined
* from the array of variant names
*/
private def joinNames(variant: Variant): Option[String] = {
if (variant.getNames != null && variant.getNames.nonEmpty) {
Some(variant.getNames.mkString(VCFConstants.ID_FIELD_SEPARATOR))
} else {
None
}
}
// htsjdk --> variant format functions
private[converters] def formatNames(
vc: HtsjdkVariantContext,
vb: Variant.Builder): Variant.Builder = {
splitIds(vc).fold(vb)(vb.setNames)
}
private[converters] def formatQuality(
vc: HtsjdkVariantContext,
vb: Variant.Builder): Variant.Builder = {
if (vc.hasLog10PError) {
vb.setQuality(vc.getPhredScaledQual)
} else {
vb
}
}
private[converters] def formatFilters(
vc: HtsjdkVariantContext,
vb: Variant.Builder): Variant.Builder = {
vb.setFiltersApplied(vc.filtersWereApplied)
if (vc.filtersWereApplied) {
vb.setFiltersPassed(!vc.isFiltered)
}
if (vc.isFiltered) {
vb.setFiltersFailed(new java.util.ArrayList(vc.getFilters))
}
vb
}
private val variantFormatFns: Iterable[(HtsjdkVariantContext, Variant.Builder) => Variant.Builder] = Iterable(
formatNames(_, _),
formatQuality(_, _),
formatFilters(_, _)
)
// variant --> htsjdk extract functions
private[converters] def extractNames(
v: Variant,
vcb: VariantContextBuilder): VariantContextBuilder = {
joinNames(v).fold(vcb.noID())(vcb.id)
}
private[converters] def extractQuality(
v: Variant,
vcb: VariantContextBuilder): VariantContextBuilder = {
if (v.getQuality != null) {
vcb.log10PError(-v.getQuality / 10.0)
} else {
vcb
}
}
private[converters] def extractFilters(
v: Variant,
vcb: VariantContextBuilder): VariantContextBuilder = {
Option(v.getFiltersApplied)
.filter(ft => ft)
.map(applied => {
Option(v.getFiltersPassed).map(passed => {
if (passed) {
vcb.passFilters
} else {
val failedFilters = v.getFiltersFailed
require(failedFilters.nonEmpty,
"Variant marked as filtered, but no failed filters listed in %s.".format(v))
vcb.filters(failedFilters.toSet)
}
}).getOrElse({
throw new IllegalArgumentException("Filters were applied but filters passed is null in %s.".format(v))
})
}).getOrElse(vcb.unfiltered)
}
private val variantExtractFns: Iterable[(Variant, VariantContextBuilder) => VariantContextBuilder] = Iterable(
extractNames(_, _),
extractQuality(_, _),
extractFilters(_, _)
)
// htsjdk --> variant annotation format functions
private[converters] def formatAncestralAllele(
vc: HtsjdkVariantContext,
vab: VariantAnnotation.Builder,
v: Variant,
index: Int): VariantAnnotation.Builder = {
Option(vc.getAttributeAsString("AA", null))
.fold(vab)(vab.setAncestralAllele)
}
private[converters] def formatDbSnp(
vc: HtsjdkVariantContext,
vab: VariantAnnotation.Builder,
v: Variant,
index: Int): VariantAnnotation.Builder = {
Option(vc.getAttribute("DB").asInstanceOf[java.lang.Boolean])
.fold(vab)(vab.setDbSnp)
}
private[converters] def formatHapMap2(
vc: HtsjdkVariantContext,
vab: VariantAnnotation.Builder,
v: Variant,
index: Int): VariantAnnotation.Builder = {
Option(vc.getAttribute("H2").asInstanceOf[java.lang.Boolean])
.fold(vab)(vab.setHapMap2)
}
private[converters] def formatHapMap3(
vc: HtsjdkVariantContext,
vab: VariantAnnotation.Builder,
v: Variant,
index: Int): VariantAnnotation.Builder = {
Option(vc.getAttribute("H3").asInstanceOf[java.lang.Boolean])
.fold(vab)(vab.setHapMap3)
}
private[converters] def formatValidated(
vc: HtsjdkVariantContext,
vab: VariantAnnotation.Builder,
v: Variant,
index: Int): VariantAnnotation.Builder = {
Option(vc.getAttribute("VALIDATED").asInstanceOf[java.lang.Boolean])
.fold(vab)(vab.setValidated)
}
private[converters] def formatThousandGenomes(
vc: HtsjdkVariantContext,
vab: VariantAnnotation.Builder,
v: Variant,
index: Int): VariantAnnotation.Builder = {
Option(vc.getAttribute("1000G").asInstanceOf[java.lang.Boolean])
.fold(vab)(vab.setThousandGenomes)
}
private[converters] def formatSomatic(
vc: HtsjdkVariantContext,
vab: VariantAnnotation.Builder,
v: Variant,
index: Int): VariantAnnotation.Builder = {
// default somatic to false if unspecified
Option(vc.getAttribute("SOMATIC").asInstanceOf[java.lang.Boolean])
.fold(vab.setSomatic(false))(vab.setSomatic)
}
private[converters] def formatAlleleCount(
vc: HtsjdkVariantContext,
vab: VariantAnnotation.Builder,
v: Variant,
index: Int): VariantAnnotation.Builder = {
val ac = vc.getAttributeAsList("AC")
if (ac.size > index) {
vab.setAlleleCount(toInt(ac.get(index)))
}
vab
}
private[converters] def formatAlleleFrequency(
vc: HtsjdkVariantContext,
vab: VariantAnnotation.Builder,
v: Variant,
index: Int): VariantAnnotation.Builder = {
val af = vc.getAttributeAsList("AF")
if (af.size > index) {
vab.setAlleleFrequency(toFloat(af.get(index)))
}
vab
}
private[converters] def formatCigar(
vc: HtsjdkVariantContext,
vab: VariantAnnotation.Builder,
v: Variant,
index: Int): VariantAnnotation.Builder = {
val cigar = vc.getAttributeAsList("CIGAR")
if (cigar.size > index) {
vab.setCigar(asString(cigar.get(index)))
}
vab
}
private[converters] def formatReadDepth(
vc: HtsjdkVariantContext,
vab: VariantAnnotation.Builder,
v: Variant,
index: Int): VariantAnnotation.Builder = {
val ad = vc.getAttributeAsList("AD")
if (ad.size > (index + 1)) {
vab.setReferenceReadDepth(toInt(ad.get(0)))
vab.setReadDepth(toInt(ad.get(index + 1)))
}
vab
}
private[converters] def formatForwardReadDepth(
vc: HtsjdkVariantContext,
vab: VariantAnnotation.Builder,
v: Variant,
index: Int): VariantAnnotation.Builder = {
val adf = vc.getAttributeAsList("ADF")
if (adf.size > (index + 1)) {
vab.setReferenceForwardReadDepth(toInt(adf.get(0)))
vab.setForwardReadDepth(toInt(adf.get(index + 1)))
}
vab
}
private[converters] def formatReverseReadDepth(
vc: HtsjdkVariantContext,
vab: VariantAnnotation.Builder,
v: Variant,
index: Int): VariantAnnotation.Builder = {
val adr = vc.getAttributeAsList("ADR")
if (adr.size > (index + 1)) {
vab.setReferenceReverseReadDepth(toInt(adr.get(0)))
vab.setReverseReadDepth(toInt(adr.get(index + 1)))
}
vab
}
private[converters] def formatTranscriptEffects(
vc: HtsjdkVariantContext,
vab: VariantAnnotation.Builder,
v: Variant,
index: Int): VariantAnnotation.Builder = {
TranscriptEffectConverter.convertToTranscriptEffects(v, vc)
.fold(vab)(vab.setTranscriptEffects(_))
}
private val variantAnnotationFormatFns: Iterable[(HtsjdkVariantContext, VariantAnnotation.Builder, Variant, Int) => VariantAnnotation.Builder] = Iterable(
formatAncestralAllele(_, _, _, _),
formatDbSnp(_, _, _, _),
formatHapMap2(_, _, _, _),
formatHapMap3(_, _, _, _),
formatValidated(_, _, _, _),
formatThousandGenomes(_, _, _, _),
formatSomatic(_, _, _, _),
formatAlleleCount(_, _, _, _),
formatAlleleFrequency(_, _, _, _),
formatCigar(_, _, _, _),
formatReadDepth(_, _, _, _),
formatForwardReadDepth(_, _, _, _),
formatReverseReadDepth(_, _, _, _),
formatTranscriptEffects(_, _, _, _)
)
// variant annotation --> htsjdk extract functions
private[converters] def extractAncestralAllele(
va: VariantAnnotation,
vcb: VariantContextBuilder): VariantContextBuilder = {
Option(va.getAncestralAllele).fold(vcb)(vcb.attribute("AA", _))
}
private[converters] def extractDbSnp(
va: VariantAnnotation,
vcb: VariantContextBuilder): VariantContextBuilder = {
Option(va.getDbSnp).fold(vcb)(vcb.attribute("DB", _))
}
private[converters] def extractHapMap2(
va: VariantAnnotation,
vcb: VariantContextBuilder): VariantContextBuilder = {
Option(va.getHapMap2).fold(vcb)(vcb.attribute("H2", _))
}
private[converters] def extractHapMap3(
va: VariantAnnotation,
vcb: VariantContextBuilder): VariantContextBuilder = {
Option(va.getHapMap3).fold(vcb)(vcb.attribute("H3", _))
}
private[converters] def extractValidated(
va: VariantAnnotation,
vcb: VariantContextBuilder): VariantContextBuilder = {
Option(va.getValidated).fold(vcb)(vcb.attribute("VALIDATED", _))
}
private[converters] def extractThousandGenomes(
va: VariantAnnotation,
vcb: VariantContextBuilder): VariantContextBuilder = {
Option(va.getThousandGenomes).fold(vcb)(vcb.attribute("1000G", _))
}
private[converters] def extractSomatic(
va: VariantAnnotation,
vcb: VariantContextBuilder): VariantContextBuilder = {
Option(va.getSomatic).fold(vcb)(vcb.attribute("SOMATIC", _))
}
private[converters] def extractAlleleCount(
va: VariantAnnotation,
vcb: VariantContextBuilder): VariantContextBuilder = {
Option(va.getAlleleCount).fold(vcb)(i => vcb.attribute("AC", i.toString))
}
private[converters] def extractAlleleFrequency(
va: VariantAnnotation,
vcb: VariantContextBuilder): VariantContextBuilder = {
Option(va.getAlleleFrequency).fold(vcb)(f => vcb.attribute("AF", f.toString))
}
private[converters] def extractCigar(
va: VariantAnnotation,
vcb: VariantContextBuilder): VariantContextBuilder = {
Option(va.getCigar).fold(vcb)(vcb.attribute("CIGAR", _))
}
private[converters] def extractReadDepth(
va: VariantAnnotation,
vcb: VariantContextBuilder): VariantContextBuilder = {
(Option(va.getReferenceReadDepth), Option(va.getReadDepth)) match {
case (Some(ref), Some(alt)) => vcb.attribute("AD", ImmutableList.of(ref.toString, alt.toString))
case (None, Some(_)) => throw new IllegalArgumentException("Read depth specified without reference read depth")
case (Some(_), None) => throw new IllegalArgumentException("Reference read depth specified without read depth")
case _ =>
}
vcb
}
private[converters] def extractForwardReadDepth(
va: VariantAnnotation,
vcb: VariantContextBuilder): VariantContextBuilder = {
(Option(va.getReferenceForwardReadDepth), Option(va.getForwardReadDepth)) match {
case (Some(ref), Some(alt)) => vcb.attribute("ADF", ImmutableList.of(ref.toString, alt.toString))
case (None, Some(_)) => throw new IllegalArgumentException("Forward read depth specified without reference forward read depth")
case (Some(_), None) => throw new IllegalArgumentException("Reference forward read depth specified without forward read depth")
case _ =>
}
vcb
}
private[converters] def extractReverseReadDepth(
va: VariantAnnotation,
vcb: VariantContextBuilder): VariantContextBuilder = {
(Option(va.getReferenceReverseReadDepth), Option(va.getReverseReadDepth)) match {
case (Some(ref), Some(alt)) => vcb.attribute("ADR", ImmutableList.of(ref.toString, alt.toString))
case (None, Some(_)) => throw new IllegalArgumentException("Reverse read depth specified without reference reverse read depth")
case (Some(_), None) => throw new IllegalArgumentException("Reference reverse read depth specified without reverse read depth")
case _ =>
}
vcb
}
private[converters] def extractTranscriptEffects(
va: VariantAnnotation,
vcb: VariantContextBuilder): VariantContextBuilder = {
if (!va.getTranscriptEffects.isEmpty) {
vcb.attribute("ANN", TranscriptEffectConverter.convertToVcfInfoAnnValue(va.getTranscriptEffects))
}
vcb
}
private val variantAnnotationExtractFns: Iterable[(VariantAnnotation, VariantContextBuilder) => VariantContextBuilder] = Iterable(
extractAncestralAllele(_, _),
extractDbSnp(_, _),
extractHapMap2(_, _),
extractHapMap3(_, _),
extractValidated(_, _),
extractThousandGenomes(_, _),
extractSomatic(_, _),
extractAlleleCount(_, _),
extractAlleleFrequency(_, _),
extractCigar(_, _),
extractReadDepth(_, _),
extractForwardReadDepth(_, _),
extractReverseReadDepth(_, _),
extractTranscriptEffects(_, _)
)
// htsjdk --> genotype format functions
private[converters] def formatAllelicDepth(g: HtsjdkGenotype,
gb: Genotype.Builder,
gIdx: Int,
gIndices: Array[Int]): Genotype.Builder = {
// AD is an array type field
if (g.hasAD && gIdx < g.getAD.length) {
val ad = g.getAD
gb.setReferenceReadDepth(ad(0))
.setAlternateReadDepth(ad(gIdx))
} else {
gb
}
}
private[converters] def formatReadDepth(g: HtsjdkGenotype,
gb: Genotype.Builder,
gIdx: Int,
gIndices: Array[Int]): Genotype.Builder = {
if (g.hasDP) {
gb.setReadDepth(g.getDP)
} else {
gb
}
}
private[converters] def formatMinReadDepth(g: HtsjdkGenotype,
gb: Genotype.Builder,
gIdx: Int,
gIndices: Array[Int]): Genotype.Builder = {
Option(g.getExtendedAttribute("MIN_DP", null))
.map(attr => {
tryAndCatchStringCast(attr, attribute => {
gb.setMinReadDepth(attribute.asInstanceOf[java.lang.Integer])
}, attribute => {
gb.setMinReadDepth(attribute.toInt)
})
}).getOrElse(gb)
}
private[converters] def formatGenotypeQuality(g: HtsjdkGenotype,
gb: Genotype.Builder,
gIdx: Int,
gIndices: Array[Int]): Genotype.Builder = {
if (g.hasGQ) {
gb.setGenotypeQuality(g.getGQ)
} else {
gb
}
}
private[converters] def formatGenotypeLikelihoods(g: HtsjdkGenotype,
gb: Genotype.Builder,
gIdx: Int,
gIndices: Array[Int]): Genotype.Builder = {
if (g.hasPL) {
val pl = g.getPL
try {
val likelihoods = gIndices.map(idx => {
jDouble(PhredUtils.phredToLogProbability(pl(idx)))
}).toList
gb.setGenotypeLikelihoods(likelihoods)
} catch {
case _: ArrayIndexOutOfBoundsException => {
logger.warn("Ran into Array Out of Bounds when accessing indices %s of genotype %s.".format(gIndices.mkString(","), g))
gb
}
}
} else {
gb
}
}
private[converters] def formatNonRefGenotypeLikelihoods(g: HtsjdkGenotype,
gb: Genotype.Builder,
gIndices: Array[Int]): Genotype.Builder = {
if (g.hasPL) {
val pl = g.getPL
gb.setNonReferenceLikelihoods(gIndices.map(idx => {
jDouble(PhredUtils.phredToLogProbability(pl(idx)))
}).toList)
} else {
gb
}
}
private def tryAndCatchStringCast[T](attr: java.lang.Object,
tryFn: (java.lang.Object) => T,
catchFn: (String) => T): T = {
try {
tryFn(attr)
} catch {
case cce: ClassCastException => {
// is this a string? if so, parse...
if (attr.getClass.isAssignableFrom(classOf[String])) {
catchFn(attr.asInstanceOf[String])
} else {
throw cce
}
}
case t: Throwable => throw t
}
}
private[converters] def formatStrandBiasComponents(g: HtsjdkGenotype,
gb: Genotype.Builder,
gIdx: Int,
gIndices: Array[Int]): Genotype.Builder = {
Option(g.getExtendedAttribute("SB"))
.map(attr => {