Skip to content

Commit

Permalink
Deprecating "Ontology Manager"
Browse files Browse the repository at this point in the history
  • Loading branch information
alkidbaci committed Feb 13, 2025
1 parent 729c4fc commit eb7bebc
Show file tree
Hide file tree
Showing 16 changed files with 87 additions and 196 deletions.
17 changes: 8 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,10 @@ owlapy --path_ontology "KGs/Family/family-benchmark_rich_background.owl" --infer
<details><summary> Click me! </summary>

```python
from owlapy.owl_ontology_manager import SyncOntologyManager
from owlapy.owl_ontology import SyncOntology

ontology_path = "KGs/Family/father.owl"
onto = SyncOntologyManager().load_ontology(ontology_path)
onto = SyncOntology(ontology_path)

print({owl_class.reminder for owl_class in onto.classes_in_signature()})
# {'Thing', 'female', 'male', 'person'}
Expand Down Expand Up @@ -112,10 +112,9 @@ for axiom in onto.get_abox_axioms():
from owlapy.class_expression import OWLClass, OWLObjectIntersectionOf, OWLObjectSomeValuesFrom
from owlapy.owl_property import OWLObjectProperty
from owlapy import owl_expression_to_sparql, owl_expression_to_dl
from owlapy.owl_ontology_manager import OntologyManager
from owlapy.owl_axiom import OWLDeclarationAxiom, OWLClassAssertionAxiom
from owlapy.owl_individual import OWLNamedIndividual, IRI
from owlapy.static_funcs import create_ontology
from owlapy.owl_individual import OWLNamedIndividual
from owlapy.util_owl_static_funcs import create_ontology
# Using owl classes to create a complex class expression
male = OWLClass("http://example.com/society#male")
hasChild = OWLObjectProperty("http://example.com/society#hasChild")
Expand Down Expand Up @@ -155,14 +154,14 @@ OWL objects in [owlapy api](https://dice-group.github.io/owlapy/autoapi/owlapy/i
<details><summary> Click me! </summary>

```python
from owlapy.owl_ontology_manager import OntologyManager
from owlapy.owl_reasoner import SyncReasoner
from owlapy.static_funcs import stopJVM
from owlapy.owl_ontology import Ontology

