Skip to content

Ontology

Python classes in this page are strongly dependent on the OWLAPI library. The base class Ontology extends several features including convenient access to specially defined entities (e.g., owl:Thing and owl:Nothing), indexing of entities in the signature with their IRIs as keys, and some other customised functions for specific ontology engineering purposes. Ontology also has an OntologyReasoner attribute which provides reasoning facilities such as classifying entities, checking entailment, and so on. Users who are familiar with the OWLAPI should feel relatively easy to extend the Python classes here.

Ontology(owl_path, reasoner_type='hermit')

Ontology class that extends from the Java library OWLAPI.

Typing from OWLAPI

Types with OWL prefix are mostly imported from the OWLAPI library by, for example, from org.semanticweb.owlapi.model import OWLObject.

Attributes:

Name Type Description
owl_path str

The path to the OWL ontology file.

owl_manager OWLOntologyManager

A ontology manager for creating OWLOntology.

owl_onto OWLOntology

An OWLOntology created by owl_manger from owl_path.

owl_iri str

The IRI of the owl_onto.

owl_classes dict[str, OWLClass]

A dictionary that stores the (iri, ontology_class) pairs.

owl_object_properties dict[str, OWLObjectProperty]

A dictionary that stores the (iri, ontology_object_property) pairs.

owl_data_properties dict[str, OWLDataProperty]

A dictionary that stores the (iri, ontology_data_property) pairs.

owl_annotation_properties dict[str, OWLAnnotationProperty]

A dictionary that stores the (iri, ontology_annotation_property) pairs.

owl_individuals dict[str, OWLIndividual]

A dictionary that stores the (iri, ontology_individual) pairs.

owl_data_factory OWLDataFactory

A data factory for manipulating axioms.

reasoner_type str

The type of reasoner used. Defaults to "hermit". Options are ["hermit", "elk", "struct"].

reasoner OntologyReasoner

A reasoner for ontology inference.

Parameters:

Name Type Description Default
owl_path str

The path to the OWL ontology file.

required
reasoner_type str

The type of reasoner used. Defaults to "hermit". Options are ["hermit", "elk", "struct"].

'hermit'
Source code in src/deeponto/onto/ontology.py
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
def __init__(self, owl_path: str, reasoner_type: str = "hermit"):
    """Initialise a new ontology.

    Args:
        owl_path (str): The path to the OWL ontology file.
        reasoner_type (str): The type of reasoner used. Defaults to `"hermit"`. Options are `["hermit", "elk", "struct"]`.
    """
    self.owl_path = os.path.abspath(owl_path)
    self.owl_manager = OWLManager.createOWLOntologyManager()
    self.owl_onto = self.owl_manager.loadOntologyFromOntologyDocument(IRI.create(File(self.owl_path)))
    self.owl_iri = str(self.owl_onto.getOntologyID().getOntologyIRI().get())
    self.owl_classes = self._get_owl_objects("Classes")
    self.owl_object_properties = self._get_owl_objects("ObjectProperties")
    # for some reason the top object property is included
    if OWL_TOP_OBJECT_PROPERTY in self.owl_object_properties.keys():
        del self.owl_object_properties[OWL_TOP_OBJECT_PROPERTY]
    self.owl_data_properties = self._get_owl_objects("DataProperties")
    self.owl_data_factory = self.owl_manager.getOWLDataFactory()
    self.owl_annotation_properties = self._get_owl_objects("AnnotationProperties")
    self.owl_individuals = self._get_owl_objects("Individuals")

    # reasoning
    self.reasoner_type = reasoner_type
    self.reasoner = OntologyReasoner(self, self.reasoner_type)

    # hidden attributes
    self._multi_children_classes = None
    self._sibling_class_groups = None
    self._axiom_type = AxiomType  # for development use

    # summary
    self.info = {
        type(self).__name__: {
            "loaded_from": os.path.basename(self.owl_path),
            "num_classes": len(self.owl_classes),
            "num_object_properties": len(self.owl_object_properties),
            "num_data_properties": len(self.owl_data_properties),
            "num_annotation_properties": len(self.owl_annotation_properties),
            "num_individuals": len(self.owl_individuals),
            "reasoner_type": self.reasoner_type,
        }
    }

