def test_add_individual(self):
        mlc_repo = self.__get_new_repo()

        # mlc repository is empty
        self.assertEqual(mlc_repo.count_individual(), 0)

        # add the first individual
        indiv_id, exists = mlc_repo.add_individual(
            Individual("(root (+ 1 1))"))
        self.assertEqual(indiv_id, 1)
        self.assertFalse(exists)
        self.assertEqual(mlc_repo.count_individual(), 1)

        # trying to add an Individual with the same value
        indiv_id, exists = mlc_repo.add_individual(
            Individual("(root (+ 1 1))"))
        self.assertEqual(indiv_id, 1)
        self.assertTrue(exists)
        self.assertEqual(mlc_repo.count_individual(), 1)

        # adds another individual
        indiv_id, exists = mlc_repo.add_individual(
            Individual("(root (+ 2 2))"))
        self.assertEqual(indiv_id, 2)
        self.assertFalse(exists)
        self.assertEqual(mlc_repo.count_individual(), 2)
Ejemplo n.º 2
0
    def create(self, gen_size):
        ramp = np.array(self._config.get_list('GP', 'ramp'), dtype='float')
        center = (np.max(ramp) + np.amin(ramp)) / 2
        sigma = self._config.getint('GP', 'gaussigma')
        distrib = self.__create_gaussian_distribution(ramp, center, sigma,
                                                      gen_size)

        # Append a zero to the begginning of the array
        distrib = np.concatenate((np.array([0.]), distrib))
        lg.logger_.debug('[MIXED_RAMP_GAUSS] Distribution generated: ' +
                         np.array_str(distrib))

        i = 0
        j = 0
        while j < len(distrib) - 1:
            # Change th maxdepth propery while we generate the first generation
            Individual.set_maxdepthfirst(ramp[j])
            aux = distrib[j] + round((distrib[j + 1] - distrib[j]) / 2)

            # Numpy ranges doesn't include the last element as in python.
            # Increment the max value by 1 to correct this effect
            indiv_indexes_1 = np.arange(1, aux + 1, dtype=int)
            indiv_indexes_2 = np.arange(1, distrib[j + 1] + 1, dtype=int)

            i = self._fill_creation(indiv_indexes_1, i, 1)
            i = self._fill_creation(indiv_indexes_2, i, 3)
            j += 1
    def test_reload_individuals_from_file(self):
        with saved(Config.get_instance()) as config:
            config.set("BEHAVIOUR", "save", "true")
            config.set("BEHAVIOUR", "savedir", "test.db")
            config.set("POPULATION", "sensor_spec", "false")
            config.set("POPULATION", "sensors", "0")
            config.set("OPTIMIZATION", "simplify", "false")

            mlc_repo = self.__get_new_repo()

            # add individuals
            mlc_repo.add_individual(Individual("(root (+ 1 1))"))
            mlc_repo.add_individual(Individual("(root (+ 2 2))"))

            # add population
            p = Population(3, 0, Config.get_instance(), mlc_repo)
            p._individuals = [2, 1, 2]
            mlc_repo.add_population(p)

            # check status
            self.assertEqual(mlc_repo.count_individual(), 2)
            self.assertEqual(mlc_repo.count_population(), 1)

            # reload mlc_repository using another instance
            mlc_repo = self.__get_new_repo()
            self.assertEqual(mlc_repo.count_individual(), 2)
            self.assertEqual(mlc_repo.count_population(), 1)
    def test_remove_population_to_from_bad_values(self):
        mlc_repo = self.__get_new_repo()

        # add individuals
        mlc_repo.add_individual(Individual("(root (+ 1 1))"))
        mlc_repo.add_individual(Individual("(root (+ 2 2))"))
        mlc_repo.add_individual(Individual("(root (+ 3 3))"))
        mlc_repo.add_individual(Individual("(root (+ 4 4))"))
        mlc_repo.add_individual(Individual("(root (+ 5 5))"))

        # add  population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [1, 1, 1]
        mlc_repo.add_population(p)

        # add population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [2, 2, 2]
        mlc_repo.add_population(p)

        # add population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [3, 3, 3]
        mlc_repo.add_population(p)

        self.assertEqual(mlc_repo.count_population(), 3)

        # Remove all generations (1 to 3)
        mlc_repo.remove_population_to(10)
        self.assertEqual(mlc_repo.count_population(), 0)
