From f71a0dab7a2acc079bb04d167e5251221b130fa7 Mon Sep 17 00:00:00 2001 From: Caglar Demir Date: Thu, 20 Jun 2024 11:33:39 +0200 Subject: [PATCH 1/4] Reasoner selection possible --- owlapy/owlapi_adaptor.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/owlapy/owlapi_adaptor.py b/owlapy/owlapi_adaptor.py index 20ee458b..ed2275e1 100644 --- a/owlapy/owlapi_adaptor.py +++ b/owlapy/owlapi_adaptor.py @@ -10,8 +10,10 @@ class OWLAPIAdaptor: - def __init__(self, path: str): + def __init__(self, path: str, reasoner: str = "HermiT"): self.path = path + assert reasoner in ["HermiT"], f"{reasoner} is not implemented. Please use HermiT" + self.reasoner = reasoner def __enter__(self): """Initialization via the `with` statement""" @@ -27,7 +29,11 @@ def __enter__(self): # Import Java classes from org.semanticweb.owlapi.apibinding import OWLManager from java.io import File - from org.semanticweb.HermiT import ReasonerFactory + if self.reasoner == "HermiT": + from org.semanticweb.HermiT import ReasonerFactory + else: + raise NotImplementedError("Not implemented") + from org.semanticweb.owlapi.manchestersyntax.parser import ManchesterOWLSyntaxClassExpressionParser from org.semanticweb.owlapi.util import BidirectionalShortFormProviderAdapter, SimpleShortFormProvider from org.semanticweb.owlapi.expression import ShortFormEntityChecker @@ -99,4 +105,3 @@ def __exit__(self, exc_type, exc_val, exc_tb): """Shuts down the java virtual machine hosted by jpype.""" if jpype.isJVMStarted() and not jpype.isThreadAttachedToJVM(): jpype.shutdownJVM() - From 2449cec899cff8a4312b456b2e8e9d3bd337674b Mon Sep 17 00:00:00 2001 From: Caglar Demir Date: Fri, 21 Jun 2024 09:42:49 +0200 Subject: [PATCH 2/4] Todos added --- owlapy/owlapi_adaptor.py | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/owlapy/owlapi_adaptor.py b/owlapy/owlapi_adaptor.py index ed2275e1..b621e60c 100644 --- a/owlapy/owlapi_adaptor.py +++ b/owlapy/owlapi_adaptor.py @@ -9,12 +9,18 @@ class OWLAPIAdaptor: + """ TODO:CD: Using OWLAPIAdaptor without the context manager would be good for the ease usage.""" def __init__(self, path: str, reasoner: str = "HermiT"): self.path = path assert reasoner in ["HermiT"], f"{reasoner} is not implemented. Please use HermiT" self.reasoner = reasoner + def __exit__(self, exc_type, exc_val, exc_tb): + """Shuts down the java virtual machine hosted by jpype.""" + if jpype.isJVMStarted() and not jpype.isThreadAttachedToJVM(): + jpype.shutdownJVM() + def __enter__(self): """Initialization via the `with` statement""" if not jpype.isJVMStarted(): @@ -24,6 +30,7 @@ def __enter__(self): else: jar_folder = "../jar_dependencies" jar_files = [os.path.join(jar_folder, f) for f in os.listdir(jar_folder) if f.endswith('.jar')] + # Starting JVM. jpype.startJVM(classpath=jar_files) # Import Java classes @@ -40,21 +47,17 @@ def __enter__(self): from java.util import HashSet from org.semanticweb.owlapi.manchestersyntax.renderer import ManchesterOWLSyntaxOWLObjectRendererImpl - # Manager is needed to load an ontology + # () Manager is needed to load an ontology self.manager = OWLManager.createOWLOntologyManager() - # Load a local ontology using the manager - file = File(self.path) - self.ontology = self.manager.loadOntologyFromOntologyDocument(file) - - # Create a HermiT reasoner for the loaded ontology - reasoner_factory = ReasonerFactory() - self.reasoner = reasoner_factory.createReasoner(self.ontology) + # () Load a local ontology using the manager + self.ontology = self.manager.loadOntologyFromOntologyDocument(File(self.path)) + # () Create a HermiT reasoner for the loaded ontology + self.reasoner = ReasonerFactory().createReasoner(self.ontology) - # Create a manchester parser and all the necessary attributes for parsing manchester syntax string to owlapi ce - short_form_provider = SimpleShortFormProvider() + # () Create a manchester parser and all the necessary attributes for parsing manchester syntax string to owlapi ce ontology_set = HashSet() ontology_set.add(self.ontology) - bidi_provider = BidirectionalShortFormProviderAdapter(self.manager, ontology_set, short_form_provider) + bidi_provider = BidirectionalShortFormProviderAdapter(self.manager, ontology_set, SimpleShortFormProvider()) entity_checker = ShortFormEntityChecker(bidi_provider) self.parser = ManchesterOWLSyntaxClassExpressionParser(self.manager.getOWLDataFactory(), entity_checker) @@ -100,8 +103,3 @@ def instances(self, ce: OWLClassExpression): def has_consistent_ontology(self) -> bool: """ Check if the used ontology is consistent.""" return self.reasoner.isConsistent() - - def __exit__(self, exc_type, exc_val, exc_tb): - """Shuts down the java virtual machine hosted by jpype.""" - if jpype.isJVMStarted() and not jpype.isThreadAttachedToJVM(): - jpype.shutdownJVM() From 2650c78d14ef110c221001c9e1dc0d74abc3acf8 Mon Sep 17 00:00:00 2001 From: Caglar Demir Date: Fri, 21 Jun 2024 09:54:47 +0200 Subject: [PATCH 3/4] DemoOWLAPIAdaptor Adapter as a potential start() and close() --- owlapy/owlapi_adaptor.py | 61 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 60 insertions(+), 1 deletion(-) diff --git a/owlapy/owlapi_adaptor.py b/owlapy/owlapi_adaptor.py index b621e60c..bdcecd97 100644 --- a/owlapy/owlapi_adaptor.py +++ b/owlapy/owlapi_adaptor.py @@ -8,8 +8,8 @@ from owlapy.render import owl_expression_to_manchester +# TODO:What are the downsides of start() close() fashion ?: class OWLAPIAdaptor: - """ TODO:CD: Using OWLAPIAdaptor without the context manager would be good for the ease usage.""" def __init__(self, path: str, reasoner: str = "HermiT"): self.path = path @@ -103,3 +103,62 @@ def instances(self, ce: OWLClassExpression): def has_consistent_ontology(self) -> bool: """ Check if the used ontology is consistent.""" return self.reasoner.isConsistent() + + +class DemoOWLAPIAdaptor(OWLAPIAdaptor): + + def __init__(self, *args, **kwargs): + + super().__init__(*args, **kwargs) + self.__start() + + @staticmethod + def close(*args, **kwargs): + """Shuts down the java virtual machine hosted by jpype.""" + if jpype.isJVMStarted() and not jpype.isThreadAttachedToJVM(): + jpype.shutdownJVM() + + def __start(self): + """Initialization via the `with` statement""" + if not jpype.isJVMStarted(): + # Start a java virtual machine using the dependencies in the respective folder: + if os.getcwd()[-6:] == "owlapy": + jar_folder = "jar_dependencies" + else: + jar_folder = "../jar_dependencies" + jar_files = [os.path.join(jar_folder, f) for f in os.listdir(jar_folder) if f.endswith('.jar')] + # Starting JVM. + jpype.startJVM(classpath=jar_files) + + # Import Java classes + from org.semanticweb.owlapi.apibinding import OWLManager + from java.io import File + if self.reasoner == "HermiT": + from org.semanticweb.HermiT import ReasonerFactory + else: + raise NotImplementedError("Not implemented") + + from org.semanticweb.owlapi.manchestersyntax.parser import ManchesterOWLSyntaxClassExpressionParser + from org.semanticweb.owlapi.util import BidirectionalShortFormProviderAdapter, SimpleShortFormProvider + from org.semanticweb.owlapi.expression import ShortFormEntityChecker + from java.util import HashSet + from org.semanticweb.owlapi.manchestersyntax.renderer import ManchesterOWLSyntaxOWLObjectRendererImpl + + # () Manager is needed to load an ontology + self.manager = OWLManager.createOWLOntologyManager() + # () Load a local ontology using the manager + self.ontology = self.manager.loadOntologyFromOntologyDocument(File(self.path)) + # () Create a HermiT reasoner for the loaded ontology + self.reasoner = ReasonerFactory().createReasoner(self.ontology) + + # () Create a manchester parser and all the necessary attributes for parsing manchester syntax string to owlapi ce + ontology_set = HashSet() + ontology_set.add(self.ontology) + bidi_provider = BidirectionalShortFormProviderAdapter(self.manager, ontology_set, SimpleShortFormProvider()) + entity_checker = ShortFormEntityChecker(bidi_provider) + self.parser = ManchesterOWLSyntaxClassExpressionParser(self.manager.getOWLDataFactory(), entity_checker) + + # A manchester renderer to render owlapi ce to manchester syntax + self.renderer = ManchesterOWLSyntaxOWLObjectRendererImpl() + + return self From 963bb7611cf737cfaa18936d1ff1d3e5f665415c Mon Sep 17 00:00:00 2001 From: Caglar Demir Date: Fri, 21 Jun 2024 10:39:03 +0200 Subject: [PATCH 4/4] Docstrings added --- owlapy/owlapi_adaptor.py | 175 +++++++++++++++++++-------------------- 1 file changed, 87 insertions(+), 88 deletions(-) diff --git a/owlapy/owlapi_adaptor.py b/owlapy/owlapi_adaptor.py index bdcecd97..98a4bdef 100644 --- a/owlapy/owlapi_adaptor.py +++ b/owlapy/owlapi_adaptor.py @@ -6,23 +6,69 @@ from owlapy.iri import IRI from owlapy.owl_individual import OWLNamedIndividual from owlapy.render import owl_expression_to_manchester +from typing import List - -# TODO:What are the downsides of start() close() fashion ?: class OWLAPIAdaptor: + """ + A class to interface with the OWL API using the HermiT reasoner, enabling ontology management, + reasoning, and parsing class expressions in Manchester OWL Syntax. + + Attributes: + path (str): The file path to the ontology. + name_reasoner (str): The reasoner to be used, default is "HermiT". + manager: The OWL ontology manager. + ontology: The loaded OWL ontology. + reasoner: The HermiT reasoner for the ontology. + parser: The Manchester OWL Syntax parser. + renderer: The Manchester OWL Syntax renderer. + __is_open (bool): Flag to check if the JVM is open. + """ + def __init__(self, path: str, name_reasoner: str = "HermiT"): + """ + Initialize the OWLAPIAdaptor with a path to an ontology and a reasoner name. + + Args: + path (str): The file path to the ontology. + name_reasoner (str, optional): The reasoner to be used. Defaults to "HermiT". - def __init__(self, path: str, reasoner: str = "HermiT"): + Raises: + AssertionError: If the provided reasoner name is not implemented. + """ self.path = path - assert reasoner in ["HermiT"], f"{reasoner} is not implemented. Please use HermiT" - self.reasoner = reasoner + assert name_reasoner in ["HermiT"], f"{name_reasoner} is not implemented. Please use HermiT" + self.name_reasoner = name_reasoner + # Attributes are initialized as JVMStarted is started + # () Manager is needed to load an ontology + self.manager = None + # () Load a local ontology using the manager + self.ontology = None + # () Create a HermiT reasoner for the loaded ontology + self.reasoner = None + self.parser = None + # () A manchester renderer to render owlapi ce to manchester syntax + self.renderer = None + self.open() + self.__is_open = True def __exit__(self, exc_type, exc_val, exc_tb): """Shuts down the java virtual machine hosted by jpype.""" - if jpype.isJVMStarted() and not jpype.isThreadAttachedToJVM(): - jpype.shutdownJVM() + self.close() def __enter__(self): - """Initialization via the `with` statement""" + """ + Initialization via the `with` statement. + + Returns: + OWLAPIAdaptor: The current instance. + """ + if not self.__is_open: + self.open() + return self + + def open(self): + """ + Start the JVM with jar dependencies, import necessary OWL API dependencies, and initialize attributes. + """ if not jpype.isJVMStarted(): # Start a java virtual machine using the dependencies in the respective folder: if os.getcwd()[-6:] == "owlapy": @@ -36,7 +82,7 @@ def __enter__(self): # Import Java classes from org.semanticweb.owlapi.apibinding import OWLManager from java.io import File - if self.reasoner == "HermiT": + if self.name_reasoner == "HermiT": from org.semanticweb.HermiT import ReasonerFactory else: raise NotImplementedError("Not implemented") @@ -60,105 +106,58 @@ def __enter__(self): bidi_provider = BidirectionalShortFormProviderAdapter(self.manager, ontology_set, SimpleShortFormProvider()) entity_checker = ShortFormEntityChecker(bidi_provider) self.parser = ManchesterOWLSyntaxClassExpressionParser(self.manager.getOWLDataFactory(), entity_checker) - # A manchester renderer to render owlapi ce to manchester syntax self.renderer = ManchesterOWLSyntaxOWLObjectRendererImpl() - return self + def close(self, *args, **kwargs) -> None: + """Shuts down the java virtual machine hosted by jpype.""" + if jpype.isJVMStarted() and not jpype.isThreadAttachedToJVM(): + jpype.shutdownJVM() + self.__is_open = False def convert_to_owlapi(self, ce: OWLClassExpression): - """ Converts an owlapy ce to an owlapi ce. + """ + Converts an OWLAPY class expression to an OWLAPI class expression. - Args: - ce (OWLClassExpression): class expression in owlapy format to be converted. + Args: + ce (OWLClassExpression): The class expression in OWLAPY format to be converted. - Return: - Class expression in owlapi format. + Returns: + The class expression in OWLAPI format. """ return self.parser.parse(owl_expression_to_manchester(ce)) def convert_from_owlapi(self, ce, namespace: str) -> OWLClassExpression: - """Converts an owlapi ce to an owlapy ce. + """ + Converts an OWLAPI class expression to an OWLAPY class expression. - Args: - ce: Class expression in owlapi format. - namespace: Ontology's namespace where class expression belongs. + Args: + ce: The class expression in OWLAPI format. + namespace (str): The ontology's namespace where the class expression belongs. - Return: - Class expression in owlapy format. + Returns: + OWLClassExpression: The class expression in OWLAPY format. """ return manchester_to_owl_expression(str(self.renderer.render(ce)), namespace) - def instances(self, ce: OWLClassExpression): - """ Get the instances for a given class expression using HermiT. - Args: - ce: Class expression in owlapy format. + def instances(self, ce: OWLClassExpression)->List[OWLNamedIndividual]: + """ + Get the instances for a given class expression using HermiT. + + Args: + ce (OWLClassExpression): The class expression in OWLAPY format. - Return: - Individuals which are classified by the given class expression. + Returns: + list: A list of individuals classified by the given class expression. """ inds = self.reasoner.getInstances(self.convert_to_owlapi(ce), False).getFlattened() return [OWLNamedIndividual(IRI.create(str(ind)[1:-1])) for ind in inds] def has_consistent_ontology(self) -> bool: - """ Check if the used ontology is consistent.""" - return self.reasoner.isConsistent() - - -class DemoOWLAPIAdaptor(OWLAPIAdaptor): - - def __init__(self, *args, **kwargs): - - super().__init__(*args, **kwargs) - self.__start() - - @staticmethod - def close(*args, **kwargs): - """Shuts down the java virtual machine hosted by jpype.""" - if jpype.isJVMStarted() and not jpype.isThreadAttachedToJVM(): - jpype.shutdownJVM() - - def __start(self): - """Initialization via the `with` statement""" - if not jpype.isJVMStarted(): - # Start a java virtual machine using the dependencies in the respective folder: - if os.getcwd()[-6:] == "owlapy": - jar_folder = "jar_dependencies" - else: - jar_folder = "../jar_dependencies" - jar_files = [os.path.join(jar_folder, f) for f in os.listdir(jar_folder) if f.endswith('.jar')] - # Starting JVM. - jpype.startJVM(classpath=jar_files) - - # Import Java classes - from org.semanticweb.owlapi.apibinding import OWLManager - from java.io import File - if self.reasoner == "HermiT": - from org.semanticweb.HermiT import ReasonerFactory - else: - raise NotImplementedError("Not implemented") - - from org.semanticweb.owlapi.manchestersyntax.parser import ManchesterOWLSyntaxClassExpressionParser - from org.semanticweb.owlapi.util import BidirectionalShortFormProviderAdapter, SimpleShortFormProvider - from org.semanticweb.owlapi.expression import ShortFormEntityChecker - from java.util import HashSet - from org.semanticweb.owlapi.manchestersyntax.renderer import ManchesterOWLSyntaxOWLObjectRendererImpl - - # () Manager is needed to load an ontology - self.manager = OWLManager.createOWLOntologyManager() - # () Load a local ontology using the manager - self.ontology = self.manager.loadOntologyFromOntologyDocument(File(self.path)) - # () Create a HermiT reasoner for the loaded ontology - self.reasoner = ReasonerFactory().createReasoner(self.ontology) - - # () Create a manchester parser and all the necessary attributes for parsing manchester syntax string to owlapi ce - ontology_set = HashSet() - ontology_set.add(self.ontology) - bidi_provider = BidirectionalShortFormProviderAdapter(self.manager, ontology_set, SimpleShortFormProvider()) - entity_checker = ShortFormEntityChecker(bidi_provider) - self.parser = ManchesterOWLSyntaxClassExpressionParser(self.manager.getOWLDataFactory(), entity_checker) - - # A manchester renderer to render owlapi ce to manchester syntax - self.renderer = ManchesterOWLSyntaxOWLObjectRendererImpl() + """ + Check if the used ontology is consistent. - return self + Returns: + bool: True if the ontology is consistent, False otherwise. + """ + return self.reasoner.isConsistent()