name property

Return the name of the ontology file.

OWLThing property

Return OWLThing.

OWLNothing property

Return OWLNoThing.

OWLTopObjectProperty property

Return OWLTopObjectProperty.

OWLBottomObjectProperty property

Return OWLBottomObjectProperty.

OWLTopDataProperty property

Return OWLTopDataProperty.

OWLBottomDataProperty property

Return OWLBottomDataProperty.

sibling_class_groups: List[List[str]] property

Return grouped sibling classes (with a common direct parent);

NOTE that only groups with size > 1 will be considered

get_entity_type(entity, return_singular=False) staticmethod

A handy method to get the type of an OWLObject entity.

Source code in src/deeponto/onto/ontology.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
@staticmethod
def get_entity_type(entity: OWLObject, return_singular: bool = False):
    """A handy method to get the `type` of an `OWLObject` entity."""
    if isinstance(entity, OWLClassExpression):
        return "Classes" if not return_singular else "Class"
    elif isinstance(entity, OWLObjectPropertyExpression):
        return "ObjectProperties" if not return_singular else "ObjectProperty"
    elif isinstance(entity, OWLDataPropertyExpression):
        return "DataProperties" if not return_singular else "DataProperty"
    elif isinstance(entity, OWLIndividual):
        return "Individuals" if not return_singular else "Individual"
    else:
        # NOTE: add further options in future
        pass

get_max_jvm_memory() staticmethod

Get the maximum heap size assigned to the JVM.

Source code in src/deeponto/onto/ontology.py
204
205
206
207
208
209
210
@staticmethod
def get_max_jvm_memory():
    """Get the maximum heap size assigned to the JVM."""
    if jpype.isJVMStarted():
        return int(Runtime.getRuntime().maxMemory())
    else:
        raise RuntimeError("Cannot retrieve JVM memory as it is not started.")

get_owl_object(iri)

Get an OWLObject given its IRI.

Source code in src/deeponto/onto/ontology.py
227
228
229
230
231
232
233
234
235
236
237
238
239
240
def get_owl_object(self, iri: str):
    """Get an `OWLObject` given its IRI."""
    if iri in self.owl_classes.keys():
        return self.owl_classes[iri]
    elif iri in self.owl_object_properties.keys():
        return self.owl_object_properties[iri]
    elif iri in self.owl_data_properties.keys():
        return self.owl_data_properties[iri]
    elif iri in self.owl_annotation_properties.keys():
        return self.owl_annotation_properties[iri]
    elif iri in self.owl_individuals.keys():
        return self.owl_individuals[iri]
    else:
        raise KeyError(f"Cannot retrieve unknown IRI: {iri}.")

get_iri(owl_object)

Get the IRI of an OWLObject. Raises an exception if there is no associated IRI.

Source code in src/deeponto/onto/ontology.py
242
243
244
245
246
247
def get_iri(self, owl_object: OWLObject):
    """Get the IRI of an `OWLObject`. Raises an exception if there is no associated IRI."""
    try:
        return str(owl_object.getIRI())
    except:
        raise RuntimeError("Input owl object does not have IRI.")

get_axiom_type(axiom) staticmethod

Get the axiom type (in str) for the given axiom.

Check full list at: http://owlcs.github.io/owlapi/apidocs_5/org/semanticweb/owlapi/model/AxiomType.html.

Source code in src/deeponto/onto/ontology.py
249
250
251
252
253
254
255
@staticmethod
def get_axiom_type(axiom: OWLAxiom):
    r"""Get the axiom type (in `str`) for the given axiom.

    Check full list at: <http://owlcs.github.io/owlapi/apidocs_5/org/semanticweb/owlapi/model/AxiomType.html>.
    """
    return str(axiom.getAxiomType())

get_all_axioms()

Return all axioms (in a list) asserted in the ontology.

Source code in src/deeponto/onto/ontology.py
257
258
259
def get_all_axioms(self):
    """Return all axioms (in a list) asserted in the ontology."""
    return list(self.owl_onto.getAxioms())

get_subsumption_axioms(entity_type='Classes')