Ejemplo n.º 5
0
    def test_parameter_controls_mutate_hoist(self):
        # save and restore original configuration
        with saved(Config.get_instance()):

            Config.get_instance().set("POPULATION", "controls", "5")
            individual = Individual(
                '(root (/ (exp (/ 8.2118 S0)) (* (* S0 (* 1.6755 -0.0699)) (log (exp -3.2288)))) (* (+ (sin -9.8591) (exp S0)) -9.4159) 0.0290 (* (log (* (+ -5.0573 -6.2191) S0)) (/ (cos (log S0)) (cos (tanh 2.2886)))) (log -8.6795))'
            )

            new_ind = individual.mutate(Individual.MutationType.HOIST)
            self.assertEqual(
                new_ind.get_value(),
                "(root (log (exp -3.2288)) (* (+ (sin -9.8591) (exp S0)) -9.4159) 0.0290 (* (log (* (+ -5.0573 -6.2191) S0)) (/ (cos (log S0)) (cos (tanh 2.2886)))) (log -8.6795))"
            )

            new_ind = individual.mutate(Individual.MutationType.HOIST)
            self.assertEqual(
                new_ind.get_value(),
                "(root (/ (exp (/ 8.2118 S0)) (* (* S0 (* 1.6755 -0.0699)) (log (exp -3.2288)))) (exp S0) 0.0290 (* (log (* (+ -5.0573 -6.2191) S0)) (/ (cos (log S0)) (cos (tanh 2.2886)))) (log -8.6795))"
            )

            new_ind = individual.mutate(Individual.MutationType.HOIST)
            self.assertEqual(
                new_ind.get_value(),
                "(root (* S0 (* 1.6755 -0.0699)) (* (+ (sin -9.8591) (exp S0)) -9.4159) 0.0290 (* (log (* (+ -5.0573 -6.2191) S0)) (/ (cos (log S0)) (cos (tanh 2.2886)))) (log -8.6795))"
            )
    def test_update_individual_cost_in_generation(self):
        mlc_repo = self.__get_new_repo()

        # add individuals
        mlc_repo.add_individual(Individual("(root (+ 1 1))"))
        mlc_repo.add_individual(Individual("(root (+ 2 2))"))

        # add first population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [1, 2, 1]
        p._costs = [4, 5, 6]
        p._ev_time = [5, 6, 7]
        mlc_repo.add_population(p)

        # add second population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [2, 1, 2]
        p._costs = [8, 9, 10]
        p._ev_time = [11, 12, 13]
        mlc_repo.add_population(p)

        # update cost for individual 1
        mlc_repo.update_individual_cost(1, 45, 46, generation=1)

        # check cost update in the first population
        p = mlc_repo.get_population(1)
        self.assertEqual(p._individuals, [1, 2, 1])
        self.assertEqual(p._costs, [45, 5, 45])
        self.assertEqual(p._ev_time, [46, 6, 46])

        # check cost update in the second population
        p = mlc_repo.get_population(2)
        self.assertEqual(p._individuals, [2, 1, 2])
        self.assertEqual(p._costs, [8, 9, 10])
        self.assertEqual(p._ev_time, [11, 12, 13])
    def test_get_individual_data(self):
        mlc_repo = self.__get_new_repo()

        # add individuals
        mlc_repo.add_individual(Individual("(root (+ 1 1))"))
        mlc_repo.add_individual(Individual("(root (+ 2 2))"))
        mlc_repo.add_individual(Individual("(root (+ 3 3))"))
        mlc_repo.add_individual(Individual("(root (+ 4 4))"))

        # first population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [1, 2, 1]
        p._costs = [4, 5, 6]
        p._ev_time = [5, 6, 7]
        mlc_repo.add_population(p)

        # second population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [3, 4, 2]
        p._costs = [7, 4, 9]
        p._ev_time = [8, 5, 10]

        mlc_repo.add_population(p)

        # check idividuals data loaded from the mlc_repo
        self.assertEqual(mlc_repo.count_population(), 2)

        # Individual 1 have two appearances in the first generation
        data = mlc_repo.get_individual_data(1)
        self.assertEqual(data.get_value(), "(root (+ 1 1))")
        self.assertEqual(data.get_appearances(), 2)
        self.assertEqual(data.get_cost_history(), {1: [(4.0, 5), (6.0, 7)]})

        # Individual 2 have two appearances
        data = mlc_repo.get_individual_data(2)
        self.assertEqual(data.get_value(), "(root (+ 2 2))")
        self.assertEqual(data.get_appearances(), 2)
        self.assertEqual(data.get_cost_history(), {
            1: [(5.0, 6)],
            2: [(9.0, 10)]
        })

        # Individual 3 have one appearances
        data = mlc_repo.get_individual_data(3)
        self.assertEqual(data.get_value(), "(root (+ 3 3))")
        self.assertEqual(data.get_appearances(), 1)
        self.assertEqual(data.get_cost_history(), {2: [(7.0, 8)]})

        # Individual 4 have one appearances
        data = mlc_repo.get_individual_data(4)
        self.assertEqual(data.get_value(), "(root (+ 4 4))")
        self.assertEqual(data.get_appearances(), 1)
        self.assertEqual(data.get_cost_history(), {2: [(4.0, 5)]})

        # get individual data from invalid individual
        try:
            data = mlc_repo.get_individual_data(100)
            self.assertTrue(False)
        except KeyError, ex:
            self.assertTrue(True)
    def test_add_population(self):
        mlc_repo = self.__get_new_repo()

        mlc_repo.add_individual(Individual("(root (+ 1 1))"))
        mlc_repo.add_individual(Individual("(root (+ 2 2))"))
        mlc_repo.add_individual(Individual("(root (+ 3 3))"))
        self.assertEqual(mlc_repo.count_individual(), 3)

        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [1, 2, 3]
        p._costs = [4, 5, 6]
        p._ev_time = [7, 8, 9]
        p._gen_method = [10, 11, 12]

        # add population to the mlc_repository
        self.assertEqual(mlc_repo.count_population(), 0)
        mlc_repo.add_population(p)
        self.assertEqual(mlc_repo.count_population(), 1)

        # obtain population
        p_from_repo = mlc_repo.get_population(1)

        # check population content
        self.assertEqual(p_from_repo._individuals, p._individuals)
        self.assertEqual(p_from_repo._costs, p._costs)
        self.assertEqual(p_from_repo._ev_time, p._ev_time)
        self.assertEqual(p_from_repo._gen_method, p._gen_method)
    def test_get_individuals(self):
        mlc_repo = self.__get_new_repo()
        mlc_repo.add_individual(Individual("(root (+ 1 1))"))
        mlc_repo.add_individual(Individual("(root (+ 2 2))"))

        # get individuals
        individual = mlc_repo.get_individual(1)
        self.assertEqual(individual.get_value(), "(root (+ 1 1))")

        individual = mlc_repo.get_individual(2)
        self.assertEqual(individual.get_value(), "(root (+ 2 2))")

        # get individual data
        data = mlc_repo.get_individual_data(1)
        self.assertEqual(data.get_appearances(), 0)
        self.assertEqual(data.get_value(), "(root (+ 1 1))")
        self.assertEqual(data.get_cost_history(), {})

        data = mlc_repo.get_individual_data(2)
        self.assertEqual(data.get_appearances(), 0)
        self.assertEqual(data.get_value(), "(root (+ 2 2))")
        self.assertEqual(data.get_cost_history(), {})

        # invalid id
        try:
            individual = mlc_repo.get_individual(3)
            self.assertTrue(False)
        except KeyError:
            self.assertTrue(True)
