Skip to content

Commit

Permalink
KnowledgeBase changed to AbstractKnowledgeBase where applicable
Browse files Browse the repository at this point in the history
  • Loading branch information
alkidbaci committed Jan 13, 2025
1 parent c0474fb commit 302eb15
Show file tree
Hide file tree
Showing 11 changed files with 55 additions and 57 deletions.
12 changes: 6 additions & 6 deletions ontolearn/base_concept_learner.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
from owlapy.owl_ontology_manager import OntologyManager
from owlapy.render import DLSyntaxObjectRenderer
from .abstracts import BaseRefinement, AbstractScorer, AbstractHeuristic, \
AbstractConceptNode, AbstractLearningProblem
AbstractConceptNode, AbstractLearningProblem, AbstractKnowledgeBase
from .utils import oplogging

_N = TypeVar('_N', bound=AbstractConceptNode) #:
Expand Down Expand Up @@ -81,7 +81,7 @@ class BaseConceptLearner(metaclass=ABCMeta):
∀ H \\in \\hypotheses: { (K \\wedge H \\models E^+) \\wedge \\neg( K \\wedge H \\models E^-) }.
Attributes:
kb (KnowledgeBase): The knowledge base that the concept learner is using.
kb (AbstractKnowledgeBase): The knowledge base that the concept learner is using.
quality_func (AbstractScorer) The quality function to be used.
max_num_of_concepts_tested (int) Limit to stop the algorithm after n concepts tested.
terminate_on_goal (bool): Whether to stop the algorithm if a perfect solution is found.
Expand All @@ -96,7 +96,7 @@ class BaseConceptLearner(metaclass=ABCMeta):

name: ClassVar[str]

kb: KnowledgeBase
kb: AbstractKnowledgeBase
quality_func: Optional[AbstractScorer]
max_num_of_concepts_tested: Optional[int]
terminate_on_goal: Optional[bool]
Expand All @@ -107,7 +107,7 @@ class BaseConceptLearner(metaclass=ABCMeta):

