-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathonto_extension_new.py
More file actions
2051 lines (1967 loc) · 82.5 KB
/
Copy pathonto_extension_new.py
File metadata and controls
2051 lines (1967 loc) · 82.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 13 15:43:18 2023
@author: smdicher
"""
import os
import spacy
import re
import pandas as pd
from preprocess_onto import *
from chemdataextractor import Document
import time
from text_mining import add_publication
def preprocess_classes(categories,abbreviation, onto_new_dict, sup_cat, rel_synonym, chem_list, missing_all, match_dict_all,entities_raw):
"""
Parameters
----------
categories : TYPE
DESCRIPTION.
sup_cat : TYPE
DESCRIPTION.
rel_synonym : TYPE
DESCRIPTION.
chem_list : TYPE
DESCRIPTION.
missing_all : TYPE
DESCRIPTION.
match_dict_all : TYPE
DESCRIPTION.
Returns
-------
df_entity : TYPE
DESCRIPTION.
rel_synonym : TYPE
DESCRIPTION.
missing_all : TYPE
DESCRIPTION.
match_dict_all : TYPE
DESCRIPTION.
"""
global nlp
global comment_treat
global comment_charac
global entities_raw1
entities_raw1=entities_raw
not_process=['Characterization','Treatment']
nlp = spacy.load('en_core_web_sm')
classes = {}
spans_dict = {}
support = []
list_all = []
heads = []
chem_e = []
#chem_list.extend([str(i) for i in rel_synonym.values()])
pop=[]
comment_treat=[]
comment_charac=[]
values_comp = [i for v in onto_new_dict.values() for i in v if i]
for k in sup_cat.keys():
sup_cat[k]=[*set(sup_cat[k])]
if k in rel_synonym.keys():
if rel_synonym[k] in sup_cat.keys():
sup_cat[rel_synonym[k]].extend(sup_cat[k])
else:
pop.append({rel_synonym[k]:sup_cat[k]})
pop.append(k)
for i in pop:
if type(i) == dict:
if list(i.keys())[0] in sup_cat.keys():
sup_cat[list(i.keys())[0]].extend(list(i.values())[0])
else:
sup_cat.update(i)
else:
sup_cat.pop(i)
for entity,l in categories.items():
print(entity)
if l in not_process:
if l == 'Treatment':
comment_treat.append(entity)
else:
comment_charac.append(entity)
elif entity in classes.keys():
continue
else:
entity_raw=entity
chem_all=[cem for cem in chem_list if cem in entity]
seen_items = set()
# Create a new list to store the filtered items
chem_entity = []
# Iterate through the items and filter out substrings
for item in chem_all:
# Check if the item is not a substring of any seen item
if not any(item in seen_item for seen_item in seen_items):
chem_entity.append(item)
seen_items.add(item)
if entity not in chem_list and entity in values_comp:
chem_entity.append(entity)
chem_list.append(entity)
# Create a set to keep track of entities to remove
entities_to_remove = set()
# Iterate through the entities and check if they are substrings of others
for i, cem1 in enumerate(chem_entity):
for j, cem2 in enumerate(chem_entity):
if i != j and cem1 in cem2:
entities_to_remove.add(cem1)
# Filter out entities that are substrings of others
chem_entity = [c for c in chem_entity if c not in entities_to_remove]
print(entity+':')
print(chem_entity)
spans_dict[entity] = []
spans_n = []
if l == 'Catalyst':
support = []
if "based" in entity:
e_snip = None
based_m = re.search('based',entity)
if based_m.start() != 0 or entity[:based_m.start()-1].lower() != 'catalyst':
e_snip = entity[:based_m.start()-1]
e_snip_old = entities_raw[entity][0][:based_m.start()-1]
e_cleaned = e_snip
for c in chem_entity:
pattern ='\\b'+c+'\\b'
if re.search(pattern,e_snip):
e_snip = e_snip[e_snip.index(c)+len(c)+1:]
c_t = rel_synonym[c]
if c_t not in spans_n:
spans_n.append(c_t)
if re.search('[Ss]upported', e_snip_old):
e_cleaned = e_snip[re.search('[sS]upported',e_snip).end()+1:]
support.append(c_t)
continue
e_snip=e_snip.replace(c,'')
if 'catalyst' in e_cleaned:
classes,_ = check_in_snip(e_cleaned, classes, entity,l,chem_entity)
if entity[based_m.end()+1:] != 'catalyst':
s_on = False
e_snip = entity[based_m.end()+1:]
e_snip_old = entities_raw[entity][0][based_m.end()+1:]
if ' on ' in e_snip: #based on/ based exclusivelly on
if re.search('supported on', e_snip_old):
s_on = True
sup_i = True
#Rh-Co based system supported on alumina, titania and silica
e_btwn=e_snip[re.search('supported on', e_snip).end():]
else:
based_m = re.search('on',entity)
e_snip = entity[based_m.end()+1:]
if re.search('supported', e_snip_old) and s_on==False:
#based on silica supported bimetallic catalysts
e_btwn = e_snip[:re.search('supported', e_snip).start()-1]
sup_i = True
else:
sup_i = False
for c in chem_entity:
pattern ='\\b[\\d.]*'+c+'\\b'
if re.search(pattern,e_snip):
c_t = rel_synonym[c]
if sup_i == True and c in e_btwn:
support.append(c_t)
if c_t not in spans_n:
spans_n.append(c_t)
if 'catalyst' in e_snip:
classes,_ = check_in_snip(e_snip, classes, entity,l,chem_entity)
elif entity not in chem_list and not set(entity.split()).issubset(chem_list):
sup_i = False
entity_n = entity
if re.search('supported on', entities_raw[entity][0]) or re.search('encapsulated within', entities_raw[entity][0]):
#Rh-Co supported on alumina, titania and silica
if 'supported on' in entities_raw[entity][0]:
e_btwn=entity[re.search('supported on ', entity).end():]
else:
e_btwn=entity[re.search('encapsulated within ', entity).end():]
sup_i=True
elif re.search('supported', entities_raw[entity][0]): #bimetallic SiO2-supported RhCo3 cluster catalyst
if '-' in entity and entity.index('-')==re.search('supported',entity).start()-1:
entity_n= entity[:entity.index('-')]+ ' '+entity[entity.index('-')+1:]
e_btwn=entity[:re.search('supported', entity).start()-1]
sup_i = True
for c in chem_entity:
if ('(' and')') in c: #Rh(111)
d=c
d=d.replace('(','\\(')
d=d.replace(')', '\\)')
pattern=d
else:
pattern='\\b[\\d.]*'+c+'\\b'
if re.search(pattern,entity_n):
c_t = rel_synonym[c] if c in rel_synonym.keys() else c
if sup_i==True and c in e_btwn:
eq_idx=e_btwn.find('=') #RhM3/MCM-41, M = Fe, Co, Ni, Cu, or Zn
if eq_idx != -1:
if re.search(pattern,entity_n).start() < eq_idx:
support.append(c_t)
else:
support.append(c_t)
if c_t not in spans_n:
spans_n.append(c_t)
classes,_ = check_in_snip(entity, classes,entity,l,chem_entity)
if support:
snaps_n = [c for c in spans_n if c not in support]
for i in support:
if i in sup_cat.keys():
sup_cat[i].extend([c for c in snaps_n if c not in sup_cat[i]])
else:
sup_cat[i] = snaps_n
elif l == 'Reaction':
classes,head = check_in_snip(entity, classes,entity,l,chem_entity)
if head and head not in heads and head != 'reaction':
heads.append(head)
for c in chem_entity: #hydride hydroformulation
pattern = '\\b'+c+'\\b'
if re.search(pattern,entity):
c_t = rel_synonym[c]
if c_t not in spans_n:
spans_n.append(c_t)
spans_dict[entity].extend(spans_n)
if entity!=entity_raw:
if entity in entities_raw1.keys():
entities_raw1[entity].extend(entities_raw1[entity_raw])
entities_raw1[entity]=[*set(entities_raw1[entity])]
else:
entities_raw1[entity]=entities_raw1[entity_raw]
if entity in chem_list or set(entity.split()).issubset(chem_list):
if entity in rel_synonym.keys():
c_list = [rel_synonym[entity]]
elif entity in rel_synonym.values():
c_list = [entity]
else:
c_list = []
for c in entity.split():
c_t = rel_synonym[c] if c in rel_synonym.keys() else c
if "atom" in c_t:
c_list=[entity]
break
c_list.append(c_t)
list_all.append([' '.join(c_list),[],[' '.join(c_list)],categories[entity]]) #changed entity! prop-1-ene instead propylene
if len(entity.split()) > 1 and set(entity.split()).issubset(chem_list):
chem_e.append(' '.join(c_list))
print('changed entity:'+' '.join(c_list))
elif entity.split()[-1] in chem_list and entity not in classes.keys():
#i.e. light olefin
print('entity.split()[-1] in chem_list: {}'.format(entity))
classes,_ = check_in_snip(entity, classes, entity, l,chem_list)
c_t = rel_synonym[entity.split()[-1]] if entity.split()[-1] in rel_synonym.keys() else entity.split()[-1]
spans_dict[entity].append(c_t) #
elif entity not in classes.keys() and l in ['Product','Reactant']:
for c in chem_entity:
c_t = rel_synonym[c] if c in rel_synonym.keys() else c
spans_dict[entity].append(c_t) #muss für entities wie "phenolic species", alkyl group erweitert werden
list_all.append([entity,['chemical substance'],[],l])
for k,v in spans_dict.items(): #replacement of parts of chemical entities with full name. i.e. ['zeolite', 'ZSM-5']-> ['ZSM-5 zeolite'] if 'ZSM-5 zeolite' is in entity
for c in chem_e:
for i in range(len(c.split())):
if c.split()[i] in sup_cat.keys(): #'ZSM-5' instead of 'ZSM-5 zeolite' (change to second)
if c.split()[i] not in rel_synonym.keys(): #check!
rel_synonym[c.split()[i]] = c
sup_cat[c] = sup_cat[c.split()[i]]
print('{} was replaced with {} in support-catalyst dictionary'.format(c.split()[i],c))
sup_cat.pop(c.split()[i],None)
if c in k:
spans_dict[k]=list(filter(lambda x: x not in c.split(), v))
not_del = []
classes_n = {}
for k_1,v_1 in classes.items():
v_1.sort(key = lambda x: len(x.split()), reverse=False)
classes_n[k_1] = []
for k,v in classes.items():
i = len(v_1)-1
ele_old = None
while i >= 0:
if k != k_1 and v_1[i] not in classes_n[k_1]:
if v_1[i] in v:
classes_n,ele_old = shortcut_add_class(ele_old, classes_n, not_del, value=v_1, i=i, key=k_1 )
elif ele_old:
not_del.append(ele_old)
i -= 1
else:
break
i = len(v_1)-1
ele_old=None
while i >= 0:
if v_1[i] not in classes_n[k_1]:
classes_n,ele_old = shortcut_add_class(ele_old, classes_n, not_del, value=v_1, i=i, key=k_1 )
elif ele_old:
not_del.append(ele_old)
i -= 1
v_all = []
if heads:
v_all.extend(heads)
print('classes_n:{}'.format(classes_n))
for k,v in classes_n.items():
list_all.append([k,v,spans_dict[k],categories[k]])
v_all.extend(v)
v_all.append(k)
v_all=[*set(v_all)]
df_entity = pd.DataFrame(list_all, columns=['entity','classes', 'cems', 'category'])
df_entity=df_entity.drop_duplicates(['entity']).reset_index()
missing,match_dict = create_list_IRIs(v_all, IRI_json_filename = 'iriDictionary')
missing_all.extend(missing)
match_dict_all.update(match_dict)
comment_treat=[*set(comment_treat)]
comment_charac=[*set(comment_charac)]
print('comment_treat:{}'.format(comment_treat))
print('comment_charac:{}'.format(comment_charac))
return df_entity, rel_synonym, missing_all, match_dict_all
"""
def catalyst_support(entity, chem_list):
spans = sorted(Document(entity).cems, key = lambda span: span.start)
chem_entity=[c.text for c in spans]
list_spans=[i for c in spans for i in c.text.split()]+[c.text for c in spans]
chem_entity.extend([cem for cem in chem_list if cem in entity and cem not in chem_entity and cem not in list_spans])
mol = re.findall(r'(([\w—–-]+)(?:[\s]?/[\s]?|[\s]?@[\s]?|[\s]on[\s])+([\w—–-]+))', entity) # 'RhCo on Al2O3' or 'RhCo/Al2O3' or 'RhCo@Al2O3'r'((?:([\w@—–-]+)[\s])?([\w@—–-]+)(?:[\s]?/[\s]?|[\s]on[\s])+([\w@—–-]+))', entity
if mol:
for i in range(len(mol)):
if ('supported' or 'Supported') in mol[i][0]:
continue
cem=[]
if '/' in mol[i][0]:
entity = entity.replace('/',' supported on ')
support = mol[i][2]
catalyst = mol[i][1]
sup = True
elif '@' in mol[i][0]:
#if entity not in abbreviation.keys():
entity = entity.replace('@',' supported on ')
support = mol[i][2]
catalyst = mol[i][1]
sup = True
elif 'on' in mol[i][0]:
sup = False
if 'based' not in entity[:re.search(r'[\s]on[\s]',entity).start()]:
for c in chem_entity:
if mol[i][1] in chem_list_all:
sup = True
cem.append(mol[i][1])
if c in entity[:re.search(r'[\s]on[\s]',entity).start()]:
cem.append(c)
for c in chem_entity:
if c in entity[re.search(r'[\s]on[\s]',entity).end():]:
support = c
sup =True
break
else:
sup=False
if sup==True:
entity = entity.replace('on','supported on')
if sup==True:
if support in sup_cat.keys():
if cem:
sup_cat[support].extend([c for c in cem if c not in sup_cat[support]])
elif catalyst not in sup_cat[support]:
sup_cat[support].append(catalyst)
else:
if cem:
cem=[*set(cem)]
sup_cat[support] = cem
else:
sup_cat[support] = [catalyst]
for k, v in sup_cat.items():
new_values=[]
for i in v :
new_values.append(rel_synonym[i])
sup_cat[k]=new_values
"""
def shortcut_add_class(ele_old,classes_n, not_del, value, i, key ):
classes_n[key].append(value[i])
if ele_old != None and ele_old not in not_del:
classes_n[key].remove(ele_old)
if i!=0:
if len(value[i].split()) > len(value[i-1].split()):
ele_old = value[i-1]
print('ele_old:{}'.format(ele_old))
else:
ele_old = None
return classes_n, ele_old
def check_in_snip(e_snip, classes, entity, l, chem_list):
global entities_raw1
classes[entity] = []
doc_snip = nlp(e_snip)
head = None
if chem_list:
chem_list.extend([c for c in [cem.split() for cem in chem_list]][0])
c_i=[]
for c in chem_list:
if '-' in c:
c_i=c.split('-')
c_i.append('-')
chem_list.extend(c_i)
chem_list=[*set(chem_list)]
if l == 'Catalyst':
classes[entity] = ['catalyst role']
if e_snip == entity:
if 'catalyst' in entity:
#token_new = 'catalyst role'
try:
if [t.text for t in [token for token in doc_snip if token.text=='catalyst'][0].children if t.text != "catalyst" and t.text not in chem_list]:
for t in [token for token in doc_snip if token.text=='catalyst'][0].children:
if t.text != "catalyst" and t.text!='containing' and t.text not in chem_list:
print(t.text)
if not re.search(r'[Ss]upported',t.text):
token_new=t.text.lower()+' catalyst role'
classes[entity].append(token_new)
if t.children:
children=list(t.children)
for i in reversed(range(len([k.text for k in children if k.text != "catalyst" and k.text not in chem_list and 'supported' not in k.text]))):
token_new=[t.text.lower() for t in children if t.text != "catalyst" and t.text not in chem_list and 'supported' not in t.text][i] +' ' + token_new
classes[entity].append(token_new)
except:
print('\nDependency parsing could not be performed.\nAssigned class for "{}" is "catalyst role"\n'.format(entity))
"""
for i in reversed(range(len([t.text for t in [token for token in doc_snip if token.text!='catalyst'][0].children if t.text != "catalyst" and t.text not in chem_list]))):
token_new = [t.text.lower() for t in [token for token in doc_snip if token.text == 'catalyst'][0].children][i]+' ' + token_new
classes[entity].append(token_new) # Problem: from 'bimetallic SiO2-supported RhCo3 cluster catalyst' only 'cluster catalyst role'
"""
else:
print('no catalyst in entity:{}'.format(entity))
else:
for token in doc_snip:
if token.head.text == 'catalyst' or token.pos_=='VERB':
token_new=' catalyst role'
if token.text != 'catalyst':
if not re.search(r'[Ss]upported',token.text) and token.text not in chem_list:
token_new=token.text.lower()+token_new
classes[entity].append(token_new)
if token.children:
for i in reversed(range(len([t.text for t in token.children if t.text != "catalyst" and t.text not in chem_list and 'supported' not in t.text]))):
token_new=[t.text.lower() for t in token.children if t.text != "catalyst" and t.text not in chem_list and 'supported' not in t.text][i] +' ' + token_new
classes[entity].append(token_new)
elif l=='Reaction':
if len(doc_snip) > 1:
if '-' in doc_snip.text:
doc_snip = nlp(e_snip.replace('-',' '))
for token in reversed(list(doc_snip)):
if token.text =='reaction':
token_new = token.text
head = token_new
elif token.head.text == token.text:
token_new = token.head.text
head=token_new
else:
continue
list_token=[]
classes[entity].extend(check_in_children(token, token_new,list_token))
elif doc_snip[0].pos_ == 'VERB' and re.search('ed$',doc_snip[0].text):
head = re.sub('e$','ion', doc_snip[0].lemma_)
classes[entity].append(head)
entities_raw1[head]=[entity]
else:
classes[entity].append(e_snip)
classes[entity] = [*set(classes[entity])]
if len(classes[entity])>1 and l == 'Catalyst':
classes[entity].remove('catalyst role')
return classes, head
def check_in_children(token, token_new,list_token):
if token.children:
for t in reversed(list(token.children)):
token = t
token_new = t.text.lower() +' ' + token_new
list_token = check_in_children(token, token_new,list_token)
list_token.append(token_new)
return list_token
def create_classes_onto(abbreviation, sup_cat, missing, match_dict, df_entity,reac_dict,p_id,rel_synonym,chem_list,onto_new_dict):
global num
global classes_all
print(entities_raw1)
nlp = spacy.load('en_core_web_sm')
num = 0
sup_sub_df = pd.DataFrame(columns=['super_class','subclass'])
new_world = owlready2.World()
super_classes=['molecule','support material','chemical substance' ]
onto = new_world.get_ontology('./ontologies/{}.owl'.format(onto_new)).load()
created_classes =[]
classes_all=[i.label[0].lower() for i in onto.classes() if i.label]
chem_sub = {}
#chem_list.extend([str(i) for i in rel_synonym.values()]) check!
onto_names={}
idx_abb=[]
for v in match_dict.values():
onto_names[v[0]]=v[1]
for row in df_entity.itertuples():
if row.entity in abbreviation.values():
idx_abb.append(row.Index)
continue
classes_parent = []
classes = sorted(list(row.classes),reverse = False, key = len)
if row.cems:
for c in row.cems:
if c in onto_names.keys():
try:
if c.lower() not in [i.label[0].lower() for i in onto.individuals() if i.label]:
cem = onto.search_one(label = onto_names[c])
print('cem:{}, c:{}, onto:{}'.format(str(cem.name),c, str(onto.name)))
onto,_ = add_individum(onto,cem, c,p_id = p_id)
except:
if cem != None:
print('EXCEPTION: cem:{}, c:{}'.format(str(cem.name), c))
elif onto != None:
print('EXCEPTION: c:{}, onto:{}'.format(c, str(onto.name)))
print('No cem found for label {}'.format(onto_names[c]))
continue
else:
if len(c.split()) > 1:
for i in range(len(c.split())):
if c.split()[i] in onto_names.keys():
sup_sub_df = sup_sub_df.append({'super_class':onto_names[c.split()[i]], 'subclass': c},ignore_index = True)
if c in sup_cat.keys():
sup_sub_df = sup_sub_df.append({'super_class':'support material', 'subclass': c},ignore_index = True)
elif c not in list(sup_sub_df['subclass']):
sup_sub_df = sup_sub_df.append({'super_class':'molecule', 'subclass': c},ignore_index = True)
elif c in sup_cat.keys():
sup_sub_df = sup_sub_df.append({'super_class':'support material', 'subclass': c},ignore_index = True)
elif c not in abbreviation.keys():
sup_sub_df = sup_sub_df.append({'super_class':'molecule', 'subclass': c},ignore_index = True)
if row.cems[0] != row.entity:
if nlp(row.entity)[-1].text in chem_list and 'supported' not in row.entity:
sup_sub_df = sup_sub_df.append({'super_class':row.cems[0], 'subclass': row.entity},ignore_index=True)
"""
if row.entity in abbreviation.values():
sup_sub_df = sup_sub_df.append({'super_class':[k for k,v in abbreviation.items() if v==row.entity][0], 'subclass': row.entity},ignore_index=True)
"""
if row.category == 'Catalyst' and row.entity not in sup_sub_df['subclass'] : # and "based" not in row.entity
sup_sub_df = sup_sub_df.append({'super_class':'chemical substance', 'subclass': row.entity},ignore_index=True)
if row.classes==['chemical substance']:
sup_sub_df = sup_sub_df.append({'super_class':'chemical substance', 'subclass': row.entity},ignore_index=True)
if row.category =='Catalyst':
k = 0
while k < len(row.classes):
classes_parent.append(classes[k])
if k != 0:
if len(classes[k-1].split()) < len(classes[k].split()):
sup_sub_df = sup_sub_df.append({'super_class':classes[k-1],'subclass':classes[k]},ignore_index=True)
classes_parent.remove(classes[k-1])
else:
sup_sub_df = sup_sub_df.append({'super_class':'catalyst role','subclass':classes[k]},ignore_index=True)
elif classes[k] != 'catalyst role':
sup_sub_df = sup_sub_df.append({'super_class':'catalyst role','subclass':classes[k]},ignore_index=True)
k += 1
if row.entity not in list(sup_sub_df['subclass']) and not row.cems:
sup_sub_df = sup_sub_df.append({'super_class':'chemical substance', 'subclass': row.entity},ignore_index=True)
"""
if row.entity not in abbreviation.values():
sup_sub_df = sup_sub_df.append({'super_class':'chemical substance', 'subclass': row.entity},ignore_index=True)
else:
idx_abb.append(row.Index) #in case catalyst is a chemical substance and have an abbreviation it will not be created as entity but will be added in the annotations of its abbreviation
"""
"""
for i in classes_parent:
sup_sub_df = sup_sub_df.append({'super_class':i, 'subclass':row.entity},ignore_index = True)
"""
if classes_parent:
chem_sub[row.entity] = classes_parent
elif row.category == 'Reaction':
k=0
while k<len(row.classes):
classes_parent.append(row.classes[k])
if k != 0:
if len(classes[k-1].split()) < len(classes[k].split()):
sup_sub_df = sup_sub_df.append({'super_class':classes[k-1],'subclass':classes[k]},ignore_index=True)
classes_parent.remove(classes[k-1])
k += 1
for k in classes_parent:
i = len(k.split())-1
if k in onto_names.keys() and k not in [c.label[0] for c in onto.individuals() if c.label]:
onto, _ = add_individum(onto, onto.search_one(label=onto_names[k]), k, p_id=p_id)
if onto.search_one(label=onto_names[k]) != None:
onto, _ = add_individum(onto,onto.search_one(label = onto_names[k]), k,p_id = p_id)
else:
print('label {} not found'.format(str(onto_names[k])))
elif k in onto_names.values() and k not in [c.label[0] for c in onto.individuals() if c.label]:
onto, _ = add_individum(onto,onto.search_one(label = k), k,p_id = p_id)
elif k.split()[i] in onto_names.keys():
sup_sub_df = sup_sub_df.append({'super_class': onto_names[k.split()[i]], 'subclass':k},ignore_index=True)
else:
sup_sub_df = sup_sub_df.append({'super_class': 'chemical reaction (molecular)', 'subclass':k},ignore_index = True)
df_entity_all=df_entity
df_entity= df_entity.drop(index=idx_abb)
with onto:
support_mat = onto.search_one(label='support material')
if not support_mat:
support_mat = types.new_class('DC_{:02d}{:02d}'.format(p_id,num), (onto.search_one(label = 'material'),))
support_mat.label.append('support material')
num += 1
created_classes.append('support material')
try:
support_role_i = [i for i in list(onto.search(label='support role')) if i in list(onto.individuals())][0]
except:
onto, support_role_i = add_individum(onto,onto.search_one(label='support role'),'support role',p_id)
if 'Product' in list(df_entity.category):
try:
prod_role_i = [i for i in list(onto.search(label='product role')) if i in list(onto.individuals())][0]
except:
onto, prod_role_i = add_individum(onto,onto.search_one(label='product role'), 'product role',p_id=p_id)
if 'Reactant' in list(df_entity.category):
try:
reac_role_i = [i for i in list(onto.search(label='reactant role')) if i in list(onto.individuals())][0]
except:
onto, reac_role_i = add_individum(onto,onto.search_one(label='reactant role'), 'reactant role',p_id)
if 'Catalyst' in list(df_entity.category):
try:
cat_role_i = [i for i in list(onto.search(label='catalyst role')) if i in list(onto.individuals())][0]
except:
onto, cat_role_i = add_individum(onto,onto.search_one(label='catalyst role'), 'catalyst role',p_id)
indecies = []
entities = [i for i in df_entity['entity'] if i]
for s in sup_sub_df.itertuples():
if s.index in indecies:
continue
elif s.super_class in super_classes or s.super_class in chem_list :
indecies, onto,_,created_classes = create_sub_super(missing, onto,s.Index, indecies,entities, sup_sub_df,created_classes,chem_list,abbreviation,p_id,s.subclass)
else:
indecies, onto,_,created_classes = create_sub_super(missing, onto,s.Index, indecies,entities, sup_sub_df,created_classes,chem_list,abbreviation,p_id = p_id)
for row in df_entity.itertuples():
if row.cems:
e_ind=[]
if row.category == 'Catalyst' and row.entity in chem_sub.keys():
e_ind = [i for i in list(onto.search(label=row.entity)) if i in list(onto.individuals())][0]
for c in chem_sub[row.entity]: #assign catalyst roles
print(row.entity+':'+c)
try:
cat_cl = [i for i in list(onto.search(label=c)) if i in list(onto.individuals())][0]
except:
onto,cat_cl =add_individum(onto,list(onto.search(label = c))[0], c ,p_id)
e_ind.RO_0000087.append(cat_cl) #'has role' = RO_0000087
for c in row.cems:
if c != row.entity and not row.classes:
if [i for i in list(onto.search(label=c)) if i in list(onto.classes())]:
onto, ind = add_individum(onto,[i for i in list(onto.search(label=c)) if i in list(onto.classes())][0], row.entity,p_id)
else:
onto, ind = add_individum(onto,[i for i in list(onto.search(label=c+' (molecule)')) if i in list(onto.classes())][0], row.entity,p_id)
else:
try:
ind = [i for i in list(onto.search(label = c)) if i in list(onto.individuals())][0]
except:
try:
print('c in row.cems individuum added:{}'.format(c))
onto, ind = add_individum(onto,list(onto.search(label = c))[0], c,p_id)
except:
mol=[i for i in list(onto.search(label='chemical substance')) if i in onto.classes()][0]
onto, ind = add_individum(onto,mol, c,p_id)
if c in sup_cat.keys():
ind.RO_0000087.append(support_role_i) #'has role' = RO_0000087
ind.support_component_of.append(e_ind)
for k in row.cems:
if k in sup_cat[c]:
try:
cat=[i for i in list(onto.search(label=k)) if i in list(onto.individuals())][0]
except:
onto, cat=add_individum(onto,list(onto.search(label=k))[0], c,p_id)
cat.supported_on.append(ind)
cat.catalytic_component_of.append(e_ind)
if row.category== 'Product':
ind.RO_0000087.append(prod_role_i)
elif row.category =='Reactant':
ind.RO_0000087.append(reac_role_i)
elif row.category=='Catalyst':
if c==row.entity:
ind.RO_0000087.append(cat_role_i) #'has role' = RO_0000087
elif e_ind and e_ind not in ind.support_component_of:
ind.catalytic_component_of.append(e_ind)
if row.category== 'Reaction':
if row.entity in reac_dict.keys():
try:
ind= [i for i in list(onto.search(label=row.entity)) if i in list(onto.individuals())][0]
except:
try:
ind= [i for i in list(onto.search(label=row.entity.lower())) if i in list(onto.individuals())][0]
except:
onto,ind=add_individum(onto,[i for i in list(onto.search(label=row.classes[0])) if i in list(onto.classes())][0], row.entity,p_id)
for r in reac_dict[row.entity]:
c_t=rel_synonym[r] if r in rel_synonym.keys() else r
try:
cem_i=[i for i in list(onto.search(label=r)) if i in list(onto.individuals())][0]
except:
try:
cem_i=[i for i in list(onto.search(label=c_t)) if i in list(onto.individuals())][0]
except:
try:
cem_i=[i for i in list(onto.search(label=c_t+' (molecule)')) if i in list(onto.individuals())][0]
except:
print(r+" was skipped in reac_dict")
continue
ind.RO_0000057.append(cem_i) #'has participant' = RO_0000057
try:
if row.entity in abbreviation.keys() or entities_raw1[row.entity][0] in abbreviation.keys():
try: # check for abbreviations
e_ind.comment.append(abbreviation[row.entity])
except:
e_ind = [i for i in list(onto.search(label=row.entity)) if i in list(onto.individuals())][0]
e_ind.comment.append(abbreviation[row.entity])
except:
continue
for sup,v in sup_cat.items():
if sup in rel_synonym.keys():
sup = rel_synonym[sup]
try:
sup = [i for i in list(onto.search(label=sup)) if i in list(onto.individuals())][0]
except:
try:
onto, sup=add_individum(onto,list(onto.search(label=sup))[0], sup,p_id)
except:
sup_mat=[i for i in list(onto.search(label='support material')) if i in onto.classes()][0]
new_cl = types.new_class(sup, (sup_mat,))
onto, sup = add_individum(onto,new_cl, sup,p_id)
sup.RO_0000087.append(support_role_i)
for cat in v:
cat = rel_synonym[cat] if cat in rel_synonym.keys() else cat
try:
cat = [i for i in list(onto.search(label=cat)) if i in list(onto.individuals())][0]
except:
try:
onto, cat = add_individum(onto,list(onto.search(label=cat))[0], cat,p_id)
except:
mol=[i for i in list(onto.search(label='molecule')) if i in onto.classes()][0]
new_cl = types.new_class(cat, (mol,))
onto, cat = add_individum(onto,new_cl, cat,p_id)
cat.RO_0000087.append(cat_role_i) #has role catalyst role
cat.supported_on.append(sup)
entities_pub = []
entities_pub.extend([c for c in df_entity.entity])
entities_pub.extend([i for c in df_entity_all.cems if c for i in c if i not in entities_pub])
entities_pub = [*set(entities_pub)]
pub_new = onto.search_one(iri='*publication{}'.format(p_id))
if comment_treat:
pub_new.comment.append('treatment: '+', '.join(comment_treat))
if comment_charac:
pub_new.comment.append('characterization: '+', '.join(comment_charac))
for entity in entities_pub:
print('entity:{}'.format(entity))
try:
ind = [i for i in list(onto.search(label = entity)) if i in list(onto.individuals())][0]
except:
continue
ind.mentioned_in.append(pub_new)
if entity in entities_raw1.keys() and entity != entities_raw1[entity][0]:
for i in entities_raw1[entity]:
ind.comment.append(i)
for short,entity in rel_synonym.items():
inds = [i for i in list(onto.search(label=entity))]
for i in inds:
if i.label[0]!=short: #check!
i.comment.append(short)
onto = create_comp_relation(onto,list(onto_names.keys()), rel_synonym,p_id,onto_new_dict)
onto.save('./ontologies/{}.owl'.format(onto_new))
return created_classes, sup_sub_df
def create_comp_relation(onto,values, rel_synonym,p_id,onto_new_dict):
global num
#global onto_new_dict
short = []
pub_new = onto.search_one(iri='*publication{}'.format(p_id))
with onto:
for k,v in onto_new_dict.items():
if k in values or len(v) == 1:
continue
else:
try:
mol = [m for m in onto.search(label = k) if m in onto.individuals()][0]
except:
try:
onto,mol = add_individum(onto,onto.search_one(label = k),k,p_id)
except:
continue
print('mol:{}'.format(mol))
for c in v:
comp = onto.search(label=c)
if not comp:
continue
elif len(comp) == 1:
onto,c_i = add_individum(onto,comp[0],c,p_id)
else:
c_i = [i for i in comp if i in onto.individuals()][0]
short = [i for i in rel_synonym.keys() if rel_synonym[i] == c]#check
if short:
for i in short:
if i not in list(c_i.comment) and i != c_i:
c_i.comment.append(i)
mol.BFO_0000051.append(c_i) #"has part" relation between classes or individuals? chosen individuals because of reasoning time
c_i.mentioned_in.append(pub_new)
return onto
def create_subclass(onto,subclass,entities,super_class,created_classes,chem_list,abbreviation,p_id ):
global num
new_sub = None
created_ind = [i.label[0].lower() for i in onto.individuals() if i.label]
if [c for c in chem_list if re.search(r'\b[\d.,%]*{}\b'.format(re.escape(c)),subclass) if c != subclass]:
print('subclass:{}'.format(subclass))
if subclass.lower() not in created_ind:
onto, new_i = add_individum(onto,super_class,subclass,p_id)
else:
new_i = onto.search_one(label = subclass)
new_i.is_a.append(super_class)
elif subclass in abbreviation.values():
if subclass.lower() not in created_ind:
onto, new_i = add_individum(onto,super_class,subclass,p_id)
elif subclass.lower() == super_class.label[0].lower() or ("role" in super_class.label[0] and "role" not in subclass): #to implement for reaction
onto, new_i = add_individum(onto,super_class, subclass,p_id)
elif subclass.lower() not in created_classes and subclass.lower() not in classes_all:
class_name = 'DC_{:02d}{:02d}'.format(p_id, num)
num += 1
new_sub = types.new_class(class_name,(super_class,))
new_sub.label.append(subclass)
created_classes.append(subclass.lower())
if subclass in entities:
if subclass.lower() not in created_ind:
onto, new_i = add_individum(onto,new_sub, subclass,p_id)
elif subclass.lower() in created_ind:
new_i = onto.search_one(label=subclass)
new_i.is_a.append(super_class)
elif subclass.lower() not in classes_all and subclass in entities:
super_class=[i for i in onto.search(label=subclass.lower()) if i in onto.classes()][0]
if subclass.lower() not in created_ind:
onto, new_i = add_individum(onto,super_class, subclass,p_id)
elif subclass in created_ind:
new_i = [i for i in onto.search(label=subclass) if i in onto.individuals()][0]
new_i.is_a.append(super_class)
if new_sub:
new_sub.comment.append('created automatically')
return onto, created_classes
def add_individum(onto,super_class, ind,p_id):
global num
with onto:
new_i = [i for i in onto.search(label=ind) if i in onto.individuals()]
if new_i:
new_i = new_i[0]
else:
print(type(super_class), super_class)
new_i = super_class('DC_{:02d}{:02d}'.format(p_id,num))
num += 1
new_i.label.append(ind)
new_i.comment.append('created automatically')
return onto, new_i
def create_sub_super(missing, onto, idx, indecies, entities, sup_sub_df, created_classes, chem_list, abbreviation,p_id, subclass = None ):
global num
super_class_l = sup_sub_df.loc[idx, 'super_class']
with onto:
if super_class_l not in missing or super_class_l in created_classes or super_class_l in classes_all:
try:
super_class = [c for c in onto.search(label=super_class_l) if c in onto.classes()][0]
except:
try:
super_class = [c for c in onto.search(prefLabel=super_class_l) if c in onto.classes()][0]
except:
try:
super_class = [c for c in onto.search(label=super_class_l.lower()) if c in onto.classes()][0]
except:
super_class = onto.search_one(label=super_class_l+ ' (molecule)')
if not subclass:
onto, created_classes = create_subclass(onto, sup_sub_df.loc[idx, 'subclass'], entities, super_class,created_classes,chem_list,abbreviation,p_id=p_id)
elif super_class_l in list(sup_sub_df['subclass']):
query = sup_sub_df.query('subclass == "{}"'.format(super_class_l))
idx = query.index[0]
subclass=super_class_l
indecies.extend(list(query.index))
indecies, onto, super_class,created_classes = create_sub_super(missing, onto, idx, indecies,entities,sup_sub_df,created_classes,chem_list,abbreviation,p_id,subclass=subclass)
query = sup_sub_df.query('super_class == "{}"'.format(super_class_l))
if query.empty == False:
indecies.extend(list(query.index))
for q in range(len(query)):
subclass = query['subclass'].iloc[q]
onto, created_classes=create_subclass(onto,subclass,entities,super_class,created_classes,chem_list,abbreviation,p_id=p_id)
subclass = None
else:
class_name = 'DC_{:02d}{:02d}'.format(p_id, num)
num += 1
super_class = types.new_class(class_name, (Thing,))
super_class.comment.append('created automatically')
super_class.label.append(super_class_l)
created_classes.append(super_class_l.lower())
if subclass:
if subclass.lower() not in created_classes and subclass.lower() not in classes_all:
if super_class_l== 'chemical substance' or super_class_l in chem_list: #or super_class_l in abbreviation.keys()
if super_class != None:
onto, _ = add_individum(onto,super_class, subclass,p_id)
new_sub = super_class
else:
print("undefined superclass for indv {}".format(str(subclass.lower())))
new_sub = subclass
else:
class_name = 'DC_{:02d}{:02d}'.format(p_id, num)
num += 1
new_sub = types.new_class(class_name,(super_class,))
#new_sub = types.new_class(class_name, super_class)
new_sub.comment.append('created automatically')
new_sub.label.append(subclass)
created_classes.append(subclass.lower())
else:
new_sub = onto.search_one(label= subclass)
super_class = new_sub
if super_class_l.lower() not in created_classes:
created_classes.append(super_class_l.lower())
return indecies, onto,super_class, created_classes
"""
sup_cat={'SiO2': ['Rh2P', 'RhCo3', 'Rh'],
'MCM-41': ['RhCo3'],
'Al2O3': ['Rh', 'Rh', 'Rh', 'Co', 'Co'], #problem mit duplikaten gelöst!
'Al': ['Rh']}
rel_synonym= {'OH': 'hydroxide',
'O': 'oxygen atom',
'H': 'hydrogen atom',
'Cobalt': 'cobalt atom',
'Rhodium': 'rhodium atom',
'hydrotalcite': 'dialuminum;hexamagnesium;oxygen(2-);carbonate;dodecahydrate',
'Rh': 'rhodium atom',
'hexane': 'hexane',
'cobalt': 'cobalt atom',
'Rh3+': 'rhodium',
'C10': '(z)-13-methyltetradec-2-enoic acid',
'C': 'carbon atom',
'1-octene': '1-octene',
'olefin': 'olefin',
'Pd': 'palladium',
'rhodium': 'rhodium atom',
'aldehyde': 'aldehyde',
'Fe': 'iron atom',
'C7H14': '1-heptene',
'alkene': 'alkene',
'1-Hexene': '1-hexene',
'1-decene': '1-decene',
'Ru': 'ruthenium atom',
'1-Octene': '1-octene',
'CoRh': 'cobalt;rhodium',
'Co': 'cobalt atom',
'1-Heptene': '1-heptene',
'Rh3': 'rhodium',
'C8H16': '1-octene',
'H2': 'dihydrogen',
'Pt': 'platinum',
'1-Decene': '1-decene'}
missing=['dialuminum;hexamagnesium;oxygen(2-);carbonate;dodecahydrate',
'Cobalt Rhodium HT',
'CoRhHT-2',