forked from genome-nexus/annotation-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstandardize_mutation_data.py
More file actions
1624 lines (1409 loc) · 71.5 KB
/
Copy pathstandardize_mutation_data.py
File metadata and controls
1624 lines (1409 loc) · 71.5 KB
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) 2020 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 optparse
import re
import json
from chardet import detect
# ---------------------------- GLOBALS ----------------------------
OUTPUT_FILE = sys.stdout
ERROR_FILE = sys.stderr
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_NCBI_BUILD = "GRCh37"
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"
]
VALID_VARIANT_TYPES = ["SNP", "DNP", "TNP", "ONP", "DEL", "INS"]
MUTATION_FILTER = ["3'Flank", "3'UTR", "5'Flank", "5'UTR", "IGR", "Intron", "RNA", "Silent"]
MUTATION_STATUS_FILTER = ["LOH", "Wildtype"]
# 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(["", ".", "./."])
# problematic files tracker
PROBLEMATIC_FILES_REPORT = {}
# ----------------------------------------------------------------
def get_file_header(filename):
""" Returns the file header as a list. """
header = []
raw_header_line = ""
for line in extract_file_data(filename):
if line.startswith("#"):
continue
raw_header_line = line
header = list(map(str.strip, line.split("\t")))
break
if not header:
print("Could not extract header from mutation data file: %s - Exiting..." % (filename))
sys.exit(2)
return (header, raw_header_line)
def process_datum(value):
"""
Returns a cleaned up data value.
A null or 'empty' value is always returned as an empty string.
"""
try:
vfixed = value.strip().replace('"',"")
except AttributeError:
vfixed = ""
if is_missing_data_value(vfixed):
return ""
return vfixed
def resolve_tumor_seq_alleles(data, ref_allele):
""" Resolve the tumor seq allele. """
tum_seq_allele1 = ""
tum_seq_allele2 = ""
if MUTATED_TO_ALLELE_COLUMN in data.keys():
# use ref allele for tumor seq allele 1 if "mutated_from_allele" not present
# but "mutated_to_allele" is present
tum_seq_allele1 = data.get(MUTATED_FROM_ALLELE_COLUMN, ref_allele)
tum_seq_allele2 = data[MUTATED_TO_ALLELE_COLUMN]
return (tum_seq_allele1, tum_seq_allele2)
for column in TUMOR_SEQ_ALLELE1_COLUMNS:
if column in data.keys():
tum_seq_allele1 = process_datum(data[column])
if tum_seq_allele1 != "":
break
for column in TUMOR_SEQ_ALLELE2_COLUMNS:
if column in data.keys():
tum_seq_allele2 = process_datum(data[column])
if tum_seq_allele2 != "":
break
# if both tumor seq alleles are empty then there might be something wrong with the data
if tum_seq_allele1 == "" and tum_seq_allele2 == "":
return ("", "")
# resolve tumor seq allele 1 from the tumor genotype column if it still has not been resolved
if TUMOR_GENOTYPE_COLUMN in data.keys() and tum_seq_allele1 == "":
tum_seq_allele1 = re.split("[\/|]", data[TUMOR_GENOTYPE_COLUMN])[0]
# the importer determines which tumor seq allele to use as the alt allele
# so simply return the resolved values as they are
return (tum_seq_allele1, tum_seq_allele2)
def print_warning(message):
print(message, file = ERROR_FILE)
def resolve_variant_type(data, ref_allele, tum_seq_allele):
""" Resolve variant type. """
variant_type = ""
for column in VARIANT_TYPE_COLUMNS:
if column in data.keys():
variant_type = process_datum(data[column].upper())
break
if variant_type == "1":
return "SNP"
elif variant_type == "2":
return "INS"
elif variant_type == "3":
return "DEL"
# if variant type is empty or not valid then try
# resolving it based on ref allele and tum seq allele values
if not variant_type in VALID_VARIANT_TYPES:
if len(ref_allele) > len(tum_seq_allele):
variant_type = "DEL"
elif len(ref_allele) < len(tum_seq_allele):
variant_type = "INS"
elif len(ref_allele) == len(tum_seq_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 still not in VALID_VARIANT_TYPES then must be SUB/SNV
if variant_type == "SNV":
variant_type = "SNP"
elif variant_type.upper() == "SUB":
variant_type = "ONP"
# if variant type is still an empty string then report error to user
if variant_type == "":
message = "Could not salvage variant type from alleles [ ref allele = %s , tumor allele = %s ] " % (ref_allele, tum_seq_allele)
print_warning(message)
return variant_type
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_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_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_ref_allele(data):
""" Resolves reference allele. """
ref = ""
for col in REFERENCE_ALLELE_COLUMNS:
if col in data.keys():
ref = data[col]
return ref
def resolve_variant_allele_data(data, maf_data):
"""
Resolves the variant allele data.
Updates maf_data dict with values for:
- Variant_Classification
- Variant_Type
- Reference_Allele
- Tumor_Seq_Allele1
- Tumor_Seq_Allele2
- Start_Position
- End_Position
"""
ref_allele = resolve_ref_allele(data)
(tumor_seq_allele1, tumor_seq_allele2) = resolve_tumor_seq_alleles(data, ref_allele)
# set the general tumor_seq_allele as the first non-ref allele encountered
# this will be used to resolve the variant classification and variant type
# if there are no tumor alleles that do not match the ref allele then use empty string
# in the event that this happens then there might be something wrong with the data itself
tumor_seq_allele = ""
for allele in [tumor_seq_allele1, tumor_seq_allele2]:
if allele != "" and allele != ref_allele:
tumor_seq_allele = allele
break
# resolve start and end positions
start_pos = resolve_start_position(data)
# if the alleles share a common prefix then remove and adjust the start position accordingly
if not is_missing_data_value(ref_allele) and not is_missing_data_value(tumor_seq_allele) and not is_missing_data_value(start_pos):
common_prefix = os.path.commonprefix([ref_allele, tumor_seq_allele])
if common_prefix:
start_pos = str(int(start_pos) + len(common_prefix))
ref_allele = ref_allele[len(common_prefix):]
tumor_seq_allele = tumor_seq_allele[len(common_prefix):]
if not is_missing_data_value(tumor_seq_allele1):
tumor_seq_allele1 = tumor_seq_allele1[len(common_prefix):]
if not is_missing_data_value(tumor_seq_allele2):
tumor_seq_allele2 = tumor_seq_allele2[len(common_prefix):]
# ref and tumor seq allele might have been updated to remove common prefixes
# attempt to resolve the variant type based on the potentially updated allele strings
variant_type = resolve_variant_type(data, ref_allele, tumor_seq_allele)
variant_class = resolve_variant_classification(data, variant_type, ref_allele, tumor_seq_allele)
# fix variant type just in case it was missed before
if variant_class.endswith("INS") and variant_type != "INS":
variant_type = "INS"
elif variant_class.endswith("DEL") and variant_type != "DEL":
variant_type = "DEL"
# fix ref allele and tum seq allele for INS or DEL variant types
if variant_type == "INS" and len(ref_allele) == 0:
ref_allele = "-"
elif variant_type == "DEL" and len(tumor_seq_allele) == 0:
tumor_seq_allele = "-"
end_pos = resolve_end_position(data, start_pos, variant_type, ref_allele)
maf_data["Variant_Classification"] = variant_class
maf_data["Variant_Type"] = variant_type
maf_data["Reference_Allele"] = ref_allele
maf_data["Tumor_Seq_Allele1"] = tumor_seq_allele1
maf_data["Tumor_Seq_Allele2"] = tumor_seq_allele2
maf_data["Start_Position"] = start_pos
maf_data["End_Position"] = end_pos
return maf_data
def resolve_allele_counts_data(data, maf_data):
"""
Resolves allele counts data based on which tumor/normal reads columns are present.
"""
# get defaults from expected maf columns first
t_depth = process_datum(data.get("t_depth", ""))
t_ref_count = process_datum(data.get("t_ref_count", ""))
t_alt_count = process_datum(data.get("t_alt_count", ""))
n_depth = process_datum(data.get("n_depth", ""))
n_ref_count = process_datum(data.get("n_ref_count", ""))
n_alt_count = process_datum(data.get("n_alt_count", ""))
if "Tumor_ReadCount_Total" in data.keys():
# tumor counts
t_depth = process_datum(data.get("Tumor_ReadCount_Total", ""))
t_ref_count = process_datum(data.get("Tumor_ReadCount_Ref", ""))
t_alt_count = process_datum(data.get("Tumor_ReadCount_Alt", ""))
# normal counts
n_depth = process_datum(data.get("Normal_ReadCount_Total", ""))
n_ref_count = process_datum(data.get("Normal_ReadCount_Ref", ""))
n_alt_count = process_datum(data.get("Normal_ReadCount_Alt", ""))
if "TTotCovVal" in data.keys():
# tumor counts
t_depth = process_datum(data.get("TTotCovVal", ""))
t_alt_count = process_datum(data.get("TVarCovVal", ""))
if not t_depth in ["", "None"] and not t_alt_count in ["", "None"]:
t_ref_count = str(int(t_depth) - int(t_alt_count))
# normal counts
n_depth = process_datum(data.get("NTotCovVal", ""))
n_alt_count = process_datum(data.get("NVarCovVal", ""))
if not n_depth in ["", "None"] and not n_alt_count in ["", "None"]:
n_ref_count = str(int(n_depth)-int(n_alt_count))
elif "Ref_Allele_Coverage" in data.keys():
# tumor counts
t_ref_count = process_datum(data.get("Ref_Allele_Coverage", ""))
t_alt_count = process_datum(data.get("Tumor_Seq_Allele1_Coverage", ""))
if t_ref_count != "" and t_alt_count != "":
t_depth = str(int(t_ref_count) + int(t_alt_count))
# normal counts
n_ref_count = process_datum(data.get("Normal_Ref_Allele_Coverage", ""))
n_alt_count = process_datum(data.get("Normal_Seq_Allele1_Coverage", ""))
if n_ref_count != "" and n_alt_count != "":
n_depth = str(int(n_ref_count) + int(n_alt_count))
if "total_read_count" in data.keys():
# tumor counts
t_depth = process_datum(data.get("total_read_count", ""))
t_alt_count = process_datum(data.get("mutant_allele_read_count", ""))
if not t_depth in ["", "None"] and not t_alt_count in ["", "None"]:
t_ref_count = str(int(t_depth) - int(t_alt_count))
maf_data["t_depth"] = t_depth
maf_data["t_ref_count"] = t_ref_count
maf_data["t_alt_count"] = t_alt_count
maf_data["n_depth"] = n_depth
maf_data["n_ref_count"] = n_ref_count
maf_data["n_alt_count"] = n_alt_count
return maf_data
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 resolve_match_normal_sample_barcode(data):
""" Resolves the matched normal sample barcode. """
barcode = ""
for column in MATCHED_NORMAL_SAMPLE_BARCODE_COLUMNS:
if column in data.keys():
barcode = process_datum(data[column])
break
return barcode
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_mutation_status(data):
""" Resolves the mutation status. """
mutation_status = process_datum(data.get("Mutation_Status", DEFAULT_MUTATION_STATUS))
if mutation_status == "":
mutation_status = DEFAULT_MUTATION_STATUS
return mutation_status
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 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_ncbi_build(data):
""" Resolves the NCBI build. """
ncbi_build = ""
for col in ["NCBI_Build", "assembly_version"]:
if col in data.keys():
ncbi_build = process_datum(data.get(col, ""))
break
if ncbi_build == "":
ncbi_build = DEFAULT_NCBI_BUILD
return ncbi_build
def resolve_dbsnp_rs(data):
""" Resolves the dbSNP ID. """
dbsnp_rs = ""
for column in ["dbSNP_RS", "dbSNP rsID"]:
if column in data.keys():
dbsnp_rs = process_datum(data[column])
break
return dbsnp_rs
def resolve_verification_status(data):
""" Resolves the verification status. """
ver_status = ""
for col in VERIFICATION_STATUS_COLUMNS:
if col in data.keys():
ver_status = process_datum(data[col])
if ver_status == "1":
ver_status = "Verified"
elif ver_status == "":
ver_status = DEFAULT_VERIFICATION_STATUS
return ver_status
def resolve_sequencer(data):
""" Resolves the sequencer. """
sequencer = ""
for col in ["Sequencer", "platform"]:
if col in data.keys():
sequencer = process_datum(data.get(col, ""))
break
if sequencer == "60":
sequencer = "Illumina HiSeq 2000"
return sequencer
def resolve_validation_method(data):
""" Resolves validation method. """
validation_method = ""
for col in VALIDATION_METHOD_COLUMNS:
if col in data.keys():
validation_method = process_datum(data.get(col, ""))
break
if validation_method == "60":
validation_method = "Illumina HiSeq (RNAseq)"
elif validation_method == "6":
validation_method = "454 sequencing"
elif validation_method == "67":
validation_method = "Ion Torrent PGM"
elif validation_method == "-888":
validation_method = "NA"
return validation_method
def resolve_match_norm_seq_alleles(data, maf_data):
""" Resolves matched normal seq alleles. """
norm_allele1 = ""
for col in MATCHED_NORMAL_SEQ_ALLELE1_COLUMNS:
if col in data.keys():
norm_allele1 = process_datum(data.get(col,""))
break
norm_allele2 = ""
for col in MATCHED_NORMAL_SEQ_ALLELE2_COLUMNS:
if col in data.keys():
norm_allele2 = process_datum(data.get(col,""))
if col == "control_genotype":
norm_allele2 = norm_allele2.split("/")[1]
break
maf_data["Match_Norm_Seq_Allele1"] = norm_allele1
maf_data["Match_Norm_Seq_Allele2"] = norm_allele2
return maf_data
def create_maf_record_from_maf(filename, data, center_name, sequence_source):
""" Creates a MAF record from a given input MAF. """
maf_data = init_maf_record()
# identify the tumor sample barcode column present in the input MAF
try:
for col in TUMOR_SAMPLE_BARCODE_COLUMNS:
if col in data.keys():
tumor_sample_barcode_col_name = col
break
maf_data["Tumor_Sample_Barcode"] = data[tumor_sample_barcode_col_name]
except AttributeError:
message = "[ERROR] create_maf_record_from_maf(), Error enountered while trying to identify the tumor sample barcode column to use from MAF. "
message += "MAF columns found: %s" % (", ".join(data.keys()))
PROBLEMATIC_FILES_REPORT[filename] = {"ERROR": [message]}
print_warning(message)
return None
# set values for MAF fields
maf_data["Matched_Norm_Sample_Barcode"] = resolve_match_normal_sample_barcode(data)
maf_data["Hugo_Symbol"] = resolve_hugo_symbol(data)
maf_data["Entrez_Gene_Id"] = process_datum(data.get("Entrez_Gene_Id","").split("|")[0])
maf_data["NCBI_Build"] = resolve_ncbi_build(data)
maf_data["Chromosome"] = resolve_chromosome(data)
maf_data["dbSNP_RS"] = resolve_dbsnp_rs(data)
maf_data["Sequencing_Phase"] = process_datum(data.get("Sequencing_Phase", ""))
maf_data["Sequence_Source"] = resolve_sequence_source(data, sequence_source)
maf_data["Validation_Method"] = resolve_validation_method(data)
maf_data["Center"] = resolve_center_name(data, center_name)
maf_data["Verification_Status"] = resolve_verification_status(data)
maf_data["Mutation_Status"] = resolve_mutation_status(data)
maf_data["Center"] = resolve_center_name(data, center_name)
maf_data["Sequencer"] = resolve_sequencer(data)
maf_data["FILTER"] = data.get("FILTER", "")
# if the verification status if "Verified" then the validation status can be set to "Valid"
if maf_data["Verification_Status"] == "Verified":
maf_data["Validation_Status"] = "Valid"
# resolve allele counts for tumor and normal sample
resolve_allele_counts_data(data, maf_data)
resolve_variant_allele_data(data, maf_data)
resolve_match_norm_seq_alleles(data, maf_data)
return maf_data
def detect_file_encoding(filename):
"""
Reads the first million bytes of a file
to detect the type of encoding.
"""
with open(filename, "rb") as data_file:
encoding = detect(data_file.read(52428800))
if encoding["encoding"] != "ascii":
print("[WARNING] detect_file_encoding(), Non-ASCII encoding detected in file %s, encoding type detected: %s - non-ASCII characters will be ignored and removed" % (filename, encoding["encoding"]))
return encoding["encoding"]
def extract_file_data(filename):
"""
Reads in file data with the appropriate encoding
type and returns file data as ascii.
"""
encoding_type = detect_file_encoding(filename)
with open(filename, encoding = encoding_type) as data_file:
filedata = []
for line in data_file.readlines():
# TODO: report on a line-by-line basis if there are non-ascii characters encountered
filedata.append(line.encode("ascii", "ignore").decode("ascii"))
return filedata
def get_vcf_sample_and_normal_ids(filename):
"""
Returns the sample name, tumor sample barcode column,
and normal column/sample id from the VCF file.
Note: The VCF fixed header may not always have "TUMOR" as the column
name where the tumor sample data is stored. Even so it can still be assumed
that the first column following the non-case ID fixed VCF headers is the
column where the tumor data is stored. If there is an additional header
after the "TUMOR" column then it can be assumed that the column contains
data for the "NORMAL" sample.
The "NORMAL" column is optional and can have a different name other than "NORMAL".
As with the "TUMOR" column, it can be assumed that if there is an additional column
present after the "TUMOR" column then this is the column to refer to for extracting
"NORMAL" sample data.
"""
vcf_file_header = []
for line in extract_file_data(filename):
if line.startswith("#CHROM"):
vcf_file_header = list(map(str.strip, line.replace("#", "").split("\t")))
break
# get the case id columns based on which columns in the header are not part of the fixed VCF header
case_ids_cols = [col for col in vcf_file_header if col not in VCF_FIXED_HEADER_NON_CASE_IDS]
if len(case_ids_cols) == 1:
tumor_sample_data_col_name = case_ids_cols[0]
matched_normal_sample_id = "NORMAL"
elif len(case_ids_cols) == 2:
tumor_sample_data_col_name = case_ids_cols[0]
matched_normal_sample_id = case_ids_cols[1]
else:
tumor_sample_data_col_name = "TUMOR"
matched_normal_sample_id = "NORMAL"
if tumor_sample_data_col_name == "TUMOR":
tumor_sample_id = os.path.basename(filename).replace(".vcf", "")
else:
tumor_sample_id = tumor_sample_data_col_name
return (tumor_sample_id, tumor_sample_data_col_name, matched_normal_sample_id)
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_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 extract_vcf_format_info_data(vcf_data, tumor_sample_data_col, matched_normal_sample_id):
"""
Extract data from VCF 'INFO' and 'FORMAT' columns.
The 'INFO' columns stores data as a string of semi-colon separated key-value pairs.
This function formats the data in the 'INFO' column into an actual dictionary.
Example:
vcf_data["INFO"] = { key1;value1, key2:value2, ... }
The 'FORMAT' column stores keys corresponding to values in the 'TUMOR' and 'NORMAL' column
(if 'NORMAL' column is present in the VCF header). This function formats the data in the
'FORMAT' column as a list of keys.
Example:
vcf_data["FORMAT"] = [ key1, key2, ... ]
"""
parsed_vcf_info = {}
for key_value_pair in vcf_data["INFO"].split(";"):
key = process_datum(key_value_pair.split("=")[0])
try:
value = process_datum(key_value_pair.split("=")[1])
except:
value = ""
parsed_vcf_info[key] = value
# if 'FUNC' is a key in the 'INFO' data then promote key-value pairs to primary
# key-value pairs in vcf_data dictionary - "FUNC" may contain important tumor or
# normal sample data such as reads, alleles, etc.
if key.startswith("FUNC"):
# must replace single quotes with double quotes to avoid
# errors when loading string as a json
vcf_func_data = json.loads(str(value.replace("'", '"')))
for elem in vcf_func_data[0].items():
vcf_data[elem[0].upper().strip()] = process_datum(elem[1])
vcf_data["INFO"] = parsed_vcf_info
# the VCF "FORMAT" column stores keys that correspond to values in the "TUMOR"
# column and "NORMAL" column (if "NORMAL" is present) and the keys are
# separated by colons ":"
parsed_vcf_format_keys = list(map(lambda v: process_datum(v), vcf_data["FORMAT"].split(":")))
vcf_data["FORMAT"] = parsed_vcf_format_keys
# map the corresponding values in the VCF tumor column to the appropriate "FORMAT" keys
# which is also separated by colons (":")
tumor_vcf_format_values = list(map(lambda v: process_datum(v), vcf_data[tumor_sample_data_col].split(":")))
vcf_data["MAPPED_TUMOR_FORMAT_DATA"] = dict(zip(parsed_vcf_format_keys, tumor_vcf_format_values))
# repeat above to map the corresponding values in the VCF normal column (if present)
if matched_normal_sample_id in vcf_data.keys():
normal_vcf_format_values = list(map(lambda v: process_datum(v), vcf_data[matched_normal_sample_id].split(":")))
vcf_data["MAPPED_NORMAL_FORMAT_DATA"] = dict(zip(parsed_vcf_format_keys, normal_vcf_format_values))
return vcf_data
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 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"])