@abstractmethod
def __init__(self,
knowledge_base: KnowledgeBase,
knowledge_base: AbstractKnowledgeBase,
reasoner: Optional[AbstractOWLReasoner] = None,
quality_func: Optional[AbstractScorer] = None,
max_num_of_concepts_tested: Optional[int] = None,
Expand Down Expand Up @@ -405,7 +405,7 @@ class RefinementBasedConceptLearner(BaseConceptLearner):
Base class for refinement based Concept Learning approaches.
Attributes:
kb (KnowledgeBase): The knowledge base that the concept learner is using.
kb (AbstractKnowledgeBase): The knowledge base that the concept learner is using.
quality_func (AbstractScorer) The quality function to be used.
max_num_of_concepts_tested (int) Limit to stop the algorithm after n concepts tested.
terminate_on_goal (bool): Whether to stop the algorithm if a perfect solution is found.
Expand All @@ -432,7 +432,7 @@ class RefinementBasedConceptLearner(BaseConceptLearner):

@abstractmethod
def __init__(self,
knowledge_base: KnowledgeBase,
knowledge_base: AbstractKnowledgeBase,
reasoner: Optional[AbstractOWLReasoner] = None,
refinement_operator: Optional[BaseRefinement] = None,
heuristic_func: Optional[AbstractHeuristic] = None,
Expand Down
31 changes: 17 additions & 14 deletions ontolearn/concept_learner.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,9 @@
from owlapy.utils import EvaluatedDescriptionSet, ConceptOperandSorter
from owlapy.parser import DLSyntaxParser

from ontolearn.knowledge_base import KnowledgeBase
from ontolearn.abstracts import AbstractFitness, AbstractScorer, BaseRefinement, AbstractHeuristic
from ontolearn.concept_generator import ConceptGenerator
from ontolearn.abstracts import AbstractFitness, AbstractScorer, BaseRefinement, AbstractHeuristic, \
AbstractKnowledgeBase
from ontolearn.base_concept_learner import BaseConceptLearner
from ontolearn.data_struct import NCESDataLoader, NCESDataLoaderInference, CLIPDataLoader, CLIPDataLoaderInference
from ontolearn.ea_algorithms import AbstractEvolutionaryAlgorithm, EASimple
Expand Down Expand Up @@ -89,7 +90,7 @@ class EvoLearner(BaseConceptLearner):
fitness_func (AbstractFitness): Fitness function.
height_limit (int): The maximum value allowed for the height of the Crossover and Mutation operations.
init_method (AbstractEAInitialization): The evolutionary algorithm initialization method.
kb (KnowledgeBase): The knowledge base that the concept learner is using.
kb (AbstractKnowledgeBase): The knowledge base that the concept learner is using.
max_num_of_concepts_tested (int): Limit to stop the algorithm after n concepts tested.
max_runtime (int): max_runtime: Limit to stop the algorithm after n seconds.
mut_uniform_gen (AbstractEAInitialization): The initialization method to create the tree for mutation operation.
Expand Down Expand Up @@ -117,11 +118,11 @@ class EvoLearner(BaseConceptLearner):
__slots__ = 'fitness_func', 'init_method', 'algorithm', 'value_splitter', 'tournament_size', \
'population_size', 'num_generations', 'height_limit', 'use_data_properties', 'pset', 'toolbox', \
'_learning_problem', '_result_population', 'mut_uniform_gen', '_dp_to_prim_type', '_dp_splits', \
'_split_properties', '_cache', 'use_card_restrictions', 'card_limit', 'use_inverse', 'total_fits'
'_split_properties', '_cache', 'use_card_restrictions', 'card_limit', 'use_inverse', 'total_fits', 'generator'

name = 'evolearner'

kb: KnowledgeBase
kb: AbstractKnowledgeBase
fitness_func: AbstractFitness
init_method: AbstractEAInitialization
algorithm: AbstractEvolutionaryAlgorithm
Expand All @@ -135,6 +136,7 @@ class EvoLearner(BaseConceptLearner):
population_size: int
num_generations: int
height_limit: int
generator: ConceptGenerator

pset: gp.PrimitiveSetTyped
toolbox: base.Toolbox
Expand All @@ -146,7 +148,7 @@ class EvoLearner(BaseConceptLearner):
_cache: Dict[str, Tuple[float, float]]

def __init__(self,
knowledge_base: KnowledgeBase,
knowledge_base: AbstractKnowledgeBase,
reasoner: Optional[AbstractOWLReasoner] = None,
quality_func: Optional[AbstractScorer] = None,
fitness_func: Optional[AbstractFitness] = None,
Expand Down Expand Up @@ -174,7 +176,7 @@ def __init__(self,
Defaults to 17.
init_method (AbstractEAInitialization): The evolutionary algorithm initialization method. Defaults
to EARandomWalkInitialization.
knowledge_base (KnowledgeBase): The knowledge base that the concept learner is using.
knowledge_base (AbstractKnowledgeBase): The knowledge base that the concept learner is using.
max_runtime (int): max_runtime: Limit to stop the algorithm after n seconds. Defaults to 5.
mut_uniform_gen (AbstractEAInitialization): The initialization method to create the tree for mutation
operation. Defaults to
Expand Down Expand Up @@ -217,6 +219,7 @@ def __init__(self,
self.num_generations = num_generations
self.height_limit = height_limit
self.total_fits = 0
self.generator = ConceptGenerator()
self.__setup()

def __setup(self):
Expand Down Expand Up @@ -251,7 +254,7 @@ def __build_primitive_set(self) -> gp.PrimitiveSetTyped:
intersection = factory.create_intersection()

pset = gp.PrimitiveSetTyped("concept_tree", [], OWLClassExpression)
pset.addPrimitive(self.kb.generator.negation, [OWLClassExpression], OWLClassExpression,
pset.addPrimitive(self.generator.negation, [OWLClassExpression], OWLClassExpression,
name=OperatorVocabulary.NEGATION)
pset.addPrimitive(union, [OWLClassExpression, OWLClassExpression], OWLClassExpression,
name=OperatorVocabulary.UNION)
Expand Down Expand Up @@ -323,10 +326,10 @@ class Bool(object):
for class_ in self.kb.get_concepts():
pset.addTerminal(class_, OWLClassExpression, name=escape(class_.iri.get_remainder()))

pset.addTerminal(self.kb.generator.thing, OWLClassExpression,
name=escape(self.kb.generator.thing.iri.get_remainder()))
pset.addTerminal(self.kb.generator.nothing, OWLClassExpression,
name=escape(self.kb.generator.nothing.iri.get_remainder()))
pset.addTerminal(self.generator.thing, OWLClassExpression,
name=escape(self.generator.thing.iri.get_remainder()))
pset.addTerminal(self.generator.nothing, OWLClassExpression,
name=escape(self.generator.nothing.iri.get_remainder()))
return pset

def __build_toolbox(self) -> base.Toolbox:
Expand Down Expand Up @@ -527,7 +530,7 @@ class CLIP(CELOE):
heuristic_func (AbstractHeuristic): Function to guide the search heuristic.
heuristic_queue (SortedSet[OENode]): A sorted set that compares the nodes based on Heuristic.
iter_bound (int): Limit to stop the algorithm after n refinement steps are done.
kb (KnowledgeBase): The knowledge base that the concept learner is using.
kb (AbstractKnowledgeBase): The knowledge base that the concept learner is using.
max_child_length (int): Limit the length of concepts generated by the refinement operator.
max_he (int): Maximal value of horizontal expansion.
max_num_of_concepts_tested (int) Limit to stop the algorithm after n concepts tested.
Expand All @@ -553,7 +556,7 @@ class CLIP(CELOE):
name = 'clip'

def __init__(self,
knowledge_base: KnowledgeBase,
knowledge_base: AbstractKnowledgeBase,
knowledge_base_path='',
reasoner: Optional[AbstractOWLReasoner] = None,
refinement_operator: Optional[BaseRefinement[OENode]] = ExpressRefinement,
Expand Down
6 changes: 3 additions & 3 deletions ontolearn/ea_initialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@
from owlapy.owl_literal import OWLLiteral
from owlapy.owl_property import OWLDataProperty, OWLObjectProperty

from ontolearn.abstracts import AbstractKnowledgeBase
from ontolearn.ea_utils import OperatorVocabulary, Tree, escape, owlliteral_to_primitive_string
from ontolearn.knowledge_base import KnowledgeBase
import random
from abc import ABCMeta, abstractmethod
from typing import Any, Callable, Dict, Final, List, Set, Union
Expand Down Expand Up @@ -153,7 +153,7 @@ class EARandomWalkInitialization(AbstractEAInitialization):
type_counts: Dict[OWLClass, int]
dp_to_prim_type: Dict[OWLDataProperty, Any]
dp_splits: Dict[OWLDataProperty, List[OWLLiteral]]
kb: KnowledgeBase
kb: AbstractKnowledgeBase

def __init__(self, max_t: int = 2, jump_pr: float = 0.5):
"""
Expand All @@ -175,7 +175,7 @@ def get_population(self, container: Callable,
pos: List[OWLNamedIndividual] = None,
dp_to_prim_type: Dict[OWLDataProperty, Any] = None,
dp_splits: Dict[OWLDataProperty, List[OWLLiteral]] = None,
kb: KnowledgeBase = None) -> List[Tree]:
kb: AbstractKnowledgeBase = None) -> List[Tree]:
assert pos is not None
assert kb is not None
assert dp_to_prim_type is not None
Expand Down
4 changes: 2 additions & 2 deletions ontolearn/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
from ontolearn.learning_problem import PosNegLPStandard
from ontolearn.refinement_operators import ModifiedCELOERefinement
from ontolearn.metrics import Accuracy, F1, Recall, Precision, WeightedAccuracy
from ontolearn.triple_store import TripleStoreKnowledgeBase
from ontolearn.triple_store import TripleStore
from ontolearn.value_splitter import BinningValueSplitter, EntropyValueSplitter

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -200,7 +200,7 @@ def execute(args): # pragma: no cover
learner_type = models[args.model]
optargs = {}
if args.sparql_endpoint:
kb = TripleStoreKnowledgeBase(args.sparql_endpoint)
kb = TripleStore(args.sparql_endpoint)
else:
kb = KnowledgeBase(path=args.knowledge_base_path)

Expand Down
12 changes: 6 additions & 6 deletions ontolearn/learners/celoe.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from ..base_concept_learner import RefinementBasedConceptLearner
from ..knowledge_base import KnowledgeBase

from ..abstracts import AbstractScorer, BaseRefinement, AbstractHeuristic, EncodedPosNegLPStandardKind
from ..abstracts import AbstractScorer, BaseRefinement, AbstractHeuristic, EncodedPosNegLPStandardKind, \
AbstractKnowledgeBase
from ..learning_problem import PosNegLPStandard
from ..quality_funcs import evaluate_concept
from ..search import OENode, TreeNode, EvaluatedConcept, HeuristicOrderedNode, QualityOrderedNode, LengthOrderedNode
Expand All @@ -22,6 +22,7 @@

_concept_operand_sorter = ConceptOperandSorter()


class CELOE(RefinementBasedConceptLearner):
"""Class Expression Learning for Ontology Engineering.
Attributes:
Expand All @@ -31,7 +32,7 @@ class CELOE(RefinementBasedConceptLearner):
heuristic_func (AbstractHeuristic): Function to guide the search heuristic.
heuristic_queue (SortedSet[OENode]): A sorted set that compares the nodes based on Heuristic.
iter_bound (int): Limit to stop the algorithm after n refinement steps are done.
kb (KnowledgeBase): The knowledge base that the concept learner is using.
kb (AbstractKnowledgeBase): The knowledge base that the concept learner is using.
max_child_length (int): Limit the length of concepts generated by the refinement operator.
max_he (int): Maximal value of horizontal expansion.
max_num_of_concepts_tested (int) Limit to stop the algorithm after n concepts tested.
Expand All @@ -55,7 +56,7 @@ class CELOE(RefinementBasedConceptLearner):
name = 'celoe_python'

def __init__(self,
knowledge_base: KnowledgeBase=None,
knowledge_base: AbstractKnowledgeBase = None,
reasoner: Optional[owlapy.abstracts.AbstractOWLReasoner] = None,
refinement_operator: Optional[BaseRefinement[OENode]] = None,
quality_func: Optional[AbstractScorer] = None,
Expand All @@ -78,7 +79,7 @@ def __init__(self,
Defaults to `ModifiedCELOERefinement`.
heuristic_func (AbstractHeuristic): Function to guide the search heuristic. Defaults to `CELOEHeuristic`.
iter_bound (int): Limit to stop the algorithm after n refinement steps are done. Defaults to 10'000.
knowledge_base (KnowledgeBase): The knowledge base that the concept learner is using.
knowledge_base (AbstractKnowledgeBase): The knowledge base that the concept learner is using.
max_num_of_concepts_tested (int) Limit to stop the algorithm after n concepts tested. Defaults to 10'000.
max_runtime (int): Limit to stop the algorithm after n seconds. Defaults to 5.
max_results (int): Maximum hypothesis to store. Defaults to 10.
Expand Down Expand Up @@ -124,7 +125,6 @@ def next_node_to_expand(self, step: int) -> OENode: # pragma: no cover
# from reimplementation, pick without quality criterion
return self.heuristic_queue[-1]


def best_hypotheses(self, n: int = 1, return_node: bool = False) -> Union[
OWLClassExpression | Iterable[OWLClassExpression],
OENode | Iterable[OENode]]:
Expand Down
4 changes: 2 additions & 2 deletions ontolearn/learners/drill.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
from owlapy import owl_expression_to_dl
from ontolearn.base_concept_learner import RefinementBasedConceptLearner
from ontolearn.refinement_operators import LengthBasedRefinement
from ontolearn.abstracts import AbstractNode
from ontolearn.abstracts import AbstractNode, AbstractKnowledgeBase
from ontolearn.search import RL_State
from typing import Set, List, Tuple, Optional, Generator, SupportsFloat, Iterable, FrozenSet, Callable, Union
from ontolearn.learning_problem import PosNegLPStandard
Expand Down Expand Up @@ -56,7 +56,7 @@
class Drill(RefinementBasedConceptLearner): # pragma: no cover
""" Neuro-Symbolic Class Expression Learning (https://www.ijcai.org/proceedings/2023/0403.pdf)"""

def __init__(self, knowledge_base,
def __init__(self, knowledge_base: AbstractKnowledgeBase,
path_embeddings: str = None,
refinement_operator: LengthBasedRefinement = None,
use_inverse: bool = True,
Expand Down
8 changes: 4 additions & 4 deletions ontolearn/learners/ocel.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from ..knowledge_base import KnowledgeBase
from typing import Optional
import owlapy
from ..abstracts import AbstractScorer, BaseRefinement, AbstractHeuristic
from ..abstracts import AbstractScorer, BaseRefinement, AbstractHeuristic, AbstractKnowledgeBase
from ..search import OENode, LBLNode
from owlapy.class_expression import OWLClassExpression
from ..heuristics import OCELHeuristic
Expand All @@ -19,7 +19,7 @@ class OCEL(CELOE):
heuristic_func (AbstractHeuristic): Function to guide the search heuristic.
heuristic_queue (SortedSet[OENode]): A sorted set that compares the nodes based on Heuristic.
iter_bound (int): Limit to stop the algorithm after n refinement steps are done.
kb (KnowledgeBase): The knowledge base that the concept learner is using.
kb (AbstractKnowledgeBase): The knowledge base that the concept learner is using.
max_child_length (int): Limit the length of concepts generated by the refinement operator.
max_he (int): Maximal value of horizontal expansion.
max_num_of_concepts_tested (int) Limit to stop the algorithm after n concepts tested.
Expand All @@ -41,7 +41,7 @@ class OCEL(CELOE):
name = 'ocel_python'

def __init__(self,
knowledge_base: KnowledgeBase,
knowledge_base: AbstractKnowledgeBase,
reasoner: Optional[owlapy.abstracts.AbstractOWLReasoner] = None,
refinement_operator: Optional[BaseRefinement[OENode]] = None,
quality_func: Optional[AbstractScorer] = None,
Expand All @@ -64,7 +64,7 @@ def __init__(self,
Defaults to `ModifiedCELOERefinement`.
heuristic_func (AbstractHeuristic): Function to guide the search heuristic. Defaults to `OCELHeuristic`.
iter_bound (int): Limit to stop the algorithm after n refinement steps are done. Defaults to 10'000.
knowledge_base (KnowledgeBase): The knowledge base that the concept learner is using.
knowledge_base (AbstractKnowledgeBase): The knowledge base that the concept learner is using.
max_num_of_concepts_tested (int) Limit to stop the algorithm after n concepts tested. Defaults to 10'000.
max_runtime (int): Limit to stop the algorithm after n seconds. Defaults to 5.
max_results (int): Maximum hypothesis to store. Defaults to 10.
Expand Down
15 changes: 6 additions & 9 deletions ontolearn/learning_problem.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,10 @@
"""Learning problem in Ontolearn."""
import logging
import random
from typing import Set, Optional, TYPE_CHECKING

from typing import Set, Optional
from owlapy.render import DLSyntaxObjectRenderer

if TYPE_CHECKING:
from ontolearn.knowledge_base import KnowledgeBase
from ontolearn.abstracts import AbstractLearningProblem, EncodedLearningProblem, EncodedPosNegLPStandardKind
from ontolearn.abstracts import AbstractLearningProblem, EncodedLearningProblem, EncodedPosNegLPStandardKind, \
AbstractKnowledgeBase
from owlapy.owl_individual import OWLNamedIndividual

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -103,7 +100,7 @@ def __init__(self,
# def encode_kb(self, knowledge_base: 'KnowledgeBase') -> EncodedPosNegLPStandard:
# return knowledge_base.encode_learning_problem(self)

def encode_kb(self, kb: 'KnowledgeBase') -> EncodedPosNegLPStandard:
def encode_kb(self, kb: 'AbstractKnowledgeBase') -> EncodedPosNegLPStandard:
"""
Provides the encoded learning problem (lp), i.e. the class containing the set of OWLNamedIndividuals
as follows:
Expand All @@ -117,9 +114,9 @@ def encode_kb(self, kb: 'KnowledgeBase') -> EncodedPosNegLPStandard:
EncodedPosNegLPStandard: The encoded learning problem.
"""
if self.all is None:
kb_all = kb.individuals()
kb_all = set(kb.individuals())
else:
kb_all = kb.individuals_set(self.all)
kb_all = set(kb.individuals_set(self.all))

assert 0 < len(self.pos) < len(kb_all) and len(kb_all) > len(self.neg)
if logger.isEnabledFor(logging.INFO):
Expand Down
Loading

0 comments on commit 302eb15

Please sign in to comment.