-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenparse.py
More file actions
executable file
·1870 lines (1530 loc) · 62.9 KB
/
Copy pathgenparse.py
File metadata and controls
executable file
·1870 lines (1530 loc) · 62.9 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/python3
"""
Generic CSV / data parsing code.
"""
__author__ = "Sheila M Reynolds"
__version__ = "0.0.2"
__status__ = "Prototype"
import argparse
import ast
import csv
import datetime
import distutils.util as util
import json
import logging
import os
import re
import string
import sys
import time
import warnings
from collections import Counter
import dateutil
import pandas as pd
from biothings_client import get_client
# ----------------------------------------------------------------------------------------------------
gene_client = get_client('gene')
geneSymbolPattern = re.compile("[A-Z0-9]+")
# ----------------------------------------------------------------------------------------------------
def estimateFileSize(fileName):
logging.debug("in estimateFileSize ... <%s>" % fileName)
chunkSizeBytes = 333333333
chunkSizeBytes = 111111111
fileSize = os.path.getsize(fileName)
if (fileSize < chunkSizeBytes):
chunkSizeBytes = fileSize
elif (fileSize < 5*chunkSizeBytes):
chunkSizeBytes = fileSize//5
fh = open(fileName, "r+")
lineBuf = fh.readlines(chunkSizeBytes)
fh.close()
nBuf = len(lineBuf)
rowCountEst = int(nBuf * float(fileSize) / float(chunkSizeBytes))
print(fileSize, chunkSizeBytes, nBuf, rowCountEst)
chunkSizeRows = float(chunkSizeBytes) / \
(float(fileSize)/float(rowCountEst))
if (chunkSizeRows < 0.90*rowCountEst):
if (chunkSizeRows > 10000000):
rndN = 1000000
elif (chunkSizeRows > 1000000):
rndN = 100000
elif (chunkSizeRows > 100000):
rndN = 10000
else:
rndN = 1000
chunkSizeRows = rndN * int(1 + chunkSizeRows/rndN)
numChunks = rowCountEst//chunkSizeRows + 1
else:
chunkSizeRows = -1
numChunks = 1
print(" file size = %d MB" % (fileSize//1000000))
print(" row count estimate = %d" % (rowCountEst))
if (chunkSizeRows > 0):
print(" recommended chunk size = %d" % (chunkSizeRows))
print(" estimated number of chunks = %d" % (numChunks))
else:
print(" file can be read in one chunk")
chunkSizeRows = nBuf + 1000
return (fileSize, rowCountEst, chunkSizeRows, numChunks)
# ----------------------------------------------------------------------------------------------------
# BigQuery data types = ['string','bytes','integer','float','boolean','record','timestamp']
def getFieldType(fConfig):
## print (" ... in getFieldType ... ", fConfig)
if ('bqType' in fConfig):
return (fConfig['bqType'])
for aKey in fConfig:
if (aKey.lower().find("type") > 0):
if (fConfig[aKey] == 'boolean'):
return ('boolean')
if (fConfig[aKey] == 'chromosome'):
return ('string')
if (fConfig[aKey] == 'date'):
return ('string')
if (fConfig[aKey] == 'datetime'):
return ('timestamp')
if (fConfig[aKey] == 'float'):
return ('float')
if (fConfig[aKey] == 'genomic_locus'):
return ('string')
if (fConfig[aKey] == 'integer'):
return ('integer')
if (fConfig[aKey] == 'string'):
return ('string')
print("UHOH in getFieldType: what should I do with this ??? ",
aKey, fConfig[aKey])
return ('string')
# ----------------------------------------------------------------------------------------------------
# optional descriptive text for this field that can go into the BigQuery JSON schema file
def getFieldDescription(fConfig):
if ('description' in fConfig):
return (fConfig['description'])
else:
return ('')
# ----------------------------------------------------------------------------------------------------
# TODO: get rid of this ???
def isHexBlob(s):
logging.debug("in isHexBlob ... <%s>" % s[:128])
if s is None:
return (False)
if not isinstance(s, str):
return (False)
if len(s) == 0:
return (False)
if len(s) < 128:
return (False)
for c in s:
if c not in string.hexdigits:
return (False)
return (True)
# ----------------------------------------------------------------------------------------------------
def stripBlanks(s):
if (str(s) == 'nan'): return ('')
if (s == ''): return ('')
if (not isinstance(s, str)): return (s)
return (s.strip().strip(u'\u200b'))
# ----------------------------------------------------------------------------------------------------
# strip the specified prefix (if present) from the input string ...
def stripPrefixFromStr(s, p):
## print (" in stripPrefixFromStr ... ")
if (str(s) == 'nan'):
return ('')
if (not isinstance(s, str)):
print(" UHOH ??? in stripPrefixFromStr but don't have a string ??? ", s, p)
if (s.startswith(p)):
np = len(p)
t = s[len(p):]
return (t)
return (s)
# ----------------------------------------------------------------------------------------------------
# strip the specified suffix (if present) from the input string ...
def stripSuffixFromStr(s, p):
## print (" in stripSuffixFromStr ... ")
if (str(s) == 'nan'):
return ('')
if (s.endswith(p)):
np = len(p)
t = s[:-len(p)]
return (t)
return (s)
# ----------------------------------------------------------------------------------------------------
def hackDate(s):
if ( s == "00/00/00" ): return ( s )
if ( s == "00/00/0000" ): return ( s )
today = datetime.date.today()
nowYear = int ( today.timetuple()[0] )
i1 = s.find('/')
if ( i1 > 0 ):
i2 = s.find('/',i1+1)
## print ( s, i1, i2 )
if ( i2 > i1 ):
iYear = int ( s[i2+1:] )
if ( iYear == 0 ):
print ( " UHOH year 0 ??? ", s )
return ( s )
elif ( iYear < 100 ):
iYear += 2000
if ( iYear > nowYear ): iYear -= 100
ns = s[:i2+1] + str(iYear)
## print ( " --> returning <%s> " % ns )
return ( ns )
elif ( iYear >= 1850 ):
return ( s )
print ( " UHOH ... did something go wrong in hackDate ??? <%s> " % s )
print ( i1, i2 )
sys.exit(-1)
# ----------------------------------------------------------------------------------------------------
# handle the 'standard' types ...
def handleStandardType(s, p):
if (s == ''):
return (s)
if (str(s) == 'nan'):
return ('')
standardTypeList = ["boolean", "datetime",
"date", "integer", "float", "string"]
## print (" in handleStandardType ... ", s, p)
if (p not in standardTypeList):
logging.warning('invalid standard type ' + p)
print(" UHOH -- invalid standard type ")
return (s)
if (p == "boolean"):
try:
## print (" input: <%s> " % s.strip().lower() )
t = str(bool(util.strtobool(s.strip().lower())))
## print (" got back ", t )
return (t)
except:
print (" UHOH -- FAILED TO interpret/cast to boolean ??? <%s> " % s.strip().lower() )
sys.exit(-1)
elif (p == "datetime"):
# input: 2018-12-18T15:41:29.554Z
# Python ISO format: 2018-12-18T15:41:29.554000+00:00
# 2018-12-18T15:41:29+00:00
try:
t = dateutil.parser.parse(s.strip())
## print (" input: <%s> " % s.strip() )
## print (" ISO format: ", t.isoformat() )
u = str(t.isoformat())[:23]
# the ISO format apparently is a little bit different if
# the fractional part of the seconds is zero
if (u.endswith('+00:')):
u = u[:-4]
## print (" --> returning DATETIME <%s> " % u )
return (u)
except:
print(" UHOH FAILED to interpret as datetime ??? ", s)
elif (p == "date"):
## KNOWN BUG: if the input date is like 06/18/15
## there isn't any real way to know whether this should be 2015 or 1915 ...
if ( s.find('/') > 0 ): s = hackDate(s)
try:
t = dateutil.parser.parse(s.strip())
## print (" input: <%s> " % s.strip() )
## print (" ISO format: ", t.isoformat() )
# keep just the first 10 characters: YYYY-MM-DD
u = str(t.isoformat())[:10]
print (" --> returning DATE <%s> (derived from input string %s) " % ( u, s ) )
return (u)
except:
if (s == "00/00/0000"): return ('')
print (" UHOH FAILED to interpret as date ??? ", s )
elif (p == "integer"):
try:
t = int(s.strip())
u = str(t)
return (u)
except:
print(" UHOH FAILED to interpret as integer ??? ", s)
elif (p == "float"):
try:
t = float(s.strip())
u = str(t)
return (u)
except:
print(" UHOH FAILED to interpret as float ??? ", s)
elif (p == "string"):
# nothing really needs to be done, this 'type' is just being
# included for completeness...
return (s)
else:
print(" UHOH TODO: implement handling for additional pyTypes ... ", p)
sys.exit(-1)
# ----------------------------------------------------------------------------------------------------
def handleCustomType(s, p):
chrList = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10',
'11', '12', '13', '14', '15', '16', '17', '18', '19', '20',
'21', '22', 'X', 'Y', 'M']
if (str(s) == 'nan'):
return ('')
if (s == ''):
return (s)
customTypeList = ["genomic_locus", "chromosome", ]
## print (" in handleCustomType ... ", s, p)
if (p not in customTypeList):
logging.warning('invalid custom type ' + p)
print(" UHOH ... invalid custom type ", p)
return (s)
if (p == "genomic_locus"):
# expecting strings like chrX:1234567 or chr1:98765432-98765437
t = s
if (str(t) == 'nan'):
return ('')
if (not t.startswith('chr')):
t = 'chr' + t
u = t.split(':')
while ('' in u):
u.remove('')
# print(u)
v = u[0][3:]
if (v not in chrList):
print(" INVALID chromosome ??? ", u)
print(" --> re-setting entire string to blank ", s, t, u)
return ('')
# is this something simple like chrX:1234567 ?
if (len(u) == 2):
try:
ipos = int(u[1])
# good to go!
return (t)
# if it's not, then is it something like chr17:112233-123456 ?
except:
if (u[1].find('-') > 0):
v = u[1].split('-')
if (len(v) == 2):
try:
ipos = int(v[0])
jpos = int(v[1])
# good to go!
return (t)
except:
print(" (c) UHOH more complicated ??? ", s, t, u)
print(" (a) UHOH more complicated ??? ", s, t, u)
print(" --> returning (%s) " % t)
# oh well, just return what we have ...
return (t)
else:
# if thre is no ':' then what exactly do we have ???
# it's also possible that we have just something like 'chr17:' ...
if (len(u) == 1):
t = u[0][3:]
if t in chrList:
# if its just the chromosome, it's not really a
# valid 'locus' but we'll return it anyway ...
return (u[0])
# otherwise, let's dump it
print(" UHOH BAD genomic locus ??? !!! <%s> " % t)
print(" --> re-setting to blank")
return ('')
else:
# one common error is that the string looks like
# this: chr3:chr3:987654
# in which case we want to remove the leading 'chr3:'
if (u[1].startswith('chr')):
if (u[0] == u[1]):
u.remove(u[0])
if (len(u) == 2):
try:
ipos = int(u[1])
return (u[0] + ':' + u[1])
except:
print(" (c) UHOH new error type ??? ", t)
else:
print(" UHOH BAD genomic locus ??? !!! <%s> " % t)
print(" (b) UHOH more complicated ??? ", t)
print(" --> returning (%s) " % t)
# oh well, just return what we have ...
return (t)
print(" UHOH ... CRASHING in handleCustomType ... ", s, t)
sys.exit(-1)
if (p == "chromosome"):
if (not s.startswith('chr')):
s = 'chr' + s
t = s[3:]
if t not in chrList:
print(" UHOH INVALID chromosome ??? ", s, t)
print(" --> re-setting to blank")
return ('')
else:
# good to go!
return (s)
print(" UHOH TODO: write more code in handleCustomType !!! ", s)
return (s)
# ----------------------------------------------------------------------------------------------------
def reMatchTest(s, r):
if (s == ''):
return (s)
if (str(s) == 'nan'):
return ('')
## print (" in reMatchTest ... ", s, r)
t = re.match(r, s)
if (t):
## print (" --> TRUE ")
return (s)
else:
## print (" --> FALSE ")
return ("RE-MATCH-FAIL|"+s)
# ----------------------------------------------------------------------------------------------------
def enforceAllowed(s, aList, mDict):
if (str(s) == 'nan'):
return ('')
if (s == ''):
return ('')
print (" in enforceAllowed ... ", aList, mDict)
for m in mDict:
b = m.lower()
t = s.lower()
if (t == b):
print (" --> applying mapping", s, m, mDict[m])
s = mDict[m]
for a in aList:
t = s.lower()
b = a.lower()
if (t == b):
print (" --> found allowed match ", s, a)
return (s)
print(" UHOH failed to match to allowed strings !!! ", s, aList)
sys.exit(-1)
##----------------------------------------------------------------------------------------------------
## this function takes a string that may have line-delimiters and returns it as a list
## of strings split by line ...
def string2list(s):
if (str(s) == 'nan'):
return ('')
if (s == ''):
return ('')
print (" in string2list ... ")
print (" >>> %s <<< " % s )
## total hack to fix a really messed up input string
if ( s == "MET c.3029C>T: p.T1010IMET c.3029C>T: p.T1010I" ):
s = "MET c.3029C>T: p.T1010I"
sList = []
for u in s.splitlines():
u = stripBlanks(u)
if (len(u) > 0):
sList += [u]
if (len(sList) < 1):
return ('')
print (" --> returning from string2list : ", len(sList), str(sList) )
return ( str(sList) )
##----------------------------------------------------------------------------------------------------
def uniqueStringsFromX ( x ):
if ( x is None ): return ( x )
try:
if ( len(x) == 0 ): return ( x )
except:
return ( x )
## print ( " XXXX ... ", x )
if ( isinstance(x,list) ):
nx = []
for a in x:
if len(a) == 0: continue
## print ( type(a), a )
if ( isinstance(a,tuple) or isinstance(a,list) ):
for b in a:
if len(b) == 0: continue
if b not in nx: nx += [ b ]
else:
if a not in nx: nx += [ a ]
## print ( " --> returning : ", nx )
return ( nx )
else:
print ( " XXXX ... need to handle something that is not a list ??? " )
print ( type(x) )
print ( x )
sys.exit(-1)
return ( x )
##----------------------------------------------------------------------------------------------------
def handleKnownTerms ( s ):
knownTerms = { 'amplification':-1, 'splice site':-1, 'promoter':-1, 'fusion':-1, \
'no clinvar entry for this variant':-1, \
'no clinvar entry':-1, 'clinvar reports as':-1, \
'no database entries for this variant':-1, \
'not expected in this sample':-1, \
'expected in this sample':-1, \
'low level variant with no cosmic or dbsnp entries':-1, \
'see previous analysis':-1, \
'(clinically relevant)':-1, \
'clinically relevant':-1, \
'germline':-1, 'exon':-1, \
'likely benign':-1, \
'likely_pathogenic':-1, 'likely pathogenic':-1, \
'pathogenic':-1, \
'unknown_significance':-1, 'unknown significance':-1, \
'tumor mutational burden':-1, 'TMB':-1, \
'microsatellite instability':-1, 'microsatellite':-1, 'MSI':-1 }
lowerTerms = [x.lower() for x in list ( knownTerms.keys() )]
## first, we just need to "find" all the known terms ...
## note that we are assuming that each known terms only appears ONCE
## 12nov2019: we need to find and remove the string(s), so that any of their
## substrings don't also wind up getting 'found' ...
foundTerms = []
nn = 0
t = s
for k in knownTerms:
knownTerms[k] = t.lower().find(k.lower())
if ( knownTerms[k] >= 0 ):
foundTerms += [k]
tt = t[:knownTerms[k]] + t[knownTerms[k]+len(k):]
t = tt
nn += 1
print ( " --> found %d terms ... " % nn, foundTerms )
nn = 0
ix = []
for k in foundTerms:
knownTerms[k] = s.lower().find(k.lower())
if ( knownTerms[k] >= 0 ):
print ( " term %s FOUND at %d ... " % ( k, knownTerms[k] ), s )
nn += 1
ix += [ knownTerms[k], knownTerms[k]+len(k) ]
## if we did NOT find any of these terms, we're done!
if ( nn == 0 ): return ( [s] )
## otherwise, we need to do some more customized string-handling ...
print ( " %d terms found in one alteration string " % nn )
## now let's figure out where we have to split this string ...
ix = list(set(ix))
ix.sort()
print ( " split points : ", len(ix), ix )
logString = "substrings after splitting : "
ss = [''] * (len(ix)+1)
print ( ss )
for js in range(len(ix)+1):
print ( js, ix, s, ss )
if ( js == 0 ):
ss[js] = stripBlanks ( s[:ix[js]] )
elif ( js == len(ix) ):
ss[js] = stripBlanks ( s[ix[js-1]:] )
else:
ss[js] = stripBlanks ( s[ix[js-1]:ix[js]] )
logString += " <%s> " % ss[js]
print ( logString )
## make sure that we don't have any blank substrings ...
## also strip off special characters at the start or end of substrings
## and split strings at ':' and ' ' unless they match a 'known term'
## ( yeah, I know this is hideous )
us = []
for u in ss:
if ( len(u) == 0 ): continue
if ( u[0] in [':','-'] ):
u = stripBlanks ( u[1:] )
if ( len(u) == 0 ): continue
if ( u[-1] in [':','-'] ):
u = stripBlanks ( u[:-1] )
if ( len(u) == 0 ): continue
v = u.split(':')
for w in v:
if ( w.lower() not in knownTerms and w[0]!='(' and w[-1]!=')' ):
z = w.split(' ')
for y in z:
if ( len(y) == 0 ): continue
if ( y not in us ): us += [ y ]
else:
if ( len(w) == 0 ): continue
if ( w not in us ): us += [ w ]
print ( " --> unique substrings : ", us )
## next up, there are 3 known terms that require special handling:
## exon
## microsatellite
## tumor mutational burden
for js in range(len(us)):
u = us[js]
if ( u.lower() == 'exon' ):
print ( js, u )
ns = us[js] + '=' + us[js+1]
print ( ns )
us.remove(us[js])
us.remove(us[js])
print ( us )
us = us[:js] + [ns] + us[js:]
print ( " --> after handling exon : ", us )
break
for js in range(len(us)):
u = us[js]
if ( u.lower() == 'microsatellite' ):
if ( us[js+1].lower() == 'instability' ): us.remove(us[js+1])
ns = 'MSI=' + us[js+1]
us.remove(us[js])
us.remove(us[js])
us = us[:js] + [ns] + us[js:]
print ( " --> after handling MSI : ", us )
break
for js in range(len(us)):
u = us[js]
if ( u.lower() == 'msi' ):
if ( us[js+1].lower() == 'instability' ): us.remove(us[js+1])
ns = 'MSI=' + us[js+1]
us.remove(us[js])
us.remove(us[js])
us = us[:js] + [ns] + us[js:]
print ( " --> after handling MSI : ", us )
break
for js in range(len(us)):
u = us[js]
if ( u.lower() == 'tumor mutational burden' ):
ns = 'TMB=' + us[js+1]
us.remove(us[js])
us.remove(us[js])
us = us[:js] + [ns] + us[js:]
print ( " --> after handling TMB : ", us )
break
for js in range(len(us)):
u = us[js]
if ( u.lower() == 'tmb' ):
ns = 'TMB=' + us[js+1]
us.remove(us[js])
us.remove(us[js])
us = us[:js] + [ns] + us[js:]
print ( " --> after handling TMB : ", us )
break
## we also need to eliminate the blank from strings like 'splice site':
for js in range(len(us)):
u = us[js]
if ( u.lower() == 'splice site' ):
ns = 'splice_site'
us = us[:js] + [ns] + us[js+1:]
print ( " --> after handling splice site : ", us )
break
for js in range(len(us)):
u = us[js]
if ( u.lower() == 'likely pathogenic' ):
ns = 'likely_pathogenic'
us = us[:js] + [ns] + us[js+1:]
print ( " --> after handling likely pathogenic : ", us )
break
for js in range(len(us)):
u = us[js]
if ( u.lower() == 'unknown significance' ):
ns = 'unknown_significance'
us = us[:js] + [ns] + us[js+1:]
print ( " --> after handling unknown significance : ", us )
break
return ( us )
##----------------------------------------------------------------------------------------------------
def noCommonWords ( s ):
cw = ['the', 'but', 'not', 'was', 'is', 'be', 'may', 'in', 'it', 'be', 'at', \
'of', 'from', 'with', 'only', 'like' ]
print ( " checking for common words ... <%s> " % s )
t = s.lower()
for w in cw:
iw = t.find(w)
if ( iw == 0 ):
try:
if ( t[len(w)]==' ' ):
print ( " FOUND CW ", iw, w )
return ( False )
except:
pass
if ( iw > 0 ):
try:
if ( t[iw-1]==' ' ):
if ( t[iw+len(w)]==' ' ):
print ( " FOUND CW ", iw, w )
return ( False )
except:
pass
print ( " NO CW FOUND " )
return ( True )
##----------------------------------------------------------------------------------------------------
def lookForHGVSabbrevs ( s ):
if ( s == '' ): return ( False )
abbrevs = ['c.', 'g.', 'r.', 'p.', 'm.', 'n.']
t = s
## but not inside parenthetical statements ...
while ( t.find ('(') >= 0 ):
i1 = t.find('(')
i2 = t.find(')', i1)
if ( i2 > i1 ):
t = t[:i1] + t[i2+1:]
else:
t = t[:i1]
if ( t == '' ): return ( False )
## also remove a final '.'
if ( t[-1] == '.' ): t = t[:-1]
for a in abbrevs:
skipFlag = False
ia = t.find(a)
if ( ia >= 0 ):
## is there another lower-case letter preceding this?
ja = ia - 1
if ( ja >= 0 ):
ka = ord(t[ja])
print ( ja, t, t[ja], ka )
if ( ka >= 97 and ka <= 122 ):
skipFlag = True
if ( not skipFlag ): return ( True )
return ( False )
##----------------------------------------------------------------------------------------------------
def removeCertainBlanks ( u ):
if ( u == '' ): return ( '' )
d = [' =', '= ', ' :', ': ']
t = u
for e in d:
print ( " e = <%s> " % e )
while ( t.find(e) >= 0 ):
ii = t.find(e)
print ( " ii = %d " % ii )
try:
if ( t[ii] == ' ' ): t = t[:ii] + t[ii+1:]
except:
continue
try:
if ( t[ii+1] == ' ' ): t = t[:ii+1] + t[ii+2:]
except:
continue
if ( t == '' ): return ( '' )
if ( t[0] in ['=',':'] ):
t = t[1:]
if ( t == '' ): return ( '' )
if ( t[-1] in ['=',':'] ):
t = t[:-1]
t = stripBlanks ( t )
return ( t )
##----------------------------------------------------------------------------------------------------
## example:
## we start with: ASXL1 c.2083C>T: p.Q695X
## after "first pass" we have: ['ASXL1 c.2083C>T: p.Q695X']
## after "second pass" we have: ['ASXL1', 'c.2083C>T', 'p.Q695X']
def handleFreeAlterationText ( u ):
print ( " ... in handleFreeAlterationText ... ", type(u), len(u), u )
u = removeCertainBlanks ( u )
## there are a few key words and phrases that we need to look for ...
## but maybe only when there is something like a coding- or protein-variant ???
if ( lookForHGVSabbrevs(u) and noCommonWords(u) ):
v = handleKnownTerms ( u )
else:
print ( " skipping the handleKnownTerms part ... " )
v = [ u ]
print ( " ==> first pass produces : ", v )
## is there anything else we need to do ??? probably is ...
vv = []
for w in v:
if ( lookForHGVSabbrevs(w) and noCommonWords(w) ):
z = uniqueStringsFromX ( re.split('\s|:', w) )
else:
z = [ w ]
vv += z
print ( " ==> second pass produces : ", vv )
## evidently sometimes we get here and the 'c.' and/or the 'p,'
## have been separated from the rest of the HGVS description ...
if ( 'c.' in vv ):
if ( 1 ):
ic = vv.index('c.')
print ( " found 'c.' at %d " % ic, vv )
pref = vv[:ic]
try:
suff = vv[ic+2:]
except:
suff = []
print ( " ", pref, suff )
try:
if ( vv[ic+1][0] in [ '*', 'A', 'C', 'G', 'T', '-', '1', '2', '3', '4', '5', '6', '7', '8', '9' ] ):
ns = vv[ic] + vv[ic+1]
else:
ns = vv[ic+1]
except:
ns = ''
print ( " ns = <%s> " % ns )
vv = pref + [ns] + suff
print ( " FIXED : ", vv )
## except:
## print ( " FAILED to fix a problem ??? ", vv )
if ( 'p.' in vv ):
if ( 1 ):
ic = vv.index('p.')
print ( " found 'p.' at %d " % ic, vv )
if ( ic == len(vv)-1 ):
print ( " but it's at the end, so ditching ... " )
vv = vv[:-1]
else:
pref = vv[:ic]
try:
suff = vv[ic+2:]
except:
suff = []
print ( " ", pref, suff )
try:
if ( ord(vv[ic+1][0])>=65 and ord(vv[ic+1][0])<=90 ):
ns = vv[ic] + vv[ic+1]
else:
ns = vv[ic+1]
except:
ns = ''
print ( " ns = <%s> " % ns )
vv = pref + [ns] + suff
print ( " FIXED : ", vv )
## except:
## print ( " FAILED to fix a problem ??? ", vv )
return ( vv )
##----------------------------------------------------------------------------------------------------
def findLongestInteger(s):
if ( s[0] == '*' ):
print ( " in findLongestInteger ... ignoring leading * ... " )
s = s[1:]
ii = len(s)
done = False
while not done:
try:
ipos = int(s[:ii])
done = True
return ( ipos )
except:
ii -= 1
## print ( " in findLongestInteger ... nothing worked !!! ", s )
if ( ii == 0 ): return ( None )
##----------------------------------------------------------------------------------------------------
## one problematic example seems to be c.GG34_35TT
def handleRefPosVar ( s ):
## not really sure if * should be considered a valid nucleotide ... ???
validN = ['A', 'C', 'G', 'T', 'N', '*']
try:
j1 = 0
while ( s[j1] in validN ): j1 += 1
j2 = len(s) - 1
while ( s[j2] in validN ): j2 -= 1
print ( s, j1, j2 )
ref = s[:j1]
pstr = s[j1:j2+1]
var = s[j2+1:]
print ( " in handlRefPosVar ... ", ref, pstr, var )
except:
return ( s )
try:
ipos = int ( pstr )
print ( " --> integer position : ", ipos )
except:
print ( " UHOH ... first attempt at getting integer position failed ??? ", pstr )
try:
ipos = int ( pstr[:-1] )
print ( " --> second attempt: ", ipos )
except:
print ( " UHOH ... still not working in handlRefPosVar ??? ", pstr )
if ( pstr.find('_') > 0 ):
print ( " ... AAAAAH ... need to deal with underscore too ... " )
sys.exit(-1)
return ( 'c.' + str(ipos) + ref + '>' + var )
##----------------------------------------------------------------------------------------------------
def validateCodingAlt(w):
## 12nov2019: this function was bombing on c.*2336_*2339del ... FIXED
## not really sure if * should be considered a valid nucleotide ... ???