66from owlapy .iri import IRI
77from owlapy .owl_individual import OWLNamedIndividual
88from owlapy .render import owl_expression_to_manchester
9+ from typing import List
910
10-
11- # TODO:What are the downsides of start() close() fashion ?:
1211class 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".
1333
14- def __init__ (self , path : str , reasoner : str = "HermiT" ):
34+ Raises:
35+ AssertionError: If the provided reasoner name is not implemented.
36+ """
1537 self .path = path
16- assert reasoner in ["HermiT" ], f"{ reasoner } is not implemented. Please use HermiT"
17- self .reasoner = reasoner
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
1852
1953 def __exit__ (self , exc_type , exc_val , exc_tb ):
2054 """Shuts down the java virtual machine hosted by jpype."""
21- if jpype .isJVMStarted () and not jpype .isThreadAttachedToJVM ():
22- jpype .shutdownJVM ()
55+ self .close ()
2356
2457 def __enter__ (self ):
25- """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+ """
2672 if not jpype .isJVMStarted ():
2773 # Start a java virtual machine using the dependencies in the respective folder:
2874 if os .getcwd ()[- 6 :] == "owlapy" :
@@ -36,7 +82,7 @@ def __enter__(self):
3682 # Import Java classes
3783 from org .semanticweb .owlapi .apibinding import OWLManager
3884 from java .io import File
39- if self .reasoner == "HermiT" :
85+ if self .name_reasoner == "HermiT" :
4086 from org .semanticweb .HermiT import ReasonerFactory
4187 else :
4288 raise NotImplementedError ("Not implemented" )
@@ -60,105 +106,58 @@ def __enter__(self):
60106 bidi_provider = BidirectionalShortFormProviderAdapter (self .manager , ontology_set , SimpleShortFormProvider ())
61107 entity_checker = ShortFormEntityChecker (bidi_provider )
62108 self .parser = ManchesterOWLSyntaxClassExpressionParser (self .manager .getOWLDataFactory (), entity_checker )
63-
64109 # A manchester renderer to render owlapi ce to manchester syntax
65110 self .renderer = ManchesterOWLSyntaxOWLObjectRendererImpl ()
66111
67- 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
68117
69118 def convert_to_owlapi (self , ce : OWLClassExpression ):
70- """ Converts an owlapy ce to an owlapi ce.
119+ """
120+ Converts an OWLAPY class expression to an OWLAPI class expression.
71121
72- Args:
73- ce (OWLClassExpression): class expression in owlapy format to be converted.
122+ Args:
123+ ce (OWLClassExpression): The class expression in OWLAPY format to be converted.
74124
75- Return :
76- Class expression in owlapi format.
125+ Returns :
126+ The class expression in OWLAPI format.
77127 """
78128 return self .parser .parse (owl_expression_to_manchester (ce ))
79129
80130 def convert_from_owlapi (self , ce , namespace : str ) -> OWLClassExpression :
81- """Converts an owlapi ce to an owlapy ce.
131+ """
132+ Converts an OWLAPI class expression to an OWLAPY class expression.
82133
83- Args:
84- ce: Class expression in owlapi format.
85- 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.
86137
87- Return :
88- Class expression in owlapy format.
138+ Returns :
139+ OWLClassExpression: The class expression in OWLAPY format.
89140 """
90141 return manchester_to_owl_expression (str (self .renderer .render (ce )), namespace )
91142
92- def instances (self , ce : OWLClassExpression ):
93- """ Get the instances for a given class expression using HermiT.
94- Args:
95- 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.
96149
97- Return :
98- Individuals which are classified by the given class expression.
150+ Returns :
151+ list: A list of individuals classified by the given class expression.
99152 """
100153 inds = self .reasoner .getInstances (self .convert_to_owlapi (ce ), False ).getFlattened ()
101154 return [OWLNamedIndividual (IRI .create (str (ind )[1 :- 1 ])) for ind in inds ]
102155
103156 def has_consistent_ontology (self ) -> bool :
104- """ Check if the used ontology is consistent."""
105- return self .reasoner .isConsistent ()
106-
107-
108- class DemoOWLAPIAdaptor (OWLAPIAdaptor ):
109-
110- def __init__ (self , * args , ** kwargs ):
111-
112- super ().__init__ (* args , ** kwargs )
113- self .__start ()
114-
115- @staticmethod
116- def close (* args , ** kwargs ):
117- """Shuts down the java virtual machine hosted by jpype."""
118- if jpype .isJVMStarted () and not jpype .isThreadAttachedToJVM ():
119- jpype .shutdownJVM ()
120-
121- def __start (self ):
122- """Initialization via the `with` statement"""
123- if not jpype .isJVMStarted ():
124- # Start a java virtual machine using the dependencies in the respective folder:
125- if os .getcwd ()[- 6 :] == "owlapy" :
126- jar_folder = "jar_dependencies"
127- else :
128- jar_folder = "../jar_dependencies"
129- jar_files = [os .path .join (jar_folder , f ) for f in os .listdir (jar_folder ) if f .endswith ('.jar' )]
130- # Starting JVM.
131- jpype .startJVM (classpath = jar_files )
132-
133- # Import Java classes
134- from org .semanticweb .owlapi .apibinding import OWLManager
135- from java .io import File
136- if self .reasoner == "HermiT" :
137- from org .semanticweb .HermiT import ReasonerFactory
138- else :
139- raise NotImplementedError ("Not implemented" )
140-
141- from org .semanticweb .owlapi .manchestersyntax .parser import ManchesterOWLSyntaxClassExpressionParser
142- from org .semanticweb .owlapi .util import BidirectionalShortFormProviderAdapter , SimpleShortFormProvider
143- from org .semanticweb .owlapi .expression import ShortFormEntityChecker
144- from java .util import HashSet
145- from org .semanticweb .owlapi .manchestersyntax .renderer import ManchesterOWLSyntaxOWLObjectRendererImpl
146-
147- # () Manager is needed to load an ontology
148- self .manager = OWLManager .createOWLOntologyManager ()
149- # () Load a local ontology using the manager
150- self .ontology = self .manager .loadOntologyFromOntologyDocument (File (self .path ))
151- # () Create a HermiT reasoner for the loaded ontology
152- self .reasoner = ReasonerFactory ().createReasoner (self .ontology )
153-
154- # () Create a manchester parser and all the necessary attributes for parsing manchester syntax string to owlapi ce
155- ontology_set = HashSet ()
156- ontology_set .add (self .ontology )
157- bidi_provider = BidirectionalShortFormProviderAdapter (self .manager , ontology_set , SimpleShortFormProvider ())
158- entity_checker = ShortFormEntityChecker (bidi_provider )
159- self .parser = ManchesterOWLSyntaxClassExpressionParser (self .manager .getOWLDataFactory (), entity_checker )
160-
161- # A manchester renderer to render owlapi ce to manchester syntax
162- self .renderer = ManchesterOWLSyntaxOWLObjectRendererImpl ()
157+ """
158+ Check if the used ontology is consistent.
163159
164- return self
160+ Returns:
161+ bool: True if the ontology is consistent, False otherwise.
162+ """
163+ return self .reasoner .isConsistent ()
0 commit comments