示例#1
0
def build_and_run(early_conv_avoid, mutation_rate, crossover_rate,
                  population_size, elitism_count, ga_type, chromo_type):
    ga = ga_type(elitism_count, mutation_rate, crossover_rate, population_size)
    population = Population()
    population.init_population(population_size, chromo_type)

    print(ga)
    print(early_conv_avoid)
    return run(ga, population, early_conv_avoid)
    def crossover(self, parents: List[Tuple[Chromosome]], pop_size: int) -> Population:
        """
        get list of parents to mate, return the new population

        NOTE: when population (size - elitism amount) doesn't divide in (offspring amount) then the remainder
         offsprings won't enter the new population.
        """
        new_population = Population()
        for chromosomes in parents:
            # do crossover with probability self.crossover_rate
            if random.random() < self.crossover_rate:
                offsprings = self.pair_chromosomes(chromosomes)
            else:
                offsprings = chromosomes  # [ch.__copy__() for ch in chromosomes]  # todo: maybe redundant
            for ch in offsprings:
                new_population.add_chromosome(ch)
                # if there are too many offsprings then stop adding them to population
                if new_population.get_size() == pop_size:
                    return new_population
    def selection(self, population: Population) -> List[Tuple[Chromosome]]:
        """
        select parents for crossover

        implements basic selection method: 1) create a pool of chromosomes, 2) select the amount needed for mating.
        """
        parents = []
        pairings = math.ceil(population.get_size() / self.get_offsprings_amount())
        self.set_selection_pool([ch for ch in population])
        for _ in range(pairings):
            parents.append(tuple([self.select() for _ in range(self.get_parents_amount())]))
        return parents
 def mutation(self, population: Population) -> Population:
     """  """
     new_pop = Population()
     for ch in population:
         new_pop.add_chromosome(self.mutate(ch))
     return new_pop
示例#5
0
def build_and_run(mutation_rate, crossover_rate, population_size,
                  elitism_count, ga_type, chromo_type):
    ga = ga_type(elitism_count, mutation_rate, crossover_rate, population_size)
    population = Population()
    population.init_population(population_size, chromo_type)
    return run(ga, population)
 def check_for_ec(self, gen: int, ga: GeneticAlgorithm,
                  population: Population):
     w = population.get_least_fit().get_fitness()
     b = population.get_fittest().get_fitness()
     return b - w < self.dist
 def check_for_ec(self, gen: int, ga: GeneticAlgorithm,
                  population: Population):
     f = population.get_fittest().get_fitness()
     m = mean(ch.get_fitness() for ch in population)
     return f - m < self.dist_from_avg