eckity.creators.gp_creators.tree_creator

  1from typing import Any, Callable, Dict, List, Tuple, Union, Optional
  2
  3from overrides import override
  4
  5from eckity.base.utils import arity
  6from eckity.creators.creator import Creator
  7from eckity.fitness.gp_fitness import GPFitness
  8from eckity.fitness.simple_fitness import SimpleFitness
  9from eckity.genetic_encodings.gp import (
 10    FunctionNode,
 11    TerminalNode,
 12    Tree,
 13    TreeNode,
 14)
 15from eckity.genetic_encodings.gp.tree.utils import get_func_types
 16
 17
 18class GPTreeCreator(Creator):
 19    def __init__(
 20        self,
 21        init_depth: Tuple[int, int] = None,
 22        function_set: List[Callable] = None,
 23        terminal_set: Union[Dict[Any, type], List[Any]] = None,
 24        erc_range: Union[Tuple[int, int], Tuple[float, float]] = None,
 25        fitness_type: type = SimpleFitness,
 26        bloat_weight: float = 0.0,
 27        events: List[str] = None,
 28        root_type: Optional[type] = None,
 29        update_parents: bool = False
 30    ):
 31        if events is None:
 32            events = ["after_creation"]
 33        super().__init__(events, fitness_type)
 34
 35        if init_depth is None:
 36            init_depth = (2, 4)
 37
 38        if function_set is None:
 39            raise ValueError("function_set must be provided")
 40
 41        if terminal_set is None:
 42            raise ValueError("terminal_set must be provided")
 43
 44        self.init_depth = init_depth
 45        self.function_set = function_set
 46        self.terminal_set = terminal_set
 47        self.bloat_weight = bloat_weight
 48        self.root_type = root_type
 49        self.update_parents = update_parents
 50        self.erc_range = erc_range
 51
 52    @override
 53    def create_individuals(
 54        self, n_individuals: int, higher_is_better: bool
 55    ) -> List[Tree]:
 56        individuals = [
 57            Tree(
 58                function_set=self.function_set,
 59                terminal_set=self.terminal_set,
 60                fitness=GPFitness(
 61                    bloat_weight=self.bloat_weight,
 62                    higher_is_better=higher_is_better,
 63                ),
 64                root_type=self.root_type,
 65                update_parents=self.update_parents,
 66                erc_range=self.erc_range,
 67            )
 68            for _ in range(n_individuals)
 69        ]
 70        for ind in individuals:
 71            self.create_tree(
 72                ind.tree,
 73                ind.random_function,
 74                ind.random_terminal,
 75                node_type=self.root_type,
 76            )
 77        self.created_individuals = individuals
 78        return individuals
 79
 80    def create_tree(
 81        self,
 82        tree: List[TreeNode],
 83        random_function: Callable[[type], Optional[FunctionNode]],
 84        random_terminal: Callable[[type], Optional[TerminalNode]],
 85        depth: int = 0,
 86        node_type: Optional[type] = None,
 87    ) -> None:
 88        """
 89        Recursively build the tree representation
 90        of an existing Tree individual.
 91        
 92        (This method is not abstract as it is not required in HalfCreator)
 93
 94        Parameters
 95        ----------
 96        tree_ind : Tree
 97            Individual to create the tree representation for
 98        """
 99        pass
