Example #1
0
 def test_exceptions(self):
     self.assertRaises(ValueError, NotNode, TerminalNode(9))
     self.assertFalse(NotNode(TerminalNode(True)).evaluate())
     self.assertRaises(ValueError, AndNode, TerminalNode(8), TerminalNode(7))
     self.assertFalse(AndNode(TerminalNode(True), TerminalNode(False)).evaluate())
     self.assertRaises(ValueError, OrNode, TerminalNode(8), TerminalNode(7))
     self.assertFalse(OrNode(TerminalNode(False), TerminalNode(False)).evaluate())
Example #2
0
    def test_div_zero_behaviour(self):
        from genetic_programming.equation_guesser import _mean_diff

        def _hyperbola(x: float) -> float:
            return 1 / x

        evaluate_at = list(range(-10, 10 + 1))

        equation_guesser = EquationGuesser(_hyperbola, [AddNode], float, 0, 0,
                                           0, True)
        equation_guesser.root = MultNode(
            AddNode(TerminalNode(3), TerminalVariable("x", float)),
            TerminalVariable("x", float))
        self.assertGreaterEqual(0,
                                equation_guesser.fitness(values=evaluate_at),
                                "Random Equation")
        equation_guesser.root = DivNode(TerminalNode(1),
                                        TerminalVariable("x", float))
        self.assertGreaterEqual(
            EPSILON, abs(0 - equation_guesser.fitness(values=evaluate_at)),
            "Same equation")
        equation_guesser.root = DivNode(TerminalVariable("x", float),
                                        TerminalNode(0))
        self.assertEqual(-float("Inf"),
                         equation_guesser.fitness(values=evaluate_at),
                         "Wrong equation")
Example #3
0
 def setUp(self) -> None:
     """
     Sets up unittest
     """
     seed(2)
     values = [uniform(0, 100) for _ in range(10)]
     self.first_node = OrNode(
         AndNode(
             GreaterNode(TerminalNode(values[0]), TerminalNode(values[1])),
             LesserNode(TerminalNode(values[2]), TerminalNode(values[3]))
         ), AndNode(
             GreaterNode(TerminalNode(values[4]), TerminalNode(values[5])),
             LesserNode(TerminalNode(values[6]), TerminalNode(values[7]))
         )
     )
     self.second_node = NotNode(
         EqualNode(
             TerminalNode(values[8]), TerminalNode(values[9])
         )
     )
     expected1 = (values[0] > values[1] and
                  values[2] < values[3]) or (values[4] > values[5] and
                                             values[6] < values[7])
     expected2 = values[8] != values[9]
     self.values = values
     self.expected = (expected1, expected2)
Example #4
0
 def test_terminal_node(self):
     a = 0.0
     node = TerminalNode(a)
     actual = node.evaluate(values={"x": [1, 2, 3], "y": [4, 5]})
     self.assertEqual(6, len(actual), "Length of terminal node with values")
     self.assertEqual([a] * 6, actual, "Terminal node miscalculated")
     actual = node.evaluate(values={"x": [1, 2, 3]})
     self.assertEqual(3, len(actual), "Length of terminal node with values")
     self.assertEqual([a] * 3, actual, "Terminal node miscalculated")
     actual = node.evaluate(values={})
     self.assertEqual(0, len(actual), "Length of terminal node with values")
     self.assertEqual([a] * 0, actual, "Terminal node miscalculated")
Example #5
0
 def test_assertion(self):
     seed(2)
     values = [uniform(-100, 100) for _ in range(4)]
     if values[0] > values[1]:
         expected = values[2]
     else:
         expected = values[3]
     node = IfThenElseNode(
         GreaterNode(TerminalNode(values[0]), TerminalNode(values[1])),
         TerminalNode(values[2]), TerminalNode(values[3])
     )
     self.assertGreaterEqual(EPSILON, abs(expected - node.evaluate()), "Wrong evaluation")
 def expected_individuals(self):
     """
     Generate individual with known performance knapsack
     """
     self.individual.root = AddNode(
         AddNode(
             AddNode(TerminalNode(1), TerminalNode(2)),
             AddNode(TerminalNode(3), TerminalNode(4))
         ),
         AddNode(TerminalNode(5), TerminalNode(6))
     )
     self.stable_one.root = AddNode(
         AddNode(TerminalNode(1), TerminalNode(2)),
         AddNode(TerminalNode(3), TerminalNode(4))
     )
     self.individual.fitness()
     self.stable_one.fitness()
     self.expected_values = (21, 10)
Example #7
0
 def test_replace_node(self):
     node = IfThenElseNode(TerminalNode(True), TerminalNode(1), TerminalNode(2))
     self.assertGreaterEqual(EPSILON, abs(1 - node.evaluate()), "Wrong calculated")
     node.replace_node(TerminalNode(3), 2)
     self.assertGreaterEqual(EPSILON, abs(1 - node.evaluate()), "Wrong calculated (replaced wrongly 'else')")
     node.replace_node(TerminalNode(3), 1)
     self.assertGreaterEqual(EPSILON, abs(3 - node.evaluate()), "Wrong calculated (replaced wrongly 'then')")
     node.replace_node(TerminalNode(4), 2)
     node.replace_node(TerminalNode(False), 0)
     self.assertGreaterEqual(EPSILON, abs(4 - node.evaluate()), "Wrong calculated (replaced wrongly 'if')")
