-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmulti_sieve.py
executable file
·1908 lines (1443 loc) · 68.9 KB
/
multi_sieve.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
# -*- coding: UTF-8 -*-
import os
import argparse
import codecs
import re
import shutil
from jpype import *
from data import get_fda_file, get_bioc_file
import logging
from data_structure import Entity
import norm_utils
from options import opt
import numpy as np
class Util:
@classmethod
def setMap(self, keyValueListMap, key, value):
valueList = keyValueListMap.get(key)
if valueList == None:
valueList = list()
keyValueListMap[key] = valueList
valueList = Util.setList(valueList, value)
return keyValueListMap
@classmethod
def setList(self, listt, value):
if (value not in listt) and (value != u""):
listt.append(value)
return listt
@classmethod
def firstIndexOf(self, tokens, i, pattern):
while i >=0:
if re.match(pattern+r".*", tokens[i]):
i -= 1
return i
i -= 1
return -1
@classmethod
def read(self, file_path):
with codecs.open(file_path, 'r', 'UTF-8') as fp:
return fp.read()
@classmethod
def containsAny(self, first, second):
first_ = set(first)
second_ = set(second)
return len(first_ & second_) != 0
@classmethod
def getTokenIndex (self, tokens, token):
i = 0
while i < len(tokens):
if tokens[i] == token:
return i
i += 1
return -1
@classmethod
def addUnique(self, list, newList):
for value in newList:
list = Util.setList(list, value)
return list
class Abbreviation:
wikiAbbreviationExpansionListMap = dict()
def __init__(self):
self.textAbbreviationExpansionMap = dict()
@classmethod
def setWikiAbbreviationExpansionMap(self, file_path):
with codecs.open(file_path, 'r', 'UTF-8') as fp:
for line in fp:
line = line.strip()
token = re.split(r"\|\|", line)
Abbreviation.wikiAbbreviationExpansionListMap = Util.setMap(Abbreviation.wikiAbbreviationExpansionListMap, token[0].lower(), token[1].lower())
@classmethod
def clearWikiAbbreviationExpansionMap(self):
Abbreviation.wikiAbbreviationExpansionListMap.clear()
@classmethod
def getTentativeExpansion(self, tokens, i, abbreviationLength):
expansion = u""
while (i >= 0 and abbreviationLength > 0):
expansion = tokens[i]+" "+expansion
i -= 1
abbreviationLength -= 1
return expansion.strip()
@classmethod
def getExpansionByHearstAlgorithm(self, shortForm, longForm):
sIndex = len(shortForm) - 1
lIndex = len(longForm) - 1
while(sIndex >= 0):
currChar = shortForm[sIndex].lower()
if not currChar.isalnum():
sIndex -= 1
continue
while (((lIndex >= 0) and
(longForm[lIndex].lower() != currChar)) or
((sIndex == 0) and (lIndex > 0) and
(longForm[lIndex-1].isalnum()))):
lIndex -= 1
if lIndex < 0:
return u""
lIndex -= 1
sIndex -= 1
lIndex = longForm.rfind(u" ", lIndex) + 1
longForm = longForm[lIndex:]
return longForm
@classmethod
def getEntireAbbreviation(self, text, string, indexes):
if len(indexes) != 2:
return string
begin = int(indexes[0])
end = int(indexes[1])
if re.match(r"(^|\s|\W)[a-zA-Z]/"+string+r"/[a-zA-Z](\s|$|\W)", text[begin-3, end+3].lower()) :
return text[begin-2, end+2].lower()
elif re.matches(r"(^|\s|\W)"+string+r"/[a-zA-Z]/[a-zA-Z](\s|$|\W)", text[begin-1, end+5].lower()):
return text[begin, end+4].lower()
elif re.matches(r"(^|\s|\W)[a-zA-Z]/[a-zA-Z]/"+string+r"(\s|$|\W)", text[begin-5, end+1].lower()):
return text[begin-4, end].lower()
return string
@classmethod
def getBestExpansion(self, text, expansionList):
maxNumberOfContentWords = 0
maxContainedContentWords = 0
returnExpansion = u""
for expansion in expansionList:
expansionContentWordsList = Ling.getContentWordsList(re.split(r"\s", expansion))
tempNumberOfContentWords = len(expansionContentWordsList)
tempContainedContentWords = 0
for expansionContentWord in expansionContentWordsList:
if text.find(u" " + expansionContentWord) != -1 or text.find(expansionContentWord + u" ") != -1:
tempContainedContentWords += 1
if tempNumberOfContentWords > maxNumberOfContentWords and tempContainedContentWords == tempNumberOfContentWords:
maxNumberOfContentWords = tempNumberOfContentWords
maxContainedContentWords = 1000
returnExpansion = expansion
elif tempNumberOfContentWords >= maxNumberOfContentWords and tempContainedContentWords > maxContainedContentWords:
maxNumberOfContentWords = tempNumberOfContentWords
maxContainedContentWords = tempContainedContentWords
returnExpansion = expansion
return returnExpansion
@classmethod
def getTrimmedExpansion(self, text, string, indexes, expansion):
if len(indexes) != 2:
return string
begin = int(indexes[0])
end = int(indexes[1])
if re.matches(r"(^|\s|\W)[a-zA-Z]/"+string+r"/[a-zA-Z](\s|$|\W)", text[begin-3, end+3].lower()):
return expansion[1].lower()
elif re.matches(r"(^|\s|\W)"+string+r"/[a-zA-Z]/[a-zA-Z](\s|$|\W)", text[begin-1, end+5].lower()):
return expansion[0].lower()
elif re.matches(r"(^|\s|\W)[a-zA-Z]/[a-zA-Z]/"+string+r"(\s|$|\W)", text[begin-5, end+1].lower()):
return expansion[2].lower()
return string
@classmethod
def getAbbreviationExpansion(self, abbreviationObject, text, string, indexes):
shortForm_longForm_map = abbreviationObject.getTextAbbreviationExpansionMap()
stringTokens = re.split(r"\s", string)
if len(stringTokens) == 1 and len(stringTokens[0]) == 1 :
stringTokens[0] = Abbreviation.getEntireAbbreviation(text, string, re.split(r"\|", indexes))
newString = u""
for stringToken in stringTokens:
if stringToken in shortForm_longForm_map:
newString += shortForm_longForm_map.get(stringToken)+u" "
continue
candidateExpansionsList = Abbreviation.wikiAbbreviationExpansionListMap.get(stringToken) if stringToken in Abbreviation.wikiAbbreviationExpansionListMap else None
if candidateExpansionsList == None:
newString += stringToken + u" "
else :
expansion = candidateExpansionsList[0] if len(candidateExpansionsList) == 1 else Abbreviation.getBestExpansion(text, candidateExpansionsList)
if expansion == u"":
newString += stringToken + u" "
else:
newString += expansion + u" "
if len(stringTokens) == 1 and stringTokens[0] != string:
newString = getTrimmedExpansion(text, string, re.split(r"\|", indexes), re.split(r"/", newString))
newString = newString.strip()
return u"" if newString == (string) else newString
def setTextAbbreviationExpansionMap_(self, tokens, abbreviationLength, abbreviation, expansionIndex):
expansion = Abbreviation.getTentativeExpansion(tokens, expansionIndex, abbreviationLength)
expansion = Abbreviation.getExpansionByHearstAlgorithm(abbreviation, expansion).lower().strip()
if expansion != u"":
self.textAbbreviationExpansionMap[abbreviation] = expansion
def setTextAbbreviationExpansionMap (self, text):
lines = re.split(r"\n+", text)
for line in lines:
line = line.strip()
tokens = re.split(r"\s+", line)
size = len(tokens)
for i in range(size):
expansionIndex = -1
if (re.match(r"\(\w+(\-\w+)?\)(,|\.)?", tokens[i])) or (re.match(r"\([A-Z]+(;|,|\.)", tokens[i])):
expansionIndex = i - 1
elif re.match(r"[A-Z]+\)", tokens[i]):
expansionIndex = Util.firstIndexOf(tokens, i, r"\(")
if expansionIndex == -1:
continue
abbreviation = tokens[i].replace(u"(", u"").replace(u")", u"").lower()
reversedAbbreviation = Ling.reverse(abbreviation)
if abbreviation[len(abbreviation) - 1] == u',' or abbreviation[len(abbreviation) - 1] == u'.' or abbreviation[len(abbreviation) - 1] == u';':
abbreviation = abbreviation[0: len(abbreviation) - 1]
if (abbreviation in self.textAbbreviationExpansionMap) or (reversedAbbreviation in self.textAbbreviationExpansionMap):
continue
abbreviationLength = len(abbreviation)
self.setTextAbbreviationExpansionMap_(tokens, abbreviationLength, abbreviation, expansionIndex)
if abbreviation not in self.textAbbreviationExpansionMap:
self.setTextAbbreviationExpansionMap_(tokens, abbreviationLength, reversedAbbreviation, expansionIndex)
def getTextAbbreviationExpansionMap(self):
return self.textAbbreviationExpansionMap
class Ling:
stopwords = set()
digitToWordMap = dict()
wordToDigitMap = dict()
suffixMap = dict()
prefixMap = dict()
affixMap = dict()
logging.info("JVM class path {}".format(os.path.abspath(".")))
startJVM(getDefaultJVMPath(), "-ea", "-Dfile.encoding=UTF-8", "-Djava.class.path={}".format(os.path.abspath(".")))
PorterStemmer = JClass("PorterStemmer")
AFFIX = u"ganglioma|cancer"
PLURAL_DISORDER_SYNONYMS = [u"diseases", u"disorders", u"conditions", u"syndromes", u"symptoms",
u"abnormalities", u"events", u"episodes", u"issues", u"impairments"]
PREPOSITIONS = [u"in", u"with", u"on", u"of"]
SINGULAR_DISORDER_SYNONYMS = [u"disease", u"disorder", u"condition", u"syndrome", u"symptom",
u"abnormality", u"NOS", u"event", u"episode", u"issue", u"impairment"]
def __init__(self):
pass
@classmethod
def setStopwordsList(self, file_path):
with codecs.open(file_path, 'r', 'UTF-8') as fp:
for line in fp:
line = line.strip()
if line == u'':
continue
Ling.stopwords.add(line)
@classmethod
def getStopwordsList(self):
return Ling.stopwords
@classmethod
def clearStopwordsList(self):
Ling.stopwords.clear()
@classmethod
def setDigitToWordformMapAndReverse(self, file_path):
with codecs.open(file_path, 'r', 'UTF-8') as fp:
for line in fp:
line = line.strip()
tokens = re.split(r"\|\|", line)
Ling.digitToWordMap = Util.setMap(Ling.digitToWordMap, tokens[0], tokens[1]);
Ling.wordToDigitMap[tokens[1]]=tokens[0]
@classmethod
def clearDigitToWordformMapAndReverse(self):
Ling.digitToWordMap.clear()
Ling.wordToDigitMap.clear()
@classmethod
def setSuffixMap(self, file_path):
with codecs.open(file_path, 'r', 'UTF-8') as fp:
for line in fp:
line = line.strip()
tokens = re.split(r"\|\|", line)
if len(tokens) == 1:
values = Ling.suffixMap.get(tokens[0])
if values == None:
values = list()
Ling.suffixMap[tokens[0]]=values
else:
Ling.suffixMap = Util.setMap(Ling.suffixMap, tokens[0], tokens[1])
@classmethod
def clearSuffixMap(self):
Ling.suffixMap.clear()
@classmethod
def setPrefixMap(self, file_path):
with codecs.open(file_path, 'r', 'UTF-8') as fp:
for line in fp:
line = line.strip()
tokens = re.split(r"\|\|", line)
value = u"" if len(tokens) == 1 else tokens[1]
Ling.prefixMap[tokens[0]] = value
@classmethod
def clearPrefixMap(self):
Ling.prefixMap.clear()
@classmethod
def setAffixMap(self, file_path):
with codecs.open(file_path, 'r', 'UTF-8') as fp:
for line in fp:
line = line.strip()
tokens = re.split(r"\|\|", line)
value = u"" if len(tokens) == 1 else tokens[1]
Ling.affixMap[tokens[0]] = value
@classmethod
def clearAffixMap(self):
Ling.affixMap.clear()
@classmethod
def getStemmedPhrase(self, string):
stemmed_name = u""
str_tokens = re.split(r"\s+", string)
for token in str_tokens:
if token in Ling.stopwords:
stemmed_name += token + u" "
continue
stemmed_token = Ling.PorterStemmer.get_stem(token).strip()
if stemmed_token == u"":
stemmed_token = token
stemmed_name += stemmed_token + u" "
stemmed_name = stemmed_name.strip()
return stemmed_name
@classmethod
def reverse(self, string):
reversedString = u""
size = len(string)-1
for i in range(size, -1, -1):
reversedString += string[i]
return reversedString
@classmethod
def getContentWordsList(self, words):
contentWordsList = list()
for word in words:
if word in Ling.stopwords:
continue
contentWordsList = Util.setList(contentWordsList, word)
return contentWordsList
@classmethod
def getStringPreposition(self, string):
for preposition in Ling.PREPOSITIONS:
if string.find(u" "+preposition+u" ") != -1:
return preposition
return u""
@classmethod
def getSubstring(self, tokens, begin, end):
substring = u""
i = begin
while i < end:
substring += tokens[i]+u" "
i += 1
substring = substring.strip()
return substring
@classmethod
def getDigitToWordMap(self):
return Ling.digitToWordMap
@classmethod
def getWordToDigitMap(self):
return Ling.wordToDigitMap
@classmethod
def getSuffix_(self, str, len_):
if len(str) < len_:
return u""
return str[len(str) - len_]
@classmethod
def getSuffix(self, str):
if Ling.getSuffix_(str, 10) in Ling.suffixMap:
return Ling.getSuffix_(str, 10)
else:
if Ling.getSuffix_(str, 7) in Ling.suffixMap:
return Ling.getSuffix_(str, 7)
else:
if Ling.getSuffix_(str, 6) in Ling.suffixMap:
return Ling.getSuffix_(str, 6)
else:
if Ling.getSuffix_(str, 5) in Ling.suffixMap:
return Ling.getSuffix_(str, 5)
else:
if Ling.getSuffix_(str, 4) in Ling.suffixMap:
return Ling.getSuffix_(str, 4)
else:
if Ling.getSuffix_(str, 3) in Ling.suffixMap:
return Ling.getSuffix_(str, 3)
else:
if Ling.getSuffix_(str, 2) in Ling.suffixMap:
return Ling.getSuffix_(str, 2)
else:
return u""
@classmethod
def getSuffixMap(self):
return Ling.suffixMap
@classmethod
def getPrefix_(self, str, len_):
if len(str) < len_:
return u""
return str[0 : len_]
@classmethod
def getPrefix(self, str):
if Ling.getPrefix_(str, 5) in Ling.prefixMap:
return Ling.getPrefix_(str, 5)
else:
if Ling.getPrefix_(str, 4) in Ling.prefixMap:
return Ling.getPrefix_(str, 4)
else:
if Ling.getPrefix_(str, 3) in Ling.prefixMap:
return Ling.getPrefix_(str, 3)
else:
return u""
@classmethod
def getPrefixMap(self):
return Ling.prefixMap
@classmethod
def getAffixMap(self):
return Ling.affixMap
@classmethod
def getMatchingTokensCount(self, phrase1, phrase2):
tokens = re.split(r"\s+", phrase1)
temp = list()
temp1 = re.split(r"\s+", phrase2)
for t in tokens:
if t in temp1:
temp.append(t)
tokens = temp
temp = list()
for t in tokens:
if t in Ling.stopwords:
continue
temp.append(t)
tokens = temp
return 0 if len(tokens) == 0 else len(tokens)
class Terminology:
def __init__(self):
self.cuiAlternateCuiMap = dict()
self.nameToCuiListMap = dict()
self.cuiToNameListMap = dict()
self.stemmedNameToCuiListMap = dict()
self.cuiToStemmedNameListMap = dict()
self.tokenToNameListMap = dict()
self.compoundNameToCuiListMap = dict()
self.simpleNameToCuiListMap = dict()
def getTokenToNameListMap(self):
return self.tokenToNameListMap
def getSimpleNameToCuiListMap(self):
return self.simpleNameToCuiListMap
def getCuiToNameListMap(self):
return self.cuiToNameListMap
def getCompoundNameToCuiListMap(self):
return self.compoundNameToCuiListMap
def getStemmedNameToCuiListMap(self):
return self.stemmedNameToCuiListMap
def getNameToCuiListMap(self):
return self.nameToCuiListMap
def getCuiAlternateCuiMap(self):
return self.cuiAlternateCuiMap
def loadMaps(self, conceptName, cui):
self.nameToCuiListMap = Util.setMap(self.nameToCuiListMap, conceptName, cui)
self.cuiToNameListMap = Util.setMap(self.cuiToNameListMap, cui, conceptName)
stemmedConceptName = Ling.getStemmedPhrase(conceptName)
self.stemmedNameToCuiListMap = Util.setMap(self.stemmedNameToCuiListMap, stemmedConceptName, cui)
self.cuiToStemmedNameListMap = Util.setMap(self.cuiToStemmedNameListMap, cui, stemmedConceptName)
conceptNameTokens = re.split(r"\s+", conceptName)
for conceptNameToken in conceptNameTokens:
if conceptNameToken in Ling.getStopwordsList():
continue
self.tokenToNameListMap = Util.setMap(self.tokenToNameListMap, conceptNameToken, conceptName);
def loadTerminology(self, dictionary, isMeddra_dict):
# with codecs.open(path, 'r', 'UTF-8') as fp:
# for line in fp:
# line = line.strip()
# if line == u'':
# continue
# token = re.split(r"\|\|", line)
# cui = token[0]
#
# conceptNames = token[1].lower()
#
# self.loadMaps(conceptNames, cui)
if isMeddra_dict:
for cui, conceptNames in dictionary.items():
self.loadMaps(conceptNames.lower(), cui)
else:
for cui, concept in dictionary.items():
for concept_name in concept.names:
self.loadMaps(concept_name.lower(), cui)
def clearTerminology(self):
self.cuiAlternateCuiMap.clear()
self.nameToCuiListMap.clear()
self.cuiToNameListMap.clear()
self.stemmedNameToCuiListMap.clear()
self.cuiToStemmedNameListMap.clear()
self.tokenToNameListMap.clear()
self.compoundNameToCuiListMap.clear()
self.simpleNameToCuiListMap.clear()
def loadTrainingDataTerminology(self, documents, dictionary_reverse, isMeddra_dict):
for document in documents:
for mention in document.entities:
conceptName = mention.name.lower().strip()
for idx, norm_id in enumerate(mention.norm_ids):
if isMeddra_dict:
self.loadMaps(conceptName, norm_id)
cui = norm_id
simpleConceptNames = SimpleNameSieve.getTerminologySimpleNames(re.split(r"\s+", conceptName))
for simpleConceptName in simpleConceptNames:
self.simpleNameToCuiListMap = Util.setMap(self.simpleNameToCuiListMap, simpleConceptName,
cui)
else:
if norm_id in dictionary_reverse:
cui = dictionary_reverse[norm_id]
self.loadMaps(conceptName, cui[0])
simpleConceptNames = SimpleNameSieve.getTerminologySimpleNames(
re.split(r"\s+", conceptName))
for simpleConceptName in simpleConceptNames:
self.simpleNameToCuiListMap = Util.setMap(self.simpleNameToCuiListMap,
simpleConceptName,
cui[0])
def loadTrainingDataTerminology_frompath(self, path, dictionary_reverse, isMeddra_dict):
for input_file_name in os.listdir(path):
if input_file_name.find(".xml") == -1:
continue
input_file_path = os.path.join(path, input_file_name)
if isMeddra_dict:
annotation_file = get_fda_file(input_file_path)
for mention in annotation_file.mentions:
conceptName = mention.name.lower().strip()
for idx, norm_id in enumerate(mention.norm_ids):
self.loadMaps(conceptName, norm_id)
cui = norm_id
simpleConceptNames = SimpleNameSieve.getTerminologySimpleNames(re.split(r"\s+", conceptName))
for simpleConceptName in simpleConceptNames:
self.simpleNameToCuiListMap = Util.setMap(self.simpleNameToCuiListMap, simpleConceptName, cui)
else:
annotation_file = get_bioc_file(input_file_path)
bioc_passage = annotation_file[0].passages[0]
for entity in bioc_passage.annotations:
if opt.types and (entity.infons['type'] not in opt.type_filter):
continue
conceptName = entity.text.lower().strip()
if ('SNOMED code' in entity.infons and entity.infons['SNOMED code'] != 'N/A') :
if entity.infons['SNOMED code'] in dictionary_reverse:
cui = dictionary_reverse[entity.infons['SNOMED code']]
self.loadMaps(conceptName, cui[0])
simpleConceptNames = SimpleNameSieve.getTerminologySimpleNames(
re.split(r"\s+", conceptName))
for simpleConceptName in simpleConceptNames:
self.simpleNameToCuiListMap = Util.setMap(self.simpleNameToCuiListMap,
simpleConceptName,
cui[0])
elif ('MedDRA code' in entity.infons and entity.infons['MedDRA code'] != 'N/A') :
if entity.infons['MedDRA code'] in dictionary_reverse:
cui = dictionary_reverse[entity.infons['MedDRA code']]
self.loadMaps(conceptName, cui[0])
simpleConceptNames = SimpleNameSieve.getTerminologySimpleNames(
re.split(r"\s+", conceptName))
for simpleConceptName in simpleConceptNames:
self.simpleNameToCuiListMap = Util.setMap(self.simpleNameToCuiListMap,
simpleConceptName,
cui[0])
def loadTAC2017Terminology(self, path, dictionary):
for input_file_name in os.listdir(path):
if input_file_name.find(".xml") == -1:
continue
input_file_path = os.path.join(path, input_file_name)
annotation_file = get_fda_file(input_file_path)
for reaction in annotation_file.reactions:
conceptName = reaction.name.lower().strip()
for normalization in reaction.normalizations:
if normalization.meddra_pt_id is None:
continue
if normalization.meddra_pt_id not in dictionary:
# logging.info(normalization.meddra_pt_id)
continue
# conceptName = normalization.meddra_pt.lower().strip()
self.loadMaps(conceptName, normalization.meddra_pt_id)
cui = normalization.meddra_pt_id
simpleConceptNames = SimpleNameSieve.getTerminologySimpleNames(re.split(r"\s+", conceptName))
for simpleConceptName in simpleConceptNames:
self.simpleNameToCuiListMap = Util.setMap(self.simpleNameToCuiListMap, simpleConceptName, cui)
@classmethod
def getOMIMCuis(self, cuis):
OMIMcuis = list()
for cui in cuis:
if cui.find(u"OMIM") == -1:
continue
cui = re.split(u":", cui)[1]
OMIMcuis = Util.setList(OMIMcuis, cui)
return OMIMcuis
def setOMIM(self, cuis, MeSHorSNOMEDcuis, conceptName):
if MeSHorSNOMEDcuis == u"": # 如果Mesh ID为空,则用OMIM
cuis = cuis.replace(u"OMIM:", u"")
self.loadMaps(conceptName, cuis)
else : # 否则用OMIM为候选ID
cuis_arr = re.split(r"\|", cuis)
for cui in cuis_arr:
if cui.find(u"OMIM") == -1:
continue
cui = re.split(u":", cui)[1]
self.cuiAlternateCuiMap = Util.setMap(self.cuiAlternateCuiMap, MeSHorSNOMEDcuis, cui)
class Concept:
def __init__(self, indexes, name, goldMeSHorSNOMEDCui, goldOMIMCuis):
self.indexes = indexes
self.name = name.lower().strip()
self.goldMeSHorSNOMEDCui = goldMeSHorSNOMEDCui
self.goldOMIMCuis = goldOMIMCuis
self.nameExpansion = None
self.stemmedName = None
self.cui = None
self.alternateCuis = None
self.normalizingSieveLevel = 0
self.namesKnowledgeBase = list()
self.stemmedNamesKnowledgeBase = list()
def setNameExpansion(self, text, abbreviationObject):
self.nameExpansion = Abbreviation.getAbbreviationExpansion(abbreviationObject, text, self.name, self.indexes)
def setStemmedName(self):
self.stemmedName = Ling.getStemmedPhrase(self.name)
def setCui(self, cui):
self.cui = cui
def getCui(self):
return self.cui
def setAlternateCuis(self, alternateCuis):
self.alternateCuis = list()
for alternateCui in alternateCuis:
self.alternateCuis = Util.setList(self.alternateCuis, alternateCui)
def setNormalizingSieveLevel(self, sieveLevel):
self.normalizingSieveLevel = sieveLevel
def getName(self):
return self.name
def getNormalizingSieve(self):
return self.normalizingSieveLevel
def getGoldMeSHorSNOMEDCui(self):
return self.goldMeSHorSNOMEDCui
def getGoldOMIMCuis(self):
return self.goldOMIMCuis
def getAlternateCuis(self):
return self.alternateCuis
def getNameExpansion(self):
return self.nameExpansion
def setNamesKnowledgeBase(self, name):
if isinstance(name, list):
self.namesKnowledgeBase = Util.addUnique(self.namesKnowledgeBase, name)
else:
self.namesKnowledgeBase = Util.setList(self.namesKnowledgeBase, name)
def getNamesKnowledgeBase(self):
return self.namesKnowledgeBase
def getStemmedNamesKnowledgeBase(self):
return self.stemmedNamesKnowledgeBase
def setStemmedNamesKnowledgeBase(self, namesList):
self.stemmedNamesKnowledgeBase = Util.addUnique(self.stemmedNamesKnowledgeBase, namesList)
class Evaluation:
totalNames = 0
tp = 0
fp = 0
accuracy = 0.0
map_whichSieveFires = dict()
@classmethod
def initialize(self, data):
for i in range(int(data.config['norm_rule_num'])+1):
Evaluation.map_whichSieveFires[i] = 0
@classmethod
def incrementTotal(self):
Evaluation.totalNames += 1
@classmethod
def incrementTP(self):
Evaluation.tp += 1
@classmethod
def incrementFP(self):
Evaluation.fp += 1
@classmethod
def evaluateClassification(self, concept, concepts):
Evaluation.incrementTotal()
if (concept.getGoldMeSHorSNOMEDCui() != u"" and concept.getGoldMeSHorSNOMEDCui() == concept.getCui()) \
or (len(concept.getGoldOMIMCuis()) != 0 and concept.getCui() in concept.getGoldOMIMCuis()):
Evaluation.incrementTP()
elif concept.getGoldMeSHorSNOMEDCui().find(u"|") != -1 and concept.getCui().find(u"|") != -1:
gold = set(re.split(r"\|", concept.getGoldMeSHorSNOMEDCui()))
predicted = set(re.split(r"\|", concept.getCui()))
bFindPredictNotInGold = False
for p in predicted:
if p not in gold:
bFindPredictNotInGold = True
break
if bFindPredictNotInGold:
Evaluation.incrementFP()
else:
Evaluation.incrementTP()
minus_set = gold - predicted
if len(minus_set) == 0:
Evaluation.incrementTP()
else :
Evaluation.incrementFP()
elif concept.getAlternateCuis() is not None and len(concept.getAlternateCuis()) != 0 :
if concept.getGoldMeSHorSNOMEDCui() != u"" and concept.getGoldMeSHorSNOMEDCui() in concept.getAlternateCuis() :
Evaluation.incrementTP()
concept.setCui(concept.getGoldMeSHorSNOMEDCui())
elif len(concept.getGoldOMIMCuis()) != 0 and Util.containsAny(concept.getAlternateCuis(), concept.getGoldOMIMCuis()) :
Evaluation.incrementTP();
if len(concept.getGoldOMIMCuis()) == 1:
concept.setCui(concept.getGoldOMIMCuis()[0])
else :
Evaluation.incrementFP()
else :
Evaluation.incrementFP()
count = Evaluation.map_whichSieveFires.get(concept.normalizingSieveLevel)
count += 1
Evaluation.map_whichSieveFires[concept.normalizingSieveLevel] = count
@classmethod
def computeAccuracy(self):
Evaluation.accuracy = Evaluation.tp * 1.0 / Evaluation.totalNames
@classmethod
def printResults(self):
print("*********************")
print("Total Names: {}".format(Evaluation.totalNames))
print("True Normalizations: {}".format(Evaluation.tp))
print("False Normalizations: {}".format(Evaluation.fp))
print("Accuracy: {}".format(Evaluation.accuracy))
print("*********************")
for sieve_level in Evaluation.map_whichSieveFires:
if sieve_level == 0:
print("{} unmapped names, accounting for {:.2f}%".format(Evaluation.map_whichSieveFires[sieve_level],
Evaluation.map_whichSieveFires[sieve_level]*100.0/Evaluation.totalNames))
else:
print("Sieve {} fires {} times, accounting for {:.2f}%".format(sieve_level, Evaluation.map_whichSieveFires[sieve_level],
Evaluation.map_whichSieveFires[sieve_level]*100.0/Evaluation.totalNames))
print("*********************")
class MultiPassSieveNormalizer:
maxSieveLevel = 0
def __init__(self):
pass
@classmethod
def pass_(self, concept, currentSieveLevel):
if concept.getCui() != u"":
concept.setAlternateCuis(Sieve.getAlternateCuis(concept.getCui()))
concept.setNormalizingSieveLevel(currentSieveLevel-1)
return False
if currentSieveLevel > MultiPassSieveNormalizer.maxSieveLevel:
return False
return True
@classmethod
def applyMultiPassSieve(self, concept):
currentSieveLevel = 1
# Sieve 1
concept.setCui(Sieve.exactMatchSieve(concept.getName()))
currentSieveLevel += 1
if not MultiPassSieveNormalizer.pass_(concept, currentSieveLevel):
return
# Sieve 2
concept.setCui(Sieve.exactMatchSieve(concept.getNameExpansion()))
currentSieveLevel += 1
if not MultiPassSieveNormalizer.pass_(concept, currentSieveLevel):
return
# Sieve 3
concept.setCui(PrepositionalTransformSieve.apply(concept))
currentSieveLevel += 1
if not MultiPassSieveNormalizer.pass_(concept, currentSieveLevel):
return
# Sieve 4
concept.setCui(SymbolReplacementSieve.apply(concept))
currentSieveLevel += 1
if not MultiPassSieveNormalizer.pass_(concept, currentSieveLevel):
return
# Sieve 5
concept.setCui(HyphenationSieve.apply(concept))
currentSieveLevel += 1
if not MultiPassSieveNormalizer.pass_(concept, currentSieveLevel):
return
# Sieve 6
concept.setCui(AffixationSieve.apply(concept))
currentSieveLevel += 1
if not MultiPassSieveNormalizer.pass_(concept, currentSieveLevel):
return
# Sieve 7
concept.setCui(DiseaseModifierSynonymsSieve.apply(concept))
currentSieveLevel += 1
if not MultiPassSieveNormalizer.pass_(concept, currentSieveLevel):
return
# Sieve 8
concept.setCui(StemmingSieve.apply(concept))
currentSieveLevel += 1
if not MultiPassSieveNormalizer.pass_(concept, currentSieveLevel):
return
# Sieve 9
concept.setCui(CompoundPhraseSieve.applyNCBI(concept.getName()))
currentSieveLevel += 1
if not MultiPassSieveNormalizer.pass_(concept, currentSieveLevel):
return
# Sieve 10
concept.setCui(SimpleNameSieve.apply(concept))
currentSieveLevel += 1
if not MultiPassSieveNormalizer.pass_(concept, currentSieveLevel):
return
# Sieve 11
concept.setCui(PartialMatchNCBISieve.apply(concept))
currentSieveLevel += 1