diff --git a/MANIFEST.in b/MANIFEST.in index 0e236750..9312c357 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -7,9 +7,5 @@ recursive-include examples *.py recursive-include examples *.json recursive-include examples *.conf recursive-include tests *.py -include sortedcontainers-stubs/py.typed -recursive-include sortedcontainers-stubs *.pyi -include superprop/py.typed -recursive-include superprop *.pyi prune *.egg-info prune .tox diff --git a/README.md b/README.md index 330eab95..bbda21a0 100644 --- a/README.md +++ b/README.md @@ -59,12 +59,13 @@ the learning algorithms. Also in the [tests](https://github.com/dice-group/Ontol For more detailed instructions we suggest to follow the [guides](https://ontolearn-docs-dice-group.netlify.app/usage/03_algorithm.html) in the documentation. Below we give a simple example on using CELOE to learn class expressions for a small dataset. + ```python from ontolearn.concept_learner import CELOE from ontolearn.model_adapter import ModelAdapter -from owlapy.model import OWLNamedIndividual, IRI -from owlapy.namespaces import Namespaces -from owlapy.render import DLSyntaxObjectRenderer +from ontolearn.owlapy.model import OWLNamedIndividual, IRI +from ontolearn.owlapy.namespaces import Namespaces +from ontolearn.owlapy.render import DLSyntaxObjectRenderer from examples.experiments_standard import ClosedWorld_ReasonerFactory NS = Namespaces('ex', 'http://example.com/father#') diff --git a/deploy_cl.py b/deploy_cl.py index 2ed78fb4..8c83fa27 100644 --- a/deploy_cl.py +++ b/deploy_cl.py @@ -15,8 +15,8 @@ from ontolearn.learning_problem import PosNegLPStandard from ontolearn.refinement_operators import ModifiedCELOERefinement from ontolearn.value_splitter import EntropyValueSplitter, BinningValueSplitter -from owlapy.model import OWLNamedIndividual, IRI -from owlapy.render import DLSyntaxObjectRenderer +from ontolearn.owlapy.model import OWLNamedIndividual, IRI +from ontolearn.owlapy.render import DLSyntaxObjectRenderer metrics = {'F1': F1, 'Accuracy': Accuracy, diff --git a/docs/usage/01_knowledge_base.md b/docs/usage/01_knowledge_base.md index 852c995a..c6125856 100644 --- a/docs/usage/01_knowledge_base.md +++ b/docs/usage/01_knowledge_base.md @@ -68,13 +68,14 @@ before fitting a model. It can be done as follows: + ```python -from owlapy.model import OWLClass -from owlapy.model import IRI +from ontolearn.owlapy.model import OWLClass +from ontolearn.owlapy.model import IRI -iri = IRI('http://example.com/father#', 'Father') +iri = IRI('http://example.com/father#', 'Father') father_concept = OWLClass(iri) -concepts_to_ignore = {father_concept} # you can add more than 1 +concepts_to_ignore = {father_concept} # you can add more than 1 new_kb = kb.ignore_and_copy(ignored_classes=concepts_to_ignore) ``` diff --git a/docs/usage/02_learning_problem.md b/docs/usage/02_learning_problem.md index 40240630..80a834e2 100644 --- a/docs/usage/02_learning_problem.md +++ b/docs/usage/02_learning_problem.md @@ -33,9 +33,10 @@ describe) are stefan, markus, and martin. And our negative examples could write the following Python code: + ```python -from owlapy.namespaces import Namespaces -from owlapy.model import OWLNamedIndividual, IRI +from ontolearn.owlapy.namespaces import Namespaces +from ontolearn.owlapy.model import OWLNamedIndividual, IRI NS = Namespaces('ex', 'http://example.com/father#') diff --git a/docs/usage/03_ontologies.md b/docs/usage/03_ontologies.md index bbad9eef..016eb481 100644 --- a/docs/usage/03_ontologies.md +++ b/docs/usage/03_ontologies.md @@ -13,8 +13,8 @@ To load an ontology as well as to manage it, you will need an [OWLOntologyManage To load an ontology, use the following Python code: ```python -from owlapy.model import IRI -from owlapy.owlready2 import OWLOntologyManager_Owlready2 +from ontolearn.owlapy.model import IRI +from ontolearn.owlapy.owlready2 import OWLOntologyManager_Owlready2 manager = OWLOntologyManager_Owlready2() onto = manager.load_ontology(IRI.create("file://KGs/father.owl")) @@ -70,9 +70,10 @@ Let's suppose you want to add a new class in our example ontology `KGs/father.ow to see a description of it). It can be done as follows: + ```python -from owlapy.model import OWLClass -from owlapy.model import OWLDeclarationAxiom +from ontolearn.owlapy.model import OWLClass +from ontolearn.owlapy.model import OWLDeclarationAxiom iri = IRI('http://example.com/father#', 'child') child_class = OWLClass(iri) @@ -98,16 +99,17 @@ you can use the class [OWLObjectProperty](owlapy.model.OWLObjectProperty) and fo properties you can use the class [OWLDataProperty](owlapy.model.OWLDataProperty). + ```python -from owlapy.model import OWLObjectProperty -from owlapy.model import OWLDataProperty +from ontolearn.owlapy.model import OWLObjectProperty +from ontolearn.owlapy.model import OWLDataProperty # adding the object property 'hasParent' hasParent_op = OWLObjectProperty(IRI('http://example.com/father#', 'hasParent')) hasParent_op_declaration_axiom = OWLDeclarationAxiom(hasParent_op) manager.add_axiom(onto, hasParent_op_declaration_axiom) -#adding the data property 'hasAge' +# adding the data property 'hasAge' hasAge_dp = OWLDataProperty(IRI('http://example.com/father#', 'hasAge')) hasAge_dp_declaration_axiom = OWLDeclarationAxiom(hasAge_dp) manager.add_axiom(onto, hasAge_dp_declaration_axiom) @@ -120,11 +122,12 @@ See the [API documentation](owlapy.model) for more OWL entities that you can add To assign a class to a specific individual use the following code: + ```python -from owlapy.model import OWLClassAssertionAxiom +from ontolearn.owlapy.model import OWLClassAssertionAxiom individuals = list(onto.individuals_in_signature()) -heinz = individuals[1] # get the 2nd individual in the list which is 'heinz' +heinz = individuals[1] # get the 2nd individual in the list which is 'heinz' class_assertion_axiom = OWLClassAssertionAxiom(heinz, child_class) @@ -142,9 +145,10 @@ Let's show one more example using a `OWLDataPropertyAssertionAxiom` to assign th heinz. + ```python -from owlapy.model import OWLLiteral -from owlapy.model import OWLDataPropertyAssertionAxiom +from ontolearn.owlapy.model import OWLLiteral +from ontolearn.owlapy.model import OWLDataPropertyAssertionAxiom literal_17 = OWLLiteral(17) dp_assertion_axiom = OWLDataPropertyAssertionAxiom(heinz, hasAge_dp, literal_17) diff --git a/docs/usage/04_reasoner.md b/docs/usage/04_reasoner.md index a40ee4df..d231784b 100644 --- a/docs/usage/04_reasoner.md +++ b/docs/usage/04_reasoner.md @@ -24,9 +24,9 @@ To load any reasoner, use the following code: ```python -from owlapy.owlready2 import OWLReasoner_Owlready2 -from owlapy.owlready2.complex_ce_instances import OWLReasoner_Owlready2_ComplexCEInstances -from owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker +from ontolearn.owlapy.owlready2 import OWLReasoner_Owlready2 +from ontolearn.owlapy.owlready2.complex_ce_instances import OWLReasoner_Owlready2_ComplexCEInstances +from ontolearn.owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker structural_reasoner = OWLReasoner_Owlready2(onto) complex_reasoner = OWLReasoner_Owlready2_ComplexCEInstances(onto) @@ -60,11 +60,13 @@ but a reasoner can give you more than that. You can get the subclasses, supercla equivalent classes of a class in the ontology: + ```python -from owlapy.model import OWLClass -from owlapy.model import IRI +from ontolearn.owlapy.model import OWLClass +from ontolearn.owlapy.model import IRI + namespace = "http://example.com/father#" -male = OWLClass(IRI(namespace,"male")) +male = OWLClass(IRI(namespace, "male")) male_super_classes = fast_instance_checker.super_classes(male) male_sub_classes = fast_instance_checker.sub_classes(male) @@ -87,12 +89,14 @@ upon the class, object property, or data property hierarchy. You can get all the types of a certain individual using `types` method: + ```python -from owlapy.owlready2 import OWLOntologyManager_Owlready2 +from ontolearn.owlapy.owlready2 import OWLOntologyManager_Owlready2 manager = OWLOntologyManager_Owlready2() onto = manager.load_ontology(IRI.create("KGs/father.owl")) -anna = list(onto.individuals_in_signature()).pop() # getting the 1st individual in the list of individuals which is 'anna' +anna = list( + onto.individuals_in_signature()).pop() # getting the 1st individual in the list of individuals which is 'anna' anna_types = fast_instance_checker.types(anna) ``` @@ -146,10 +150,11 @@ specified individual. In the same way as with classes, you can also get the sub object properties or equivalent object properties. + ```python -from owlapy.model import OWLObjectProperty +from ontolearn.owlapy.model import OWLObjectProperty -hasChild = OWLObjectProperty(IRI(namespace,"hasChild")) +hasChild = OWLObjectProperty(IRI(namespace, "hasChild")) equivalent_to_hasChild = fast_instance_checker.equivalent_object_properties(hasChild) hasChild_sub_properties = fast_instance_checker.sub_object_properties(hasChild) diff --git a/docs/usage/05_concept_learners.md b/docs/usage/05_concept_learners.md index c3603a72..53e8e74b 100644 --- a/docs/usage/05_concept_learners.md +++ b/docs/usage/05_concept_learners.md @@ -137,13 +137,14 @@ each individual (stored as `string`) from the set `positive_examples ` and `negative_examples` to `OWLNamedIndividual`: + ```python from ontolearn.learning_problem import PosNegLPStandard - from owlapy.model import IRI,OWLNamedIndividual - - typed_pos = set(map(OWLNamedIndividual, map(IRI.create, p))) - typed_neg = set(map(OWLNamedIndividual, map(IRI.create, n))) - lp = PosNegLPStandard(pos=typed_pos, neg=typed_neg) +from ontolearn.owlapy.model import IRI, OWLNamedIndividual + +typed_pos = set(map(OWLNamedIndividual, map(IRI.create, p))) +typed_neg = set(map(OWLNamedIndividual, map(IRI.create, n))) +lp = PosNegLPStandard(pos=typed_pos, neg=typed_neg) ``` To construct an [OWLNamedIndividual](owlapy.model.OWLNamedIndividual) object an [IRI](owlapy.model.IRI) is required as an input. diff --git a/docs/usage/09_model_adapter.md b/docs/usage/09_model_adapter.md index 5d60e108..8f33112b 100644 --- a/docs/usage/09_model_adapter.md +++ b/docs/usage/09_model_adapter.md @@ -10,12 +10,11 @@ from ontolearn.concept_learner import CELOE from ontolearn.heuristics import CELOEHeuristic from ontolearn.metrics import Accuracy from ontolearn.model_adapter import ModelAdapter -from owlapy.model import OWLNamedIndividual, IRI -from owlapy.namespaces import Namespaces -from owlapy.owlready2 import OWLOntologyManager_Owlready2 -from owlapy.owlready2.complex_ce_instances import OWLReasoner_Owlready2_ComplexCEInstances -from owlapy.render import DLSyntaxObjectRenderer - +from ontolearn.owlapy.model import OWLNamedIndividual, IRI +from ontolearn.owlapy.namespaces import Namespaces +from ontolearn.owlapy.owlready2 import OWLOntologyManager_Owlready2 +from ontolearn.owlapy.owlready2.complex_ce_instances import OWLReasoner_Owlready2_ComplexCEInstances +from ontolearn.owlapy.render import DLSyntaxObjectRenderer manager = OWLOntologyManager_Owlready2() onto = manager.load_ontology(IRI.create("KGs/father.owl")) @@ -32,10 +31,10 @@ negative_examples = {OWLNamedIndividual(IRI.create(NS, 'heinz')), # Only the class of the learning algorithm is specified model = ModelAdapter(learner_type=CELOE, - reasoner=complex_ce_reasoner, # (*) + reasoner=complex_ce_reasoner, # (*) path="KGs/father.owl", quality_type=Accuracy, - heuristic_type=CELOEHeuristic, # (*) + heuristic_type=CELOEHeuristic, # (*) expansionPenaltyFactor=0.05, startNodeBonus=1.0, nodeRefinementPenalty=0.01, diff --git a/examples/concept_learning_drill_train.py b/examples/concept_learning_drill_train.py index 7914eed4..c1e3f99d 100644 --- a/examples/concept_learning_drill_train.py +++ b/examples/concept_learning_drill_train.py @@ -12,16 +12,16 @@ from ontolearn.concept_learner import Drill from ontolearn.metrics import F1 from ontolearn.heuristics import Reward -from owlapy.model import OWLOntology, OWLReasoner +from ontolearn.owlapy.model import OWLOntology, OWLReasoner from ontolearn.utils import setup_logging setup_logging() def ClosedWorld_ReasonerFactory(onto: OWLOntology) -> OWLReasoner: - from owlapy.owlready2 import OWLOntology_Owlready2 - from owlapy.owlready2.complex_ce_instances import OWLReasoner_Owlready2_ComplexCEInstances - from owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker + from ontolearn.owlapy.owlready2 import OWLOntology_Owlready2 + from ontolearn.owlapy.owlready2.complex_ce_instances import OWLReasoner_Owlready2_ComplexCEInstances + from ontolearn.owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker assert isinstance(onto, OWLOntology_Owlready2) base_reasoner = OWLReasoner_Owlready2_ComplexCEInstances(ontology=onto) reasoner = OWLReasoner_FastInstanceChecker(ontology=onto, diff --git a/examples/concept_learning_with_celoe_heuristic.py b/examples/concept_learning_with_celoe_heuristic.py index 74ee5161..65ca5648 100644 --- a/examples/concept_learning_with_celoe_heuristic.py +++ b/examples/concept_learning_with_celoe_heuristic.py @@ -8,7 +8,7 @@ from ontolearn.heuristics import CELOEHeuristic from ontolearn.learning_problem import PosNegLPStandard from ontolearn.metrics import Accuracy -from owlapy.model import OWLClass, OWLNamedIndividual, IRI +from ontolearn.owlapy.model import OWLClass, OWLNamedIndividual, IRI from ontolearn.refinement_operators import ModifiedCELOERefinement from ontolearn.utils import setup_logging diff --git a/examples/concept_learning_with_celoe_heuristic_ma.py b/examples/concept_learning_with_celoe_heuristic_ma.py index 8435e8c0..444d38bd 100644 --- a/examples/concept_learning_with_celoe_heuristic_ma.py +++ b/examples/concept_learning_with_celoe_heuristic_ma.py @@ -5,10 +5,10 @@ from ontolearn.concept_learner import CELOE from ontolearn.knowledge_base import KnowledgeBase from ontolearn.model_adapter import ModelAdapter -from owlapy.model import OWLClass, OWLNamedIndividual, IRI +from ontolearn.owlapy.model import OWLClass, OWLNamedIndividual, IRI from ontolearn.utils import setup_logging -from owlapy.owlready2 import BaseReasoner_Owlready2, OWLOntology_Owlready2 -from owlapy.owlready2.complex_ce_instances import OWLReasoner_Owlready2_ComplexCEInstances +from ontolearn.owlapy.owlready2 import BaseReasoner_Owlready2, OWLOntology_Owlready2 +from ontolearn.owlapy.owlready2.complex_ce_instances import OWLReasoner_Owlready2_ComplexCEInstances from typing import cast setup_logging() diff --git a/examples/concept_learning_with_evolearner.py b/examples/concept_learning_with_evolearner.py index bcf0d5db..f1eabc34 100644 --- a/examples/concept_learning_with_evolearner.py +++ b/examples/concept_learning_with_evolearner.py @@ -4,7 +4,7 @@ from ontolearn.knowledge_base import KnowledgeBase from ontolearn.concept_learner import EvoLearner from ontolearn.learning_problem import PosNegLPStandard -from owlapy.model import OWLClass, OWLNamedIndividual, IRI +from ontolearn.owlapy.model import OWLClass, OWLNamedIndividual, IRI from ontolearn.utils import setup_logging setup_logging() diff --git a/examples/concept_learning_with_ocel.py b/examples/concept_learning_with_ocel.py index 55536933..757c7e61 100644 --- a/examples/concept_learning_with_ocel.py +++ b/examples/concept_learning_with_ocel.py @@ -5,7 +5,7 @@ from ontolearn.concept_learner import OCEL from ontolearn.learning_problem import PosNegLPStandard from ontolearn.utils import setup_logging -from owlapy.model import OWLClass, IRI, OWLNamedIndividual +from ontolearn.owlapy.model import OWLClass, IRI, OWLNamedIndividual setup_logging() diff --git a/examples/example_knowledge_base.py b/examples/example_knowledge_base.py index 7cb47c35..e85f94ff 100644 --- a/examples/example_knowledge_base.py +++ b/examples/example_knowledge_base.py @@ -1,3 +1,4 @@ +from ontolearn.concept_generator import ConceptGenerator from ontolearn.knowledge_base import KnowledgeBase import os @@ -8,7 +9,7 @@ kb_path = '../KGs/Family/family-benchmark_rich_background.owl' kb = KnowledgeBase(path=kb_path) - +generator = ConceptGenerator() # All concepts. for i in kb.get_concepts(): @@ -42,23 +43,23 @@ print('*' * 100) -for concept in kb.most_general_existential_restrictions(domain=kb.thing): +for concept in kb.most_general_existential_restrictions(domain=generator.thing): print(concept) print('*' * 100) -for concept in kb.most_general_universal_restrictions(domain=kb.thing): +for concept in kb.most_general_universal_restrictions(domain=generator.thing): print(concept) print('*' * 100) -for concept in kb.most_general_existential_restrictions(domain=kb.nothing): +for concept in kb.most_general_existential_restrictions(domain=generator.nothing): print(concept) print('*' * 100) -for concept in kb.most_general_universal_restrictions(domain=kb.nothing): +for concept in kb.most_general_universal_restrictions(domain=generator.nothing): print(concept) print('*' * 100) for c in kb.get_concepts(): - neg_c = kb.negation(c) - neg_neg_c = kb.negation(neg_c) + neg_c = generator.negation(c) + neg_neg_c = generator.negation(neg_c) assert neg_neg_c == c diff --git a/examples/example_reasoner.py b/examples/example_reasoner.py index 2e66e120..b1b55e17 100644 --- a/examples/example_reasoner.py +++ b/examples/example_reasoner.py @@ -1,11 +1,9 @@ -from owlapy.model import OWLSubClassOfAxiom, OWLEquivalentClassesAxiom, \ - OWLEquivalentObjectPropertiesAxiom, OWLObjectPropertyDomainAxiom, OWLDataProperty -from owlapy.owlready2._base import OWLReasoner_Owlready2, BaseReasoner_Owlready2 -from owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker +from ontolearn.owlapy.model import OWLSubClassOfAxiom, OWLEquivalentObjectPropertiesAxiom, OWLObjectPropertyDomainAxiom, OWLDataProperty +from ontolearn.owlapy.owlready2 import OWLReasoner_Owlready2, BaseReasoner_Owlready2 from ontolearn.knowledge_base import KnowledgeBase -from owlapy.model import OWLObjectProperty, IRI, OWLObjectSomeValuesFrom, \ +from ontolearn.owlapy.model import OWLObjectProperty, IRI, OWLObjectSomeValuesFrom, \ OWLObjectIntersectionOf, OWLClass, OWLNamedIndividual -from owlapy.owlready2.complex_ce_instances import OWLReasoner_Owlready2_ComplexCEInstances +from ontolearn.owlapy.owlready2.complex_ce_instances import OWLReasoner_Owlready2_ComplexCEInstances data_file = '../KGs/test_ontology.owl' NS = 'http://www.semanticweb.org/stefan/ontologies/2023/1/untitled-ontology-11#' diff --git a/examples/experiments_standard.py b/examples/experiments_standard.py index 441700f6..444efe2a 100644 --- a/examples/experiments_standard.py +++ b/examples/experiments_standard.py @@ -27,7 +27,7 @@ from ontolearn.metrics import F1 from ontolearn.refinement_operators import LengthBasedRefinement from ontolearn.utils import setup_logging -from owlapy.model import OWLOntology, OWLReasoner +from ontolearn.owlapy.model import OWLOntology, OWLReasoner setup_logging() full_computation_time = time.time() @@ -44,9 +44,9 @@ def sanity_checking_args(args): def ClosedWorld_ReasonerFactory(onto: OWLOntology) -> OWLReasoner: - from owlapy.owlready2 import OWLOntology_Owlready2 - from owlapy.owlready2.complex_ce_instances import OWLReasoner_Owlready2_ComplexCEInstances - from owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker + from ontolearn.owlapy.owlready2 import OWLOntology_Owlready2 + from ontolearn.owlapy.owlready2.complex_ce_instances import OWLReasoner_Owlready2_ComplexCEInstances + from ontolearn.owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker assert isinstance(onto, OWLOntology_Owlready2) base_reasoner = OWLReasoner_Owlready2_ComplexCEInstances(ontology=onto) reasoner = OWLReasoner_FastInstanceChecker(ontology=onto, diff --git a/examples/refinements.py b/examples/refinements.py deleted file mode 100644 index a94c63e5..00000000 --- a/examples/refinements.py +++ /dev/null @@ -1,15 +0,0 @@ -import os - -from ontolearn.knowledge_base import KnowledgeBase -from ontolearn.refinement_operators import CustomRefinementOperator - -try: - os.chdir("examples") -except FileNotFoundError: - pass - -kb = KnowledgeBase(path='../KGs/Family/family-benchmark_rich_background.owl') -rho = CustomRefinementOperator(kb) -# TODO: Line 14 throws a TypeError -for r in rho.refine(kb.thing): - print(r) diff --git a/examples/simple_drill_endpoint.py b/examples/simple_drill_endpoint.py index 44cfe5cd..5f7ded30 100755 --- a/examples/simple_drill_endpoint.py +++ b/examples/simple_drill_endpoint.py @@ -5,19 +5,17 @@ from argparse import ArgumentParser from datetime import datetime from functools import wraps, update_wrapper -from typing import List from flask import Flask, request, Response, abort from flask import make_response -from owlapy.model import OWLNamedIndividual +from ontolearn.owlapy.model import OWLNamedIndividual from experiments_standard import ClosedWorld_ReasonerFactory -from ontolearn import KnowledgeBase +from ontolearn.knowledge_base import KnowledgeBase from ontolearn.heuristics import Reward from ontolearn.metrics import F1 from ontolearn.concept_learner import Drill from ontolearn.refinement_operators import LengthBasedRefinement -from ontolearn.search import Node def nocache(view): @@ -60,7 +58,7 @@ def concept_learning_endpoint(): app.logger.debug(learning_problem) no_of_hypotheses = request.form.get("no_of_hypotheses", 1, type=int) try: - from owlapy.model import IRI + from ontolearn.owlapy.model import IRI typed_pos = set(map(OWLNamedIndividual, map(IRI.create, set(learning_problem["positives"])))) typed_neg = set(map(OWLNamedIndividual, map(IRI.create, set(learning_problem["negatives"])))) drill.fit(typed_pos, typed_neg, diff --git a/examples/sml_bench.py b/examples/sml_bench.py index 4f36ddc9..34ceba72 100644 --- a/examples/sml_bench.py +++ b/examples/sml_bench.py @@ -6,10 +6,10 @@ from ontolearn.learning_problem import PosNegLPStandard from ontolearn.metrics import Accuracy, F1 from ontolearn.utils import setup_logging, read_individuals_file -from owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker -from owlapy.model import IRI -from owlapy.owlready2 import OWLOntologyManager_Owlready2, OWLReasoner_Owlready2 -from owlapy.render import ManchesterOWLSyntaxOWLObjectRenderer, DLSyntaxObjectRenderer # noqa: F401 +from ontolearn.owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker +from ontolearn.owlapy.model import IRI +from ontolearn.owlapy.owlready2 import OWLOntologyManager_Owlready2, OWLReasoner_Owlready2 +from ontolearn.owlapy.render import ManchesterOWLSyntaxOWLObjectRenderer, DLSyntaxObjectRenderer # noqa: F401 def run(data_file, pos_file, neg_file): diff --git a/examples/sml_sparql.py b/examples/sml_sparql.py index af65cee8..381f881b 100644 --- a/examples/sml_sparql.py +++ b/examples/sml_sparql.py @@ -7,7 +7,7 @@ from ontolearn.refinement_operators import ModifiedCELOERefinement from ontolearn.sparqlkb import SparqlKnowledgeBase from ontolearn.utils import setup_logging, read_individuals_file -from owlapy.render import ManchesterOWLSyntaxOWLObjectRenderer, DLSyntaxObjectRenderer # noqa: F401 +from ontolearn.owlapy.render import ManchesterOWLSyntaxOWLObjectRenderer, DLSyntaxObjectRenderer # noqa: F401 ENDPOINT_URL = "http://172.17.0.2:3030/ds/query" # ENDPOINT_URL = "http://172.18.0.2:7200/repositories/carcinogenesis" diff --git a/examples/sml_tentris.py b/examples/sml_tentris.py index 6b7f1e6d..c2c5014a 100644 --- a/examples/sml_tentris.py +++ b/examples/sml_tentris.py @@ -7,7 +7,7 @@ from ontolearn.refinement_operators import ModifiedCELOERefinement from ontolearn.tentris import TentrisKnowledgeBase from ontolearn.utils import setup_logging, read_individuals_file -from owlapy.render import ManchesterOWLSyntaxOWLObjectRenderer, DLSyntaxObjectRenderer # noqa: F401 +from ontolearn.owlapy.render import ManchesterOWLSyntaxOWLObjectRenderer, DLSyntaxObjectRenderer # noqa: F401 # TODO: check if this works after fixing the warnings in ontolearn\tentris.py diff --git a/examples/usecase.py b/examples/usecase.py index 51ae372b..9d4a1d67 100644 --- a/examples/usecase.py +++ b/examples/usecase.py @@ -4,10 +4,10 @@ from ontolearn.concept_learner import CELOE from ontolearn.learning_problem import PosNegLPStandard from ontolearn.metrics import Accuracy, F1 -from owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker -from owlapy.model import OWLClass, OWLObjectSomeValuesFrom, OWLObjectProperty, IRI -from owlapy.owlready2 import OWLOntologyManager_Owlready2, OWLReasoner_Owlready2 -from owlapy.render import DLSyntaxObjectRenderer +from ontolearn.owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker +from ontolearn.owlapy.model import OWLClass, OWLObjectSomeValuesFrom, OWLObjectProperty, IRI +from ontolearn.owlapy.owlready2 import OWLOntologyManager_Owlready2, OWLReasoner_Owlready2 +from ontolearn.owlapy.render import DLSyntaxObjectRenderer if __name__ == '__main__': # In[45]: diff --git a/ontolearn/abstracts.py b/ontolearn/abstracts.py index e7287237..6207bf85 100644 --- a/ontolearn/abstracts.py +++ b/ontolearn/abstracts.py @@ -1,9 +1,9 @@ import logging from abc import ABCMeta, abstractmethod -from typing import Set, List, Tuple, Iterable, TypeVar, Generic, ClassVar, Optional, Protocol +from typing import Set, List, Tuple, Iterable, TypeVar, Generic, ClassVar, Optional -from owlapy.model import OWLClassExpression, OWLOntology -from owlapy.util import iter_count +from ontolearn.owlapy.model import OWLClassExpression, OWLOntology +from ontolearn.owlapy.util import iter_count from .data_struct import Experience from .utils import read_csv from collections import OrderedDict @@ -279,8 +279,6 @@ class AbstractKnowledgeBase(metaclass=ABCMeta): """Abstract knowledge base""" __slots__ = () - thing: OWLClassExpression - @abstractmethod def ontology(self) -> OWLOntology: """The base ontology of this knowledge base""" diff --git a/ontolearn/base_concept_learner.py b/ontolearn/base_concept_learner.py index 6ac7f3f7..1fe74e86 100644 --- a/ontolearn/base_concept_learner.py +++ b/ontolearn/base_concept_learner.py @@ -12,12 +12,12 @@ from ontolearn.refinement_operators import ModifiedCELOERefinement from ontolearn.search import _NodeQuality -from owlapy.model import OWLDeclarationAxiom, OWLNamedIndividual, OWLOntologyManager, OWLOntology, AddImport, \ +from ontolearn.owlapy.model import OWLDeclarationAxiom, OWLNamedIndividual, OWLOntologyManager, OWLOntology, AddImport, \ OWLImportsDeclaration, OWLClass, OWLEquivalentClassesAxiom, OWLAnnotationAssertionAxiom, OWLAnnotation, \ OWLAnnotationProperty, OWLLiteral, IRI, OWLClassExpression, OWLReasoner, OWLAxiom, OWLThing -from owlapy.owlready2 import OWLOntologyManager_Owlready2, OWLOntology_Owlready2 -from owlapy.owlready2.complex_ce_instances import OWLReasoner_Owlready2_ComplexCEInstances -from owlapy.render import DLSyntaxObjectRenderer +from ontolearn.owlapy.owlready2 import OWLOntologyManager_Owlready2, OWLOntology_Owlready2 +from ontolearn.owlapy.owlready2.complex_ce_instances import OWLReasoner_Owlready2_ComplexCEInstances +from ontolearn.owlapy.render import DLSyntaxObjectRenderer from .abstracts import BaseRefinement, AbstractScorer, AbstractHeuristic, \ AbstractConceptNode, AbstractLearningProblem from .utils import oplogging @@ -414,7 +414,7 @@ def __default_values(self): self.heuristic_func = CELOEHeuristic() if self.start_class is None: - self.start_class = self.kb.thing + self.start_class = self.kb.generator.thing if self.iter_bound is None: self.iter_bound = 10_000 diff --git a/ontolearn/base_nces.py b/ontolearn/base_nces.py index 7a3bd334..5db9ad63 100644 --- a/ontolearn/base_nces.py +++ b/ontolearn/base_nces.py @@ -1,5 +1,5 @@ from ontolearn.knowledge_base import KnowledgeBase -from owlapy.render import DLSyntaxObjectRenderer +from ontolearn.owlapy.render import DLSyntaxObjectRenderer import numpy as np from torch.functional import F from torch.nn.utils.rnn import pad_sequence diff --git a/ontolearn/concept_generator.py b/ontolearn/concept_generator.py index 2d89af51..a708403d 100644 --- a/ontolearn/concept_generator.py +++ b/ontolearn/concept_generator.py @@ -1,76 +1,15 @@ -from typing import FrozenSet, Iterable, List, Optional, Dict, Generator, Set +from typing import Iterable, List, Generator -from ontolearn.core.owl.hierarchy import ClassHierarchy, ObjectPropertyHierarchy, DatatypePropertyHierarchy from ontolearn.utils import parametrized_performance_debugger -from owlapy.model import OWLObjectMaxCardinality, OWLObjectMinCardinality, OWLObjectSomeValuesFrom, \ +from ontolearn.owlapy.model import OWLObjectMaxCardinality, OWLObjectMinCardinality, OWLObjectSomeValuesFrom, \ OWLObjectAllValuesFrom, OWLObjectIntersectionOf, OWLObjectUnionOf, OWLObjectPropertyExpression, OWLThing, \ - OWLNothing, OWLReasoner, OWLObjectProperty, OWLClass, OWLClassExpression, OWLObjectComplementOf, \ + OWLNothing, OWLClass, OWLClassExpression, OWLObjectComplementOf, \ OWLObjectExactCardinality, OWLDataAllValuesFrom, OWLDataPropertyExpression, OWLDataRange, OWLDataSomeValuesFrom, \ - OWLDataHasValue, OWLIndividual, OWLLiteral, OWLDataProperty, OWLObjectHasValue, NUMERIC_DATATYPES, TIME_DATATYPES, \ - BooleanOWLDatatype, OWLDatatype, OWLNamedIndividual + OWLDataHasValue, OWLIndividual, OWLLiteral, OWLObjectHasValue class ConceptGenerator: """A class that can generate some sorts of OWL Class Expressions""" - __slots__ = '_class_hierarchy', '_object_property_hierarchy', '_data_property_hierarchy', '_reasoner', \ - '_op_domains', '_op_ranges', '_dp_domains', '_dp_ranges' - - _class_hierarchy: ClassHierarchy - _object_property_hierarchy: ObjectPropertyHierarchy - _data_property_hierarchy: DatatypePropertyHierarchy - _reasoner: OWLReasoner - _op_domains: Dict[OWLObjectProperty, OWLClassExpression] - _op_ranges: Dict[OWLObjectProperty, OWLClassExpression] - _dp_domains: Dict[OWLDataProperty, OWLClassExpression] - _dp_ranges: Dict[OWLDataProperty, FrozenSet[OWLDataRange]] - - def __init__(self, reasoner: OWLReasoner, - class_hierarchy: Optional[ClassHierarchy] = None, - object_property_hierarchy: Optional[ObjectPropertyHierarchy] = None, - data_property_hierarchy: Optional[DatatypePropertyHierarchy] = None): - """Create a new Concept Generator - - Args: - reasoner: OWL reasoner with ontology loaded - class_hierarchy: Class hierarchy to answer subclass queries. Created from the root ontology loaded in the - reasoner if not given - object_property_hierarchy: Object property hierarchy. Created from the root ontology loaded in the reasoner - if not given - data_property_hierarchy: Data property hierarchy. Created from the root ontology loaded in the reasoner - if not given - """ - self._reasoner = reasoner - - if class_hierarchy is None: - class_hierarchy = ClassHierarchy(self._reasoner) - - if object_property_hierarchy is None: - object_property_hierarchy = ObjectPropertyHierarchy(self._reasoner) - - if data_property_hierarchy is None: - data_property_hierarchy = DatatypePropertyHierarchy(self._reasoner) - - self._class_hierarchy = class_hierarchy - self._object_property_hierarchy = object_property_hierarchy - self._data_property_hierarchy = data_property_hierarchy - - self._op_domains = dict() - self._op_ranges = dict() - self._dp_domains = dict() - self._dp_ranges = dict() - - def get_leaf_concepts(self, concept: OWLClass): - """Get leaf classes - - Args: - concept: atomic class for which to find leaf classes - - Returns: - Leaf classes - - { x \\| (x subClassOf concept) AND not exist y: y subClassOf x )} """ - assert isinstance(concept, OWLClass) - yield from self._class_hierarchy.leaves(of=concept) @parametrized_performance_debugger() def negation_from_iterables(self, class_expressions: Iterable[OWLClassExpression]): @@ -119,236 +58,6 @@ def union_from_iterables(a_operands: Iterable[OWLClassExpression], seen.add((j, i)) yield i_and_j - @parametrized_performance_debugger() - def get_direct_sub_concepts(self, concept: OWLClass) -> Iterable[OWLClass]: - """Direct sub classes of atomic class - - Args: - concept: atomic concept - - Returns: - direct sub classes of concept - - { x \\| ( x subClassOf concept )} """ - assert isinstance(concept, OWLClass) - yield from self._class_hierarchy.sub_classes(concept, direct=True) - - def get_object_property_domains(self, prop: OWLObjectProperty) -> OWLClassExpression: - """Get the domains of an object property - - Args: - prop: object property - - Returns: - domains of the property - """ - if prop not in self._op_domains: - domains = list(self._reasoner.object_property_domains(prop, direct=True)) - self._op_domains[prop] = self.intersection(domains) if len(domains) > 1 else domains[0] - return self._op_domains[prop] - - def get_object_property_ranges(self, prop: OWLObjectProperty) -> OWLClassExpression: - """Get the ranges of an object property - - Args: - prop: object property - - Returns: - ranges of the property - """ - if prop not in self._op_ranges: - ranges = list(self._reasoner.object_property_ranges(prop, direct=True)) - self._op_ranges[prop] = self.intersection(ranges) if len(ranges) > 1 else ranges[0] - return self._op_ranges[prop] - - def get_data_property_domains(self, prop: OWLDataProperty) -> OWLClassExpression: - """Get the domains of a data property - - Args: - prop: data property - - Returns: - domains of the property - """ - if prop not in self._dp_domains: - domains = list(self._reasoner.data_property_domains(prop, direct=True)) - self._dp_domains[prop] = self.intersection(domains) if len(domains) > 1 else domains[0] - return self._dp_domains[prop] - - def get_data_property_ranges(self, prop: OWLDataProperty) -> FrozenSet[OWLDataRange]: - """Get the ranges of a data property - - Args: - prop: data property - - Returns: - ranges of the property - """ - if prop not in self._dp_ranges: - self._dp_ranges[prop] = frozenset(self._reasoner.data_property_ranges(prop, direct=True)) - return self._dp_ranges[prop] - - def most_general_object_properties(self, *, domain: OWLClassExpression, inverse: bool = False) \ - -> Iterable[OWLObjectProperty]: - """Find most general object properties that are applicable to a domain - - Args: - domain: domain for which to search properties - inverse: whether to consider the inverse direction - - Returns: - most general object properties for the given domain - """ - assert isinstance(domain, OWLClassExpression) - - func = self.get_object_property_ranges if inverse else self.get_object_property_domains - - inds_domain = set(self._reasoner.instances(domain)) - for prop in self._object_property_hierarchy.most_general_roles(): - if domain.is_owl_thing() or inds_domain <= set(self._reasoner.instances(func(prop))): - yield prop - - def _data_properties_for_domain(self, domain: OWLClassExpression, data_properties: Iterable[OWLDataProperty]) \ - -> Iterable[OWLDataProperty]: - """Find the data properties that are applicable to a domain - - Args: - domain: domain for which to search properties - data_properties: list of data properties - - Returns: - data properties applicaple for the given domain - """ - assert isinstance(domain, OWLClassExpression) - - inds_domain = set(self._reasoner.instances(domain)) - for prop in data_properties: - if domain.is_owl_thing() or inds_domain <= set(self._reasoner.instances( - self.get_data_property_domains(prop))): - yield prop - - def most_general_data_properties(self, *, domain: OWLClassExpression) -> Iterable[OWLDataProperty]: - """Find most general data properties that are applicable to a domain - - Args: - domain: domain for which to search properties - - Returns: - most general data properties for the given domain - """ - yield from self._data_properties_for_domain(domain, self.get_data_properties()) - - def most_general_boolean_data_properties(self, *, domain: OWLClassExpression) -> Iterable[OWLDataProperty]: - """Find most general boolean data properties that are applicable to a domain - - Args: - domain: domain for which to search properties - - Returns: - most general boolean data properties for the given domain - """ - yield from self._data_properties_for_domain(domain, self.get_boolean_data_properties()) - - def most_general_numeric_data_properties(self, *, domain: OWLClassExpression) -> Iterable[OWLDataProperty]: - """Find most general numeric data properties that are applicable to a domain - - Args: - domain: domain for which to search properties - - Returns: - most general numeric data properties for the given domain - """ - yield from self._data_properties_for_domain(domain, self.get_numeric_data_properties()) - - def most_general_time_data_properties(self, *, domain: OWLClassExpression) -> Iterable[OWLDataProperty]: - """Find most general time data properties that are applicable to a domain - - Args: - domain: domain for which to search properties - - Returns: - most general time data properties for the given domain - """ - yield from self._data_properties_for_domain(domain, self.get_time_data_properties()) - - def most_general_existential_restrictions(self, *, - domain: OWLClassExpression, filler: Optional[OWLClassExpression] = None) \ - -> Iterable[OWLObjectSomeValuesFrom]: - """Find most general existential restrictions that are applicable to a domain - - Args: - domain: domain for which to search properties - filler: optional filler to put in the restriction (not normally used) - - Returns: - most general existential restrictions for the given domain - """ - if filler is None: - filler = self.thing - assert isinstance(filler, OWLClassExpression) - - for prop in self.most_general_object_properties(domain=domain): - yield OWLObjectSomeValuesFrom(property=prop, filler=filler) - - def most_general_universal_restrictions(self, *, - domain: OWLClassExpression, filler: Optional[OWLClassExpression] = None) \ - -> Iterable[OWLObjectAllValuesFrom]: - """Find most general universal restrictions that are applicable to a domain - - Args: - domain: domain for which to search properties - filler: optional filler to put in the restriction (not normally used) - - Returns: - most general universal restrictions for the given domain - """ - if filler is None: - filler = self.thing - assert isinstance(filler, OWLClassExpression) - - for prop in self.most_general_object_properties(domain=domain): - yield OWLObjectAllValuesFrom(property=prop, filler=filler) - - def most_general_existential_restrictions_inverse(self, *, - domain: OWLClassExpression, - filler: Optional[OWLClassExpression] = None) \ - -> Iterable[OWLObjectSomeValuesFrom]: - """Find most general inverse existential restrictions that are applicable to a domain - - Args: - domain: domain for which to search properties - filler: optional filler to put in the restriction (not normally used) - - Returns: - most general existential restrictions over inverse property - """ - if filler is None: - filler = self.thing - assert isinstance(filler, OWLClassExpression) - - for prop in self.most_general_object_properties(domain=domain, inverse=True): - yield OWLObjectSomeValuesFrom(property=prop.get_inverse_property(), filler=filler) - - def most_general_universal_restrictions_inverse(self, *, - domain: OWLClassExpression, - filler: Optional[OWLClassExpression] = None) \ - -> Iterable[OWLObjectAllValuesFrom]: - """Find most general inverse universal restrictions that are applicable to a domain - - Args: - domain: domain for which to search properties - filler: optional filler to put in the restriction (not normally used) - - Returns: - most general universal restrictions over inverse property - """ - if filler is None: - filler = self.thing - assert isinstance(filler, OWLClassExpression) - - for prop in self.most_general_object_properties(domain=domain, inverse=True): - yield OWLObjectAllValuesFrom(property=prop.get_inverse_property(), filler=filler) - # noinspection PyMethodMayBeStatic def intersection(self, ops: Iterable[OWLClassExpression]) -> OWLObjectIntersectionOf: """Create intersection of class expression @@ -368,7 +77,7 @@ def intersection(self, ops: Iterable[OWLClassExpression]) -> OWLObjectIntersecti else: assert isinstance(c, OWLClassExpression) operands.append(c) - # operands = _avoid_overly_redundand_operands(operands) + # operands = _avoid_overly_redundant_operands(operands) return OWLObjectIntersectionOf(operands) # noinspection PyMethodMayBeStatic @@ -391,176 +100,6 @@ def union(self, ops: Iterable[OWLClassExpression]) -> OWLObjectUnionOf: # operands = _avoid_overly_redundand_operands(operands) return OWLObjectUnionOf(operands) - def get_direct_parents(self, concept: OWLClassExpression) -> Iterable[OWLClass]: - """Direct parent concepts - - Args: - concept: concept to find super concepts of - - Returns: - direct parent concepts - """ - assert isinstance(concept, OWLClass) - yield from self._class_hierarchy.super_classes(concept, direct=True) - - def get_all_direct_sub_concepts(self, concept: OWLClassExpression) -> Iterable[OWLClassExpression]: - """All direct sub concepts of a concept - - Args: - concept: parent concept for which to get sub concepts - - Returns: - direct sub concepts - """ - assert isinstance(concept, OWLClass) - yield from self._class_hierarchy.sub_classes(concept, direct=True) - - def get_all_sub_concepts(self, concept: OWLClassExpression) -> Iterable[OWLClassExpression]: - """All sub concepts of a concept - - Args: - concept: parent concept for which to get sub concepts - - Returns: - sub concepts - """ - assert isinstance(concept, OWLClass) - yield from self._class_hierarchy.sub_classes(concept, direct=False) - - def get_concepts(self) -> Iterable[OWLClass]: - """Get all concepts of this concept generator - - Returns: - concepts - """ - yield from self._class_hierarchy.items() - - def get_object_properties(self) -> Iterable[OWLObjectProperty]: - """Get all object properties of this concept generator - - Returns: - object properties - """ - yield from self._object_property_hierarchy.items() - - def get_data_properties(self, ranges: Set[OWLDatatype] = None) -> Iterable[OWLDataProperty]: - """Get all data properties of this concept generator for the given ranges - - Args: - ranges: ranges for which to extract the data properties - - Returns: - data properties for the given range - """ - if ranges is not None: - for dp in self._data_property_hierarchy.items(): - if self.get_data_property_ranges(dp) & ranges: - yield dp - else: - yield from self._data_property_hierarchy.items() - - def get_boolean_data_properties(self) -> Iterable[OWLDataProperty]: - """Get all boolean data properties of this concept generator - - Returns: - boolean data properties - """ - yield from self.get_data_properties({BooleanOWLDatatype}) - - def get_numeric_data_properties(self) -> Iterable[OWLDataProperty]: - """Get all numeric data properties of this concept generator - - Returns: - numeric data properties - """ - yield from self.get_data_properties(NUMERIC_DATATYPES) - - def get_time_data_properties(self) -> Iterable[OWLDataProperty]: - """Get all time data properties of this concept generator - - Returns: - time data properties - """ - yield from self.get_data_properties(TIME_DATATYPES) - - def get_types(self, ind: OWLNamedIndividual, direct: bool = False) -> Iterable[OWLClass]: - """Get the named classes which are (direct) types of the specified individual - - Args: - ind: individual - direct: whether to consider direct types - - Returns: - types of the given individual - """ - all_types = set(self.get_concepts()) - for type_ in self._reasoner.types(ind, direct): - if type_ in all_types or type_ == OWLThing: - yield type_ - - def get_object_properties_for_ind(self, ind: OWLNamedIndividual, direct: bool = True) \ - -> Iterable[OWLObjectProperty]: - """Get the object properties for the given individual - - Args: - ind: individual - direct: Whether only direct properties should be considered (True), or if also - indirect properties should be considered (False). Indirect properties - would be super properties super_p of properties p with ObjectPropertyAssertion(p ind obj) - - Returns: - object properties - """ - properties = set(self.get_object_properties()) - yield from (pe for pe in self._reasoner.ind_object_properties(ind, direct) if pe in properties) - - def get_data_properties_for_ind(self, ind: OWLNamedIndividual, direct: bool = True) -> Iterable[OWLDataProperty]: - """Get the data properties for the given individual - - Args: - ind: individual - direct: Whether only direct properties should be considered (True), or if also - indirect properties should be considered (False). Indirect properties - would be super properties super_p of properties p with ObjectPropertyAssertion(p ind obj) - - Returns: - data properties - """ - properties = set(self.get_data_properties()) - yield from (pe for pe in self._reasoner.ind_data_properties(ind, direct) if pe in properties) - - def get_object_property_values(self, ind: OWLNamedIndividual, - property_: OWLObjectPropertyExpression, - direct: bool = True) -> Iterable[OWLNamedIndividual]: - """Get the object property values for the given individual and property - - Args: - ind: individual - property: object property - direct: Whether only the property property_ should be considered (True), or if also - the values of sub properties of property_ should be considered (False) - - Returns: - individuals - """ - yield from self._reasoner.object_property_values(ind, property_, direct) - - def get_data_property_values(self, ind: OWLNamedIndividual, - property_: OWLDataPropertyExpression, - direct: bool = True) -> Iterable[OWLLiteral]: - """Get the data property values for the given individual and property - - Args: - ind: individual - property: data property - direct: Whether only the property property_ should be considered (True), or if also - the values of sub properties of property_ should be considered (False) - - Returns: - literals - """ - yield from self._reasoner.data_property_values(ind, property_, direct) - # noinspection PyMethodMayBeStatic def existential_restriction(self, filler: OWLClassExpression, property: OWLObjectPropertyExpression) \ -> OWLObjectSomeValuesFrom: @@ -711,42 +250,6 @@ def negation(self, concept: OWLClassExpression) -> OWLClassExpression: else: return concept.get_object_complement_of() - def contains_class(self, concept: OWLClassExpression) -> bool: - """Check if an atomic class is contained within this concept generator - - Args: - concept: atomic class - - Returns: - whether the class is contained in the concept generator - """ - assert isinstance(concept, OWLClass) - return concept in self._class_hierarchy - - def class_hierarchy(self) -> ClassHierarchy: - """Access the Class Hierarchy of this Concept Generator - - Returns: - class hierarchy - """ - return self._class_hierarchy - - def object_property_hierarchy(self) -> ObjectPropertyHierarchy: - """Access the Object property hierarchy of this concept generator - - Returns: - object property hierarchy - """ - return self._object_property_hierarchy - - def data_property_hierarchy(self) -> DatatypePropertyHierarchy: - """Access the Datatype property hierarchy of this concept generator - - Returns: - data property hierarchy - """ - return self._data_property_hierarchy - @property def thing(self) -> OWLClass: """OWL Thing""" @@ -755,8 +258,4 @@ def thing(self) -> OWLClass: @property def nothing(self) -> OWLClass: """OWL Nothing""" - return OWLNothing - - def clean(self): - """Clear any state and caches""" - self._op_domains.clear() + return OWLNothing \ No newline at end of file diff --git a/ontolearn/concept_learner.py b/ontolearn/concept_learner.py index 414ed99f..0967c364 100644 --- a/ontolearn/concept_learner.py +++ b/ontolearn/concept_learner.py @@ -39,10 +39,10 @@ from ontolearn.nces_architectures import LSTM, GRU, SetTransformer from ontolearn.nces_trainer import NCESTrainer, before_pad from ontolearn.nces_utils import SimpleSolution -from owlapy.model import OWLClassExpression, OWLDataProperty, OWLLiteral, OWLNamedIndividual, OWLReasoner -from owlapy.render import DLSyntaxObjectRenderer -from owlapy.parser import DLSyntaxParser -from owlapy.util import OrderedOWLObject +from ontolearn.owlapy.model import OWLClassExpression, OWLDataProperty, OWLLiteral, OWLNamedIndividual, OWLReasoner +from ontolearn.owlapy.render import DLSyntaxObjectRenderer +from ontolearn.owlapy.parser import DLSyntaxParser +from ontolearn.owlapy.util import OrderedOWLObject from sortedcontainers import SortedSet import os @@ -1367,7 +1367,6 @@ def __init__(self, self.population_size = population_size self.num_generations = num_generations self.height_limit = height_limit - self.__setup() def __setup(self): @@ -1397,12 +1396,12 @@ def __setup(self): self.toolbox = self.__build_toolbox() def __build_primitive_set(self) -> gp.PrimitiveSetTyped: - factory = PrimitiveFactory(self.kb) + factory = PrimitiveFactory() union = factory.create_union() intersection = factory.create_intersection() pset = gp.PrimitiveSetTyped("concept_tree", [], OWLClassExpression) - pset.addPrimitive(self.kb.negation, [OWLClassExpression], OWLClassExpression, + pset.addPrimitive(self.kb.generator.negation, [OWLClassExpression], OWLClassExpression, name=OperatorVocabulary.NEGATION) pset.addPrimitive(union, [OWLClassExpression, OWLClassExpression], OWLClassExpression, name=OperatorVocabulary.UNION) @@ -1473,8 +1472,8 @@ class Bool(object): for class_ in self.kb.get_concepts(): pset.addTerminal(class_, OWLClassExpression, name=escape(class_.get_iri().get_remainder())) - pset.addTerminal(self.kb.thing, OWLClassExpression, name=escape(self.kb.thing.get_iri().get_remainder())) - pset.addTerminal(self.kb.nothing, OWLClassExpression, name=escape(self.kb.nothing.get_iri().get_remainder())) + pset.addTerminal(self.kb.generator.thing, OWLClassExpression, name=escape(self.kb.generator.thing.get_iri().get_remainder())) + pset.addTerminal(self.kb.generator.nothing, OWLClassExpression, name=escape(self.kb.generator.nothing.get_iri().get_remainder())) return pset def __build_toolbox(self) -> base.Toolbox: @@ -1583,8 +1582,12 @@ def best_hypotheses(self, n: int = 5, key: str = 'fitness') -> Iterable[EvoLearn def _get_top_hypotheses(self, population: List[Tree], n: int = 5, key: str = 'fitness') \ -> Iterable[EvoLearnerNode]: - best_inds = tools.selBest(population, k=n, fit_attr=key) - best_concepts = [gp.compile(ind, self.pset) for ind in best_inds] + best_inds = tools.selBest(population, k=n*10, fit_attr=key) + best_inds_distinct = [] + for ind in best_inds: + if ind not in best_inds_distinct: + best_inds_distinct.append(ind) + best_concepts = [gp.compile(ind, self.pset) for ind in best_inds_distinct[:n]] for con, ind in zip(best_concepts, best_inds): individuals_count = len(self.kb.individuals_set(con)) diff --git a/ontolearn/core/owl/hierarchy.py b/ontolearn/core/owl/hierarchy.py index e151902c..f19c2b5f 100644 --- a/ontolearn/core/owl/hierarchy.py +++ b/ontolearn/core/owl/hierarchy.py @@ -3,7 +3,7 @@ from functools import reduce from typing import Dict, Iterable, Tuple, overload, TypeVar, Generic, Type, cast, Optional, FrozenSet, Set -from owlapy.model import OWLClass, OWLReasoner, OWLObjectProperty, OWLDataProperty, OWLTopObjectProperty, \ +from ontolearn.owlapy.model import OWLClass, OWLReasoner, OWLObjectProperty, OWLDataProperty, OWLTopObjectProperty, \ OWLBottomObjectProperty, OWLTopDataProperty, OWLBottomDataProperty, OWLThing, OWLNothing, HasIRI _S = TypeVar('_S', bound=HasIRI) #: diff --git a/ontolearn/core/owl/utils.py b/ontolearn/core/owl/utils.py index 24e19506..c9ba6948 100644 --- a/ontolearn/core/owl/utils.py +++ b/ontolearn/core/owl/utils.py @@ -2,7 +2,7 @@ from functools import singledispatchmethod from typing import Iterable, Generic, TypeVar, Callable, List -from owlapy.model import OWLDataRange, OWLLiteral, OWLObject, OWLClass, OWLObjectProperty, OWLObjectSomeValuesFrom, \ +from ontolearn.owlapy.model import OWLDataRange, OWLLiteral, OWLObject, OWLClass, OWLObjectProperty, OWLObjectSomeValuesFrom, \ OWLObjectAllValuesFrom, OWLObjectUnionOf, OWLObjectIntersectionOf, OWLObjectComplementOf, OWLObjectInverseOf, \ OWLObjectCardinalityRestriction, OWLObjectHasSelf, OWLObjectHasValue, OWLObjectOneOf, OWLNamedIndividual, \ OWLObjectMinCardinality, OWLObjectExactCardinality, OWLObjectMaxCardinality, OWLClassExpression, OWLThing, \ @@ -10,7 +10,7 @@ OWLDataCardinalityRestriction, OWLDatatype, OWLDataHasValue, OWLDataUnionOf, OWLDataIntersectionOf, \ OWLDataExactCardinality, OWLDataMaxCardinality, OWLDataMinCardinality, OWLDataProperty -from owlapy.util import OrderedOWLObject, iter_count +from ontolearn.owlapy.util import OrderedOWLObject, iter_count from sortedcontainers import SortedSet diff --git a/ontolearn/ea_initialization.py b/ontolearn/ea_initialization.py index 2be33210..fd5f1380 100644 --- a/ontolearn/ea_initialization.py +++ b/ontolearn/ea_initialization.py @@ -4,7 +4,7 @@ from itertools import chain, cycle from ontolearn.ea_utils import OperatorVocabulary, Tree, escape, owlliteral_to_primitive_string from ontolearn.knowledge_base import KnowledgeBase -from owlapy.model import OWLClass, OWLClassExpression, OWLDataProperty, OWLLiteral, OWLNamedIndividual, \ +from ontolearn.owlapy.model import OWLClass, OWLClassExpression, OWLDataProperty, OWLLiteral, OWLNamedIndividual, \ OWLObjectProperty, OWLThing import random from abc import ABCMeta, abstractmethod diff --git a/ontolearn/ea_utils.py b/ontolearn/ea_utils.py index 90480251..f977629c 100644 --- a/ontolearn/ea_utils.py +++ b/ontolearn/ea_utils.py @@ -2,14 +2,15 @@ from typing import Callable, Final, List, Optional, Tuple, Union from deap.gp import Primitive, Terminal -from owlapy.model import OWLObjectPropertyExpression, OWLObjectSomeValuesFrom, OWLObjectUnionOf, \ + +from ontolearn.concept_generator import ConceptGenerator +from ontolearn.owlapy.model import OWLObjectPropertyExpression, OWLObjectSomeValuesFrom, OWLObjectUnionOf, \ OWLClassExpression, OWLDataHasValue, OWLDataPropertyExpression, OWLDataSomeValuesFrom, OWLLiteral, \ OWLObjectAllValuesFrom, OWLObjectIntersectionOf, NUMERIC_DATATYPES, OWLDataProperty, OWLObjectProperty, \ OWLObjectExactCardinality, OWLObjectMaxCardinality, OWLObjectMinCardinality -from ontolearn.knowledge_base import KnowledgeBase import re -from owlapy.model.providers import OWLDatatypeMinExclusiveRestriction, OWLDatatypeMinInclusiveRestriction, \ +from ontolearn.owlapy.model.providers import OWLDatatypeMinExclusiveRestriction, OWLDatatypeMinInclusiveRestriction, \ OWLDatatypeMaxExclusiveRestriction, OWLDatatypeMaxInclusiveRestriction @@ -18,22 +19,22 @@ class PrimitiveFactory: - __slots__ = 'knowledge_base' + __slots__ = 'generator' - def __init__(self, knowledge_base: KnowledgeBase): - self.knowledge_base = knowledge_base + def __init__(self): + self.generator = ConceptGenerator() def create_union(self) -> Callable[[OWLClassExpression, OWLClassExpression], OWLObjectUnionOf]: def union(A: OWLClassExpression, B: OWLClassExpression) -> OWLObjectUnionOf: - return self.knowledge_base.union([A, B]) + return self.generator.union([A, B]) return union def create_intersection(self) -> Callable[[OWLClassExpression, OWLClassExpression], OWLObjectIntersectionOf]: def intersection(A: OWLClassExpression, B: OWLClassExpression) -> OWLObjectIntersectionOf: - return self.knowledge_base.intersection([A, B]) + return self.generator.intersection([A, B]) return intersection @@ -42,10 +43,10 @@ def create_existential_universal(self, property_: OWLObjectPropertyExpression) \ Callable[[OWLClassExpression], OWLObjectAllValuesFrom]]: def existential_restriction(filler: OWLClassExpression) -> OWLObjectSomeValuesFrom: - return self.knowledge_base.existential_restriction(filler, property_) + return self.generator.existential_restriction(filler, property_) def universal_restriction(filler: OWLClassExpression) -> OWLObjectAllValuesFrom: - return self.knowledge_base.universal_restriction(filler, property_) + return self.generator.universal_restriction(filler, property_) return existential_restriction, universal_restriction @@ -55,13 +56,13 @@ def create_card_restrictions(self, property_: OWLObjectPropertyExpression) \ Callable[[int, OWLClassExpression], OWLObjectExactCardinality]]: def min_cardinality(card: int, filler: OWLClassExpression) -> OWLObjectMinCardinality: - return self.knowledge_base.min_cardinality_restriction(filler, property_, card) + return self.generator.min_cardinality_restriction(filler, property_, card) def max_cardinality(card: int, filler: OWLClassExpression) -> OWLObjectMaxCardinality: - return self.knowledge_base.max_cardinality_restriction(filler, property_, card) + return self.generator.max_cardinality_restriction(filler, property_, card) def exact_cardinality(card: int, filler: OWLClassExpression) -> OWLObjectExactCardinality: - return self.knowledge_base.exact_cardinality_restriction(filler, property_, card) + return self.generator.exact_cardinality_restriction(filler, property_, card) return min_cardinality, max_cardinality, exact_cardinality @@ -71,26 +72,26 @@ def create_data_some_values(self, property_: OWLDataPropertyExpression) \ def data_some_min_inclusive(value: OWLLiteral) -> OWLDataSomeValuesFrom: filler = OWLDatatypeMinInclusiveRestriction(value) - return self.knowledge_base.data_existential_restriction(filler, property_) + return self.generator.data_existential_restriction(filler, property_) def data_some_max_inclusive(value: OWLLiteral) -> OWLDataSomeValuesFrom: filler = OWLDatatypeMaxInclusiveRestriction(value) - return self.knowledge_base.data_existential_restriction(filler, property_) + return self.generator.data_existential_restriction(filler, property_) def data_some_min_exclusive(value: OWLLiteral) -> OWLDataSomeValuesFrom: filler = OWLDatatypeMinExclusiveRestriction(value) - return self.knowledge_base.data_existential_restriction(filler, property_) + return self.generator.data_existential_restriction(filler, property_) def data_some_max_exclusive(value: OWLLiteral) -> OWLDataSomeValuesFrom: filler = OWLDatatypeMaxExclusiveRestriction(value) - return self.knowledge_base.data_existential_restriction(filler, property_) + return self.generator.data_existential_restriction(filler, property_) return data_some_min_inclusive, data_some_max_inclusive, data_some_min_exclusive, data_some_max_exclusive def create_data_has_value(self, property_: OWLDataPropertyExpression) -> Callable[[OWLLiteral], OWLDataHasValue]: def data_has_value(value: OWLLiteral) -> OWLDataHasValue: - return self.knowledge_base.data_has_value_restriction(value, property_) + return self.generator.data_has_value_restriction(value, property_) return data_has_value diff --git a/ontolearn/endpoint/nces_endpoint b/ontolearn/endpoint/nces_endpoint index d27a8b91..0277903e 100755 --- a/ontolearn/endpoint/nces_endpoint +++ b/ontolearn/endpoint/nces_endpoint @@ -1,6 +1,5 @@ #!/usr/bin/env python -import os import threading from datetime import datetime from argparse import ArgumentParser @@ -8,13 +7,12 @@ from functools import wraps, update_wrapper from flask import Flask, request, Response, abort from flask import make_response -import ontolearn from ontolearn.concept_learner import NCES from ontolearn.utils.log_config import setup_logging -from owlapy.model import OWLNamedIndividual, OWLOntologyManager, OWLOntology, AddImport, \ +from ontolearn.owlapy.model import OWLNamedIndividual, OWLOntologyManager, OWLOntology, AddImport, \ OWLImportsDeclaration, OWLClass, OWLEquivalentClassesAxiom, IRI -from owlapy.owlready2 import OWLOntologyManager_Owlready2 +from ontolearn.owlapy.owlready2 import OWLOntologyManager_Owlready2 import time, io from typing import Final diff --git a/ontolearn/endpoint/simple_drill_endpoint b/ontolearn/endpoint/simple_drill_endpoint index e0ed7c8f..6d4bd8ac 100644 --- a/ontolearn/endpoint/simple_drill_endpoint +++ b/ontolearn/endpoint/simple_drill_endpoint @@ -5,19 +5,17 @@ import threading from argparse import ArgumentParser from datetime import datetime from functools import wraps, update_wrapper -from typing import List from flask import Flask, request, Response, abort from flask import make_response -from owlapy.model import OWLNamedIndividual +from ontolearn.owlapy.model import OWLNamedIndividual from experiments_standard import ClosedWorld_ReasonerFactory -from ontolearn import KnowledgeBase +from ontolearn.knowledge_base import KnowledgeBase from ontolearn.heuristics import Reward from ontolearn.metrics import F1 from ontolearn.concept_learner import Drill from ontolearn.refinement_operators import LengthBasedRefinement -from ontolearn.search import Node def nocache(view): @@ -60,7 +58,7 @@ def create_flask_app(): app.logger.debug(learning_problem) no_of_hypotheses = request.form.get("no_of_hypotheses", 1, type=int) try: - from owlapy.model import IRI + from ontolearn.owlapy.model import IRI typed_pos = set(map(OWLNamedIndividual, map(IRI.create, set(learning_problem["positives"])))) typed_neg = set(map(OWLNamedIndividual, map(IRI.create, set(learning_problem["negatives"])))) drill.fit(typed_pos, typed_neg, diff --git a/ontolearn/experiments.py b/ontolearn/experiments.py index f3ca8ce1..e4c23b40 100644 --- a/ontolearn/experiments.py +++ b/ontolearn/experiments.py @@ -6,7 +6,7 @@ import numpy as np from sklearn.model_selection import KFold -from owlapy.model import OWLNamedIndividual, IRI +from ontolearn.owlapy.model import OWLNamedIndividual, IRI class Experiments: diff --git a/ontolearn/knowledge_base.py b/ontolearn/knowledge_base.py index 957ab967..c349bb26 100644 --- a/ontolearn/knowledge_base.py +++ b/ontolearn/knowledge_base.py @@ -1,17 +1,20 @@ import logging import random from functools import singledispatchmethod -from typing import Iterable, Optional, Callable, overload, Union, FrozenSet -from owlapy.owlready2 import OWLOntology_Owlready2, OWLOntologyManager_Owlready2, OWLReasoner_Owlready2 -from owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker -from owlapy.model import OWLOntologyManager, OWLOntology, OWLReasoner, OWLClassExpression, OWLNamedIndividual, \ - OWLObjectProperty, OWLClass, OWLDataProperty, IRI -from owlapy.render import DLSyntaxObjectRenderer -from owlapy.util import iter_count, LRUCache +from typing import Iterable, Optional, Callable, overload, Union, FrozenSet, Set, Dict +from ontolearn.owlapy.owlready2 import OWLOntology_Owlready2, OWLOntologyManager_Owlready2, OWLReasoner_Owlready2 +from ontolearn.owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker +from ontolearn.owlapy.model import OWLOntologyManager, OWLOntology, OWLReasoner, OWLClassExpression, OWLNamedIndividual, \ + OWLObjectProperty, OWLClass, OWLDataProperty, IRI, OWLDataRange, OWLObjectSomeValuesFrom, OWLObjectAllValuesFrom, \ + OWLDatatype, BooleanOWLDatatype, NUMERIC_DATATYPES, TIME_DATATYPES, OWLThing, OWLObjectPropertyExpression, \ + OWLLiteral, OWLDataPropertyExpression +from ontolearn.owlapy.render import DLSyntaxObjectRenderer +from ontolearn.owlapy.util import iter_count, LRUCache from .abstracts import AbstractKnowledgeBase, AbstractScorer, EncodedLearningProblem, AbstractLearningProblem from .concept_generator import ConceptGenerator from .core.owl.utils import OWLClassExpressionLengthMetric from .learning_problem import PosNegLPStandard, EncodedPosNegLPStandard +from ontolearn.core.owl.hierarchy import ClassHierarchy, ObjectPropertyHierarchy, DatatypePropertyHierarchy Factory = Callable @@ -47,7 +50,9 @@ class EvaluatedConcept: # TODO:CD: __init__ is overcrowded. This bit can/should be simplified to few lines # TODO:CD: Namings are not self-explanatory: User does not need to know # a) factory programming pattern b) Manager Classes etc inadvertently increases cognitive load -class KnowledgeBase(AbstractKnowledgeBase, ConceptGenerator): + + +class KnowledgeBase(AbstractKnowledgeBase): """Knowledge Base Class is used to represent an OWL knowledge base in Ontolearn, meaning that it represents the Tbox and Abox along with concept hierarchies @@ -62,7 +67,9 @@ class KnowledgeBase(AbstractKnowledgeBase, ConceptGenerator): individuals_cache_size: how many individuals of class expressions to cache """ __slots__ = '_manager', '_ontology', '_reasoner', '_length_metric', \ - '_ind_set', '_ind_cache', 'path', 'use_individuals_cache' + '_ind_set', '_ind_cache', 'path', 'use_individuals_cache', 'generator', '_class_hierarchy', \ + '_object_property_hierarchy', '_data_property_hierarchy', '_op_domains', '_op_ranges', '_dp_domains', \ + '_dp_ranges' _manager: OWLOntologyManager _ontology: OWLOntology @@ -75,9 +82,16 @@ class KnowledgeBase(AbstractKnowledgeBase, ConceptGenerator): path: str use_individuals_cache: bool + generator: ConceptGenerator + + _class_hierarchy: ClassHierarchy + _object_property_hierarchy: ObjectPropertyHierarchy + _data_property_hierarchy: DatatypePropertyHierarchy + _op_domains: Dict[OWLObjectProperty, OWLClassExpression] + _op_ranges: Dict[OWLObjectProperty, OWLClassExpression] + _dp_domains: Dict[OWLDataProperty, OWLClassExpression] + _dp_ranges: Dict[OWLDataProperty, FrozenSet[OWLDataRange]] - # The simplest way to create an instance of this class is by just passing the 'path' of the OWL knowledge base in - # the constructor @overload def __init__(self, *, path: str, @@ -110,15 +124,14 @@ def __init__(self, *, length_metric: Optional[OWLClassExpressionLengthMetric] = None, individuals_cache_size=128, - backend_store: bool = False): + backend_store: bool = False, + class_hierarchy: Optional[ClassHierarchy] = None, + object_property_hierarchy: Optional[ObjectPropertyHierarchy] = None, + data_property_hierarchy: Optional[DatatypePropertyHierarchy] = None + ): AbstractKnowledgeBase.__init__(self) self.path = path - """ - In the code below, until the first method of the class, - we assign some of the class attributes depending on - the arguments passed on the instance initialization. - """ if ontology is not None: self._manager = ontology.get_owl_ontology_manager() self._ontology = ontology @@ -136,7 +149,7 @@ def __init__(self, *, raise TypeError("path missing") self._ontology = self._manager.load_ontology(IRI.create('file://' + self.path)) - from owlapy.owlready2 import OWLOntologyManager_Owlready2 + from ontolearn.owlapy.owlready2 import OWLOntologyManager_Owlready2 if isinstance(self._manager, OWLOntologyManager_Owlready2) and backend_store: self._manager.save_world() logger.debug("Synced world to backend store") @@ -156,9 +169,26 @@ def __init__(self, *, else: self._length_metric = _Default_ClassExpressionLengthMetricFactory() - ConceptGenerator.__init__(self, reasoner=self._reasoner) + if class_hierarchy is None: + class_hierarchy = ClassHierarchy(self._reasoner) + + if object_property_hierarchy is None: + object_property_hierarchy = ObjectPropertyHierarchy(self._reasoner) - from owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker + if data_property_hierarchy is None: + data_property_hierarchy = DatatypePropertyHierarchy(self._reasoner) + + self._class_hierarchy = class_hierarchy + self._object_property_hierarchy = object_property_hierarchy + self._data_property_hierarchy = data_property_hierarchy + + self._op_domains = dict() + self._op_ranges = dict() + self._dp_domains = dict() + self._dp_ranges = dict() + self.generator = ConceptGenerator() + + from ontolearn.owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker if isinstance(self._reasoner, OWLReasoner_FastInstanceChecker): self._ind_set = self._reasoner._ind_set # performance hack else: @@ -171,8 +201,6 @@ def __init__(self, *, self.describe() - """____________________________↓ Class Methods ↓____________________________""" - def ontology(self) -> OWLOntology: """Get the root Ontology loaded in this knowledge base @@ -214,6 +242,11 @@ def ignore_and_copy(self, ignored_classes: Optional[Iterable[OWLClass]] = None, new._ind_set = self._ind_set new.path = self.path new.use_individuals_cache = self.use_individuals_cache + new.generator = self.generator + new._op_domains = self._op_domains + new._op_ranges = self._op_ranges + new._dp_domains = self._dp_domains + new._dp_ranges = self._dp_ranges if self.use_individuals_cache: new._ind_cache = LRUCache(maxsize=self._ind_cache.maxsize) @@ -230,26 +263,20 @@ def ignore_and_copy(self, ignored_classes: Optional[Iterable[OWLClass]] = None, if logger.isEnabledFor(logging.INFO): r = DLSyntaxObjectRenderer() logger.info('Concepts to ignore: {0}'.format(' '.join(map(r.render, owl_concepts_to_ignore)))) - class_hierarchy = self._class_hierarchy.restrict_and_copy(remove=owl_concepts_to_ignore) + new._class_hierarchy = self._class_hierarchy.restrict_and_copy(remove=owl_concepts_to_ignore) else: - class_hierarchy = self._class_hierarchy + new._class_hierarchy = self._class_hierarchy if ignored_object_properties is not None: - object_property_hierarchy = self._object_property_hierarchy.restrict_and_copy( + new._object_property_hierarchy = self._object_property_hierarchy.restrict_and_copy( remove=ignored_object_properties) else: - object_property_hierarchy = self._object_property_hierarchy + new._object_property_hierarchy = self._object_property_hierarchy if ignored_data_properties is not None: - data_property_hierarchy = self._data_property_hierarchy.restrict_and_copy(remove=ignored_data_properties) + new._data_property_hierarchy = self._data_property_hierarchy.restrict_and_copy(remove=ignored_data_properties) else: - data_property_hierarchy = self._data_property_hierarchy - - ConceptGenerator.__init__(new, - reasoner=self._reasoner, - class_hierarchy=class_hierarchy, - object_property_hierarchy=object_property_hierarchy, - data_property_hierarchy=data_property_hierarchy) + new._data_property_hierarchy = self._data_property_hierarchy return new @@ -276,7 +303,7 @@ def clean(self): use this method before the initialization to avoid data mismatch. """ - ConceptGenerator.clean(self) + self._op_domains.clear() if self.use_individuals_cache: self._ind_cache.cache_clear() @@ -285,7 +312,7 @@ def _cache_individuals(self, ce: OWLClassExpression) -> None: raise TypeError if ce in self._ind_cache: return - from owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker + from ontolearn.owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker if isinstance(self._reasoner, OWLReasoner_FastInstanceChecker): self._ind_cache[ce] = self._reasoner._find_instances(ce) # performance hack else: @@ -500,3 +527,414 @@ async def evaluate_concept_async(self, concept: OWLClassExpression, quality_func NotImplementedError: This method is not implemented yet """ raise NotImplementedError + + def get_leaf_concepts(self, concept: OWLClass): + """Get leaf classes + + Args: + concept: atomic class for which to find leaf classes + + Returns: + Leaf classes + + { x \\| (x subClassOf concept) AND not exist y: y subClassOf x )} """ + assert isinstance(concept, OWLClass) + yield from self._class_hierarchy.leaves(of=concept) + + def get_direct_sub_concepts(self, concept: OWLClass) -> Iterable[OWLClass]: + """Direct sub classes of atomic class + + Args: + concept: atomic concept + + Returns: + direct sub classes of concept + + { x \\| ( x subClassOf concept )} """ + assert isinstance(concept, OWLClass) + yield from self._class_hierarchy.sub_classes(concept, direct=True) + + def get_object_property_domains(self, prop: OWLObjectProperty) -> OWLClassExpression: + """Get the domains of an object property + + Args: + prop: object property + + Returns: + domains of the property + """ + if prop not in self._op_domains: + domains = list(self._reasoner.object_property_domains(prop, direct=True)) + self._op_domains[prop] = self.generator.intersection(domains) if len(domains) > 1 else domains[0] + return self._op_domains[prop] + + def get_object_property_ranges(self, prop: OWLObjectProperty) -> OWLClassExpression: + """Get the ranges of an object property + + Args: + prop: object property + + Returns: + ranges of the property + """ + if prop not in self._op_ranges: + ranges = list(self._reasoner.object_property_ranges(prop, direct=True)) + self._op_ranges[prop] = self.generator.intersection(ranges) if len(ranges) > 1 else ranges[0] + return self._op_ranges[prop] + + def get_data_property_domains(self, prop: OWLDataProperty) -> OWLClassExpression: + """Get the domains of a data property + + Args: + prop: data property + + Returns: + domains of the property + """ + if prop not in self._dp_domains: + domains = list(self._reasoner.data_property_domains(prop, direct=True)) + self._dp_domains[prop] = self.generator.intersection(domains) if len(domains) > 1 else domains[0] + return self._dp_domains[prop] + + def get_data_property_ranges(self, prop: OWLDataProperty) -> FrozenSet[OWLDataRange]: + """Get the ranges of a data property + + Args: + prop: data property + + Returns: + ranges of the property + """ + if prop not in self._dp_ranges: + self._dp_ranges[prop] = frozenset(self._reasoner.data_property_ranges(prop, direct=True)) + return self._dp_ranges[prop] + + def most_general_data_properties(self, *, domain: OWLClassExpression) -> Iterable[OWLDataProperty]: + """Find most general data properties that are applicable to a domain + + Args: + domain: domain for which to search properties + + Returns: + most general data properties for the given domain + """ + yield from self._data_properties_for_domain(domain, self.get_data_properties()) + + def most_general_boolean_data_properties(self, *, domain: OWLClassExpression) -> Iterable[OWLDataProperty]: + """Find most general boolean data properties that are applicable to a domain + + Args: + domain: domain for which to search properties + + Returns: + most general boolean data properties for the given domain + """ + yield from self._data_properties_for_domain(domain, self.get_boolean_data_properties()) + + def most_general_numeric_data_properties(self, *, domain: OWLClassExpression) -> Iterable[OWLDataProperty]: + """Find most general numeric data properties that are applicable to a domain + + Args: + domain: domain for which to search properties + + Returns: + most general numeric data properties for the given domain + """ + yield from self._data_properties_for_domain(domain, self.get_numeric_data_properties()) + + def most_general_time_data_properties(self, *, domain: OWLClassExpression) -> Iterable[OWLDataProperty]: + """Find most general time data properties that are applicable to a domain + + Args: + domain: domain for which to search properties + + Returns: + most general time data properties for the given domain + """ + yield from self._data_properties_for_domain(domain, self.get_time_data_properties()) + + def most_general_existential_restrictions(self, *, + domain: OWLClassExpression, filler: Optional[OWLClassExpression] = None) \ + -> Iterable[OWLObjectSomeValuesFrom]: + """Find most general existential restrictions that are applicable to a domain + + Args: + domain: domain for which to search properties + filler: optional filler to put in the restriction (not normally used) + + Returns: + most general existential restrictions for the given domain + """ + if filler is None: + filler = self.generator.thing + assert isinstance(filler, OWLClassExpression) + + for prop in self.most_general_object_properties(domain=domain): + yield OWLObjectSomeValuesFrom(property=prop, filler=filler) + + def most_general_universal_restrictions(self, *, + domain: OWLClassExpression, filler: Optional[OWLClassExpression] = None) \ + -> Iterable[OWLObjectAllValuesFrom]: + """Find most general universal restrictions that are applicable to a domain + + Args: + domain: domain for which to search properties + filler: optional filler to put in the restriction (not normally used) + + Returns: + most general universal restrictions for the given domain + """ + if filler is None: + filler = self.generator.thing + assert isinstance(filler, OWLClassExpression) + + for prop in self.most_general_object_properties(domain=domain): + yield OWLObjectAllValuesFrom(property=prop, filler=filler) + + def most_general_existential_restrictions_inverse(self, *, + domain: OWLClassExpression, + filler: Optional[OWLClassExpression] = None) \ + -> Iterable[OWLObjectSomeValuesFrom]: + """Find most general inverse existential restrictions that are applicable to a domain + + Args: + domain: domain for which to search properties + filler: optional filler to put in the restriction (not normally used) + + Returns: + most general existential restrictions over inverse property + """ + if filler is None: + filler = self.generator.thing + assert isinstance(filler, OWLClassExpression) + + for prop in self.most_general_object_properties(domain=domain, inverse=True): + yield OWLObjectSomeValuesFrom(property=prop.get_inverse_property(), filler=filler) + + def most_general_universal_restrictions_inverse(self, *, + domain: OWLClassExpression, + filler: Optional[OWLClassExpression] = None) \ + -> Iterable[OWLObjectAllValuesFrom]: + """Find most general inverse universal restrictions that are applicable to a domain + + Args: + domain: domain for which to search properties + filler: optional filler to put in the restriction (not normally used) + + Returns: + most general universal restrictions over inverse property + """ + if filler is None: + filler = self.generator.thing + assert isinstance(filler, OWLClassExpression) + + for prop in self.most_general_object_properties(domain=domain, inverse=True): + yield OWLObjectAllValuesFrom(property=prop.get_inverse_property(), filler=filler) + + def get_direct_parents(self, concept: OWLClassExpression) -> Iterable[OWLClass]: + """Direct parent concepts + + Args: + concept: concept to find super concepts of + + Returns: + direct parent concepts + """ + assert isinstance(concept, OWLClass) + yield from self._class_hierarchy.super_classes(concept, direct=True) + + def get_all_direct_sub_concepts(self, concept: OWLClassExpression) -> Iterable[OWLClassExpression]: + """All direct sub concepts of a concept + + Args: + concept: parent concept for which to get sub concepts + + Returns: + direct sub concepts + """ + assert isinstance(concept, OWLClass) + yield from self._class_hierarchy.sub_classes(concept, direct=True) + + def get_all_sub_concepts(self, concept: OWLClassExpression) -> Iterable[OWLClassExpression]: + """All sub concepts of a concept + + Args: + concept: parent concept for which to get sub concepts + + Returns: + sub concepts + """ + assert isinstance(concept, OWLClass) + yield from self._class_hierarchy.sub_classes(concept, direct=False) + + def get_concepts(self) -> Iterable[OWLClass]: + """Get all concepts of this concept generator + + Returns: + concepts + """ + yield from self._class_hierarchy.items() + + def get_object_properties(self) -> Iterable[OWLObjectProperty]: + """Get all object properties of this concept generator + + Returns: + object properties + """ + + yield from self._object_property_hierarchy.items() + + def get_data_properties(self, ranges: Set[OWLDatatype] = None) -> Iterable[OWLDataProperty]: + """Get all data properties of this concept generator for the given ranges + + Args: + ranges: ranges for which to extract the data properties + + Returns: + data properties for the given range + """ + if ranges is not None: + for dp in self._data_property_hierarchy.items(): + if self.get_data_property_ranges(dp) & ranges: + yield dp + else: + yield from self._data_property_hierarchy.items() + + def get_boolean_data_properties(self) -> Iterable[OWLDataProperty]: + """Get all boolean data properties of this concept generator + + Returns: + boolean data properties + """ + yield from self.get_data_properties({BooleanOWLDatatype}) + + def get_numeric_data_properties(self) -> Iterable[OWLDataProperty]: + """Get all numeric data properties of this concept generator + + Returns: + numeric data properties + """ + yield from self.get_data_properties(NUMERIC_DATATYPES) + + def get_time_data_properties(self) -> Iterable[OWLDataProperty]: + """Get all time data properties of this concept generator + + Returns: + time data properties + """ + yield from self.get_data_properties(TIME_DATATYPES) + + def get_types(self, ind: OWLNamedIndividual, direct: bool = False) -> Iterable[OWLClass]: + """Get the named classes which are (direct) types of the specified individual + + Args: + ind: individual + direct: whether to consider direct types + + Returns: + types of the given individual + """ + all_types = set(self.get_concepts()) + for type_ in self._reasoner.types(ind, direct): + if type_ in all_types or type_ == OWLThing: + yield type_ + + def get_object_properties_for_ind(self, ind: OWLNamedIndividual, direct: bool = True) \ + -> Iterable[OWLObjectProperty]: + """Get the object properties for the given individual + + Args: + ind: individual + direct: Whether only direct properties should be considered (True), or if also + indirect properties should be considered (False). Indirect properties + would be super properties super_p of properties p with ObjectPropertyAssertion(p ind obj) + + Returns: + object properties + """ + properties = set(self.get_object_properties()) + yield from (pe for pe in self._reasoner.ind_object_properties(ind, direct) if pe in properties) + + def get_data_properties_for_ind(self, ind: OWLNamedIndividual, direct: bool = True) -> Iterable[OWLDataProperty]: + """Get the data properties for the given individual + + Args: + ind: individual + direct: Whether only direct properties should be considered (True), or if also + indirect properties should be considered (False). Indirect properties + would be super properties super_p of properties p with ObjectPropertyAssertion(p ind obj) + + Returns: + data properties + """ + properties = set(self.get_data_properties()) + yield from (pe for pe in self._reasoner.ind_data_properties(ind, direct) if pe in properties) + + def get_object_property_values(self, ind: OWLNamedIndividual, + property_: OWLObjectPropertyExpression, + direct: bool = True) -> Iterable[OWLNamedIndividual]: + """Get the object property values for the given individual and property + + Args: + ind: individual + property_: object property + direct: Whether only the property property_ should be considered (True), or if also + the values of sub properties of property_ should be considered (False) + + Returns: + individuals + """ + yield from self._reasoner.object_property_values(ind, property_, direct) + + def get_data_property_values(self, ind: OWLNamedIndividual, + property_: OWLDataPropertyExpression, + direct: bool = True) -> Iterable[OWLLiteral]: + """Get the data property values for the given individual and property + + Args: + ind: individual + property_: data property + direct: Whether only the property property_ should be considered (True), or if also + the values of sub properties of property_ should be considered (False) + + Returns: + literals + """ + yield from self._reasoner.data_property_values(ind, property_, direct) + + def contains_class(self, concept: OWLClassExpression) -> bool: + """Check if an atomic class is contained within this concept generator + + Args: + concept: atomic class + + Returns: + whether the class is contained in the concept generator + """ + assert isinstance(concept, OWLClass) + return concept in self._class_hierarchy + + def class_hierarchy(self) -> ClassHierarchy: + """Access the Class Hierarchy of this Concept Generator + + Returns: + class hierarchy + """ + return self._class_hierarchy + + def object_property_hierarchy(self) -> ObjectPropertyHierarchy: + """Access the Object property hierarchy of this concept generator + + Returns: + object property hierarchy + """ + return self._object_property_hierarchy + + def data_property_hierarchy(self) -> DatatypePropertyHierarchy: + """Access the Datatype property hierarchy of this concept generator + + Returns: + data property hierarchy + """ + return self._data_property_hierarchy + diff --git a/ontolearn/learning_problem.py b/ontolearn/learning_problem.py index b857c838..f905e0e5 100644 --- a/ontolearn/learning_problem.py +++ b/ontolearn/learning_problem.py @@ -2,9 +2,9 @@ from typing import Set, Optional, TYPE_CHECKING if TYPE_CHECKING: - from ontolearn import KnowledgeBase + from ontolearn.knowledge_base import KnowledgeBase from ontolearn.abstracts import AbstractLearningProblem, EncodedLearningProblem, EncodedPosNegLPStandardKind -from owlapy.model import OWLNamedIndividual +from ontolearn.owlapy.model import OWLNamedIndividual logger = logging.getLogger(__name__) diff --git a/ontolearn/learning_problem_generator.py b/ontolearn/learning_problem_generator.py index 456338ea..8b6dad83 100644 --- a/ontolearn/learning_problem_generator.py +++ b/ontolearn/learning_problem_generator.py @@ -4,7 +4,7 @@ import numpy as np -from owlapy.model import OWLClassExpression, OWLOntologyManager, OWLOntology, AddImport, OWLImportsDeclaration, \ +from ontolearn.owlapy.model import OWLClassExpression, OWLOntologyManager, OWLOntology, AddImport, OWLImportsDeclaration, \ OWLClass, OWLEquivalentClassesAxiom, IRI, OWLNamedIndividual, OWLAnnotationAssertionAxiom, OWLAnnotation, \ OWLAnnotationProperty, OWLLiteral from ontolearn.knowledge_base import KnowledgeBase @@ -66,7 +66,7 @@ def export_concepts(self, concepts: List[Node], path: str): assert isinstance(self.kb, KnowledgeBase) - from owlapy.owlready2 import OWLOntologyManager_Owlready2 + from ontolearn.owlapy.owlready2 import OWLOntologyManager_Owlready2 manager: OWLOntologyManager = OWLOntologyManager_Owlready2() ontology: OWLOntology = manager.create_ontology(IRI.create(NS)) @@ -176,7 +176,7 @@ def class_expression_sanity_checking(x): def balanced_n_sampled_lp(self, n: int, string_all_pos: set): - string_all_neg = set(self.kb.individuals(self.kb.thing)).difference(string_all_pos) + string_all_neg = set(self.kb.individuals(self.kb.generator.thing)).difference(string_all_pos) for i in range(n): string_balanced_pos, string_balanced_neg = balanced_sets(string_all_pos, string_all_neg) assert len(string_balanced_pos) >= self.min_num_instances @@ -354,8 +354,8 @@ def f1(x): def f2(x): return self.max_length >= len(x.length) >= self.min_length - rl_state = RL_State(self.kb.thing, parent_node=None, is_root=True) - rl_state.length = self.kb.concept_len(self.kb.thing) + rl_state = RL_State(self.kb.generator.thing, parent_node=None, is_root=True) + rl_state.length = self.kb.concept_len(self.kb.generator.thing) rl_state.instances = set(self.kb.individuals(rl_state.concept)) refinements_rl = self.apply_rho_on_rl_state(rl_state) diff --git a/ontolearn/model_adapter.py b/ontolearn/model_adapter.py index 0e5575bd..954723a7 100644 --- a/ontolearn/model_adapter.py +++ b/ontolearn/model_adapter.py @@ -5,9 +5,8 @@ from ontolearn.abstracts import AbstractHeuristic, AbstractScorer, BaseRefinement, AbstractKnowledgeBase, \ AbstractNode from ontolearn.base_concept_learner import BaseConceptLearner -from owlapy.model import OWLReasoner -from owlapy.owlready2.complex_ce_instances import OWLReasoner_Owlready2_ComplexCEInstances -from owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker +from ontolearn.owlapy.model import OWLReasoner +from ontolearn.owlapy.owlready2.complex_ce_instances import OWLReasoner_Owlready2_ComplexCEInstances logger = logging.getLogger(__name__) # TODO:CD: Move all imports to the top of the file diff --git a/ontolearn/nces_data_generator/helper_classes.py b/ontolearn/nces_data_generator/helper_classes.py index b907769d..db506195 100644 --- a/ontolearn/nces_data_generator/helper_classes.py +++ b/ontolearn/nces_data_generator/helper_classes.py @@ -1,8 +1,8 @@ from tqdm import tqdm -import random, numpy as np +import random from rdflib import graph from ontolearn.knowledge_base import KnowledgeBase -from owlapy.render import DLSyntaxObjectRenderer +from ontolearn.owlapy.render import DLSyntaxObjectRenderer from ontolearn.refinement_operators import ExpressRefinement import os, json @@ -22,7 +22,7 @@ def apply_rho(self, concept): return {ref for ref in self.rho.refine(concept, max_length=self.max_length)} def generate(self): - roots = self.apply_rho(self.kb.thing) + roots = self.apply_rho(self.kb.generator.thing) Refinements = set() Refinements.update(roots) print ("|Thing refinements|: ", len(roots)) diff --git a/owlapy/LICENSE b/ontolearn/owlapy/LICENSE similarity index 100% rename from owlapy/LICENSE rename to ontolearn/owlapy/LICENSE diff --git a/owlapy/__init__.py b/ontolearn/owlapy/__init__.py similarity index 86% rename from owlapy/__init__.py rename to ontolearn/owlapy/__init__.py index 1111c981..8156d78e 100644 --- a/owlapy/__init__.py +++ b/ontolearn/owlapy/__init__.py @@ -9,4 +9,3 @@ """ # the import order must be fixed otherwise there are circular import errors -import owlapy.model # noqa: F401 diff --git a/owlapy/_utils.py b/ontolearn/owlapy/_utils.py similarity index 100% rename from owlapy/_utils.py rename to ontolearn/owlapy/_utils.py diff --git a/owlapy/ext/__init__.py b/ontolearn/owlapy/ext/__init__.py similarity index 96% rename from owlapy/ext/__init__.py rename to ontolearn/owlapy/ext/__init__.py index 8eb6f8fe..48b76335 100644 --- a/owlapy/ext/__init__.py +++ b/ontolearn/owlapy/ext/__init__.py @@ -2,7 +2,7 @@ from abc import ABCMeta from typing import Iterable -from owlapy.model import OWLNamedIndividual, OWLObjectProperty, OWLReasoner, OWLDataProperty, OWLDataRange, OWLLiteral +from ontolearn.owlapy.model import OWLNamedIndividual, OWLObjectProperty, OWLReasoner, OWLDataProperty, OWLDataRange, OWLLiteral logger = logging.getLogger(__name__) diff --git a/owlapy/fast_instance_checker.py b/ontolearn/owlapy/fast_instance_checker.py similarity index 98% rename from owlapy/fast_instance_checker.py rename to ontolearn/owlapy/fast_instance_checker.py index 72800fe0..06c1b921 100644 --- a/owlapy/fast_instance_checker.py +++ b/ontolearn/owlapy/fast_instance_checker.py @@ -7,15 +7,15 @@ from types import MappingProxyType, FunctionType from typing import DefaultDict, Iterable, Dict, Mapping, Set, Type, TypeVar, Optional, FrozenSet -from owlapy.ext import OWLReasonerEx -from owlapy.model import OWLDataRange, OWLObjectOneOf, OWLOntology, OWLNamedIndividual, OWLClass, OWLClassExpression, \ +from ontolearn.owlapy.ext import OWLReasonerEx +from ontolearn.owlapy.model import OWLDataRange, OWLObjectOneOf, OWLOntology, OWLNamedIndividual, OWLClass, OWLClassExpression, \ OWLObjectProperty, OWLDataProperty, OWLObjectUnionOf, OWLObjectIntersectionOf, OWLObjectSomeValuesFrom, \ OWLObjectPropertyExpression, OWLObjectComplementOf, OWLObjectAllValuesFrom, IRI, OWLObjectInverseOf, \ OWLDataSomeValuesFrom, OWLDataPropertyExpression, OWLDatatypeRestriction, OWLLiteral, \ OWLDataComplementOf, OWLDataAllValuesFrom, OWLDatatype, OWLDataHasValue, OWLDataOneOf, OWLReasoner, \ OWLDataIntersectionOf, OWLDataUnionOf, OWLObjectCardinalityRestriction, OWLObjectMinCardinality, \ OWLObjectMaxCardinality, OWLObjectExactCardinality, OWLObjectHasValue, OWLPropertyExpression, OWLFacetRestriction -from owlapy.util import LRUCache +from ontolearn.owlapy.util import LRUCache logger = logging.getLogger(__name__) @@ -196,7 +196,7 @@ def _lazy_cache_obj_prop(self, pe: OWLObjectPropertyExpression) -> None: opc: DefaultDict[OWLNamedIndividual, Set[OWLNamedIndividual]] = defaultdict(set) # shortcut for owlready2 - from owlapy.owlready2 import OWLOntology_Owlready2 + from ontolearn.owlapy.owlready2 import OWLOntology_Owlready2 if isinstance(self._ontology, OWLOntology_Owlready2): import owlready2 # _x => owlready2 objects @@ -238,7 +238,7 @@ def _some_values_subject_index(self, pe: OWLPropertyExpression) -> FrozenSet[OWL subs = set() # shortcut for owlready2 - from owlapy.owlready2 import OWLOntology_Owlready2 + from ontolearn.owlapy.owlready2 import OWLOntology_Owlready2 if isinstance(self._ontology, OWLOntology_Owlready2): import owlready2 # _x => owlready2 objects @@ -315,7 +315,7 @@ def _lazy_cache_data_prop(self, pe: OWLDataPropertyExpression) -> None: opc: Dict[OWLNamedIndividual, Set[OWLLiteral]] = dict() # shortcut for owlready2 - from owlapy.owlready2 import OWLOntology_Owlready2 + from ontolearn.owlapy.owlready2 import OWLOntology_Owlready2 if isinstance(self._ontology, OWLOntology_Owlready2): import owlready2 # _x => owlready2 objects diff --git a/owlapy/io.py b/ontolearn/owlapy/io.py similarity index 96% rename from owlapy/io.py rename to ontolearn/owlapy/io.py index c255af73..17f3fe40 100644 --- a/owlapy/io.py +++ b/ontolearn/owlapy/io.py @@ -1,6 +1,6 @@ from abc import abstractmethod, ABCMeta -from owlapy.model import OWLObject +from ontolearn.owlapy.model import OWLObject class OWLObjectRenderer(metaclass=ABCMeta): diff --git a/owlapy/model/__init__.py b/ontolearn/owlapy/model/__init__.py similarity index 99% rename from owlapy/model/__init__.py rename to ontolearn/owlapy/model/__init__.py index bba3be51..43274a49 100644 --- a/owlapy/model/__init__.py +++ b/ontolearn/owlapy/model/__init__.py @@ -13,10 +13,10 @@ from pandas import Timedelta from datetime import datetime, date -from owlapy.vocab import OWLRDFVocabulary, XSDVocabulary, OWLFacet -from owlapy._utils import MOVE -from owlapy.model._base import OWLObject, OWLAnnotationObject, OWLAnnotationSubject, OWLAnnotationValue -from owlapy.model._iri import HasIRI, IRI +from ontolearn.owlapy.vocab import OWLRDFVocabulary, XSDVocabulary, OWLFacet +from ontolearn.owlapy._utils import MOVE +from ontolearn.owlapy.model._base import OWLObject, OWLAnnotationObject, OWLAnnotationSubject, OWLAnnotationValue +from ontolearn.owlapy.model._iri import HasIRI, IRI MOVE(OWLObject, OWLAnnotationObject, OWLAnnotationSubject, OWLAnnotationValue, HasIRI, IRI) @@ -118,7 +118,7 @@ def get_object_complement_of(self) -> 'OWLObjectComplementOf': def get_nnf(self) -> 'OWLClassExpression': # documented in parent - from owlapy.util import NNF + from ontolearn.owlapy.util import NNF return NNF().get_class_nnf(self) diff --git a/owlapy/model/_base.py b/ontolearn/owlapy/model/_base.py similarity index 94% rename from owlapy/model/_base.py rename to ontolearn/owlapy/model/_base.py index d66a4922..909d5d5f 100644 --- a/owlapy/model/_base.py +++ b/ontolearn/owlapy/model/_base.py @@ -2,8 +2,8 @@ from typing import Optional, TYPE_CHECKING if TYPE_CHECKING: - from owlapy.model._iri import IRI - from owlapy.model import OWLLiteral + from ontolearn.owlapy.model._iri import IRI + from ontolearn.owlapy.model import OWLLiteral class OWLObject(metaclass=ABCMeta): diff --git a/owlapy/model/_iri.py b/ontolearn/owlapy/model/_iri.py similarity index 94% rename from owlapy/model/_iri.py rename to ontolearn/owlapy/model/_iri.py index 57fda20a..fcaf084f 100644 --- a/owlapy/model/_iri.py +++ b/ontolearn/owlapy/model/_iri.py @@ -3,9 +3,9 @@ from typing import Final, Union, overload from weakref import WeakKeyDictionary -from owlapy import namespaces -from owlapy.model._base import OWLAnnotationSubject, OWLAnnotationValue -from owlapy.namespaces import Namespaces +from ontolearn.owlapy import namespaces +from ontolearn.owlapy.model._base import OWLAnnotationSubject, OWLAnnotationValue +from ontolearn.owlapy.namespaces import Namespaces class HasIRI(metaclass=ABCMeta): @@ -117,7 +117,7 @@ def is_nothing(self): Returns: :True if this IRI is equal to and otherwise False """ - from owlapy.vocab import OWLRDFVocabulary + from ontolearn.owlapy.vocab import OWLRDFVocabulary return self == OWLRDFVocabulary.OWL_NOTHING.get_iri() def is_thing(self): @@ -126,7 +126,7 @@ def is_thing(self): Returns: :True if this IRI is equal to and otherwise False """ - from owlapy.vocab import OWLRDFVocabulary + from ontolearn.owlapy.vocab import OWLRDFVocabulary return self == OWLRDFVocabulary.OWL_THING.get_iri() def is_reserved_vocabulary(self) -> bool: diff --git a/owlapy/model/providers.py b/ontolearn/owlapy/model/providers.py similarity index 95% rename from owlapy/model/providers.py rename to ontolearn/owlapy/model/providers.py index 1f671049..59cf64ba 100644 --- a/owlapy/model/providers.py +++ b/ontolearn/owlapy/model/providers.py @@ -1,6 +1,6 @@ from typing import Union from datetime import datetime, date -from owlapy.model import OWLDatatypeRestriction, OWLFacet, OWLFacetRestriction, OWLLiteral +from ontolearn.owlapy.model import OWLDatatypeRestriction, OWLFacet, OWLFacetRestriction, OWLLiteral from pandas import Timedelta Restriction_Literals = Union[OWLLiteral, int, float, Timedelta, datetime, date] diff --git a/owlapy/namespaces.py b/ontolearn/owlapy/namespaces.py similarity index 100% rename from owlapy/namespaces.py rename to ontolearn/owlapy/namespaces.py diff --git a/owlapy/owl2sparql/__init__.py b/ontolearn/owlapy/owl2sparql/__init__.py similarity index 100% rename from owlapy/owl2sparql/__init__.py rename to ontolearn/owlapy/owl2sparql/__init__.py diff --git a/owlapy/owl2sparql/converter.py b/ontolearn/owlapy/owl2sparql/converter.py similarity index 99% rename from owlapy/owl2sparql/converter.py rename to ontolearn/owlapy/owl2sparql/converter.py index fa671294..917a9992 100644 --- a/owlapy/owl2sparql/converter.py +++ b/ontolearn/owlapy/owl2sparql/converter.py @@ -6,13 +6,13 @@ from rdflib.plugins.sparql.parser import parseQuery -from owlapy.model import OWLClassExpression, OWLClass, OWLEntity, OWLObjectProperty, OWLObjectIntersectionOf, \ +from ontolearn.owlapy.model import OWLClassExpression, OWLClass, OWLEntity, OWLObjectProperty, OWLObjectIntersectionOf, \ OWLObjectUnionOf, OWLObjectComplementOf, OWLObjectSomeValuesFrom, OWLObjectAllValuesFrom, OWLObjectHasValue, \ OWLNamedIndividual, OWLObjectCardinalityRestriction, OWLObjectMinCardinality, OWLObjectExactCardinality, \ OWLObjectMaxCardinality, OWLDataCardinalityRestriction, OWLDataProperty, OWLObjectHasSelf, OWLObjectOneOf, \ OWLDataSomeValuesFrom, OWLDataAllValuesFrom, OWLDataHasValue, OWLDatatype, TopOWLDatatype, OWLDataOneOf, \ OWLLiteral, OWLDatatypeRestriction -from owlapy.vocab import OWLFacet, OWLRDFVocabulary +from ontolearn.owlapy.vocab import OWLFacet, OWLRDFVocabulary _Variable_facet_comp = MappingProxyType({ OWLFacet.MIN_INCLUSIVE: ">=", diff --git a/owlapy/owlready2/__init__.py b/ontolearn/owlapy/owlready2/__init__.py similarity index 60% rename from owlapy/owlready2/__init__.py rename to ontolearn/owlapy/owlready2/__init__.py index d2ae1c16..45e325f3 100644 --- a/owlapy/owlready2/__init__.py +++ b/ontolearn/owlapy/owlready2/__init__.py @@ -1,5 +1,5 @@ -from owlapy._utils import MOVE -from owlapy.owlready2._base import OWLOntologyManager_Owlready2, OWLReasoner_Owlready2, OWLOntology_Owlready2,\ +from ontolearn.owlapy._utils import MOVE +from ontolearn.owlapy.owlready2._base import OWLOntologyManager_Owlready2, OWLReasoner_Owlready2, OWLOntology_Owlready2,\ BaseReasoner_Owlready2 MOVE(OWLOntologyManager_Owlready2, OWLReasoner_Owlready2, OWLOntology_Owlready2, BaseReasoner_Owlready2) __all__ = 'OWLOntologyManager_Owlready2', 'OWLReasoner_Owlready2', 'OWLOntology_Owlready2', 'BaseReasoner_Owlready2' diff --git a/owlapy/owlready2/_base.py b/ontolearn/owlapy/owlready2/_base.py similarity index 99% rename from owlapy/owlready2/_base.py rename to ontolearn/owlapy/owlready2/_base.py index 8069d95c..d682a3e3 100644 --- a/owlapy/owlready2/_base.py +++ b/ontolearn/owlapy/owlready2/_base.py @@ -1,5 +1,4 @@ import logging -import random from datetime import date, datetime from enum import Enum, auto from itertools import chain @@ -10,16 +9,16 @@ from owlready2 import declare_datatype from pandas import Timedelta -from owlapy.owlready2 import axioms -from owlapy import namespaces -from owlapy.ext import OWLReasonerEx -from owlapy.model import OWLObjectPropertyRangeAxiom, OWLOntologyManager, OWLDataProperty, OWLObjectProperty, \ +from ontolearn.owlapy.owlready2 import axioms +from ontolearn.owlapy import namespaces +from ontolearn.owlapy.ext import OWLReasonerEx +from ontolearn.owlapy.model import OWLObjectPropertyRangeAxiom, OWLOntologyManager, OWLDataProperty, OWLObjectProperty, \ OWLNamedIndividual, OWLClassExpression, OWLObjectPropertyExpression, OWLOntologyID, OWLAxiom, OWLOntology, \ OWLOntologyChange, AddImport, OWLThing, DoubleOWLDatatype, OWLObjectPropertyDomainAxiom, OWLLiteral, \ OWLObjectInverseOf, BooleanOWLDatatype, IntegerOWLDatatype, DateOWLDatatype, DateTimeOWLDatatype, OWLClass, \ DurationOWLDatatype, StringOWLDatatype, IRI, OWLDataPropertyRangeAxiom, OWLDataPropertyDomainAxiom, OWLClassAxiom, \ OWLSubClassOfAxiom, OWLEquivalentClassesAxiom, OWLObjectSomeValuesFrom -from owlapy.owlready2.utils import FromOwlready2 +from ontolearn.owlapy.owlready2.utils import FromOwlready2 logger = logging.getLogger(__name__) diff --git a/owlapy/owlready2/axioms.py b/ontolearn/owlapy/owlready2/axioms.py similarity index 99% rename from owlapy/owlready2/axioms.py rename to ontolearn/owlapy/owlready2/axioms.py index 8c6602bc..8341f8c5 100644 --- a/owlapy/owlready2/axioms.py +++ b/ontolearn/owlapy/owlready2/axioms.py @@ -6,7 +6,7 @@ import owlready2 from owlready2 import destroy_entity, AllDisjoint, AllDifferent, GeneralClassAxiom -from owlapy.model import OWLDisjointUnionAxiom, OWLQuantifiedDataRestriction, OWLQuantifiedObjectRestriction, \ +from ontolearn.owlapy.model import OWLDisjointUnionAxiom, OWLQuantifiedDataRestriction, OWLQuantifiedObjectRestriction, \ OWLAnnotationAssertionAxiom, OWLClass, OWLClassAssertionAxiom, OWLEquivalentClassesAxiom, OWLObject, \ OWLAnnotationProperty, OWLDataHasValue, OWLDataProperty, OWLDeclarationAxiom, OWLIndividual, \ OWLNamedIndividual, OWLNaryBooleanClassExpression, OWLObjectComplementOf, OWLObjectHasValue, \ @@ -19,7 +19,7 @@ OWLDisjointDataPropertiesAxiom, OWLDisjointObjectPropertiesAxiom, OWLEquivalentDataPropertiesAxiom, \ OWLEquivalentObjectPropertiesAxiom, OWLInverseObjectPropertiesAxiom, OWLNaryPropertyAxiom, OWLNaryIndividualAxiom, \ OWLDifferentIndividualsAxiom, OWLDisjointClassesAxiom, OWLSameIndividualAxiom, OWLProperty -from owlapy.owlready2.utils import ToOwlready2 +from ontolearn.owlapy.owlready2.utils import ToOwlready2 @singledispatch diff --git a/owlapy/owlready2/complex_ce_instances.py b/ontolearn/owlapy/owlready2/complex_ce_instances.py similarity index 94% rename from owlapy/owlready2/complex_ce_instances.py rename to ontolearn/owlapy/owlready2/complex_ce_instances.py index 207382e1..f7d468e9 100644 --- a/owlapy/owlready2/complex_ce_instances.py +++ b/ontolearn/owlapy/owlready2/complex_ce_instances.py @@ -5,10 +5,10 @@ import os import owlready2 -from owlapy.model import OWLClass, OWLClassExpression, OWLNamedIndividual, IRI, OWLAxiom -from owlapy.owlready2 import OWLReasoner_Owlready2, OWLOntology_Owlready2, BaseReasoner_Owlready2, \ +from ontolearn.owlapy.model import OWLClass, OWLClassExpression, OWLNamedIndividual, IRI, OWLAxiom +from ontolearn.owlapy.owlready2 import OWLReasoner_Owlready2, OWLOntology_Owlready2, BaseReasoner_Owlready2, \ OWLOntologyManager_Owlready2 -from owlapy.owlready2.utils import ToOwlready2 +from ontolearn.owlapy.owlready2.utils import ToOwlready2 logger = logging.getLogger(__name__) diff --git a/owlapy/owlready2/plus.py b/ontolearn/owlapy/owlready2/plus.py similarity index 94% rename from owlapy/owlready2/plus.py rename to ontolearn/owlapy/owlready2/plus.py index 80eb5dc0..2c8a31e0 100644 --- a/owlapy/owlready2/plus.py +++ b/ontolearn/owlapy/owlready2/plus.py @@ -2,9 +2,9 @@ import owlready2 -from owlapy import namespaces -from owlapy.model import OWLObjectPropertyExpression, OWLObjectProperty, OWLClassExpression, OWLClass, OWLThing, IRI -from owlapy.owlready2 import OWLReasoner_Owlready2 +from ontolearn.owlapy import namespaces +from ontolearn.owlapy.model import OWLObjectPropertyExpression, OWLObjectProperty, OWLClassExpression, OWLClass, OWLThing, IRI +from ontolearn.owlapy.owlready2 import OWLReasoner_Owlready2 class OWLReasoner_Owlready2_Plus(OWLReasoner_Owlready2): diff --git a/owlapy/owlready2/utils.py b/ontolearn/owlapy/owlready2/utils.py similarity index 98% rename from owlapy/owlready2/utils.py rename to ontolearn/owlapy/owlready2/utils.py index d53b34e5..94cfaad6 100644 --- a/owlapy/owlready2/utils.py +++ b/ontolearn/owlapy/owlready2/utils.py @@ -6,7 +6,7 @@ import owlready2 from pandas import Timedelta -from owlapy.model import OWLObjectMinCardinality, OWLObjectOneOf, OWLObjectRestriction, OWLPropertyExpression, \ +from ontolearn.owlapy.model import OWLObjectMinCardinality, OWLObjectOneOf, OWLObjectRestriction, OWLPropertyExpression, \ OWLObjectComplementOf, OWLObjectUnionOf, OWLObjectIntersectionOf, OWLObjectSomeValuesFrom, OWLObjectAllValuesFrom, \ OWLObjectPropertyExpression, OWLObject, OWLOntology, OWLAnnotationProperty, IRI, OWLObjectInverseOf, \ DoubleOWLDatatype, IntegerOWLDatatype, OWLClassExpression, OWLDataAllValuesFrom, OWLDataComplementOf, \ @@ -17,7 +17,7 @@ DateOWLDatatype, DateTimeOWLDatatype, DurationOWLDatatype, OWLRestriction, OWLDataOneOf, OWLDataRestriction, \ OWLIndividual, StringOWLDatatype -from owlapy.vocab import OWLFacet +from ontolearn.owlapy.vocab import OWLFacet OWLREADY2_FACET_KEYS = MappingProxyType({ diff --git a/owlapy/parser.py b/ontolearn/owlapy/parser.py similarity index 99% rename from owlapy/parser.py rename to ontolearn/owlapy/parser.py index 63d1c5e5..76302055 100644 --- a/owlapy/parser.py +++ b/ontolearn/owlapy/parser.py @@ -3,8 +3,8 @@ from parsimonious.grammar import Grammar from parsimonious.grammar import NodeVisitor from parsimonious.nodes import Node -from owlapy.io import OWLObjectParser -from owlapy.model import OWLObjectHasSelf, OWLObjectIntersectionOf, OWLObjectMinCardinality, OWLObjectOneOf, \ +from ontolearn.owlapy.io import OWLObjectParser +from ontolearn.owlapy.model import OWLObjectHasSelf, OWLObjectIntersectionOf, OWLObjectMinCardinality, OWLObjectOneOf, \ OWLObjectProperty, OWLObjectPropertyExpression, OWLObjectSomeValuesFrom, OWLObjectUnionOf, OWLClass, IRI, \ OWLClassExpression, OWLDataProperty, OWLNamedIndividual, OWLObjectComplementOf, OWLObjectExactCardinality, \ OWLObjectHasValue, OWLQuantifiedDataRestriction, OWLQuantifiedObjectRestriction, StringOWLDatatype, \ @@ -13,10 +13,10 @@ OWLDataMaxCardinality, OWLObjectMaxCardinality, OWLDataIntersectionOf, OWLDataMinCardinality, OWLDataHasValue, \ OWLLiteral, OWLDataRange, OWLDataUnionOf, OWLDataOneOf, OWLDatatype, OWLObjectCardinalityRestriction, \ OWLDataCardinalityRestriction, OWLObjectAllValuesFrom, OWLDataAllValuesFrom, OWLDataComplementOf, BooleanOWLDatatype -from owlapy.namespaces import Namespaces +from ontolearn.owlapy.namespaces import Namespaces -from owlapy.render import _DL_SYNTAX, _MAN_SYNTAX -from owlapy.vocab import OWLFacet, OWLRDFVocabulary +from ontolearn.owlapy.render import _DL_SYNTAX, _MAN_SYNTAX +from ontolearn.owlapy.vocab import OWLFacet, OWLRDFVocabulary MANCHESTER_GRAMMAR = Grammar(r""" diff --git a/owlapy/render.py b/ontolearn/owlapy/render.py similarity index 98% rename from owlapy/render.py rename to ontolearn/owlapy/render.py index 8cff05d7..f357cc8f 100644 --- a/owlapy/render.py +++ b/ontolearn/owlapy/render.py @@ -4,9 +4,9 @@ from functools import singledispatchmethod from typing import List, Callable -from owlapy import namespaces -from owlapy.io import OWLObjectRenderer -from owlapy.model import OWLLiteral, OWLNaryDataRange, OWLObject, OWLClass, OWLObjectSomeValuesFrom, \ +from ontolearn.owlapy import namespaces +from ontolearn.owlapy.io import OWLObjectRenderer +from ontolearn.owlapy.model import OWLLiteral, OWLNaryDataRange, OWLObject, OWLClass, OWLObjectSomeValuesFrom, \ OWLObjectAllValuesFrom, OWLObjectUnionOf, OWLBooleanClassExpression, OWLNaryBooleanClassExpression, \ OWLObjectIntersectionOf, OWLObjectComplementOf, OWLObjectInverseOf, OWLClassExpression, OWLRestriction, \ OWLObjectMinCardinality, OWLObjectExactCardinality, OWLObjectMaxCardinality, OWLObjectHasSelf, OWLObjectHasValue, \ @@ -14,7 +14,7 @@ OWLFacetRestriction, OWLDatatypeRestriction, OWLDatatype, OWLDataAllValuesFrom, OWLDataComplementOf, \ OWLDataUnionOf, OWLDataIntersectionOf, OWLDataHasValue, OWLDataOneOf, OWLDataMaxCardinality, \ OWLDataMinCardinality, OWLDataExactCardinality -from owlapy.vocab import OWLFacet +from ontolearn.owlapy.vocab import OWLFacet _DL_SYNTAX = types.SimpleNamespace( diff --git a/owlapy/util.py b/ontolearn/owlapy/util.py similarity index 99% rename from owlapy/util.py rename to ontolearn/owlapy/util.py index d5e886cc..93a0cf29 100644 --- a/owlapy/util.py +++ b/ontolearn/owlapy/util.py @@ -1,7 +1,7 @@ from functools import singledispatchmethod, total_ordering from typing import Iterable, List, Type, TypeVar, Generic, Tuple, cast, Optional, Union, overload -from owlapy.model import HasIndex, HasIRI, OWLClassExpression, OWLClass, OWLObjectCardinalityRestriction, \ +from ontolearn.owlapy.model import HasIndex, HasIRI, OWLClassExpression, OWLClass, OWLObjectCardinalityRestriction, \ OWLObjectComplementOf, OWLNothing, OWLPropertyRange, OWLRestriction, OWLThing, OWLObjectSomeValuesFrom, \ OWLObjectHasValue, OWLObjectMinCardinality, OWLObjectMaxCardinality, OWLObjectExactCardinality, OWLObjectHasSelf, \ OWLObjectOneOf, OWLDataMaxCardinality, OWLDataMinCardinality, OWLDataExactCardinality, OWLDataHasValue, \ diff --git a/owlapy/vocab.py b/ontolearn/owlapy/vocab.py similarity index 96% rename from owlapy/vocab.py rename to ontolearn/owlapy/vocab.py index 31396095..90614804 100644 --- a/owlapy/vocab.py +++ b/ontolearn/owlapy/vocab.py @@ -4,9 +4,9 @@ from operator import lt, le, gt, ge from re import match -from owlapy import namespaces -from owlapy.model._iri import HasIRI, IRI -from owlapy.namespaces import Namespaces +from ontolearn.owlapy import namespaces +from ontolearn.owlapy.model._iri import HasIRI, IRI +from ontolearn.owlapy.namespaces import Namespaces class _Vocabulary(HasIRI): diff --git a/ontolearn/refinement_operators.py b/ontolearn/refinement_operators.py index 5cce9835..2297f178 100644 --- a/ontolearn/refinement_operators.py +++ b/ontolearn/refinement_operators.py @@ -1,20 +1,20 @@ from collections import defaultdict -import copy -from itertools import chain, tee +from itertools import chain import random from typing import DefaultDict, Dict, Set, Optional, Iterable, List, Type, Final, Generator from ontolearn.value_splitter import AbstractValueSplitter, BinningValueSplitter -from owlapy.model.providers import OWLDatatypeMaxInclusiveRestriction, OWLDatatypeMinInclusiveRestriction -from owlapy.vocab import OWLFacet +from ontolearn.owlapy.model.providers import OWLDatatypeMaxInclusiveRestriction, OWLDatatypeMinInclusiveRestriction +from ontolearn.owlapy.vocab import OWLFacet from .abstracts import BaseRefinement +from .concept_generator import ConceptGenerator from .knowledge_base import KnowledgeBase -from owlapy.model import OWLObjectPropertyExpression, OWLObjectSomeValuesFrom, OWLObjectAllValuesFrom, \ +from ontolearn.owlapy.model import OWLObjectPropertyExpression, OWLObjectSomeValuesFrom, OWLObjectAllValuesFrom, \ OWLObjectIntersectionOf, OWLClassExpression, OWLNothing, OWLThing, OWLNaryBooleanClassExpression, \ OWLObjectUnionOf, OWLClass, OWLObjectComplementOf, OWLObjectMaxCardinality, OWLObjectMinCardinality, \ OWLDataSomeValuesFrom, OWLDatatypeRestriction, OWLLiteral, OWLObjectInverseOf, OWLDataProperty, \ OWLDataHasValue, OWLDataPropertyExpression -from .search import Node, OENode +from .search import OENode # TODO: 23 Warnings need to be fixed here to avoid runtime errors @@ -41,15 +41,15 @@ def refine_top(self) -> Iterable: """ Refine Top Class Expression """ """ (1) Store all named classes """ iterable_container = [] - all_subs = [i for i in self.kb.get_all_sub_concepts(self.kb.thing)] + all_subs = [i for i in self.kb.get_all_sub_concepts(self.kb.generator.thing)] iterable_container.append(all_subs) """ (2) Negate (1) and store it """ - iterable_container.append(self.kb.negation_from_iterables((i for i in all_subs))) + iterable_container.append(self.kb.generator.negation_from_iterables((i for i in all_subs))) """ (3) Add Nothing """ - iterable_container.append([self.kb.nothing]) + iterable_container.append([self.kb.generator.nothing]) """ (4) Get all most general restrictions and store them forall r. T, \\exist r. T """ - iterable_container.append(self.kb.most_general_universal_restrictions(domain=self.kb.thing, filler=None)) - iterable_container.append(self.kb.most_general_existential_restrictions(domain=self.kb.thing, filler=None)) + iterable_container.append(self.kb.most_general_universal_restrictions(domain=self.kb.generator.thing, filler=None)) + iterable_container.append(self.kb.most_general_existential_restrictions(domain=self.kb.generator.thing, filler=None)) """ (5) Generate all refinements of given concept that have length less or equal to the maximum refinement length constraint """ yield from self.apply_union_and_intersection_from_iterable(iterable_container) @@ -64,7 +64,7 @@ def apply_union_and_intersection_from_iterable(self, cont: Iterable[Generator]) cumulative_refinements = dict() """ 1. Flatten list of generators """ for class_expression in chain.from_iterable(cont): - if class_expression is not self.kb.nothing: + if class_expression is not self.kb.generator.nothing: """ 1.2. Store qualifying concepts based on their lengths """ cumulative_refinements.setdefault(self.len(class_expression), set()).add(class_expression) else: @@ -93,11 +93,11 @@ def apply_union_and_intersection_from_iterable(self, cont: Iterable[Generator]) if len_ <= self.max_len_refinement_top: """ 3.4 Intersect concepts having length i with concepts having length j""" - intersect_of_concepts = self.kb.intersect_from_iterables(cumulative_refinements[i], - cumulative_refinements[j]) + intersect_of_concepts = self.kb.generator.intersect_from_iterables(cumulative_refinements[i], + cumulative_refinements[j]) """ 3.4 Union concepts having length i with concepts having length j""" - union_of_concepts = self.kb.union_from_iterables(cumulative_refinements[i], - cumulative_refinements[j]) + union_of_concepts = self.kb.generator.union_from_iterables(cumulative_refinements[i], + cumulative_refinements[j]) res = set(chain(intersect_of_concepts, union_of_concepts)) # Store newly generated concepts at 3.2. @@ -123,8 +123,8 @@ def refine_atomic_concept(self, class_expression: OWLClassExpression) -> Iterabl # No need => Daughter ⊓ Daughter # No need => Daughter ⊓ \bottom if i.is_owl_nothing() is False and (i != class_expression): - yield self.kb.intersection((class_expression, i)) - # Previously; yield self.kb.intersection(node.concept, self.kb.thing) + yield self.kb.generator.intersection((class_expression, i)) + # Previously; yield self.kb.intersection(node.concept, self.kb.generator.thing) def refine_complement_of(self, class_expression: OWLObjectComplementOf) -> Iterable[OWLClassExpression]: """ @@ -134,24 +134,24 @@ def refine_complement_of(self, class_expression: OWLObjectComplementOf) -> Itera 3- Intersection with T """ assert isinstance(class_expression, OWLObjectComplementOf) - yield from self.kb.negation_from_iterables(self.kb.get_direct_parents(self.kb.negation(class_expression))) - yield self.kb.intersection((class_expression, self.kb.thing)) + yield from self.kb.generator.negation_from_iterables(self.kb.get_direct_parents(self.kb.negation(class_expression))) + yield self.kb.generator.intersection((class_expression, self.kb.generator.thing)) def refine_object_some_values_from(self, class_expression: OWLObjectSomeValuesFrom) -> Iterable[OWLClassExpression]: assert isinstance(class_expression, OWLObjectSomeValuesFrom) # rule 1: \exists r.D = > for all r.E for i in self.refine(class_expression.get_filler()): - yield self.kb.existential_restriction(i, class_expression.get_property()) + yield self.kb.generator.existential_restriction(i, class_expression.get_property()) # rule 2: \exists r.D = > \exists r.D AND T - yield self.kb.intersection((class_expression, self.kb.thing)) + yield self.kb.generator.intersection((class_expression, self.kb.generator.thing)) def refine_object_all_values_from(self, class_expression: OWLObjectAllValuesFrom) -> Iterable[OWLClassExpression]: assert isinstance(class_expression, OWLObjectAllValuesFrom) # rule 1: \forall r.D = > \forall r.E for i in self.refine(class_expression.get_filler()): - yield self.kb.universal_restriction(i, class_expression.get_property()) + yield self.kb.generator.universal_restriction(i, class_expression.get_property()) # rule 2: \forall r.D = > \forall r.D AND T - yield self.kb.intersection((class_expression, self.kb.thing)) + yield self.kb.generator.intersection((class_expression, self.kb.generator.thing)) def refine_object_union_of(self, class_expression: OWLObjectUnionOf) -> Iterable[OWLClassExpression]: """ @@ -164,7 +164,7 @@ def refine_object_union_of(self, class_expression: OWLObjectUnionOf) -> Iterable if ref_concept_A == class_expression: # No need => Person OR MALE => rho(Person) OR MALE => MALE OR MALE yield class_expression - yield self.kb.union((class_expression, ref_concept_A)) + yield self.kb.generator.union((class_expression, ref_concept_A)) def refine_object_intersection_of(self, class_expression: OWLClassExpression) -> Iterable[OWLClassExpression]: """ @@ -178,7 +178,7 @@ def refine_object_intersection_of(self, class_expression: OWLClassExpression) -> # No need => Person ⊓ MALE => rho(Person) ⊓ MALE => MALE ⊓ MALE yield class_expression # TODO: No need to intersect disjoint expressions - yield self.kb.intersection((class_expression, ref_concept_A)) + yield self.kb.generator.intersection((class_expression, ref_concept_A)) def refine(self, class_expression) -> Iterable[OWLClassExpression]: assert isinstance(class_expression, OWLClassExpression) @@ -208,7 +208,7 @@ class ModifiedCELOERefinement(BaseRefinement[OENode]): """ __slots__ = 'max_child_length', 'use_negation', 'use_all_constructor', 'use_inverse', 'use_card_restrictions', \ 'max_nr_fillers', 'card_limit', 'use_numeric_datatypes', 'use_boolean_datatype', 'dp_splits', \ - 'value_splitter', 'use_time_datatypes' + 'value_splitter', 'use_time_datatypes', 'generator' _Node: Final = OENode @@ -225,6 +225,7 @@ class ModifiedCELOERefinement(BaseRefinement[OENode]): max_nr_fillers: DefaultDict[OWLObjectPropertyExpression, int] dp_splits: Dict[OWLDataPropertyExpression, List[OWLLiteral]] + generator: ConceptGenerator def __init__(self, knowledge_base: KnowledgeBase, @@ -253,7 +254,7 @@ def __init__(self, self.use_time_datatypes = use_time_datatypes self.use_boolean_datatype = use_boolean_datatype self.card_limit = card_limit - + self.generator = ConceptGenerator() super().__init__(knowledge_base) self._setup() @@ -307,9 +308,9 @@ def _get_dp_restrictions(self, data_properties: Iterable[OWLDataProperty]) -> Li for dp in data_properties: splits = self.dp_splits[dp] if len(splits) > 0: - restrictions.append(self.kb.data_existential_restriction( + restrictions.append(self.generator.data_existential_restriction( filler=OWLDatatypeMinInclusiveRestriction(splits[0]), property=dp)) - restrictions.append(self.kb.data_existential_restriction( + restrictions.append(self.generator.data_existential_restriction( filler=OWLDatatypeMaxInclusiveRestriction(splits[-1]), property=dp)) return restrictions @@ -362,7 +363,7 @@ def refine_atomic_concept(self, ce: OWLClass, max_length: int, # TODO probably not correct/complete if max_length >= 2 and (self.len(ce) + 1 <= self.max_child_length): # (2.2) Create negation of all leaf_concepts - iter_container.append(self.kb.negation_from_iterables(self.kb.get_leaf_concepts(ce))) + iter_container.append(self.generator.negation_from_iterables(self.kb.get_leaf_concepts(ce))) # yield from self.kb.negation_from_iterables(self.kb.get_leaf_concepts(ce)) if max_length >= 3 and (self.len(ce) + 2 <= self.max_child_length): @@ -387,8 +388,8 @@ def refine_atomic_concept(self, ce: OWLClass, max_length: int, if self.use_boolean_datatype: bool_res = [] for bool_dp in self.kb.most_general_boolean_data_properties(domain=current_domain): - bool_res.append(self.kb.data_has_value_restriction(value=OWLLiteral(True), property=bool_dp)) - bool_res.append(self.kb.data_has_value_restriction(value=OWLLiteral(False), property=bool_dp)) + bool_res.append(self.generator.data_has_value_restriction(value=OWLLiteral(True), property=bool_dp)) + bool_res.append(self.generator.data_has_value_restriction(value=OWLLiteral(False), property=bool_dp)) iter_container.append(bool_res) # yield self.kb.intersection((ce, ce)) # yield self.kb.union((ce, ce)) @@ -398,7 +399,7 @@ def refine_atomic_concept(self, ce: OWLClass, max_length: int, for prop in self.kb.most_general_object_properties(domain=current_domain): max_ = self.max_nr_fillers[prop] if max_ > 1 or (self.use_negation and max_ > 0): - card_res.append(self.kb.max_cardinality_restriction(self.kb.thing, prop, max_ - 1)) + card_res.append(self.generator.max_cardinality_restriction(self.generator.thing, prop, max_ - 1)) iter_container.append(card_res) # a, b = tee(chain.from_iterable(iter_container)) @@ -431,7 +432,7 @@ def refine_atomic_concept(self, ce: OWLClass, max_length: int, # already contained continue else: - yield self.kb.union((i, j)) + yield self.generator.union((i, j)) # if self.kb.individuals_count(temp_union) < self.kb.individuals_count(): # yield temp_union @@ -439,7 +440,7 @@ def refine_atomic_concept(self, ce: OWLClass, max_length: int, # empty continue else: - yield self.kb.intersection((i, j)) + yield self.generator.intersection((i, j)) # temp_intersection = self.kb.intersection((i, j)) # if self.kb.individuals_count(temp_intersection) > 0: @@ -448,7 +449,7 @@ def refine_complement_of(self, ce: OWLObjectComplementOf) -> Iterable[OWLClassEx if self.use_negation: parents = self.kb.get_direct_parents(ce.get_operand()) - yield from self.kb.negation_from_iterables(parents) + yield from self.generator.negation_from_iterables(parents) else: yield from {} @@ -461,19 +462,19 @@ def refine_object_some_values_from(self, ce: OWLObjectSomeValuesFrom, max_length domain = self._get_current_domain(ce.get_property()) for i in self.refine(ce.get_filler(), max_length=max_length - 2, current_domain=domain): if i is not None: - yield self.kb.existential_restriction(i, ce.get_property()) + yield self.generator.existential_restriction(i, ce.get_property()) for more_special_op in self.kb.object_property_hierarchy(). \ more_special_roles(ce.get_property().get_named_property()): - yield self.kb.existential_restriction(ce.get_filler(), more_special_op) + yield self.generator.existential_restriction(ce.get_filler(), more_special_op) if self.use_all_constructor: - yield self.kb.universal_restriction(ce.get_filler(), ce.get_property()) + yield self.generator.universal_restriction(ce.get_filler(), ce.get_property()) length = self.len(ce) if self.use_card_restrictions and length < max_length and \ length < self.max_child_length and self.max_nr_fillers[ce.get_property()] > 1: - yield self.kb.min_cardinality_restriction(ce.get_filler(), ce.get_property(), 2) + yield self.generator.min_cardinality_restriction(ce.get_filler(), ce.get_property(), 2) def refine_object_all_values_from(self, ce: OWLObjectAllValuesFrom, max_length: int) \ -> Iterable[OWLObjectAllValuesFrom]: @@ -484,13 +485,13 @@ def refine_object_all_values_from(self, ce: OWLObjectAllValuesFrom, max_length: domain = self._get_current_domain(ce.get_property()) for i in self.refine(ce.get_filler(), max_length=max_length - 2, current_domain=domain): if i is not None: - yield self.kb.universal_restriction(i, ce.get_property()) + yield self.generator.universal_restriction(i, ce.get_property()) # if not concept.get_filler().is_owl_nothing() and concept.get_filler().isatomic and (len(refs) == 0): # # TODO find a way to include nothing concept # refs.update(self.kb.universal_restriction(i, concept.get_property())) for more_special_op in self.kb.object_property_hierarchy().\ more_special_roles(ce.get_property().get_named_property()): - yield self.kb.universal_restriction(ce.get_filler(), more_special_op) + yield self.generator.universal_restriction(ce.get_filler(), more_special_op) else: yield from {} @@ -502,10 +503,10 @@ def refine_object_min_card_restriction(self, ce: OWLObjectMinCardinality, max_le domain = self._get_current_domain(ce.get_property()) for i in self.refine(ce.get_filler(), max_length=max_length - 3, current_domain=domain): if i is not None: - yield self.kb.min_cardinality_restriction(i, ce.get_property(), ce.get_cardinality()) + yield self.generator.min_cardinality_restriction(i, ce.get_property(), ce.get_cardinality()) if ce.get_cardinality() < self.max_nr_fillers[ce.get_property()]: - yield self.kb.min_cardinality_restriction(ce.get_filler(), ce.get_property(), ce.get_cardinality() + 1) + yield self.generator.min_cardinality_restriction(ce.get_filler(), ce.get_property(), ce.get_cardinality() + 1) def refine_object_max_card_restriction(self, ce: OWLObjectMaxCardinality, max_length: int) \ -> Iterable[OWLObjectMaxCardinality]: @@ -515,10 +516,10 @@ def refine_object_max_card_restriction(self, ce: OWLObjectMaxCardinality, max_le domain = self._get_current_domain(ce.get_property()) for i in self.refine(ce.get_filler(), max_length=max_length - 3, current_domain=domain): if i is not None: - yield self.kb.max_cardinality_restriction(i, ce.get_property(), ce.get_cardinality()) + yield self.generator.max_cardinality_restriction(i, ce.get_property(), ce.get_cardinality()) if ce.get_cardinality() > 1 or (self.use_negation and ce.get_cardinality() > 0): - yield self.kb.max_cardinality_restriction(ce.get_filler(), ce.get_property(), ce.get_cardinality() - 1) + yield self.generator.max_cardinality_restriction(ce.get_filler(), ce.get_property(), ce.get_cardinality() - 1) def refine_object_union_of(self, ce: OWLObjectUnionOf, max_length: int, current_domain: Optional[OWLClassExpression]) -> Iterable[OWLObjectUnionOf]: @@ -545,7 +546,7 @@ def refine_object_union_of(self, ce: OWLObjectUnionOf, max_length: int, for ref_concept in self.refine(concept, max_length=max_length - self.len(ce) + concept_length, current_domain=current_domain): - union = self.kb.union(concept_left + [ref_concept] + concept_right) + union = self.generator.union(concept_left + [ref_concept] + concept_right) if max_length >= self.len(union): yield union @@ -563,7 +564,7 @@ def refine_object_intersection_of(self, ce: OWLObjectIntersectionOf, max_length: for ref_concept in self.refine(concept, max_length=max_length - self.len(ce) + concept_length, current_domain=current_domain): - intersection = self.kb.intersection(concept_left + [ref_concept] + concept_right) + intersection = self.generator.intersection(concept_left + [ref_concept] + concept_right) if max_length >= self.len(ref_concept): # if other_concept.instances.isdisjoint(ref_concept.instances): # continue @@ -581,17 +582,17 @@ def refine_data_some_values_from(self, ce: OWLDataSomeValuesFrom) -> Iterable[OW idx = splits.index(val) if facet_res.get_facet() == OWLFacet.MIN_INCLUSIVE and (next_idx := idx + 1) < len(splits): - yield self.kb.data_existential_restriction(OWLDatatypeMinInclusiveRestriction(splits[next_idx]), + yield self.generator.data_existential_restriction(OWLDatatypeMinInclusiveRestriction(splits[next_idx]), ce.get_property()) elif facet_res.get_facet() == OWLFacet.MAX_INCLUSIVE and (next_idx := idx - 1) >= 0: - yield self.kb.data_existential_restriction(OWLDatatypeMaxInclusiveRestriction(splits[next_idx]), + yield self.generator.data_existential_restriction(OWLDatatypeMaxInclusiveRestriction(splits[next_idx]), ce.get_property()) def refine_data_has_value(self, ce: OWLDataHasValue) -> Iterable[OWLDataHasValue]: assert isinstance(ce, OWLDataHasValue) for more_special_dp in self.kb.data_property_hierarchy().more_special_roles(ce.get_property()): - yield self.kb.data_has_value_restriction(ce.get_filler(), more_special_dp) + yield self.generator.data_has_value_restriction(ce.get_filler(), more_special_dp) def refine(self, ce: OWLClassExpression, max_length: int, current_domain: Optional[OWLClassExpression] = None) \ -> Iterable[OWLClassExpression]: @@ -630,144 +631,15 @@ def refine(self, ce: OWLClassExpression, max_length: int, current_domain: Option raise ValueError(f"{type(ce)} objects are not yet supported") -class CustomRefinementOperator(BaseRefinement[Node]): - def __init__(self, knowledge_base: KnowledgeBase = None, max_size_of_concept=1000, min_size_of_concept=1): - super().__init__(knowledge_base) - - def get_node(self, c: OWLClassExpression, parent_node=None, root=False): - - # if c in self.concepts_to_nodes: - # return self.concepts_to_nodes[c] - - if parent_node is None and root is False: - print(c) - raise ValueError - - n = Node(concept=c, parent_node=parent_node, root=root) - # self.concepts_to_nodes[c] = n - return n - - def refine_atomic_concept(self, concept: OWLClass) -> Set: - # (1) Generate all all sub_concepts - sub_concepts = self.kb.get_all_sub_concepts(concept) - # (2) Create negation of all leaf_concepts - negs = self.kb.negation_from_iterables(self.kb.get_leaf_concepts(concept)) - # (3) Create ∃.r.T where r is the most general relation. - existential_rest = self.kb.most_general_existential_restrictions(concept) - universal_rest = self.kb.most_general_universal_restrictions(concept) - a, b = tee(chain(sub_concepts, negs, existential_rest, universal_rest)) - - mem = set() - for i in a: - if i is None: - continue - yield i - for j in copy.copy(b): - if j is None: - continue - if (i == j) or ((i.str, j.str) in mem) or ((j.str, i.str) in mem): - continue - mem.add((j.str, i.str)) - mem.add((i.str, j.str)) - mem.add((j.str, i.str)) - - union = self.kb.union(i, j) - if union: - if not (concept.instances.issubset(union.instances)): - yield union - - if i.instances.isdisjoint(j.instances): - continue - inter = self.kb.intersection(i, j) - - if inter: - yield inter - - def refine_complement_of(self, concept: OWLObjectComplementOf): - """ - :type concept: Concept - :param concept: - :return: - """ - for i in self.kb.negation_from_iterables(self.kb.get_direct_parents(self.kb.negation(concept))): - yield i - - def refine_object_some_values_from(self, concept: OWLClassExpression): - assert isinstance(concept, OWLClassExpression) - for i in self.refine(concept.filler): - if isinstance(i, OWLClassExpression): - yield self.kb.existential_restriction(i, concept.role) - - def refine_object_all_values_from(self, C: OWLObjectAllValuesFrom): - """ - - :param C: - :return: - """ - # rule 1: Forall r.D = > Forall r.E - for i in self.refine(C.filler): - yield self.kb.universal_restriction(i, C.role) - - def refine_object_union_of(self, C: OWLObjectUnionOf): - """ - - :param C: - :return: - """ - concept_A = C.concept_a - concept_B = C.concept_b - for ref_concept_A in self.refine(concept_A): - if isinstance(ref_concept_A, OWLClassExpression): - yield self.kb.union(ref_concept_A, concept_B) - - for ref_concept_B in self.refine(concept_B): - if isinstance(ref_concept_B, OWLClassExpression): - yield self.kb.union(ref_concept_B, concept_A) - - def refine_object_intersection_of(self, C: OWLObjectIntersectionOf): - """ - - :param C: - :return: - """ - - concept_A = C.concept_a - concept_B = C.concept_b - for ref_concept_A in self.refine(concept_A): - if isinstance(ref_concept_A, OWLClassExpression): - yield self.kb.intersection(ref_concept_A, concept_B) - - for ref_concept_B in self.refine(concept_A): - if isinstance(ref_concept_B, OWLClassExpression): - yield self.kb.intersection(ref_concept_B, concept_A) - - def refine(self, concept: OWLClassExpression): - assert isinstance(concept, OWLClassExpression) - - if isinstance(concept, OWLClass): - yield from self.refine_atomic_concept(concept) - elif isinstance(concept, OWLObjectComplementOf): - yield from self.refine_complement_of(concept) - elif isinstance(concept, OWLObjectSomeValuesFrom): - yield from self.refine_object_some_values_from(concept) - elif isinstance(concept, OWLObjectAllValuesFrom): - yield from self.refine_object_all_values_from(concept) - elif isinstance(concept, OWLObjectUnionOf): - yield from self.refine_object_union_of(concept) - elif isinstance(concept, OWLObjectIntersectionOf): - yield from self.refine_object_intersection_of(concept) - else: - raise ValueError(f"{type(concept)} objects are not yet supported") - - class ExpressRefinement(ModifiedCELOERefinement): """ A top down refinement operator refinement operator in ALCHIQ(D).""" - __slots__ = 'expressivity', 'downsample', 'sample_fillers_count' + __slots__ = 'expressivity', 'downsample', 'sample_fillers_count', 'generator' expressivity: float downsample: bool sample_fillers_count: int + generator: ConceptGenerator def __init__(self, knowledge_base, downsample: bool = True, @@ -784,7 +656,7 @@ def __init__(self, knowledge_base, self.downsample = downsample self.sample_fillers_count = sample_fillers_count self.expressivity = expressivity - + self.generator = ConceptGenerator() super().__init__(knowledge_base, value_splitter=value_splitter, max_child_length=max_child_length, @@ -807,7 +679,7 @@ def refine_atomic_concept(self, ce: OWLClass) -> Iterable[OWLClassExpression]: iter_container_sub = [ce] iter_container_restrict = [] # Get negations of all subconcepts - iter_container_neg = list(self.kb.negation_from_iterables(iter_container_sub)) + iter_container_neg = list(self.generator.negation_from_iterables(iter_container_sub)) # (3) Create ∀.r.C and ∃.r.C where r is the most general relation and C in Fillers fillers: Set[OWLClassExpression] = {OWLThing, OWLNothing} if len(iter_container_sub) >= self.sample_fillers_count: @@ -834,8 +706,8 @@ def refine_atomic_concept(self, ce: OWLClass) -> Iterable[OWLClassExpression]: if self.use_boolean_datatype: bool_res = [] for bool_dp in self.kb.most_general_boolean_data_properties(domain=ce): - bool_res.append(self.kb.data_has_value_restriction(value=OWLLiteral(True), property=bool_dp)) - bool_res.append(self.kb.data_has_value_restriction(value=OWLLiteral(False), property=bool_dp)) + bool_res.append(self.generator.data_has_value_restriction(value=OWLLiteral(True), property=bool_dp)) + bool_res.append(self.generator.data_has_value_restriction(value=OWLLiteral(False), property=bool_dp)) iter_container_restrict.append(set(bool_res)) if self.use_card_restrictions and (self.max_child_length >= self.len(ce) + 3): @@ -843,7 +715,7 @@ def refine_atomic_concept(self, ce: OWLClass) -> Iterable[OWLClassExpression]: for prop in self.kb.most_general_object_properties(domain=ce): max_ = self.max_nr_fillers[prop] if max_ > 1: - card_res.append(self.kb.max_cardinality_restriction(self.kb.thing, prop, max_ - 1)) + card_res.append(self.generator.max_cardinality_restriction(self.generator.thing, prop, max_ - 1)) iter_container_restrict.append(set(card_res)) iter_container_restrict = list(set(chain.from_iterable(iter_container_restrict))) @@ -867,16 +739,16 @@ def refine_atomic_concept(self, ce: OWLClass) -> Iterable[OWLClassExpression]: for other_ref in container: if sub != other_ref and self.len(sub) + self.len(other_ref) < self.max_child_length: if ce.is_owl_thing() or (other_ref in iter_container_sub): - union = self.kb.union([sub, other_ref]) + union = self.generator.union([sub, other_ref]) yield union any_refinement = True elif other_ref not in iter_container_sub: - union = self.kb.union([sub, other_ref]) - union = self.kb.intersection([ce, union]) + union = self.generator.union([sub, other_ref]) + union = self.generator.intersection([ce, union]) if self.len(union) <= self.max_child_length: yield union any_refinement = True - intersect = self.kb.intersection([sub, other_ref]) + intersect = self.generator.intersection([sub, other_ref]) if self.len(intersect) <= self.max_child_length: yield intersect any_refinement = True @@ -886,8 +758,8 @@ def refine_atomic_concept(self, ce: OWLClass) -> Iterable[OWLClassExpression]: def refine_complement_of(self, ce: OWLObjectComplementOf) -> Iterable[OWLClassExpression]: assert isinstance(ce, OWLObjectComplementOf) any_refinement = False - parents = self.kb.get_direct_parents(self.kb.negation(ce)) - for ref in self.kb.negation_from_iterables(parents): + parents = self.kb.get_direct_parents(self.generator.negation(ce)) + for ref in self.generator.negation_from_iterables(parents): if self.len(ref) <= self.max_child_length: any_refinement = True yield ref @@ -901,21 +773,21 @@ def refine_object_some_values_from(self, ce: OWLObjectSomeValuesFrom) -> Iterabl for ref in self.refine(ce.get_filler()): if 2 + self.len(ref) <= self.max_child_length: any_refinement = True - reft = self.kb.existential_restriction(ref, ce.get_property()) + reft = self.generator.existential_restriction(ref, ce.get_property()) yield reft if self.len(ce) <= self.max_child_length: any_refinement = True - reft = self.kb.universal_restriction(ce.get_filler(), ce.get_property()) + reft = self.generator.universal_restriction(ce.get_filler(), ce.get_property()) yield reft for more_special_op in self.kb.object_property_hierarchy(). \ more_special_roles(ce.get_property().get_named_property()): if self.len(ce) <= self.max_child_length: - yield self.kb.existential_restriction(ce.get_filler(), more_special_op) + yield self.generator.existential_restriction(ce.get_filler(), more_special_op) any_refinement = True if self.use_card_restrictions and self.len(ce) <= self.max_child_length and self.max_nr_fillers[ce.get_property()] > 1: - yield self.kb.min_cardinality_restriction(ce.get_filler(), ce.get_property(), 2) + yield self.generator.min_cardinality_restriction(ce.get_filler(), ce.get_property(), 2) any_refinement = True if not any_refinement: yield ce @@ -927,12 +799,12 @@ def refine_object_all_values_from(self, ce: OWLObjectAllValuesFrom) -> Iterable[ for ref in self.refine(ce.get_filler()): if 2 + self.len(ref) <= self.max_child_length: any_refinement = True - reft = self.kb.universal_restriction(ref, ce.get_property()) + reft = self.generator.universal_restriction(ref, ce.get_property()) yield reft for more_special_op in self.kb.object_property_hierarchy(). \ more_special_roles(ce.get_property().get_named_property()): if 2 + self.len(ce.get_filler()) <= self.max_child_length: - yield self.kb.universal_restriction(ce.get_filler(), more_special_op) + yield self.generator.universal_restriction(ce.get_filler(), more_special_op) any_refinement = True if not any_refinement and not ce.get_filler().is_owl_nothing(): yield ce @@ -946,10 +818,10 @@ def refine_object_min_card_restriction(self, ce: OWLObjectMinCardinality) \ for ref in self.refine(ce.get_filler()): if ref is not None: - yield self.kb.min_cardinality_restriction(ref, ce.get_property(), ce.get_cardinality()) + yield self.generator.min_cardinality_restriction(ref, ce.get_property(), ce.get_cardinality()) if self.use_card_restrictions and ce.get_cardinality() < self.max_nr_fillers[ce.get_property()]: - yield self.kb.min_cardinality_restriction(ce.get_filler(), ce.get_property(), ce.get_cardinality() + 1) + yield self.generator.min_cardinality_restriction(ce.get_filler(), ce.get_property(), ce.get_cardinality() + 1) def refine_object_max_card_restriction(self, ce: OWLObjectMaxCardinality) \ -> Iterable[OWLObjectMaxCardinality]: @@ -958,10 +830,10 @@ def refine_object_max_card_restriction(self, ce: OWLObjectMaxCardinality) \ for ref in self.refine(ce.get_filler()): if ref is not None: - yield self.kb.max_cardinality_restriction(ref, ce.get_property(), ce.get_cardinality()) + yield self.generator.max_cardinality_restriction(ref, ce.get_property(), ce.get_cardinality()) if ce.get_cardinality() > 1: - yield self.kb.max_cardinality_restriction(ce.get_filler(), ce.get_property(), ce.get_cardinality() - 1) + yield self.generator.max_cardinality_restriction(ce.get_filler(), ce.get_property(), ce.get_cardinality() - 1) def refine_object_union_of(self, ce: OWLObjectUnionOf) -> Iterable[OWLClassExpression]: assert isinstance(ce, OWLObjectUnionOf) @@ -976,7 +848,7 @@ def refine_object_union_of(self, ce: OWLObjectUnionOf) -> Iterable[OWLClassExpre other_length = self._operands_len(OWLObjectUnionOf, ce_left + ce_right) for ref_ce in self.refine(ce_): if self.max_child_length >= other_length + self.len(ref_ce): - yield self.kb.union(ce_left + [ref_ce] + ce_right) + yield self.generator.union(ce_left + [ref_ce] + ce_right) any_refinement = True if not any_refinement: yield ce @@ -990,7 +862,7 @@ def refine_object_intersection_of(self, ce: OWLObjectIntersectionOf) -> Iterable other_length = self._operands_len(OWLObjectIntersectionOf, ce_left + ce_right) for ref_ce in self.refine(ce): if self.max_child_length >= other_length + self.len(ref_ce): - yield self.kb.intersection(ce_left + [ref_ce] + ce_right) + yield self.generator.intersection(ce_left + [ref_ce] + ce_right) any_refinement = True if not any_refinement: yield ce @@ -1007,11 +879,11 @@ def refine_data_some_values_from(self, ce: OWLDataSomeValuesFrom) -> Iterable[OW idx = splits.index(val) if facet_res.get_facet() == OWLFacet.MIN_INCLUSIVE and (next_idx := idx + 1) < len(splits): - yield self.kb.data_existential_restriction(OWLDatatypeMinInclusiveRestriction(splits[next_idx]), + yield self.generator.data_existential_restriction(OWLDatatypeMinInclusiveRestriction(splits[next_idx]), ce.get_property()) any_refinement = True elif facet_res.get_facet() == OWLFacet.MAX_INCLUSIVE and (next_idx := idx - 1) >= 0: - yield self.kb.data_existential_restriction(OWLDatatypeMaxInclusiveRestriction(splits[next_idx]), + yield self.generator.data_existential_restriction(OWLDatatypeMaxInclusiveRestriction(splits[next_idx]), ce.get_property()) any_refinement = True if not any_refinement: @@ -1021,7 +893,7 @@ def refine_data_has_value(self, ce: OWLDataHasValue) -> Iterable[OWLDataHasValue assert isinstance(ce, OWLDataHasValue) any_refinement = False for more_special_dp in self.kb.data_property_hierarchy().more_special_roles(ce.get_property()): - yield self.kb.data_has_value_restriction(ce.get_filler(), more_special_dp) + yield self.generator.data_has_value_restriction(ce.get_filler(), more_special_dp) any_refinement = True if not any_refinement: diff --git a/ontolearn/search.py b/ontolearn/search.py index f758754d..28964fb8 100644 --- a/ontolearn/search.py +++ b/ontolearn/search.py @@ -5,11 +5,10 @@ from queue import PriorityQueue from typing import List, Optional, ClassVar, Final, Iterable, TypeVar, Generic, Set, Tuple, Dict -from owlapy.io import OWLObjectRenderer -from owlapy.model import OWLClassExpression -from owlapy.render import DLSyntaxObjectRenderer -from owlapy.util import as_index, OrderedOWLObject -from superprop import super_prop +from ontolearn.owlapy.io import OWLObjectRenderer +from ontolearn.owlapy.model import OWLClassExpression +from ontolearn.owlapy.render import DLSyntaxObjectRenderer +from ontolearn.owlapy.util import as_index, OrderedOWLObject from .abstracts import AbstractNode, AbstractHeuristic, AbstractScorer, AbstractOEHeuristicNode, LBLSearchTree, \ AbstractConceptNode, EncodedLearningProblem, DRILLAbstractTree @@ -377,7 +376,7 @@ def children(self): @property def parent_node(self) -> Optional['LBLNode']: - return super_prop(super()).parent_node + return SuperProp(super()).parent_node @parent_node.setter def parent_node(self, parent_node: Optional['LBLNode']): @@ -732,3 +731,47 @@ def get_top_n(self, n: int, key='quality') -> List[Node]: def clean(self): self.items_in_queue = PriorityQueue() self._nodes.clear() + + +class SuperProp: + """ + Super wrapper which allows property setting & deletion. Super can't be subclassed with empty __init__ arguments. + """ + + def __init__(self, super_obj): + object.__setattr__(self, 'super_obj', super_obj) + + def _find_desc(self, name): + super_obj = object.__getattribute__(self, 'super_obj') + if name != '__class__': + mro = iter(super_obj.__thisclass__.__mro__) + for cls in mro: + if cls == super_obj.__thisclass__: + break + for cls in mro: + if isinstance(cls, type): + try: + # don't lookup further up the chain + return object.__getattribute__(cls, name) + except AttributeError: + continue + except KeyError: + return None + return None + + def __getattr__(self, name): + return getattr(object.__getattribute__(self, 'super_obj'), name) + + def __setattr__(self, name, value): + super_obj = object.__getattribute__(self, 'super_obj') + desc = object.__getattribute__(self, '_find_desc')(name) + if hasattr(desc, '__set__'): + return desc.__set__(super_obj.__self__, value) + return setattr(super_obj, name, value) + + def __delattr__(self, name): + super_obj = object.__getattribute__(self, 'super_obj') + desc = object.__getattribute__(self, '_find_desc')(name) + if hasattr(desc, '__delete__'): + return desc.__delete__(super_obj.__self__) + return delattr(super_obj, name) diff --git a/ontolearn/sparqlkb.py b/ontolearn/sparqlkb.py index f1ebffce..d6dc1909 100644 --- a/ontolearn/sparqlkb.py +++ b/ontolearn/sparqlkb.py @@ -4,24 +4,23 @@ import httpx as httpx -from ontolearn import KnowledgeBase +from ontolearn.knowledge_base import KnowledgeBase from ontolearn.abstracts import AbstractScorer, AbstractLearningProblem, AbstractKnowledgeBase, \ EncodedPosNegLPStandardKind -from ontolearn.concept_generator import ConceptGenerator from ontolearn.core.owl.utils import OWLClassExpressionLengthMetric from ontolearn.knowledge_base import EvaluatedConcept, Factory, _Default_ClassExpressionLengthMetricFactory from ontolearn.learning_problem import PosNegLPStandard from ontolearn.utils import oplogging -from owlapy.ext import OWLReasonerEx -from owlapy.model import OWLClassAxiom, OWLClassExpression, OWLEntity, OWLOntology, OWLClass, OWLNamedIndividual, \ +from ontolearn.owlapy.ext import OWLReasonerEx +from ontolearn.owlapy.model import OWLClassAxiom, OWLClassExpression, OWLEntity, OWLOntology, OWLClass, OWLNamedIndividual, \ OWLObjectPropertyExpression, OWLDataProperty, OWLObjectProperty, OWLOntologyID, _M, OWLDataPropertyRangeAxiom, \ IRI, OWLLiteral, OWLDatatype, OWLDataPropertyDomainAxiom, OWLObjectPropertyDomainAxiom, \ OWLObjectPropertyRangeAxiom -from owlapy.owl2sparql.converter import Owl2SparqlConverter -from owlapy.owlready2 import OWLOntologyManager_Owlready2, OWLReasoner_Owlready2 -from owlapy.render import DLSyntaxObjectRenderer -from owlapy.util import LRUCache -from owlapy.vocab import OWLRDFVocabulary +from ontolearn.owlapy.owl2sparql.converter import Owl2SparqlConverter +from ontolearn.owlapy.owlready2 import OWLOntologyManager_Owlready2, OWLReasoner_Owlready2 +from ontolearn.owlapy.render import DLSyntaxObjectRenderer +from ontolearn.owlapy.util import LRUCache +from ontolearn.owlapy.vocab import OWLRDFVocabulary logger = logging.getLogger(__name__) @@ -293,7 +292,7 @@ def __init__(self, path: str, endpoint_url: str, *, else: self._length_metric = _Default_ClassExpressionLengthMetricFactory() - ConceptGenerator.__init__(self, reasoner=self._reasoner) + # ConceptGenerator.__init__(self, reasoner=self._reasoner) individuals = self._ontology.individuals_in_signature() self._ind_set = frozenset(individuals) diff --git a/ontolearn/tentris.py b/ontolearn/tentris.py index 9b911440..0f5d22ec 100644 --- a/ontolearn/tentris.py +++ b/ontolearn/tentris.py @@ -8,19 +8,18 @@ from ontolearn.knowledge_base import KnowledgeBase from ontolearn.abstracts import AbstractScorer, AbstractLearningProblem, AbstractKnowledgeBase, \ EncodedPosNegLPStandardKind -from ontolearn.concept_generator import ConceptGenerator from ontolearn.core.owl.utils import OWLClassExpressionLengthMetric from ontolearn.knowledge_base import EvaluatedConcept, Factory, _Default_ClassExpressionLengthMetricFactory from ontolearn.learning_problem import PosNegLPStandard from ontolearn.metrics import F1, Precision, Accuracy, Recall from ontolearn.utils import oplogging -from owlapy.ext import OWLReasonerEx -from owlapy.model import OWLClassExpression, OWLEntity, OWLOntology, OWLClass, OWLNamedIndividual, \ +from ontolearn.owlapy.ext import OWLReasonerEx +from ontolearn.owlapy.model import OWLClassExpression, OWLEntity, OWLOntology, OWLClass, OWLNamedIndividual, \ OWLObjectPropertyExpression, OWLDataProperty, OWLObjectProperty, OWLOntologyID, _M, OWLDataPropertyRangeAxiom, \ IRI, OWLThing, OWLLiteral, OWLObjectPropertyRangeAxiom, OWLObjectPropertyDomainAxiom, OWLDataPropertyDomainAxiom -from owlapy.owlready2 import OWLOntologyManager_Owlready2, OWLReasoner_Owlready2 -from owlapy.render import ManchesterOWLSyntaxOWLObjectRenderer, DLSyntaxObjectRenderer -from owlapy.util import LRUCache +from ontolearn.owlapy.owlready2 import OWLOntologyManager_Owlready2, OWLReasoner_Owlready2 +from ontolearn.owlapy.render import ManchesterOWLSyntaxOWLObjectRenderer, DLSyntaxObjectRenderer +from ontolearn.owlapy.util import LRUCache logger = logging.getLogger(__name__) @@ -225,8 +224,6 @@ def __init__(self, path: str, *, else: self._length_metric = _Default_ClassExpressionLengthMetricFactory() - ConceptGenerator.__init__(self, reasoner=self._reasoner) - individuals = self._ontology.individuals_in_signature() self._ind_set = frozenset(individuals) diff --git a/ontolearn/utils/__init__.py b/ontolearn/utils/__init__.py index 351375c2..8abc9455 100644 --- a/ontolearn/utils/__init__.py +++ b/ontolearn/utils/__init__.py @@ -6,7 +6,7 @@ from typing import Callable, Set, TypeVar, Tuple from ontolearn.utils.log_config import setup_logging # noqa: F401 -from owlapy.model import OWLNamedIndividual, IRI, OWLClass, HasIRI +from ontolearn.owlapy.model import OWLNamedIndividual, IRI, OWLClass, HasIRI Factory = Callable diff --git a/ontolearn/value_splitter.py b/ontolearn/value_splitter.py index f0a19263..ffaac196 100644 --- a/ontolearn/value_splitter.py +++ b/ontolearn/value_splitter.py @@ -9,7 +9,7 @@ from sortedcontainers import SortedDict from typing import Dict, List, Optional, Set, Tuple, Union -from owlapy.model import OWLDataProperty, OWLLiteral, OWLNamedIndividual, OWLReasoner +from ontolearn.owlapy.model import OWLDataProperty, OWLLiteral, OWLNamedIndividual, OWLReasoner import math diff --git a/setup.cfg b/setup.cfg index 5e5e314f..36452d82 100644 --- a/setup.cfg +++ b/setup.cfg @@ -14,7 +14,6 @@ classifiers = [options] python_requires = >=3.8 include_package_data = True -# packages = ontolearn, owlapy, superprop, sortedcontainers-stubs packages = find: scripts = ontolearn/endpoint/simple_drill_endpoint diff --git a/sortedcontainers-stubs/LICENSE b/sortedcontainers-stubs/LICENSE deleted file mode 100644 index 668d8ecd..00000000 --- a/sortedcontainers-stubs/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2014-2019 Grant Jenks - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/sortedcontainers-stubs/__init__.py b/sortedcontainers-stubs/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/sortedcontainers-stubs/__init__.pyi b/sortedcontainers-stubs/__init__.pyi deleted file mode 100644 index f22edee2..00000000 --- a/sortedcontainers-stubs/__init__.pyi +++ /dev/null @@ -1,19 +0,0 @@ -from .sortedlist import SortedList, SortedKeyList, SortedListWithKey -from .sortedset import SortedSet -from .sorteddict import ( - SortedDict, - SortedKeysView, - SortedItemsView, - SortedValuesView, -) - -__all__ = [ - 'SortedList', - 'SortedKeyList', - 'SortedListWithKey', - 'SortedDict', - 'SortedKeysView', - 'SortedItemsView', - 'SortedValuesView', - 'SortedSet', -] diff --git a/sortedcontainers-stubs/py.typed b/sortedcontainers-stubs/py.typed deleted file mode 100644 index e69de29b..00000000 diff --git a/sortedcontainers-stubs/sorteddict.pyi b/sortedcontainers-stubs/sorteddict.pyi deleted file mode 100644 index 9e312a61..00000000 --- a/sortedcontainers-stubs/sorteddict.pyi +++ /dev/null @@ -1,122 +0,0 @@ -from typing import ( - Any, - Callable, - Dict, - Generic, - Hashable, - Iterator, - Iterable, - ItemsView, - KeysView, - List, - Mapping, - Optional, - Sequence, - Type, - TypeVar, - Tuple, - Union, - ValuesView, - overload, -) - -_T = TypeVar("_T") -_S = TypeVar("_S") -_T_h = TypeVar("_T_h", bound=Hashable) -_KT = TypeVar("_KT", bound=Hashable) # Key type. -_VT = TypeVar("_VT") # Value type. -_KT_co = TypeVar("_KT_co", covariant=True, bound=Hashable) -_VT_co = TypeVar("_VT_co", covariant=True) -_SD = TypeVar("_SD", bound='SortedDict') -_Key = Callable[[_T], Any] - -class SortedDict(Dict[_KT, _VT]): - @overload - def __init__(self, **kwargs: _VT) -> None: ... - @overload - def __init__(self, __map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... - @overload - def __init__( - self, __iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT - ) -> None: ... - @overload - def __init__(self, __key: _Key[_KT], **kwargs: _VT) -> None: ... - @overload - def __init__( - self, __key: _Key[_KT], __map: Mapping[_KT, _VT], **kwargs: _VT - ) -> None: ... - @overload - def __init__( - self, - __key: _Key[_KT], - __iterable: Iterable[Tuple[_KT, _VT]], - **kwargs: _VT - ) -> None: ... - @property - def key(self) -> Optional[_Key[_KT]]: ... - @property - def iloc(self) -> SortedKeysView[_KT]: ... - def clear(self) -> None: ... - def __delitem__(self, key: _KT) -> None: ... - def __iter__(self) -> Iterator[_KT]: ... - def __reversed__(self) -> Iterator[_KT]: ... - def __setitem__(self, key: _KT, value: _VT) -> None: ... - def _setitem(self, key: _KT, value: _VT) -> None: ... - def copy(self: _SD) -> _SD: ... - def __copy__(self: _SD) -> _SD: ... - @classmethod - @overload - def fromkeys(cls, seq: Iterable[_T_h]) -> SortedDict[_T_h, None]: ... - @classmethod - @overload - def fromkeys(cls, seq: Iterable[_T_h], value: _S) -> SortedDict[_T_h, _S]: ... - def keys(self) -> SortedKeysView[_KT]: ... - def items(self) -> SortedItemsView[_KT, _VT]: ... - def values(self) -> SortedValuesView[_VT]: ... - @overload - def pop(self, key: _KT) -> _VT: ... - @overload - def pop(self, key: _KT, default: _T = ...) -> Union[_VT, _T]: ... - def popitem(self, index: int = ...) -> Tuple[_KT, _VT]: ... - def peekitem(self, index: int = ...) -> Tuple[_KT, _VT]: ... - def setdefault(self, key: _KT, default: _VT = ...) -> _VT: ... - @overload - def update(self, __map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... - @overload - def update( - self, __iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT - ) -> None: ... - @overload - def update(self, **kwargs: _VT) -> None: ... - def __reduce__( - self - ) -> Tuple[ - Type[SortedDict[_KT, _VT]], - Tuple[Callable[[_KT], Any], List[Tuple[_KT, _VT]]], - ]: ... - def __repr__(self) -> str: ... - def _check(self) -> None: ... - -class SortedKeysView(KeysView[_KT_co], Sequence[_KT_co]): - @overload - def __getitem__(self, index: int) -> _KT_co: ... - @overload - def __getitem__(self, index: slice) -> List[_KT_co]: ... - def __delitem__(self, index: Union[int, slice]) -> None: ... - -class SortedItemsView( - ItemsView[_KT_co, _VT_co], Sequence[Tuple[_KT_co, _VT_co]] -): - def __iter__(self) -> Iterator[Tuple[_KT_co, _VT_co]]: ... - @overload - def __getitem__(self, index: int) -> Tuple[_KT_co, _VT_co]: ... - @overload - def __getitem__(self, index: slice) -> List[Tuple[_KT_co, _VT_co]]: ... - def __delitem__(self, index: Union[int, slice]) -> None: ... - -class SortedValuesView(ValuesView[_VT_co], Sequence[_VT_co]): - @overload - def __getitem__(self, index: int) -> _VT_co: ... - @overload - def __getitem__(self, index: slice) -> List[_VT_co]: ... - def __delitem__(self, index: Union[int, slice]) -> None: ... diff --git a/sortedcontainers-stubs/sortedlist.pyi b/sortedcontainers-stubs/sortedlist.pyi deleted file mode 100644 index 3535aeb2..00000000 --- a/sortedcontainers-stubs/sortedlist.pyi +++ /dev/null @@ -1,187 +0,0 @@ -from typing import ( - Any, - Callable, - Generic, - Iterable, - Iterator, - List, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - TypeVar, - Union, - overload, -) - -_T = TypeVar("_T") -_SL = TypeVar("_SL", bound='SortedList') -_SKL = TypeVar("_SKL", bound='SortedKeyList') -_Key = Callable[[_T], Any] -_Repr = Callable[[], str] - -def recursive_repr(fillvalue: str = ...) -> Callable[[_Repr], _Repr]: ... - -class SortedList(MutableSequence[_T]): - - DEFAULT_LOAD_FACTOR: int = ... - def __init__( - self, - iterable: Optional[Iterable[_T]] = ..., - key: Optional[_Key[_T]] = ..., - ): ... - # NB: currently mypy does not honour return type, see mypy #3307 - @overload - def __new__(cls: Type[_SL], iterable: None, key: None) -> _SL: ... - @overload - def __new__( - cls: Type[_SL], iterable: None, key: _Key[_T] - ) -> SortedKeyList[_T]: ... - @overload - def __new__(cls: Type[_SL], iterable: Iterable[_T], key: None) -> _SL: ... - @overload - def __new__( - cls, iterable: Iterable[_T], key: _Key[_T] - ) -> SortedKeyList[_T]: ... - @property - def key(self) -> Optional[Callable[[_T], Any]]: ... - def _reset(self, load: int) -> None: ... - def clear(self) -> None: ... - def _clear(self) -> None: ... - def add(self, value: _T) -> None: ... - def _expand(self, pos: int) -> None: ... - def update(self, iterable: Iterable[_T]) -> None: ... - def _update(self, iterable: Iterable[_T]) -> None: ... - def discard(self, value: _T) -> None: ... - def remove(self, value: _T) -> None: ... - def _delete(self, pos: int, idx: int) -> None: ... - def _loc(self, pos: int, idx: int) -> int: ... - def _pos(self, idx: int) -> int: ... - def _build_index(self) -> None: ... - def __contains__(self, value: Any) -> bool: ... - def __delitem__(self, index: Union[int, slice]) -> None: ... - @overload - def __getitem__(self, index: int) -> _T: ... - @overload - def __getitem__(self, index: slice) -> List[_T]: ... - @overload - def _getitem(self, index: int) -> _T: ... - @overload - def _getitem(self, index: slice) -> List[_T]: ... - @overload - def __setitem__(self, index: int, value: _T) -> None: ... - @overload - def __setitem__(self, index: slice, value: Iterable[_T]) -> None: ... - def __iter__(self) -> Iterator[_T]: ... - def __reversed__(self) -> Iterator[_T]: ... - def __len__(self) -> int: ... - def reverse(self) -> None: ... - def islice( - self, - start: Optional[int] = ..., - stop: Optional[int] = ..., - reverse=bool, - ) -> Iterator[_T]: ... - def _islice( - self, - min_pos: int, - min_idx: int, - max_pos: int, - max_idx: int, - reverse: bool, - ) -> Iterator[_T]: ... - def irange( - self, - minimum: Optional[int] = ..., - maximum: Optional[int] = ..., - inclusive: Tuple[bool, bool] = ..., - reverse: bool = ..., - ) -> Iterator[_T]: ... - def bisect_left(self, value: _T) -> int: ... - def bisect_right(self, value: _T) -> int: ... - def bisect(self, value: _T) -> int: ... - def _bisect_right(self, value: _T) -> int: ... - def count(self, value: _T) -> int: ... - def copy(self: _SL) -> _SL: ... - def __copy__(self: _SL) -> _SL: ... - def append(self, value: _T) -> None: ... - def extend(self, values: Iterable[_T]) -> None: ... - def insert(self, index: int, value: _T) -> None: ... - def pop(self, index: int = ...) -> _T: ... - def index( - self, value: _T, start: Optional[int] = ..., stop: Optional[int] = ... - ) -> int: ... - def __add__(self: _SL, other: Iterable[_T]) -> _SL: ... - def __radd__(self: _SL, other: Iterable[_T]) -> _SL: ... - def __iadd__(self: _SL, other: Iterable[_T]) -> _SL: ... - def __mul__(self: _SL, num: int) -> _SL: ... - def __rmul__(self: _SL, num: int) -> _SL: ... - def __imul__(self: _SL, num: int) -> _SL: ... - def __eq__(self, other: Any) -> bool: ... - def __ne__(self, other: Any) -> bool: ... - def __lt__(self, other: Sequence[_T]) -> bool: ... - def __gt__(self, other: Sequence[_T]) -> bool: ... - def __le__(self, other: Sequence[_T]) -> bool: ... - def __ge__(self, other: Sequence[_T]) -> bool: ... - def __repr__(self) -> str: ... - def _check(self) -> None: ... - -class SortedKeyList(SortedList[_T]): - def __init__( - self, iterable: Optional[Iterable[_T]] = ..., key: _Key[_T] = ... - ) -> None: ... - def __new__( - cls, iterable: Optional[Iterable[_T]] = ..., key: _Key[_T] = ... - ) -> SortedKeyList[_T]: ... - @property - def key(self) -> Callable[[_T], Any]: ... - def clear(self) -> None: ... - def _clear(self) -> None: ... - def add(self, value: _T) -> None: ... - def _expand(self, pos: int) -> None: ... - def update(self, iterable: Iterable[_T]) -> None: ... - def _update(self, iterable: Iterable[_T]) -> None: ... - # NB: Must be T to be safely passed to self.func, yet base class imposes Any - def __contains__(self, value: _T) -> bool: ... # type: ignore - def discard(self, value: _T) -> None: ... - def remove(self, value: _T) -> None: ... - def _delete(self, pos: int, idx: int) -> None: ... - def irange( - self, - minimum: Optional[int] = ..., - maximum: Optional[int] = ..., - inclusive: Tuple[bool, bool] = ..., - reverse: bool = ..., - ): ... - def irange_key( - self, - min_key: Optional[Any] = ..., - max_key: Optional[Any] = ..., - inclusive: Tuple[bool, bool] = ..., - reserve: bool = ..., - ): ... - def bisect_left(self, value: _T) -> int: ... - def bisect_right(self, value: _T) -> int: ... - def bisect(self, value: _T) -> int: ... - def bisect_key_left(self, key: Any) -> int: ... - def _bisect_key_left(self, key: Any) -> int: ... - def bisect_key_right(self, key: Any) -> int: ... - def _bisect_key_right(self, key: Any) -> int: ... - def bisect_key(self, key: Any) -> int: ... - def count(self, value: _T) -> int: ... - def copy(self: _SKL) -> _SKL: ... - def __copy__(self: _SKL) -> _SKL: ... - def index( - self, value: _T, start: Optional[int] = ..., stop: Optional[int] = ... - ) -> int: ... - def __add__(self: _SKL, other: Iterable[_T]) -> _SKL: ... - def __radd__(self: _SKL, other: Iterable[_T]) -> _SKL: ... - def __iadd__(self: _SKL, other: Iterable[_T]) -> _SKL: ... - def __mul__(self: _SKL, num: int) -> _SKL: ... - def __rmul__(self: _SKL, num: int) -> _SKL: ... - def __imul__(self: _SKL, num: int) -> _SKL: ... - def __repr__(self) -> str: ... - def _check(self) -> None: ... - -SortedListWithKey = SortedKeyList diff --git a/sortedcontainers-stubs/sortedset.pyi b/sortedcontainers-stubs/sortedset.pyi deleted file mode 100644 index 4aaa413d..00000000 --- a/sortedcontainers-stubs/sortedset.pyi +++ /dev/null @@ -1,155 +0,0 @@ -from typing import ( - Any, - AbstractSet, - Callable, - Generic, - Hashable, - Iterable, - Iterator, - List, - MutableSet, - Optional, - Sequence, - Tuple, - Type, - Set, - TypeVar, - Union, - overload, -) - -# --- Global - -_T = TypeVar("_T", bound=Hashable) -_S = TypeVar("_S", bound=Hashable) -_SS = TypeVar("_SS", bound='SortedSet') -_Key = Callable[[_T], Any] - -class SortedSet(MutableSet[_T], Sequence[_T]): - def __init__( - self, - iterable: Optional[Iterable[_T]] = ..., - key: Optional[_Key[_T]] = ..., - ) -> None: ... - @classmethod - def _fromset( - cls, values: Set[_T], key: Optional[_Key[_T]] = ... - ) -> SortedSet[_T]: ... - # NB: currently mypy does not honour return type, see mypy #3307 - @overload - def __new__(cls: Type[_SS], iterable: None, key: None) -> _SS: ... - @overload - def __new__( - cls: Type[_SS], iterable: None, key: _Key[_T] - ) -> _SortedKeySet[_T]: ... - @overload - def __new__(cls: Type[_SS], iterable: Iterable[_T], key: None) -> _SS: ... - @overload - def __new__( - cls, iterable: Iterable[_T], key: _Key[_T] - ) -> _SortedKeySet[_T]: ... - @property - def key(self) -> Optional[_Key[_T]]: ... - def __contains__(self, value: Any) -> bool: ... - @overload - def __getitem__(self, index: int) -> _T: ... - @overload - def __getitem__(self, index: slice) -> List[_T]: ... - def __delitem__(self, index: Union[int, slice]) -> None: ... - def __eq__(self, other: Any) -> bool: ... - def __ne__(self, other: Any) -> bool: ... - def __lt__(self, other: Iterable[_T]) -> bool: ... - def __gt__(self, other: Iterable[_T]) -> bool: ... - def __le__(self, other: Iterable[_T]) -> bool: ... - def __ge__(self, other: Iterable[_T]) -> bool: ... - def __len__(self) -> int: ... - def __iter__(self) -> Iterator[_T]: ... - def __reversed__(self) -> Iterator[_T]: ... - def add(self, value: _T) -> None: ... - def _add(self, value: _T) -> None: ... - def clear(self) -> None: ... - def copy(self: _SS) -> _SS: ... - def __copy__(self: _SS) -> _SS: ... - def count(self, value: _T) -> int: ... - def discard(self, value: _T) -> None: ... - def _discard(self, value: _T) -> None: ... - def pop(self, index: int = ...) -> _T: ... - def remove(self, value: _T) -> None: ... - def difference( - self, *iterables: Iterable[_S] - ) -> SortedSet[Union[_T, _S]]: ... - def __sub__(self, *iterables: Iterable[_S]) -> SortedSet[Union[_T, _S]]: ... - def difference_update( - self, *iterables: Iterable[_S] - ) -> SortedSet[Union[_T, _S]]: ... - def __isub__( - self, *iterables: Iterable[_S] - ) -> SortedSet[Union[_T, _S]]: ... - def intersection( - self, *iterables: Iterable[_S] - ) -> SortedSet[Union[_T, _S]]: ... - def __and__(self, *iterables: Iterable[_S]) -> SortedSet[Union[_T, _S]]: ... - def __rand__( - self, *iterables: Iterable[_S] - ) -> SortedSet[Union[_T, _S]]: ... - def intersection_update( - self, *iterables: Iterable[_S] - ) -> SortedSet[Union[_T, _S]]: ... - def __iand__( - self, *iterables: Iterable[_S] - ) -> SortedSet[Union[_T, _S]]: ... - def symmetric_difference( - self, other: Iterable[_S] - ) -> SortedSet[Union[_T, _S]]: ... - def __xor__(self, other: Iterable[_S]) -> SortedSet[Union[_T, _S]]: ... - def __rxor__(self, other: Iterable[_S]) -> SortedSet[Union[_T, _S]]: ... - def symmetric_difference_update( - self, other: Iterable[_S] - ) -> SortedSet[Union[_T, _S]]: ... - def __ixor__(self, other: Iterable[_S]) -> SortedSet[Union[_T, _S]]: ... - def union(self, *iterables: Iterable[_S]) -> SortedSet[Union[_T, _S]]: ... - def __or__(self, *iterables: Iterable[_S]) -> SortedSet[Union[_T, _S]]: ... - def __ror__(self, *iterables: Iterable[_S]) -> SortedSet[Union[_T, _S]]: ... - def update(self, *iterables: Iterable[_S]) -> SortedSet[Union[_T, _S]]: ... - def __ior__(self, *iterables: Iterable[_S]) -> SortedSet[Union[_T, _S]]: ... - def _update(self, *iterables: Iterable[_S]) -> SortedSet[Union[_T, _S]]: ... - def __reduce__( - self - ) -> Tuple[Type[SortedSet[_T]], Set[_T], Callable[[_T], Any]]: ... - def __repr__(self) -> str: ... - def _check(self) -> None: ... - def bisect_left(self, value: _T) -> int: ... - def bisect_right(self, value: _T) -> int: ... - def islice( - self, - start: Optional[int] = ..., - stop: Optional[int] = ..., - reverse=bool, - ) -> Iterator[_T]: ... - def irange( - self, - minimum: Optional[_T] = ..., - maximum: Optional[_T] = ..., - inclusive: Tuple[bool, bool] = ..., - reverse: bool = ..., - ) -> Iterator[_T]: ... - def index( - self, value: _T, start: Optional[int] = ..., stop: Optional[int] = ... - ) -> int: ... - def _reset(self, load: int) -> None: ... - -class _SortedKeySet(SortedSet[_T]): - def __init__( - self, - iterable: Optional[Iterable[_T]] = ..., - key: _Key[_T] = ..., - ) -> None: ... - def bisect_key_left(self, key: Any) -> int: ... - def bisect_key_right(self, key: Any) -> int: ... - def irange_key( - self, - min_key: Optional[Any] = ..., - max_key: Optional[Any] = ..., - inclusive: Tuple[bool, bool] = ..., - reserve: bool = ..., - ): ... diff --git a/superprop/__init__.py b/superprop/__init__.py deleted file mode 100644 index d3449906..00000000 --- a/superprop/__init__.py +++ /dev/null @@ -1,57 +0,0 @@ -""" -Python property inheritance work-around module - -Based on: https://bugs.python.org/file37546/superprop.py -By: Simon Zack -See also: https://bugs.python.org/issue14965 - -""" - -__all__ = ['super_prop'] - - -class SuperProp: - """ - Super wrapper which allows property setting & deletion. Super can't be subclassed with empty __init__ arguments. - """ - - def __init__(self, super_obj): - object.__setattr__(self, 'super_obj', super_obj) - - def _find_desc(self, name): - super_obj = object.__getattribute__(self, 'super_obj') - if name != '__class__': - mro = iter(super_obj.__thisclass__.__mro__) - for cls in mro: - if cls == super_obj.__thisclass__: - break - for cls in mro: - if isinstance(cls, type): - try: - # don't lookup further up the chain - return object.__getattribute__(cls, name) - except AttributeError: - continue - except KeyError: - return None - return None - - def __getattr__(self, name): - return getattr(object.__getattribute__(self, 'super_obj'), name) - - def __setattr__(self, name, value): - super_obj = object.__getattribute__(self, 'super_obj') - desc = object.__getattribute__(self, '_find_desc')(name) - if hasattr(desc, '__set__'): - return desc.__set__(super_obj.__self__, value) - return setattr(super_obj, name, value) - - def __delattr__(self, name): - super_obj = object.__getattribute__(self, 'super_obj') - desc = object.__getattribute__(self, '_find_desc')(name) - if hasattr(desc, '__delete__'): - return desc.__delete__(super_obj.__self__) - return delattr(super_obj, name) - - -super_prop = SuperProp diff --git a/superprop/__init__.pyi b/superprop/__init__.pyi deleted file mode 100644 index e51dc2f1..00000000 --- a/superprop/__init__.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from typing import TypeVar - -_T = TypeVar('_T') - -def super_prop(super: _T) -> _T: ... diff --git a/superprop/py.typed b/superprop/py.typed deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/test_base_concept_learner.py b/tests/test_base_concept_learner.py index e59b5370..86f849c3 100644 --- a/tests/test_base_concept_learner.py +++ b/tests/test_base_concept_learner.py @@ -6,9 +6,9 @@ from ontolearn.knowledge_base import KnowledgeBase from ontolearn.learning_problem import PosNegLPStandard from ontolearn.search import EvoLearnerNode -from owlapy.model import OWLClass, OWLClassAssertionAxiom, OWLNamedIndividual, IRI, OWLObjectIntersectionOf, \ +from ontolearn.owlapy.model import OWLClass, OWLClassAssertionAxiom, OWLNamedIndividual, IRI, OWLObjectIntersectionOf, \ OWLObjectProperty, OWLObjectPropertyAssertionAxiom, OWLObjectSomeValuesFrom, OWLThing -from owlapy.render import DLSyntaxObjectRenderer +from ontolearn.owlapy.render import DLSyntaxObjectRenderer class BaseConceptLearnerTest(unittest.TestCase): diff --git a/tests/test_celoe.py b/tests/test_celoe.py index 1520135e..65f22083 100644 --- a/tests/test_celoe.py +++ b/tests/test_celoe.py @@ -7,8 +7,8 @@ from ontolearn.learning_problem import PosNegLPStandard from ontolearn.model_adapter import ModelAdapter from ontolearn.utils import setup_logging -from owlapy.model import OWLNamedIndividual, OWLClass, IRI -from owlapy.render import DLSyntaxObjectRenderer +from ontolearn.owlapy.model import OWLNamedIndividual, OWLClass, IRI +from ontolearn.owlapy.render import DLSyntaxObjectRenderer setup_logging("ontolearn/logging_test.conf") diff --git a/tests/test_concept.py b/tests/test_concept.py index e39a8028..0dda9043 100644 --- a/tests/test_concept.py +++ b/tests/test_concept.py @@ -2,8 +2,8 @@ import json from ontolearn.knowledge_base import KnowledgeBase from ontolearn.utils import setup_logging -from owlapy.model import OWLClass, IRI -from owlapy.owlready2 import OWLReasoner_Owlready2 +from ontolearn.owlapy.model import OWLClass, IRI +from ontolearn.owlapy.owlready2 import OWLReasoner_Owlready2 setup_logging("ontolearn/logging_test.conf") diff --git a/tests/test_core_owl_hierarchy.py b/tests/test_core_owl_hierarchy.py index f2772612..d4b4f7d0 100644 --- a/tests/test_core_owl_hierarchy.py +++ b/tests/test_core_owl_hierarchy.py @@ -3,8 +3,8 @@ from ontolearn.core.owl.hierarchy import ClassHierarchy, ObjectPropertyHierarchy, AbstractHierarchy from ontolearn.utils import setup_logging -from owlapy.model import OWLClass, OWLObjectProperty, IRI -from owlapy.owlready2 import OWLOntologyManager_Owlready2, OWLReasoner_Owlready2 +from ontolearn.owlapy.model import OWLClass, OWLObjectProperty, IRI +from ontolearn.owlapy.owlready2 import OWLOntologyManager_Owlready2, OWLReasoner_Owlready2 _T = TypeVar('_T') #: diff --git a/tests/test_core_utils_length.py b/tests/test_core_utils_length.py index b4525322..ebe8f60c 100644 --- a/tests/test_core_utils_length.py +++ b/tests/test_core_utils_length.py @@ -2,8 +2,8 @@ from ontolearn.core.owl.utils import OWLClassExpressionLengthMetric from ontolearn.utils import setup_logging -from owlapy.model.providers import OWLDatatypeMinMaxInclusiveRestriction -from owlapy.model import OWLDataUnionOf, OWLLiteral, OWLObjectProperty, OWLObjectUnionOf, OWLObjectSomeValuesFrom, \ +from ontolearn.owlapy.model.providers import OWLDatatypeMinMaxInclusiveRestriction +from ontolearn.owlapy.model import OWLDataUnionOf, OWLLiteral, OWLObjectProperty, OWLObjectUnionOf, OWLObjectSomeValuesFrom, \ OWLObjectComplementOf, OWLObjectIntersectionOf, OWLThing, OWLNamedIndividual, OWLObjectOneOf, OWLObjectHasValue, \ OWLObjectMinCardinality, IRI, DoubleOWLDatatype, IntegerOWLDatatype, OWLClass, \ OWLDataAllValuesFrom, OWLDataComplementOf, OWLDataExactCardinality, OWLDataHasValue, OWLDataIntersectionOf, \ diff --git a/tests/test_evolearner.py b/tests/test_evolearner.py index 72ab5a00..ccd343fe 100644 --- a/tests/test_evolearner.py +++ b/tests/test_evolearner.py @@ -2,7 +2,7 @@ import random import unittest from ontolearn.learning_problem import PosNegLPStandard -from owlapy.model import OWLNamedIndividual, IRI +from ontolearn.owlapy.model import OWLNamedIndividual, IRI from ontolearn.knowledge_base import KnowledgeBase from ontolearn.concept_learner import EvoLearner diff --git a/tests/test_express_refinement.py b/tests/test_express_refinement.py index e3b8429f..13b3dba1 100644 --- a/tests/test_express_refinement.py +++ b/tests/test_express_refinement.py @@ -4,7 +4,7 @@ from ontolearn.model_adapter import ModelAdapter from ontolearn.refinement_operators import ExpressRefinement from ontolearn.utils import setup_logging -from owlapy.model import OWLClass, OWLNamedIndividual, IRI +from ontolearn.owlapy.model import OWLClass, OWLNamedIndividual, IRI setup_logging("ontolearn/logging_test.conf") diff --git a/tests/test_concept_generator.py b/tests/test_knowledge_base.py similarity index 68% rename from tests/test_concept_generator.py rename to tests/test_knowledge_base.py index 64ee3af6..980e6227 100644 --- a/tests/test_concept_generator.py +++ b/tests/test_knowledge_base.py @@ -1,29 +1,25 @@ import unittest from itertools import repeat + from ontolearn.concept_generator import ConceptGenerator +from ontolearn.knowledge_base import KnowledgeBase -from owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker -from owlapy.model import OWLObjectUnionOf, OWLSubDataPropertyOfAxiom, OWLSubObjectPropertyOfAxiom, OWLThing, \ +from ontolearn.owlapy.model import OWLObjectUnionOf, OWLSubDataPropertyOfAxiom, OWLSubObjectPropertyOfAxiom, OWLThing, \ BooleanOWLDatatype, DoubleOWLDatatype, IntegerOWLDatatype, OWLClass, OWLDataAllValuesFrom, \ OWLDataHasValue, OWLDataProperty, OWLDataSomeValuesFrom, OWLLiteral, OWLNamedIndividual, \ OWLNothing, OWLObjectAllValuesFrom, OWLObjectComplementOf, OWLObjectExactCardinality, \ OWLObjectHasValue, OWLObjectIntersectionOf, OWLObjectInverseOf, OWLObjectMaxCardinality, \ OWLObjectMinCardinality, OWLObjectProperty, IRI, OWLObjectSomeValuesFrom -from owlapy.owlready2 import OWLOntologyManager_Owlready2, OWLReasoner_Owlready2 - -class ConceptGeneratorTest(unittest.TestCase): +class KnowledgeBaseTest(unittest.TestCase): def setUp(self): self.namespace = "http://dl-learner.org/mutagenesis#" - self.mgr = OWLOntologyManager_Owlready2() - self.onto = self.mgr.load_ontology(IRI.create("file://KGs/Mutagenesis/mutagenesis.owl")) - - base_reasoner = OWLReasoner_Owlready2(self.onto) - reasoner = OWLReasoner_FastInstanceChecker(self.onto, base_reasoner=base_reasoner, negation_default=True) - self.generator = ConceptGenerator(reasoner) - + self.kb = KnowledgeBase(path="KGs/Mutagenesis/mutagenesis.owl") + self.onto = self.kb.ontology() + self.mgr = self.onto.get_owl_ontology_manager() + self.generator = ConceptGenerator() # Classes self.atom = OWLClass(IRI.create(self.namespace, 'Atom')) self.bond = OWLClass(IRI.create(self.namespace, 'Bond')) @@ -63,115 +59,115 @@ def setUp(self): def test_classes_retrieval(self): # get concepts - self.assertEqual(86, len(list(self.generator.get_concepts()))) + self.assertEqual(86, len(list(self.kb.get_concepts()))) # direct sub concepts - classes = frozenset(self.generator.get_direct_sub_concepts(OWLThing)) + classes = frozenset(self.kb.get_direct_sub_concepts(OWLThing)) true_classes = {self.atom, self.bond, self.compound, self.ring_structure} self.assertEqual(true_classes, classes) # all sub concepts - classes = frozenset(self.generator.get_all_sub_concepts(self.bond)) + classes = frozenset(self.kb.get_all_sub_concepts(self.bond)) true_classes = {self.bond1, self.bond2, self.bond3, self.bond4, self.bond5, self.bond7} self.assertEqual(true_classes, classes) # all leaf concepts - classes = frozenset(self.generator.get_leaf_concepts(self.bond)) + classes = frozenset(self.kb.get_leaf_concepts(self.bond)) self.assertEqual(true_classes, classes) # get direct parents - classes = frozenset(self.generator.get_direct_parents(self.bond1)) + classes = frozenset(self.kb.get_direct_parents(self.bond1)) true_classes = {self.bond} self.assertEqual(true_classes, classes) # types of an individual - classes = frozenset(self.generator.get_types(self.bond5225, direct=True)) + classes = frozenset(self.kb.get_types(self.bond5225, direct=True)) true_classes = {self.bond1} self.assertEqual(true_classes, classes) - classes = frozenset(self.generator.get_types(self.bond5225)) + classes = frozenset(self.kb.get_types(self.bond5225)) true_classes = {self.bond, self.bond1, OWLThing} self.assertEqual(true_classes, classes) def test_property_retrieval(self): - self.assertEqual(self.object_properties, frozenset(self.generator.get_object_properties())) - self.assertEqual(self.data_properties, frozenset(self.generator.get_data_properties())) - self.assertEqual(self.boolean_data_properties, frozenset(self.generator.get_boolean_data_properties())) - self.assertEqual(self.numeric_data_properties, frozenset(self.generator.get_numeric_data_properties())) - self.assertFalse(frozenset(self.generator.get_time_data_properties())) + self.assertEqual(self.object_properties, frozenset(self.kb.get_object_properties())) + self.assertEqual(self.data_properties, frozenset(self.kb.get_data_properties())) + self.assertEqual(self.boolean_data_properties, frozenset(self.kb.get_boolean_data_properties())) + self.assertEqual(self.numeric_data_properties, frozenset(self.kb.get_numeric_data_properties())) + self.assertFalse(frozenset(self.kb.get_time_data_properties())) # most general data properties self.assertEqual(self.boolean_data_properties, - frozenset(self.generator.most_general_boolean_data_properties(domain=self.compound))) - self.assertFalse(frozenset(self.generator.most_general_boolean_data_properties(domain=self.bond))) + frozenset(self.kb.most_general_boolean_data_properties(domain=self.compound))) + self.assertFalse(frozenset(self.kb.most_general_boolean_data_properties(domain=self.bond))) self.assertEqual({self.charge}, - frozenset(self.generator.most_general_numeric_data_properties(domain=self.atom))) - self.assertFalse(frozenset(self.generator.most_general_numeric_data_properties(domain=self.bond))) + frozenset(self.kb.most_general_numeric_data_properties(domain=self.atom))) + self.assertFalse(frozenset(self.kb.most_general_numeric_data_properties(domain=self.bond))) self.data_properties.remove(self.charge) self.assertEqual(self.data_properties, - frozenset(self.generator.most_general_data_properties(domain=self.compound))) - self.assertFalse(frozenset(self.generator.most_general_data_properties(domain=self.bond))) + frozenset(self.kb.most_general_data_properties(domain=self.compound))) + self.assertFalse(frozenset(self.kb.most_general_data_properties(domain=self.bond))) - self.assertFalse(frozenset(self.generator.most_general_time_data_properties(domain=OWLThing))) + self.assertFalse(frozenset(self.kb.most_general_time_data_properties(domain=OWLThing))) # object property values of an individual - inds = frozenset(self.generator.get_object_property_values(self.bond5225, self.in_bond, direct=True)) + inds = frozenset(self.kb.get_object_property_values(self.bond5225, self.in_bond, direct=True)) true_inds = {self.d91_32, self.d91_17} self.assertEqual(true_inds, inds) # indirect object property values of an individual super_in_bond = OWLObjectProperty(IRI.create(self.namespace, 'super_inBond')) self.mgr.add_axiom(self.onto, OWLSubObjectPropertyOfAxiom(self.in_bond, super_in_bond)) - inds = frozenset(self.generator.get_object_property_values(self.bond5225, super_in_bond, direct=False)) + inds = frozenset(self.kb.get_object_property_values(self.bond5225, super_in_bond, direct=False)) true_inds = {self.d91_32, self.d91_17} self.assertEqual(true_inds, inds) - inds = frozenset(self.generator.get_object_property_values(self.bond5225, super_in_bond, direct=True)) + inds = frozenset(self.kb.get_object_property_values(self.bond5225, super_in_bond, direct=True)) self.assertEqual(frozenset(), inds) self.mgr.remove_axiom(self.onto, OWLSubObjectPropertyOfAxiom(self.in_bond, super_in_bond)) # data property values of an individual - values = frozenset(self.generator.get_data_property_values(self.d91_32, self.charge, direct=True)) + values = frozenset(self.kb.get_data_property_values(self.d91_32, self.charge, direct=True)) true_values = {OWLLiteral(0.146)} self.assertEqual(true_values, values) # indirect data property values of an individual super_charge = OWLDataProperty(IRI.create(self.namespace, 'super_charge')) self.mgr.add_axiom(self.onto, OWLSubDataPropertyOfAxiom(self.charge, super_charge)) - values = frozenset(self.generator.get_data_property_values(self.d91_32, super_charge, direct=False)) + values = frozenset(self.kb.get_data_property_values(self.d91_32, super_charge, direct=False)) true_values = {OWLLiteral(0.146)} self.assertEqual(true_values, values) - values = frozenset(self.generator.get_data_property_values(self.d91_32, super_charge, direct=True)) + values = frozenset(self.kb.get_data_property_values(self.d91_32, super_charge, direct=True)) self.assertEqual(frozenset(), values) self.mgr.remove_axiom(self.onto, OWLSubDataPropertyOfAxiom(self.charge, super_charge)) # object properties of an individual - properties = frozenset(self.generator.get_object_properties_for_ind(self.bond5225, direct=True)) + properties = frozenset(self.kb.get_object_properties_for_ind(self.bond5225, direct=True)) true_properties = {self.in_bond} self.assertEqual(true_properties, properties) # indirect object properties of an individual self.mgr.add_axiom(self.onto, OWLSubObjectPropertyOfAxiom(self.in_bond, self.has_bond)) - properties = frozenset(self.generator.get_object_properties_for_ind(self.bond5225, direct=False)) + properties = frozenset(self.kb.get_object_properties_for_ind(self.bond5225, direct=False)) true_properties = {self.in_bond, self.has_bond} self.assertEqual(true_properties, properties) - properties = frozenset(self.generator.get_object_properties_for_ind(self.bond5225, direct=True)) + properties = frozenset(self.kb.get_object_properties_for_ind(self.bond5225, direct=True)) true_properties = {self.in_bond} self.assertEqual(true_properties, properties) self.mgr.remove_axiom(self.onto, OWLSubObjectPropertyOfAxiom(self.in_bond, self.has_bond)) # data properties of an individual - properties = frozenset(self.generator.get_data_properties_for_ind(self.d91_32, direct=True)) + properties = frozenset(self.kb.get_data_properties_for_ind(self.d91_32, direct=True)) true_properties = {self.charge} self.assertEqual(true_properties, properties) # indirect data properties of an individual self.mgr.add_axiom(self.onto, OWLSubDataPropertyOfAxiom(self.charge, self.act)) - properties = frozenset(self.generator.get_data_properties_for_ind(self.d91_32, direct=False)) + properties = frozenset(self.kb.get_data_properties_for_ind(self.d91_32, direct=False)) true_properties = {self.charge, self.act} self.assertEqual(true_properties, properties) - properties = frozenset(self.generator.get_data_properties_for_ind(self.d91_32, direct=True)) + properties = frozenset(self.kb.get_data_properties_for_ind(self.d91_32, direct=True)) true_properties = {self.charge} self.assertEqual(true_properties, properties) self.mgr.remove_axiom(self.onto, OWLSubDataPropertyOfAxiom(self.charge, self.act)) @@ -180,76 +176,76 @@ def test_ignore(self): concepts_to_ignore = {self.bond1, self.compound} object_properties_to_ignore = {self.in_bond, self.has_structure} data_properties_to_ignore = {self.act, self.has_fife_examples} - self.generator._class_hierarchy = self.generator._class_hierarchy.restrict_and_copy(remove=concepts_to_ignore) - self.generator._object_property_hierarchy = ( - self.generator._object_property_hierarchy.restrict_and_copy(remove=object_properties_to_ignore) + self.kb._class_hierarchy = self.kb._class_hierarchy.restrict_and_copy(remove=concepts_to_ignore) + self.kb._object_property_hierarchy = ( + self.kb._object_property_hierarchy.restrict_and_copy(remove=object_properties_to_ignore) ) - self.generator._data_property_hierarchy = ( - self.generator._data_property_hierarchy.restrict_and_copy(remove=data_properties_to_ignore) + self.kb._data_property_hierarchy = ( + self.kb._data_property_hierarchy.restrict_and_copy(remove=data_properties_to_ignore) ) # get concepts - concepts = frozenset(self.generator.get_concepts()) + concepts = frozenset(self.kb.get_concepts()) self.assertEqual(84, len(concepts)) self.assertTrue(self.bond1 not in concepts) self.assertTrue(self.compound not in concepts) # direct sub concepts - classes = frozenset(self.generator.get_direct_sub_concepts(OWLThing)) + classes = frozenset(self.kb.get_direct_sub_concepts(OWLThing)) true_classes = {self.atom, self.bond, self.ring_structure} self.assertEqual(true_classes, classes) # all sub concepts - classes = frozenset(self.generator.get_all_sub_concepts(self.bond)) + classes = frozenset(self.kb.get_all_sub_concepts(self.bond)) true_classes = {self.bond2, self.bond3, self.bond4, self.bond5, self.bond7} self.assertEqual(true_classes, classes) # all leaf concepts - classes = frozenset(self.generator.get_leaf_concepts(self.bond)) + classes = frozenset(self.kb.get_leaf_concepts(self.bond)) self.assertEqual(true_classes, classes) # types of an individual - classes = frozenset(self.generator.get_types(self.bond5225, direct=True)) + classes = frozenset(self.kb.get_types(self.bond5225, direct=True)) self.assertFalse(classes) - classes = frozenset(self.generator.get_types(self.bond5225)) + classes = frozenset(self.kb.get_types(self.bond5225)) true_classes = {self.bond, OWLThing} self.assertEqual(true_classes, classes) # properties object_properties = {self.has_bond, self.has_atom, self.in_structure} - self.assertEqual(object_properties, frozenset(self.generator.get_object_properties())) + self.assertEqual(object_properties, frozenset(self.kb.get_object_properties())) data_properties = {self.charge, self.logp, self.lumo, self.has_three} - self.assertEqual(data_properties, frozenset(self.generator.get_data_properties())) + self.assertEqual(data_properties, frozenset(self.kb.get_data_properties())) boolean_data_properties = {self.has_three} - self.assertEqual(boolean_data_properties, frozenset(self.generator.get_boolean_data_properties())) + self.assertEqual(boolean_data_properties, frozenset(self.kb.get_boolean_data_properties())) numeric_data_properties = {self.charge, self.logp, self.lumo} - self.assertEqual(numeric_data_properties, frozenset(self.generator.get_numeric_data_properties())) + self.assertEqual(numeric_data_properties, frozenset(self.kb.get_numeric_data_properties())) true_res = frozenset(map(OWLObjectSomeValuesFrom, object_properties, repeat(OWLThing))) - res = frozenset(self.generator.most_general_existential_restrictions(domain=OWLThing)) + res = frozenset(self.kb.most_general_existential_restrictions(domain=OWLThing)) self.assertEqual(true_res, res) def test_domain_range_retrieval(self): # object properties - self.assertEqual(self.compound, self.generator.get_object_property_domains(self.has_atom)) - self.assertEqual(self.bond, self.generator.get_object_property_domains(self.in_bond)) + self.assertEqual(self.compound, self.kb.get_object_property_domains(self.has_atom)) + self.assertEqual(self.bond, self.kb.get_object_property_domains(self.in_bond)) - self.assertEqual(self.ring_structure, self.generator.get_object_property_ranges(self.in_structure)) - self.assertEqual(OWLThing, self.generator.get_object_property_domains(self.in_structure)) - self.assertEqual(self.atom, self.generator.get_object_property_ranges(self.in_bond)) + self.assertEqual(self.ring_structure, self.kb.get_object_property_ranges(self.in_structure)) + self.assertEqual(OWLThing, self.kb.get_object_property_domains(self.in_structure)) + self.assertEqual(self.atom, self.kb.get_object_property_ranges(self.in_bond)) # data properties - self.assertEqual(self.atom, self.generator.get_data_property_domains(self.charge)) - self.assertEqual(self.compound, self.generator.get_data_property_domains(self.act)) + self.assertEqual(self.atom, self.kb.get_data_property_domains(self.charge)) + self.assertEqual(self.compound, self.kb.get_data_property_domains(self.act)) - self.assertEqual({DoubleOWLDatatype}, self.generator.get_data_property_ranges(self.charge)) - self.assertEqual({BooleanOWLDatatype}, self.generator.get_data_property_ranges(self.has_fife_examples)) + self.assertEqual({DoubleOWLDatatype}, self.kb.get_data_property_ranges(self.charge)) + self.assertEqual({BooleanOWLDatatype}, self.kb.get_data_property_ranges(self.has_fife_examples)) - def test_concept_building(self): + def test_concept_generation(self): # negation from iterables true_ces = {OWLObjectComplementOf(self.bond), self.atom} ces = frozenset(self.generator.negation_from_iterables([self.bond, OWLObjectComplementOf(self.atom)])) @@ -276,22 +272,22 @@ def test_concept_building(self): # most general existential/universal restrictions true_res = frozenset(map(OWLObjectSomeValuesFrom, self.object_properties, repeat(OWLThing))) - res = frozenset(self.generator.most_general_existential_restrictions(domain=OWLThing)) + res = frozenset(self.kb.most_general_existential_restrictions(domain=OWLThing)) self.assertEqual(true_res, res) true_res = {OWLObjectAllValuesFrom(filler=OWLThing, property=self.in_bond), OWLObjectAllValuesFrom(filler=OWLThing, property=self.in_structure)} - res = frozenset(self.generator.most_general_universal_restrictions(domain=self.bond)) + res = frozenset(self.kb.most_general_universal_restrictions(domain=self.bond)) self.assertEqual(true_res, res) true_res = {OWLObjectSomeValuesFrom(filler=OWLThing, property=self.has_bond.get_inverse_property()), OWLObjectSomeValuesFrom(filler=OWLThing, property=self.has_structure.get_inverse_property())} - res = frozenset(self.generator.most_general_existential_restrictions_inverse(domain=self.bond)) + res = frozenset(self.kb.most_general_existential_restrictions_inverse(domain=self.bond)) self.assertEqual(true_res, res) true_res = frozenset(map(OWLObjectAllValuesFrom, map(OWLObjectInverseOf, self.object_properties), repeat(OWLThing))) - res = frozenset(self.generator.most_general_universal_restrictions_inverse(domain=OWLThing)) + res = frozenset(self.kb.most_general_universal_restrictions_inverse(domain=OWLThing)) self.assertEqual(true_res, res) # general functions for concept building diff --git a/tests/test_model_adapter.py b/tests/test_model_adapter.py index 537b6039..aa75c830 100644 --- a/tests/test_model_adapter.py +++ b/tests/test_model_adapter.py @@ -8,9 +8,9 @@ from ontolearn.metrics import Accuracy from ontolearn.model_adapter import ModelAdapter from ontolearn.refinement_operators import ModifiedCELOERefinement -from owlapy.model import IRI, OWLNamedIndividual -from owlapy.owlready2 import OWLOntology_Owlready2, BaseReasoner_Owlready2 -from owlapy.owlready2.complex_ce_instances import OWLReasoner_Owlready2_ComplexCEInstances +from ontolearn.owlapy.model import IRI, OWLNamedIndividual +from ontolearn.owlapy.owlready2 import OWLOntology_Owlready2, BaseReasoner_Owlready2 +from ontolearn.owlapy.owlready2.complex_ce_instances import OWLReasoner_Owlready2_ComplexCEInstances class ModelAdapterTest(unittest.TestCase): diff --git a/tests/test_owlapy.py b/tests/test_owlapy.py index f24507ce..ad9a8dfd 100644 --- a/tests/test_owlapy.py +++ b/tests/test_owlapy.py @@ -1,8 +1,8 @@ import unittest -from owlapy import namespaces -from owlapy.namespaces import Namespaces -from owlapy.model import OWLClass, OWLObjectUnionOf, IRI +from ontolearn.owlapy import namespaces +from ontolearn.owlapy.namespaces import Namespaces +from ontolearn.owlapy.model import OWLClass, OWLObjectUnionOf, IRI base = Namespaces("ex", "http://example.org/") diff --git a/tests/test_owlapy_cnf_dnf.py b/tests/test_owlapy_cnf_dnf.py index ffbfd525..ddd06bb7 100644 --- a/tests/test_owlapy_cnf_dnf.py +++ b/tests/test_owlapy_cnf_dnf.py @@ -1,10 +1,10 @@ import unittest -from owlapy.model import OWLObjectProperty, OWLObjectSomeValuesFrom, OWLObjectUnionOf, \ +from ontolearn.owlapy.model import OWLObjectProperty, OWLObjectSomeValuesFrom, OWLObjectUnionOf, \ OWLClass, IRI, OWLDataProperty, OWLDataSomeValuesFrom, OWLNamedIndividual, OWLObjectComplementOf, \ OWLObjectIntersectionOf, OWLObjectMinCardinality, OWLObjectOneOf -from owlapy.model.providers import OWLDatatypeMinExclusiveRestriction -from owlapy.util import TopLevelCNF, TopLevelDNF +from ontolearn.owlapy.model.providers import OWLDatatypeMinExclusiveRestriction +from ontolearn.owlapy.util import TopLevelCNF, TopLevelDNF class TopLevelNFTest(unittest.TestCase): diff --git a/tests/test_owlapy_fastinstancechecker.py b/tests/test_owlapy_fastinstancechecker.py index 606e8956..334e1ff3 100644 --- a/tests/test_owlapy_fastinstancechecker.py +++ b/tests/test_owlapy_fastinstancechecker.py @@ -4,8 +4,8 @@ from owlready2.prop import DataProperty from pandas import Timedelta -from owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker -from owlapy.model import OWLObjectInverseOf, OWLObjectOneOf, OWLObjectProperty, OWLNamedIndividual, \ +from ontolearn.owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker +from ontolearn.owlapy.model import OWLObjectInverseOf, OWLObjectOneOf, OWLObjectProperty, OWLNamedIndividual, \ OWLObjectSomeValuesFrom, OWLThing, OWLObjectComplementOf, IRI, OWLObjectAllValuesFrom, OWLNothing, \ OWLObjectHasValue, DoubleOWLDatatype, OWLClass, OWLDataAllValuesFrom, OWLDataComplementOf, \ OWLDataHasValue, OWLDataIntersectionOf, OWLDataOneOf, OWLDataProperty, OWLDataSomeValuesFrom, \ @@ -13,9 +13,9 @@ OWLObjectIntersectionOf, OWLSubDataPropertyOfAxiom, OWLSubObjectPropertyOfAxiom, OWLInverseObjectPropertiesAxiom, \ DurationOWLDatatype -from owlapy.model.providers import OWLDatatypeMinExclusiveRestriction, OWLDatatypeMinMaxInclusiveRestriction, \ +from ontolearn.owlapy.model.providers import OWLDatatypeMinExclusiveRestriction, OWLDatatypeMinMaxInclusiveRestriction, \ OWLDatatypeMinMaxExclusiveRestriction, OWLDatatypeMaxExclusiveRestriction, OWLDatatypeMaxInclusiveRestriction -from owlapy.owlready2 import OWLOntologyManager_Owlready2, OWLReasoner_Owlready2 +from ontolearn.owlapy.owlready2 import OWLOntologyManager_Owlready2, OWLReasoner_Owlready2 class Owlapy_FastInstanceChecker_Test(unittest.TestCase): diff --git a/tests/test_owlapy_nnf.py b/tests/test_owlapy_nnf.py index 4d772dc4..35589746 100644 --- a/tests/test_owlapy_nnf.py +++ b/tests/test_owlapy_nnf.py @@ -24,14 +24,14 @@ # import unittest -from owlapy.model import OWLObjectProperty, OWLNamedIndividual, OWLObjectComplementOf, \ +from ontolearn.owlapy.model import OWLObjectProperty, OWLNamedIndividual, OWLObjectComplementOf, \ OWLObjectAllValuesFrom, OWLObjectSomeValuesFrom, OWLObjectIntersectionOf, OWLObjectUnionOf, \ OWLObjectMinCardinality, OWLObjectMaxCardinality, OWLObjectHasValue, OWLObjectOneOf, OWLClassExpression, IRI, \ BooleanOWLDatatype, DoubleOWLDatatype, IntegerOWLDatatype, OWLClass, OWLDataAllValuesFrom, OWLDataComplementOf, \ OWLDataIntersectionOf, OWLDataProperty, OWLDataSomeValuesFrom, OWLDataUnionOf, \ OWLDataHasValue, OWLDataMaxCardinality, OWLDataMinCardinality, OWLDataOneOf, OWLLiteral -from owlapy.model.providers import OWLDatatypeMinMaxExclusiveRestriction -from owlapy.util import NNF +from ontolearn.owlapy.model.providers import OWLDatatypeMinMaxExclusiveRestriction +from ontolearn.owlapy.util import NNF def iri(suffix): diff --git a/tests/test_owlapy_owl2sparql_converter.py b/tests/test_owlapy_owl2sparql_converter.py index 7792e1a6..e606dade 100644 --- a/tests/test_owlapy_owl2sparql_converter.py +++ b/tests/test_owlapy_owl2sparql_converter.py @@ -1,14 +1,13 @@ import unittest -from typing import Iterable import rdflib.plugins.sparql.sparql -from owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker -from owlapy.model import OWLObjectProperty, IRI, OWLObjectSomeValuesFrom, OWLObjectMaxCardinality, OWLThing, \ - OWLObjectMinCardinality, OWLObjectUnionOf, OWLObjectIntersectionOf, OWLNamedIndividual -from owlapy.owlready2 import OWLOntologyManager_Owlready2, OWLReasoner_Owlready2 -from owlapy.parser import DLSyntaxParser -from owlapy.owl2sparql.converter import Owl2SparqlConverter +from ontolearn.owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker +from ontolearn.owlapy.model import OWLObjectProperty, IRI, OWLObjectSomeValuesFrom, OWLObjectMaxCardinality, OWLThing, \ + OWLObjectMinCardinality, OWLObjectIntersectionOf +from ontolearn.owlapy.owlready2 import OWLOntologyManager_Owlready2, OWLReasoner_Owlready2 +from ontolearn.owlapy.parser import DLSyntaxParser +from ontolearn.owlapy.owl2sparql.converter import Owl2SparqlConverter from rdflib import Graph PATH_FAMILY = 'KGs/Family/family-benchmark_rich_background.owl' diff --git a/tests/test_owlapy_owlready2.py b/tests/test_owlapy_owlready2.py index a736e45c..6ffa9a32 100644 --- a/tests/test_owlapy_owlready2.py +++ b/tests/test_owlapy_owlready2.py @@ -2,13 +2,12 @@ import unittest from pandas import Timedelta -from owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker -from owlapy.model.providers import OWLDatatypeMaxInclusiveRestriction, OWLDatatypeMinInclusiveRestriction, \ +from ontolearn.owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker +from ontolearn.owlapy.model.providers import OWLDatatypeMaxInclusiveRestriction, OWLDatatypeMinInclusiveRestriction, \ OWLDatatypeMinMaxExclusiveRestriction, OWLDatatypeMinMaxInclusiveRestriction import owlready2 -import owlapy.owlready2.utils -from owlapy.model import OWLObjectInverseOf, OWLObjectPropertyRangeAxiom, OWLSameIndividualAxiom, OWLClass, \ +from ontolearn.owlapy.model import OWLObjectInverseOf, OWLObjectPropertyRangeAxiom, OWLSameIndividualAxiom, OWLClass, \ OWLObjectIntersectionOf, OWLObjectSomeValuesFrom, OWLObjectComplementOf, IRI, OWLDataAllValuesFrom, \ OWLDataComplementOf, OWLDataHasValue, OWLDataIntersectionOf, OWLDataProperty, OWLDataSomeValuesFrom, \ OWLDataUnionOf, OWLLiteral, BooleanOWLDatatype, DoubleOWLDatatype, IntegerOWLDatatype, OWLDataOneOf, \ @@ -21,8 +20,9 @@ OWLDataPropertyAssertionAxiom, OWLObjectProperty, OWLDataPropertyDomainAxiom, OWLDataPropertyRangeAxiom, \ OWLObjectPropertyAssertionAxiom, OWLObjectPropertyDomainAxiom, OWLInverseObjectPropertiesAxiom, OWLSubClassOfAxiom -from owlapy.owlready2 import OWLOntologyManager_Owlready2, OWLReasoner_Owlready2 -from owlapy.owlready2.complex_ce_instances import OWLReasoner_Owlready2_ComplexCEInstances +from ontolearn.owlapy.owlready2 import OWLOntologyManager_Owlready2, OWLReasoner_Owlready2 +from ontolearn.owlapy.owlready2.complex_ce_instances import OWLReasoner_Owlready2_ComplexCEInstances +from ontolearn.owlapy.owlready2.utils import ToOwlready2, FromOwlready2 class Owlapy_Owlready2_Test(unittest.TestCase): @@ -583,7 +583,7 @@ def test_mapping(self): female = OWLClass(IRI.create(ns, 'female')) has_child = OWLObjectProperty(IRI(ns, 'hasChild')) - to_owlready = owlapy.owlready2.utils.ToOwlready2(world=onto._world) + to_owlready = ToOwlready2(world=onto._world) ce = male owlready_ce = onto._onto.male @@ -638,7 +638,7 @@ def test_mapping_data_properties(self): act = OWLDataProperty(IRI(ns, 'act')) charge = OWLDataProperty(IRI(ns, 'charge')) - to_owlready = owlapy.owlready2.utils.ToOwlready2(world=onto._world) + to_owlready = ToOwlready2(world=onto._world) # owlready2 defines no equal or hash method for ConstrainedDatatype, just using the __dict__ attribute # should be sufficient for the purpose of these tests @@ -696,7 +696,7 @@ def test_mapping_rev(self): female = onto._onto.female has_child = onto._onto.hasChild - from_owlready = owlapy.owlready2.utils.FromOwlready2() + from_owlready = FromOwlready2() ce = male | female owl_ce = OWLObjectUnionOf((OWLClass(IRI.create(ns, 'male')), OWLClass(IRI.create(ns, 'female')))) @@ -747,7 +747,7 @@ def test_mapping_rev_data_properties(self): act = onto._onto.act charge = onto._onto.charge - from_owlready = owlapy.owlready2.utils.FromOwlready2() + from_owlready = FromOwlready2() ce = act.some(float) owl_ce = OWLDataSomeValuesFrom(OWLDataProperty(IRI(ns, 'act')), DoubleOWLDatatype) diff --git a/tests/test_owlapy_parser.py b/tests/test_owlapy_parser.py index 4dc88272..ca729e91 100644 --- a/tests/test_owlapy_parser.py +++ b/tests/test_owlapy_parser.py @@ -2,7 +2,7 @@ from datetime import date, datetime, timedelta, timezone from pandas import Timedelta -from owlapy.model import OWLObjectInverseOf, OWLObjectMinCardinality, OWLObjectSomeValuesFrom, OWLObjectUnionOf, \ +from ontolearn.owlapy.model import OWLObjectInverseOf, OWLObjectMinCardinality, OWLObjectSomeValuesFrom, OWLObjectUnionOf, \ DoubleOWLDatatype, IntegerOWLDatatype, OWLClass, IRI, OWLDataAllValuesFrom, OWLDataIntersectionOf, \ OWLDataOneOf, OWLDataProperty, OWLDataSomeValuesFrom, OWLDatatypeRestriction, OWLFacetRestriction, \ OWLLiteral, OWLNamedIndividual, OWLObjectAllValuesFrom, OWLObjectComplementOf, OWLObjectExactCardinality, \ @@ -10,10 +10,10 @@ OWLObjectProperty, OWLDataComplementOf, OWLDataExactCardinality, OWLDataMaxCardinality, OWLDataUnionOf, \ OWLDataMinCardinality, OWLDataHasValue, OWLThing, OWLNothing -from owlapy.model.providers import OWLDatatypeMinExclusiveRestriction, OWLDatatypeMinMaxExclusiveRestriction, \ +from ontolearn.owlapy.model.providers import OWLDatatypeMinExclusiveRestriction, OWLDatatypeMinMaxExclusiveRestriction, \ OWLDatatypeMaxExclusiveRestriction -from owlapy.parser import DLSyntaxParser, ManchesterOWLSyntaxParser -from owlapy.vocab import OWLFacet +from ontolearn.owlapy.parser import DLSyntaxParser, ManchesterOWLSyntaxParser +from ontolearn.owlapy.vocab import OWLFacet class ManchesterOWLSyntaxParserTest(unittest.TestCase): diff --git a/tests/test_owlapy_render.py b/tests/test_owlapy_render.py index 5ecec7fb..27023b43 100644 --- a/tests/test_owlapy_render.py +++ b/tests/test_owlapy_render.py @@ -1,13 +1,13 @@ import unittest -from owlapy.model import OWLDataMinCardinality, OWLObjectIntersectionOf, OWLObjectSomeValuesFrom, \ +from ontolearn.owlapy.model import OWLDataMinCardinality, OWLObjectIntersectionOf, OWLObjectSomeValuesFrom, \ OWLThing, OWLObjectComplementOf, OWLObjectUnionOf, OWLNamedIndividual, OWLObjectOneOf, OWLObjectHasValue, \ OWLObjectMinCardinality, IRI, OWLDataProperty, DoubleOWLDatatype, OWLClass, OWLDataComplementOf, \ OWLDataIntersectionOf, IntegerOWLDatatype, OWLDataExactCardinality, OWLDataHasValue, OWLDataAllValuesFrom, \ OWLDataOneOf, OWLDataSomeValuesFrom, OWLDataUnionOf, OWLLiteral, OWLObjectProperty, BooleanOWLDatatype, \ OWLDataMaxCardinality -from owlapy.model.providers import OWLDatatypeMinMaxInclusiveRestriction -from owlapy.render import DLSyntaxObjectRenderer, ManchesterOWLSyntaxOWLObjectRenderer +from ontolearn.owlapy.model.providers import OWLDatatypeMinMaxInclusiveRestriction +from ontolearn.owlapy.render import DLSyntaxObjectRenderer, ManchesterOWLSyntaxOWLObjectRenderer class Owlapy_DLRenderer_Test(unittest.TestCase): diff --git a/tests/test_refinement_operators.py b/tests/test_refinement_operators.py index 2cd16903..8403693d 100644 --- a/tests/test_refinement_operators.py +++ b/tests/test_refinement_operators.py @@ -1,20 +1,20 @@ """ Test for refinement_operators.py""" from functools import partial from itertools import repeat -from pytest import mark import unittest import json +from ontolearn.concept_generator import ConceptGenerator from ontolearn.knowledge_base import KnowledgeBase from ontolearn.core.owl.utils import ConceptOperandSorter from ontolearn.utils import setup_logging -from owlapy.model.providers import OWLDatatypeMaxInclusiveRestriction, OWLDatatypeMinInclusiveRestriction -from owlapy.render import DLSyntaxObjectRenderer -from owlapy.model import OWLObjectMinCardinality, OWLObjectProperty, OWLObjectSomeValuesFrom, OWLObjectUnionOf, \ +from ontolearn.owlapy.model.providers import OWLDatatypeMaxInclusiveRestriction, OWLDatatypeMinInclusiveRestriction +from ontolearn.owlapy.render import DLSyntaxObjectRenderer +from ontolearn.owlapy.model import OWLObjectMinCardinality, OWLObjectProperty, OWLObjectSomeValuesFrom, OWLObjectUnionOf, \ OWLClass, IRI, OWLDataHasValue, OWLDataProperty, OWLDataSomeValuesFrom, OWLLiteral, OWLObjectAllValuesFrom, \ OWLObjectCardinalityRestriction, OWLObjectComplementOf, OWLObjectIntersectionOf, OWLObjectMaxCardinality -from ontolearn.refinement_operators import CustomRefinementOperator, ModifiedCELOERefinement, LengthBasedRefinement, \ +from ontolearn.refinement_operators import ModifiedCELOERefinement, LengthBasedRefinement, \ ExpressRefinement @@ -39,7 +39,7 @@ def setUp(self): self.bond5 = OWLClass(IRI.create(namespace_, 'Bond-5')) self.bond7 = OWLClass(IRI.create(namespace_, 'Bond-7')) self.ball3 = OWLClass(IRI.create(namespace_, 'Ball3')) - + self.generator = ConceptGenerator() self.all_bond_classes = {self.bond1, self.bond2, self.bond3, self.bond4, self.bond5, self.bond7} # Object Properties @@ -68,8 +68,8 @@ def test_atomic_refinements_classes(self): OWLObjectComplementOf(self.ball3)} rho = ModifiedCELOERefinement(self.kb, use_negation=True) - thing_refs = set(rho.refine(self.kb.thing, max_length=2, current_domain=self.kb.thing)) - bond_refs = set(rho.refine(self.bond, max_length=2, current_domain=self.kb.thing)) + thing_refs = set(rho.refine(self.generator.thing, max_length=2, current_domain=self.generator.thing)) + bond_refs = set(rho.refine(self.bond, max_length=2, current_domain=self.generator.thing)) self.assertLessEqual(thing_true_refs, thing_refs) self.assertLessEqual(bond_true_refs, bond_refs) @@ -77,30 +77,30 @@ def test_atomic_refinements_classes(self): self.assertFalse(bond_refs & bond_false_refs) def test_atomic_refinements_existential_universal(self): - thing_true_refs = {OWLObjectSomeValuesFrom(self.in_bond, self.kb.thing), - OWLObjectAllValuesFrom(self.has_bond, self.kb.thing), - OWLObjectSomeValuesFrom(self.has_atom.get_inverse_property(), self.kb.thing), - OWLObjectAllValuesFrom(self.in_structure.get_inverse_property(), self.kb.thing)} - bond_true_refs = {OWLObjectSomeValuesFrom(self.in_bond, self.kb.thing), - OWLObjectAllValuesFrom(self.in_bond, self.kb.thing), - OWLObjectSomeValuesFrom(self.has_bond.get_inverse_property(), self.kb.thing), - OWLObjectAllValuesFrom(self.has_bond.get_inverse_property(), self.kb.thing)} + thing_true_refs = {OWLObjectSomeValuesFrom(self.in_bond, self.generator.thing), + OWLObjectAllValuesFrom(self.has_bond, self.generator.thing), + OWLObjectSomeValuesFrom(self.has_atom.get_inverse_property(), self.generator.thing), + OWLObjectAllValuesFrom(self.in_structure.get_inverse_property(), self.generator.thing)} + bond_true_refs = {OWLObjectSomeValuesFrom(self.in_bond, self.generator.thing), + OWLObjectAllValuesFrom(self.in_bond, self.generator.thing), + OWLObjectSomeValuesFrom(self.has_bond.get_inverse_property(), self.generator.thing), + OWLObjectAllValuesFrom(self.has_bond.get_inverse_property(), self.generator.thing)} bond_false_refs = {OWLObjectSomeValuesFrom(self.has_bond, self.bond), OWLObjectAllValuesFrom(self.has_bond, self.bond)} rho = ModifiedCELOERefinement(self.kb, use_negation=True, use_all_constructor=True, use_inverse=True) - thing_refs = set(rho.refine(self.kb.thing, max_length=3, current_domain=self.kb.thing)) - bond_refs = set(rho.refine(self.bond, max_length=3, current_domain=self.kb.thing)) + thing_refs = set(rho.refine(self.generator.thing, max_length=3, current_domain=self.generator.thing)) + bond_refs = set(rho.refine(self.bond, max_length=3, current_domain=self.generator.thing)) self.assertLessEqual(thing_true_refs, thing_refs) self.assertLessEqual(bond_true_refs, bond_refs) self.assertFalse(bond_refs & bond_false_refs) # max_length = 2 so property refinements should not be generated - for i in rho.refine(self.kb.thing, max_length=2, current_domain=self.kb.thing): + for i in rho.refine(self.generator.thing, max_length=2, current_domain=self.generator.thing): self.assertFalse(isinstance(i, OWLObjectSomeValuesFrom)) self.assertFalse(isinstance(i, OWLObjectAllValuesFrom)) - for i in rho.refine(self.bond, max_length=2, current_domain=self.kb.thing): + for i in rho.refine(self.bond, max_length=2, current_domain=self.generator.thing): self.assertFalse(isinstance(i, OWLObjectSomeValuesFrom)) self.assertFalse(isinstance(i, OWLObjectAllValuesFrom)) @@ -113,12 +113,12 @@ def test_atomic_refinements_union_intersection(self): OWLObjectUnionOf([self.atom, self.compound])} sorter = ConceptOperandSorter() true_refs = {sorter.sort(i) for i in true_refs} - thing_refs = set(rho.refine(self.kb.thing, max_length=3, current_domain=self.kb.thing)) + thing_refs = set(rho.refine(self.generator.thing, max_length=3, current_domain=self.generator.thing)) thing_refs = {sorter.sort(i) for i in thing_refs} self.assertLessEqual(true_refs, thing_refs) # max_length = 2 so union or intersection refinements should not be generated - for i in rho.refine(self.kb.thing, max_length=2, current_domain=self.kb.thing): + for i in rho.refine(self.generator.thing, max_length=2, current_domain=self.generator.thing): self.assertFalse(isinstance(i, OWLObjectIntersectionOf)) self.assertFalse(isinstance(i, OWLObjectUnionOf)) @@ -133,7 +133,7 @@ def test_atomic_refinements_data_properties(self): OWLDataSomeValuesFrom(self.act, OWLDatatypeMaxInclusiveRestriction(9))} true_charge = {OWLDataSomeValuesFrom(self.charge, OWLDatatypeMinInclusiveRestriction(1)), OWLDataSomeValuesFrom(self.charge, OWLDatatypeMaxInclusiveRestriction(9))} - thing_refs = set(rho.refine(self.kb.thing, max_length=3, current_domain=self.kb.thing)) + thing_refs = set(rho.refine(self.generator.thing, max_length=3, current_domain=self.generator.thing)) compound_refs = set(rho.refine(self.compound, max_length=3, current_domain=self.compound)) bond_refs = set(rho.refine(self.bond, max_length=3, current_domain=self.bond)) self.assertLessEqual(true_act, thing_refs) @@ -153,33 +153,33 @@ def test_atomic_refinements_data_properties(self): self.assertFalse(true_boolean & bond_refs) # max_length = 2 so data property refinements should not be generated - for i in rho.refine(self.kb.thing, max_length=2, current_domain=self.kb.thing): + for i in rho.refine(self.generator.thing, max_length=2, current_domain=self.generator.thing): self.assertFalse(isinstance(i, OWLDataSomeValuesFrom)) self.assertFalse(isinstance(i, OWLDataHasValue)) def test_atomic_refinements_cardinality(self): rho = ModifiedCELOERefinement(self.kb, card_limit=10, use_card_restrictions=True) - thing_true_refs = {OWLObjectMaxCardinality(9, self.has_bond, self.kb.thing), - OWLObjectMaxCardinality(9, self.has_atom, self.kb.thing), - OWLObjectMaxCardinality(1, self.in_bond, self.kb.thing), - OWLObjectMaxCardinality(9, self.has_structure, self.kb.thing)} - thing_refs = set(rho.refine(self.kb.thing, max_length=4, current_domain=self.kb.thing)) - bond_refs = set(rho.refine(self.bond, max_length=4, current_domain=self.kb.thing)) + thing_true_refs = {OWLObjectMaxCardinality(9, self.has_bond, self.generator.thing), + OWLObjectMaxCardinality(9, self.has_atom, self.generator.thing), + OWLObjectMaxCardinality(1, self.in_bond, self.generator.thing), + OWLObjectMaxCardinality(9, self.has_structure, self.generator.thing)} + thing_refs = set(rho.refine(self.generator.thing, max_length=4, current_domain=self.generator.thing)) + bond_refs = set(rho.refine(self.bond, max_length=4, current_domain=self.generator.thing)) self.assertLessEqual(thing_true_refs, thing_refs) - self.assertIn(OWLObjectMaxCardinality(1, self.in_bond, self.kb.thing), bond_refs) + self.assertIn(OWLObjectMaxCardinality(1, self.in_bond, self.generator.thing), bond_refs) # max_length = 3 so cardinality refinements should not be generated - thing_refs = set(rho.refine(self.kb.thing, max_length=3, current_domain=self.kb.thing)) - bond_refs = set(rho.refine(self.bond, max_length=3, current_domain=self.kb.thing)) + thing_refs = set(rho.refine(self.generator.thing, max_length=3, current_domain=self.generator.thing)) + bond_refs = set(rho.refine(self.bond, max_length=3, current_domain=self.generator.thing)) self.assertFalse(thing_true_refs & thing_refs) - self.assertNotIn(OWLObjectMaxCardinality(1, self.in_bond, self.kb.thing), bond_refs) + self.assertNotIn(OWLObjectMaxCardinality(1, self.in_bond, self.generator.thing), bond_refs) def test_atomic_use_flags(self): rho = ModifiedCELOERefinement(self.kb, use_negation=False, use_all_constructor=False, use_numeric_datatypes=False, use_boolean_datatype=False, use_card_restrictions=False) - for i in rho.refine(self.kb.thing, max_length=4, current_domain=self.kb.thing): + for i in rho.refine(self.generator.thing, max_length=4, current_domain=self.generator.thing): self.assertFalse(isinstance(i, OWLObjectAllValuesFrom)) self.assertFalse(isinstance(i, OWLDataSomeValuesFrom)) self.assertFalse(isinstance(i, OWLDataHasValue)) @@ -188,10 +188,10 @@ def test_atomic_use_flags(self): def test_complement_of_refinements(self): rho = ModifiedCELOERefinement(self.kb, use_negation=True) - bond_refs = set(rho.refine(OWLObjectComplementOf(self.bond1), max_length=3, current_domain=self.kb.thing)) + bond_refs = set(rho.refine(OWLObjectComplementOf(self.bond1), max_length=3, current_domain=self.generator.thing)) self.assertEqual({OWLObjectComplementOf(self.bond)}, bond_refs) - ball3_refs = set(rho.refine(OWLObjectComplementOf(self.ball3), max_length=3, current_domain=self.kb.thing)) + ball3_refs = set(rho.refine(OWLObjectComplementOf(self.ball3), max_length=3, current_domain=self.generator.thing)) self.assertEqual({OWLObjectComplementOf(self.ring_structure)}, ball3_refs) def test_object_some_values_from_refinements(self): @@ -199,31 +199,31 @@ def test_object_some_values_from_refinements(self): true_refs = set(map(partial(OWLObjectSomeValuesFrom, self.in_bond), self.all_bond_classes)) true_refs.add(OWLObjectAllValuesFrom(self.in_bond, self.bond)) refs = set(rho.refine(OWLObjectSomeValuesFrom(self.in_bond, self.bond), - max_length=3, current_domain=self.kb.thing)) + max_length=3, current_domain=self.generator.thing)) self.assertEqual(refs, true_refs) refs = set(rho.refine(OWLObjectSomeValuesFrom(self.in_bond, self.bond), - max_length=4, current_domain=self.kb.thing)) + max_length=4, current_domain=self.generator.thing)) self.assertIn(OWLObjectMinCardinality(2, self.in_bond, self.bond), refs) def test_object_all_values_from_refinements(self): rho = ModifiedCELOERefinement(self.kb, use_all_constructor=True) true_refs = set(map(partial(OWLObjectAllValuesFrom, self.in_bond), self.all_bond_classes)) refs = set(rho.refine(OWLObjectAllValuesFrom(self.in_bond, self.bond), - max_length=3, current_domain=self.kb.thing)) + max_length=3, current_domain=self.generator.thing)) self.assertEqual(refs, true_refs) def test_intersection_refinements(self): rho = ModifiedCELOERefinement(self.kb) true_refs = set(map(OWLObjectIntersectionOf, zip(self.all_bond_classes, repeat(self.ball3)))) refs = set(rho.refine(OWLObjectIntersectionOf([self.bond, self.ball3]), - max_length=3, current_domain=self.kb.thing)) + max_length=3, current_domain=self.generator.thing)) self.assertEqual(refs, true_refs) def test_union_refinements(self): rho = ModifiedCELOERefinement(self.kb) true_refs = set(map(OWLObjectUnionOf, zip(self.all_bond_classes, repeat(self.ball3)))) - refs = set(rho.refine(OWLObjectUnionOf([self.bond, self.ball3]), max_length=3, current_domain=self.kb.thing)) + refs = set(rho.refine(OWLObjectUnionOf([self.bond, self.ball3]), max_length=3, current_domain=self.generator.thing)) self.assertEqual(refs, true_refs) def test_data_some_values_from_refinements(self): @@ -234,24 +234,24 @@ def test_data_some_values_from_refinements(self): # min inclusive refs = set(rho.refine(OWLDataSomeValuesFrom(self.charge, OWLDatatypeMinInclusiveRestriction(4)), - max_length=0, current_domain=self.kb.thing)) + max_length=0, current_domain=self.generator.thing)) true_refs = {OWLDataSomeValuesFrom(self.charge, OWLDatatypeMinInclusiveRestriction(5))} self.assertEqual(refs, true_refs) # test empty refs = set(rho.refine(OWLDataSomeValuesFrom(self.act, OWLDatatypeMinInclusiveRestriction(9)), - max_length=0, current_domain=self.kb.thing)) + max_length=0, current_domain=self.generator.thing)) self.assertFalse(refs) # max inclusive refs = set(rho.refine(OWLDataSomeValuesFrom(self.charge, OWLDatatypeMaxInclusiveRestriction(8)), - max_length=0, current_domain=self.kb.thing)) + max_length=0, current_domain=self.generator.thing)) true_refs = {OWLDataSomeValuesFrom(self.charge, OWLDatatypeMaxInclusiveRestriction(7))} self.assertEqual(refs, true_refs) # test empty refs = set(rho.refine(OWLDataSomeValuesFrom(self.act, OWLDatatypeMaxInclusiveRestriction(1)), - max_length=0, current_domain=self.kb.thing)) + max_length=0, current_domain=self.generator.thing)) self.assertFalse(refs) def test_cardinality_refinements(self): @@ -259,24 +259,24 @@ def test_cardinality_refinements(self): # min cardinality refs = set(rho.refine(OWLObjectMinCardinality(4, self.has_atom, self.bond1), - max_length=0, current_domain=self.kb.thing)) + max_length=0, current_domain=self.generator.thing)) true_refs = {OWLObjectMinCardinality(5, self.has_atom, self.bond1)} self.assertEqual(true_refs, refs) # test empty refs = set(rho.refine(OWLObjectMinCardinality(10, self.has_atom, self.bond1), - max_length=0, current_domain=self.kb.thing)) + max_length=0, current_domain=self.generator.thing)) self.assertFalse(refs) # max cardinality refs = set(rho.refine(OWLObjectMaxCardinality(7, self.has_atom, self.bond1), - max_length=0, current_domain=self.kb.thing)) + max_length=0, current_domain=self.generator.thing)) true_refs = {OWLObjectMaxCardinality(6, self.has_atom, self.bond1)} self.assertEqual(true_refs, refs) # test empty refs = set(rho.refine(OWLObjectMaxCardinality(0, self.has_atom, self.bond1), - max_length=0, current_domain=self.kb.thing)) + max_length=0, current_domain=self.generator.thing)) self.assertFalse(refs) def test_max_nr_fillers(self): @@ -304,7 +304,7 @@ class LengthBasedRefinementTest(unittest.TestCase): def test_length_refinement_operator(self): r = DLSyntaxObjectRenderer() rho = LengthBasedRefinement(kb) - for _ in enumerate(rho.refine(kb.thing)): + for _ in enumerate(rho.refine(kb.generator.thing)): print(r.render(_[1])) pass @@ -314,7 +314,7 @@ class ExpressRefinementTest(unittest.TestCase): def test_express_refinement_operator(self): r = DLSyntaxObjectRenderer() rho = ExpressRefinement(kb) - for _ in enumerate(rho.refine(kb.thing)): + for _ in enumerate(rho.refine(kb.generator.thing)): print(r.render(_[1])) pass diff --git a/tests/test_value_splitter.py b/tests/test_value_splitter.py index afd32b1e..fe8a3bcf 100644 --- a/tests/test_value_splitter.py +++ b/tests/test_value_splitter.py @@ -3,9 +3,9 @@ from owlready2.prop import DataProperty from ontolearn.value_splitter import BinningValueSplitter -from owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker -from owlapy.model import OWLDataProperty, OWLLiteral, IRI -from owlapy.owlready2 import OWLOntologyManager_Owlready2, OWLReasoner_Owlready2 +from ontolearn.owlapy.fast_instance_checker import OWLReasoner_FastInstanceChecker +from ontolearn.owlapy.model import OWLDataProperty, OWLLiteral, IRI +from ontolearn.owlapy.owlready2 import OWLOntologyManager_Owlready2, OWLReasoner_Owlready2 class BinningValueSplitter_Test(unittest.TestCase):