-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgurobiILPOntSolver.py
1522 lines (1111 loc) · 79.9 KB
/
gurobiILPOntSolver.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
from six import string_types
from itertools import product, permutations, groupby
import logging
import datetime
# numpy
import numpy as np
# ontology
from owlready2 import *
# Gurobi
from gurobipy import *
from regr.graph.concept import Concept
from regr.solver.ilpOntSolver import ilpOntSolver
from regr.solver.gurobiILPBooleanMethods import gurobiILPBooleanProcessor
from regr.graph import LogicalConstrain, andL, orL, ifL, existsL, notL
class gurobiILPOntSolver(ilpOntSolver):
ilpSolver = 'Gurobi'
def __init__(self, graph, ontologiesTuple, _ilpConfig) -> None:
super().__init__(graph, ontologiesTuple, _ilpConfig)
self.myIlpBooleanProcessor = gurobiILPBooleanProcessor()
def valueToBeSkipped(self, x):
return (
x != x or # nan
abs(x) == float('inf') # inf
)
def addTokenConstrains(self, m, conceptNames, tokens, x, graphResultsForPhraseToken):
if graphResultsForPhraseToken is None:
return None
self.myLogger.info('Starting method addTokenConstrains')
self.myLogger.debug('graphResultsForPhraseToken')
padding = max([len(str(t)) for t in tokens])
spacing = max([len(str(c)) for c in conceptNames]) + 1
self.myLogger.debug("{:^{}}".format("", spacing) + ' '.join(map('{:^10}'.format, ['\''+ str(t) + '\'' for t in tokens])))
for concept, tokenTable in graphResultsForPhraseToken.items():
self.myLogger.debug("{:<{}}".format(concept, spacing) + ' '.join(map('{:^10f}'.format, [t[1] for t in tokenTable])))
# Create variables for token - concept and negative variables
for conceptName in conceptNames:
for tokenIndex, token in enumerate(tokens):
currentProbability = graphResultsForPhraseToken[conceptName][tokenIndex]
# Check if probability is NaN or if and has to be skipped
if self.valueToBeSkipped(currentProbability[1]):
self.myLogger.info("Probability is %f for concept %s and token %s - skipping it"%(currentProbability[1],token,conceptName))
continue
# Create variable
x[conceptName, token]=m.addVar(vtype=GRB.BINARY,name="x_%s_is_%s"%(token, conceptName))
#self.myLogger.debug("Created ILP variable for concept %s and token %s it's probability is %f"%(conceptName,token,currentProbability[1]))
# Check if probability is NaN or if and has to be created based on positive value
if self.valueToBeSkipped(currentProbability[0]):
currentProbability[0] = 1 - currentProbability[1]
self.myLogger.info("No ILP negative variable for concept %s and token %s - created based on positive value %f"%(token, conceptName, currentProbability[0]))
# Create negative variable
if True: # ilpOntSolver.__negVarTrashhold:
x['Not_'+conceptName, token]=m.addVar(vtype=GRB.BINARY,name="x_%s_is_not_%s"%(token, conceptName))
else:
self.myLogger.info("No ILP negative variable for concept %s and token %s created"%(token, conceptName))
# Add constraints forcing decision between variable and negative variables
for conceptName in conceptNames:
for token in tokens:
if ('Not_'+conceptName, token) in x:
currentConstrLinExpr = x[conceptName, token] + x['Not_'+conceptName, token]
m.addConstr(currentConstrLinExpr == 1, name='c_%s_%sselfDisjoint'%(conceptName, token))
#self.myLogger.debug("Disjoint constrain between token %s is concept %s and token %s is concept - %s == %i"%(token,conceptName,token,'Not_'+conceptName,1))
m.update()
if len(x):
self.myLogger.info("Created %i ILP variables for tokens"%(len(x)))
else:
self.myLogger.warning("No ILP variables created for tokens")
return
if hasattr(self, 'myOnto'): # --- Use Ontology as a source of constrains
# -- Add constraints based on concept disjoint statements in ontology - not(and(var1, var2)) = nand(var1, var2)
foundDisjoint = dict() # too eliminate duplicates
for conceptName in conceptNames:
currentConcept = self.myOnto.search_one(iri = "*%s"%(conceptName))
if currentConcept is None :
continue
#self.myLogger.debug("Concept \"%s\" from data set mapped to \"%s\" concept in ontology"%(currentConcept.name, conceptName))
for d in currentConcept.disjoints():
disjointConcept = d.entities[1]._name
if currentConcept._name == disjointConcept:
disjointConcept = d.entities[0]._name
if currentConcept._name == disjointConcept:
continue
if disjointConcept not in conceptNames:
continue
if conceptName in foundDisjoint:
if disjointConcept in foundDisjoint[conceptName]:
continue
if disjointConcept in foundDisjoint:
if conceptName in foundDisjoint[disjointConcept]:
continue
for tokenIndex, token in enumerate(tokens):
if (conceptName, token) not in x:
continue
self.myIlpBooleanProcessor.nandVar(m, x[conceptName, token], x[disjointConcept, token], onlyConstrains = True)
if not (conceptName in foundDisjoint):
foundDisjoint[conceptName] = {disjointConcept}
else:
foundDisjoint[conceptName].add(disjointConcept)
if conceptName in foundDisjoint:
self.myLogger.info("Created - disjoint - constrains between concept \"%s\" and concepts %s"%(conceptName,foundDisjoint[conceptName]))
# -- Add constraints based on concept equivalent statements in ontology - and(var1, av2)
foundEquivalent = dict() # too eliminate duplicates
for conceptName in conceptNames:
currentConcept = self.myOnto.search_one(iri = "*%s"%(conceptName))
if currentConcept is None :
continue
for equivalentConcept in currentConcept.equivalent_to:
if equivalentConcept.name not in conceptNames:
continue
if conceptName in foundEquivalent:
if equivalentConcept.name in foundEquivalent[conceptName]:
continue
if equivalentConcept.name in foundEquivalent:
if conceptName in foundEquivalent[equivalentConcept.name]:
continue
for tokenIndex, token in enumerate(tokens):
if (conceptName, token) not in x:
continue
self.myIlpBooleanProcessor.andVar(m, x[conceptName, token], x[equivalentConcept, token], onlyConstrains = True)
if not (conceptName in foundEquivalent):
foundEquivalent[conceptName] = {equivalentConcept.name}
else:
foundEquivalent[conceptName].add(equivalentConcept.name)
if conceptName in foundEquivalent:
self.myLogger.info("Created - equivalent - constrains between concept \"%s\" and concepts %s"%(conceptName,foundEquivalent[conceptName]))
# -- Add constraints based on concept subClassOf statements in ontology - var1 -> var2
for conceptName in conceptNames:
currentConcept = self.myOnto.search_one(iri = "*%s"%(conceptName))
if currentConcept is None :
continue
for ancestorConcept in currentConcept.ancestors(include_self = False):
if ancestorConcept.name not in conceptNames:
continue
for tokenIndex, token in enumerate(tokens):
if (conceptName, token) not in x:
continue
if (ancestorConcept, token) not in x:
continue
self.myIlpBooleanProcessor.ifVar(m, x[conceptName, token], x[ancestorConcept.name, token], onlyConstrains = True)
self.myLogger.info("Created - subClassOf - constrains between concept \"%s\" and concept \"%s\""%(conceptName,ancestorConcept.name))
# -- Add constraints based on concept intersection statements in ontology - and(var1, var2, var3, ..)
for conceptName in conceptNames:
currentConcept = self.myOnto.search_one(iri = "*%s"%(conceptName))
if currentConcept is None:
continue
for conceptConstruct in currentConcept.constructs(Prop = None):
if type(conceptConstruct) is And:
for tokenIndex, token in enumerate(tokens):
if (conceptName, token) not in x:
continue
_varAnd = m.addVar(name="andVar_%s_%s"%(conceptName, token))
andList = []
for currentClass in conceptConstruct.Classes :
if (currentClass.name, token) not in x:
continue
andList.append(x[currentClass.name, token])
andList.append(x[conceptName, token])
self.myIlpBooleanProcessor.andVar(m, andList, onlyConstrains = True)
# -- Add constraints based on concept union statements in ontology - or(var1, var2, var3, ..)
for conceptName in conceptNames:
currentConcept = self.myOnto.search_one(iri = "*%s"%(conceptName))
if currentConcept is None:
continue
for conceptConstruct in currentConcept.constructs(Prop = None):
if type(conceptConstruct) is Or:
for tokenIndex, token in enumerate(tokens):
if (conceptName, token) not in x:
continue
_varOr = m.addVar(name="orVar_%s_%s"%(conceptName, token))
orList = []
for currentClass in conceptConstruct.Classes :
if (currentClass.name, token) not in x:
continue
orList.append(x[currentClass.name, token])
orList.append(x[conceptName, token])
self.myIlpBooleanProcessor.orVar(m, orList, onlyConstrains = True)
# -- Add constraints based on concept objectComplementOf statements in ontology - xor(var1, var2)
for conceptName in conceptNames:
currentConcept = self.myOnto.search_one(iri = "*%s"%(conceptName))
if currentConcept is None:
continue
for conceptConstruct in currentConcept.constructs(Prop = None):
if type(conceptConstruct) is Not:
complementClass = conceptConstruct.Class
for tokenIndex, token in enumerate(tokens):
if (conceptName, token) not in x:
continue
if (complementClass.name, token) not in x:
continue
self.myIlpBooleanProcessor.xorVar(m, x[conceptName, token], x[complementClass.name, token], onlyConstrains = True)
self.myLogger.info("Created - objectComplementOf - constrains between concept \"%s\" and concept \"%s\""%(conceptName,complementClass.name))
# ---- No supported yet
# -- Add constraints based on concept disjonitUnion statements in ontology - Not supported by owlready2 yet
# -- Add constraints based on concept oneOf statements in ontology - ?
else: # ---------- no Ontology
concepts = set()
# Get concept based on concept names
for graph in self.myGraph:
for conceptName in conceptNames:
if conceptName in graph.concepts:
concepts.add(graph.concepts[conceptName])
for subGraphKey in graph._objs:
subGraph = graph._objs[subGraphKey]
for conceptName in conceptNames:
if conceptName in subGraph.concepts:
concepts.add(subGraph.concepts[conceptName])
# Create subclass constrains
for concept in concepts:
for rel in concept.is_a():
# A is_a B : if(A, B) : A(x) <= B(x)
for token in tokens:
if (rel.src.name, token) not in x: # subclass (A)
continue
if (rel.dst.name, token) not in x: # superclass (B)
continue
self.myIlpBooleanProcessor.ifVar(m, x[rel.src.name, token], x[rel.dst.name, token], onlyConstrains = True)
self.myLogger.info("Created - subclass - constrains between concept \"%s\" and concepts %s"%(rel.src.name,rel.dst.name))
# Create disjoint constraints
foundDisjoint = dict() # To eliminate duplicates
for concept in concepts:
for rel in concept.not_a():
conceptName = concept.name
disjointConcept = rel.dst.name
if disjointConcept not in conceptNames:
continue
if conceptName in foundDisjoint:
if disjointConcept in foundDisjoint[conceptName]:
continue
if disjointConcept in foundDisjoint:
if conceptName in foundDisjoint[disjointConcept]:
continue
for tokenIndex, token in enumerate(tokens):
if (conceptName, token) not in x:
continue
if (disjointConcept, token) not in x:
continue
self.myIlpBooleanProcessor.nandVar(m, x[conceptName, token], x[disjointConcept, token], onlyConstrains = True)
if not (conceptName in foundDisjoint):
foundDisjoint[conceptName] = {disjointConcept}
else:
foundDisjoint[conceptName].add(disjointConcept)
if conceptName in foundDisjoint:
self.myLogger.info("Created - disjoint - constrains between concept \"%s\" and concepts %s"%(conceptName,foundDisjoint[conceptName]))
m.update()
# Add objectives
X_Q = None
for tokenIndex, token in enumerate(tokens):
for conceptName in conceptNames:
if (conceptName, token) not in x:
continue
currentQElement = graphResultsForPhraseToken[conceptName][tokenIndex][1] * x[conceptName, token]
X_Q += currentQElement
#self.myLogger.debug("Created objective element %s"%(currentQElement))
if ('Not_'+conceptName, token) in x:
currentQElement = graphResultsForPhraseToken[conceptName][tokenIndex][0]*x['Not_'+conceptName, token]
X_Q += currentQElement
#self.myLogger.debug("Created objective element %s"%(currentQElement))
return X_Q
def addRelationsConstrains(self, m, conceptNames, tokens, x, y, graphResultsForPhraseRelation):
if graphResultsForPhraseRelation is None:
return None
self.myLogger.info('Starting method addRelationsConstrains with graphResultsForPhraseToken')
if graphResultsForPhraseRelation is not None:
for relation in graphResultsForPhraseRelation:
#self.myLogger.debug('graphResultsForPhraseRelation for relation \"%s\" \n%s'%(relation, np.column_stack( ([" "] + tokens, np.vstack((tokens, graphResultsForPhraseRelation[relation])))) ))
pass
relationNames = list(graphResultsForPhraseRelation)
# Create variables for relation - token - token and negative variables
for relationName in relationNames:
for token1Index, token1 in enumerate(tokens):
for token2Index, token2 in enumerate(tokens):
if token1 == token2:
continue
# Check if probability is NaN or if and has to be skipped
currentProbability = graphResultsForPhraseRelation[relationName][token1Index][token2Index]
if self.valueToBeSkipped(currentProbability[1]):
self.myLogger.info("Probability is %f for relation %s and tokens %s %s - skipping it"%(currentProbability[1],relationName,token1,token2))
continue
# Create variable
y[relationName, token1, token2]=m.addVar(vtype=GRB.BINARY,name="y_%s_%s_%s"%(token1, relationName, token2))
#self.myLogger.debug("Probability for token %s in relation %s to token %s is %f"%(token1,relationName,token2, currentProbability[1]))
# Check if probability is NaN or if and has to be created based on positive value
if self.valueToBeSkipped(currentProbability[0]):
currentProbability[0] = 1 - currentProbability[1]
self.myLogger.info("No ILP negative variable for relation %s and tokens %s %s - created based on positive value %f"%(relationName,token1,token2, currentProbability[0]))
# Create negative variable
if True: # ilpOntSolver.__negVarTrashhold:
y[relationName+'-neg', token1, token2]=m.addVar(vtype=GRB.BINARY,name="y_%s_not_%s_%s"%(token1, relationName, token2))
else:
self.myLogger.info("No ILP negative variable for relation %s and tokens %s %s created"%(relationName,token1,token2))
# Add constraints forcing decision between variable and negative variables
for relationName in relationNames:
for token1 in tokens:
for token2 in tokens:
if token2 == token1:
continue
if (relationName+'-neg', token1, token2) in y:
m.addConstr(y[relationName, token1, token2] + y[relationName+'-neg', token1, token2] == 1, name='c_%s_%s_%sselfDisjoint'%(token1, token2, relationName))
#self.myLogger.debug("Disjoint constrain between relation %s and not relation %s between tokens - %s %s == %i"%(relationName,relationName,token1,token2,1))
m.update()
self.myLogger.info("Created %i ilp variables for relations"%(len(y)))
if hasattr(self, 'myOnto'): # --- Use Ontology as a source of constrains
# -- Add constraints based on property domain and range statements in ontology - P(x,y) -> D(x), R(y)
for relationName in graphResultsForPhraseRelation:
currentRelation = self.myOnto.search_one(iri = "*%s"%(relationName))
if currentRelation is None:
continue
self.myLogger.debug("Relation \"%s\" from data set mapped to \"%s\" concept in ontology"%(currentRelation.name, relationName))
currentRelationDomain = currentRelation.get_domain() # domains_indirect()
currentRelationRange = currentRelation.get_range()
for domain in currentRelationDomain:
if domain._name not in conceptNames:
continue
for range in currentRelationRange:
if range.name not in conceptNames:
continue
for token1Index, token1 in enumerate(tokens):
for token2Index, token2 in enumerate(tokens):
if token1 == token2:
continue
if (domain.name, token1) not in x:
continue
if (range.name, token2) not in x:
continue
if (currentRelation.name, token1, token2) not in y:
continue
self.myIlpBooleanProcessor.ifVar(m, y[currentRelation._name, token1, token2], x[domain._name, token1], onlyConstrains = True)
self.myIlpBooleanProcessor.ifVar(m, y[currentRelation._name, token1, token2], x[range._name, token2], onlyConstrains = True)
self.myLogger.info("Created - domain-range - constrains for relation \"%s\" for domain \"%s\" and range \"%s\""%(relationName,domain._name,range._name))
# -- Add constraints based on property subProperty statements in ontology R subproperty of S - R(x, y) -> S(x, y)
for relationName in graphResultsForPhraseRelation:
currentRelation = self.myOnto.search_one(iri = "*%s"%(relationName))
if currentRelation is None:
continue
for superProperty in currentRelation.is_a:
if superProperty.name not in graphResultsForPhraseRelation:
continue
for token1Index, token1 in enumerate(tokens):
for token2Index, token2 in enumerate(tokens):
if token1 == token2:
continue
if (superProperty.name, token1, token2) not in y:
continue
self.myIlpBooleanProcessor.ifVar(m, y[relationName, token1, token2], y[superProperty.name, token1, token2], onlyConstrains = True)
# -- Add constraints based on property equivalentProperty statements in ontology - and(R, S)
foundEquivalent = dict() # too eliminate duplicates
for relationName in graphResultsForPhraseRelation:
currentRelation = self.myOnto.search_one(iri = "*%s"%(relationName))
if currentRelation is None:
continue
for equivalentProperty in currentRelation.equivalent_to:
if equivalentProperty.name not in graphResultsForPhraseRelation:
continue
if relationName in foundEquivalent:
if equivalentProperty.name in foundEquivalent[relationName]:
continue
if equivalentProperty.name in foundEquivalent:
if relationName in foundEquivalent[equivalentProperty.name]:
continue
for token1Index, token1 in enumerate(tokens):
for token2Index, token2 in enumerate(tokens):
if token1 == token2:
continue
if (relationName, token1, token2) not in y:
continue
if (equivalentProperty.name, token1, token2) not in y:
continue
self.myIlpBooleanProcessor.andVar(m, y[relationName, token1, token2], y[equivalentProperty.name, token1, token2], onlyConstrains = True)
if not (relationName in foundEquivalent):
foundEquivalent[relationName] = {equivalentProperty.name}
else:
foundEquivalent[relationName].add(equivalentProperty.name)
# -- Add constraints based on property inverseProperty statements in ontology - S(x,y) -> R(y,x)
for relationName in graphResultsForPhraseRelation:
currentRelation = self.myOnto.search_one(iri = "*%s"%(relationName))
if currentRelation is None:
continue
currentRelationInverse = currentRelation.get_inverse_property()
if not currentRelationInverse:
continue
if currentRelationInverse.name not in graphResultsForPhraseRelation:
continue
if currentRelationInverse is not None:
for token1Index, token1 in enumerate(tokens):
for token2Index, token2 in enumerate(tokens):
if token1 == token2:
continue
if (relationName, token1, token2) not in y:
continue
if (currentRelationInverse.name, token1, token2) not in y:
continue
self.myIlpBooleanProcessor.ifVar(m, y[currentRelationInverse.name, token1, token2], y[relationName, token1, token2], onlyConstrains = True)
# -- Add constraints based on property functionalProperty statements in ontology - at most one P(x,y) for x
for relationName in graphResultsForPhraseRelation:
currentRelation = self.myOnto.search_one(iri = "*%s"%(relationName))
if currentRelation is None:
continue
functionalLinExpr = LinExpr()
if FunctionalProperty in currentRelation.is_a:
for token1Index, token1 in enumerate(tokens):
for token2Index, token2 in enumerate(tokens):
if token1 == token2:
continue
if (relationName, token1, token2) not in y:
continue
functionalLinExpr += y[relationName, token1, token2]
if functionalLinExpr:
constrainName = 'c_%s_FunctionalProperty'%(relationName)
m.addConstr(functionalLinExpr <= 1, name=constrainName)
# -- Add constraints based on property inverseFunctionaProperty statements in ontology - at most one P(x,y) for y
for relationName in graphResultsForPhraseRelation:
currentRelation = self.myOnto.search_one(iri = "*%s"%(relationName))
if currentRelation is None:
continue
if InverseFunctionalProperty in currentRelation.is_a:
for token1 in tokens:
for token2 in tokens:
if token1 == token2:
continue
if (relationName, token1, token2) not in y:
continue
functionalLinExpr += y[relationName, token2, token1]
if functionalLinExpr:
constrainName = 'c_%s_InverseFunctionalProperty'%(relationName)
m.addConstr(functionalLinExpr <= 1, name=constrainName)
# -- Add constraints based on property reflexiveProperty statements in ontology - P(x,x)
for relationName in graphResultsForPhraseRelation:
currentRelation = self.myOnto.search_one(iri = "*%s"%(relationName))
if currentRelation is None:
continue
if ReflexiveProperty in currentRelation.is_a:
for tokenIndex, token in enumerate(tokens):
if (relationName, token1, token2) not in y:
continue
constrainName = 'c_%s_%s_ReflexiveProperty'%(token, relationName)
m.addConstr(y[relationName, token, token] == 1, name=constrainName)
# -- Add constraints based on property irreflexiveProperty statements in ontology - not P(x,x)
for relationName in graphResultsForPhraseRelation:
currentRelation = self.myOnto.search_one(iri = "*%s"%(relationName))
if currentRelation is None:
continue
if IrreflexiveProperty in currentRelation.is_a:
for tokenIndex, token in enumerate(tokens):
if (relationName, token1, token2) not in y:
continue
constrainName = 'c_%s_%s_ReflexiveProperty'%(token, relationName)
m.addConstr(y[relationName, token, token] == 0, name=constrainName)
# -- Add constraints based on property symetricProperty statements in ontology - R(x, y) -> R(y,x)
for relationName in graphResultsForPhraseRelation:
currentRelation = self.myOnto.search_one(iri = "*%s"%(relationName))
if currentRelation is None:
continue
if SymmetricProperty in currentRelation.is_a:
for token1Index, token1 in enumerate(tokens):
for token2Index, token2 in enumerate(tokens):
if token1 == token2:
continue
if (relationName, token1, token2) not in y:
continue
constrainName = 'c_%s_%s_%s_SymmetricProperty'%(token1, token2, relationName)
m.addGenConstrIndicator(y[relationName, token1, token2], True, y[relationName, token2, token1] == 1)
# -- Add constraints based on property asymetricProperty statements in ontology - not R(x, y) -> R(y,x)
for relationName in graphResultsForPhraseRelation:
currentRelation = self.myOnto.search_one(iri = "*%s"%(relationName))
if currentRelation is None:
continue
if AsymmetricProperty in currentRelation.is_a:
for token1Index, token1 in enumerate(tokens):
for token2Index, token2 in enumerate(tokens):
if token1 == token2:
continue
if (relationName, token1, token2) not in y:
continue
constrainName = 'c_%s_%s_%s_AsymmetricProperty'%(token1, token2, relationName)
m.addGenConstrIndicator(y[relationName, token1, token2], True, y[relationName, token2, token1] == 0)
# -- Add constraints based on property transitiveProperty statements in ontology - P(x,y) and P(y,z) - > P(x,z)
for relationName in graphResultsForPhraseRelation:
currentRelation = self.myOnto.search_one(iri = "*%s"%(relationName))
if currentRelation is None:
continue
if TransitiveProperty in currentRelation.is_a:
for token1Index, token1 in enumerate(tokens):
for token2Index, token2 in enumerate(tokens):
if token1 == token2:
continue
if (relationName, token1, token2) not in y:
continue
constrainName = 'c_%s_%s_%s_TransitiveProperty'%(token1, token2, relationName)
#m.addGenConstrIndicator(y[relationName, token, token1], True, y[relationName, token1, token] == 1)
# -- Add constraints based on property allValueFrom statements in ontology
# -- Add constraints based on property hasValueFrom statements in ontology
# -- Add constraints based on property objectHasSelf statements in ontology
# -- Add constraints based on property disjointProperty statements in ontology
# -- Add constraints based on property key statements in ontology
# -- Add constraints based on property exactCardinality statements in ontology
# -- Add constraints based on property minCardinality statements in ontology
# -- Add constraints based on property maxCardinality statements in ontology
for relationName in graphResultsForPhraseRelation:
currentRelation = self.myOnto.search_one(iri = "*%s"%(relationName))
if currentRelation is None:
continue
# ---- Related to DataType properties - not sure yet if we need to support them
# -- Add constraints based on property dataSomeValuesFrom statements in ontology
# -- Add constraints based on property dataHasValue statements in ontology
# -- Add constraints based on property dataAllValuesFrom statements in ontology
else: # ------ No Ontology
relations = set()
for graph in self.myGraph:
for currentGraphConceptName in graph.concepts:
for relationName in graphResultsForPhraseRelation:
if relationName in graph.concepts:
relations.add(graph.concepts[relationName])
for subGraphKey in graph._objs:
subGraph = graph._objs[subGraphKey]
for relationName in graphResultsForPhraseRelation:
if relationName in subGraph.concepts:
relations.add(subGraph.concepts[relationName])
for relation in relations:
for arg_id, rel in enumerate(relation.has_a()):
# TODO: need to include indirect ones like sp_tr is a tr while tr has a lm
# A has_a B : A(x,y,...) <= B(x)
#for xy in candidates[rel.src]:
#x = xy[arg_id]
relationName = rel.src.name
conceptName = rel.dst.name
for token1 in tokens:
for token2 in tokens:
if token1 == token2:
continue
else:
if (relationName, token1, token2) not in y:
continue
if arg_id is 0: # Domain
if (conceptName, token1) not in x:
continue
self.myIlpBooleanProcessor.ifVar(m, y[relationName, token1, token2], x[conceptName, token1], onlyConstrains = True)
#self.myLogger.info("Created - domain - constrains for relation \"%s\" and \"%s\""%(y[relationName, token1, token2].VarName,x[conceptName, token1].VarName))
elif arg_id is 1: # Range
if (conceptName, token2) not in x:
continue
self.myIlpBooleanProcessor.ifVar(m, y[relationName, token1, token2], x[conceptName, token2], onlyConstrains = True)
#self.myLogger.info("Created - range - constrains for relation \"%s\" and \"%s\""%(y[relationName, token1, token2].VarName,x[conceptName, token2].VarName))
else:
self.myLogger.warn("When creating domain-range constrains for relation \"%s\" for concept \"%s\" received more then two concepts"%(relationName,conceptName))
m.update()
# Add objectives
Y_Q = None
for relationName in relationNames:
for token1Index, token1 in enumerate(tokens):
for token2Index, token2 in enumerate(tokens):
if token1 == token2 :
continue
if (relationName, token1, token2) not in y:
continue
currentQElement = graphResultsForPhraseRelation[relationName][token1Index][token2Index][1]*y[relationName, token1, token2]
Y_Q += currentQElement
#self.myLogger.debug("Created objective element %s"%(currentQElement))
if (relationName+'-neg', token1, token2) in y:
currentQElement = graphResultsForPhraseRelation[relationName][token1Index][token2Index][0]*y[relationName+'-neg', token1, token2]
Y_Q += currentQElement
#self.myLogger.debug("Created objective element %s"%(currentQElement))
return Y_Q
def addTripleRelationsConstrains(self, m, conceptNames, tokens, x, y, z, graphResultsForPhraseTripleRelation):
if graphResultsForPhraseTripleRelation is None:
return None
self.myLogger.info('Starting method addTripleRelationsConstrains with graphResultsForPhraseTripleRelation')
if graphResultsForPhraseTripleRelation is not None:
for tripleRelation in graphResultsForPhraseTripleRelation:
self.myLogger.debug('graphResultsForPhraseTripleRelation for relation \"%s"'%(tripleRelation))
for token1Index, token1 in enumerate(tokens):
#self.myLogger.debug('for token \"%s \n%s"'%(token1, np.column_stack( ([" "] + tokens, np.vstack((tokens, graphResultsForPhraseTripleRelation[tripleRelation][token1Index]))))))
pass
tripleRelationNames = list(graphResultsForPhraseTripleRelation)
# Create variables for relation - token - token -token and negative variables
for tripleRelationName in tripleRelationNames:
for token1Index, token1 in enumerate(tokens):
for token2Index, token2 in enumerate(tokens):
if token2 == token1:
continue
for token3Index, token3 in enumerate(tokens):
if token3 == token2:
continue
if token3 == token1:
continue
# Check if probability is NaN or if and has to be skipped
currentProbability = graphResultsForPhraseTripleRelation[tripleRelationName][token1Index][token2Index][token3Index]
#self.myLogger.info("Probability is %f for relation %s and tokens %s %s %s"%(currentProbability[1],tripleRelationName,token1,token2,token3))
if self.valueToBeSkipped(currentProbability[1]):
self.myLogger.info("Probability is %f for relation %s and tokens %s %s %s - skipping it"%(currentProbability[1],tripleRelationName,token1,token2, token3))
continue
# Create variable
z[tripleRelationName, token1, token2, token3]=m.addVar(vtype=GRB.BINARY,name="z_%s_%s_%s_%s"%(tripleRelationName, token1, token2, token3))
#self.myLogger.debug("Created variable for relation %s between tokens %s %s %s, probability is %f"%(tripleRelationName,token1, token2, token3, currentProbability[1]))
# Check if probability is NaN or if and has to be created based on positive value
if self.valueToBeSkipped(currentProbability[0]):
currentProbability[0] = 1 - currentProbability[1]
self.myLogger.info("No ILP negative variable for relation %s and tokens %s %s %s - created based on positive value %f"%(tripleRelationName,token1,token2,token3, currentProbability[0]))
# Create negative variable
if True: #ilpOntSolver.__negVarTrashhold:
z[tripleRelationName+'-neg', token1, token2, token3]=m.addVar(vtype=GRB.BINARY,name="y_%s_not_%s_%s_%s"%(tripleRelationName, token1, token2, token3))
else:
self.myLogger.info("No ILP negative variable for relation %s and tokens %s %s %s created"%(tripleRelationName,token1,token2,token3))
# Add constraints forcing decision between variable and negative variables
for tripleRelationName in tripleRelationNames:
for token1Index, token1 in enumerate(tokens):
for token2Index, token2 in enumerate(tokens):
if token2 == token1:
continue
for token3Index, token3 in enumerate(tokens):
if token3 == token2:
continue
if token3 == token1:
continue
currentProbability = graphResultsForPhraseTripleRelation[tripleRelationName][token1Index][token2Index][token3Index]
if currentProbability[1] == 0:
continue
if (tripleRelationName+'-neg', token1, token2, token3) in z:
m.addConstr(z[tripleRelationName, token1, token2, token3] + z[tripleRelationName+'-neg', token1, token2, token3] == 1, name='c_%s_%s_%s_%sselfDisjoint'%(token1, token2, token3, tripleRelationName))
#self.myLogger.debug("Disjoint constrain between relation %s and not relation %s between tokens - %s %s %s == %i"%(tripleRelationName,tripleRelationName,token1,token2,token3,1))
m.update()
self.myLogger.info("Created %i ilp variables for triple relations"%(len(z)))
if hasattr(self, 'myOnto'): # --- Use Ontology as a source of constrains
# -- Add constraints based on concept subClassOf statements in ontology - var1 -> var2
for tripleRelationName in tripleRelationNames:
tripleRelation = self.myOnto.search_one(iri = "*%s"%(tripleRelationName))
if tripleRelation is None :
continue
for ancestorTripleRelation in tripleRelation.ancestors(include_self = False) :
if ancestorTripleRelation.name not in tripleRelationNames:
continue
for token1Index, token1 in enumerate(tokens):
for token2Index, token2 in enumerate(tokens):
if token2 == token1:
continue
for token3Index, token3 in enumerate(tokens):
if token3 == token2:
continue
if token3 == token1:
continue
if (tripleRelationName, token1, token2, token3) not in z:
continue
if (ancestorTripleRelation.name, token1, token2, token3) not in z:
continue
self.myIlpBooleanProcessor.ifVar(m, z[tripleRelationName, token1, token2, token3], z[ancestorTripleRelation.name, token1, token2, token3], onlyConstrains = True)
self.myLogger.info("Created - subClassOf - constrains between triple relations \"%s\" -> \"%s\""%(tripleRelationName,ancestorTripleRelation.name))
# -- Add constraints based on concept disjoint statements in ontology - not(and(var1, var2)) = nand(var1, var2)
foundDisjoint = dict() # too eliminate duplicates
for tripleRelationName in tripleRelationNames:
tripleRelation = self.myOnto.search_one(iri = "*%s"%(tripleRelationName))
if tripleRelation is None :
continue
for d in tripleRelation.disjoints():
disjointTriple = d.entities[1]._name
if tripleRelationName == disjointTriple:
disjointTriple = d.entities[0]._name
if tripleRelationName == disjointTriple:
continue
if disjointTriple not in tripleRelationNames:
continue
if tripleRelationName in foundDisjoint:
if disjointTriple in foundDisjoint[tripleRelationName]:
continue
if disjointTriple in foundDisjoint:
if tripleRelationName in foundDisjoint[disjointTriple]:
continue
for token1Index, token1 in enumerate(tokens):
for token2Index, token2 in enumerate(tokens):
if token2 == token1:
continue
for token3Index, token3 in enumerate(tokens):
if token3 == token2:
continue
if token3 == token1:
continue
if (tripleRelationName, token1, token2, token3) not in z:
continue
if (disjointTriple, token1, token2, token3) not in z:
continue
self.myIlpBooleanProcessor.nandVar(m, z[tripleRelationName, token1, token2, token3], z[disjointTriple, token1, token2, token3], onlyConstrains = True)
if not (tripleRelationName in foundDisjoint):
foundDisjoint[tripleRelationName] = {disjointTriple}
else:
foundDisjoint[tripleRelationName].add(disjointTriple)
if tripleRelationName in foundDisjoint:
self.myLogger.info("Created - disjoint - constrains between triples \"%s\" and %s"%(tripleRelationName,foundDisjoint[tripleRelationName]))
# -- Add constraints based on triple relation ranges
for tripleRelationName in graphResultsForPhraseTripleRelation:
currentTripleRelation = self.myOnto.search_one(iri = "*%s"%(tripleRelationName))
if currentTripleRelation is None:
continue
#self.myLogger.debug("Triple Relation \"%s\" from data set mapped to \"%s\" concept in ontology"%(currentTripleRelation.name, currentTripleRelation))
ancestorConcept = None
for _ancestorConcept in currentTripleRelation.ancestors(include_self = True):
if _ancestorConcept.name == "Thing":
continue
ancestorConcept = _ancestorConcept
break
if ancestorConcept is None:
break
tripleProperties = {}
triplePropertiesRanges = {}
noTriplePropertiesRanges = 0
for property in self.myOnto.object_properties():
_domain = property.domain
if _domain is None:
break
domain = _domain[0]._name
if domain is ancestorConcept.name:
for superProperty in property.is_a:
if superProperty is None:
continue
if superProperty.name == "ObjectProperty":
continue
if superProperty.name == 'first':
tripleProperties['1'] = property
_range = property.range
if _range is None:
break
range = _range[0]._name