Coverage for lode / profiles / owl / reader.py: 74%
717 statements
« prev ^ index » next coverage.py v7.13.0, created at 2026-11-22 15:54 +0000
« prev ^ index » next coverage.py v7.13.0, created at 2026-11-22 15:54 +0000
1"""Reader for OWL artefacts."""
3from rdflib import Graph, URIRef, Node, Literal as RDFlibLiteral, BNode
4from rdflib.namespace import RDF, RDFS, OWL, SKOS, XSD, Namespace
5from rdflib.collection import Collection as RDFLibCollection
7SWRL_NS = Namespace("http://www.w3.org/2003/11/swrl#")
9from lode.models import *
10from lode.helpers.rdf import iri_local_name
11from lode.reader.reader import Reader
12from lode.profiles.owl import checks
14import logging
15logger = logging.getLogger(__name__)
17class OwlReader(Reader):
18 """
19 OWL-specific reader.
21 Extends Reader with:
22 - Phase 1 BNode classification for OWL restrictions and truth functions
23 - OWL defaults for domain, range (owl:Thing) and Individual type
24 - Handlers for property characteristics, cardinality, truth functions,
25 quantifiers, and group axioms (AllDisjointClasses, AllDifferent, etc.)
26 - Property type inference for properties not explicitly typed in the artefact
27 """
29 # A Restriction exists only as a blank node, so an IRI is never given that class.
30 _BNODE_ONLY_CLASSES = (Restriction,)
31 _FALLBACK_CLASS = Individual
33 def phase1_classify_from_predicates(self):
34 """Classify from the predicates as the base does, then apply what only OWL knows.
36 The base has already created the entities, blank nodes included. OWL drops
37 the anonymous property expressions that sit inside a restriction, flags the
38 malformed restrictions and classifies the nodes nested in OWL lists.
39 Phase 1 runs first, so every blank node in the cache comes from the base.
40 """
41 super().phase1_classify_from_predicates()
43 # [ owl:inverseOf <prop> ] used as object of owl:onProperty is an anonymous
44 # property expression, not an entity of its own: it would leave a spurious
45 # cache entry, and nothing has populated or tracked it yet
46 spurious = [n for n in self.entities
47 if isinstance(n, BNode) and (None, OWL.onProperty, n) in self.graph]
48 for bnode in spurious:
49 del self.entities[bnode]
51 classified = {n: type(next(iter(entities)))
52 for n, entities in self.entities.items()
53 if isinstance(n, BNode)}
55 checks.flag_malformed_restrictions(self, classified)
57 first_level = set(classified)
58 self._classify_nested(classified, self._configuration.get_classifier_predicates())
60 for bnode, python_class in classified.items():
61 if bnode not in first_level:
62 self.get_or_create(bnode, python_class, populate=False)
64 def phase2_create_from_types(self):
65 """Create the entities of the mapped types, then Individuals for the other types.
67 The base creates the entities of the mapped types. Subjects whose type is not
68 mapped become Individuals, except for structural vocabulary types.
69 """
70 super().phase2_create_from_types()
71 type_mapping = self._configuration.get_type_mapping()
73 # Subjects with rdf:type not covered by config -> Individual
74 for s, o in self.graph.subject_objects(RDF.type):
75 if isinstance(s, BNode) or s in self.entities:
76 continue
77 if o not in type_mapping:
78 if isinstance(o, URIRef):
79 o_str = str(o)
80 if any(o_str.startswith(ns) for ns in self._allowed_namespaces) and o not in (OWL.Thing, OWL.Nothing, RDFS.Literal):
81 continue
82 self.get_or_create(s, Individual, populate=True)
84 # Subjects with an rdf:type not mapped in config -> Individual
85 for s, o in self.graph.subject_objects(RDF.type):
86 if o not in type_mapping and not isinstance(s, BNode) and s not in self.entities:
87 self.get_or_create(s, Individual, populate=True)
90 def phase5_fallback(self):
91 """
92 First the base fallback (none for OWL: _FALLBACK_CLASS is Individual), then the OWL steps.
94 Classifies or reclassifies any entity whose concrete type could not be
95 determined in earlier phases, in particular generic Property entities
96 whose subtype (Relation, Attribute, Annotation) is not explicitly
97 asserted in the semantic artefact via rdf:type (handled by phase 2). It uses _infer_property_type to resolve the concrete subtype.
99 After reclassification, applies OWL defaults (e.g., domain, range, thing) to all entities via _enrich_or_apply_owl_defaults.
100 """
102 super().phase5_fallback()
104 for uri, entities in list(self.entities.items()):
105 for entity in list(entities):
107 if type(entity) is Property:
108 # Check if a more specific Property subclass already exists for this URI
110 has_concrete = any(
111 type(i) in (Relation, Attribute, Annotation)
112 for i in entities if i is not entity
113 )
115 if has_concrete:
116 # Remove generic Property, keep the concrete one
117 self.entities[uri].discard(entity)
118 else:
119 inferred = self._infer_property_type(entity)
120 old_dict = entity.__dict__.copy()
121 entity.__class__ = inferred
122 inferred.__init__(entity)
123 entity.__dict__.update(old_dict)
124 self._populate_entity(entity, uri)
126 self._enrich_or_apply_owl_defaults(entity, uri)
128 def handle_domain(self, entity, uri, predicate, obj, setter=None):
129 """Handle rdfs:domain: link the property to its domain and the domain back to the property.
131 A domain that cannot become a Concept (it is cached as something else) is
132 forced into one, because of OWL punning.
133 """
134 concept = self.get_or_create(obj, Concept)
135 if concept is None:
136 concept = self._force_as_concept(obj)
137 entity.set_has_domain(concept)
138 concept.set_is_in_domain_of(entity)
140 def _is_data_range(self, node) -> bool:
141 """True if node denotes a data range: XSD/RDF built-in datatypes, rdfs:Literal,
142 anything typed rdfs:Datatype, or a datatype restriction BNode."""
143 if (node, RDF.type, RDFS.Datatype) in self.graph:
144 return True
145 if isinstance(node, BNode):
146 return (node, OWL.onDatatype, None) in self.graph
147 return str(node).startswith(str(XSD)) or node in (
148 RDFS.Literal, RDF.PlainLiteral, RDF.XMLLiteral, RDF.langString, RDF.HTML)
150 def handle_range(self, entity, uri, predicate, obj, setter=None):
151 """Handle rdfs:range: set the range of a property and link the target back to it.
153 An Attribute accepts only data ranges and a Relation only class ranges: any
154 other triple returns False, so it is not tracked for that entity.
155 """
156 # Punning: each entity takes only the ranges its class admits.
157 # Returning False marks the triple as not admissible (not tracked).
158 is_data = self._is_data_range(obj)
159 if isinstance(entity, Attribute) != is_data and isinstance(entity, (Attribute, Relation)):
160 return False
161 if isinstance(entity, Attribute):
162 resource = self.get_or_create(obj, Datatype)
163 else:
164 resource = self.get_or_create(obj, Concept)
165 if resource is None:
166 resource = self._force_as_concept(obj)
167 entity.set_has_range(resource)
168 resource.set_is_in_range_of(entity)
170 def handle_equivalent_class(self, entity, uri, predicate, obj, setter=None):
171 """§9.1.2 EquivalentClasses — symmetry guaranteed."""
173 # add WARNING
174 if not isinstance(entity, Concept):
175 return
177 other = self.get_or_create(obj, Concept)
178 # add WARNING
179 if not other or not isinstance(other, Concept):
180 return
182 if other not in entity.get_is_equivalent_to():
183 entity.set_is_equivalent_to(other)
184 if entity not in other.get_is_equivalent_to():
185 other.set_is_equivalent_to(entity)
187 def handle_disjoint_with(self, entity, uri, predicate, obj, setter=None):
188 """§9.1.3 DisjointClasses — symmetry guaranteed."""
189 other = self.get_or_create(obj, Concept)
190 if other:
191 if other not in entity.get_is_disjoint_with():
192 entity.set_is_disjoint_with(other)
193 if entity not in other.get_is_disjoint_with():
194 other.set_is_disjoint_with(entity)
196 def handle_equivalent_property(self, entity, uri, predicate, obj, setter=None):
197 """Handle owl:equivalentProperty: link the two properties to each other (symmetric)."""
198 if obj in self.entities:
199 other = self.get_or_create(obj, Property)
200 else:
201 other = self.get_or_create(obj, type(entity))
202 if other:
203 if other not in entity.get_is_equivalent_to():
204 entity.set_is_equivalent_to(other)
205 if entity not in other.get_is_equivalent_to():
206 other.set_is_equivalent_to(entity)
208 def handle_property_disjoint_with(self, entity, uri, predicate, obj, setter=None):
209 """§9.2.3 DisjointObjectProperties — symmetry guaranteed."""
210 other = self.get_or_create(obj, Property)
211 if other:
212 if other not in entity.get_is_disjoint_with():
213 entity.set_is_disjoint_with(other)
214 if entity not in other.get_is_disjoint_with():
215 other.set_is_disjoint_with(entity)
217 def _ensure_individual(self, node):
218 """Get or create an Individual for node, preserving existing types (punning)."""
219 if isinstance(node, RDFlibLiteral):
220 return None
221 cached = self.entities.get(node, set())
222 ind = next((i for i in cached if isinstance(i, Individual)), None)
223 if ind:
224 return ind
225 ind = Individual()
226 ind.set_has_identifier(str(node))
227 self.entities.setdefault(node, set()).add(ind)
228 return ind
230 def handle_same_as(self, entity, uri, predicate, obj, setter=None):
231 """§9.6.1 SameIndividual — symmetry guaranteed."""
232 subj_ind = self._ensure_individual(uri)
233 other = self._ensure_individual(obj)
234 if subj_ind and other:
235 if other not in subj_ind.get_is_same_as():
236 subj_ind.set_is_same_as(other)
237 if subj_ind not in other.get_is_same_as():
238 other.set_is_same_as(subj_ind)
240 def handle_different_from(self, entity, uri, predicate, obj, setter=None):
241 """§9.6.2 DifferentIndividuals — symmetry guaranteed."""
242 subj_ind = self._ensure_individual(uri)
243 other = self._ensure_individual(obj)
244 if subj_ind and other:
245 if other not in subj_ind.get_is_different_from():
246 subj_ind.set_is_different_from(other)
247 if subj_ind not in other.get_is_different_from():
248 other.set_is_different_from(subj_ind)
250 def handle_inverse_of(self, entity, uri, predicate, obj, setter=None):
251 """Handle owl:inverseOf.
253 On a restriction it sets the property the restriction applies to; on a
254 relation it links the two relations to each other (symmetric).
255 """
256 if isinstance(entity, Restriction) and not isinstance(entity, Relation):
257 prop = self.get_or_create(obj, Property)
258 if prop:
259 entity.set_applies_on_property(prop)
260 return
261 other = self.get_or_create(obj, Relation)
262 if other:
263 if entity.get_is_inverse_of() is not other:
264 entity.set_is_inverse_of(other)
265 if other.get_is_inverse_of() is not entity:
266 other.set_is_inverse_of(entity)
268 def handle_on_property(self, entity, uri, predicate, obj, setter=None):
269 """If obj is a BNode with owl:inverseOf, resolve the real property and mark as inverse.
270 Undeclared properties default to Relation (ObjectProperty) per OWL DL.
271 """
272 if isinstance(obj, BNode) and (obj, OWL.inverseOf, None) in self.graph:
273 inverse_of = self.graph.value(obj, OWL.inverseOf)
274 if inverse_of:
275 prop = self.get_or_create(inverse_of, Property)
276 if prop and type(prop) is Property:
277 prop = self.get_or_create(inverse_of, Relation)
278 if prop and isinstance(entity, PropertyConceptRestriction):
279 entity.set_applies_on_property(prop)
280 entity.set_is_inverse(True)
281 return
282 prop = self.get_or_create(obj, Property)
283 if prop and type(prop) is Property:
284 prop = self.get_or_create(obj, Relation)
285 if prop:
286 entity.set_applies_on_property(prop)
288 def _force_as_concept(self, uri):
289 """Add a Concept to the cache for an IRI already classified as Individual or Resource (OWL punning).
291 It copies the attributes of the first cached entity, when there is one.
292 """
293 cached = list(self.entities.get(uri, set()))
294 concept = Concept()
295 if cached:
296 concept.__dict__.update(cached[0].__dict__)
297 else:
298 concept.set_has_identifier(str(uri))
299 self.entities.setdefault(uri, set()).add(concept)
300 return concept
302 def _enrich_or_apply_owl_defaults(self, entity, uri):
303 """
304 Applies OWL-mandated defaults to entities lacking explicit declarations.
305 A Relation or Attribute without a domain (or with only owl:Thing) inherits
306 it from its super properties or its inverses, falling back to owl:Thing.
307 The range falls back to owl:Thing for a Relation and to rdfs:Literal for
308 an Attribute. An Individual without a type gets owl:Thing. Entities that
309 share an IRI (punning) are cross-linked through also_defined_as, except
310 for punning subordinates.
311 """
313 if uri not in self.entities:
314 return
316 owl_thing = self.get_or_create(OWL.Thing, Concept)
317 rdfs_string = self.get_or_create(RDFS.Literal, Datatype)
319 def _safe_inherited(entity, getter_name):
320 """Inherited values, with ranges filtered to the right kind: datatypes for an Attribute, concepts for a Relation."""
321 values = self._get_inherited_property_values(entity, getter_name)
322 if isinstance(entity, Attribute):
323 if getter_name == "get_has_range":
324 return [v for v in values if isinstance(v, (Datatype, DatatypeRestriction))]
325 if isinstance(entity, Relation):
326 if getter_name == "get_has_range":
327 return [v for v in values if isinstance(v, Concept)]
328 return values
330 def _is_only_default(values, default_id):
331 """True if the list is not empty and holds nothing but the default value."""
332 return values and all(d.get_has_identifier() == default_id for d in values)
334 # Type-specific defaults: always apply, even for punning subordinates
335 # (these are constitutive of the class, not generic Resource enrichments)
337 if isinstance(entity, Relation):
338 current_domains = entity.get_has_domain()
339 if not current_domains or _is_only_default(current_domains, owl_thing):
340 inherited_domain = _safe_inherited(entity, "get_has_domain")
341 if inherited_domain:
342 entity.has_domain.clear()
343 for domain in inherited_domain:
344 entity.set_has_domain(domain)
345 elif not current_domains:
346 entity.set_has_domain(owl_thing)
348 current_ranges = entity.get_has_range()
349 if not current_ranges or _is_only_default(current_ranges, owl_thing):
350 inherited_range = _safe_inherited(entity, "get_has_range")
351 if inherited_range:
352 entity.has_range.clear()
353 for r in inherited_range:
354 entity.set_has_range(r)
355 elif not current_ranges:
356 entity.set_has_range(owl_thing)
358 if isinstance(entity, Attribute):
359 current_domains = entity.get_has_domain()
360 if not current_domains or _is_only_default(current_domains, owl_thing):
361 inherited_domain = _safe_inherited(entity, "get_has_domain")
362 if inherited_domain:
363 entity.has_domain.clear()
364 for domain in inherited_domain:
365 entity.set_has_domain(domain)
366 elif not current_domains:
367 entity.set_has_domain(owl_thing)
369 current_ranges = entity.get_has_range()
370 if not current_ranges or _is_only_default(current_ranges, rdfs_string):
371 inherited_range = _safe_inherited(entity, "get_has_range")
372 if inherited_range:
373 entity.has_range.clear()
374 for r in inherited_range:
375 entity.set_has_range(r)
376 elif not current_ranges:
377 entity.set_has_range(rdfs_string)
379 if isinstance(entity, Individual):
380 if not entity.get_has_type():
381 entity.set_has_type(owl_thing)
383 # Generic Resource-level enrichments: skip for punning subordinates
384 if self._is_punning_subordinate(entity, uri):
385 return
387 if isinstance(entity, Resource):
388 if len(self.entities[uri]) > 1:
389 existing = entity.get_also_defined_as() or []
390 for other in self.entities[uri]:
391 if other is entity:
392 continue
393 if other not in existing:
394 entity.set_also_defined_as(other)
395 if entity not in (other.get_also_defined_as() or []):
396 other.set_also_defined_as(entity)
399 def _get_inherited_property_values(self, property_instance, getter_name: str) -> list:
400 """Return the domain or range inherited by a property, or [] when nothing is found.
402 For a Relation the inverse relations are tried first, with domain and range
403 swapped (the domain of a relation is the range of its inverse); then the
404 super properties are walked upwards.
405 """
406 def collect(node):
407 """Return the first non-empty value on an ancestor (or on its inverses, swapped), never on the property itself."""
408 if node is property_instance:
409 return None
410 getter = getattr(node, getter_name, None)
411 if getter:
412 values = getter()
413 if values:
414 return values if isinstance(values, list) else [values]
415 if isinstance(node, Relation):
416 swapped_getter = {"get_has_domain": "get_has_range", "get_has_range": "get_has_domain"}.get(getter_name)
417 if swapped_getter:
418 for inverse in (node.get_is_inverse_of() or []):
419 swapped = getattr(inverse, swapped_getter, lambda: None)()
420 if swapped:
421 return swapped if isinstance(swapped, list) else [swapped]
422 inverse_uri = URIRef(inverse.get_has_identifier())
423 graph_pred = RDFS.range if swapped_getter == "get_has_range" else RDFS.domain
424 for obj in self.graph.objects(inverse_uri, graph_pred):
425 if isinstance(obj, BNode):
426 continue
427 inst = self.get_or_create(obj, Concept)
428 if inst:
429 return [inst]
430 return None
432 if isinstance(property_instance, Relation):
433 swapped_getter = {"get_has_domain": "get_has_range", "get_has_range": "get_has_domain"}.get(getter_name)
434 if swapped_getter:
435 owl_thing_id = str(OWL.Thing)
436 for inverse in (property_instance.get_is_inverse_of() or []):
437 swapped = getattr(inverse, swapped_getter, lambda: None)()
438 if swapped:
439 filtered = [v for v in (swapped if isinstance(swapped, list) else [swapped])
440 if v.get_has_identifier() != owl_thing_id]
441 if filtered:
442 return filtered
443 inverse_uri = URIRef(inverse.get_has_identifier())
444 graph_pred = RDFS.range if swapped_getter == "get_has_range" else RDFS.domain
445 for obj in self.graph.objects(inverse_uri, graph_pred):
446 if isinstance(obj, BNode):
447 continue
448 inst = self.get_or_create(obj, Concept)
449 if inst:
450 return [inst]
452 result = self._traverse_hierarchy(
453 property_instance,
454 next_getter="get_is_sub_property_of",
455 direction="up",
456 collect=collect,
457 )
458 return result if result is not None else []
461 def _infer_property_type(self, entity) -> type:
462 """
463 Infers the concrete subtype (Relation, Attribute, Annotation) for a
464 generic Property entity.
466 Strategy:
467 1. owl:inverseOf in graph — if present, this is a Relation.
468 2. Traverse UP subPropertyOf — inherit type from ancestor.
469 3. Traverse DOWN subPropertyOf — inherit type from descendant.
470 4. Declared rdfs:range — XSD/Literal range -> Attribute, URIRef range -> Relation.
471 5. Graph usage — all literal objects -> Attribute, any URIRef object -> Relation.
472 6. Fallback to Annotation.
473 """
474 uri_ref = URIRef(entity.get_has_identifier()) if entity.get_has_identifier() else None
476 # (1) inverseOf in graph (entity not yet populated as Property)
477 if uri_ref:
478 if any(self.graph.objects(uri_ref, OWL.inverseOf)) or \
479 any(self.graph.subjects(OWL.inverseOf, uri_ref)):
480 return Relation
482 CONCRETE = (Relation, Attribute, Annotation)
484 # (2) UP THE HIERARCHY
485 def collect_type(node):
486 """Return the node's class when it is already a concrete property type."""
487 if type(node) in CONCRETE:
488 return type(node)
489 return None
491 result = self._traverse_hierarchy(
492 entity,
493 next_getter="get_is_sub_property_of",
494 direction="up",
495 collect=collect_type,
496 )
497 if result:
498 return result
500 # (3) DOWN THE HIERARCHY
501 result = self._traverse_hierarchy(
502 entity,
503 next_getter="get_is_sub_property_of",
504 direction="down",
505 collect=collect_type,
506 )
507 if result:
508 return result
510 # (4) Declared rdfs:range
511 if uri_ref:
512 for range_obj in self.graph.objects(uri_ref, RDFS.range):
513 range_str = str(range_obj)
514 if range_str.startswith(str(XSD)) or range_obj in (RDFS.Literal,):
515 return Attribute
516 if isinstance(range_obj, URIRef):
517 return Relation
519 # (5) Graph usage: how the property is used as predicate
520 if uri_ref:
521 has_literal = False
522 has_uriref = False
523 for s, p, o in self.graph.triples((None, uri_ref, None)):
524 if isinstance(o, RDFlibLiteral):
525 has_literal = True
526 elif isinstance(o, URIRef):
527 has_uriref = True
528 if has_uriref:
529 return Relation
530 if has_literal:
531 return Attribute
533 # (6) fallback
534 return Annotation
536 # ========== HELPERS & RELATED FUNCTIONS PHASE 1 ==========
538 def _classify_nested(self, classified, predicates):
539 """
540 Recursively classifies BNodes found inside OWL list collections
541 (owl:intersectionOf, owl:unionOf, owl:oneOf) hanging off already-classified
542 BNodes. Extends the classified dict in place with any newly discovered
543 BNode-to-class mappings.
544 """
546 list_preds = [OWL.intersectionOf, OWL.unionOf, OWL.oneOf, OWL.onDataRange]
548 for bnode in list(classified.keys()):
549 for pred, obj in self.graph.predicate_objects(bnode):
550 if pred in list_preds:
551 try:
552 collection = RDFLibCollection(self.graph, obj)
553 for item in collection:
554 if isinstance(item, BNode) and item not in classified:
555 py_class = self._configuration.classify_by_predicate(item, self.graph)
556 if py_class:
557 classified[item] = py_class
558 except:
559 pass
561 # ========== HELPERS & RELATED FUNCTIONS PHASE 2 ==========
563 def _apply_setters_immediate(self, entity, setters_config):
564 """Applies static setter values from the config directly to an entity,
565 without resolving any RDF object. Used in phase2 to apply constant values
566 (e.g. set_is_symmetric: True) defined alongside is: class entries.
567 """
568 for setter_item in setters_config:
569 if isinstance(setter_item, dict):
570 for setter_name, value in setter_item.items():
571 if hasattr(entity, setter_name):
572 getattr(entity, setter_name)(value)
573 else:
574 if hasattr(entity, setter_item):
575 getattr(entity, setter_item)()
577 # ========== HANDLERS PHASE 4 (GROUP AXIOMS) ==========
579 def process_all_disjoint_classes(self, uri: Node):
580 """
581 Handles owl:AllDisjointClasses axioms by resolving the owl:members
582 collection and marking every pair of member Concepts as mutually
583 disjoint via set_is_disjoint_with.
584 """
585 members_list = self.graph.value(uri, OWL.members)
586 if not members_list:
587 return
588 try:
589 members = list(RDFLibCollection(self.graph, members_list))
590 for i, class_a_uri in enumerate(members):
591 class_a = self.get_or_create(class_a_uri, Concept)
592 for class_b_uri in members[i + 1:]:
593 class_b = self.get_or_create(class_b_uri, Concept)
594 class_a.set_is_disjoint_with(class_b)
595 class_b.set_is_disjoint_with(class_a)
596 except Exception:
597 logger.warning("AllDisjointClasses failed for %s", uri, exc_info=True)
599 def process_all_different(self, uri: Node):
600 """
601 Handles owl:AllDifferent axioms by resolving the owl:distinctMembers
602 collection and marking every pair of member Individuals as mutually
603 different via set_is_different_from.
604 """
605 members_list = self.graph.value(uri, OWL.distinctMembers)
606 if not members_list:
607 return
608 try:
609 members = list(RDFLibCollection(self.graph, members_list))
610 for i, ind_a_uri in enumerate(members):
611 ind_a = self.get_or_create(ind_a_uri, Individual)
612 for ind_b_uri in members[i + 1:]:
613 ind_b = self.get_or_create(ind_b_uri, Individual)
614 ind_a.set_is_different_from(ind_b)
615 ind_b.set_is_different_from(ind_a)
616 except Exception:
617 logger.warning("AllDifferent failed for %s", uri, exc_info=True)
619 def process_all_disjoint_properties(self, uri: Node):
620 """
621 Handles owl:AllDisjointProperties axioms by resolving the owl:members
622 collection and marking every pair of member Properties as mutually
623 disjoint via set_is_disjoint_with.
624 """
625 members_list = self.graph.value(uri, OWL.members)
626 if not members_list:
627 return
628 try:
629 members = list(RDFLibCollection(self.graph, members_list))
630 for i, prop_a_uri in enumerate(members):
631 prop_a = self.get_or_create(prop_a_uri, Property)
632 for prop_b_uri in members[i + 1:]:
633 prop_b = self.get_or_create(prop_b_uri, Property)
634 prop_a.set_is_disjoint_with(prop_b)
635 prop_b.set_is_disjoint_with(prop_a)
636 except Exception:
637 logger.warning("AllDisjointProperties failed for %s", uri, exc_info=True)
639# ==========================================================================
640# OWL-SPECIFIC HANDLERS READ FROM DECLARATIVE MAPPING
641# ==========================================================================
643 def handle_property_chain(self, entity, uri, predicate, obj, setter=None):
644 """Handler per owl:propertyChainAxiom"""
646 if not self._is_rdf_collection(obj):
647 raise ValueError(f"owl:propertyChainAxiom object is not an RDF list: {obj}")
648 collection = RDFLibCollection(self.graph, obj)
649 chain_instances = []
650 for chain_uri in collection:
651 chain_instance = self.get_or_create(chain_uri, Relation)
652 chain_instances.append(chain_instance)
653 entity.set_has_property_chain(chain_instances)
655 def handle_has_key(self, entity, uri, predicate, obj, setter=None):
656 """Handle owl:hasKey: add every property of the key list to the concept."""
657 try:
658 for prop_uri in RDFLibCollection(self.graph, obj):
659 prop = self.get_or_create(prop_uri, Property)
660 if prop:
661 entity.set_has_key(prop)
662 except Exception:
663 logger.warning("handle_has_key failed for %s", uri, exc_info=True)
665 # ========== RESTRICTIONS ================================================
667 def handle_disjoint_union(self, entity, uri, predicate, obj, setter=None):
668 """§9.1.4 DisjointUnion(C CE1...CEn) — equivalent to:
669 EquivalentClasses(C ObjectUnionOf(CE1...CEn)) + DisjointClasses(CE1...CEn).
670 """
671 if not isinstance(entity, Concept):
672 return
673 try:
674 collection = RDFLibCollection(self.graph, obj)
675 members = list(collection)
677 # 1. C equivalentClass ObjectUnionOf(CE1...CEn)
678 tf = self.get_or_create(obj, TruthFunction)
679 if tf:
680 tf.set_has_logical_operator("or")
681 for member_uri in members:
682 concept = self.get_or_create(member_uri, Concept)
683 if concept:
684 tf.set_applies_on_concept(concept)
685 entity.set_is_equivalent_to(tf)
687 # 2. DisjointClasses(CE1...CEn) — pairwise
688 for i, uri_a in enumerate(members):
689 concept_a = self.get_or_create(uri_a, Concept)
690 for uri_b in members[i+1:]:
691 concept_b = self.get_or_create(uri_b, Concept)
692 if concept_a and concept_b:
693 concept_a.set_is_disjoint_with(concept_b)
694 concept_b.set_is_disjoint_with(concept_a)
696 except Exception:
697 logger.warning("disjointUnion failed for %s", uri, exc_info=True)
699 def handle_datatype_restriction(self, entity, uri, predicate, obj, setter=None):
700 """Handle owl:withRestrictions: preserve the base datatype and every facet/value pair.
702 Facet nodes (e.g. xsd:minInclusive) are cached and tracked, so phase 6
703 does not turn them into Statements.
704 """
705 on_datatype = self.graph.value(uri, OWL.onDatatype)
706 if on_datatype:
707 dt = self.get_or_create(on_datatype, Datatype)
708 if dt:
709 entity.set_applies_on_concept(dt)
710 try:
711 collection = RDFLibCollection(self.graph, obj)
712 for facet_node in collection:
713 for facet_pred, facet_val in self.graph.predicate_objects(facet_node):
714 if facet_pred == RDF.type:
715 continue
716 if isinstance(facet_val, RDFlibLiteral):
717 FACET_MAP = {
718 str(XSD.minInclusive): ">=",
719 str(XSD.maxInclusive): "<=",
720 str(XSD.minExclusive): ">",
721 str(XSD.maxExclusive): "<",
722 str(XSD.pattern): "pattern",
723 str(XSD.length): "length",
724 str(XSD.minLength): "minLength",
725 str(XSD.maxLength): "maxLength",
726 }
727 manchester_facet = FACET_MAP.get(str(facet_pred), str(facet_pred))
728 literal = self._create_literal(facet_val)
729 entity.set_has_facet(manchester_facet, literal)
731 # Register facet node in cache keyed to the parent DatatypeRestriction
732 # and mark all its triples as mapped, so phase6 does not create
733 # spurious Statements or Individuals for the facet BNode.
734 if facet_node not in self.entities:
735 self.entities[facet_node] = set()
736 self.entities[facet_node].add(entity)
737 self._track(entity, *((facet_node, fp, fv) for fp, fv in self.graph.predicate_objects(facet_node)))
739 except Exception:
740 logger.warning("Datatype restriction failed for %s", uri, exc_info=True)
742 def handle_cardinality_exactly(self, entity, uri, predicate, obj, setter=None):
743 """Handle an exact cardinality (plain or qualified): type "exactly", the number, and owl:Thing as the default concept."""
744 entity.set_has_cardinality_type("exactly")
745 entity.set_has_cardinality(obj)
746 entity.set_applies_on_concept(self.get_or_create(OWL.Thing, Concept))
748 def handle_cardinality_min(self, entity, uri, predicate, obj, setter=None):
749 """Handle a minimum cardinality (plain or qualified): type "min", the number, and owl:Thing as the default concept."""
750 entity.set_has_cardinality_type("min")
751 entity.set_has_cardinality(obj)
752 entity.set_applies_on_concept(self.get_or_create(OWL.Thing, Concept))
754 def handle_cardinality_max(self, entity, uri, predicate, obj, setter=None):
755 """Handle a maximum cardinality (plain or qualified): type "max", the number, and owl:Thing as the default concept."""
756 entity.set_has_cardinality_type("max")
757 entity.set_has_cardinality(obj)
758 entity.set_applies_on_concept(self.get_or_create(OWL.Thing, Concept))
760 # ========== HANDLER TRUTH FUNCTIONS ==========
762 def _build_truth_function(self, entity, obj, operator):
763 """
764 If entity is TruthFunction: populate in-place, return None.
765 If entity is Concept: create a separate TruthFunction keyed on obj, return tf.
767 If the list has a single element, log a warning and:
768 - if entity is TruthFunction: populate applies_on_concept anyway, return None
769 - if entity is Concept: return the Concept directly (no TruthFunction created)
771 If the list is empty, log a warning and return None.
772 """
773 try:
774 items = list(RDFLibCollection(self.graph, obj))
775 except Exception:
776 logger.warning("Truth function list failed for %s", obj, exc_info=True)
777 return None
779 if len(items) == 0:
780 checks.empty_truth_function(self, entity, obj, operator)
781 return None
783 if len(items) == 1:
784 checks.singleton_truth_function(self, entity, obj, operator)
785 single_concept = self.get_or_create(items[0], Concept)
786 if type(entity) is TruthFunction:
787 entity.set_has_logical_operator(operator)
788 if single_concept:
789 entity.set_applies_on_concept(single_concept)
790 return None
791 else:
792 return single_concept
794 if type(entity) is TruthFunction:
795 entity.set_has_logical_operator(operator)
796 for item in items:
797 concept = self.get_or_create(item, Concept)
798 if concept:
799 entity.set_applies_on_concept(concept)
800 return None
801 else:
802 tf = self.get_or_create(obj, TruthFunction)
803 if tf:
804 tf.set_has_logical_operator(operator)
805 for item in items:
806 concept = self.get_or_create(item, Concept)
807 if concept:
808 tf.set_applies_on_concept(concept)
809 return tf
811 def handle_intersection(self, entity, uri, predicate, obj, setter=None):
812 """Handle owl:intersectionOf as an "and" truth function; on a Concept it becomes an equivalent class."""
813 if type(entity) not in (TruthFunction, Concept):
814 return
815 tf = self._build_truth_function(entity, obj, "and")
816 if tf and isinstance(entity, Concept):
817 entity.set_is_equivalent_to(tf)
819 def handle_union(self, entity, uri, predicate, obj, setter=None):
820 """Handle owl:unionOf as an "or" truth function; on a Concept it becomes an equivalent class."""
821 if type(entity) not in (TruthFunction, Concept):
822 return
823 tf = self._build_truth_function(entity, obj, "or")
824 if tf and isinstance(entity, Concept):
825 entity.set_is_equivalent_to(tf)
827 def handle_complement(self, entity, uri, predicate, obj, setter=None):
828 """Handle owl:complementOf as a "not" truth function over the target concept."""
829 if type(entity) not in (TruthFunction, Concept):
830 return
831 if type(entity) is TruthFunction:
832 entity.set_has_logical_operator("not")
833 concept = self.get_or_create(obj, Concept)
834 if concept:
835 entity.set_applies_on_concept(concept)
836 else:
837 tf = self.get_or_create(obj, TruthFunction)
838 if tf:
839 tf.set_has_logical_operator("not")
840 concept = self.get_or_create(obj, Concept)
841 if concept:
842 tf.set_applies_on_concept(concept)
843 entity.set_is_equivalent_to(tf)
845 def handle_one_of(self, entity, uri, predicate, obj, setter=None):
846 """Handle owl:oneOf: add the listed individuals to an enumeration.
848 On a Concept a OneOf is created and set as its equivalent class.
849 """
850 if type(entity) not in (OneOf, Concept):
851 return
852 if type(entity) is Concept:
853 one_of = self.get_or_create(uri, OneOf)
854 if one_of:
855 try:
856 collection = RDFLibCollection(self.graph, obj)
857 for item in collection:
858 resource = self.get_or_create(item, Individual)
859 if resource:
860 one_of.set_applies_on_resource(resource)
861 except Exception:
862 logger.warning("oneOf on Concept failed for %s", uri, exc_info=True)
863 entity.set_is_equivalent_to(one_of)
864 else: # type(entity) is OneOf
865 try:
866 collection = RDFLibCollection(self.graph, obj)
867 for item in collection:
868 resource = self.get_or_create(item, Individual)
869 if resource:
870 entity.set_applies_on_resource(resource)
871 except Exception:
872 logger.warning("oneOf failed for %s", uri, exc_info=True)
874 def handle_has_value(self, entity, uri, predicate, obj, setter=None):
875 """Handle owl:hasValue: set the resource and, when the restriction names one, its property."""
876 resource = self.get_or_create(obj, Resource)
877 if resource:
878 entity.set_applies_on_resource(resource)
879 on_prop = self.graph.value(uri, OWL.onProperty)
880 if on_prop:
881 prop = self.get_or_create(on_prop, Property)
882 if prop:
883 entity.set_applies_on_property(prop)
886 def handle_rdf_type(self, entity, uri, predicate, obj, setter=None):
887 """
888 Bidirectional handler for rdf:type.
890 - subject.has_type += object (Individual/Resource side)
891 - object.individuals_with_this_type += subject (Concept side, only if the object
892 is really classified as a Concept and is not a structural vocabulary URI)
894 Mirrors the filter logic of _apply_setters for set_has_type: it discards
895 objects in the OWL/RDF/RDFS namespaces, except owl:Thing, owl:Nothing,
896 rdfs:Literal.
897 """
898 if not isinstance(obj, URIRef) and not isinstance(obj, BNode):
899 return
901 # Structural URI filter (same logic as _apply_setters)
902 if isinstance(obj, URIRef):
903 obj_str = str(obj)
904 if any(obj_str.startswith(ns) for ns in self._allowed_namespaces) \
905 and obj not in (OWL.Thing, OWL.Nothing, RDFS.Literal):
906 return
908 concept = self.get_or_create(obj, Concept)
909 if concept is None:
910 return
912 # Direct side
913 if hasattr(entity, 'set_has_type'):
914 entity.set_has_type(concept)
916 # Inverse side: only if the object is really a Concept
917 # (get_or_create can promote; the exact type() check avoids polluting
918 # TruthFunction/Restriction/OneOf/etc.)
919 if type(concept) is Concept and isinstance(entity, Individual):
920 concept.set_individuals_with_this_type(entity)
923 # ========== Statement OVERRIDE for OWL (typed subject/object) ==========
925 def _create_statement_for_triple(self, subj, pred, obj):
926 """
927 Creates a Statement entity for a triple that was not mapped during
928 population phases.
930 Skips rdf:type triples — those are handled by phase2 and must not be
931 reified as Statements.
933 Subject is resolved as Individual; if the namespace filter blocks it
934 (e.g. OWL/RDF/RDFS URIs), the triple is silently dropped.
936 Predicate is looked up in the entity cache first. If not found, a bare
937 Annotation is created directly, bypassing the namespace filter — predicates
938 must always be reifiable regardless of their namespace.
940 Object is resolved based on its RDF type: RDF collections become
941 Containers, RDFLib Literals become Literal entities, everything else
942 is resolved as Individual.
944 OWL defaults (owl:Thing type for untyped Individuals) are applied to
945 subject and object after the Statement is built, since these entities
946 may have been created here for the first time, after phase3 defaults
947 have already run.
948 """
949 if pred == RDF.type or pred in self._property_mapping:
950 return
952 # Subject: an unmapped structured BNode is a Statement, not an Individual.
953 # This handles the case where phase6 visits the BNode's outgoing triples
954 # before visiting the triple that points to it.
955 if self._is_unmapped_structured_bnode(subj):
956 # Just materialise it; its outgoing triples will be absorbed inside.
957 # Skip emitting a wrapper Statement for this triple — _create_nested_statement
958 # already records (subj, pred, obj) in the BNode-Statement's triples_map.
959 self._create_nested_statement(subj)
960 return
962 subj_inst = self._resolve_statement_endpoint(subj, Individual)
963 if subj_inst is None:
964 # Fallback for structural-namespace subjects: create a bare Resource
965 # so the predicate is still reifiable.
966 subj_inst = Resource()
967 subj_inst.set_has_identifier(str(subj))
968 if subj not in self.entities:
969 self.entities[subj] = set()
970 self.entities[subj].add(subj_inst)
972 if pred in self.entities:
973 pred_inst = next(
974 (i for i in self.entities[pred] if isinstance(i, Property)),
975 None
976 )
977 else:
978 pred_inst = None
980 if pred_inst is None:
981 pred_inst = Annotation()
982 pred_inst.set_has_identifier(str(pred))
983 if pred not in self.entities:
984 self.entities[pred] = set()
985 self.entities[pred].add(pred_inst)
987 statement = Statement()
988 stmt_bnode = BNode()
989 statement.set_has_identifier(str(stmt_bnode))
991 self._track(statement, (subj, pred, obj))
993 statement.set_has_subject(subj_inst)
994 statement.set_has_predicate(pred_inst)
996 if self._is_rdf_collection(obj):
997 obj_inst = self._convert_collection_to_container(obj)
998 elif isinstance(obj, RDFlibLiteral):
999 obj_inst = self._create_literal(obj)
1000 elif self._is_unmapped_structured_bnode(obj):
1001 obj_inst = self._create_nested_statement(obj)
1002 else:
1003 # object never seen: Individual (fallback class — _resolve_statement_endpoint
1004 # returns the cached dominant entity if any, otherwise creates one)
1005 obj_inst = self._resolve_statement_endpoint(obj, Resource)
1007 if obj_inst:
1008 statement.set_has_object(obj_inst)
1010 if stmt_bnode not in self.entities:
1011 self.entities[stmt_bnode] = set()
1012 self.entities[stmt_bnode].add(statement)
1014 self._enrich_or_apply_owl_defaults(subj_inst, subj)
1015 if obj_inst and not isinstance(obj, RDFlibLiteral):
1016 self._enrich_or_apply_owl_defaults(obj_inst, obj)
1018 def _resolve_statement_endpoint(self, node, fallback_class):
1019 """Return the entity to use as subject or object of a Statement.
1021 It is the punning-dominant cached entity, or a new one of `fallback_class`.
1022 """
1023 dom = self._get_punning_dominant(node)
1024 if dom is not None:
1025 return dom
1026 return self.get_or_create(node, fallback_class)
1028 # ========== SWRL ==========
1030 def handle_swrl_imp(self, uri):
1031 """Build a Rule from a swrl:Imp, with its body atoms as antecedent and head atoms as consequent."""
1032 # Force promotion to Rule if cached as something else
1033 if uri in self.entities:
1034 existing = next(iter(self.entities[uri]))
1035 if not isinstance(existing, Rule):
1036 rule = Rule()
1037 rule.__dict__.update(existing.__dict__)
1038 self.entities[uri].discard(existing)
1039 self.entities[uri].add(rule)
1040 self._move_tracking(existing, rule)
1041 else:
1042 rule = existing
1043 else:
1044 rule = self.get_or_create(uri, Rule)
1046 if not rule:
1047 return
1049 body_node = self.graph.value(uri, SWRL_NS.body)
1050 if body_node:
1051 try:
1052 for atom_node in RDFLibCollection(self.graph, body_node):
1053 atom = self._parse_swrl_atom(atom_node)
1054 if atom:
1055 rule.set_has_antecedent(atom)
1056 except Exception:
1057 logger.warning("SWRL body parsing failed for rule %s", uri, exc_info=True)
1059 head_node = self.graph.value(uri, SWRL_NS.head)
1060 if head_node:
1061 try:
1062 for atom_node in RDFLibCollection(self.graph, head_node):
1063 atom = self._parse_swrl_atom(atom_node)
1064 if atom:
1065 rule.set_has_consequent(atom)
1066 except Exception:
1067 logger.warning("SWRL head parsing failed for rule %s", uri, exc_info=True)
1069 def _parse_swrl_atom(self, atom_node):
1070 """Build an Atom from a SWRL atom node: its predicate (by atom kind) and its arguments."""
1071 atom = self.get_or_create(atom_node, Atom)
1072 if not atom:
1073 return None
1075 # classPredicate (ClassAtom)
1076 class_pred = self.graph.value(atom_node, SWRL_NS.classPredicate)
1077 if class_pred:
1078 atom.set_has_predicate(self.get_or_create(class_pred, Concept))
1080 # propertyPredicate (IndividualPropertyAtom, DatavaluedPropertyAtom)
1081 prop_pred = self.graph.value(atom_node, SWRL_NS.propertyPredicate)
1082 if prop_pred:
1083 atom_type_uri = self.graph.value(atom_node, RDF.type)
1084 local = iri_local_name(atom_type_uri) if atom_type_uri else ''
1085 if local == 'DatavaluedPropertyAtom':
1086 atom.set_has_predicate(self.get_or_create(prop_pred, Attribute))
1087 else:
1088 atom.set_has_predicate(self.get_or_create(prop_pred, Relation))
1090 # builtin (BuiltinAtom)
1091 builtin = self.graph.value(atom_node, SWRL_NS.builtin)
1092 if builtin:
1093 atom.set_has_predicate(self.get_or_create(builtin, Resource))
1095 # SameIndividualsAtom / DifferentIndividualsAtom — no predicate in RDF
1096 atom_type_uri = self.graph.value(atom_node, RDF.type)
1097 if atom_type_uri:
1098 local = iri_local_name(atom_type_uri)
1099 if local == 'SameIndividualsAtom':
1100 atom.set_has_predicate(self.get_or_create(OWL.sameAs, Relation))
1101 elif local == 'DifferentIndividualsAtom':
1102 atom.set_has_predicate(self.get_or_create(OWL.differentFrom, Relation))
1104 # dataRange (DataRangeAtom)
1105 data_range = self.graph.value(atom_node, SWRL_NS.dataRange)
1106 if data_range and atom.get_has_predicate() is None:
1107 atom.set_has_predicate(self.get_or_create(data_range, Datatype))
1109 # argument1 / argument2 (most atom types)
1110 arg1 = self.graph.value(atom_node, SWRL_NS.argument1)
1111 if arg1:
1112 atom.set_has_arguments(self._resolve_swrl_arg(arg1))
1114 arg2 = self.graph.value(atom_node, SWRL_NS.argument2)
1115 if arg2:
1116 atom.set_has_arguments(self._resolve_swrl_arg(arg2))
1118 # arguments (BuiltinAtom — RDF list)
1119 args_node = self.graph.value(atom_node, SWRL_NS.arguments)
1120 if args_node:
1121 try:
1122 for arg in RDFLibCollection(self.graph, args_node):
1123 atom.set_has_arguments(self._resolve_swrl_arg(arg))
1124 except Exception:
1125 logger.warning("SWRL builtin arguments failed for atom %s",
1126 atom_node, exc_info=True)
1128 return atom
1130 def _resolve_swrl_arg(self, node):
1131 """Resolve a SWRL argument: a Literal, a Variable or, by default, an Individual."""
1132 if isinstance(node, RDFlibLiteral):
1133 return self._create_literal(node)
1134 if (node, RDF.type, SWRL_NS.Variable) in self.graph:
1135 return self.get_or_create(node, Variable)
1136 return self.get_or_create(node, Individual)
1139 # ========== PROVENANCE OWL-SPECIFIC ==========
1141 _PROVENANCE_AXIOM_TYPES = (
1142 OWL.AllDisjointClasses,
1143 OWL.AllDifferent,
1144 OWL.AllDisjointProperties,
1145 )
1147 def _add_axiom_provenance(self, entity, sub):
1148 """Include general axioms that mention `entity` URI in members/distinctMembers."""
1149 uri_str = getattr(entity, 'has_identifier', None)
1150 if not uri_str:
1151 return
1152 uri_ref = URIRef(uri_str)
1153 for axiom_type in self._PROVENANCE_AXIOM_TYPES:
1154 for axiom in self.graph.subjects(RDF.type, axiom_type):
1155 if self._uri_in_axiom_members(axiom, uri_ref):
1156 self._expand_bnode_into(axiom, sub, set())
1158 def _uri_in_axiom_members(self, axiom_node, uri_ref):
1159 """True if uri_ref appears in owl:members or owl:distinctMembers list of axiom_node."""
1160 for list_pred in (OWL.members, OWL.distinctMembers):
1161 head = self.graph.value(axiom_node, list_pred)
1162 if head is None:
1163 continue
1164 node = head
1165 while node and node != RDF.nil:
1166 first = self.graph.value(node, RDF.first)
1167 if first == uri_ref:
1168 return True
1169 node = self.graph.value(node, RDF.rest)
1170 return False