-
Notifications
You must be signed in to change notification settings - Fork 80
/
InferenceEngine.java
1285 lines (1198 loc) · 60.8 KB
/
InferenceEngine.java
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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.rya.rdftriplestore.inference;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Stack;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang3.mutable.MutableObject;
import org.apache.log4j.Logger;
import org.apache.rya.api.RdfCloudTripleStoreConfiguration;
import org.apache.rya.api.persist.RyaDAO;
import org.apache.rya.api.persist.RyaDAOException;
import org.apache.rya.api.persist.utils.RyaDAOHelper;
import org.apache.rya.api.persist.utils.RyaDaoQueryWrapper;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.impl.StatementImpl;
import org.openrdf.model.impl.ValueFactoryImpl;
import org.openrdf.model.vocabulary.OWL;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.model.vocabulary.RDFS;
import org.openrdf.query.QueryEvaluationException;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.helpers.RDFHandlerBase;
import com.google.common.collect.Sets;
import info.aduna.iteration.CloseableIteration;
/**
* Will pull down inference relationships from dao every x seconds. <br>
* Will infer extra relationships. <br>
* Will cache relationships in Graph for later use. <br>
*/
public class InferenceEngine {
private static final Logger log = Logger.getLogger(InferenceEngine.class);
private Graph subClassOfGraph;
private Graph subPropertyOfGraph;
private Set<URI> symmetricPropertySet;
private Map<URI, URI> inverseOfMap;
private Set<URI> transitivePropertySet;
private Map<URI, Set<URI>> domainByType;
private Map<URI, Set<URI>> rangeByType;
private Map<Resource, Map<URI, Value>> hasValueByType;
private Map<URI, Map<Resource, Value>> hasValueByProperty;
private Map<Resource, Map<Resource, URI>> allValuesFromByValueType;
private final ConcurrentHashMap<Resource, List<Set<Resource>>> intersections = new ConcurrentHashMap<>();
private RyaDAO<?> ryaDAO;
private RdfCloudTripleStoreConfiguration conf;
private RyaDaoQueryWrapper ryaDaoQueryWrapper;
private boolean initialized = false;
private boolean schedule = true;
private long refreshGraphSchedule = 5 * 60 * 1000; //5 min
private Timer timer;
private HashMap<URI, List<URI>> propertyChainPropertyToChain = new HashMap<>();
public static final String URI_PROP = "uri";
public void init() throws InferenceEngineException {
try {
if (isInitialized()) {
return;
}
checkNotNull(conf, "Configuration is null");
checkNotNull(ryaDAO, "RdfDao is null");
checkArgument(ryaDAO.isInitialized(), "RdfDao is not initialized");
ryaDaoQueryWrapper = new RyaDaoQueryWrapper(ryaDAO, conf);
if (schedule) {
refreshGraph();
timer = new Timer(InferenceEngine.class.getName());
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
try {
refreshGraph();
} catch (final InferenceEngineException e) {
throw new RuntimeException(e);
}
}
}, refreshGraphSchedule, refreshGraphSchedule);
}
refreshGraph();
setInitialized(true);
} catch (final RyaDAOException e) {
throw new InferenceEngineException(e);
}
}
public void destroy() throws InferenceEngineException {
setInitialized(false);
if (timer != null) {
timer.cancel();
}
}
public void refreshGraph() throws InferenceEngineException {
final ValueFactory vf = ValueFactoryImpl.getInstance();
try {
CloseableIteration<Statement, QueryEvaluationException> iter;
//get all subclassof
Graph graph = TinkerGraph.open();
addPredicateEdges(RDFS.SUBCLASSOF, Direction.OUT, graph, RDFS.SUBCLASSOF.stringValue());
//equivalentClass is the same as subClassOf both ways
addPredicateEdges(OWL.EQUIVALENTCLASS, Direction.BOTH, graph, RDFS.SUBCLASSOF.stringValue());
// Add unions to the subclass graph: if c owl:unionOf LIST(c1, c2, ... cn), then any
// instances of c1, c2, ... or cn are also instances of c, meaning c is a superclass
// of all the rest.
// (In principle, an instance of c is likewise implied to be at least one of the other
// types, but this fact is ignored for now to avoid nondeterministic reasoning.)
iter = RyaDAOHelper.query(ryaDAO, null, OWL.UNIONOF, null, conf);
try {
while (iter.hasNext()) {
final Statement st = iter.next();
final Value unionType = st.getSubject();
// Traverse the list of types constituting the union
Value current = st.getObject();
while (current instanceof Resource && !RDF.NIL.equals(current)) {
final Resource listNode = (Resource) current;
CloseableIteration<Statement, QueryEvaluationException> listIter = RyaDAOHelper.query(ryaDAO,
listNode, RDF.FIRST, null, conf);
try {
if (listIter.hasNext()) {
final Statement firstStatement = listIter.next();
if (firstStatement.getObject() instanceof Resource) {
final Resource subclass = (Resource) firstStatement.getObject();
final Statement subclassStatement = vf.createStatement(subclass, RDFS.SUBCLASSOF, unionType);
addStatementEdge(graph, RDFS.SUBCLASSOF.stringValue(), subclassStatement);
}
}
} finally {
listIter.close();
}
listIter = RyaDAOHelper.query(ryaDAO, listNode, RDF.REST, null, conf);
try {
if (listIter.hasNext()) {
current = listIter.next().getObject();
}
else {
current = RDF.NIL;
}
} finally {
listIter.close();
}
}
}
} finally {
if (iter != null) {
iter.close();
}
}
subClassOfGraph = graph; //TODO: Should this be synchronized?
graph = TinkerGraph.open();
addPredicateEdges(RDFS.SUBPROPERTYOF, Direction.OUT, graph, RDFS.SUBPROPERTYOF.stringValue());
//equiv property really is the same as a subPropertyOf both ways
addPredicateEdges(OWL.EQUIVALENTPROPERTY, Direction.BOTH, graph, RDFS.SUBPROPERTYOF.stringValue());
subPropertyOfGraph = graph; //TODO: Should this be synchronized?
refreshIntersectionOf();
iter = RyaDAOHelper.query(ryaDAO, null, RDF.TYPE, OWL.SYMMETRICPROPERTY, conf);
final Set<URI> symProp = new HashSet<>();
try {
while (iter.hasNext()) {
final Statement st = iter.next();
symProp.add((URI) st.getSubject()); //safe to assume it is a URI?
}
} finally {
if (iter != null) {
iter.close();
}
}
symmetricPropertySet = symProp;
iter = RyaDAOHelper.query(ryaDAO, null, RDF.TYPE, OWL.TRANSITIVEPROPERTY, conf);
final Set<URI> transProp = new HashSet<>();
try {
while (iter.hasNext()) {
final Statement st = iter.next();
transProp.add((URI) st.getSubject());
}
} finally {
if (iter != null) {
iter.close();
}
}
transitivePropertySet = transProp;
iter = RyaDAOHelper.query(ryaDAO, null, OWL.INVERSEOF, null, conf);
final Map<URI, URI> invProp = new HashMap<>();
try {
while (iter.hasNext()) {
final Statement st = iter.next();
invProp.put((URI) st.getSubject(), (URI) st.getObject());
invProp.put((URI) st.getObject(), (URI) st.getSubject());
}
} finally {
if (iter != null) {
iter.close();
}
}
inverseOfMap = invProp;
iter = RyaDAOHelper.query(ryaDAO, null,
vf.createURI("http://www.w3.org/2002/07/owl#propertyChainAxiom"),
null, conf);
final Map<URI,URI> propertyChainPropertiesToBNodes = new HashMap<>();
propertyChainPropertyToChain = new HashMap<>();
try {
while (iter.hasNext()){
final Statement st = iter.next();
propertyChainPropertiesToBNodes.put((URI)st.getSubject(), (URI)st.getObject());
}
} finally {
if (iter != null) {
iter.close();
}
}
// now for each property chain bNode, get the indexed list of properties associated with that chain
for (final URI propertyChainProperty : propertyChainPropertiesToBNodes.keySet()){
final URI bNode = propertyChainPropertiesToBNodes.get(propertyChainProperty);
// query for the list of indexed properties
iter = RyaDAOHelper.query(ryaDAO, bNode, vf.createURI("http://www.w3.org/2000/10/swap/list#index"),
null, conf);
final TreeMap<Integer, URI> orderedProperties = new TreeMap<>();
// TODO refactor this. Wish I could execute sparql
try {
while (iter.hasNext()){
final Statement st = iter.next();
final String indexedElement = st.getObject().stringValue();
log.info(indexedElement);
CloseableIteration<Statement, QueryEvaluationException> iter2 = RyaDAOHelper.query(ryaDAO, vf.createURI(st.getObject().stringValue()), RDF.FIRST,
null, conf);
String integerValue = "";
Value anonPropNode = null;
Value propURI = null;
if (iter2 != null){
while (iter2.hasNext()){
final Statement iter2Statement = iter2.next();
integerValue = iter2Statement.getObject().stringValue();
break;
}
iter2.close();
}
iter2 = RyaDAOHelper.query(ryaDAO, vf.createURI(st.getObject().stringValue()), RDF.REST,
null, conf);
if (iter2 != null){
while (iter2.hasNext()){
final Statement iter2Statement = iter2.next();
anonPropNode = iter2Statement.getObject();
break;
}
iter2.close();
if (anonPropNode != null){
iter2 = RyaDAOHelper.query(ryaDAO, vf.createURI(anonPropNode.stringValue()), RDF.FIRST,
null, conf);
while (iter2.hasNext()){
final Statement iter2Statement = iter2.next();
propURI = iter2Statement.getObject();
break;
}
iter2.close();
}
}
if (!integerValue.isEmpty() && propURI!=null) {
try {
final int indexValue = Integer.parseInt(integerValue);
final URI chainPropURI = vf.createURI(propURI.stringValue());
orderedProperties.put(indexValue, chainPropURI);
}
catch (final Exception ex){
// TODO log an error here
}
}
}
} finally{
if (iter != null){
iter.close();
}
}
final List<URI> properties = new ArrayList<>();
for (final Map.Entry<Integer, URI> entry : orderedProperties.entrySet()){
properties.add(entry.getValue());
}
propertyChainPropertyToChain.put(propertyChainProperty, properties);
}
// could also be represented as a list of properties (some of which may be blank nodes)
for (final URI propertyChainProperty : propertyChainPropertiesToBNodes.keySet()){
final List<URI> existingChain = propertyChainPropertyToChain.get(propertyChainProperty);
// if we didn't get a chain, try to get it through following the collection
if ((existingChain == null) || existingChain.isEmpty()) {
CloseableIteration<Statement, QueryEvaluationException> iter2 = RyaDAOHelper.query(ryaDAO, propertyChainPropertiesToBNodes.get(propertyChainProperty), RDF.FIRST,
null, conf);
final List<URI> properties = new ArrayList<>();
URI previousBNode = propertyChainPropertiesToBNodes.get(propertyChainProperty);
if (iter2.hasNext()) {
Statement iter2Statement = iter2.next();
Value currentPropValue = iter2Statement.getObject();
while ((currentPropValue != null) && (!currentPropValue.stringValue().equalsIgnoreCase(RDF.NIL.stringValue()))){
if (currentPropValue instanceof URI){
iter2 = RyaDAOHelper.query(ryaDAO, vf.createURI(currentPropValue.stringValue()), RDF.FIRST,
null, conf);
if (iter2.hasNext()){
iter2Statement = iter2.next();
if (iter2Statement.getObject() instanceof URI){
properties.add((URI)iter2Statement.getObject());
}
}
// otherwise see if there is an inverse declaration
else {
iter2 = RyaDAOHelper.query(ryaDAO, vf.createURI(currentPropValue.stringValue()), OWL.INVERSEOF,
null, conf);
if (iter2.hasNext()){
iter2Statement = iter2.next();
if (iter2Statement.getObject() instanceof URI){
properties.add(new InverseURI((URI)iter2Statement.getObject()));
}
}
}
// get the next prop pointer
iter2 = RyaDAOHelper.query(ryaDAO, previousBNode, RDF.REST,
null, conf);
if (iter2.hasNext()){
iter2Statement = iter2.next();
previousBNode = (URI)currentPropValue;
currentPropValue = iter2Statement.getObject();
}
else {
currentPropValue = null;
}
}
else {
currentPropValue = null;
}
}
propertyChainPropertyToChain.put(propertyChainProperty, properties);
}
}
}
refreshDomainRange();
refreshPropertyRestrictions();
} catch (final QueryEvaluationException e) {
throw new InferenceEngineException(e);
}
}
/**
* Query for all triples involving a given predicate and add corresponding edges to a
* {@link Graph} in one or both directions.
* @param predicate Find all connections via this predicate URI
* @param dir Direction of interest: for a matching triple, if {@link Direction#OUT} add an edge
* from subject to object; if {@link Direction#IN} add an edge from object to subject;
* if {@link Direction#BOTH} add both.
* @param graph A TinkerPop graph
* @param edgeName Label that will be given to all added edges
* @throws QueryEvaluationException
*/
private void addPredicateEdges(final URI predicate, final Direction dir, final Graph graph, final String edgeName)
throws QueryEvaluationException {
final CloseableIteration<Statement, QueryEvaluationException> iter = RyaDAOHelper.query(ryaDAO,
null, predicate, null, conf);
try {
while (iter.hasNext()) {
final Statement st = iter.next();
if (Direction.OUT.equals(dir) || Direction.BOTH.equals(dir)) {
addStatementEdge(graph, edgeName, st);
}
if (Direction.IN.equals(dir) || Direction.BOTH.equals(dir)) {
addStatementEdge(graph, edgeName, new StatementImpl((Resource) st.getObject(),
st.getPredicate(), st.getSubject()));
}
}
} finally {
if (iter != null) {
iter.close();
}
}
}
/**
* Queries domain and range information, then populates the inference engine with direct
* domain/range relations and any that can be inferred from the subclass graph, subproperty
* graph, and inverse property map. Should be called after that class and property information
* has been refreshed.
*
* Computes indirect domain/range:
* - If p1 has domain c, and p2 is a subproperty of p1, then p2 also has domain c.
* - If p1 has range c, and p2 is a subproperty of p1, then p2 also has range c.
* - If p1 has domain c, and p2 is the inverse of p1, then p2 has range c.
* - If p1 has range c, and p2 is the inverse of p1, then p2 has domain c.
* - If p has domain c1, and c1 is a subclass of c2, then p also has domain c2.
* - If p has range c1, and c1 is a subclass of c2, then p also has range c2.
* @throws QueryEvaluationException
*/
private void refreshDomainRange() throws QueryEvaluationException {
final Map<URI, Set<URI>> domainByTypePartial = new ConcurrentHashMap<>();
final Map<URI, Set<URI>> rangeByTypePartial = new ConcurrentHashMap<>();
// First, populate domain and range based on direct domain/range triples.
CloseableIteration<Statement, QueryEvaluationException> iter = RyaDAOHelper.query(ryaDAO, null, RDFS.DOMAIN, null, conf);
try {
while (iter.hasNext()) {
final Statement st = iter.next();
final Resource property = st.getSubject();
final Value domainType = st.getObject();
if (domainType instanceof URI && property instanceof URI) {
if (!domainByTypePartial.containsKey(domainType)) {
domainByTypePartial.put((URI) domainType, new HashSet<>());
}
domainByTypePartial.get(domainType).add((URI) property);
}
}
} finally {
if (iter != null) {
iter.close();
}
}
iter = RyaDAOHelper.query(ryaDAO, null, RDFS.RANGE, null, conf);
try {
while (iter.hasNext()) {
final Statement st = iter.next();
final Resource property = st.getSubject();
final Value rangeType = st.getObject();
if (rangeType instanceof URI && property instanceof URI) {
if (!rangeByTypePartial.containsKey(rangeType)) {
rangeByTypePartial.put((URI) rangeType, new HashSet<>());
}
rangeByTypePartial.get(rangeType).add((URI) property);
}
}
} finally {
if (iter != null) {
iter.close();
}
}
// Then combine with the subclass/subproperty graphs and the inverse property map to compute
// the closure of domain and range per class.
final Set<URI> domainRangeTypeSet = new HashSet<>(domainByTypePartial.keySet());
domainRangeTypeSet.addAll(rangeByTypePartial.keySet());
// Extend to subproperties: make sure that using a more specific form of a property
// still triggers its domain/range inferences.
// Mirror for inverse properties: make sure that using the inverse form of a property
// triggers the inverse domain/range inferences.
// These two rules can recursively trigger one another.
for (final URI domainRangeType : domainRangeTypeSet) {
final Set<URI> propertiesWithDomain = domainByTypePartial.getOrDefault(domainRangeType, new HashSet<>());
final Set<URI> propertiesWithRange = rangeByTypePartial.getOrDefault(domainRangeType, new HashSet<>());
// Since findParents will traverse the subproperty graph and find all indirect
// subproperties, the subproperty rule does not need to trigger itself directly.
// And since no more than one inverseOf relationship is stored for any property, the
// inverse property rule does not need to trigger itself directly. However, each rule
// can trigger the other, so keep track of how the inferred domains/ranges were
// discovered so we can apply only those rules that might yield new information.
final Stack<URI> domainViaSuperProperty = new Stack<>();
final Stack<URI> rangeViaSuperProperty = new Stack<>();
final Stack<URI> domainViaInverseProperty = new Stack<>();
final Stack<URI> rangeViaInverseProperty = new Stack<>();
// Start with the direct domain/range assertions, which can trigger any rule.
domainViaSuperProperty.addAll(propertiesWithDomain);
domainViaInverseProperty.addAll(propertiesWithDomain);
rangeViaSuperProperty.addAll(propertiesWithRange);
rangeViaInverseProperty.addAll(propertiesWithRange);
// Repeatedly infer domain/range from subproperties/inverse properties until no new
// information can be generated.
while (!(domainViaSuperProperty.isEmpty() && rangeViaSuperProperty.isEmpty()
&& domainViaInverseProperty.isEmpty() && rangeViaInverseProperty.isEmpty())) {
// For a type c and property p, if c is a domain of p, then c is the range of any
// inverse of p. Would be redundant for properties discovered via inverseOf.
while (!domainViaSuperProperty.isEmpty()) {
final URI property = domainViaSuperProperty.pop();
final URI inverseProperty = findInverseOf(property);
if (inverseProperty != null && propertiesWithRange.add(inverseProperty)) {
rangeViaInverseProperty.push(inverseProperty);
}
}
// For a type c and property p, if c is a range of p, then c is the domain of any
// inverse of p. Would be redundant for properties discovered via inverseOf.
while (!rangeViaSuperProperty.isEmpty()) {
final URI property = rangeViaSuperProperty.pop();
final URI inverseProperty = findInverseOf(property);
if (inverseProperty != null && propertiesWithDomain.add(inverseProperty)) {
domainViaInverseProperty.push(inverseProperty);
}
}
// For a type c and property p, if c is a domain of p, then c is also a domain of
// p's subproperties. Would be redundant for properties discovered via this rule.
while (!domainViaInverseProperty.isEmpty()) {
final URI property = domainViaInverseProperty.pop();
final Set<URI> subProperties = findParents(subPropertyOfGraph, property);
subProperties.removeAll(propertiesWithDomain);
propertiesWithDomain.addAll(subProperties);
domainViaSuperProperty.addAll(subProperties);
}
// For a type c and property p, if c is a range of p, then c is also a range of
// p's subproperties. Would be redundant for properties discovered via this rule.
while (!rangeViaInverseProperty.isEmpty()) {
final URI property = rangeViaInverseProperty.pop();
final Set<URI> subProperties = findParents(subPropertyOfGraph, property);
subProperties.removeAll(propertiesWithRange);
propertiesWithRange.addAll(subProperties);
rangeViaSuperProperty.addAll(subProperties);
}
}
if (!propertiesWithDomain.isEmpty()) {
domainByTypePartial.put(domainRangeType, propertiesWithDomain);
}
if (!propertiesWithRange.isEmpty()) {
rangeByTypePartial.put(domainRangeType, propertiesWithRange);
}
}
// Once all properties have been found for each domain/range class, extend to superclasses:
// make sure that the consequent of a domain/range inference goes on to apply any more
// general classes as well.
for (final URI subtype : domainRangeTypeSet) {
final Set<URI> supertypes = getSuperClasses(subtype);
final Set<URI> propertiesWithDomain = domainByTypePartial.getOrDefault(subtype, new HashSet<>());
final Set<URI> propertiesWithRange = rangeByTypePartial.getOrDefault(subtype, new HashSet<>());
for (final URI supertype : supertypes) {
// For a property p and its domain c: all of c's superclasses are also domains of p.
if (!propertiesWithDomain.isEmpty() && !domainByTypePartial.containsKey(supertype)) {
domainByTypePartial.put(supertype, new HashSet<>());
}
for (final URI property : propertiesWithDomain) {
domainByTypePartial.get(supertype).add(property);
}
// For a property p and its range c: all of c's superclasses are also ranges of p.
if (!propertiesWithRange.isEmpty() && !rangeByTypePartial.containsKey(supertype)) {
rangeByTypePartial.put(supertype, new HashSet<>());
}
for (final URI property : propertiesWithRange) {
rangeByTypePartial.get(supertype).add(property);
}
}
}
domainByType = domainByTypePartial;
rangeByType = rangeByTypePartial;
}
private void refreshPropertyRestrictions() throws QueryEvaluationException {
// Get a set of all property restrictions of any type
final CloseableIteration<Statement, QueryEvaluationException> iter = RyaDAOHelper.query(ryaDAO, null, OWL.ONPROPERTY, null, conf);
final Map<Resource, URI> restrictions = new HashMap<>();
try {
while (iter.hasNext()) {
final Statement st = iter.next();
restrictions.put(st.getSubject(), (URI) st.getObject());
}
} finally {
if (iter != null) {
iter.close();
}
}
// Query for specific types of restriction and add their details to the schema
refreshHasValueRestrictions(restrictions);
refreshAllValuesFromRestrictions(restrictions);
}
private void refreshHasValueRestrictions(final Map<Resource, URI> restrictions) throws QueryEvaluationException {
hasValueByType = new HashMap<>();
hasValueByProperty = new HashMap<>();
final CloseableIteration<Statement, QueryEvaluationException> iter = RyaDAOHelper.query(ryaDAO, null, OWL.HASVALUE, null, conf);
try {
while (iter.hasNext()) {
final Statement st = iter.next();
final Resource restrictionClass = st.getSubject();
if (restrictions.containsKey(restrictionClass)) {
final URI property = restrictions.get(restrictionClass);
final Value value = st.getObject();
if (!hasValueByType.containsKey(restrictionClass)) {
hasValueByType.put(restrictionClass, new HashMap<>());
}
if (!hasValueByProperty.containsKey(property)) {
hasValueByProperty.put(property, new HashMap<>());
}
hasValueByType.get(restrictionClass).put(property, value);
hasValueByProperty.get(property).put(restrictionClass, value);
}
}
} finally {
if (iter != null) {
iter.close();
}
}
}
private void refreshAllValuesFromRestrictions(final Map<Resource, URI> restrictions) throws QueryEvaluationException {
allValuesFromByValueType = new HashMap<>();
final CloseableIteration<Statement, QueryEvaluationException> iter = RyaDAOHelper.query(ryaDAO, null, OWL.ALLVALUESFROM, null, conf);
try {
while (iter.hasNext()) {
final Statement st = iter.next();
if (restrictions.containsKey(st.getSubject()) && st.getObject() instanceof URI) {
final URI property = restrictions.get(st.getSubject());
final URI valueClass = (URI) st.getObject();
// Should also be triggered by subclasses of the property restriction
final Set<Resource> restrictionClasses = new HashSet<>();
restrictionClasses.add(st.getSubject());
if (st.getSubject() instanceof URI) {
restrictionClasses.addAll(getSubClasses((URI) st.getSubject()));
}
for (final Resource restrictionClass : restrictionClasses) {
if (!allValuesFromByValueType.containsKey(valueClass)) {
allValuesFromByValueType.put(valueClass, new HashMap<>());
}
allValuesFromByValueType.get(valueClass).put(restrictionClass, property);
}
}
}
} finally {
if (iter != null) {
iter.close();
}
}
}
private void refreshIntersectionOf() throws QueryEvaluationException {
final Map<Resource, List<Set<Resource>>> intersectionsProp = new HashMap<>();
// First query for all the owl:intersectionOf's.
// If we have the following intersectionOf:
// :A owl:intersectionOf[:B, :C]
// It will be represented by triples following a pattern similar to:
// <:A> owl:intersectionOf _:bnode1 .
// _:bnode1 rdf:first <:B> .
// _:bnode1 rdf:rest _:bnode2 .
// _:bnode2 rdf:first <:C> .
// _:bnode2 rdf:rest rdf:nil .
ryaDaoQueryWrapper.queryAll(null, OWL.INTERSECTIONOF, null, new RDFHandlerBase() {
@Override
public void handleStatement(final Statement statement) throws RDFHandlerException {
final Resource type = statement.getSubject();
// head will point to a type that is part of the intersection.
final URI head = (URI) statement.getObject();
if (!intersectionsProp.containsKey(type)) {
intersectionsProp.put(type, new ArrayList<Set<Resource>>());
}
// head should point to a list of items that forms the
// intersection.
try {
final Set<Resource> intersection = new LinkedHashSet<>(getList(head));
if (!intersection.isEmpty()) {
// Add this intersection for this type. There may be more
// intersections for this type so each type has a list of
// intersection sets.
intersectionsProp.get(type).add(intersection);
}
} catch (final QueryEvaluationException e) {
throw new RDFHandlerException("Error getting intersection list.", e);
}
}
});
intersections.clear();
for (final Entry<Resource, List<Set<Resource>>> entry : intersectionsProp.entrySet()) {
final Resource type = entry.getKey();
final List<Set<Resource>> intersectionList = entry.getValue();
final Set<Resource> otherTypes = new HashSet<>();
// Combine all of a type's intersections together.
for (final Set<Resource> intersection : intersectionList) {
otherTypes.addAll(intersection);
}
for (final Resource other : otherTypes) {
// :A intersectionOf[:B, :C] implies that
// :A subclassOf :B
// :A subclassOf :C
// So add each type that's part of the intersection to the
// subClassOf graph.
addSubClassOf(type, other);
for (final Set<Resource> intersection : intersectionList) {
if (!intersection.contains(other)) {
addIntersection(intersection, other);
}
}
}
for (final Set<Resource> intersection : intersectionList) {
addIntersection(intersection, type);
}
}
for (final Entry<Resource, List<Set<Resource>>> entry : intersectionsProp.entrySet()) {
final Resource type = entry.getKey();
final List<Set<Resource>> intersectionList = entry.getValue();
final Set<URI> superClasses = getSuperClasses((URI) type);
for (final URI superClass : superClasses) {
// Add intersections to super classes if applicable.
// IF:
// :A intersectionOf[:B, :C]
// AND
// :A subclassOf :D
// Then we can infer:
// intersectionOf[:B, :C] subclassOf :D
for (final Set<Resource> intersection : intersectionList) {
addIntersection(intersection, superClass);
}
}
// Check if other keys have any of the same intersections and infer
// the same subclass logic to them that we know from the current
// type. Propagating up through all the superclasses.
for (final Set<Resource> intersection : intersectionList) {
final Set<Resource> otherKeys = Sets.newHashSet(intersectionsProp.keySet());
otherKeys.remove(type);
for (final Resource otherKey : otherKeys) {
if (intersectionsProp.get(otherKey).contains(intersection)) {
addSubClassOf(otherKey, type);
addSubClassOf(type, otherKey);
}
}
}
}
}
/**
* Queries for all items that are in a list of the form:
* <pre>
* <:A> ?x _:bnode1 .
* _:bnode1 rdf:first <:B> .
* _:bnode1 rdf:rest _:bnode2 .
* _:bnode2 rdf:first <:C> .
* _:bnode2 rdf:rest rdf:nil .
* </pre>
* Where {@code :_bnode1} represents the first item in the list and
* {@code ?x} is some restriction on {@code <:A>}. This will return the
* list of resources, {@code [<:B>, <:C>]}.
* @param firstItem the first item in the list.
* @return the {@link List} of {@link Resource}s.
* @throws QueryEvaluationException
*/
private List<Resource> getList(final URI firstItem) throws QueryEvaluationException {
URI head = firstItem;
final List<Resource> list = new ArrayList<>();
// Go through and find all bnodes that are part of the defined list.
while (!RDF.NIL.equals(head)) {
// rdf.first will point to a type item that is in the list.
ryaDaoQueryWrapper.queryFirst(head, RDF.FIRST, null, new RDFHandlerBase() {
@Override
public void handleStatement(final Statement statement) throws RDFHandlerException {
// The object found in the query represents a type
// that should be included in the list.
final URI object = (URI) statement.getObject();
list.add(object);
}
});
final MutableObject<URI> headHolder = new MutableObject<>();
// rdf.rest will point to the next bnode that's part of the list.
ryaDaoQueryWrapper.queryFirst(head, RDF.REST, null, new RDFHandlerBase() {
@Override
public void handleStatement(final Statement statement) throws RDFHandlerException {
// This object is the next bnode head to look for.
final URI object = (URI) statement.getObject();
headHolder.setValue(object);
}
});
// As long as we get a new head there are more bnodes that are part
// of the list. Keep going until we reach rdf.nil.
if (headHolder.getValue() != null) {
head = headHolder.getValue();
} else {
head = RDF.NIL;
}
}
return list;
}
private void addSubClassOf(final Resource s, final Resource o) {
final Statement statement = new StatementImpl(s, RDFS.SUBCLASSOF, o);
final String edgeName = RDFS.SUBCLASSOF.stringValue();
addStatementEdge(subClassOfGraph, edgeName, statement);
}
private void addIntersection(final Set<Resource> intersection, final Resource type) {
if (type != null && intersection != null && !intersection.isEmpty()) {
List<Set<Resource>> intersectionList = intersections.get(type);
if (intersectionList == null) {
intersectionList = new ArrayList<>();
}
if (!intersectionList.contains(intersection)) {
intersectionList.add(intersection);
}
intersections.put(type, intersectionList);
}
}
private static Vertex getVertex(final Graph graph, final Object id) {
final Iterator<Vertex> it = graph.vertices(id.toString());
if (it.hasNext()) {
return it.next();
}
return null;
}
private static void addStatementEdge(final Graph graph, final String edgeName, final Statement st) {
final Resource subj = st.getSubject();
Vertex a = getVertex(graph, subj);
if (a == null) {
a = graph.addVertex(T.id, subj.toString());
a.property(URI_PROP, subj);
}
final Value obj = st.getObject();
Vertex b = getVertex(graph, obj);
if (b == null) {
b = graph.addVertex(T.id, obj.toString());
b.property(URI_PROP, obj);
}
a.addEdge(edgeName, b);
}
/**
* Returns all super class types of the specified type based on the
* internal subclass graph.
* @param type the type {@link URI} to find super classes for.
* @return the {@link Set} of {@link URI} types that are super classes types
* of the specified {@code type}. Returns an empty set if nothing was found.
*/
public Set<URI> getSuperClasses(final URI type) {
return findChildren(subClassOfGraph, type);
}
/**
* Returns all sub class types of the specified type based on the
* internal subclass graph.
* @param type the type {@link URI} to find sub classes for.
* @return the {@link Set} of {@link URI} types that are sub classes types
* of the specified {@code type}. Returns an empty set if nothing was found.
*/
public Set<URI> getSubClasses(final URI type) {
return findParents(subClassOfGraph, type);
}
public static Set<URI> findParents(final Graph graph, final URI vertexId) {
return findParents(graph, vertexId, true);
}
public static Set<URI> findParents(final Graph graph, final URI vertexId, final boolean isRecursive) {
return findConnected(graph, vertexId, Direction.IN, isRecursive);
}
public static Set<URI> findChildren(final Graph graph, final URI vertexId) {
return findChildren(graph, vertexId, true);
}
public static Set<URI> findChildren(final Graph graph, final URI vertexId, final boolean isRecursive) {
return findConnected(graph, vertexId, Direction.OUT, isRecursive);
}
private static Set<URI> findConnected(final Graph graph, final URI vertexId, final Direction traversal, final boolean isRecursive) {
final Set<URI> connected = new HashSet<>();
if (graph == null) {
return connected;
}
final Vertex v = getVertex(graph, vertexId);
if (v == null) {
return connected;
}
addConnected(v, connected, traversal, isRecursive);
return connected;
}
private static void addConnected(final Vertex v, final Set<URI> connected, final Direction traversal, final boolean isRecursive) {
v.edges(traversal).forEachRemaining(edge -> {
final Vertex ov = edge.vertices(traversal.opposite()).next();
final Object o = ov.property(URI_PROP).value();
if (o != null && o instanceof URI) {
final boolean contains = connected.contains(o);
if (!contains) {
connected.add((URI) o);
if (isRecursive) {
addConnected(ov, connected, traversal, isRecursive);
}
}
}
});
}
public boolean isSymmetricProperty(final URI prop) {
return (symmetricPropertySet != null) && symmetricPropertySet.contains(prop);
}
public URI findInverseOf(final URI prop) {
return (inverseOfMap != null) ? inverseOfMap.get(prop) : (null);
}
public boolean isTransitiveProperty(final URI prop) {
return (transitivePropertySet != null) && transitivePropertySet.contains(prop);
}
/**
* TODO: This chaining can be slow at query execution. the other option is to perform this in the query itself, but that will be constrained to how many levels we decide to go
*/
public Set<Statement> findTransitiveProperty(final Resource subj, final URI prop, final Value obj, final Resource... contxts) throws InferenceEngineException {
if (transitivePropertySet.contains(prop)) {
final Set<Statement> sts = new HashSet<>();
final boolean goUp = subj == null;
chainTransitiveProperty(subj, prop, obj, (goUp) ? (obj) : (subj), sts, goUp, contxts);
return sts;
} else {
return null;
}
}
/**
* TODO: This chaining can be slow at query execution. the other option is to perform this in the query itself, but that will be constrained to how many levels we decide to go
*/
public Set<Resource> findSameAs(final Resource value, final Resource... contxts) throws InferenceEngineException{
final Set<Resource> sameAs = new HashSet<>();
sameAs.add(value);
findSameAsChaining(value, sameAs, contxts);
return sameAs;
}
public CloseableIteration<Statement, QueryEvaluationException> queryDao(final Resource subject, final URI predicate, final Value object, final Resource... contexts) throws QueryEvaluationException {
return RyaDAOHelper.query(ryaDAO, subject, predicate, object, conf, contexts);
}
/**
* TODO: This chaining can be slow at query execution. the other option is to perform this in the query itself, but that will be constrained to how many levels we decide to go
*/
public void findSameAsChaining(final Resource subj, final Set<Resource> currentSameAs, final Resource[] contxts) throws InferenceEngineException{
CloseableIteration<Statement, QueryEvaluationException> subjIter = null;
CloseableIteration<Statement, QueryEvaluationException> objIter = null;
try {
subjIter = queryDao(subj, OWL.SAMEAS, null, contxts);
while (subjIter.hasNext()){
final Statement st = subjIter.next();
if (!currentSameAs.contains(st.getObject())){
final Resource castedObj = (Resource) st.getObject();
currentSameAs.add(castedObj);
findSameAsChaining(castedObj, currentSameAs, contxts);
}
}
objIter = queryDao(null, OWL.SAMEAS, subj, contxts);
while (objIter.hasNext()){
final Statement st = objIter.next();
if (!currentSameAs.contains(st.getSubject())){
final Resource sameAsSubj = st.getSubject();
currentSameAs.add(sameAsSubj);
findSameAsChaining(sameAsSubj, currentSameAs, contxts);
}
}
} catch (final QueryEvaluationException e) {
throw new InferenceEngineException(e);
} finally {
if (subjIter != null) {
try {
subjIter.close();
} catch (final QueryEvaluationException e) {
throw new InferenceEngineException("Error while closing \"same as chaining\" statement subject iterator.", e);
}