aboutsummaryrefslogtreecommitdiff
path: root/src/main/scala/uk/ac/ox/cs/rsacomb/approximation/Lowerbound.scala
blob: 154cbd16f8e6e30b91e6c23445d2c06eecf4b3cc (plain) (blame)
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
package uk.ac.ox.cs.rsacomb.approximation

import org.semanticweb.owlapi.apibinding.OWLManager
import org.semanticweb.owlapi.model.{IRI => OWLIRI, _}

import tech.oxfordsemantic.jrdfox.logic.expression.{Resource, IRI, Literal}

import scala.collection.mutable.{Set, Map}
import scalax.collection.Graph
import scalax.collection.GraphPredef._, scalax.collection.GraphEdge._
import scalax.collection.GraphTraversal._

import uk.ac.ox.cs.rsacomb.ontology.RSAOntology
import uk.ac.ox.cs.rsacomb.ontology.Ontology
import uk.ac.ox.cs.rsacomb.util.{DataFactory, RDFoxUtil, RSA}
import uk.ac.ox.cs.rsacomb.RSAConfig

object Lowerbound {

  private val manager = OWLManager.createOWLOntologyManager()
  private val factory = manager.getOWLDataFactory()

}

/** Approximation algorithm that mantains soundness for CQ answering.
  *
  * The input OWL 2 ontology is assumed to be normalized and the output
  * ontology is guaranteed to be in RSA.
  *
  * The algorithm is performed in three steps:
  * 1. the ontology is reduced to ALCHOIQ by discarding any axiom
  *    that is not in the language;
  * 2. the ontology is further reduced to Horn-ALCHOIQ by shifting
  *    axioms with disjunction on the rhs;
  * 3. the ontology is approximated to RSA by manipulating its
  *    dependency graph.
  *
  * @see [[uk.ac.ox.cs.rsacomb.converter.Normalizer]]
  */