100
101    def _add_children(
102        self,
103        tree: List[TreeNode],
104        fn_node: FunctionNode,
105        random_function: Callable[[type], Optional[FunctionNode]],
106        random_terminal: Callable[[type], Optional[TerminalNode]],
107        depth: int,
108    ) -> None:
109        """
110        Recursively add children to a function node.
111
112        Parameters
113        ----------
114        tree : List[TreeNode]
115            Total representation of the tree.
116        fn_node : FunctionNode
117            Function node, parent of the children to be created.
118        random_function : Callable[[type], Optional[FunctionNode]]
119            Random FunctionNode generator.
120        random_terminal : Callable[[type], Optional[TerminalNode]]
121            Random TerminalNode generator.
122        depth : int
123            current depth of the tree
124        """
125        func_types = get_func_types(fn_node.function)
126        for i in range(arity(fn_node.function)):
127            self.create_tree(
128                tree,
129                random_function,
130                random_terminal,
131                depth=depth + 1,
132                node_type=func_types[i],
133            )
134
135    def _assert_node_created(
136        self,
137        node: Optional[TreeNode],
138        node_type: Optional[type] = None
139    ) -> None:
140        """
141        Assert that a TreeNode was created successfully.
142
143        Parameters
144        ----------
145        node : Optional[TreeNode]
146            Generated tree node.
147        node_type : Optional[type], optional
148            Generated tree node type, by default None
149
150        Raises
151        ------
152        ValueError
153            Raised if a node was not generated successfully.
154        """
155        if node is None:
156            # optionally add type info for typed case
157            type_info = (
158                f"with type {node_type}" if node_type is not None else ""
159            )
160
161            # optionally add erc_range info if it was defined
162            erc_info = (
163                f"erc range ({self.erc_range}) ,"
164                if self.erc_range is not None
165                else ""
166            )
167
168            raise ValueError(
169                f"Could not generate node {type_info} "
170                f"due to a mismatch in terminals ({self.terminal_set}), "
171                f"functions ({self.function_set}), {erc_info} "
172                f"or init_depth ({self.init_depth}) configuration."
173            )
class GPTreeCreator(eckity.creators.creator.Creator):
 19class GPTreeCreator(Creator):
 20    def __init__(
 21        self,
 22        init_depth: Tuple[int, int] = None,
 23        function_set: List[Callable] = None,
 24        terminal_set: Union[Dict[Any, type], List[Any]] = None,
 25        erc_range: Union[Tuple[int, int], Tuple[float, float]] = None,
 26        fitness_type: type = SimpleFitness,
 27        bloat_weight: float = 0.0,
 28        events: List[str] = None,
 29        root_type: Optional[type] = None,
 30        update_parents: bool = False
 31    ):
 32        if events is None:
 33            events = ["after_creation"]
 34        super().__init__(events, fitness_type)
 35
 36        if init_depth is None:
 37            init_depth = (2, 4)
 38
 39        if function_set is None:
 40            raise ValueError("function_set must be provided")
 41
 42        if terminal_set is None:
 43            raise ValueError("terminal_set must be provided")
 44
 45        self.init_depth = init_depth
 46        self.function_set = function_set
 47        self.terminal_set = terminal_set
 48        self.bloat_weight = bloat_weight
 49        self.root_type = root_type
 50        self.update_parents = update_parents
 51        self.erc_range = erc_range
 52
 53    @override
 54    def create_individuals(
 55        self, n_individuals: int, higher_is_better: bool
 56    ) -> List[Tree]:
 57        individuals = [
 58            Tree(
 59                function_set=self.function_set,
 60                terminal_set=self.terminal_set,
 61                fitness=GPFitness(
 62                    bloat_weight=self.bloat_weight,
 63                    higher_is_better=higher_is_better,
 64                ),
 65                root_type=self.root_type,
 66                update_parents=self.update_parents,
 67                erc_range=self.erc_range,
 68            )
 69            for _ in range(n_individuals)
 70        ]
 71        for ind in individuals:
 72            self.create_tree(
 73                ind.tree,
 74                ind.random_function,
 75                ind.random_terminal,
 76                node_type=self.root_type,
 77            )
 78        self.created_individuals = individuals
 79        return individuals
 80
 81    def create_tree(
 82        self,
 83        tree: List[TreeNode],
 84        random_function: Callable[[type], Optional[FunctionNode]],
 85        random_terminal: Callable[[type], Optional[TerminalNode]],
 86        depth: int = 0,
 87        node_type: Optional[type] = None,
 88    ) -> None:
 89        """
 90        Recursively build the tree representation
 91        of an existing Tree individual.
 92        
 93        (This method is not abstract as it is not required in HalfCreator)
 94
 95        Parameters
 96        ----------
 97        tree_ind : Tree
 98            Individual to create the tree representation for
 99        """
100        pass
101
102    def _add_children(
103        self,
104        tree: List[TreeNode],
105        fn_node: FunctionNode,
106        random_function: Callable[[type], Optional[FunctionNode]],
107        random_terminal: Callable[[type], Optional[TerminalNode]],
108        depth: int,
109    ) -> None:
110        """
111        Recursively add children to a function node.
112
113        Parameters
114        ----------
115        tree : List[TreeNode]
116            Total representation of the tree.
117        fn_node : FunctionNode
118            Function node, parent of the children to be created.
119        random_function : Callable[[type], Optional[FunctionNode]]
120            Random FunctionNode generator.
121        random_terminal : Callable[[type], Optional[TerminalNode]]
122            Random TerminalNode generator.
123        depth : int
124            current depth of the tree
125        """
126        func_types = get_func_types(fn_node.function)
127        for i in range(arity(fn_node.function)):
128            self.create_tree(
129                tree,
130                random_function,
131                random_terminal,
132                depth=depth + 1,
133                node_type=func_types[i],
134            )
135
136    def _assert_node_created(
137        self,
138        node: Optional[TreeNode],
139        node_type: Optional[type] = None
140    ) -> None:
141        """
142        Assert that a TreeNode was created successfully.
143
144        Parameters
145        ----------
146        node : Optional[TreeNode]
147            Generated tree node.
148        node_type : Optional[type], optional
149            Generated tree node type, by default None
150
151        Raises
152        ------
153        ValueError
154            Raised if a node was not generated successfully.
155        """
156        if node is None:
157            # optionally add type info for typed case
158            type_info = (
159                f"with type {node_type}" if node_type is not None else ""
160            )
161
162            # optionally add erc_range info if it was defined
163            erc_info = (
164                f"erc range ({self.erc_range}) ,"
165                if self.erc_range is not None
166                else ""
167            )
168
169            raise ValueError(
170                f"Could not generate node {type_info} "
171                f"due to a mismatch in terminals ({self.terminal_set}), "
172                f"functions ({self.function_set}), {erc_info} "
173                f"or init_depth ({self.init_depth}) configuration."
174            )