ontology_path = "KGs/Family/family-benchmark_rich_background.owl"
# Available OWL Reasoners: 'HermiT', 'Pellet', 'JFact', 'Openllet'
sync_reasoner = SyncReasoner(ontology = ontology_path, reasoner="Pellet")
onto = OntologyManager().load_ontology(ontology_path)
onto = Ontology(ontology_path)
# Iterate over defined owl Classes in the signature
for i in onto.classes_in_signature():
# Performing type inference with Pellet
Expand Down Expand Up @@ -206,7 +205,7 @@ Check also the [examples](https://github.com/dice-group/owlapy/tree/develop/exam
<details><summary> Click me! </summary>

```python
from owlapy.owl_ontology_manager import SyncOntologyManager
from owlapy.owl_ontology import SyncOntology
from owlapy.util_owl_static_funcs import csv_to_rdf_kg
import pandas as pd
from sklearn.datasets import load_iris
Expand All @@ -216,7 +215,7 @@ df.to_csv("iris_dataset.csv", index=False)
path_kg = "iris_kg.owl"
# Construct an RDF Knowledge Graph from a CSV file
csv_to_rdf_kg(path_csv="iris_dataset.csv", path_kg=path_kg, namespace="http://owlapy.com/iris")
onto = SyncOntologyManager().load_ontology(path_kg)
onto = SyncOntology(path_kg)
assert len(onto.get_abox_axioms()) == 750

```
Expand Down
6 changes: 4 additions & 2 deletions examples/ontology_reasoning_retrieval_agreements.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from owlapy.owl_reasoner import SyncReasoner
from owlapy import OntologyManager
from owlapy.owl_ontology import Ontology
from owlapy.class_expression import OWLClassExpression
from typing import Dict
ontology_path = "../KGs/Family/family-benchmark_rich_background.owl"
# () Load ontology
onto = OntologyManager().load_ontology(ontology_path)
onto = Ontology(ontology_path, load=True)

# () Initialize Reasoners
reasoners = dict()
Expand All @@ -13,6 +13,7 @@
reasoners["JFact"] = SyncReasoner(ontology=ontology_path, reasoner="JFact")
reasoners["Openllet"] = SyncReasoner(ontology=ontology_path, reasoner="Openllet")


def compute_agreements(owl_reasoners:Dict[str,SyncReasoner], expression: OWLClassExpression, verbose=False):
if verbose:
print(f"Computing agreements between Reasoners on {expression}...",end="\t")
Expand All @@ -27,6 +28,7 @@ def compute_agreements(owl_reasoners:Dict[str,SyncReasoner], expression: OWLClas
print(f"Successful:{flag}")
return flag


# () Iterate over named classes
for c in onto.classes_in_signature():
# reasoners must agree
Expand Down
4 changes: 2 additions & 2 deletions owlapy/abstracts/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .abstract_owl_ontology_manager import AbstractOWLOntologyManager, AbstractOWLOntologyChange, AbstractOWLOntology
from .abstract_owl_reasoner import AbstractOWLReasoner
from .abstract_owl_ontology import AbstractOWLOntology

__all__ = ['AbstractOWLOntologyManager', 'AbstractOWLOntologyChange', 'AbstractOWLOntology', 'AbstractOWLReasoner']
__all__ = ['AbstractOWLOntology', 'AbstractOWLReasoner']
3 changes: 0 additions & 3 deletions owlapy/abstracts/abstract_owl_ontology.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from owlapy.owl_object import OWLObject
from owlapy.owl_property import OWLDataProperty, OWLObjectProperty

_M = TypeVar('_M', bound='OWLOntologyManager') # noqa: F821
_OI = TypeVar('_OI', bound='OWLOntologyID') # noqa: F821


Expand All @@ -20,8 +19,6 @@ class AbstractOWLOntology(OWLObject, metaclass=ABCMeta):
An ontology can have an ontology IRI which can be used to identify the ontology. If it has an ontology IRI then
it may also have an ontology version IRI. Since OWL 2, an ontology need not have an ontology IRI. (See the OWL 2
Structural Specification).
An ontology cannot be modified directly. Changes must be applied via its OWLOntologyManager.
"""
__slots__ = ()
type_index: Final = 1
Expand Down
70 changes: 0 additions & 70 deletions owlapy/abstracts/abstract_owl_ontology_manager.py

This file was deleted.

6 changes: 5 additions & 1 deletion owlapy/owl_ontology.py
Original file line number Diff line number Diff line change
Expand Up @@ -1005,7 +1005,11 @@ def __init__(self, path: Union[IRI, str], load: bool = True):
if isinstance(path, IRI):
self.owlapi_ontology = self.owlapi_manager.createOntology(Stream.empty(), owlapi_IRI.create(path.str))
else:
raise NotImplementedError("Cant initialize a new ontology using path. Use IRI instead")
try:
self.owlapi_ontology = self.owlapi_manager.createOntology(Stream.empty(),
owlapi_IRI.create(path))
except Exception as e:
raise NotImplementedError("Cant initialize a new ontology using path. Use IRI instead")
else: # means we are loading an existing ontology
self.owlapi_ontology = self.owlapi_manager.loadOntologyFromOntologyDocument(File(file_path))
self.mapper = OWLAPIMapper()
Expand Down
3 changes: 1 addition & 2 deletions owlapy/owl_reasoner.py
Original file line number Diff line number Diff line change
Expand Up @@ -1040,8 +1040,7 @@ def __init__(self, ontology: Union[SyncOntology, str], reasoner="HermiT"):
if isinstance(ontology, SyncOntology):
self.ontology = ontology
elif isinstance(ontology, str):
manager = OWLManager.createOWLOntologyManager()
self.ontology = manager.load_ontology(ontology)
self.ontology = SyncOntology(ontology)

self._owlapi_manager = self.ontology.owlapi_manager
self._owlapi_ontology = self.ontology.get_owlapi_ontology()
Expand Down
12 changes: 2 additions & 10 deletions owlapy/static_funcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
import jpype
import jpype.imports
import pkg_resources
from owlapy.owl_ontology import SyncOntology, Ontology

# NOTE: Static functions closely related with owl classes should be placed in utils.py not here
# NOTE: Static functions closely related with owl classes should be placed in utils.py
# or util_owl_static_funcs.py not here


def move(*args):
Expand Down Expand Up @@ -58,11 +58,3 @@ def stopJVM() -> None:
if jpype.isJVMStarted():
jpype.detachThreadFromJVM()
jpype.shutdownJVM()


def create_ontology(iri, with_owlapi=False):
""" A convenient function"""
if with_owlapi:
return SyncOntology(iri, load=False)
else:
return Ontology(iri, load=False)
36 changes: 20 additions & 16 deletions owlapy/util_owl_static_funcs.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from .owl_ontology import Ontology, SyncOntology
from .owl_ontology_manager import OntologyManager
from .class_expression import OWLClassExpression, OWLClass
from .owl_individual import OWLNamedIndividual
from .iri import IRI
Expand All @@ -11,10 +10,11 @@
from tqdm import tqdm
import pandas as pd


def save_owl_class_expressions(expressions: OWLClassExpression | List[OWLClassExpression],
path: str = 'predictions',
rdf_format: str = 'rdfxml',
namespace:str=None) -> None:
namespace: str = None) -> None:
"""
Saves a set of OWL class expressions to an ontology file in RDF/XML format.
Expand Down Expand Up @@ -49,20 +49,20 @@ def save_owl_class_expressions(expressions: OWLClassExpression | List[OWLClassEx
if isinstance(expressions, OWLClassExpression):
expressions = [expressions]

namespace= 'https://dice-research.org/predictions#' if namespace is None else namespace
namespace = 'https://dice-research.org/predictions#' if namespace is None else namespace
assert "#" == namespace[-1], "namespace must end with #"
# Initialize an Ontology Manager.
manager = OntologyManager()
# Create an ontology given an ontology manager.
ontology:Ontology = manager.create_ontology(namespace)
ontology: Ontology = Ontology(namespace, load=False)
# () Iterate over concepts
for th, i in enumerate(expressions):
cls_a = OWLClass(IRI.create(namespace, str(th)))
equivalent_classes_axiom = OWLEquivalentClassesAxiom([cls_a, i])
ontology.add_axiom(equivalent_classes_axiom)
ontology.save(path=path, inplace=False, rdf_format=rdf_format)

def csv_to_rdf_kg(path_csv:str=None,path_kg:str=None,namespace:str=None):

def csv_to_rdf_kg(path_csv: str = None, path_kg: str = None, namespace: str = None):
"""
Transfroms a CSV file to an RDF Knowledge Graph in RDF/XML format.
Expand All @@ -87,24 +87,21 @@ def csv_to_rdf_kg(path_csv:str=None,path_kg:str=None,namespace:str=None):
>>> print("Dataset saved as iris_dataset.csv")
>>> csv_to_rdf_kg("iris_dataset.csv")
"""
from owlapy.owl_ontology_manager import SyncOntologyManager
assert path_csv is not None, "path cannot be None"
assert os.path.exists(path_csv), f"path **{path_csv}**does not exist."
assert path_kg is not None, f"path_kg cannot be None.Currently {path_kg}"
assert namespace is not None, "namespace cannot be None"
assert namespace[:7]=="http://", "First characters of namespace must be 'http://'"
assert namespace[:7] == "http://", "First characters of namespace must be 'http://'"

# Initialize an Ontology Manager.
manager = SyncOntologyManager()
# Create an ontology given an ontology manager.
ontology:SyncOntology = manager.create_ontology(namespace)
ontology: SyncOntology = SyncOntology(namespace, load=False)

# Read the CSV file
df = pd.read_csv(path_csv)

# () Iterate over rows
for index, row in (tqdm_bar := tqdm(df.iterrows()) ):
individual=OWLNamedIndividual(f"{namespace}#{str(index)}".replace(" ","_"))
for index, row in (tqdm_bar := tqdm(df.iterrows())):
individual = OWLNamedIndividual(f"{namespace}#{str(index)}".replace(" ", "_"))
tqdm_bar.set_description_str(f"Creating RDF Graph from Row:{index}")
# column_name is considered as a predicate
# value is considered as a data property
Expand All @@ -126,6 +123,7 @@ def csv_to_rdf_kg(path_csv:str=None,path_kg:str=None,namespace:str=None):
f"has not been decided")
ontology.save(path=path_kg)


def rdf_kg_to_csv(path_kg: str = None, path_csv: str = None):
"""
Constructs a CSV file from an RDF Knowledge Graph (RDF/XML)
Expand All @@ -145,16 +143,14 @@ def rdf_kg_to_csv(path_kg: str = None, path_csv: str = None):
"""
import os
import pandas as pd
from owlapy.owl_ontology_manager import SyncOntologyManager

# Validate arguments
assert path_kg is not None, "path_kg cannot be None"
assert path_csv is not None, "path_csv cannot be None"
assert os.path.exists(path_kg), f"RDF Knowledge Graph file {path_kg} does not exist."

# Load the ontology
manager = SyncOntologyManager()
ontology = manager.load_ontology(path_kg)
ontology = SyncOntology(path_kg, load=True)
# Extract individuals and data property assertions
rows = {}
columns_list = []
Expand Down Expand Up @@ -206,3 +202,11 @@ def rdf_kg_to_csv(path_kg: str = None, path_csv: str = None):
df = pd.DataFrame(data_list, columns=columns)
df.to_csv(path_csv, index=False, na_rep="")
print(f"CSV reconstructed and saved to {path_csv}")


def create_ontology(iri, with_owlapi=False):
""" A convenient function"""
if with_owlapi:
return SyncOntology(iri, load=False)
else:
return Ontology(iri, load=False)
3 changes: 1 addition & 2 deletions tests/test_ontology.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import unittest
from owlapy.owl_ontology_manager import RDFLibOntologyManager
from owlapy.owl_ontology import SyncOntology, Ontology
from owlapy.owl_ontology import RDFLibOntology

Expand All @@ -11,7 +10,7 @@ def test_counting(self):
o_owlready: Ontology
o_owlready = Ontology(ontology_iri="KGs/Family/father.owl")
o_rdf: RDFLibOntology
o_rdf = RDFLibOntologyManager().load_ontology(path="KGs/Family/father.owl")
o_rdf = RDFLibOntology(path="KGs/Family/father.owl")

assert len({i for i in o_sync.get_tbox_axioms()})==len({i for i in o_rdf.get_tbox_axioms()})
assert len({i for i in o_sync.get_abox_axioms()})==len({i for i in o_rdf.get_abox_axioms()})
Loading

0 comments on commit eb7bebc

Please sign in to comment.