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
|
package rsacomb
/* Java imports */
import java.util.HashMap
import java.util.stream.{Collectors, Stream}
import org.semanticweb.owlapi.model.{OWLOntology, OWLAxiom}
import org.semanticweb.owlapi.model.{
OWLClass,
OWLObjectProperty,
OWLSubObjectPropertyOfAxiom,
OWLObjectPropertyExpression,
OWLObjectSomeValuesFrom,
OWLSubClassOfAxiom
}
import org.semanticweb.owlapi.model.parameters.Imports
import org.semanticweb.owlapi.reasoner.structural.StructuralReasonerFactory
import org.semanticweb.owlapi.model.{IRI => OWLIRI}
import uk.ac.manchester.cs.owl.owlapi.OWLObjectPropertyImpl
import tech.oxfordsemantic.jrdfox.client.{UpdateType, DataStoreConnection}
import tech.oxfordsemantic.jrdfox.logic.datalog.{
Rule,
TupleTableAtom,
Negation,
BodyFormula
}
import tech.oxfordsemantic.jrdfox.logic.expression.{
Term,
Variable,
IRI,
Resource
}
import tech.oxfordsemantic.jrdfox.logic.sparql.statement.SelectQuery
/* Scala imports */
import scala.collection.JavaConverters._
import scala.collection.mutable.Set
import scalax.collection.immutable.Graph
import scalax.collection.GraphEdge.UnDiEdge
/* Debug only */
import org.semanticweb.owlapi.dlsyntax.renderer.DLSyntaxObjectRenderer
import tech.oxfordsemantic.jrdfox.logic._
import org.semanticweb.owlapi.model.OWLObjectInverseOf
import suffix.{Empty, Forward, Backward, Inverse}
object RSAOntology {}
/* Wrapper trait for the implicit class `RSAOntology`.
*/
trait RSAOntology {
/* Implements additional features to reason about RSA ontologies
* on top of `OWLOntology` from the OWLAPI.
*/
implicit class RSAOntology(ontology: OWLOntology) extends RSAAxiom {
// Gather TBox/RBox/ABox from original ontology
lazy val tbox: List[OWLAxiom] =
ontology
.tboxAxioms(Imports.INCLUDED)
.collect(Collectors.toList())
.asScala
.toList
lazy val rbox: List[OWLAxiom] =
ontology
.rboxAxioms(Imports.INCLUDED)
.collect(Collectors.toList())
.asScala
.toList
lazy val abox: List[OWLAxiom] =
ontology
.aboxAxioms(Imports.INCLUDED)
.collect(Collectors.toList())
.asScala
.toList
lazy val axioms: List[OWLAxiom] = abox ++ tbox ++ rbox
/* Retrieve individuals in the original ontology
*/
lazy val individuals: List[IRI] =
ontology
.getIndividualsInSignature()
.asScala
.map(_.getIRI)
.map(RDFoxUtil.owlapi2rdfox)
.toList
lazy val concepts: List[OWLClass] =
ontology.getClassesInSignature().asScala.toList
lazy val roles: List[OWLObjectPropertyExpression] =
axioms
.flatMap(_.objectPropertyExpressionsInSignature)
.distinct
// OWLAPI reasoner for same easier tasks
private val reasoner =
(new StructuralReasonerFactory()).createReasoner(ontology)
/* Steps for RSA check
* 1) convert ontology axioms into LP rules
* 2) call RDFox on the onto and compute materialization
* 3) build graph from E(x,y) facts
* 4) check if the graph is tree-like
* ideally this annotates the graph with info about the reasons
* why the ontology might not be RSA. This could help a second
* step of approximation of an Horn-ALCHOIQ to RSA
*/
lazy val isRSA: Boolean = {
val unsafe = this.unsafeRoles
/* DEBUG: print rules in DL syntax and unsafe roles */
//val renderer = new DLSyntaxObjectRenderer()
//println("\nDL rules:")
//axioms.foreach(x => println(renderer.render(x)))
//println("\nUnsafe roles:")
//println(unsafe)
/* Ontology convertion into LP rules */
val datalog = for {
axiom <- axioms
visitor = new RDFoxAxiomConverter(
RSA.getFreshVariable(),
unsafe,
SkolemStrategy.ConstantRSA(axiom.toString),
Empty
)
rule <- axiom.accept(visitor)
} yield rule
/* DEBUG: print datalog rules */
//println("\nDatalog roles:")
//datalog.foreach(println)
// Open connection with RDFox
val (server, data) = RDFoxUtil.openConnection("RSACheck")
// Add Data (hardcoded for now)
data.importData(UpdateType.ADDITION, RSA.Prefixes, ":a a :A .")
/* Add built-in rules
*/
data.importData(
UpdateType.ADDITION,
RSA.Prefixes,
"<http://127.0.0.1/E>[?X,?Y] :- <http://127.0.0.1/PE>[?X,?Y], <http://127.0.0.1/U>[?X], <http://127.0.0.1/U>[?Y] ."
)
/* Add built-in rules
*/
// data.importData(
// UpdateType.ADDITION,
// RSA.Prefixes,
// "[?entity, a, ?superClass] :- [?entity, a, ?class], [?class, rdfs:subClassOf, ?superClass] ."
// )
/* Add ontology rules
*/
data.addRules(datalog.asJava)
/* Build graph
*/
val graph = this.rsaGraph(data);
//println(graph)
// Close connection to RDFox
RDFoxUtil.closeConnection(server, data)
/* To check if the graph is tree-like we check for acyclicity in a
* undirected graph.
*
* TODO: Implement additional checks (taking into account equality)
*/
graph.isAcyclic
}
lazy val unsafeRoles: List[OWLObjectPropertyExpression] = {
/* DEBUG: print rules in DL syntax */
//val renderer = new DLSyntaxObjectRenderer()
/* Checking for (1) unsafety condition:
*
* For all roles r1 appearing in an axiom of type T5, r1 is unsafe
* if there exists a role r2 (different from top) appearing in an axiom
* of type T3 and r1 is a subproperty of the inverse of r2.
*/
val unsafe1 = for {
axiom <- tbox
if axiom.isT5
role1 <- axiom.objectPropertyExpressionsInSignature
roleSuper =
role1 +: reasoner
.superObjectProperties(role1)
.collect(Collectors.toList())
.asScala
roleSuperInv = roleSuper.map(_.getInverseProperty)
axiom <- tbox
if axiom.isT3 && !axiom.isT3top
role2 <- axiom.objectPropertyExpressionsInSignature
if roleSuperInv.contains(role2)
} yield role1
/* Checking for (2) unsafety condition:
*
* For all roles p1 appearing in an axiom of type T5, p1 is unsafe if
* there exists a role p2 appearing in an axiom of type T4 and p1 is a
* subproperty of either p2 or the inverse of p2.
*
*/
val unsafe2 = for {
axiom <- tbox
if axiom.isT5
role1 <- axiom.objectPropertyExpressionsInSignature
roleSuper =
role1 +: reasoner
.superObjectProperties(role1)
.collect(Collectors.toList())
.asScala
roleSuperInv = roleSuper.map(_.getInverseProperty)
axiom <- tbox
if axiom.isT4
role2 <- axiom.objectPropertyExpressionsInSignature
if roleSuper.contains(role2) || roleSuperInv.contains(role2)
} yield role1
(unsafe1 ++ unsafe2).toList
}
private def rsaGraph(
data: DataStoreConnection
): Graph[Resource, UnDiEdge] = {
val query = "SELECT ?X ?Y WHERE { ?X rsa:E ?Y }"
val cursor =
data.createCursor(RSA.Prefixes, query, new HashMap[String, String]());
var mul = cursor.open()
var edges: List[UnDiEdge[Resource]] = List()
while (mul > 0) {
edges = UnDiEdge(cursor.getResource(0), cursor.getResource(1)) :: edges
mul = cursor.advance()
}
Graph(edges: _*)
}
def filteringProgram(
query: SelectQuery,
nis: List[Term]
): FilteringProgram =
new FilteringProgram(query, nis)
// TODO: the following functions needs testing
def confl(
role: OWLObjectPropertyExpression
): Set[OWLObjectPropertyExpression] = {
val invSuperRoles = reasoner
.superObjectProperties(role)
.collect(Collectors.toSet())
.asScala
.addOne(role)
.map(_.getInverseProperty)
invSuperRoles
.flatMap(x =>
reasoner
.subObjectProperties(x)
.collect(Collectors.toSet())
.asScala
.addOne(x)
)
.filterNot(_.isOWLBottomObjectProperty())
.filterNot(_.getInverseProperty.isOWLTopObjectProperty())
}
def self(axiom: OWLSubClassOfAxiom): Set[Term] = {
// Assuming just one role in the signature of a T5 axiom
val role = axiom.objectPropertyExpressionsInSignature(0)
if (this.confl(role).contains(role)) {
Set(
RSA.rsa("v0_" ++ RSA.hashed(axiom)),
RSA.rsa("v1_" ++ RSA.hashed(axiom))
)
} else {
Set()
}
}
// def cycle(axiom: OWLSubClassOfAxiom): Set[Term] = {
// // Assuming just one role in the signature of a T5 axiom
// val roleR = axiom.objectPropertyExpressionsInSignature(0)
// val conflR = this.confl(roleR)
// // We just need the TBox to find
// val tbox = ontology
// .tboxAxioms(Imports.INCLUDED)
// .collect(Collectors.toSet())
// .asScala
// for {
// axiom1 <- tbox
// // TODO: is this an optimization or an error?
// if axiom1.isT5
// // We expect only one role coming out of a T5 axiom
// roleS <- axiom1.objectPropertyExpressionsInSignature
// // Triples ordering is among triples involving safe roles.
// if !unsafeRoles.contains(roleS)
// if conflR.contains(roleS)
// individual =
// if (axiom.hashCode < axiom1.hashCode) {
// RSA.rsa("v0_" ++ axiom1.hashCode.toString())
// } else {
// RSA.rsa("v1_" ++ axiom1.hashCode.toString())
// }
// } yield individual
// }
def cycle(axiom: OWLSubClassOfAxiom): Set[Term] = {
// TODO: we can actually use `toTriple` from `RSAAxiom`
val classes =
axiom.classesInSignature.collect(Collectors.toList()).asScala
val classA = classes(0)
val roleR = axiom
.objectPropertyExpressionsInSignature(0)
.asInstanceOf[OWLObjectProperty]
val classB = classes(1)
cycle_aux(classA, roleR, classB)
}
def cycle_aux(
classA: OWLClass,
roleR: OWLObjectProperty,
classB: OWLClass
): Set[Term] = {
val conflR = this.confl(roleR)
val classes = ontology
.classesInSignature(Imports.INCLUDED)
.collect(Collectors.toSet())
.asScala
for {
classD <- classes
roleS <- conflR
classC <- classes
// Keeping this check for now
if !unsafeRoles.contains(roleS)
tripleARB = RSA.hashed(classA, roleR, classB)
tripleDSC = RSA.hashed(classD, roleS, classC)
individual =
if (tripleARB > tripleDSC) {
RSA.rsa("v1_" ++ tripleDSC)
} else {
// Note that this is also the case for
// `tripleARB == tripleDSC`
RSA.rsa("v0_" ++ tripleDSC)
}
} yield individual
}
def unfold(axiom: OWLSubClassOfAxiom): Set[Term] =
this.self(axiom) | this.cycle(axiom)
object canonicalModel {
import RDFoxUtil._
val named: List[Rule] =
individuals.map(a =>
Rule.create(
TupleTableAtom.rdf(a, IRI.RDF_TYPE, RSA.rsa("NAMED"))
)
)
val rolesAdditionalRules: List[Rule] = {
// Given a role (predicate) compute additional logic rules
def additional(pred: String): Seq[Rule] = {
val varX = Variable.create("X")
val varY = Variable.create("Y")
List(
Rule.create(
TupleTableAtom.rdf(varX, IRI.create(pred), varY),
TupleTableAtom
.rdf(
varX,
IRI.create(pred :: Forward),
varY
)
),
Rule.create(
TupleTableAtom.rdf(varX, IRI.create(pred), varY),
TupleTableAtom
.rdf(
varX,
IRI.create(pred :: Backward),
varY
)
),
Rule.create(
TupleTableAtom.rdf(varX, IRI.create(pred ++ "_inv"), varY),
TupleTableAtom
.rdf(
varX,
IRI.create(pred :: Forward + Inverse),
varY
)
),
Rule.create(
TupleTableAtom.rdf(varX, IRI.create(pred ++ "_inv"), varY),
TupleTableAtom
.rdf(
varX,
IRI.create(pred :: Backward + Inverse),
varY
)
),
Rule.create(
TupleTableAtom.rdf(
varY,
IRI.create(pred :: Backward + Inverse),
varX
),
TupleTableAtom
.rdf(
varX,
IRI.create(pred :: Forward),
varY
)
),
Rule.create(
TupleTableAtom.rdf(
varY,
IRI.create(pred :: Forward + Inverse),
varX
),
TupleTableAtom.rdf(
varX,
IRI.create(pred :: Backward),
varY
)
),
Rule.create(
TupleTableAtom.rdf(
varY,
IRI.create(pred :: Backward),
varX
),
TupleTableAtom
.rdf(
varX,
IRI.create(pred :: Forward + Inverse),
varY
)
),
Rule.create(
TupleTableAtom.rdf(
varY,
IRI.create(pred :: Forward),
varX
),
TupleTableAtom.rdf(
varX,
IRI.create(pred :: Backward + Inverse),
varY
)
)
)
}
// Compute additional rules per role
axioms
.flatMap(
_.objectPropertiesInSignature.collect(Collectors.toSet()).asScala
)
.distinct
.map(_.getIRI.getIRIString)
.flatMap(additional)
}
private lazy val topAxioms: List[Rule] =
concepts.map(c => {
val x = Variable.create("X")
Rule.create(
TupleTableAtom.rdf(x, IRI.RDF_TYPE, IRI.THING),
TupleTableAtom.rdf(x, IRI.RDF_TYPE, c.getIRI)
)
}) ++
roles.map(r => {
val x = Variable.create("X")
val y = Variable.create("Y")
val iri: IRI = r match {
case x: OWLObjectProperty => x.getIRI
case x: OWLObjectInverseOf =>
IRI.create(x.getNamedProperty.getIRI.getIRIString ++ "_inv")
case x => x.getNamedProperty.getIRI
}
Rule.create(
List(
TupleTableAtom.rdf(x, IRI.RDF_TYPE, IRI.THING),
TupleTableAtom.rdf(y, IRI.RDF_TYPE, IRI.THING)
).asJava,
List[BodyFormula](TupleTableAtom.rdf(x, iri, y)).asJava
)
})
private val equalityAxioms: List[Rule] = {
val x = Variable.create("X")
val y = Variable.create("Y")
val z = Variable.create("Z")
List(
Rule.create(
TupleTableAtom.rdf(x, RSA.EquivTo, x),
TupleTableAtom.rdf(x, IRI.RDF_TYPE, IRI.THING)
),
Rule.create(
TupleTableAtom.rdf(y, RSA.EquivTo, x),
TupleTableAtom.rdf(x, RSA.EquivTo, y)
),
Rule.create(
TupleTableAtom.rdf(x, RSA.EquivTo, z),
TupleTableAtom.rdf(x, RSA.EquivTo, y),
TupleTableAtom.rdf(y, RSA.EquivTo, z)
)
)
}
val rules: List[Rule] = {
// Compute rules from ontology axioms
val rules = axioms.flatMap(_.accept(this.ProgramGenerator))
// Return full set of rules
rules ++ rolesAdditionalRules ++ topAxioms ++ equalityAxioms ++ named
}
object ProgramGenerator
extends RDFoxAxiomConverter(
Variable.create("X"),
unsafeRoles,
SkolemStrategy.None,
Empty
) {
private def rules1(axiom: OWLSubClassOfAxiom): List[Rule] = {
val unfold = ontology.unfold(axiom).toList
// Fresh Variables
val v0 = RSA.rsa("v0_" ++ RSA.hashed(axiom))
val varX = Variable.create("X")
// Predicates
val atomA: TupleTableAtom = {
val cls = axiom.getSubClass.asInstanceOf[OWLClass].getIRI
TupleTableAtom.rdf(varX, IRI.RDF_TYPE, cls)
}
def in(t: Term): TupleTableAtom = {
TupleTableAtom.rdf(
t,
RSA.rsa("IN"),
RSA.rsa(unfold.hashCode.toString)
)
}
def notIn(t: Term): Negation = Negation.create(in(t))
val roleRf: TupleTableAtom = {
val visitor =
new RDFoxPropertyExprConverter(varX, v0, Forward)
axiom.getSuperClass
.asInstanceOf[OWLObjectSomeValuesFrom]
.getProperty
.accept(visitor)
.head
}
val atomB: TupleTableAtom = {
val cls = axiom.getSuperClass
.asInstanceOf[OWLObjectSomeValuesFrom]
.getFiller
.asInstanceOf[OWLClass]
.getIRI
TupleTableAtom.rdf(v0, IRI.RDF_TYPE, cls)
}
// TODO: To be consistent with the specifics of the visitor we are
// returning facts as `Rule`s with true body. While this is correct
// there is an easier way to import facts into RDFox. Are we able to
// do that?
val facts = unfold.map(x => Rule.create(in(x)))
val rules = List(
Rule.create(roleRf, atomA, notIn(varX)),
Rule.create(atomB, atomA, notIn(varX))
)
facts ++ rules
}
private def rules2(axiom: OWLSubClassOfAxiom): List[Rule] = {
val roleR =
axiom.getSuperClass
.asInstanceOf[OWLObjectSomeValuesFrom]
.getProperty
if (ontology.confl(roleR) contains roleR) {
// Fresh Variables
val v0 = RSA.rsa("v0_" ++ RSA.hashed(axiom))
val v1 = RSA.rsa("v1_" ++ RSA.hashed(axiom))
val v2 = RSA.rsa("v2_" ++ RSA.hashed(axiom))
// Predicates
def atomA(t: Term): TupleTableAtom = {
val cls = axiom.getSubClass.asInstanceOf[OWLClass].getIRI
TupleTableAtom.rdf(t, IRI.RDF_TYPE, cls)
}
def roleRf(t1: Term, t2: Term): TupleTableAtom = {
val visitor =
new RDFoxPropertyExprConverter(t1, t2, Forward)
roleR.accept(visitor).head
}
def atomB(t: Term): TupleTableAtom = {
val cls = axiom.getSuperClass
.asInstanceOf[OWLObjectSomeValuesFrom]
.getFiller
.asInstanceOf[OWLClass]
.getIRI
TupleTableAtom.rdf(t, IRI.RDF_TYPE, cls)
}
//Rules
List(
Rule.create(roleRf(v0, v1), atomA(v0)),
Rule.create(atomB(v1), atomA(v0)),
Rule.create(roleRf(v1, v2), atomA(v1)),
Rule.create(atomB(v2), atomA(v1))
)
} else {
List()
}
}
private def rules3(axiom: OWLSubClassOfAxiom): List[Rule] = {
val cycle = ontology.cycle(axiom).toList
val roleR =
axiom.getSuperClass
.asInstanceOf[OWLObjectSomeValuesFrom]
.getProperty
// Fresh Variables
val v1 = RSA.rsa("v1_" ++ RSA.hashed(axiom))
// Predicates
def atomA(t: Term): TupleTableAtom = {
val cls = axiom.getSubClass.asInstanceOf[OWLClass].getIRI
TupleTableAtom.rdf(t, IRI.RDF_TYPE, cls)
}
def roleRf(t: Term): TupleTableAtom = {
val visitor =
new RDFoxPropertyExprConverter(t, v1, Forward)
roleR.accept(visitor).head
}
val atomB: TupleTableAtom = {
val cls = axiom.getSuperClass
.asInstanceOf[OWLObjectSomeValuesFrom]
.getFiller
.asInstanceOf[OWLClass]
.getIRI
TupleTableAtom.rdf(v1, IRI.RDF_TYPE, cls)
}
cycle.flatMap { x =>
List(
Rule.create(roleRf(x), atomA(x)),
Rule.create(atomB, atomA(x))
)
}
}
override def visit(axiom: OWLSubClassOfAxiom): List[Rule] = {
if (axiom.isT5) {
// TODO: get role in T5 axiom
// Assuming one role here
val role = axiom.objectPropertyExpressionsInSignature(0)
if (ontology.unsafeRoles.contains(role)) {
val visitor =
new RDFoxAxiomConverter(
Variable.create("X"),
ontology.unsafeRoles,
SkolemStrategy.Standard(axiom.toString),
Forward
)
axiom.accept(visitor)
} else {
rules1(axiom) ++ rules2(axiom) ++ rules3(axiom)
}
} else {
// Fallback to standard OWL to LP translation
super.visit(axiom)
}
}
override def visit(axiom: OWLSubObjectPropertyOfAxiom): List[Rule] = {
val varX = Variable.create("X")
val varY = Variable.create("Y")
val visitorF = new RDFoxAxiomConverter(
Variable.create("X"),
ontology.unsafeRoles,
SkolemStrategy.None,
Forward
)
val visitorB = new RDFoxAxiomConverter(
Variable.create("X"),
ontology.unsafeRoles,
SkolemStrategy.None,
Backward
)
axiom.accept(visitorB) ++ axiom.accept(visitorF)
}
}
}
} // implicit class RSAOntology
} // trait RSAOntology
|