Ejemplo n.º 10
0
    def test_add_one_individual_incomplete_population(self):
        base_creator = MixedRampedGauss()
        creator = IndividualSelection({Individual("1+1"): [0]}, base_creator)

        self.__fill_and_assert(fill_creator=creator,
                               expected_pop_indexes=[1],
                               expected_individuals={1: Individual("1+1")})
    def test_remove_population_to(self):
        mlc_repo = self.__get_new_repo()

        # add individuals
        mlc_repo.add_individual(Individual("(root (+ 1 1))"))
        mlc_repo.add_individual(Individual("(root (+ 2 2))"))
        mlc_repo.add_individual(Individual("(root (+ 3 3))"))
        mlc_repo.add_individual(Individual("(root (+ 4 4))"))
        mlc_repo.add_individual(Individual("(root (+ 5 5))"))

        # add  population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [1, 1, 1]
        mlc_repo.add_population(p)

        # add population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [2, 2, 2]
        mlc_repo.add_population(p)

        # add population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [3, 3, 3]
        mlc_repo.add_population(p)

        # add population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [4, 4, 4]
        mlc_repo.add_population(p)

        self.assertEqual(mlc_repo.count_population(), 4)

        # remove generations 1 to 2
        mlc_repo.remove_population_to(2)
        self.assertEqual(mlc_repo.count_population(), 2)

        p = mlc_repo.get_population(1)
        self.assertEqual(p._individuals, [3, 3, 3])

        p = mlc_repo.get_population(2)
        self.assertEqual(p._individuals, [4, 4, 4])

        # New generation must be number 3
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [5, 5, 5]
        mlc_repo.add_population(p)

        self.assertEqual(mlc_repo.count_population(), 3)

        p = mlc_repo.get_population(1)
        self.assertEqual(p._individuals, [3, 3, 3])

        p = mlc_repo.get_population(2)
        self.assertEqual(p._individuals, [4, 4, 4])

        p = mlc_repo.get_population(3)
        self.assertEqual(p._individuals, [5, 5, 5])
    def test_cut_generation(self):
        """
        Cut a generation using remove_population_from/remove_population_last
        :return:
        """
        mlc_repo = self.__get_new_repo()

        # add individuals
        mlc_repo.add_individual(Individual("(root (+ 1 1))"))
        mlc_repo.add_individual(Individual("(root (+ 2 2))"))
        mlc_repo.add_individual(Individual("(root (+ 3 3))"))
        mlc_repo.add_individual(Individual("(root (+ 4 4))"))
        mlc_repo.add_individual(Individual("(root (+ 5 5))"))

        # add  population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [1, 1, 1]
        mlc_repo.add_population(p)

        # add population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [2, 2, 2]
        mlc_repo.add_population(p)

        # add population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [3, 3, 3]
        mlc_repo.add_population(p)

        # add population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [4, 4, 4]
        mlc_repo.add_population(p)

        # add population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [5, 5, 5]
        mlc_repo.add_population(p)

        self.assertEqual(mlc_repo.count_population(), 5)

        # Cut population 4
        mlc_repo.remove_population_from(4 + 1)
        mlc_repo.remove_population_to(4 - 1)

        # remove unused individuals
        mlc_repo.remove_unused_individuals()

        self.assertEqual(mlc_repo.count_population(), 1)
        self.assertEqual(mlc_repo.count_individual(), 1)

        p = mlc_repo.get_population(1)
        self.assertEqual(p._individuals, [4, 4, 4])

        individual = mlc_repo.get_individual(4)
        self.assertEqual(individual.get_value(), "(root (+ 4 4))")
    def test_remove_population_to_clear_generations(self):
        mlc_repo = self.__get_new_repo()

        # add individuals
        mlc_repo.add_individual(Individual("(root (+ 1 1))"))
        mlc_repo.add_individual(Individual("(root (+ 2 2))"))
        mlc_repo.add_individual(Individual("(root (+ 3 3))"))
        mlc_repo.add_individual(Individual("(root (+ 4 4))"))
        mlc_repo.add_individual(Individual("(root (+ 5 5))"))

        # add  population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [1, 1, 1]
        mlc_repo.add_population(p)

        # add population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [2, 2, 2]
        mlc_repo.add_population(p)

        # add population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [3, 3, 3]
        mlc_repo.add_population(p)

        self.assertEqual(mlc_repo.count_population(), 3)

        # Remove all generations (1 to 3)
        mlc_repo.remove_population_to(3)
        self.assertEqual(mlc_repo.count_population(), 0)

        # Insert populations again
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [3, 3, 3]
        mlc_repo.add_population(p)

        # add population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [4, 4, 4]
        mlc_repo.add_population(p)

        # add population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [5, 5, 5]
        mlc_repo.add_population(p)

        self.assertEqual(mlc_repo.count_population(), 3)

        p = mlc_repo.get_population(1)
        self.assertEqual(p._individuals, [3, 3, 3])

        p = mlc_repo.get_population(2)
        self.assertEqual(p._individuals, [4, 4, 4])

        p = mlc_repo.get_population(3)
        self.assertEqual(p._individuals, [5, 5, 5])
