Debian Codegraph @

FaCT++.Python/pyfactxx/coras/parser.py

raw symbols SCIP
1 #
2 # Coras - OWL reasoning system
3 #
4 # Copyright (C) 2018 by Artur Wroblewski <[email protected]>
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 #
19
20 """
21 OWL parsers to load data from RDFLib graph to FaCT++ reasoner.
22 """
23
24 import os
25 import itertools
26 import logging
27 from collections import namedtuple
28 from functools import partial, singledispatch
29
30 import rdflib
31 from rdflib.namespace import RDF, RDFS, OWL
32
33 from . import debug
34
35 logger = logging.getLogger(__name__)
36
37 CLASS_TYPE = {RDFS.Class, OWL.Class}
38
39 QUERY_CLASS = [
40 (None, RDF.type, OWL.Class),
41 (None, RDF.type, RDFS.Class),
42 (None, RDF.type, OWL.Restriction),
43 (None, RDF.type, OWL.AllDisjointClasses),
44 (None, OWL.distinctMembers, None),
45 ]
46
47 # instances of special classes
48 QUERY_INSTANCES = [
49 (None, RDF.type, OWL.Thing),
50 (None, RDF.type, OWL.NamedIndividual),
51 ]
52
53 QUERY_OBJ_PROPERTY = [
54 (None, RDF.type, OWL.ObjectProperty),
55 (None, RDF.type, OWL.InverseFunctionalProperty),
56 (None, RDF.type, OWL.SymmetricProperty),
57 (None, RDF.type, OWL.TransitiveProperty),
58 ]
59
60 QUERY_AXIOM = [
61 (None, RDF.type, OWL.NegativePropertyAssertion),
62 ]
63
64 QUERY_DATA_PROPERTY = (None, RDF.type, OWL.DatatypeProperty)
65
66 Meta = namedtuple('Meta', ['attr', 'type', 'relation'])
67 MetaAttrQuery = namedtuple('MetaAttrQuery', ['pred', 'obj'])
68
69 flatten = itertools.chain.from_iterable
70
71 @debug.register
72 def parse(graph, reasoner):
73 parsers = create_parsers(graph, reasoner)
74 for q, ctor, meta in parsers:
75 items = [s for s, p, o in find_triples(q, graph)]
76 parse_items(graph, items, ctor, meta)
77
78 data_properties = set()
79 for s, p, o in find_triples((None, None, None), graph):
80 if isinstance(o, rdflib.Literal):
81 data_properties.add(p)
82
83 parse_items(graph, data_properties, parsers[3][1], parsers[3][2])
84
85 def data_value(graph, reasoner, individual, role, literal):
86 for cls in {OWL.Class, RDFS.Class, OWL.Restriction, OWL.AllDisjointClasses, RDF.Property, OWL.ObjectProperty, OWL.DatatypeProperty}:
87 if list(find_triples((individual, RDF.type, cls), graph)):
88 return
89
90 individual = reasoner.individual(individual)
91
92 if (not isinstance(literal, rdflib.Literal)):
93 reasoner.value_of_str(individual, role, '"' + str(literal) + '"')
94 elif literal.datatype == rdflib.URIRef("http://www.w3.org/2001/XMLSchema#integer"):
95 reasoner.value_of_int(individual, role, int(literal.value))
96 elif literal.datatype == rdflib.URIRef("http://www.w3.org/2001/XMLSchema#float"):
97 reasoner.value_of_float(individual, role, float(literal.value))
98 elif literal.datatype == rdflib.URIRef("http://www.w3.org/2001/XMLSchema#bool"):
99 reasoner.value_of_bool(individual, role, literal.value == 'true')
100 else:
101 reasoner.value_of_str(individual, role, literal.n3())
102
103 def set_data_range(reasoner, role, datatype):
104 if datatype != "http://www.w3.org/2000/01/rdf-schema#Literal": # ignore top generic datatype to avoid (pseudo-)inconsistency
105 reasoner.set_d_range(role, reasoner.data_type(datatype))
106
107 def set_o_sub_role(reasoner, sub_role, super_role):
108 if super_role != rdflib.URIRef('http://www.w3.org/2002/07/owl#topObjectProperty'):
109 reasoner.implies_o_roles(sub_role, reasoner.object_role(super_role))
110
111 def set_d_sub_role(reasoner, sub_role, super_role):
112 if super_role != rdflib.URIRef('http://www.w3.org/2002/07/owl#topDataProperty'):
113 reasoner.implies_d_roles(sub_role, reasoner.data_role(super_role))
114
115 def create_parsers(graph, reasoner):
116 sq = lambda pred: MetaAttrQuery(pred, None)
117 tq = lambda obj: MetaAttrQuery(RDF.type, obj)
118
119 top = reasoner.concept_top()
120 thing = reasoner.concept(OWL.Thing)
121 ni = reasoner.concept(OWL.NamedIndividual)
122 reasoner.equal_concepts(top, thing)
123 reasoner.equal_concepts(top, ni)
124
125 p_list_cls = partial(parse_list, graph, reasoner.concept)
126 p_list_obj = partial(parse_list, graph, reasoner.individual)
127 p_list_obj_prop = partial(parse_list, graph, reasoner.object_role)
128
129 p_diff_classes = partial(parse_members, reasoner.disjoint_concepts, reasoner.concept)
130 p_diff_individuals = partial(parse_members, reasoner.different_individuals, reasoner.individual)
131
132 p_union_of = partial(parse_union_of, reasoner)
133 p_one_of = partial(parse_one_of, reasoner)
134 p_intersection = partial(parse_intersection, reasoner)
135 p_distinct_members = partial(parse_distinct_members, reasoner)
136 p_complement_of = partial(parse_complement_of, reasoner)
137 p_all_different = partial(p_diff_individuals, graph, reasoner)
138 p_disjoint_cls = partial(p_diff_classes, graph, reasoner)
139 p_restriction = partial(parse_restriction, graph, reasoner)
140
141 p_property_chain = partial(parse_property_chain, reasoner)
142 p_negative_assert_obj_property = partial(parse_negative_assert_obj_property, graph, reasoner)
143
144 cls_meta = Meta(
145 (
146 (sq(RDFS.subClassOf), reasoner.implies_concepts, reasoner.concept),
147 (sq(OWL.disjointWith), reasoner.disjoint_concepts, reasoner.concept),
148 (tq(OWL.AllDisjointClasses), p_disjoint_cls, None),
149 (sq(OWL.equivalentClass), reasoner.equal_concepts, reasoner.concept),
150 (sq(OWL.unionOf), p_union_of, p_list_cls),
151 (sq(OWL.oneOf), p_one_of, p_list_obj),
152 (sq(OWL.intersectionOf), p_intersection, p_list_cls),
153 (sq(OWL.distinctMembers), p_distinct_members, p_list_obj),
154 (sq(OWL.complementOf), p_complement_of, reasoner.concept),
155 (tq(OWL.AllDifferent), p_all_different, None),
156 (tq(OWL.Restriction), p_restriction, None),
157 ),
158 (reasoner.instance_of, reasoner.individual),
159 [],
160 )
161
162 inst_meta = Meta(
163 (
164 (tq(OWL.Thing), reasoner.instance_of, reasoner.concept),
165 (tq(OWL.NamedIndividual), reasoner.instance_of, reasoner.concept),
166 ),
167 [],
168 [],
169 )
170
171 obj_p_meta = Meta(
172 (
173 (tq(OWL.FunctionalProperty), reasoner.set_o_functional, None),
174 (tq(OWL.InverseFunctionalProperty), reasoner.set_inverse_functional, None),
175 (tq(OWL.SymmetricProperty), reasoner.set_symmetric, None),
176 (tq(OWL.TransitiveProperty), reasoner.set_transitive, None),
177 (tq(OWL.IrreflexiveProperty), reasoner.set_irreflexive, None),
178 (sq(RDFS.domain), reasoner.set_o_domain, reasoner.concept),
179 (sq(RDFS.range), reasoner.set_o_range, reasoner.concept),
180 (sq(RDFS.subPropertyOf), lambda sub_role, super_role: set_o_sub_role(reasoner, sub_role, super_role), lambda x: x),
181 (sq(OWL.equivalentProperty), reasoner.equal_o_roles, reasoner.object_role),
182 (sq(OWL.inverseOf), reasoner.set_inverse_roles, reasoner.object_role),
183 (sq(OWL.propertyChainAxiom), p_property_chain, p_list_obj_prop),
184 ),
185 [],
186 (reasoner.related_to, reasoner.individual, reasoner.individual),
187 )
188
189 data_p_meta = Meta(
190 (
191 (tq(OWL.FunctionalProperty), reasoner.set_d_functional, None),
192 (sq(RDFS.domain), reasoner.set_d_domain, reasoner.concept),
193 (sq(RDFS.range), lambda role, range: set_data_range(reasoner, role, range), lambda datatype: str(datatype)),
194 (sq(RDFS.subPropertyOf), lambda sub_role, super_role: set_d_sub_role(reasoner, sub_role, super_role), lambda x: x),
195 (sq(OWL.equivalentProperty), reasoner.equal_d_roles, reasoner.data_role),
196 ),
197 [],
198 (lambda individual, role, value: data_value(graph, reasoner, individual, role, value), lambda ind: ind, lambda obj: obj),
199 )
200
201 axiom_meta = Meta(
202 [
203 (tq(OWL.NegativePropertyAssertion), p_negative_assert_obj_property, None),
204 ],
205 [],
206 [],
207 )
208
209 parsers = (
210 (QUERY_CLASS, reasoner.concept, cls_meta),
211 (QUERY_INSTANCES, reasoner.individual, inst_meta),
212 (QUERY_OBJ_PROPERTY, reasoner.object_role, obj_p_meta),
213 (QUERY_DATA_PROPERTY, reasoner.data_role, data_p_meta),
214 (QUERY_AXIOM, lambda v: v, axiom_meta),
215 )
216 return parsers
217
218 def parse_items(graph, items, ctor, meta):
219 # declare each item in the reasoner; this might seem unnecessary, but
220 # see declaration consistency in OWL 2
221 for s in items:
222 ctor(s)
223
224 for q, f_meta, f_obj in meta.attr:
225 # for each item, set its metadata in the reasoner
226 triples = query_subjects(graph, items, q.pred, q.obj)
227 parse_meta(triples, f_meta, ctor, f_obj)
228
229 if meta.type:
230 # for each item
231 #
232 # X -> (X, RDF.type, OWL.Class) -> then parse (a, RDF.type, X)
233 parse_type(graph, items, meta.type[0], meta.type[1], ctor)
234
235 if meta.relation:
236 # when each item is a predicate
237 parse_rel(graph, ctor, items, *meta.relation)
238
239 def parse_rel(graph, f_pred, predicates, f_meta, f_sub, f_obj):
240 triples = query_predicates(graph, None, predicates, None)
241 for s, p, o in triples:
242 f_meta(f_sub(s), f_pred(p), f_obj(o))
243
244 def parse_type(graph, objects, f_meta, f_sub, f_obj):
245 # to avoid classes of an ontology to be instances of RDF/OWL class
246 objects = (o for o in objects if o not in CLASS_TYPE)
247 triples = query_objects(graph, None, RDF.type, objects)
248 parse_meta(triples, f_meta, f_sub, f_obj)
249
250 def parse_meta(triples, f_meta, f_sub, f_obj):
251 if f_obj:
252 parse_meta_binary(triples, f_meta, f_sub, f_obj)
253 else:
254 parse_meta_unary(triples, f_meta, f_sub)
255
256 def parse_meta_unary(triples, f_meta, f_sub):
257 for s, _, _ in triples:
258 if __debug__:
259 logger.debug('parse: {} {}'.format(f_name(f_meta), s))
260 f_meta(f_sub(s))
261
262 def parse_meta_binary(triples, f_meta, f_sub, f_obj):
263 for s, _, o in triples:
264 if __debug__:
265 logger.debug('parse: {} {} {}'.format(f_name(f_meta), s, o))
266 f_meta(f_sub(s), f_obj(o))
267
268 def parse_list(graph, f, start):
269 return (f(v) for v in graph.items(start))
270
271 def parse_union_of(reasoner, cls, items):
272 c = reasoner.union(*items)
273 reasoner.equal_concepts(cls, c)
274
275 def parse_one_of(reasoner, cls, items):
276 c = reasoner.one_of(*items)
277 reasoner.equal_concepts(cls, c)
278
279 def parse_intersection(reasoner, cls, items):
280 c = reasoner.intersection(*items)
281 reasoner.equal_concepts(cls, c)
282
283 def parse_distinct_members(reasoner, cls, items):
284 reasoner.different_individuals(*items)
285
286 def parse_complement_of(reasoner, cls, other_cls):
287 c = reasoner.complement_of(other_cls)
288 reasoner.equal_concepts(cls, c)
289
290 def parse_members(f_axiom, f_ctor, graph, reasoner, cls):
291 from rdflib import BNode
292 fetch = partial(fetch_object, graph, BNode(cls.name))
293
294 start = fetch(OWL.members, lambda v: v)
295 if start is None:
296 start = fetch(OWL.distinctMembers, lambda v: v)
297 assert start is not None
298
299 items = parse_list(graph, f_ctor, start)
300 f_axiom(*items)
301
302 def parse_property_chain(reasoner, prop, items):
303 chain = reasoner.compose(*items)
304 reasoner.implies_o_roles(chain, prop)
305
306 def parse_restriction(graph, reasoner, cls):
307 # FIXME: pass bnode directly
308 from rdflib import BNode
309 b = BNode(cls.name)
310 prop = fetch_object(graph, b, OWL.onProperty, reasoner.object_role)
311 assert prop is not None
312
313 inv_prop = fetch_object(graph, BNode(prop.name), OWL.inverseOf, reasoner.object_role)
314
315 if inv_prop is not None:
316 reasoner.set_inverse_roles(prop, inv_prop);
317
318 parse_cardinality(graph, reasoner, cls, b, prop)
319 parse_q_cardinality(graph, reasoner, cls, b, prop)
320 parse_has_value(graph, reasoner, cls, b, prop)
321 parse_some_values_from(graph, reasoner, cls, b, prop)
322 parse_all_values_from(graph, reasoner, cls, b, prop)
323
324 def parse_negative_assert_obj_property(graph, reasoner, axiom):
325 prop = fetch_object(graph, axiom, OWL.assertionProperty, reasoner.object_role)
326 i1 = fetch_object(graph, axiom, OWL.sourceIndividual, reasoner.individual)
327 i2 = fetch_object(graph, axiom, OWL.targetIndividual, reasoner.individual)
328 assert prop is not None
329 assert i1 is not None
330 assert i2 is not None
331 reasoner.related_to_not(i1, prop, i2)
332
333 def parse_cardinality(graph, reasoner, cls, b, prop):
334
335 card = fetch_object(graph, b, OWL.cardinality, int)
336 if card:
337 if __debug__:
338 logger.debug(
339 'exact cardinality: {} {}: {}'
340 .format(cls.name, prop, card)
341 )
342 c = reasoner.o_cardinality(card, prop, reasoner.concept_top())
343 reasoner.equal_concepts(cls, c)
344
345 card = fetch_object(graph, b, OWL.minCardinality, int)
346 if card:
347 if __debug__:
348 logger.debug(
349 'min cardinality: {} {}: {}'
350 .format(cls.name, prop, card)
351 )
352 c = reasoner.min_o_cardinality(card, prop, reasoner.concept_top())
353 reasoner.equal_concepts(cls, c)
354
355 card = fetch_object(graph, b, OWL.maxCardinality, int)
356 if card:
357 if __debug__:
358 logger.debug(
359 'max cardinality: {} {}: {}'
360 .format(cls.name, prop, card)
361 )
362 c = reasoner.max_o_cardinality(card, prop, reasoner.concept_top())
363 reasoner.equal_concepts(cls, c)
364
365 def parse_q_cardinality(graph, reasoner, cls, b, prop):
366 on_cls = fetch_object(graph, b, OWL.onClass, reasoner.concept)
367
368 card = fetch_object(graph, b, OWL.qualifiedCardinality, int)
369 if card and on_cls:
370 if __debug__:
371 logger.debug(
372 'exact qual cardinality: {} {}: {} {}'
373 .format(cls.name, prop, card, on_cls.name)
374 )
375 c = reasoner.o_cardinality(card, prop, on_cls)
376 reasoner.equal_concepts(cls, c)
377
378 card = fetch_object(graph, b, OWL.minQualifiedCardinality, int)
379 if card and on_cls:
380 if __debug__:
381 logger.debug(
382 'min qual cardinality: {} {}: {} {}'
383 .format(cls.name, prop, card, on_cls.name)
384 )
385 c = reasoner.min_o_cardinality(card, prop, on_cls)
386 reasoner.equal_concepts(cls, c)
387
388 card = fetch_object(graph, b, OWL.maxQualifiedCardinality, int)
389 if card and on_cls:
390 if __debug__:
391 logger.debug(
392 'max qual cardinality: {} {}: {} {}'
393 .format(cls.name, prop, card, on_cls.name)
394 )
395 c = reasoner.max_o_cardinality(card, prop, on_cls)
396 reasoner.equal_concepts(cls, c)
397
398 def parse_has_value(graph, reasoner, cls, b, prop):
399 v_ind = fetch_object(graph, b, OWL.hasValue, lambda x: x)
400 if v_ind and isinstance(v_ind, rdflib.URIRef):
401 v_ind = reasoner.individual(v_ind)
402 if __debug__:
403 logger.debug(
404 'has value: {} {}: {}'
405 .format(cls.name, prop, v_ind.name)
406 )
407 c = reasoner.o_value(prop, v_ind)
408 reasoner.equal_concepts(cls, c)
409
410 def parse_some_values_from(graph, reasoner, cls, b, prop):
411 v_cls = fetch_object(graph, b, OWL.someValuesFrom, reasoner.concept)
412 if v_cls:
413 if __debug__:
414 logger.debug(
415 'some values from: {} {}: {}'
416 .format(cls.name, prop, v_cls.name)
417 )
418 c = reasoner.o_exists(prop, v_cls)
419 reasoner.equal_concepts(cls, c)
420
421 def parse_all_values_from(graph, reasoner, cls, b, prop):
422 v_cls = fetch_object(graph, b, OWL.allValuesFrom, reasoner.concept)
423 if v_cls:
424 if __debug__:
425 logger.debug(
426 'all values from: {} {}: {}'
427 .format(cls.name, prop, v_cls.name)
428 )
429 c = reasoner.o_forall(prop, v_cls)
430 reasoner.equal_concepts(cls, c)
431
432 def fetch_object(graph, sub, pred, f):
433 r = next(graph.objects(sub, pred), None)
434 return r if r is None else f(r)
435
436 @singledispatch
437 def query(q):
438 raise NotImplementedError('Unknown query type: {}'.format(q))
439
440 @query.register(list)
441 def _(items, graph):
442 items = flatten(query(q, graph) for q in items)
443 yield from set(items)
444
445 @query.register(tuple)
446 def _(q, graph):
447 yield from graph.triples(q)
448
449 @debug.triples
450 def find_triples(q, graph):
451 return query(q, graph)
452
453 @debug.triples
454 def query_subjects(graph, subjects, pred, obj):
455 q = [(s, pred, obj) for s in subjects]
456 return query(q, graph)
457
458 @debug.triples
459 def query_predicates(graph, sub, predicates, obj):
460 q = [(sub, p, obj) for p in predicates]
461 return query(q, graph)
462
463 @debug.triples
464 def query_objects(graph, sub, pred, objects):
465 q = [(sub, pred, o) for o in objects]
466 return query(q, graph)
467
468 def f_name(f):
469 name = getattr(f, '__qualname__', None)
470 if name is None and hasattr(f, 'func'):
471 name = getattr(f.func, '__qualname__', None)
472 if name is None:
473 name = str(f)
474 return name
475
476 # vim: sw=4:et:ai