Пример #1
0
def test_offspring_returns_two_chromosomes_combining_parents():
    parents = [Chromosome.random(), Chromosome.random()]
    subject = Crossover(parents)
    result = subject.offspring()
    assert len(result) == 2
    assert isinstance(result[0], Chromosome)
    assert isinstance(result[1], Chromosome)
Пример #2
0
def test_offspring_returns_chromosomes_combining_parents(monkeypatch):
    parents = [
        Chromosome(np.array(list("XXXXXXXXXXXXXXXXXXXXXXXXXX"))),
        Chromosome(np.array(list("YYYYYYYYYYYYYYYYYYYYYYYYYY"))),
    ]
    subject = Crossover(parents)
    monkeypatch.setattr(subject, "pivot", 3)
    result = subject.offspring()
    assert result[0] == Chromosome(np.array(
        list("XXXYYYYYYYYYYYYYYYYYYYYYYY")))
    assert result[1] == Chromosome(np.array(
        list("YYYXXXXXXXXXXXXXXXXXXXXXXX")))
Пример #3
0
    def __init__(self, chromosome_list, population_size, route_size, crossover_probability, mutation_probability, random_population = False):
        self.route_size = route_size
        self.counter=0
        self.population_size = population_size
        self.crossover_probability = crossover_probability
        self.mutation_probability = mutation_probability
        self.chromosome_list = chromosome_list
        self.pop = []
        [self.pop.append(Route(route_size, chromosome_list, random_population, counter=self.counter)) for i in range(0, population_size)]

        self.selected = []
        self._selection = Selection(self)
        self._mutation = Mutation(self)
        self._crossover = Crossover(self)
Пример #4
0
    def minimize_objective(self):
        start_code = time.time()

        data_dict = dict()
        data_dict['max_fitness'] = []
        data_dict['max_fitness_chromosome'] = []

        population = InitialPopulation(
            objective_function=self.objective_function,
            population_size=self.population_size).generate_initial_population(
            )

        for iteration in range(self.n_iters):

            # If there is a timing limit and the stopwatch is greater than the timing limit then break
            if self.time_limit and self.time_limit <= self.stopwatch:
                break
            start_iteration = time.time()
            crossover_offspring = Crossover(
                population=population,
                percent_crossover=self.pct_crossover).perform_crossover()
            mutated_offspring = Mutation(
                population=population,
                percent_mutate=self.pct_mutation).perform_mutation()

            selection = TournamentSelection(
                final_population_size=self.population_size,
                input_population=population,
                mutated_offspring=mutated_offspring,
                crossover_offspring=crossover_offspring,
                objective_function=self.objective_function)

            population = selection.select_chromosomes()
            fitness = selection.chromosome_fitness(population)
            max_fitness = min(fitness)
            max_fit_chromosome = population[fitness.index(max_fitness)]

            data_dict['max_fitness'].append(max_fitness)
            data_dict['max_fitness_chromosome'].append(max_fit_chromosome)

            print("")
            print("Generation {}".format(iteration + 1))
            print("Max fitness: {}".format(max_fitness))
            print("Max fitness_chromosome: {}".format(max_fit_chromosome))

            end_iteration = time.time()
            self.stopwatch += end_iteration - start_iteration

        end_code = time.time()
        timing_code = end_code - start_code

        ga_ans = min(data_dict['max_fitness'])
        num_iters = len(data_dict['max_fitness'])

        percent_error = abs(self.solution - ga_ans) / self.solution * 100

        return ga_ans, percent_error, timing_code, num_iters, data_dict, data_dict[
            'max_fitness']
Пример #5
0
 def evolve_previous_generation(self):
     number_of_candidates_to_maintain = round(self.SIZE *
                                              self.etilism_percentage)
     next_generation = self.etilist_candidates()
     for _ in range(self.n_crossovers):
         parents = self.previous_generation.random_parents()
         offspring = Crossover(parents)()
         for chromosome in offspring:
             next_generation.append(chromosome.mutated())
     return Population(next_generation)
Пример #6
0
def test_call_returns_parents_if_must_not_crossover(monkeypatch):
    parents = [Chromosome.random(), Chromosome.random()]
    subject = Crossover(parents)
    monkeypatch.setattr(subject, "will_crossover_happen", lambda: False)
    assert subject() == parents
Пример #7
0
def test_will_crossover_happen_returns_false_if_random_is_greater_than_probability(
        random):
    parents = [Chromosome.random(), Chromosome.random()]
    subject = Crossover(parents, probability=0.8)
    random.return_value = 0.9
    assert not subject.will_crossover_happen()
Пример #8
0
def test_call_returns_crossed_over_if_must_crossover(monkeypatch):
    parents = [Chromosome.random(), Chromosome.random()]
    subject = Crossover(parents)
    monkeypatch.setattr(subject, "will_crossover_happen", lambda: True)
    assert subject() == subject.offspring()
Пример #9
0
class Population(list):

    def __init__(self, chromosome_list, population_size, route_size, crossover_probability, mutation_probability, random_population = False):
        self.route_size = route_size
        self.counter=0
        self.population_size = population_size
        self.crossover_probability = crossover_probability
        self.mutation_probability = mutation_probability
        self.chromosome_list = chromosome_list
        self.pop = []
        [self.pop.append(Route(route_size, chromosome_list, random_population, counter=self.counter)) for i in range(0, population_size)]

        self.selected = []
        self._selection = Selection(self)
        self._mutation = Mutation(self)
        self._crossover = Crossover(self)


    def calc_fitness(self):
        [i.calc_fitness() for i in self.pop]

    def remove_duplicates(self):
        lenpop = len(self.pop)
        x = self.pop
        xx = set(self.pop)
        lenset = len(xx)
        npop = []
        for i in xx:
            npop.append(i)
        self.pop= npop

    def normalize_fitness(self):
        all_fitness = 0
        n_fit = 0
        for i in self.pop:
            all_fitness += i.fitness

        for i in self.pop:
            i.n_fitness = i.fitness / all_fitness
        self.mean_fitness = all_fitness / len(self.pop)

    def sort_by_fitness(self):
        self.pop.sort(key=lambda x: x.fitness, reverse=False)

    def mutation(self, mutation_options):

        self._mutation.mutation(mutation_options)

    def selection__best_half(self, number_to_select=50):
        self._selection.best_half(number_to_select)

    def random_select(self, number_to_select=50):
        self._selection.random_select(number_to_select)

    def trn_select(self, tournament_members):
        self._selection.trn_select(tournament_members)

    def tournament_selection(self, tournament_size=5, number_to_select=50, choosen=[]):
        self._selection.tournament_selection(tournament_size, number_to_select, choosen)

    def crossover__random_points(self):
        self._crossover.random_points()

    def crossover_two_pointsof_crossing(self):
        self._crossover.two_points()

    def crossover_pointOfCross(self):
        self._crossover.one_point()