Ejemplo n.º 14
0
    def test_crossover_same_level_4(self):
        individual_1 = Individual("(root S0)", Config.get_instance())
        individual_2 = Individual("(root S0)", Config.get_instance())

        try:
            new_ind_1, new_ind_2, _ = individual_1.crossover(individual_2)
            self.assertFalse(True,
                             "crossover with individual type 4 should fail")
        except OperationOverIndividualFail, ex:
            self.assertTrue(True)
Ejemplo n.º 15
0
    def test_generate_from_value(self):
        individual = Individual(
            "(root (exp (tanh (- (tanh -8.049) (* 9.15 -6.848)))))")

        self.assertEquals(
            individual.get_value(),
            "(root (exp (tanh (- (tanh -8.049) (* 9.15 -6.848)))))")
        self.assertEquals(individual.get_formal(),
                          "exp(tanh((tanh((-8.049)) - (9.15 .* (-6.848)))))")
        self.assertEquals(individual.get_complexity(), 20)
Ejemplo n.º 16
0
    def test_compare_random_individuals(self):
        individual_1 = Individual.generate(individual_type=3,
                                           config=Config.get_instance())

        RandomManager.clear_random_values()
        RandomManager.load_random_values(self._random_file)
        individual_2 = Individual.generate(individual_type=3,
                                           config=Config.get_instance())

        self.assertTrue(individual_1.compare(individual_2))