Return subsumption axioms (subject to input entity type) asserted in the ontology.

Parameters:

Name Type Description Default
entity_type str

The entity type to be considered. Defaults to "Classes". Options are "Classes", "ObjectProperties", "DataProperties", and "AnnotationProperties".

'Classes'

Returns:

Type Description
List[OWLAxiom]

A list of equivalence axioms subject to input entity type.

Source code in src/deeponto/onto/ontology.py
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
def get_subsumption_axioms(self, entity_type: str = "Classes"):
    """Return subsumption axioms (subject to input entity type) asserted in the ontology.

    Args:
        entity_type (str, optional): The entity type to be considered. Defaults to `"Classes"`.
            Options are `"Classes"`, `"ObjectProperties"`, `"DataProperties"`, and `"AnnotationProperties"`.
    Returns:
        (List[OWLAxiom]): A list of equivalence axioms subject to input entity type.
    """
    if entity_type == "Classes":
        return list(self.owl_onto.getAxioms(AxiomType.SUBCLASS_OF))
    elif entity_type == "ObjectProperties":
        return list(self.owl_onto.getAxioms(AxiomType.SUB_OBJECT_PROPERTY))
    elif entity_type == "DataProperties":
        return list(self.owl_onto.getAxioms(AxiomType.SUB_DATA_PROPERTY))
    elif entity_type == "AnnotationProperties":
        return list(self.owl_onto.getAxioms(AxiomType.SUB_ANNOTATION_PROPERTY_OF))
    else:
        raise ValueError(f"Unknown entity type {entity_type}.")

get_equivalence_axioms(entity_type='Classes')

Return equivalence axioms (subject to input entity type) asserted in the ontology.

Parameters:

Name Type Description Default
entity_type str

The entity type to be considered. Defaults to "Classes". Options are "Classes", "ObjectProperties", and "DataProperties".

'Classes'

Returns:

Type Description
list[OWLAxiom]

A list of equivalence axioms subject to input entity type.

Source code in src/deeponto/onto/ontology.py
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
def get_equivalence_axioms(self, entity_type: str = "Classes"):
    """Return equivalence axioms (subject to input entity type) asserted in the ontology.

    Args:
        entity_type (str, optional): The entity type to be considered. Defaults to `"Classes"`.
            Options are `"Classes"`, `"ObjectProperties"`, and `"DataProperties"`.
    Returns:
        (list[OWLAxiom]): A list of equivalence axioms subject to input entity type.
    """
    if entity_type == "Classes":
        return list(self.owl_onto.getAxioms(AxiomType.EQUIVALENT_CLASSES))
    elif entity_type == "ObjectProperties":
        return list(self.owl_onto.getAxioms(AxiomType.EQUIVALENT_OBJECT_PROPERTIES))
    elif entity_type == "DataProperties":
        return list(self.owl_onto.getAxioms(AxiomType.EQUIVALENT_DATA_PROPERTIES))
    else:
        raise ValueError(f"Unknown entity type {entity_type}.")

get_assertion_axioms(entity_type='Classes')

Return assertion (ABox) axioms (subject to input entity type) asserted in the ontology.

Parameters:

Name Type Description Default
entity_type str

The entity type to be considered. Defaults to "Classes". Options are "Classes", "ObjectProperties", and "DataProperties".

'Classes'

Returns:

Type Description
list[OWLAxiom]

A list of assertion axioms subject to input entity type.

Source code in src/deeponto/onto/ontology.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
def get_assertion_axioms(self, entity_type: str = "Classes"):
    """Return assertion (ABox) axioms (subject to input entity type) asserted in the ontology.

    Args:
        entity_type (str, optional): The entity type to be considered. Defaults to `"Classes"`.
            Options are `"Classes"`, `"ObjectProperties"`, and `"DataProperties"`.
    Returns:
        (list[OWLAxiom]): A list of assertion axioms subject to input entity type.
    """
    if entity_type == "Classes":
        return list(self.owl_onto.getAxioms(AxiomType.CLASS_ASSERTION))
    elif entity_type == "ObjectProperties":
        return list(self.owl_onto.getAxioms(AxiomType.OBJECT_PROPERTY_ASSERTION))
    elif entity_type == "DataProperties":
        return list(self.owl_onto.getAxioms(AxiomType.DATA_PROPERTY_ASSERTION))
    elif entity_type == "Annotations":
        return list(self.owl_onto.getAxioms(AxiomType.ANNOTATION_ASSERTION))
    else:
        raise ValueError(f"Unknown entity type {entity_type}.")