class Lowerbound(
  implicit fresh: DataFactory, config: RSAConfig.Config
) extends Approximation[RSAOntology] {

  /** Simplify conversion between Java and Scala collections */
  import uk.ac.ox.cs.rsacomb.implicits.JavaCollections._

  /** Simplify conversion between OWLAPI and RDFox concepts */
  import uk.ac.ox.cs.rsacomb.implicits.RDFox._

  /** Main entry point for the approximation algorithm */
  def approximate(ontology: Ontology): RSAOntology = {
    val axioms = ontology.axioms filter inALCHOIQ flatMap shift
    toRSA(new Ontology(ontology.origin, axioms, ontology.datafiles))
  }

  /** Discards all axioms outside ALCHOIQ */
  private def inALCHOIQ(axiom: OWLLogicalAxiom): Boolean =
    axiom match {
      case a: OWLSubClassOfAxiom => {
        val sub = a.getSubClass.getNNF
        val sup = a.getSuperClass.getNNF
        (sub, sup) match {
          case (sub: OWLObjectAllValuesFrom, _) => false
          case (sub: OWLDataAllValuesFrom, _)   => false
          case (_, sup: OWLDataAllValuesFrom)   => false
          case (sub: OWLObjectMinCardinality, _) if sub.getCardinality >= 2 =>
            false
          case (sub: OWLDataMinCardinality, _) if sub.getCardinality >= 2 =>
            false
          case (_, sup: OWLObjectMinCardinality) if sup.getCardinality >= 2 =>
            false
          case (_, sup: OWLDataMinCardinality) if sup.getCardinality >= 2 =>
            false
          case (sub: OWLObjectMaxCardinality, _) => false
          case (sub: OWLDataMaxCardinality, _)   => false
          case (_, sup: OWLObjectMaxCardinality) if sup.getCardinality >= 2 =>
            false
          case (_, sup: OWLDataMaxCardinality) if sup.getCardinality >= 1 =>
            false
          case (_, sup: OWLObjectOneOf) if sup.getIndividuals.length > 2 =>
            false
          case (sub: OWLObjectHasSelf, _) => false
          case (_, sup: OWLObjectHasSelf) => false
          case _                          => true
        }
      }
      case a: OWLTransitiveObjectPropertyAxiom => config('transitive).get[Boolean]
      case a: OWLReflexiveObjectPropertyAxiom  => false
      case a: OWLSubPropertyChainOfAxiom       => config('transitive).get[Boolean]
      case a: OWLAsymmetricObjectPropertyAxiom => false
      case a                                   => true
    }

  /** Shifting axioms with disjunction on the rhs.
    *
    * The process of shifting presenves soundness but completenes w.r.t.
    * CQ answering is lost.
    *
    * @example
    *
    *   A -> B1 u B2 u B3 .
    *
    *   becomes
    *
    *   A n nB1 n nB2 n nB3 -> bot .
    *   A n nB1 n nB2 -> B3 .
    *   A n nB1 n nB3 -> B2 .
    *   A n nB2 n nB3 -> B1 .
    *   nB1 n nB2 n nB3 -> nA .
    *
    *   where nA, nB1, nB2, nB3 are fresh predicates "corresponding" to
    *   the negation of A, B1, B2, B3 respectively.
    *
    * @note this method maintains the normal form of the input axiom.
    */
  private def shift(axiom: OWLLogicalAxiom): List[OWLLogicalAxiom] =
    axiom match {
      case a: OWLSubClassOfAxiom => {
        val sub = a.getSubClass.getNNF
        val sup = a.getSuperClass.getNNF
        sup match {
          case sup: OWLObjectUnionOf => {
            val body =
              sub.asConjunctSet.map((atom) => (atom, fresh.getOWLClass))
            val head =
              sup.asDisjunctSet.map((atom) => (atom, fresh.getOWLClass))

            val r1 =
              Lowerbound.factory.getOWLSubClassOfAxiom(
                Lowerbound.factory.getOWLObjectIntersectionOf(
                  (body.map(_._1) ++ head.map(_._2)): _*
                ),
                Lowerbound.factory.getOWLNothing
              )

            val r2s =
              for {
                (a, na) <- head
                hs = head.map(_._2).filterNot(_ equals na)
              } yield Lowerbound.factory.getOWLSubClassOfAxiom(
                Lowerbound.factory.getOWLObjectIntersectionOf(
                  (body.map(_._1) ++ hs): _*
                ),
                a
              )

            val r3s =
              for {
                (a, na) <- body
                bs = body.map(_._1).filterNot(_ equals a)
              } yield Lowerbound.factory.getOWLSubClassOfAxiom(
                Lowerbound.factory.getOWLObjectIntersectionOf(
                  (bs ++ head.map(_._2)): _*
                ),
                na
              )

            List(r1) ++ r2s ++ r3s
          }
          case _ => List(axiom)
        }
      }
      case _ => List(axiom)
    }

  /** Approximate a Horn-ALCHOIQ ontology to RSA
    *
    * This is done by gathering those axioms that prevent the ontology
    * dependency graph from being tree-shaped, and removing them.
    *
    * @param ontology the set of axioms to approximate.
    * @return the approximated RSA ontology
    */
  private def toRSA(ontology: Ontology): RSAOntology = {
    val factory = Lowerbound.factory
    val (graph,nodemap) = ontology.dependencyGraph
    val (server,data) = RDFoxUtil.openConnection(Ontology.DataStore)

    /* G is an oriented forest.
     * This is a custom DFS visit on the dependency graph.
     */

    /* Define node colors for the graph visit */
    sealed trait NodeColor
    case object Unvisited extends NodeColor
    case object Visited extends NodeColor
    case object ToDelete extends NodeColor

    /* Keep track of node colors during graph visit */
    var color = Map.from[Resource, NodeColor](
      graph.nodes.toOuter.map(k => (k, Unvisited))
    )

    for {
      component <- graph.componentTraverser().map(_ to Graph)
      edge <- component
        .outerEdgeTraverser(component.nodes.head)
        .withKind(BreadthFirst)
    } yield {
      val source = edge._1
      val target = edge._2
      color(source) match {
        case Unvisited | Visited => {
          color(target) match {
            case Unvisited =>
              color(source) = Visited;
              color(target) = Visited
            case Visited =>
              color(source) = ToDelete
            case ToDelete =>
              color(source) = Visited
          }
        }
        case ToDelete =>
      }
    }

    val delete: Set[OWLAxiom] =
      Set.from(color.collect {
        case (resource: IRI, ToDelete) => nodemap(resource.getIRI)
      })
    /* Equality safety: condition 1 */
    val answers2 = RDFoxUtil.submitQuery(data, s"""
      SELECT ?a ?s ?b
      WHERE {
        graph ${Ontology.RSACheck} { ?w ${RSA.CONGRUENT} ?t } .
        filter ( ?w != ?t ) .
        graph ${Ontology.RSACheck} { ?t ?r [ a ${RSA.U} ] } .
        graph ${Ontology.RBoxReasoning} {
          ?r rdfs:subPropertyOf [ owl:inverseOf ?s ] .
          ?x rdf:type owl:Restriction ;
             owl:onProperty ?s ;
             owl:maxQualifiedCardinality "1"^^xsd:nonNegativeInteger ;
             owl:onClass ?b .
          ?a rdfs:subClassOf ?b .
        } .
      }
    """).get
    // NOTE: there seems to be a bug that turns any [[Resource]] answer
    // to a query into a [[Literal]] (while here we would expect them to
    // be [[IRI]]).
    answers2.foldLeft(delete)((d, res) => {
      val a = res._2(0).asInstanceOf[Literal].getLexicalForm
      val r = res._2(1).asInstanceOf[Literal].getLexicalForm
      val b = res._2(1).asInstanceOf[Literal].getLexicalForm
      val axiom = factory.getOWLSubClassOfAxiom(
        factory.getOWLClass(a),
        factory.getOWLObjectMaxCardinality(1,
          factory.getOWLObjectProperty(r),
          factory.getOWLClass(b)
        )
      )
      d += axiom
    })
    /* Equality safety: condition 2 */
    val answers3 = RDFoxUtil.submitQuery(data, s"""
      SELECT ?r ?r1 ?s ?s1
      WHERE {
        graph ${Ontology.RSACheck} { 
          ?u ?s ?a ; a ${RSA.U} .
          ?a ?r ?u ; a ${RSA.NI} .
        } .
        graph ${Ontology.RBoxReasoning} {
          ?r rdfs:subPropertyOf ?r1 .
          ?r1 ${RSA("subPropertyOfTrans")} ?t .
          ?t owl:inverseOf ?ti .
          ?s rdfs:subPropertyOf ?s1 .
          ?s1 ${RSA("subPropertyOfTrans")} ?ti .
        }
      }
    """).get
    // NOTE: there seems to be a bug that turns any [[Resource]] answer
    // to a query into a [[Literal]] (while here we would expect them to
    // be [[IRI]]).
    println(s"Answers 3: ${answers3.length}")
    answers3.foldLeft(delete)((d, res) => {
      val r1 = res._2(0).asInstanceOf[Literal].getLexicalForm
      val r2 = res._2(1).asInstanceOf[Literal].getLexicalForm
      val s1 = res._2(2).asInstanceOf[Literal].getLexicalForm
      val s2 = res._2(3).asInstanceOf[Literal].getLexicalForm
      val axiom = if (r1 == r2) {
        factory.getOWLSubObjectPropertyOfAxiom(
          factory.getOWLObjectProperty(s1),
          factory.getOWLObjectProperty(s2),
        )
      } else {
        factory.getOWLSubObjectPropertyOfAxiom(
          factory.getOWLObjectProperty(r1),
          factory.getOWLObjectProperty(r2),
        )
      }
      d += axiom
    })

    println(s"To Delete (${delete.size}):")
    delete foreach println

    println(s"Before: ${ontology.axioms.length}")
    println(s"After: ${(ontology.axioms diff delete.toList).length}")

    /* Remove axioms from approximated ontology */
    RSAOntology(
      ontology.origin,
      ontology.axioms diff delete.toList,
      ontology.datafiles
    )




  }

  // val edges1 = Seq('A ~> 'B, 'B ~> 'C, 'C ~> 'D, 'D ~> 'H, 'H ~>
  // 'G, 'G ~> 'F, 'E ~> 'A, 'E ~> 'F, 'B ~> 'E, 'F ~> 'G, 'B ~> 'F,
  // 'C ~> 'G, 'D ~> 'C, 'H ~> 'D)
  // val edges2 = Seq('I ~> 'M, 'I ~> 'L, 'L ~> 'N, 'M ~> 'N)
  // val edges3 = Seq('P ~> 'O)
  // val graph = Graph.from(edges = edges1 ++ edges2 ++ edges3)
  //
}