Ejemplo n.º 17
0
 def create(self, gen_size):
     MLCRepository.get_instance().add_individual(
         Individual("(root 1)"))
     MLCRepository.get_instance().add_individual(
         Individual("(root 2)"))
     MLCRepository.get_instance().add_individual(
         Individual("(root 3)"))
     MLCRepository.get_instance().add_individual(
         Individual("(root 4)"))
     MLCRepository.get_instance().add_individual(
         Individual("(root 5)"))
    def test_remove_from_population(self):
        mlc_repo = self.__get_new_repo()

        # add individuals
        mlc_repo.add_individual(Individual("(root (+ 1 1))"))
        mlc_repo.add_individual(Individual("(root (+ 2 2))"))
        mlc_repo.add_individual(Individual("(root (+ 3 3))"))
        mlc_repo.add_individual(Individual("(root (+ 4 4))"))

        # add first population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [1, 2, 1]
        mlc_repo.add_population(p)

        # add second population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [1, 2, 3]
        mlc_repo.add_population(p)

        # add third population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [1, 2, 4]
        mlc_repo.add_population(p)

        # remove last population
        mlc_repo.remove_population_from(2)

        # last generation must be removed
        self.assertEqual(mlc_repo.count_population(), 1)

        # first generation exists
        p = mlc_repo.get_population(1)
        self.assertEqual(p._individuals, [1, 2, 1])

        # all individuals exists and the third individual do not appear in any generation
        self.assertEqual(mlc_repo.count_individual(), 4)

        # remove unused individuals
        deleted = mlc_repo.remove_unused_individuals()
        self.assertEqual(deleted, 2)
        self.assertEqual(mlc_repo.count_individual(), 2)

        individual = mlc_repo.get_individual(1)
        self.assertEqual(individual.get_value(), "(root (+ 1 1))")

        individual = mlc_repo.get_individual(2)
        self.assertEqual(individual.get_value(), "(root (+ 2 2))")

        try:
            individual = mlc_repo.get_individual(3)
            self.assertTrue(False)
        except KeyError:
            self.assertTrue(True)