Example #8
0
 def _generate_tree(d: int, p: float) -> Node:
     if d == 0 or uniform(0, 1) < p:
         value = choice(values)
         if isinstance(value, str):
             return TerminalVariable(value, variable_type)
         else:
             return TerminalNode(value)
     else:
         this = choice(internal_nodes)
         children = list()
         for _ in range(this.get_arguments()):
             children.append(_generate_tree(d - 1, p))
         return this(*children)
Example #9
0
 def setUp(self) -> None:
     """
     Sets up unittest
     """
     seed(2)
     values = [uniform(1, 100) for _ in range(9)]
     self.first_node = AddNode(
         DivNode(TerminalNode(values[0]), TerminalNode(values[1])),
         MultNode(
             MaxNode(
                 TerminalNode(values[2]),
                 DivNode(TerminalNode(values[3]), TerminalNode(values[4]))),
             TerminalNode(values[5])))
     self.second_node = MultNode(
         TerminalNode(values[6]),
         MaxNode(TerminalNode(values[7]),
                 DivNode(TerminalNode(values[8]), TerminalNode(0))))
     expected1 = (values[0] /
                  values[1]) + (max(values[2], values[3] / values[4]) *
                                (values[5]))
     expected2 = None
     self.values = values
     self.expected = expected1, expected2
Example #10
0
 def setUp(self) -> None:
     """
     Alter nodes to test with variables
     """
     seed(2)
     values = [uniform(0, 100) for _ in range(4)]
     self.first_node = OrNode(
         AndNode(
             GreaterNode(TerminalNode(values[0]), TerminalNode(values[1])),
             TerminalVariable("x", bool)),
         AndNode(
             TerminalVariable("y", bool),
             LesserNode(TerminalNode(values[2]), TerminalNode(values[3]))))
     self.second_node = NotNode(TerminalVariable("y", bool))
     expected1 = list()
     variables = [{
         "x": True,
         "y": True
     }, {
         "x": True,
         "y": False
     }, {
         "x": False,
         "y": True
     }, {
         "x": False,
         "y": False
     }]
     for variable in variables:
         expected1.append((values[0] > values[1] and variable["x"])
                          or (variable["y"] and values[2] < values[3]))
     expected2 = list()
     for variable in variables:
         expected2.append(not variable["y"])
     self.variables = {"x": [True, False], "y": [True, False]}
     self.values = values
     self.expected = (expected1, expected2)
Example #11
0
 def setUp(self) -> None:
     """
     Sets up unittest
     """
     seed(2)
     values = [uniform(0, 100) for _ in range(10)]
     self.first_node = AddNode(
         SubNode(TerminalNode(values[0]), TerminalNode(values[1])),
         MultNode(
             MaxNode(
                 TerminalNode(values[2]),
                 AddNode(TerminalNode(values[3]), TerminalNode(values[4]))),
             TerminalNode(values[5])))
     self.second_node = MultNode(
         TerminalNode(values[6]),
         MaxNode(TerminalNode(values[7]),
                 AddNode(TerminalNode(values[8]), TerminalNode(values[9]))))
     self.values = values
     expected1 = (self.values[0] - self.values[1]) + (
         max(self.values[2], self.values[3] + self.values[4]) *
         (self.values[5]))
     expected2 = (self.values[6] *
                  max(self.values[7], self.values[8] + self.values[9]))
     self.expected = expected1, expected2
Example #12
0
 def test_crossover(self):
     seed(10)
     first_one = self.individual.generate_individual()
     first_expected = self.individual.replace_on_position(
         (0, 0, 1, 0, 0, 1, 1, 0, 0, 0),
         first_one.get_node((0, 0, 0, 0, 1, 1, 0, 0, 1, 0)))
     """mutate"""
     graft = SubNode(
         SubNode(SubNode(TerminalNode(89), TerminalNode(53)),
                 AddNode(TerminalNode(-32), TerminalNode(-65))),
         MaxNode(MultNode(TerminalNode(-2), TerminalNode(65)),
                 MultNode(TerminalNode(-50), TerminalNode(-2))))
     reference = first_expected.arguments[1].arguments[0].arguments[
         0].arguments[1].arguments[0].arguments[1]
     reference.replace_node(graft, 0)
     """"""
     second_one = self.stable_one.generate_individual()
     second_expected = self.stable_one.replace_on_position(
         (0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0),
         second_one.get_node((0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1)))
     self.std_test_crossover(first_expected, second_expected, first_one,
                             second_one)