get_asserted_parents(owl_object, named_only=False)

Get all the asserted parents of a given owl object.

Parameters:

Name Type Description Default
owl_object OWLObject

An owl object that could have a parent.

required
named_only bool

If True, return parents that are named classes.

False

Returns:

Type Description
set[OWLObject]

The parent set of the given owl object.

Source code in src/deeponto/onto/ontology.py
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
def get_asserted_parents(self, owl_object: OWLObject, named_only: bool = False):
    r"""Get all the asserted parents of a given owl object.

    Args:
        owl_object (OWLObject): An owl object that could have a parent.
        named_only (bool): If `True`, return parents that are named classes.
    Returns:
        (set[OWLObject]): The parent set of the given owl object.
    """
    entity_type = self.get_entity_type(owl_object)
    if entity_type == "Classes":
        parents = set(EntitySearcher.getSuperClasses(owl_object, self.owl_onto))
    elif entity_type.endswith("Properties"):
        parents = set(EntitySearcher.getSuperProperties(owl_object, self.owl_onto))
    else:
        raise ValueError(f"Unsupported entity type {entity_type}.")
    if named_only:
        parents = set([p for p in parents if self.check_named_entity(p)])
    return parents

get_asserted_children(owl_object, named_only=False)

Get all the asserted children of a given owl object.

Parameters:

Name Type Description Default
owl_object OWLObject

An owl object that could have a child.

required
named_only bool

If True, return children that are named classes.

False

Returns:

Type Description
set[OWLObject]

The children set of the given owl object.

Source code in src/deeponto/onto/ontology.py
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
def get_asserted_children(self, owl_object: OWLObject, named_only: bool = False):
    r"""Get all the asserted children of a given owl object.

    Args:
        owl_object (OWLObject): An owl object that could have a child.
        named_only (bool): If `True`, return children that are named classes.
    Returns:
        (set[OWLObject]): The children set of the given owl object.
    """
    entity_type = self.get_entity_type(owl_object)
    if entity_type == "Classes":
        children = set(EntitySearcher.getSubClasses(owl_object, self.owl_onto))
    elif entity_type.endswith("Properties"):
        children = set(EntitySearcher.getSubProperties(owl_object, self.owl_onto))
    else:
        raise ValueError(f"Unsupported entity type {entity_type}.")
    if named_only:
        children = set([c for c in children if self.check_named_entity(c)])
    return children

get_asserted_complex_classes(gci_only=False)

Get complex classes that occur in at least one of the ontology axioms.

Parameters:

Name Type Description Default
gci_only bool

If True, consider complex classes that occur in GCIs only; otherwise consider those that occur in equivalence axioms as well.

False

Returns:

Type Description
set[OWLClassExpression]

A set of complex classes.

Source code in src/deeponto/onto/ontology.py
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
def get_asserted_complex_classes(self, gci_only: bool = False):
    """Get complex classes that occur in at least one of the ontology axioms.

    Args:
        gci_only (bool): If `True`, consider complex classes that occur in GCIs only; otherwise consider
            those that occur in equivalence axioms as well.
    Returns:
        (set[OWLClassExpression]): A set of complex classes.
    """
    complex_classes = []

    for gci in self.get_subsumption_axioms("Classes"):
        super_class = gci.getSuperClass()
        sub_class = gci.getSubClass()
        if not OntologyReasoner.has_iri(super_class):
            complex_classes.append(super_class)
        if not OntologyReasoner.has_iri(sub_class):
            complex_classes.append(sub_class)

    # also considering equivalence axioms
    if not gci_only:
        for eq in self.get_equivalence_axioms("Classes"):
            gci = list(eq.asOWLSubClassOfAxioms())[0]
            super_class = gci.getSuperClass()
            sub_class = gci.getSubClass()
            if not OntologyReasoner.has_iri(super_class):
                complex_classes.append(super_class)
            if not OntologyReasoner.has_iri(sub_class):
                complex_classes.append(sub_class)

    return set(complex_classes)