Ejemplo n.º 19
0
    def test_sensor_list(self):
        # save and restore original configuration
        with saved(Config.get_instance()):
            Config.get_instance().set("POPULATION", "sensor_list",
                                      "6,15,2,8,4,10")
            Config.get_instance().set("POPULATION", "sensors", "6")
            Config.get_instance().set("POPULATION", "sensor_spec", "true")
            Config.get_instance().set("POPULATION", "sensor_prob", "1.0")

            # test generate and mutate using sensor list
            individual = Individual.generate(individual_type=3,
                                             config=Config.get_instance())
            self.assertEqual(
                individual.get_value(),
                '(root (sin (/ (+ (exp S6) (cos S10)) (/ (log S10) (log S4)))))'
            )

            individual = Individual.generate(individual_type=3,
                                             config=Config.get_instance())
            self.assertEqual(
                individual.get_value(),
                '(root (exp (* (- (tanh S6) (tanh S10)) (- (/ S6 S6) (/ S6 S4)))))'
            )

            new_ind = self._individual_l2.mutate(
                Individual.MutationType.REMOVE_SUBTREE_AND_REPLACE)
            self.assertEqual(
                individual.get_value(),
                '(root (exp (* (- (tanh S6) (tanh S10)) (- (/ S6 S6) (/ S6 S4)))))'
            )

            new_ind = self._individual_l2.mutate(
                Individual.MutationType.REMOVE_SUBTREE_AND_REPLACE)
            self.assertEqual(
                individual.get_value(),
                '(root (exp (* (- (tanh S6) (tanh S10)) (- (/ S6 S6) (/ S6 S4)))))'
            )

            new_ind = self._individual_l2.mutate(
                Individual.MutationType.SHRINK)
            self.assertEqual(
                individual.get_value(),
                '(root (exp (* (- (tanh S6) (tanh S10)) (- (/ S6 S6) (/ S6 S4)))))'
            )

            new_ind = self._individual_l2.mutate(
                Individual.MutationType.SHRINK)
            self.assertEqual(
                individual.get_value(),
                '(root (exp (* (- (tanh S6) (tanh S10)) (- (/ S6 S6) (/ S6 S4)))))'
            )
    def test_reload_individuals_in_memory_loss_data(self):
        mlc_repo = self.__get_new_repo()

        # add individuals
        mlc_repo.add_individual(Individual("(root (+ 1 1))"))
        mlc_repo.add_individual(Individual("(root (+ 2 2))"))

        # add population
        p = Population(3, 0, Config.get_instance(), mlc_repo)
        p._individuals = [2, 1, 2]

        # reload mlc_repository using another instance
        mlc_repo = self.__get_new_repo()
        self.assertEqual(mlc_repo.count_individual(), 0)
        self.assertEqual(mlc_repo.count_population(), 0)
Ejemplo n.º 21
0
    def test_crossover_same_level_0(self):
        individual_1 = Individual("(root (cos 5.046))", Config.get_instance())
        individual_2 = Individual("(root (cos 5.046))", Config.get_instance())

        new_ind_1, new_ind_2, _ = individual_1.crossover(individual_2)

        self._assert_individual(new_ind_1,
                                complexity=4,
                                value="(root (cos 5.046))",
                                formal="cos(5.046)")

        self._assert_individual(new_ind_2,
                                complexity=4,
                                value="(root (cos 5.046))",
                                formal="cos(5.046)")
Ejemplo n.º 22
0
    def _fill_creation(self, individuals, index, type):
        while index < len(individuals):
            indiv = Individual.generate(individual_type=type,
                                        config=Config.get_instance())
            response = MLCRepository.get_instance().add_individual(indiv)

            if not response[1]:
                # The individual didn't exist
                indiv_number = individuals[index]

                lg.logger_.info('[FILL_CREATION] Generating individual N#' +
                                str(indiv_number))
                lg.logger_.debug('[FILL_CREATION] Individual N#' +
                                 str(indiv_number) + ' - Value: ' +
                                 indiv.get_value())

                # Call the preevaluation function if it exists and if it is configured
                if self._config.getboolean('EVALUATOR', 'preevaluation'):
                    callback = PreevaluationManager.get_callback().preev
                    if callback is not None:
                        if not callback(indiv):
                            lg.logger_.info(
                                '[FILL_CREATION] Preevaluation failed'
                                '. Individual value: ' + indiv.get_value())
                            continue

                self._individuals.append((index, response[0]))
                index += 1
            else:
                lg.logger_.debug('[FILL_CREATION] Replica created.')

        return index
