-
Notifications
You must be signed in to change notification settings - Fork 61
/
AnnotatorCore.py
1950 lines (1568 loc) · 72.5 KB
/
AnnotatorCore.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/python
import datetime
import json
import csv
import sys
import requests
import os.path
import logging
import re
import ctypes as ct
from enum import Enum
from requests.adapters import HTTPAdapter
from urllib3 import Retry
from datetime import date
logging.basicConfig(level=logging.INFO)
logging.getLogger("requests").setLevel(logging.WARNING)
logging.getLogger("urllib3").setLevel(logging.WARNING)
log = logging.getLogger('AnnotatorCore')
# API timeout is set to two minutes
REQUEST_TIMEOUT = 240
API_REQUEST_RETRY_STATUS_FORCELIST = [429, 500, 502, 503, 504]
csv.field_size_limit(int(ct.c_ulong(
-1).value // 2)) # Deal with overflow problem on Windows, https://stackoverflow.co/120m/questions/15063936/csv-error-field-larger-than-field-limit-131072
sizeLimit = csv.field_size_limit()
csv.field_size_limit(sizeLimit) # for reading large files
DEFAULT_ONCOKB_URL = "https://www.oncokb.org"
oncokb_api_url = DEFAULT_ONCOKB_URL + "/api"
oncokb_annotation_api_url = oncokb_api_url + "/v1"
oncokb_api_bearer_token = ""
# 'U', which no longer has any effect in python 3. 3.11 completely removed the option.
# It will throw error if we don't do condition check.
# https://stackoverflow.com/questions/56791545/what-is-the-non-deprecated-version-of-open-u-mode
DEFAULT_READ_FILE_MODE = 'r' if sys.version_info.major > 2 else 'rU'
def setoncokbbaseurl(u):
if u and u is not None:
global oncokb_api_url
global oncokb_annotation_api_url
oncokb_api_url = u.rstrip('/') + '/api'
oncokb_annotation_api_url = oncokb_api_url + '/v1'
def setoncokbapitoken(t):
global oncokb_api_bearer_token
oncokb_api_bearer_token = t.strip()
cancerhotspotsbaseurl = "http://www.cancerhotspots.org"
def setcancerhotspotsbaseurl(u):
global cancerhotspotsbaseurl
cancerhotspotsbaseurl = u
_3dhotspotsbaseurl = "http://www.3dhotspots.org"
def set3dhotspotsbaseurl(u):
global _3dhotspotsbaseurl
_3dhotspotsbaseurl = u
sampleidsfilter = None
def setsampleidsfileterfile(f):
global sampleidsfilter
content = [line.rstrip() for line in open(f)]
sampleidsfilter = set(content)
log.info(len(sampleidsfilter))
ANNOTATED_HEADER = 'ANNOTATED'
GENE_IN_ONCOKB_HEADER = 'GENE_IN_ONCOKB'
VARIANT_IN_ONCOKB_HEADER = 'VARIANT_IN_ONCOKB'
GENE_IN_ONCOKB_DEFAULT = 'False'
VARIANT_IN_ONCOKB_DEFAULT = 'False'
levels = [
'LEVEL_R1',
'LEVEL_1',
'LEVEL_2',
'LEVEL_3A',
'LEVEL_3B',
'LEVEL_4',
'LEVEL_R2'
]
sensitive_levels = [
'LEVEL_1',
'LEVEL_2',
'LEVEL_3A',
'LEVEL_3B',
'LEVEL_4',
]
resistance_levels = [
'LEVEL_R1',
'LEVEL_R2'
]
TX_TYPE_SENSITIVE = 'sensitive'
TX_TYPE_RESISTANCE = 'resistance'
dxLevels = [
'LEVEL_Dx1',
'LEVEL_Dx2',
'LEVEL_Dx3'
]
pxLevels = [
'LEVEL_Px1',
'LEVEL_Px2',
'LEVEL_Px3'
]
mutationtypeconsequencemap = {
'3\'Flank': ['any'],
'5\'Flank ': ['any'],
'Targeted_Region': ['inframe_deletion', 'inframe_insertion'],
'COMPLEX_INDEL': ['inframe_deletion', 'inframe_insertion'],
'ESSENTIAL_SPLICE_SITE': ['feature_truncation'],
'Exon skipping': ['inframe_deletion'],
'Frameshift deletion': ['frameshift_variant'],
'Frameshift insertion': ['frameshift_variant'],
'FRAMESHIFT_CODING': ['frameshift_variant'],
'Frame_Shift_Del': ['frameshift_variant'],
'Frame_Shift_Ins': ['frameshift_variant'],
'Fusion': ['fusion'],
'Indel': ['frameshift_variant', 'inframe_deletion', 'inframe_insertion'],
'In_Frame_Del': ['inframe_deletion'],
'In_Frame_Ins': ['inframe_insertion'],
'Missense': ['missense_variant'],
'Missense_Mutation': ['missense_variant'],
'Nonsense_Mutation': ['stop_gained'],
'Nonstop_Mutation': ['stop_lost'],
'Splice_Site': ['splice_region_variant'],
'Splice_Site_Del': ['splice_region_variant'],
'Splice_Site_SNP': ['splice_region_variant'],
'splicing': ['splice_region_variant'],
'Translation_Start_Site': ['start_lost'],
'vIII deletion': ['any']
}
CNA_AMPLIFICATION_TXT = 'Amplification'
CNA_DELETION_TXT = 'Deletion'
CNA_LOSS_TXT = 'Loss'
CNA_GAIN_TXT = 'Gain'
CNAS = [
CNA_DELETION_TXT,
CNA_LOSS_TXT,
CNA_GAIN_TXT,
CNA_AMPLIFICATION_TXT,
]
GISTIC_CNA_MAP = {
"-2": CNA_DELETION_TXT,
"-1.5": CNA_DELETION_TXT,
"-1": CNA_LOSS_TXT,
"1": CNA_GAIN_TXT,
"2": CNA_AMPLIFICATION_TXT
}
CNA_FILE_FORMAT_GISTIC = 'gistic'
CNA_FILE_FORMAT_INDIVIDUAL = 'individual'
CND_FILE_FORMAT = [CNA_FILE_FORMAT_GISTIC, CNA_FILE_FORMAT_INDIVIDUAL]
# column headers
HUGO_HEADERS = ['HUGO_SYMBOL', 'HUGO_GENE_SYMBOL', 'GENE']
CONSEQUENCE_HEADERS = ['VARIANT_CLASSIFICATION', 'MUTATION_TYPE']
ALTERATION_HEADER = 'ALTERATION'
HGVSP_SHORT_HEADER = 'HGVSP_SHORT'
HGVSP_HEADER = 'HGVSP'
HGVSG_HEADER = 'HGVSG'
# columns for copy number alteration
CNA_HEADERS = [ALTERATION_HEADER, 'COPY_NUMBER_ALTERATION', 'CNA', 'GISTIC']
HGVS_HEADERS = [ALTERATION_HEADER, HGVSP_SHORT_HEADER, HGVSP_HEADER, HGVSG_HEADER, 'AMINO_ACID_CHANGE',
'FUSION'] + CNA_HEADERS
SAMPLE_HEADERS = ['SAMPLE_ID', 'TUMOR_SAMPLE_BARCODE']
PROTEIN_START_HEADERS = ['PROTEIN_START']
PROTEIN_END_HEADERS = ['PROTEIN_END']
PROTEIN_POSITION_HEADERS = ['PROTEIN_POSITION']
CANCER_TYPE_HEADERS = ['ONCOTREE_CODE', 'CANCER_TYPE']
FUSION_HEADERS = ['FUSION']
REFERENCE_GENOME_HEADERS = ['NCBI_BUILD', 'REFERENCE_GENOME']
# columns for genomic change annotation
GC_CHROMOSOME_HEADER = 'CHROMOSOME'
GC_START_POSITION_HEADER = 'START_POSITION'
GC_END_POSITION_HEADER = 'END_POSITION'
GC_REF_ALLELE_HEADER = 'REFERENCE_ALLELE'
GC_VAR_ALLELE_1_HEADER = 'TUMOR_SEQ_ALLELE1'
GC_VAR_ALLELE_2_HEADER = 'TUMOR_SEQ_ALLELE2'
GENOMIC_CHANGE_HEADERS = [GC_CHROMOSOME_HEADER, GC_START_POSITION_HEADER, GC_END_POSITION_HEADER, GC_REF_ALLELE_HEADER,
GC_VAR_ALLELE_2_HEADER]
# columns for structural variant annotation
SV_GENEA_HEADER = ['SITE1_GENE', 'GENEA', 'GENE1', 'SITE1_HUGO_SYMBOL']
SV_GENEB_HEADER = ['SITE2_GENE', 'GENEB', 'GENE2', 'SITE2_HUGO_SYMBOL']
SV_TYPE_HEADER = ['SV_CLASS_NAME', 'SV_TYPE', 'CLASS']
SV_TYPES = ['DELETION', 'TRANSLOCATION', 'DUPLICATION', 'INSERTION', 'INVERSION', 'FUSION', 'UNKNOWN']
DESCRIPTION_HEADERS = ['GENE_SUMMARY', 'VARIANT_SUMMARY', 'TUMOR_TYPE_SUMMARY', 'DIAGNOSTIC_SUMMARY',
'PROGNOSTIC_SUMMARY', 'MUTATION_EFFECT_DESCRIPTION']
ONCOKB_ANNOTATION_HEADERS_GC = ["ONCOKB_HUGO_SYMBOL", "ONCOKB_PROTEIN_CHANGE", "ONCOKB_CONSEQUENCE"]
UNKNOWN = 'UNKNOWN'
class QueryType(Enum):
HGVSP_SHORT = 'HGVSP_SHORT'
HGVSP = 'HGVSP'
HGVSG = 'HGVSG'
GENOMIC_CHANGE = 'GENOMIC_CHANGE'
class ReferenceGenome(Enum):
GRCH37 = 'GRCh37'
GRCH38 = 'GRCh38'
REQUIRED_QUERY_TYPE_COLUMNS = {
QueryType.HGVSP_SHORT: [HGVSP_SHORT_HEADER],
QueryType.HGVSP: [HGVSP_HEADER],
QueryType.HGVSG: [HGVSG_HEADER],
QueryType.GENOMIC_CHANGE: GENOMIC_CHANGE_HEADERS
}
POST_QUERIES_THRESHOLD = 200
POST_QUERIES_THRESHOLD_GC_HGVSG = 100
def getOncokbInfo():
ret = ['Files annotated on ' + date.today().strftime('%m/%d/%Y') + "\nOncoKB API URL: " + oncokb_annotation_api_url]
try:
info = requests.get(oncokb_annotation_api_url + "/info", timeout=REQUEST_TIMEOUT).json()
ret.append(
'\nOncoKB data version: ' + info['dataVersion']['version'] + ', released on ' + info['dataVersion']['date'])
except Exception:
log.error("error when fetch OncoKB info")
return ''.join(ret)
def validate_oncokb_token():
if not oncokb_annotation_api_url.startswith(DEFAULT_ONCOKB_URL):
log.warning(
"OncoKB base url has been specified by the user that is different from the default www.oncokb.org. The token validation is skipped.")
return None
if oncokb_api_bearer_token is None or not oncokb_api_bearer_token:
log.error("Please specify your OncoKB token")
exit()
response = requests.get(oncokb_api_url + "/tokens/" + oncokb_api_bearer_token, timeout=REQUEST_TIMEOUT)
if response.status_code == 200:
token = response.json()
time_stamp = datetime.datetime.strptime(token['expiration'], "%Y-%m-%dT%H:%M:%SZ")
days_from_expiration = time_stamp - datetime.datetime.now()
if (days_from_expiration.days < 0):
log.error(
"Your OncoKB API token already expired. Please reach out to us to renew your token.")
exit()
elif (days_from_expiration.days < 7):
log.warning(
"Your OncoKB API token will expire soon, please be on the lookout for an OncoKB email to renew your token. Expire on " + str(
time_stamp) + ' UTC')
else:
log.info("Your OncoKB API token is valid and will expire on " + str(time_stamp) + ' UTC')
else:
try:
response_json = response.json()
reason = response_json["title"]
if response_json["detail"]:
reason = response_json["detail"]
except Exception:
reason = response.reason
log.error("Error when validating token, " + "reason: %s" % reason)
exit()
def generateReadme(outfile):
outf = open(outfile, 'w+', 1000)
outf.write(getOncokbInfo())
outf.close()
def gethotspots(url, type):
hotspots = {}
response = requests.get(url, timeout=REQUEST_TIMEOUT)
if response.status_code == 200:
hotspotsjson = response.json()
for hs in hotspotsjson:
gene = hs['hugoSymbol']
start = hs['aminoAcidPosition']['start']
end = hs['aminoAcidPosition']['end']
if type is None or hs['type'] == type:
if gene not in hotspots:
hotspots[gene] = set()
for i in range(start, end + 1):
hotspots[gene].add(i)
else:
log.error("error when processing %s \n" % url + "reason: %s" % response.reason)
return hotspots
def requests_retry_session(
retries=3,
backoff_factor=0.3,
status_forcelist=API_REQUEST_RETRY_STATUS_FORCELIST,
allowed_methods=('GET', 'HEAD'),
session=None,
):
session = session or requests.Session()
retry = Retry(
total=retries,
read=retries,
connect=retries,
backoff_factor=backoff_factor,
status_forcelist=status_forcelist,
allowed_methods=allowed_methods,
)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
return session
def makeoncokbpostrequest(url, body):
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer %s' % oncokb_api_bearer_token
}
return requests_retry_session(allowed_methods=["POST"]).post(url, headers=headers,
data=json.dumps(body, default=lambda o: o.__dict__),
timeout=REQUEST_TIMEOUT)
def makeoncokbgetrequest(url):
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer %s' % oncokb_api_bearer_token
}
return requests_retry_session(allowed_methods=["HEAD", "GET"]).get(url, headers=headers, timeout=REQUEST_TIMEOUT)
_3dhotspots = None
def init_3d_hotspots():
global _3dhotspots
_3dhotspots = gethotspots(_3dhotspotsbaseurl + "/api/hotspots/3d", None)
conversiondict = {'Ala': 'A',
'Asx': 'B',
'Cys': 'C',
'Asp': 'D',
'Glu': 'E',
'Phe': 'F',
'Gly': 'G',
'His': 'H',
'Ile': 'I',
'Lys': 'K',
'Leu': 'L',
'Met': 'M',
'Asn': 'N',
'Pro': 'P',
'Gln': 'Q',
'Arg': 'R',
'Ser': 'S',
'Thr': 'T',
'Val': 'V',
'Trp': 'W',
'Tyr': 'Y',
'Glx': 'Z'
}
conversionlist = conversiondict.keys()
def conversion(hgvs):
threecharactersearch = re.findall(r'[a-zA-Z]{3}\d+', hgvs, flags=re.IGNORECASE)
if threecharactersearch:
if any(letters.lower() in hgvs.lower() for letters in conversionlist):
return replace_all(hgvs)
return hgvs
def replace_all(hgvs):
# Author: Thomas Glaessle
pattern = re.compile('|'.join(conversionlist), re.IGNORECASE)
return pattern.sub(lambda m: conversiondict[m.group().capitalize()], hgvs)
def append_annotation_to_file(outf, ncols, rows, annotations):
if len(rows) != len(annotations):
log.error('The length of the rows and annotations do not match')
for index, annotation in enumerate(annotations):
row = rows[index]
if annotation is not None:
row = row + annotation
row = padrow(row, ncols)
rowstr = '\t'.join(row)
rowstr = rowstr.encode('ascii', 'ignore').decode('ascii')
outf.write(rowstr + "\n")
def get_tumor_type_from_row(row, row_index, defaultCancerType, icancertype, cancerTypeMap, sample):
cancertype = defaultCancerType
if icancertype >= 0:
row_cancer_type = get_cell_content(row, icancertype)
if row_cancer_type is not None:
cancertype = row_cancer_type
if sample in cancerTypeMap:
cancertype = cancerTypeMap[sample]
if cancertype == "":
log.info(
"Cancer type for the sample should be defined for a more accurate result. \tLine %s" % (row_index))
# continue
return cancertype
def has_desired_headers(desired_headers, file_headers):
has_required_headers = True
for header in desired_headers:
if header not in file_headers:
has_required_headers = False
break
return has_required_headers
def resolve_query_type(user_input_query_type, headers):
selected_query_type = None
if isinstance(user_input_query_type, QueryType):
selected_query_type = user_input_query_type
if selected_query_type is None and HGVSP_SHORT_HEADER in headers:
selected_query_type = QueryType.HGVSP_SHORT
if selected_query_type is None and HGVSP_HEADER in headers:
selected_query_type = QueryType.HGVSP
if selected_query_type is None and HGVSG_HEADER in headers:
selected_query_type = QueryType.HGVSG
if selected_query_type is None and has_desired_headers(REQUIRED_QUERY_TYPE_COLUMNS[QueryType.GENOMIC_CHANGE],
headers):
selected_query_type = QueryType.GENOMIC_CHANGE
# default to HGVSp_Short
if selected_query_type is None:
selected_query_type = QueryType.HGVSP_SHORT
# check the file has required columns
if has_desired_headers(REQUIRED_QUERY_TYPE_COLUMNS[selected_query_type], headers) is False:
# when it is False, it will never be GENOMIC_CHANGE. For other types, we need to check whether ALTERATION column is available
if ALTERATION_HEADER not in headers:
raise Exception(
"The file does not have required columns "
+ ', '.join(REQUIRED_QUERY_TYPE_COLUMNS[user_input_query_type])
+ " for the query type: "
+ user_input_query_type.value
)
return selected_query_type
def get_reference_genome_from_row(row_reference_genome, default_reference_genome):
reference_genome = default_reference_genome
if row_reference_genome is not None and row_reference_genome != '':
try:
reference_genome = ReferenceGenome[row_reference_genome.upper()]
except KeyError:
log.warning('Unexpected reference genome, only GRCh37 and GRCh38 are supported.' + (
' Use default.' if default_reference_genome is not None else ' Skipping.'))
return reference_genome
def append_headers(outf, newncols, include_descriptions, genomic_change_annotation):
oncokb_annotation_headers = get_oncokb_annotation_column_headers(include_descriptions, genomic_change_annotation)
outf.write("\t".join(oncokb_annotation_headers))
newncols += len(oncokb_annotation_headers)
outf.write("\n")
return newncols
def processalterationevents(eventfile, outfile, previousoutfile, defaultCancerType, cancerTypeMap,
annotatehotspots, user_input_query_type, default_reference_genome, include_descriptions):
if annotatehotspots:
init_3d_hotspots()
if os.path.isfile(previousoutfile):
cacheannotated(previousoutfile, defaultCancerType, cancerTypeMap)
outf = open(outfile, 'w+', 1000)
with open(eventfile, DEFAULT_READ_FILE_MODE) as infile:
reader = csv.reader(infile, delimiter='\t')
headers = readheaders(reader)
ncols = headers["length"]
if ncols == 0:
return
newncols = 0
outf.write(headers['^-$'])
if annotatehotspots:
outf.write("\tIS-A-HOTSPOT")
outf.write("\tIS-A-3D-HOTSPOT")
newncols += 2
outf.write("\t")
query_type = resolve_query_type(user_input_query_type, headers)
if (query_type == QueryType.HGVSP_SHORT):
newncols = append_headers(outf, newncols, include_descriptions, False)
process_alteration(reader, outf, headers, [HGVSP_SHORT_HEADER, ALTERATION_HEADER], ncols, newncols,
defaultCancerType,
cancerTypeMap, annotatehotspots, default_reference_genome, include_descriptions)
if (query_type == QueryType.HGVSP):
newncols = append_headers(outf, newncols, include_descriptions, False)
process_alteration(reader, outf, headers, [HGVSP_HEADER, ALTERATION_HEADER], ncols, newncols,
defaultCancerType,
cancerTypeMap, annotatehotspots, default_reference_genome, include_descriptions)
if (query_type == QueryType.HGVSG):
newncols = append_headers(outf, newncols, include_descriptions, True)
process_hvsg(reader, outf, headers, [HGVSG_HEADER, ALTERATION_HEADER], ncols, newncols, defaultCancerType,
cancerTypeMap, annotatehotspots, default_reference_genome, include_descriptions)
if (query_type == QueryType.GENOMIC_CHANGE):
newncols = append_headers(outf, newncols, include_descriptions, True)
process_genomic_change(reader, outf, headers, ncols, newncols, defaultCancerType, cancerTypeMap,
annotatehotspots, default_reference_genome, include_descriptions)
outf.close()
def get_cell_content(row, index, return_empty_string=False):
if index >= 0 and row[index] != 'NULL' and row[index] != '':
return row[index]
elif return_empty_string:
return ''
else:
return None
def get_oncokb_annotation_column_headers(include_descriptions, genomic_change_annotation):
headers = [ANNOTATED_HEADER]
if genomic_change_annotation:
headers.extend(ONCOKB_ANNOTATION_HEADERS_GC)
headers.extend([GENE_IN_ONCOKB_HEADER,
VARIANT_IN_ONCOKB_HEADER,
"MUTATION_EFFECT",
"MUTATION_EFFECT_CITATIONS",
"ONCOGENIC"])
for level in sorted(levels):
headers.append(level)
headers.append("HIGHEST_LEVEL")
headers.append("HIGHEST_SENSITIVE_LEVEL")
headers.append("HIGHEST_RESISTANCE_LEVEL")
headers.append("TX_CITATIONS")
for dx_level in dxLevels:
headers.append(dx_level)
headers.append("HIGHEST_DX_LEVEL")
headers.append("DX_CITATIONS")
for px_level in pxLevels:
headers.append(px_level)
headers.append("HIGHEST_PX_LEVEL")
headers.append("PX_CITATIONS")
if include_descriptions:
headers.extend(DESCRIPTION_HEADERS)
return headers
def process_alteration(maffilereader, outf, maf_headers, alteration_column_names, ncols, nannotationcols,
defaultCancerType, cancerTypeMap,
annotatehotspots, default_reference_genome, include_descriptions):
ihugo = geIndexOfHeader(maf_headers, HUGO_HEADERS)
iconsequence = geIndexOfHeader(maf_headers, CONSEQUENCE_HEADERS)
ihgvs = geIndexOfHeader(maf_headers, alteration_column_names)
isample = geIndexOfHeader(maf_headers, SAMPLE_HEADERS)
istart = geIndexOfHeader(maf_headers, PROTEIN_START_HEADERS)
iend = geIndexOfHeader(maf_headers, PROTEIN_END_HEADERS)
iproteinpos = geIndexOfHeader(maf_headers, PROTEIN_POSITION_HEADERS)
icancertype = geIndexOfHeader(maf_headers, CANCER_TYPE_HEADERS)
ireferencegenome = geIndexOfHeader(maf_headers, REFERENCE_GENOME_HEADERS)
posp = re.compile('[0-9]+')
i = 0
queries = []
rows = []
for row in maffilereader:
i = i + 1
if i % POST_QUERIES_THRESHOLD == 0:
log.info(i)
row = padrow(row, ncols)
sample = row[isample]
if sampleidsfilter and sample not in sampleidsfilter:
continue
hugo = row[ihugo]
consequence = get_cell_content(row, iconsequence)
if consequence in mutationtypeconsequencemap:
consequence = '%2B'.join(mutationtypeconsequencemap[consequence])
hgvs = row[ihgvs]
if hgvs.startswith('p.'):
hgvs = hgvs[2:]
cancertype = get_tumor_type_from_row(row, i, defaultCancerType, icancertype, cancerTypeMap, sample)
reference_genome = get_reference_genome_from_row(get_cell_content(row, ireferencegenome),
default_reference_genome)
hgvs = conversion(hgvs)
start = get_cell_content(row, istart)
end = get_cell_content(row, iend)
if start is None and iproteinpos >= 0 and row[iproteinpos] != "" and row[iproteinpos] != "." and \
row[iproteinpos] != "-":
poss = row[iproteinpos].split('/')[0].split('-')
try:
if len(poss) > 0:
start = int(poss[0])
if len(poss) == 2:
end = int(poss[1])
except ValueError:
log.info("position wrong at line %s: %s" % (str(i), row[iproteinpos]))
if start is None and consequence == "missense_variant":
m = posp.search(hgvs)
if m:
start = m.group()
if start is not None and end is None:
end = start
query = ProteinChangeQuery(hugo, hgvs, cancertype, reference_genome, consequence, start, end)
queries.append(query)
rows.append(row)
if len(queries) == POST_QUERIES_THRESHOLD:
annotations = pull_protein_change_info(queries, include_descriptions, annotatehotspots)
append_annotation_to_file(outf, ncols + nannotationcols, rows, annotations)
queries = []
rows = []
if len(queries) > 0:
annotations = pull_protein_change_info(queries, include_descriptions, annotatehotspots)
append_annotation_to_file(outf, ncols + nannotationcols, rows, annotations)
# this method is from genome-nexus annotation-tools
# https://github.com/genome-nexus/annotation-tools/blob/53ff7f7fe673e961282f871ebc78d2ecc0831919/standardize_mutation_data.py
def get_var_allele(ref_allele, tumor_seq_allele1, tumor_seq_allele2):
# 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
# if both alleles are different, use allele2. Stick with the logic of GenomeNexus
try:
tumor_seq_allele = ""
if ref_allele != tumor_seq_allele2:
tumor_seq_allele = tumor_seq_allele2
elif ref_allele != tumor_seq_allele1:
tumor_seq_allele = tumor_seq_allele1
except Exception:
tumor_seq_allele = ""
return tumor_seq_allele
def process_genomic_change(maffilereader, outf, maf_headers, ncols, nannotationcols, defaultCancerType, cancerTypeMap,
annotatehotspots, default_reference_genome, include_descriptions):
ichromosome = geIndexOfHeader(maf_headers, [GC_CHROMOSOME_HEADER])
istart = geIndexOfHeader(maf_headers, [GC_START_POSITION_HEADER])
iend = geIndexOfHeader(maf_headers, [GC_END_POSITION_HEADER])
irefallele = geIndexOfHeader(maf_headers, [GC_REF_ALLELE_HEADER])
ivarallele1 = geIndexOfHeader(maf_headers, [GC_VAR_ALLELE_1_HEADER])
ivarallele2 = geIndexOfHeader(maf_headers, [GC_VAR_ALLELE_2_HEADER])
isample = geIndexOfHeader(maf_headers, SAMPLE_HEADERS)
icancertype = geIndexOfHeader(maf_headers, CANCER_TYPE_HEADERS)
ireferencegenome = geIndexOfHeader(maf_headers, REFERENCE_GENOME_HEADERS)
i = 0
queries = []
rows = []
for row in maffilereader:
i = i + 1
if i % POST_QUERIES_THRESHOLD_GC_HGVSG == 0:
log.info(i)
row = padrow(row, ncols)
sample = row[isample]
if sampleidsfilter and sample not in sampleidsfilter:
continue
cancertype = get_tumor_type_from_row(row, i, defaultCancerType, icancertype, cancerTypeMap, sample)
reference_genome = get_reference_genome_from_row(get_cell_content(row, ireferencegenome),
default_reference_genome)
chromosome = get_cell_content(row, ichromosome, True)
start = get_cell_content(row, istart, True)
end = get_cell_content(row, iend, True)
ref_allele = get_cell_content(row, irefallele, True)
var_allele_1 = get_cell_content(row, ivarallele1, True)
var_allele_2 = get_cell_content(row, ivarallele2, True)
var_allele = get_var_allele(ref_allele, var_allele_1, var_allele_2)
query = GenomicChangeQuery(chromosome, start, end, ref_allele, var_allele, cancertype, reference_genome)
queries.append(query)
rows.append(row)
if len(queries) == POST_QUERIES_THRESHOLD_GC_HGVSG:
annotations = pull_genomic_change_info(queries, include_descriptions, annotatehotspots)
append_annotation_to_file(outf, ncols + nannotationcols, rows, annotations)
queries = []
rows = []
if len(queries) > 0:
annotations = pull_genomic_change_info(queries, include_descriptions, annotatehotspots)
append_annotation_to_file(outf, ncols + nannotationcols, rows, annotations)
def process_hvsg(maffilereader, outf, maf_headers, alteration_column_names, ncols, nannotationcols, defaultCancerType,
cancerTypeMap, annotatehotspots, default_reference_genome, include_descriptions):
ihgvsg = geIndexOfHeader(maf_headers, alteration_column_names)
isample = geIndexOfHeader(maf_headers, SAMPLE_HEADERS)
icancertype = geIndexOfHeader(maf_headers, CANCER_TYPE_HEADERS)
ireferencegenome = geIndexOfHeader(maf_headers, REFERENCE_GENOME_HEADERS)
i = 0
queries = []
rows = []
for row in maffilereader:
i = i + 1
if i % POST_QUERIES_THRESHOLD_GC_HGVSG == 0:
log.info(i)
row = padrow(row, ncols)
sample = row[isample]
if sampleidsfilter and sample not in sampleidsfilter:
continue
hgvsg = get_cell_content(row, ihgvsg)
cancertype = get_tumor_type_from_row(row, i, defaultCancerType, icancertype, cancerTypeMap, sample)
reference_genome = get_reference_genome_from_row(get_cell_content(row, ireferencegenome),
default_reference_genome)
if hgvsg is None:
if annotatehotspots:
default_cols = [['', '', 'False']]
else:
default_cols = [['False']]
append_annotation_to_file(outf, ncols + nannotationcols, [row],
default_cols)
else:
query = HGVSgQuery(hgvsg, cancertype, reference_genome)
queries.append(query)
rows.append(row)
if len(queries) == POST_QUERIES_THRESHOLD_GC_HGVSG:
annotations = pull_hgvsg_info(queries, include_descriptions, annotatehotspots)
append_annotation_to_file(outf, ncols + nannotationcols, rows, annotations)
queries = []
rows = []
if len(queries) > 0:
annotations = pull_hgvsg_info(queries, include_descriptions, annotatehotspots)
append_annotation_to_file(outf, ncols + nannotationcols, rows, annotations)
def getgenesfromfusion(fusion, nameregex=None):
GENES_REGEX = r"([A-Za-z\d]+-[A-Za-z\d]+)" if nameregex is None else nameregex
searchresult = re.search(GENES_REGEX, fusion, flags=re.IGNORECASE)
geneA = None
geneB = None
if searchresult:
parts = searchresult.group(1).split("-")
geneA = parts[0]
geneB = geneA
if len(parts) > 1 and parts[1] != "intragenic":
geneB = parts[1]
else:
geneA = geneB = fusion
return geneA, geneB
def process_fusion(svdata, outfile, previousoutfile, defaultCancerType, cancerTypeMap, nameregex, include_descriptions):
if os.path.isfile(previousoutfile):
cacheannotated(previousoutfile, defaultCancerType, cancerTypeMap)
outf = open(outfile, 'w+')
with open(svdata, DEFAULT_READ_FILE_MODE) as infile:
reader = csv.reader(infile, delimiter='\t')
headers = readheaders(reader)
ncols = headers["length"]
if ncols == 0:
return
outf.write(headers['^-$'])
oncokb_annotation_headers = get_oncokb_annotation_column_headers(include_descriptions, False)
outf.write("\t")
outf.write("\t".join(oncokb_annotation_headers))
outf.write("\n")
newcols = ncols + len(oncokb_annotation_headers)
igeneA = geIndexOfHeader(headers, SV_GENEA_HEADER)
igeneB = geIndexOfHeader(headers, SV_GENEB_HEADER)
ifusion = geIndexOfHeader(headers, FUSION_HEADERS)
isample = geIndexOfHeader(headers, SAMPLE_HEADERS)
icancertype = geIndexOfHeader(headers, CANCER_TYPE_HEADERS)
i = 0
queries = []
rows = []
for row in reader:
i = i + 1
if i % POST_QUERIES_THRESHOLD == 0:
log.info(i)
row = padrow(row, ncols)
sample = row[isample]
if sampleidsfilter and sample not in sampleidsfilter:
continue
geneA = None
geneB = None
if igeneA >= 0:
geneA = row[igeneA]
if igeneB >= 0:
geneB = row[igeneB]
if igeneA < 0 and igeneB < 0 and ifusion >= 0:
fusion = row[ifusion]
geneA, geneB = getgenesfromfusion(fusion, nameregex)
cancertype = get_tumor_type_from_row(row, i, defaultCancerType, icancertype, cancerTypeMap, sample)
queries.append(StructuralVariantQuery(geneA, geneB, 'FUSION', cancertype))
rows.append(row)
if len(queries) == POST_QUERIES_THRESHOLD:
annotations = pull_structural_variant_info(queries, include_descriptions)
append_annotation_to_file(outf, newcols, rows, annotations)
queries = []
rows = []
if len(queries) > 0:
annotations = pull_structural_variant_info(queries, include_descriptions)
append_annotation_to_file(outf, newcols, rows, annotations)
outf.close()
def process_sv(svdata, outfile, previousoutfile, defaultCancerType, cancerTypeMap, include_descriptions):
if os.path.isfile(previousoutfile):
cacheannotated(previousoutfile, defaultCancerType, cancerTypeMap)
outf = open(outfile, 'w+')
with open(svdata, DEFAULT_READ_FILE_MODE) as infile:
reader = csv.reader(infile, delimiter='\t')
headers = readheaders(reader)
ncols = headers["length"]
if ncols == 0:
return
outf.write(headers['^-$'])
oncokb_annotation_headers = get_oncokb_annotation_column_headers(include_descriptions, False)
outf.write("\t")
outf.write("\t".join(oncokb_annotation_headers))
outf.write("\n")
newcols = ncols + len(oncokb_annotation_headers)
igeneA = geIndexOfHeader(headers, SV_GENEA_HEADER)
igeneB = geIndexOfHeader(headers, SV_GENEB_HEADER)
isvtype = geIndexOfHeader(headers, SV_TYPE_HEADER)
isample = geIndexOfHeader(headers, SAMPLE_HEADERS)
icancertype = geIndexOfHeader(headers, CANCER_TYPE_HEADERS)
i = 0
queries = []
rows = []
for row in reader:
i = i + 1
if i % POST_QUERIES_THRESHOLD == 0:
log.info(i)
row = padrow(row, ncols)
sample = row[isample]
if sampleidsfilter and sample not in sampleidsfilter:
continue
if igeneA < 0 or igeneB < 0:
log.warning("Please specify two genes")
continue
svtype = None
if isvtype >= 0:
svtype = row[isvtype].upper()
if svtype not in SV_TYPES:
svtype = None
if svtype is None:
svtype = UNKNOWN
cancertype = get_tumor_type_from_row(row, i, defaultCancerType, icancertype, cancerTypeMap, sample)
sv_query = StructuralVariantQuery(row[igeneA], row[igeneB], svtype, cancertype)
queries.append(sv_query)
rows.append(row)
if len(queries) == POST_QUERIES_THRESHOLD:
annotations = pull_structural_variant_info(queries, include_descriptions)
append_annotation_to_file(outf, newcols, rows, annotations)
queries = []
rows = []
if len(queries) > 0:
annotations = pull_structural_variant_info(queries, include_descriptions)
append_annotation_to_file(outf, newcols, rows, annotations)
outf.close()
def get_cna(cell_value, annotate_gain_loss=False):
cna = None
if cell_value is not None and cell_value != '':
if cell_value in GISTIC_CNA_MAP:
cna = GISTIC_CNA_MAP[cell_value]
else:
for default_cna in CNAS:
if cell_value.upper() == default_cna.upper():
cna = default_cna
if not annotate_gain_loss and cna is not None and cna.upper() in [CNA_GAIN_TXT.upper(), CNA_LOSS_TXT.upper()]:
cna = None
return cna
def process_gistic_data(outf, gistic_data_file, defaultCancerType, cancerTypeMap, annotate_gain_loss,
include_descriptions):
with open(gistic_data_file, DEFAULT_READ_FILE_MODE) as infile:
reader = csv.reader(infile, delimiter='\t')
headers = readheaders(reader)
samples = []
rawsamples = []
if headers["length"] != 0:
startofsamples = getfirstcolumnofsampleingisticdata(headers['^-$'].split('\t'))
rawsamples = headers['^-$'].split('\t')[startofsamples:]
for rs in rawsamples:
samples.append(rs)
if defaultCancerType == '' and not set(cancerTypeMap.keys()).issuperset(set(samples)):
log.info(
"Cancer type for all samples should be defined for a more accurate result\nsamples in cna file: %s\n" % (
samples))
i = 0
rows = []
queries = []