Exemple #1
0
	def next_generation(self, population):
		selection = Selection(deepcopy(population), strategy=SelectionStrategy.TOURNAMENT.value)
		mating = Mating(selection)
		crossover = Crossover(mating)

		for i, individual in enumerate(crossover.mating.selection.population.individuals):
			mutation = Mutation(individual)
			crossover.mating.selection.population.individuals[i] = mutation.mutate()

		print(f'Individuals: {len(self.individuals)}')
		print(f'New generation: {len(crossover.new_generation)}')
		return crossover.mating.selection.population
        # Select parents for offspring generation
        for ch in range(0, scored_population.__len__(), 1):
            # perform parent selection from scored population
            selection = Selection(population=scored_population)
            parents = selection.select()

            # perform crossover based on 50% probability
            crossover_prob = random.choice([True, False])
            crossover = Crossover(parents,
                                  crossover_probability=crossover_prob)
            offspring = crossover.perform_crossover()

            # perform mutation based on 50% probability
            mutation_prob = random.choice([True, False])
            mutation = Mutation(offspring, mutation_probability=mutation_prob)
            final_offspring = mutation.mutate()

            # add offspring to next generation
            next_gen_population.append(final_offspring)

        # Score next gen population
        scored_next_gen_population = []
        for chromosome in next_gen_population:
            fitness = Fitness(chromosome=chromosome, fitness_goal=fitness_goal)
            scored_next_gen_chromosome = fitness.calculate_fitness()
            scored_next_gen_population.append(scored_next_gen_chromosome)

        # Get generation best
        scored_next_gen_population.sort(key=lambda x: x[1])
        last_index = scored_next_gen_population.__len__() - 1
        best_of_generations.append(scored_next_gen_population[last_index])
Exemple #3
0
class GeneticAlgorithm(object):

    def __init__(self, population_size, sample_genotype, crossover_rate=0.6,
                 mutation_rate=0.2, maximize=True):
        self.population_size = population_size
        self.genotype = sample_genotype
        self.crossover_rate = crossover_rate
        self.mutation_rate = mutation_rate
        self.selector = RankSelector(maximize)
        self.crossover = OnePointCrossover()
        self.mutation = Mutation()
        self.generations = []
        self.maximize = maximize

    def evolve(self, fitness_obj=FitnessFunction, num_generations=10):
        # initialize population
        population = []
        for _ in range(self.population_size):
            chromosome = self.genotype.create_random_instance()
            population.append(chromosome)

        # process each generation
        for _ in range(num_generations):
            # track generations
            self.generations.append(population)
            next_population = []

            # calculate fitness for population
            for chromosome in population:
                chromosome.fitness = fitness_obj.evaluate(chromosome)

            # select parents for generation
            parents = self.selector.select_pairs(population=population)
            # perform crossover
            for parent in parents:
                do_crossover = random.random() < self.crossover_rate
                if do_crossover:
                    child_1, child_2 = self.crossover.recombine(
                        parent[0].genes,
                        parent[1].genes
                    )
                    chrom_child_1 = Chromosome(genes=child_1)
                    chrom_child_2 = Chromosome(genes=child_2)

                    # add new children to next population
                    next_population.append(chrom_child_1)
                    next_population.append(chrom_child_2)
                else:
                    # no crossover, add parents as is
                    next_population.append(parent[0])
                    next_population.append(parent[1])

            # do mutation
            do_mutation = random.random() < self.mutation_rate
            if do_mutation:
                next_population = self.mutation.mutate(self.genotype,
                                                       next_population)

            population = next_population

        # calculate fitness for last generation
        for chromosome in population:
            chromosome.fitness = fitness_obj.evaluate(chromosome)
        return population

    def best_individual(self, population):
        population.sort(key=lambda x: x.fitness, reverse=self.maximize)

        best_individual = population[0]

        fittest = dict()
        for i in range(len(best_individual.genes)):
            fittest[self.genotype.get_label_at(i)] = best_individual.genes[i]

        return fittest