Ejemplo n.º 23
0
    def test_generate_individuals_types(self):
        individual = Individual.generate(individual_type=0,
                                         config=Config.get_instance())
        self._assert_individual(
            individual,
            complexity=120,
            value=
            "(root (sin (+ (/ (cos -3.0973) (exp (log (* (* -1.3423 (tanh (log -3.5094))) (+ (/ (/ (* -9.1213 (cos (exp 3.6199))) (cos (* S0 (cos (- 5.0161 (sin 4.2656)))))) S0) (- (cos (* (+ (sin -9.8591) (exp S0)) -9.4159)) (log (* (- (tanh -8.5969) S0) (/ (exp (/ 8.2118 S0)) (* (* S0 (* 1.6755 -0.0699)) (log (exp -3.2288)))))))))))) S0)))",
            formal=
            "sin(((my_div(cos((-3.0973)),exp(my_log((((-1.3423) .* tanh(my_log((-3.5094)))) .* ((my_div((my_div(((-9.1213) .* cos(exp(3.6199))),cos((S0 .* cos((5.0161 - sin(4.2656))))))),S0)) + (cos(((sin((-9.8591)) + exp(S0)) .* (-9.4159))) - my_log(((tanh((-8.5969)) - S0) .* (my_div(exp((my_div(8.2118,S0))),((S0 .* (1.6755 .* (-0.0699))) .* my_log(exp((-3.2288))))))))))))))) + S0))"
        )

        individual = Individual.generate(individual_type=1,
                                         config=Config.get_instance())
        self._assert_individual(
            individual,
            complexity=24,
            value=
            "(root (- (sin (* (log -3.7260) (+ -5.0573 -6.2191))) (* 7.3027 (/ (cos S0) (* 4.7410 6.7097)))))",
            formal=
            "(sin((my_log((-3.7260)) .* ((-5.0573) + (-6.2191)))) - (7.3027 .* (my_div(cos(S0),(4.7410 .* 6.7097)))))"
        )

        individual = Individual.generate(individual_type=2,
                                         config=Config.get_instance())
        self._assert_individual(
            individual,
            complexity=15,
            value="(root (tanh (cos (+ (+ 5.4434 -3.1258) (+ S0 5.1136)))))",
            formal="tanh(cos(((5.4434 + (-3.1258)) + (S0 + 5.1136))))")

        individual = Individual.generate(individual_type=3,
                                         config=Config.get_instance())
        self._assert_individual(
            individual,
            complexity=18,
            value="(root (log (sin (+ (log -6.2620) (* 8.3709 -6.7676)))))",
            formal="my_log(sin((my_log((-6.2620)) + (8.3709 .* (-6.7676)))))")

        individual = Individual.generate(individual_type=4,
                                         config=Config.get_instance())
        self._assert_individual(individual,
                                complexity=1,
                                value="(root -0.6212)",
                                formal="(-0.6212)")
Ejemplo n.º 24
0
 def test_random_generate(self):
     individual = Individual.generate(individual_type=3,
                                      config=Config.get_instance())
     self.assertEquals(
         individual.get_value(),
         "(root (sin (/ (+ (exp -2.6118) (cos S0)) (/ (log 5.9383) (log -4.5037)))))"
     )
     self.assertEquals(
         individual.get_formal(),
         "sin((my_div((exp((-2.6118)) + cos(S0)),(my_div(my_log(5.9383),my_log((-4.5037)))))))"
     )
     self.assertEquals(individual.get_complexity(), 28)