get_annotations(owl_object, annotation_property_iri=None, annotation_language_tag=None, apply_lowercasing=False, normalise_identifiers=False)

Get the annotation literals of the given OWLObject.

Parameters:

Name Type Description Default
owl_object Union[OWLObject, str]

An OWLObject or its IRI.

required
annotation_property_iri str

Any particular annotation property IRI of interest. Defaults to None.

None
annotation_language_tag str

Any particular annotation language tag of interest; NOTE that not every annotation has a language tag, in this case assume it is in English. Defaults to None. Options are "en", "ge" etc.

None
apply_lowercasing bool

Whether or not to apply lowercasing to annotation literals. Defaults to False.

False
normalise_identifiers bool

Whether to normalise annotation text that is in the Java identifier format. Defaults to False.

False

Returns:

Type Description
set[str]

A set of annotation literals of the given OWLObject.

Source code in src/deeponto/onto/ontology.py
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
def get_annotations(
    self,
    owl_object: Union[OWLObject, str],
    annotation_property_iri: Optional[str] = None,
    annotation_language_tag: Optional[str] = None,
    apply_lowercasing: bool = False,
    normalise_identifiers: bool = False,
):
    """Get the annotation literals of the given `OWLObject`.

    Args:
        owl_object (Union[OWLObject, str]): An `OWLObject` or its IRI.
        annotation_property_iri (str, optional):
            Any particular annotation property IRI of interest. Defaults to `None`.
        annotation_language_tag (str, optional):
            Any particular annotation language tag of interest; NOTE that not every
            annotation has a language tag, in this case assume it is in English.
            Defaults to `None`. Options are `"en"`, `"ge"` etc.
        apply_lowercasing (bool): Whether or not to apply lowercasing to annotation literals.
            Defaults to `False`.
        normalise_identifiers (bool): Whether to normalise annotation text that is in the Java identifier format.
            Defaults to `False`.
    Returns:
        (set[str]): A set of annotation literals of the given `OWLObject`.
    """
    if isinstance(owl_object, str):
        owl_object = self.get_owl_object(owl_object)

    annotation_property = None
    if annotation_property_iri:
        # return an empty list if `annotation_property_iri` does not exist in this OWLOntology`
        annotation_property = self.get_owl_object(annotation_property_iri)

    annotations = []
    for annotation in EntitySearcher.getAnnotations(owl_object, self.owl_onto, annotation_property):
        annotation = annotation.getValue()
        # boolean that indicates whether the annotation's language is of interest
        fit_language = False
        if not annotation_language_tag:
            # it is set to `True` if `annotation_langauge` is not specified
            fit_language = True
        else:
            # restrict the annotations to a language if specified
            try:
                # NOTE: not every annotation has a language attribute
                fit_language = annotation.getLang() == annotation_language_tag
            except:
                # in the case when this annotation has no language tag
                # we assume it is in English
                if annotation_language_tag == "en":
                    fit_language = True

        if fit_language:
            # only get annotations that have a literal value
            if annotation.isLiteral():
                annotations.append(
                    process_annotation_literal(
                        str(annotation.getLiteral()), apply_lowercasing, normalise_identifiers
                    )
                )

    return uniqify(annotations)

check_consistency()

Check if the ontology is consistent according to the pre-loaded reasoner.

Source code in src/deeponto/onto/ontology.py
454
455
456
457
def check_consistency(self):
    """Check if the ontology is consistent according to the pre-loaded reasoner."""
    logging.info(f"Checking consistency with `{self.reasoner_type}` reasoner.")
    return self.reasoner.owl_reasoner.isConsistent()

check_named_entity(owl_object)

Check if the input entity is a named atomic entity. That is, it is not a complex entity, \(\top\), or \(\bot\).

