-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathvcf2maf.py
1640 lines (1421 loc) · 60.6 KB
/
vcf2maf.py
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
#!/usr/bin/env python3
# Copyright (c) 2023 Memorial Sloan Kettering Cancer Center
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# imports
import sys
import os
import click
import re
import json
from chardet import detect
import warnings
# ---------------------------- GLOBALS ----------------------------
MAF_HEADER = [
"Hugo_Symbol",
"Entrez_Gene_Id",
"Center",
"NCBI_Build",
"Chromosome",
"Start_Position",
"End_Position",
"Strand",
"Variant_Classification",
"Variant_Type",
"Reference_Allele",
"Tumor_Seq_Allele1",
"Tumor_Seq_Allele2",
"dbSNP_RS",
"dbSNP_Val_Status",
"Tumor_Sample_Barcode",
"Matched_Norm_Sample_Barcode",
"Match_Norm_Seq_Allele1",
"Match_Norm_Seq_Allele2",
"Tumor_Validation_Allele1",
"Tumor_Validation_Allele2",
"Match_Norm_Validation_Allele1",
"Match_Norm_Validation_Allele2",
"Verification_Status",
"Validation_Status",
"Mutation_Status",
"Sequencing_Phase",
"Sequence_Source",
"Validation_Method",
"Score",
"BAM_File",
"Sequencer",
"HGVSp_Short",
"t_ref_count",
"t_alt_count",
"n_ref_count",
"n_alt_count",
"Protein_position",
"Codons",
"SWISSPROT",
"RefSeq",
"t_depth",
"n_depth",
"FILTER",
"gnomAD_AF",
"gnomAD_AFR_AF",
"gnomAD_AMR_AF",
"gnomAD_ASJ_AF",
"gnomAD_EAS_AF",
"gnomAD_FIN_AF",
"gnomAD_NFE_AF",
"gnomAD_OTH_AF",
"gnomAD_SAS_AF",
]
VCF_FIXED_HEADER_NON_CASE_IDS = [
"CHROM",
"POS",
"ID",
"REF",
"ALT",
"QUAL",
"FILTER",
"INFO",
"FORMAT",
]
# DEFAULTS
DEFAULT_STRAND = "+"
DEFAULT_VALIDATION_STATUS = "Unknown"
DEFAULT_VERIFICATION_STATUS = "Unknown"
DEFAULT_MUTATION_STATUS = "Somatic"
# GLOBALS FOR VALIDATING RESULTS
VALID_VARIANT_CLASSIFICATIONS = [
"Frame_Shift_Del",
"Frame_Shift_Ins",
"In_Frame_Del",
"In_Frame_Ins",
"Missense_Mutation",
"Nonsense_Mutation",
"Silent",
"Splice_Site",
"Translation_Start_Site",
"Nonstop_Mutation",
"3'UTR",
"3'Flank",
"5'UTR",
"5'Flank",
"IGR",
"Intron",
"RNA",
"Targeted_Region",
]
# CGI GLOBALS
CGI_VARIANT_CLASS_FILTER = [
"INTRON",
"TSS-UPSTREAM",
"UTR5",
"UTR3",
"UTR",
"SPAN5",
"SPAN3",
"SPAN",
"SYNONYMOUS",
"IGR",
"NO-CHANGE",
"UPSTREAM",
]
CGI_INDEL_VARIANT_CLASSES = ["INSERT", "DELETE", "INSERT+", "DELETE+", "FRAMESHIFT"]
# NO DIRECT MAPPING FOR: UTR, SPAN, FRAMESHIFT - These require additional data either from other variant classes
# if datum contains comma-separated variant classes (i.e., NO-CHANGE,DELETE,FRAMESHIFT for one record)
# or value of variant type
# > If only UTR is present then use IGR as default
# > If only SPAN is present then use IGR as default
# > If only FRAMESHIFT is present and variant type is INS/DEL then use Frame_Shift_Ins, Frame_Shift_Del.
# Otherwise, if variant type is not INS/DEL then use Missense_Mutation
CGI_VARIANT_CLASS_MAP = {
"INTRON": "Intron",
"TSS-UPSTREAM": "5'Flank",
"UPSTREAM": "5'Flank",
"UTR5": "5'UTR",
"UTR3": "3'UTR",
"SPAN5": "5'UTR",
"SPAN3": "3'UTR",
"SYNONYMOUS": "Silent",
"MISSTART": "Translation_Start_Site",
"DONOR": "Splice_Site",
"ACCEPTOR": "Splice_Site",
"DISRUPT": "Splice_Site",
"NO-CHANGE": "Silent",
"MISSENSE": "Missense_Mutation",
"NONSENSE": "Nonsense_Mutation",
"NONSTOP": "Nonstop_Mutation",
"DELETE": "In_Frame_Del",
"INSERT": "In_Frame_Ins",
"DELETE+": "Frame_Shift_Del",
"INSERT+": "Frame_Shift_Ins",
}
# KEY COLUMN NAMES
TUMOR_SEQ_ALLELE1_COLUMNS = ["Tumor_Seq_Allele1", "TumorSeq_Allele1"]
TUMOR_SEQ_ALLELE2_COLUMNS = ["Tumor_Seq_Allele2", "TumorSeq_Allele2"]
MUTATED_FROM_ALLELE_COLUMN = "mutated_from_allele"
MUTATED_TO_ALLELE_COLUMN = "mutated_to_allele"
VARIANT_TYPE_COLUMNS = ["Variant_Type", "VariantType", "mut_type", "mutation_type"]
VARIANT_CLASSIFICATION_COLUMNS = [
"Variant_Classification",
"class",
"Transcript architecture around variant",
]
START_POSITION_COLUMNS = ["Start_Position", "Start_position", "POS", "chromosome_start"]
END_POSITION_COLUMNS = ["End_Position", "End_position", "chromosome_end"]
REFERENCE_ALLELE_COLUMNS = ["Reference_Allele", "reference_genome_allele"]
TUMOR_GENOTYPE_COLUMN = "tumour_genotype"
MATCHED_NORMAL_SAMPLE_BARCODE_COLUMNS = [
"Match_Normal_Sample_Barcode",
"Matched_Norm_Sample_Barcode",
"matched_sample_id",
]
CHROMOSOME_COLUMNS = ["Chromosome", "chromosome", "CHROM"]
VERIFICATION_STATUS_COLUMNS = ["Verification_Status", "verification_status"]
VALIDATION_METHOD_COLUMNS = ["Validation_Method", "verification_platform"]
MATCHED_NORMAL_SEQ_ALLELE1_COLUMNS = ["Match_Norm_Seq_Allele1", "mutated_to_allele"]
MATCHED_NORMAL_SEQ_ALLELE2_COLUMNS = ["Match_Norm_Seq_Allele2", "control_genotype"]
TUMOR_SAMPLE_BARCODE_COLUMNS = [
"Tumor_Sample_Barcode",
"analyzed_sample_id",
"submitted_sample_id",
]
# VCF KEYS FOR RESOLVING WHICH VCF PIPIELINE WAS USED
VCF_STRELKA_KEY_COLUMNS = ["AU", "CU", "GU", "TU"]
VCF_CAVEMAN_KEY_COLUMNS = ["FAZ", "FCZ", "FGZ", "FTZ", "RAZ", "RCZ", "RGZ", "RTZ"]
VCF_ION_TORRENT_KEY_COLUMNS = ["AO", "RO"]
VCF_DELLY_KEY_COLUMNS = ["RR", "RV"]
VCF_CGPPINDEL_KEY_COLUMNS = ["PP", "NP", "PR", "NR"]
VCF_ALT_ALLELE_FRACTION_KEY_COLUMNS = ["FA", "DP"]
VCF_MPILEUP_BCFTOOLS_KEY_COLUMNS = ["DV", "DP"]
VCF_REFERENCE_ALLELE_VALUE = "0"
VCF_VARIANT_ALLELE1_VALUE = "1"
VCF_VARIANT_ALLELE2_VALUE = "2"
VCF_DEFAULT_VARIANT_ALLELE_IDX = 1
NULL_OR_MISSING_VALUES = set(["", "N/A", None, ".", "?"])
NULL_OR_MISSING_VCF_VALUES = set(["", ".", "./."])
NORMAL_IDENTIFIERS = ["NORMAL", "DONOR"]
# problematic files tracker
PROBLEMATIC_FILES_REPORT = {}
# ----------------------------------------------------------------
def is_valid_integer(value):
try:
int(value)
except ValueError:
return False
return True
def is_missing_vcf_data_value(value):
return value in NULL_OR_MISSING_VCF_VALUES
def all_values_in_list(values_to_check, input_list):
for value in values_to_check:
if not value in input_list:
return False
return True
def is_varscan_vcf(vcf_format_data_keys):
return "RD" in vcf_format_data_keys
def is_somatic_sniper_vcf(vcf_format_data_keys):
return not "AD" in vcf_format_data_keys and "BCOUNT" in vcf_format_data_keys
def is_strelka_snp_vcf(vcf_format_data_keys):
return not "AD" in vcf_format_data_keys and all_values_in_list(
VCF_STRELKA_KEY_COLUMNS, vcf_format_data_keys
)
def is_strelka_indel_vcf(vcf_format_data_keys):
return not "AD" in vcf_format_data_keys and "TIR" in vcf_format_data_keys
def is_caveman_vcf(vcf_format_data_keys):
return not "AD" in vcf_format_data_keys and all_values_in_list(
VCF_CAVEMAN_KEY_COLUMNS, vcf_format_data_keys
)
def is_ion_torrent_vcf(vcf_format_data_keys):
return not "AD" in vcf_format_data_keys and all_values_in_list(
VCF_ION_TORRENT_KEY_COLUMNS, vcf_format_data_keys
)
def is_delly_vcf(vcf_format_data_keys):
return not "AD" in vcf_format_data_keys and all_values_in_list(
VCF_DELLY_KEY_COLUMNS, vcf_format_data_keys
)
def is_cgppindel_vcf(vcf_format_data_keys):
return not "AD" in vcf_format_data_keys and all_values_in_list(
VCF_CGPPINDEL_KEY_COLUMNS, vcf_format_data_keys
)
def is_alt_allele_fraction_vcf(vcf_format_data_keys):
return not "AD" in vcf_format_data_keys and all_values_in_list(
VCF_ALT_ALLELE_FRACTION_KEY_COLUMNS, vcf_format_data_keys
)
def is_mpileup_bcftools_vcf(vcf_format_data_keys):
return not "AD" in vcf_format_data_keys and all_values_in_list(
VCF_MPILEUP_BCFTOOLS_KEY_COLUMNS, vcf_format_data_keys
)
def resolve_vcf_allele_depth_values(
mapped_sample_format_data, vcf_alleles, variant_allele_idx, vcf_data
):
"""
Resolves the allele depth values based on the type of VCF pipeline identified.
Support VCF pipelines/methods for resolving allele counts:
1. VarScan
2. SomaticSniper
3. Strelka (SNPs only)
4. Strelka (INDELs only)
5. CaVEMan
6. Ion Torrent
7. Delly
8. cgpPINDEL
9. VCF ALT allele fractions (derive values from allele fractions)
10. MPileUp/BCFTools
11. "AD" only contains a single value (does not contain a comma)
12. If none of the above criteria are met then allele depths are set to empty strings
"""
ref_count = ""
alt_count = ""
depth = ""
# get list of keys stored in the VCF 'FORMAT' column - this is used
# to determine how to resolve the alelle counts
vcf_format_data_keys = mapped_sample_format_data.keys()
# init allele depth values to list of empty strings matching length of "vcf_alleles"
allele_depth_values = [""] * len(vcf_alleles)
# if AD is defined, then parse out all REF/ALT allele depths, or whatever is in it
if "AD" in vcf_format_data_keys and not is_missing_vcf_data_value(
mapped_sample_format_data["AD"]
):
# attempt to parse values as int - if not an int then set value to empty string
allele_depth_values = []
for value in mapped_sample_format_data["AD"].split(","):
if is_valid_integer(value):
allele_depth_values.append(value)
else:
allele_depth_values.append("")
# 1. VarScan VCF: handle VarScan VCF lines where AD contains only 1 depth, and REF allele depth is in RD
if len(allele_depth_values) == 1 and is_varscan_vcf(vcf_format_data_keys):
allele_depth_values = [""] * len(vcf_alleles)
allele_depth_values[0] = process_datum(mapped_sample_format_data["RD"])
allele_depth_values[variant_allele_idx] = process_datum(
mapped_sample_format_data["AD"]
)
# 2. SomaticSniper: handle SomaticSniper VCF lines, where allele depths must be extracted from BCOUNT
elif is_somatic_sniper_vcf(vcf_format_data_keys):
# bcount values are always reported in the order of "A", "C", "G", "T"
tumor_bcount_values = mapped_sample_format_data["BCOUNT"].split(",")
read_depth_bases = ["A", "C", "G", "T"]
read_depth_bases_to_counts_map = {}
for i, bcount_val in enumerate(tumor_bcount_values):
corresponding_base = read_depth_bases[i]
read_depth_bases_to_counts_map[read_depth_bases[i]] = bcount_val
allele_depth_values = [""] * len(vcf_alleles)
for i, allele in enumerate(vcf_alleles):
allele_depth_values[i] = read_depth_bases_to_counts_map.get(allele, "")
# 3. Strelka (SNP): handle VCF SNV lines by Strelka, where allele depths are in AU:CU:GU:TU
elif is_strelka_snp_vcf(vcf_format_data_keys):
# need to convert the read values to an integer so we can sort
read_depth_bases_to_counts_map = {}
for k in VCF_STRELKA_KEY_COLUMNS:
value = -1
# If multiple tiers, report tier1 counts by picking the first comma-delimited value
if is_valid_integer(mapped_sample_format_data[k].split(",")[0]):
value = int(mapped_sample_format_data[k].split(",")[0])
read_depth_bases_to_counts_map[k.replace("U", "")] = value
# if the only alt allele is N then set it to the allele with the highest non-ref readcount
if len(vcf_alleles) == 2 and vcf_alleles[1] == "N":
sorted_read_depths = sorted(
read_depth_bases_to_counts_map.items(), lambda k: k[1], reverse=True
)
# find highest non-ref readcount
if sorted_read_depths[0][0] != vcf_alleles[0]:
vcf_alleles[variant_allele_idx] = sorted_read_depths[0][0]
else:
vcf_alleles[variant_allele_idx] = sorted_read_depths[1][0]
# change values back to string representations of the numbers or empty strings if default value was used
allele_depth_values = [""] * len(vcf_alleles)
for i, allele in enumerate(vcf_alleles):
read_depth_value = str(read_depth_bases_to_counts_map.get(allele, -1))
# if value was set to default value of -1 from above during the sorting then set to empty string
if read_depth_value == "-1":
read_depth_value = ""
allele_depth_values[i] = read_depth_value
# 4. Strelka (INDEL): handle VCF INDEL lines by Strelka, where variant allele depth is in TIR, reference allele depth is in TAR.
elif is_strelka_indel_vcf(vcf_format_data_keys):
# pick tier1 counts if a comma-delimited value
allele_depth_values[variant_allele_idx] = mapped_sample_format_data[
"TIR"
].split(",")[0]
if variant_allele_idx == 1:
ref_allele_idx = 0
else:
ref_allele_idx = 1
allele_depth_values[ref_allele_idx] = mapped_sample_format_data["TAR"].split(
","
)[0]
# 5. CaVEMan: handle VCF lines by CaVEMan, where allele depths are in FAZ:FCZ:FGZ:FTZ:RAZ:RCZ:RGZ:RTZ
elif is_caveman_vcf(vcf_format_data_keys):
# allele depths are provided for forward strand and reverse strand, add these numbers together to get depth by nucleotide
caveman_values_as_integers = {}
for k in VCF_CAVEMAN_KEY_COLUMNS:
try:
caveman_values_as_integers[k] = int(mapped_sample_format_data[k])
except:
caveman_values_as_integers[k] = 0
read_depth_bases_to_counts_map["A"] = str(
caveman_values_as_integers["FAZ"] + caveman_values_as_integers["RAZ"]
)
read_depth_bases_to_counts_map["C"] = str(
caveman_values_as_integers["FCZ"] + caveman_values_as_integers["RCZ"]
)
read_depth_bases_to_counts_map["G"] = str(
caveman_values_as_integers["FGZ"] + caveman_values_as_integers["RGZ"]
)
read_depth_bases_to_counts_map["T"] = str(
caveman_values_as_integers["FTZ"] + caveman_values_as_integers["RTZ"]
)
allele_depth_values = [""] * len(vcf_alleles)
for i, allele in enumerate(vcf_alleles):
allele_depth_values[i] = read_depth_bases_to_counts_map.get(allele, "")
# 6. Ion Torrent: handle VCF lines from the Ion Torrent Suite where ALT depths are in AO and REF depths are in RO
elif is_ion_torrent_vcf(vcf_format_data_keys):
allele_depth_values = [process_datum(mapped_sample_format_data["RO"])]
allele_depth_values.extend(mapped_sample_format_data["AO"].split(","))
# 7. Delly: handle VCF lines from Delly where REF/ALT SV junction read counts are in RR/RV respectively
elif is_delly_vcf(vcf_format_data_keys):
allele_depth_values[0] = process_datum(mapped_sample_format_data["RR"])
allele_depth_values[variant_allele_idx] = process_datum(
mapped_sample_format_data["RV"]
)
# 8. cgpPINDEL: handle VCF lines from cgpPindel, where ALT depth and total depth are in PP:NP:PR:NR
elif is_cgppindel_vcf(vcf_format_data_keys):
# reference allele depth and depths for any other ALT alleles must be left undefined
allele_depth_values[variant_allele_idx] = str(
float(mapped_sample_format_data["PP"])
+ float(mapped_sample_format_data["NP"])
)
mapped_sample_format_data["DP"] = str(
float(mapped_sample_format_data["PR"])
+ float(mapped_sample_format_data["NR"])
)
# 9. VCF ALT allele fractions: handle VCF lines with ALT allele fraction in FA, which needs to be multiplied by DP to get AD
elif is_alt_allele_fraction_vcf(
vcf_format_data_keys
) and not is_missing_vcf_data_value(mapped_sample_format_data["DP"]):
allele_depth_values[variant_allele_idx] = "%.0f" % (
float(mapped_sample_format_data["FA"])
* float(mapped_sample_format_data["DP"])
)
# 10. MPileUp/BCFTools: handle VCF lines from mpileup/bcftools where DV contains the ALT allele depth
elif is_mpileup_bcftools_vcf(vcf_format_data_keys):
allele_depth_values[variant_allele_idx] = process_datum(
mapped_sample_format_data["DV"]
)
# 11. AD single value: handle VCF lines where AD contains only 1 value, that we can assume is the variant allele
elif "AD" in vcf_format_data_keys and len(allele_depth_values) == 1:
allele_depth_values[variant_allele_idx] = process_datum(
mapped_sample_format_data["AD"]
)
# 12. For all other lines where number of depths is not equal to number of alleles, blank out the depths
elif len(allele_depth_values) != len(vcf_alleles):
allele_depth_values = [""] * len(vcf_alleles)
ref_count = allele_depth_values[0]
alt_count = allele_depth_values[variant_allele_idx]
vcf_dp_value = process_datum(mapped_sample_format_data.get("DP", ""))
# Sanity check that REF/ALT allele depths are lower than the total depth
if (
"DP" in vcf_format_data_keys
and not is_missing_vcf_data_value(vcf_dp_value)
and (
not is_missing_vcf_data_value(ref_count)
and float(ref_count) > float(vcf_dp_value)
or (
not is_missing_vcf_data_value(alt_count)
and float(alt_count) > float(vcf_dp_value)
)
or (
not is_missing_vcf_data_value(ref_count)
and not is_missing_vcf_data_value(alt_count)
and ((float(ref_count) + float(alt_count)) > float(vcf_dp_value))
)
)
):
mapped_sample_format_data["DP"] = str(sum(map(float, allele_depth_values)))
# if we have REF/ALT allele depths, but no DP, then set DP equal to the sum of all ADs
if (
not is_missing_vcf_data_value(ref_count)
and not is_missing_vcf_data_value(alt_count)
) and (
not "DP" in vcf_format_data_keys
or is_missing_vcf_data_value(mapped_sample_format_data["DP"])
):
mapped_sample_format_data["DP"] = str(sum(map(float, allele_depth_values)))
mapped_sample_format_data["AD"] = ",".join(allele_depth_values)
try:
depth = mapped_sample_format_data["DP"]
except:
message = (
"DP could not be resolved for current record in VCF: %s - using default value of empty string..."
% (str(vcf_data))
)
print_warning(message)
# if depth has been resolved but not ref_count, alt_count then calculate the counts
# if allele frequency vcf field "AF" exists
if (
not is_missing_vcf_data_value(depth)
and (
"AF" in mapped_sample_format_data
and not is_missing_vcf_data_value(mapped_sample_format_data["AF"])
)
and (
is_missing_vcf_data_value(ref_count) or is_missing_vcf_data_value(alt_count)
)
):
# check if ref count or alt count are still missing but AF VCF field is available
if is_missing_vcf_data_value(ref_count):
ref_count = str(
round(float(depth) * float(mapped_sample_format_data["AF"]))
)
if is_missing_vcf_data_value(alt_count) and not is_missing_vcf_data_value(
ref_count
):
alt_count = str(round(float(depth) - float(ref_count)))
return (ref_count, alt_count, depth)
def get_vcf_variant_allele_idx(
tumor_sample_format_data, normal_sample_format_data, vcf_alleles
):
"""
Determines the variant allele index to use based on genotype information if available.
If genotype information is not available or a call could not be made for a sample at
a given locus then use a variant allele idx of 1 by default.
Allele values:
- 0 = reference allele (i.e., what is in the 'REF' field)
- 1 = the first allele listed in 'ALT'
- 2 = the second allele listed in 'ALT'
"""
variant_allele_idx = []
# if genotype information is available and a call was made for the sample then
# choose the first non-REF allele seen in the sample genotype
if "GT" in tumor_sample_format_data.keys() and not is_missing_vcf_data_value(
tumor_sample_format_data["GT"]
):
tumor_sample_genotype_info = re.split("[\/|]", tumor_sample_format_data["GT"])
variant_allele_idx = [
allele
for allele in tumor_sample_genotype_info
if allele != VCF_REFERENCE_ALLELE_VALUE
and not is_missing_vcf_data_value(allele)
]
# if possible, choose the first non-REF tumor allele that is also not in normal genotype
# if this check results in variant_allele_idx being empty or the index value is larger than
# the size of the alleles then use the default value "VCF_DEFAULT_VARIANT_ALLELE_IDX"
if (
normal_sample_format_data != None
and "GT" in normal_sample_format_data.keys()
and not is_missing_vcf_data_value(normal_sample_format_data["GT"])
):
normal_sample_genotype_info = re.split(
"[\/|]", normal_sample_format_data["GT"]
)
variant_allele_idx = [
allele
for allele in tumor_sample_genotype_info
if allele != VCF_REFERENCE_ALLELE_VALUE
and not is_missing_vcf_data_value(allele)
and not allele in normal_sample_genotype_info
]
# if the idx found is undefined or is equal to or larger than the size of the vcf alleles list
# then use the vcf default value for the variant allele index
if (
variant_allele_idx == []
or not is_valid_integer(variant_allele_idx[0])
or int(variant_allele_idx[0]) >= len(vcf_alleles)
):
return VCF_DEFAULT_VARIANT_ALLELE_IDX
return int(variant_allele_idx[0])
def resolve_vcf_counts_data(
vcf_data, maf_data, matched_normal_sample_id, tumor_sample_data_col
):
"""Resolves VCF allele counts data."""
vcf_alleles = [vcf_data["REF"]]
vcf_alleles.extend(vcf_data["ALT"].split(","))
tumor_sample_format_data = vcf_data["MAPPED_TUMOR_FORMAT_DATA"]
normal_sample_format_data = None
if matched_normal_sample_id in vcf_data.keys():
normal_sample_format_data = vcf_data["MAPPED_NORMAL_FORMAT_DATA"]
variant_allele_idx = get_vcf_variant_allele_idx(
tumor_sample_format_data, normal_sample_format_data, vcf_alleles
)
(t_ref_count, t_alt_count, t_depth) = resolve_vcf_allele_depth_values(
tumor_sample_format_data, vcf_alleles, variant_allele_idx, vcf_data
)
maf_data["t_ref_count"] = t_ref_count
maf_data["t_alt_count"] = t_alt_count
maf_data["t_depth"] = t_depth
# only resolve values for normal allele depths if "NORMAL" data is present in VCF
if normal_sample_format_data:
(n_ref_count, n_alt_count, n_depth) = resolve_vcf_allele_depth_values(
normal_sample_format_data, vcf_alleles, variant_allele_idx, vcf_data
)
maf_data["n_ref_count"] = n_ref_count
maf_data["n_alt_count"] = n_alt_count
maf_data["n_depth"] = n_depth
return maf_data
def resolve_sequence_source(data):
"""Resolves the sequence source."""
# convert sequence strategy to sequence source values if column present in data
if "sequencing_strategy" in data.keys():
if data["sequencing_strategy"] == "1":
return "WGS"
elif data["sequencing_strategy"] == "3":
return "WXS"
# fall back on parsing sequence source column or fall on default
seq_source = process_datum(data.get("Sequence_Source", ""))
return seq_source
def resolve_chromosome(data):
"""Resolves the chromosome."""
chromosome = ""
for column in CHROMOSOME_COLUMNS:
if column in data.keys():
chromosome = process_datum(data[column]).replace("chr", "")
break
return chromosome.split("_")[0]
def resolve_hugo_symbol(data):
"""Resolves the hugo symbol."""
hugo_symbol = ""
for column in ["Hugo_Symbol", "HugoSymbol", "Gene Symbol", "GENE"]:
if column in data.keys():
hugo_symbol = process_datum(data[column].split("|")[0])
break
if hugo_symbol == "":
hugo_symbol = "Unknown"
return hugo_symbol
def init_maf_record():
"""Creates a new MAF record with default values for every header."""
maf_data = dict(zip(MAF_HEADER, ["" for column in MAF_HEADER]))
# set defaults
maf_data["Strand"] = DEFAULT_STRAND
maf_data["Validation_Status"] = DEFAULT_VALIDATION_STATUS
return maf_data
def resolve_vcf_allele(vcf_data):
"""Resolves the VCF alleles."""
ref_allele = ""
alt_allele = ""
if vcf_data["ALT"] in ["<DEL>", "<DUP>", "<INV>", "<TRA>"]:
if vcf_data["REF"] == "N" or vcf_data["REF"] == "":
ref_allele = vcf_data["INFO"].get("CONSENSUS", "")
else:
ref_allele = vcf_data["REF"]
if ref_allele != "N" and ref_allele != "":
if vcf_data["ALT"] == "<DEL>":
alt_allele = "-"
if vcf_data["ALT"] == "<INV>":
alt_allele = ref_allele[::-1]
elif vcf_data["ALT"] == "<DUP>":
alt_allele = ref_allele * 2
else:
ref_allele = process_datum(vcf_data["REF"].split(",")[0])
alt_allele = process_datum(vcf_data["ALT"].split(",")[0])
if ref_allele == "":
ref_allele = "-"
if alt_allele == "":
alt_allele = "-"
return ref_allele, alt_allele
def resolve_start_position(data):
"""Resolves the start position."""
start_pos = ""
for column in START_POSITION_COLUMNS:
if column in data.keys():
start_pos = process_datum(data[column])
break
return start_pos
def resolve_vcf_variant_type(ref_allele, alt_allele):
"""Resolves the VCF variant type."""
variant_type = ""
# first check if indel
if ref_allele == "-" or len(ref_allele) < len(alt_allele):
variant_type = "INS"
elif alt_allele == "-" or len(alt_allele) < len(ref_allele):
variant_type = "DEL"
else:
# check whether variant type is type of polymorphism
if len(ref_allele) == len(alt_allele):
if len(ref_allele) == 1:
variant_type = "SNP"
elif len(ref_allele) == 2:
variant_type = "DNP"
elif len(ref_allele) == 3:
variant_type = "TNP"
else:
variant_type = "ONP"
# if variant type is still empty then report
if variant_type == "":
message = (
"Could not salvage variant type from alleles [ ref allele = %s , tumor allele = %s ] "
% (ref_allele, alt_allele)
)
print_warning(message)
return variant_type
def resolve_end_position(data, start_pos, variant_type, ref_allele):
"""Resolves the end position."""
end_pos = ""
for column in END_POSITION_COLUMNS:
if column in data.keys():
end_pos = process_datum(data[column])
break
# if insertion then end pos is start pos + 1
if variant_type == "INS" or ref_allele == "-":
try:
end_pos = str(int(start_pos) + 1)
except ValueError:
print(data)
sys.exit(2)
# resolve end pos from ref allele length if empty string
if end_pos == "":
end_pos = str(int(start_pos) + len(ref_allele) - 1)
return end_pos
def resolve_center_name(data, center_name):
"""Resolves the chromosome."""
center = process_datum(data.get("Center", ""))
if center == "":
center = center_name
return center
def resolve_sequence_source(data, sequence_source):
"""Resolves the sequence source."""
# convert sequence strategy to sequence source values if column present in data
if "sequencing_strategy" in data.keys():
if data["sequencing_strategy"] == "1":
return "WGS"
elif data["sequencing_strategy"] == "3":
return "WXS"
# fall back on parsing sequence source column or fall on default
seq_source = process_datum(data.get("Sequence_Source", ""))
if seq_source == "":
seq_source = sequence_source
return seq_source
def resolve_complex_variant_classification(data, variant_class_list, variant_type):
"""
Resolve a complex variant classification.
Note: Complex variant classifications may be from data generated from CGI.
"""
# MISSTART variant classes take precedence over other CGI variant classes
if "MISSTART" in variant_class_list:
return CGI_VARIANT_CLASS_MAP["MISSTART"]
# if length of variant class list is 1 and variant class is in list of filtered CGI variants then return
# direct mapping of variant class or IGR by default, as in the cases of SPAN and UTR variant classes
if (
len(variant_class_list) == 1
and variant_class_list[0] in CGI_VARIANT_CLASS_FILTER
):
return CGI_VARIANT_CLASS_MAP.get(variant_class_list[0], "IGR")
# check if any CGI variant classes that we normally filter are present in given variant_class_list
filtered_cgi_var_classes = [
var_class
for var_class in variant_class_list
if var_class in CGI_VARIANT_CLASS_FILTER
]
if len(filtered_cgi_var_classes) > 0:
# if filtered CGI variant classes are present then return the first one that can be directly mapped to
# a standard variant classification
for var_class in filtered_cgi_var_classes:
if var_class in CGI_VARIANT_CLASS_MAP.keys():
return CGI_VARIANT_CLASS_MAP[var_class]
# Map var classes to standard variant classifications or use orig var class name if not found.
# Variant classes that do not map directly include FRAMESHIFT, SPAN, UTR
variant_class_candidates = list(
map(lambda x: CGI_VARIANT_CLASS_MAP.get(x, x), variant_class_list)
)
# splice sites take precedence over other variant classifications
if "Splice_Site" in variant_class_candidates:
return "Splice_Site"
# if variant type is INS/DEL or INSERT/DELETE/FRAMESHIFT/INSERT+/DELETE+ in input variant_class_list then
# return either In_Frame_Ins/Del or Frame_Shift_Ins/Del
indel_variant_classes = [
var_class
for var_class in variant_class_list
if var_class in CGI_INDEL_VARIANT_CLASSES
]
if variant_type in ["INS", "DEL"] and len(indel_variant_classes) > 0:
for var_class in indel_variant_classes:
if var_class == "FRAMESHIFT":
return "Frame_Shift_" + variant_type.title()
else:
return CGI_VARIANT_CLASS_MAP[var_class]
# if indel variant classes present but variant_type is not INS or DEL - variant type will need to be fixed later
for var_class in indel_variant_classes:
if var_class != "FRAMESHIFT":
return CGI_VARIANT_CLASS_MAP[var_class]
# if variant class is not an indel then variant class is either Missense_Mutation, Nonsense_Mutation, Nonstop_Mutation, or NO-CHANGE/Silent
# if variant type is INS/DEL then return Frame_Shift_Ins/Del if Nonsense_Mutation or Nonstop_Mutation in variant class candidates
# or In_Frame_Ins/Del if Missense_Mutation in candidates - Nonsense/Nonstop mutations take precedence over Missense
if variant_type in ["INS", "DEL"]:
if (
"Nonsense_Mutation" in variant_class_candidates
or "Nonstop_Mutation" in variant_class_candidates
):
return "Frame_Shift_" + variant_type.title()
elif "Missense_Mutation" in variant_class_candidates:
return "In_Frame_" + variant_type.title()
# if variant type not INS/DEL then must be SNP/SNV/SUB
# Return Nonsense_Mutation, Nonstop_Mutation, or Missense_Mutation with Nonsense/Nonstop taking precedence
for var_class in ["Nonstop_Mutation", "Nonsense_Mutation", "Missense_Mutation"]:
if var_class in variant_class_candidates:
return var_class
# if variant class is empty but variant type is SNP then return missense mutation
if variant_type in ["SNP", "DNP", "TNP", "ONP"]:
return "Missense_Mutation"
# if variant class can't be resolve by this point then arbitrarily return first in list that can be mapped directly
return variant_class_candidates[0]
def resolve_variant_classification(data, variant_type, ref_allele, alt_allele):
"""Resolves the variant classification."""
variant_class = ""
for column in VARIANT_CLASSIFICATION_COLUMNS:
if column in data.keys():
variant_class = process_datum(data[column])
break
# if variant classification is valid then return, else try to resolve value
if variant_class in VALID_VARIANT_CLASSIFICATIONS:
return variant_class
# if empty string then assume missense or indel - let annotator resolve correct variant class
if variant_class == "":
# if indel then determine whether in frame or out of frame
if variant_type in ["INS", "DEL"]:
if variant_type == "INS":
in_frame_variant = len(alt_allele) % 3 == 0
else:
in_frame_variant = len(ref_allele) % 3 == 0
if in_frame_variant:
variant_class = "In_Frame_" + variant_type.title()
else:
variant_class = "Frame_Shift_" + variant_type.title()
else:
# let annotator figure it out from the VEP response
variant_class = "Missense_Mutation"
else:
variant_class_list = re.split("[\\|, ]", variant_class)
variant_class = resolve_complex_variant_classification(
data, variant_class_list, variant_type
)
return variant_class
def resolve_vcf_variant_allele_data(vcf_data, maf_data):
"""Resolves the reference allele and tumor allele values."""
# get ref allele and alt allele values
ref_allele, alt_allele = resolve_vcf_allele(vcf_data)
start_pos = resolve_start_position(vcf_data)
variant_type = ""
end_pos = ""
variant_class = ""
if (ref_allele != "N" and ref_allele != "") and alt_allele != "":
# indels from vcf need to be shifted by one nucleotide and start position needs to be incremented by one
if ref_allele[0] == alt_allele[0] and ref_allele != alt_allele:
# shift ref allele and alt allele by one nucleotide, set as "-" if len == 1
if len(ref_allele) == 1:
ref_allele = "-"
else:
ref_allele = ref_allele[1:]
if len(alt_allele) == 1:
alt_allele = "-"
else:
alt_allele = alt_allele[1:]
# fix start position value
if start_pos != "":
start_pos = str(int(start_pos) + 1)
# resolve variant type, end position, and variant class
variant_type = resolve_vcf_variant_type(ref_allele, alt_allele)
end_pos = resolve_end_position(vcf_data, start_pos, variant_type, ref_allele)
variant_class = resolve_variant_classification(
vcf_data, variant_type, ref_allele, alt_allele
)
maf_data["Variant_Classification"] = variant_class
maf_data["Variant_Type"] = variant_type
maf_data["Reference_Allele"] = ref_allele
maf_data["Tumor_Seq_Allele1"] = ref_allele
maf_data["Tumor_Seq_Allele2"] = alt_allele
maf_data["Start_Position"] = start_pos
maf_data["End_Position"] = end_pos
return maf_data
def resolve_vcf_matched_normal_allele_data(
vcf_data, maf_data, matched_normal_sample_id
):
"""Resolves VCF matched normal seq allele data if normal genotype info is available."""
# if normal genotype info is unavailable then assume normal seq alleles are ref/ref homozygous
maf_data["Match_Norm_Seq_Allele1"] = maf_data["Reference_Allele"]
maf_data["Match_Norm_Seq_Allele2"] = maf_data["Reference_Allele"]
vcf_alleles = [vcf_data["REF"]]
vcf_alleles.extend(vcf_data["ALT"].split(","))
if matched_normal_sample_id in vcf_data.keys():
normal_sample_format_data = vcf_data["MAPPED_NORMAL_FORMAT_DATA"]
if "GT" in normal_sample_format_data.keys() and not is_missing_vcf_data_value(
normal_sample_format_data["GT"]
):
normal_sample_genotype_info = re.split(
"[\/|]", normal_sample_format_data["GT"]
)
match_norm_seq_allele1 = ""
match_norm_seq_allele2 = ""
if len(normal_sample_genotype_info) == 1 and is_valid_integer(
normal_sample_genotype_info[0]
):
match_norm_seq_allele1 = vcf_alleles[
int(normal_sample_genotype_info[0])
]