Helper class that provides a standard way to create an ABC using inheritance.

GPTreeCreator( init_depth: Tuple[int, int] = None, function_set: List[Callable] = None, terminal_set: Union[Dict[Any, type], List[Any]] = None, erc_range: Union[Tuple[int, int], Tuple[float, float]] = None, fitness_type: type = <class 'eckity.fitness.simple_fitness.SimpleFitness'>, bloat_weight: float = 0.0, events: List[str] = None, root_type: Optional[type] = None, update_parents: bool = False)
20    def __init__(
21        self,
22        init_depth: Tuple[int, int] = None,
23        function_set: List[Callable] = None,
24        terminal_set: Union[Dict[Any, type], List[Any]] = None,
25        erc_range: Union[Tuple[int, int], Tuple[float, float]] = None,
26        fitness_type: type = SimpleFitness,
27        bloat_weight: float = 0.0,
28        events: List[str] = None,
29        root_type: Optional[type] = None,
30        update_parents: bool = False
31    ):
32        if events is None:
33            events = ["after_creation"]
34        super().__init__(events, fitness_type)
35
36        if init_depth is None:
37            init_depth = (2, 4)
38
39        if function_set is None:
40            raise ValueError("function_set must be provided")
41
42        if terminal_set is None:
43            raise ValueError("terminal_set must be provided")
44
45        self.init_depth = init_depth
46        self.function_set = function_set
47        self.terminal_set = terminal_set
48        self.bloat_weight = bloat_weight
49        self.root_type = root_type
50        self.update_parents = update_parents
51        self.erc_range = erc_range
init_depth
function_set
terminal_set
bloat_weight
root_type
update_parents
erc_range
@override
def create_individuals( self, n_individuals: int, higher_is_better: bool) -> List[eckity.genetic_encodings.gp.tree.tree_individual.Tree]:
53    @override
54    def create_individuals(
55        self, n_individuals: int, higher_is_better: bool
56    ) -> List[Tree]:
57        individuals = [
58            Tree(
59                function_set=self.function_set,
60                terminal_set=self.terminal_set,
61                fitness=GPFitness(
62                    bloat_weight=self.bloat_weight,
63                    higher_is_better=higher_is_better,
64                ),
65                root_type=self.root_type,
66                update_parents=self.update_parents,
67                erc_range=self.erc_range,
68            )
69            for _ in range(n_individuals)
70        ]
71        for ind in individuals:
72            self.create_tree(
73                ind.tree,
74                ind.random_function,
75                ind.random_terminal,
76                node_type=self.root_type,
77            )
78        self.created_individuals = individuals
79        return individuals
def create_tree( self, tree: List[eckity.genetic_encodings.gp.tree.tree_node.TreeNode], random_function: Callable[[type], Optional[eckity.genetic_encodings.gp.tree.tree_node.FunctionNode]], random_terminal: Callable[[type], Optional[eckity.genetic_encodings.gp.tree.tree_node.TerminalNode]], depth: int = 0, node_type: Optional[type] = None) -> None:
 81    def create_tree(
 82        self,
 83        tree: List[TreeNode],
 84        random_function: Callable[[type], Optional[FunctionNode]],
 85        random_terminal: Callable[[type], Optional[TerminalNode]],
 86        depth: int = 0,
 87        node_type: Optional[type] = None,
 88    ) -> None:
 89        """
 90        Recursively build the tree representation
 91        of an existing Tree individual.
 92        
 93        (This method is not abstract as it is not required in HalfCreator)
 94
 95        Parameters
 96        ----------
 97        tree_ind : Tree
 98            Individual to create the tree representation for
 99        """
100        pass

Recursively build the tree representation of an existing Tree individual.

(This method is not abstract as it is not required in HalfCreator)

Parameters
  • tree_ind (Tree): Individual to create the tree representation for