Skip to content

Commit 9762fbc

Browse files
authored
Merge pull request #47 from dice-group/refactoring_owlapi_adaptor
Refactoring owlapi adaptor
2 parents c716614 + 963bb76 commit 9762fbc

File tree

1 file changed

+102
-41
lines changed

1 file changed

+102
-41
lines changed

owlapy/owlapi_adaptor.py

Lines changed: 102 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -6,97 +6,158 @@
66
from owlapy.iri import IRI
77
from owlapy.owl_individual import OWLNamedIndividual
88
from owlapy.render import owl_expression_to_manchester
9-
9+
from typing import List
1010

1111
class OWLAPIAdaptor:
12+
"""
13+
A class to interface with the OWL API using the HermiT reasoner, enabling ontology management,
14+
reasoning, and parsing class expressions in Manchester OWL Syntax.
15+
16+
Attributes:
17+
path (str): The file path to the ontology.
18+
name_reasoner (str): The reasoner to be used, default is "HermiT".
19+
manager: The OWL ontology manager.
20+
ontology: The loaded OWL ontology.
21+
reasoner: The HermiT reasoner for the ontology.
22+
parser: The Manchester OWL Syntax parser.
23+
renderer: The Manchester OWL Syntax renderer.
24+
__is_open (bool): Flag to check if the JVM is open.
25+
"""
26+
def __init__(self, path: str, name_reasoner: str = "HermiT"):
27+
"""
28+
Initialize the OWLAPIAdaptor with a path to an ontology and a reasoner name.
29+
30+
Args:
31+
path (str): The file path to the ontology.
32+
name_reasoner (str, optional): The reasoner to be used. Defaults to "HermiT".
1233
13-
def __init__(self, path: str):
34+
Raises:
35+
AssertionError: If the provided reasoner name is not implemented.
36+
"""
1437
self.path = path
38+
assert name_reasoner in ["HermiT"], f"{name_reasoner} is not implemented. Please use HermiT"
39+
self.name_reasoner = name_reasoner
40+
# Attributes are initialized as JVMStarted is started
41+
# () Manager is needed to load an ontology
42+
self.manager = None
43+
# () Load a local ontology using the manager
44+
self.ontology = None
45+
# () Create a HermiT reasoner for the loaded ontology
46+
self.reasoner = None
47+
self.parser = None
48+
# () A manchester renderer to render owlapi ce to manchester syntax
49+
self.renderer = None
50+
self.open()
51+
self.__is_open = True
52+
53+
def __exit__(self, exc_type, exc_val, exc_tb):
54+
"""Shuts down the java virtual machine hosted by jpype."""
55+
self.close()
1556

1657
def __enter__(self):
17-
"""Initialization via the `with` statement"""
58+
"""
59+
Initialization via the `with` statement.
60+
61+
Returns:
62+
OWLAPIAdaptor: The current instance.
63+
"""
64+
if not self.__is_open:
65+
self.open()
66+
return self
67+
68+
def open(self):
69+
"""
70+
Start the JVM with jar dependencies, import necessary OWL API dependencies, and initialize attributes.
71+
"""
1872
if not jpype.isJVMStarted():
1973
# Start a java virtual machine using the dependencies in the respective folder:
2074
if os.getcwd()[-6:] == "owlapy":
2175
jar_folder = "jar_dependencies"
2276
else:
2377
jar_folder = "../jar_dependencies"
2478
jar_files = [os.path.join(jar_folder, f) for f in os.listdir(jar_folder) if f.endswith('.jar')]
79+
# Starting JVM.
2580
jpype.startJVM(classpath=jar_files)
2681

2782
# Import Java classes
2883
from org.semanticweb.owlapi.apibinding import OWLManager
2984
from java.io import File
30-
from org.semanticweb.HermiT import ReasonerFactory
85+
if self.name_reasoner == "HermiT":
86+
from org.semanticweb.HermiT import ReasonerFactory
87+
else:
88+
raise NotImplementedError("Not implemented")
89+
3190
from org.semanticweb.owlapi.manchestersyntax.parser import ManchesterOWLSyntaxClassExpressionParser
3291
from org.semanticweb.owlapi.util import BidirectionalShortFormProviderAdapter, SimpleShortFormProvider
3392
from org.semanticweb.owlapi.expression import ShortFormEntityChecker
3493
from java.util import HashSet
3594
from org.semanticweb.owlapi.manchestersyntax.renderer import ManchesterOWLSyntaxOWLObjectRendererImpl
3695