Ejemplo n.º 25
0
    def setUp(self):
        set_logger("testing")

        # Load randoms from file
        random_file = './mlc/unit_matlab_randoms.txt'
        RandomManager.clear_random_values()
        RandomManager.load_random_values(random_file)

        config = Config.get_instance()
        config.read(
            os.path.join(mlc_config_path.get_test_path(),
                         'mlc/individual/configuration.ini'))

        self._individual_l0 = Individual("(root (cos 5.046))")
        self._individual_l1 = Individual(
            "(root (log (sin (exp (tanh 3.6284)))))")
        self._individual_l2 = Individual(
            "(root (cos (* (+ (* -1.912 -9.178) (cos S0)) 3.113)))")
        self._individual_l3 = Individual(
            "(root (log (/ (* (sin 4.37) (- -8.815 -3.902)) (log (+ 2.025 -8.685)))))"
        )
        self._individual_l4 = Individual("(root S0)")
Ejemplo n.º 26
0
    def __load_individuals(self):
        individuals = {}
        conn = self.__get_db_connection()
        cursor = conn.execute(stmt_get_all_individuals())

        for row in cursor:
            new_individual = Individual(str(row[1]),
                                        SQLSaveFormal.from_sql(row[2]), row[3])
            individuals[row[0]] = new_individual

        cursor.close()
        conn.commit()
        return individuals
Ejemplo n.º 27
0
    def test_crossover_same_level_2(self):
        individual_1 = Individual(
            "(root (cos (* (+ (* -1.912 -9.178) (cos S0)) 3.113)))",
            Config.get_instance())
        individual_2 = Individual(
            "(root (cos (* (+ (* -1.912 -9.178) (cos S0)) 3.113)))",
            Config.get_instance())
        new_ind_1, new_ind_2, _ = individual_1.crossover(individual_2)

        self._assert_individual(
            new_ind_1,
            complexity=8,
            value="(root (cos (* (* -1.912 -9.178) 3.113)))",
            formal="cos((((-1.912) .* (-9.178)) .* 3.113))")

        self._assert_individual(
            new_ind_2,
            complexity=18,
            value=
            "(root (cos (* (+ (+ (* -1.912 -9.178) (cos S0)) (cos S0)) 3.113)))",
            formal=
            "cos((((((-1.912) .* (-9.178)) + cos(S0)) + cos(S0)) .* 3.113))")
Ejemplo n.º 28
0
    def test_compare(self):
        individual_1 = Individual(
            "(root (exp (tanh (- (tanh -8.049) (* 9.15 -6.848)))))")
        individual_2 = Individual(
            "(root (exp (tanh (- (tanh -8.049) (* 9.15 -6.848)))))")
        self.assertTrue(individual_1.compare(individual_2))

        individual_different = Individual(
            "(root (cos (+ (sin (log -0.7648)) (exp (tanh 3.6284)))))")
        self.assertFalse(individual_1.compare(individual_different))
Ejemplo n.º 29
0
    def get_gen_creator(self):
        """
        Return an IndividualSelection creator if the user added individuals
        manually.
        Return None if this was not the case
        """
        if not self._individuals:
            logger.info("[FIRST_INDIV] No individual")
            return None

        gen_method = Config.get_instance().get('GP', 'generation_method')
        fill_creator = CreationFactory.make(gen_method)

        # Creat the dictionary of individuals
        indivs_dict = {}
        for index in xrange(len(self._individuals)):
            indiv = Individual(self._individuals[index])
            indivs_dict[indiv] = [index]

        return IndividualSelection(indivs_dict, fill_creator)
Ejemplo n.º 30
0
def test_individual_value(parent, experiment_name, log_prefix, indiv_value, config):
    try:
        """
        Evaluate an individual in order to check its correctness. Handle Exceptions
        """
        LispTreeExpr.check_expression(indiv_value)
        individual = Individual.generate(config=config,
                                         rhs_value=indiv_value)
        callback = EvaluatorFactory.get_callback()
        return callback.cost(individual)
    except ExprException, err:
        # Print the error message returned in the exception,
        # removing the prefix ([EXPR_EXCEPTION]])
        QMessageBox.critical(parent,
                             "Invalid Individual",
                             "Individual inserted is not well-formed. "
                             "Error Msg: {0}"
                             .format(err.message[err.message.find(']') + 2:]))
        logger.error("{0} Experiment {1} - "
                     "Individual inserted is not well-formed. "
                     "Error Msg: {2}"
                     .format(log_prefix, experiment_name,
                             err.message[err.message.find(']') + 2:]))