Source code in src/deeponto/onto/ontology.py
459
460
461
462
463
464
465
466
467
468
469
470
def check_named_entity(self, owl_object: OWLObject):
    r"""Check if the input entity is a named atomic entity. That is,
    it is not a complex entity, $\top$, or $\bot$.
    """
    entity_type = self.get_entity_type(owl_object)
    top = TOP_BOTTOMS[entity_type].TOP
    bottom = TOP_BOTTOMS[entity_type].BOTTOM
    if OntologyReasoner.has_iri(owl_object):
        iri = str(owl_object.getIRI())
        # check if the entity is TOP or BOTTOM
        return iri != top and iri != bottom
    return False

check_deprecated(owl_object)

Check if the given OWL object is marked as deprecated according to \(\texttt{owl:deprecated}\).

NOTE: the string literal indicating deprecation is either 'true' or 'True'. Also, if \(\texttt{owl:deprecated}\) is not defined in this ontology, return False by default.

Source code in src/deeponto/onto/ontology.py
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
def check_deprecated(self, owl_object: OWLObject):
    r"""Check if the given OWL object is marked as deprecated according to $\texttt{owl:deprecated}$.

    NOTE: the string literal indicating deprecation is either `'true'` or `'True'`. Also, if $\texttt{owl:deprecated}$
    is not defined in this ontology, return `False` by default.
    """
    if not OWL_DEPRECATED in self.owl_annotation_properties.keys():
        # return False if owl:deprecated is not defined in this ontology
        return False

    deprecated = self.get_annotations(owl_object, annotation_property_iri=OWL_DEPRECATED)
    if deprecated and (list(deprecated)[0] == "true" or list(deprecated)[0] == "True"):
        return True
    else:
        return False

save_onto(save_path)

Save the ontology file to the given path.

Source code in src/deeponto/onto/ontology.py
518
519
520
def save_onto(self, save_path: str):
    """Save the ontology file to the given path."""
    self.owl_onto.saveOntology(IRI.create(File(save_path).toURI()))

build_annotation_index(annotation_property_iris=[RDFS_LABEL], entity_type='Classes', apply_lowercasing=False, normalise_identifiers=False)

Build an annotation index for a given type of entities.

Parameters:

Name Type Description Default
annotation_property_iris list[str]

A list of annotation property IRIs (it is possible that not every annotation property IRI is in use); if not provided, the built-in rdfs:label is considered. Defaults to [RDFS_LABEL].

[RDFS_LABEL]
entity_type str

The entity type to be considered. Defaults to "Classes". Options are "Classes", "ObjectProperties", "DataProperties", etc.

'Classes'
apply_lowercasing bool

Whether or not to apply lowercasing to annotation literals. Defaults to True.

False
normalise_identifiers bool

Whether to normalise annotation text that is in the Java identifier format. Defaults to False.

False

Returns:

Type Description
Tuple[dict, list[str]]

The built annotation index, and the list of annotation property IRIs that are in use.

Source code in src/deeponto/onto/ontology.py
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
def build_annotation_index(
    self,
    annotation_property_iris: List[str] = [RDFS_LABEL],
    entity_type: str = "Classes",
    apply_lowercasing: bool = False,
    normalise_identifiers: bool = False,
):
    """Build an annotation index for a given type of entities.

    Args:
        annotation_property_iris (list[str]): A list of annotation property IRIs (it is possible
            that not every annotation property IRI is in use); if not provided, the built-in
            `rdfs:label` is considered. Defaults to `[RDFS_LABEL]`.
        entity_type (str, optional): The entity type to be considered. Defaults to `"Classes"`.
            Options are `"Classes"`, `"ObjectProperties"`, `"DataProperties"`, etc.
        apply_lowercasing (bool): Whether or not to apply lowercasing to annotation literals.
            Defaults to `True`.
        normalise_identifiers (bool): Whether to normalise annotation text that is in the Java identifier format.
            Defaults to `False`.

    Returns:
        (Tuple[dict, list[str]]): The built annotation index, and the list of annotation property IRIs that are in use.
    """

    annotation_index = defaultdict(set)
    # example: Classes => owl_classes; ObjectProperties => owl_object_properties
    entity_type = "owl_" + split_java_identifier(entity_type).replace(" ", "_").lower()
    entity_index = getattr(self, entity_type)

    # preserve available annotation properties
    annotation_property_iris = [
        airi for airi in annotation_property_iris if airi in self.owl_annotation_properties.keys()
    ]

    # build the annotation index without duplicated literals
    for airi in annotation_property_iris:
        for iri, entity in entity_index.items():
            annotation_index[iri].update(
                self.get_annotations(
                    owl_object=entity,
                    annotation_property_iri=airi,
                    annotation_language_tag=None,
                    apply_lowercasing=apply_lowercasing,
                    normalise_identifiers=normalise_identifiers,
                )
            )

    return annotation_index, annotation_property_iris