37-
# Manager is needed to load an ontology
96+
# () Manager is needed to load an ontology
3897
self.manager = OWLManager.createOWLOntologyManager()
39-
# Load a local ontology using the manager
40-
file = File(self.path)
41-
self.ontology = self.manager.loadOntologyFromOntologyDocument(file)
98+
# () Load a local ontology using the manager
99+
self.ontology = self.manager.loadOntologyFromOntologyDocument(File(self.path))
100+
# () Create a HermiT reasoner for the loaded ontology
101+
self.reasoner = ReasonerFactory().createReasoner(self.ontology)
42102

43-
# Create a HermiT reasoner for the loaded ontology
44-
reasoner_factory = ReasonerFactory()
45-
self.reasoner = reasoner_factory.createReasoner(self.ontology)
46-
47-
# Create a manchester parser and all the necessary attributes for parsing manchester syntax string to owlapi ce
48-
short_form_provider = SimpleShortFormProvider()
103+
# () Create a manchester parser and all the necessary attributes for parsing manchester syntax string to owlapi ce
49104
ontology_set = HashSet()
50105
ontology_set.add(self.ontology)
51-
bidi_provider = BidirectionalShortFormProviderAdapter(self.manager, ontology_set, short_form_provider)
106+
bidi_provider = BidirectionalShortFormProviderAdapter(self.manager, ontology_set, SimpleShortFormProvider())
52107
entity_checker = ShortFormEntityChecker(bidi_provider)
53108
self.parser = ManchesterOWLSyntaxClassExpressionParser(self.manager.getOWLDataFactory(), entity_checker)
54-
55109
# A manchester renderer to render owlapi ce to manchester syntax
56110
self.renderer = ManchesterOWLSyntaxOWLObjectRendererImpl()
57111

58-
return self
112+
def close(self, *args, **kwargs) -> None:
113+
"""Shuts down the java virtual machine hosted by jpype."""
114+
if jpype.isJVMStarted() and not jpype.isThreadAttachedToJVM():
115+
jpype.shutdownJVM()
116+
self.__is_open = False
59117

60118
def convert_to_owlapi(self, ce: OWLClassExpression):
61-
""" Converts an owlapy ce to an owlapi ce.
119+
"""
120+
Converts an OWLAPY class expression to an OWLAPI class expression.
62121
63-
Args:
64-
ce (OWLClassExpression): class expression in owlapy format to be converted.
122+
Args:
123+
ce (OWLClassExpression): The class expression in OWLAPY format to be converted.
65124
66-
Return:
67-
Class expression in owlapi format.
125+
Returns:
126+
The class expression in OWLAPI format.
68127
"""
69128
return self.parser.parse(owl_expression_to_manchester(ce))
70129

71130
def convert_from_owlapi(self, ce, namespace: str) -> OWLClassExpression:
72-
"""Converts an owlapi ce to an owlapy ce.
131+
"""
132+
Converts an OWLAPI class expression to an OWLAPY class expression.
73133
74-
Args:
75-
ce: Class expression in owlapi format.
76-
namespace: Ontology's namespace where class expression belongs.
134+
Args:
135+
ce: The class expression in OWLAPI format.
136+
namespace (str): The ontology's namespace where the class expression belongs.
77137
78-
Return:
79-
Class expression in owlapy format.
138+
Returns:
139+
OWLClassExpression: The class expression in OWLAPY format.
80140
"""
81141
return manchester_to_owl_expression(str(self.renderer.render(ce)), namespace)
82142

83-
def instances(self, ce: OWLClassExpression):
84-
""" Get the instances for a given class expression using HermiT.
85-
Args:
86-
ce: Class expression in owlapy format.
143+
def instances(self, ce: OWLClassExpression)->List[OWLNamedIndividual]:
144+
"""
145+
Get the instances for a given class expression using HermiT.
146+
147+
Args:
148+
ce (OWLClassExpression): The class expression in OWLAPY format.
87149
88-
Return:
89-
Individuals which are classified by the given class expression.
150+
Returns:
151+
list: A list of individuals classified by the given class expression.
90152
"""
91153
inds = self.reasoner.getInstances(self.convert_to_owlapi(ce), False).getFlattened()
92154
return [OWLNamedIndividual(IRI.create(str(ind)[1:-1])) for ind in inds]
93155

94156
def has_consistent_ontology(self) -> bool:
95-
""" Check if the used ontology is consistent."""
96-
return self.reasoner.isConsistent()
97-
98-
def __exit__(self, exc_type, exc_val, exc_tb):
99-
"""Shuts down the java virtual machine hosted by jpype."""
100-
if jpype.isJVMStarted() and not jpype.isThreadAttachedToJVM():
101-
jpype.shutdownJVM()
157+
"""
158+
Check if the used ontology is consistent.
102159
160+
Returns:
161+
bool: True if the ontology is consistent, False otherwise.
162+
"""
163+
return self.reasoner.isConsistent()

0 commit comments

Comments
 (0)