Exemple #4
0
class GeneticAlgorithm(object):
    def __init__(self,
                 population_size,
                 sample_genotype,
                 crossover_rate=0.6,
                 mutation_rate=0.2,
                 maximize=True):
        self.population_size = population_size
        self.genotype = sample_genotype
        self.crossover_rate = crossover_rate
        self.mutation_rate = mutation_rate
        self.selector = RankSelector(maximize)
        self.crossover = OnePointCrossover()
        self.mutation = Mutation()
        self.generations = []
        self.maximize = maximize

    def evolve(self, fitness_obj=FitnessFunction, num_generations=10):
        # initialize population
        population = []
        for _ in range(self.population_size):
            chromosome = self.genotype.create_random_instance()
            population.append(chromosome)

        # process each generation
        for _ in range(num_generations):
            # track generations
            self.generations.append(population)
            next_population = []

            # calculate fitness for population
            for chromosome in population:
                chromosome.fitness = fitness_obj.evaluate(chromosome)

            # select parents for generation
            parents = self.selector.select_pairs(population=population)
            # perform crossover
            for parent in parents:
                do_crossover = random.random() < self.crossover_rate
                if do_crossover:
                    child_1, child_2 = self.crossover.recombine(
                        parent[0].genes, parent[1].genes)
                    chrom_child_1 = Chromosome(genes=child_1)
                    chrom_child_2 = Chromosome(genes=child_2)

                    # add new children to next population
                    next_population.append(chrom_child_1)
                    next_population.append(chrom_child_2)
                else:
                    # no crossover, add parents as is
                    next_population.append(parent[0])
                    next_population.append(parent[1])

            # do mutation
            do_mutation = random.random() < self.mutation_rate
            if do_mutation:
                next_population = self.mutation.mutate(self.genotype,
                                                       next_population)

            population = next_population

        # calculate fitness for last generation
        for chromosome in population:
            chromosome.fitness = fitness_obj.evaluate(chromosome)
        return population

    def best_individual(self, population):
        population.sort(key=lambda x: x.fitness, reverse=self.maximize)

        best_individual = population[0]

        fittest = dict()
        for i in range(len(best_individual.genes)):
            fittest[self.genotype.get_label_at(i)] = best_individual.genes[i]

        return fittest
Exemple #5
0
class Helix:
    def __init__(self, starthgt=11, endhgt=-9, spins=3.5, radius=1,
        speed=SPD_DEFAULT, spawn_rate=1, pair_generator=random_pair):
        self.starthgt = starthgt
        self.endhgt = endhgt
        self.spins = spins
        self.maxhgt = self.starthgt - (math.pi)*self.spins
        self.radius = radius
        self._animas = 0
        self._rungs = []
        self._tba = []
        self.speed = speed
        self.spdmod = 1
        self._last_rung = None
        self._last_ends = []
        self.spawn_rate = spawn_rate
        self.pair_generator = pair_generator
        self.mutation = Mutation()
        self.enter_callback = None
        self.exit_callback = None
        self.in_box = []
        
    def mutate(self, amt):
        self.mutation.mutate(amt)
        self.spdmod += amt * SPD_MUT_RATIO

    ### DO NOT USE
    def make_rung(self, next=None):
        rung = Rung(self, self.pair_generator())
        if next:
            rung.next = next
            self._last_rung.prev = rung
        self._rungs.append(rung)
        self._last_ends = rung
        self._last_rung = rung

    def obscure(self):
        map(Rung.obscure, self._rungs)

    def unobscure(self):
        map(Rung.unobscure, self._rungs)

    def register_callbacks(self, enter_callback, exit_callback):
        self.enter_callback = enter_callback
        self.exit_callback = exit_callback

    def update(self, dt):
        ## update the mutation
        self.mutation.update(dt)

        ## check to see if the last rung is far enough away for a new one
        if self._last_rung:
            if self._last_rung._hgt <= self.starthgt - self.spawn_rate:
                self.make_rung(self._last_rung)
        else:
            self.make_rung()

        ## compute the speed with mod -1.12 -> -1.3
        speed = self.speed*self.spdmod    
        #print "speed", speed

        ## update the mutation
        self.mutation.update(dt)

        ## check to see if the last rung is far enough away for a new one
        if self._last_rung:
            if self._last_rung._hgt <= self.starthgt - self.spawn_rate:
                self.make_rung(self._last_rung)
        else:
            self.make_rung()
            
        self.spdmod = max(self.spdmod - dt*SPD_DECAY, 1)
        ## compute the speed with mod -1.12 -> -1.3
        speed = self.speed*self.spdmod    

        for r in self._rungs:
            if r._hgt < -1.12 and r._hgt > -1.3:
                if not r.in_box:
                    r.in_box=True
                    if self.enter_callback:
                        self.enter_callback(r)
            if r.in_box and r._hgt < -1.3:
                r.in_box = False
                if self.exit_callback:
                    self.exit_callback(r)
            r.update(dt, speed)
            
        ## update and kill the rungs that have it coming :P
        dead = []
        for entity in self._rungs:
            if entity.dead:
                dead.append(entity)
        for e in dead:
            self._rungs.remove(e)