Example #13
0
 def setUp(self) -> None:
     """
     Alter nodes to test with variables
     """
     seed(2)
     values = [uniform(0, 100) for _ in range(7)]
     self.first_node = AddNode(
         SubNode(TerminalNode(values[0]), TerminalVariable("x", float)),
         MultNode(
             MaxNode(
                 TerminalNode(values[1]),
                 AddNode(TerminalNode(values[2]), TerminalNode(values[3]))),
             TerminalVariable("y", float)))
     self.second_node = MultNode(
         TerminalNode(values[4]),
         MaxNode(
             TerminalNode(values[5]),
             AddNode(TerminalNode(values[6]), TerminalVariable("y",
                                                               float))))
     expected1 = list()
     self.variables = {
         "x": list(range(-100, 101, 50)),
         "y": list(range(-100, 101, 50))
     }
     self.values = values
     variables = list()
     for x in self.variables["x"]:
         for y in self.variables["y"]:
             variables.append({"x": x, "y": y})
     for variable in variables:
         expected1.append((self.values[0] - variable["x"]) +
                          (max(self.values[1], self.values[2] +
                               self.values[3]) * variable["y"]))
     expected2 = list()
     for variable in variables:
         expected2.append(
             self.values[4] *
             max(self.values[5], self.values[6] + variable["y"]))
     self.values = values
     self.expected = (expected1, expected2)
Example #14
0
 def expected_individuals(self):
     """
     Generate individual with known performance knapsack
     """
     self.individual.root = MultNode(
         SubNode(AddNode(TerminalNode(e), TerminalVariable("x", float)),
                 MultNode(TerminalNode(1), TerminalNode(2))),
         AddNode(TerminalNode(e), TerminalNode(2)))
     self.stable_one.root = MultNode(TerminalNode(e),
                                     TerminalVariable("x", float))
     self.individual.fitness(values=VALUES_FOR_FITNESS)
     self.stable_one.fitness(values=VALUES_FOR_FITNESS)
     expected_individual = list()
     expected_stable_one = list()
     for x in VALUES_FOR_FITNESS:
         expected_individual.append(((e + x) - (1 * 2)) * (e + 2))
         expected_stable_one.append(e * x)
     self.individual_fitness = expected_individual
     self.stable_one_fitness = expected_stable_one
Example #15
0
 def test_exceptions(self):
     self.assertRaises(ValueError, IfThenElseNode, TerminalNode(1), TerminalNode(2), TerminalNode(3))
     node = IfThenElseNode(TerminalNode(True), TerminalNode(1), TerminalNode(2))
     self.assertRaises(ValueError, node.replace_node, TerminalNode(1), 0)
            return simplify(node.arguments[0])
        else:
            return simplify(node.arguments[1])
    elif node.number_of_arguments == 0:
        return node
    else:
        node.replace_node(simplify(node.arguments[0]), 0)
        node.replace_node(simplify(node.arguments[1]), 1)
        return node


""" Unbound version """
unbound_answer = AddNode(
    MultNode(
        MaxNode(
            SubNode(AddNode(TerminalNode(100), TerminalNode(7)),
                    MultNode(TerminalNode(100), TerminalNode(25))),
            AddNode(AddNode(TerminalNode(2), TerminalNode(8)),
                    AddNode(TerminalNode(100), TerminalNode(100)))),
        SubNode(
            AddNode(AddNode(TerminalNode(100), TerminalNode(25)),
                    SubNode(TerminalNode(7), TerminalNode(8))),
            MultNode(SubNode(TerminalNode(2), TerminalNode(4)),
                     SubNode(TerminalNode(100), TerminalNode(7))))),
    AddNode(
        MaxNode(
            AddNode(MaxNode(TerminalNode(7), TerminalNode(7)),
                    MaxNode(TerminalNode(8), TerminalNode(7))),
            SubNode(AddNode(TerminalNode(25), TerminalNode(25)),
                    MultNode(TerminalNode(7), TerminalNode(2)))),
        MaxNode(
 def setUp(self) -> None:
     """
     Sets up unittest
     """
     self.first_node = TerminalNode(10)
     self.second_node = TerminalNode(-10)
"""binary_nodes_expected.py: Binary Nodes expected for test purpose"""

from genetic_programming.ast.nodes import AddNode, SubNode, MultNode, MaxNode, TerminalNode

values = list(range(1, 11))
expected_individual = (values[0] -
                       values[1]) + (max(values[2], values[3] + values[4]) *
                                     (values[5]))
expected_stable_one = (values[6] * max(values[7], values[8] + values[9]))

individual = AddNode(
    SubNode(TerminalNode(values[0]), TerminalNode(values[1])),
    MultNode(
        MaxNode(TerminalNode(values[2]),
                AddNode(TerminalNode(values[3]), TerminalNode(values[4]))),
        TerminalNode(values[5])))
stable_one = MultNode(
    TerminalNode(values[6]),
    MaxNode(TerminalNode(values[7]),
            AddNode(TerminalNode(values[8]), TerminalNode(values[9]))))