build_inverted_annotation_index(annotation_index, tokenizer) staticmethod

Build an inverted annotation index given an annotation index and a tokenizer.

Source code in src/deeponto/onto/ontology.py
571
572
573
574
@staticmethod
def build_inverted_annotation_index(annotation_index: dict, tokenizer: Tokenizer):
    """Build an inverted annotation index given an annotation index and a tokenizer."""
    return InvertedIndex(annotation_index, tokenizer)

add_axiom(owl_axiom, return_undo=True)

Add an axiom into the current ontology.

Parameters:

Name Type Description Default
owl_axiom OWLAxiom

An axiom to be added.

required
return_undo bool

Returning the undo operation or not. Defaults to True.

True
Source code in src/deeponto/onto/ontology.py
576
577
578
579
580
581
582
583
584
585
586
587
def add_axiom(self, owl_axiom: OWLAxiom, return_undo: bool = True):
    """Add an axiom into the current ontology.

    Args:
        owl_axiom (OWLAxiom): An axiom to be added.
        return_undo (bool, optional): Returning the undo operation or not. Defaults to `True`.
    """
    change = AddAxiom(self.owl_onto, owl_axiom)
    result = self.owl_onto.applyChange(change)
    logger.info(f"[{str(result)}] Adding the axiom {str(owl_axiom)} into the ontology.")
    if return_undo:
        return change.reverseChange()

remove_axiom(owl_axiom, return_undo=True)

Remove an axiom from the current ontology.

Parameters:

Name Type Description Default
owl_axiom OWLAxiom

An axiom to be removed.

required
return_undo bool

Returning the undo operation or not. Defaults to True.

True
Source code in src/deeponto/onto/ontology.py
589
590
591
592
593
594
595
596
597
598
599
600
def remove_axiom(self, owl_axiom: OWLAxiom, return_undo: bool = True):
    """Remove an axiom from the current ontology.

    Args:
        owl_axiom (OWLAxiom): An axiom to be removed.
        return_undo (bool, optional): Returning the undo operation or not. Defaults to `True`.
    """
    change = RemoveAxiom(self.owl_onto, owl_axiom)
    result = self.owl_onto.applyChange(change)
    logger.info(f"[{str(result)}] Removing the axiom {str(owl_axiom)} from the ontology.")
    if return_undo:
        return change.reverseChange()

replace_entity(owl_object, entity_iri, replacement_iri)

Replace an entity in a class expression with another entity.

Parameters:

Name Type Description Default
owl_object OWLObject

An OWLObject entity to be manipulated.

required
entity_iri str

IRI of the entity to be replaced.

required
replacement_iri str

IRI of the entity to replace.

required

Returns:

Type Description
OWLObject

The changed OWLObject entity.

Source code in src/deeponto/onto/ontology.py
602
603
604
605
606
607
608
609
610
611
612
613
614
615
def replace_entity(self, owl_object: OWLObject, entity_iri: str, replacement_iri: str):
    """Replace an entity in a class expression with another entity.

    Args:
        owl_object (OWLObject): An `OWLObject` entity to be manipulated.
        entity_iri (str): IRI of the entity to be replaced.
        replacement_iri (str): IRI of the entity to replace.

    Returns:
        (OWLObject): The changed `OWLObject` entity.
    """
    iri_dict = {IRI.create(entity_iri): IRI.create(replacement_iri)}
    replacer = OWLObjectDuplicator(self.owl_data_factory, iri_dict)
    return replacer.duplicateObject(owl_object)

Last update: April 18, 2023
Created: January 13, 2023
GitHub: @Lawhy   Personal Page: yuanhe.wiki