def selection(self): """ Selection of the best individuals as well as crossover. """ assert len(self.genomes) > 0, "No individuals for selection!" # Rank the genomes and select only half of them genomes_scores = [(g, g.get_score()) for g in self.genomes] # Normalize the score of each (fitness sharing) genomes_scores_norm = self.fitness_normalizer(genomes_scores) # Sort and take the best half genomes_scores_norm.sort(key=operator.itemgetter(1), reverse=True) genomes_scores_norm = genomes_scores_norm[0:len(genomes_scores_norm) // 2] new_genomes = [genome for (genome, _) in genomes_scores_norm] # Keep stats self.stats_aver_genome.append(self.get_average()) self.stats_best_genome.append(genomes_scores_norm[0][1]) # Crossover for i in range(len(genomes_scores_norm)): if len(new_genomes) >= self.N: break # Choose two parents randomly f = np.random.randint(0, (len(genomes_scores_norm) // 2) - 1) m = np.random.randint(0, (len(genomes_scores_norm) // 2) - 1) if f == m: m = (m + 1) % (len(genomes_scores_norm) // 2) # Sexy offspring = crossover(genomes_scores_norm[f][0], genomes_scores_norm[m][0]) # Happy birthday, kid! new_genomes.append(offspring) # Cut the tail! (i.e. if population size goes beyond N) if len(new_genomes) > self.N: new_genomes = new_genomes[0:self.N] self.genomes = new_genomes
def test_crossover(self): """ Tests crossover operation. Can only be verified manually. """ # Setup genome1 = Genome() genome1.initialize(3, 1) genome2 = Genome() genome2.initialize(3, 1) connections = [ Connection(1, 5), Connection(2, 5), Connection(3, 5), Connection(5, 4), Connection(2, 4), Connection(3, 4) ] connections[0].weight = 2 connections[1].weight = 3 connections[2].weight = 4 connections[3].weight = 5 connections[4].weight = 6 connections[5].weight = 7 genome2.connection_genes = connections genome1.add_score(25) genome2.add_score(25) # Run offspring = crossover(genome1, genome2) # Verify genome1_connections = genome1.get_connections() genome2_connections = genome2.get_connections() offspring_connections = offspring.get_connections() self.assertTrue(len(genome1_connections) + len(genome2_connections) >= len(offspring_connections))
def run_simulation(simulation, log=LOG): problem = simulation.get('problem') problem_parameters = simulation.get('problem_parameters', {}) population_size = problem_parameters.get('population_size') adult_selection = simulation.get('adult_selection_method') mate_selection = simulation.get('mate_selection_method') mate_selection_args = simulation.get('mate_selection_args', {}) crossover_rate = simulation.get('crossover_rate') crossover_method = simulation.get('crossover_method') n_children = simulation.get('n_children', 2) mutation_method = simulation.get('mutation_method') mutation_chance = simulation.get('mutation_rate') stop = simulation.get('stop', {}) stop_fitness = stop.get('fitness') stop_generation = stop.get('generation') # STEP 0: Initialize child genotype population population = [] children = [{'genotype': genotype} for genotype in problem.generate_initial_population(**problem_parameters)] average_fitnesses = [] sigmas = [] best_fitnesses = [] if log: print("Start simulation") pprint(simulation, indent=2) generation_number = 0 while True: generation_number += 1 # STEP 1: Development: Generate Phenotypes from Genotypes for individual in children: individual['phenotype'] = problem.geno_to_pheno(individual['genotype'], **problem_parameters) # STEP 2: Test Fitness of Phenotypes for individual in children: individual['fitness'] = problem.fitness_evaluation(individual['phenotype'], **problem_parameters) # STEP 3: Adult Selection population = adult_selection( old_population=population, children=children, m=population_size ) children = [] total_fitness = sum(f(x) for x in population) average_fitness = total_fitness / population_size deviations = ((f(x) - average_fitness) ** 2 for x in population) sigma = sqrt(sum(deviations) / population_size) best_individual = max(population, key=f) # STEP 4: Parent Selection pairs = mate_selection( population=population, sigma=sigma, average_fitness=average_fitness, **mate_selection_args ) # STEP 5: Reproduction mutation_func = lambda x: mutation_method(x, p=mutation_chance, **problem_parameters) for pair in pairs: new_genotypes = crossover( *pair, crossover_rate=crossover_rate, method=crossover_method, n_children=n_children ) # STEP 5.5: Mutation mutated_genotypes = map(mutation_func, new_genotypes) children.extend({'genotype': g} for g in mutated_genotypes) if log: print( ''' GENERATION {n} AVG:\t{avg_fitness} STD:\t{sigma} BEST:\t{best_fitness} {best_phenotype} ''' .format( n=generation_number, avg_fitness=average_fitness, sigma=sigma, best_phenotype=problem.phenotype_representation( best_individual['phenotype'], **problem_parameters ), best_fitness=best_individual['fitness'] ) ) average_fitnesses.append(average_fitness) sigmas.append(sigma) best_fitnesses.append(best_individual['fitness']) if stop_fitness and f(best_individual) >= stop_fitness: if log: print('FITNESS STOP') break elif stop_generation and generation_number >= stop_generation: if log: print('GENERATION STOP') break # Begin Next Generation return { 'simulation': simulation, 'generation_number': generation_number, 'average_fitnesses': average_fitnesses, 'sigmas': sigmas, 'best_fitnesses': best_fitnesses, 'final_population': population, 'final_best_individual': best_individual }
max_cost = -20000 #Determines original best file. Necessary for the tournament function to work correctly. count_list = 0 for cost in cost_matrix: if (cost > max_cost): max_cost = cost current_count = count_list count_list += 1 print 'Max Cost' print max_cost (single_mutation_list, double_mutation_list, crossover_list) = reproduction.method_of_reproduction( lattice_list, mutation_rate) file_exists = os.path.isfile('child_list.txt') if (file_exists == True): os.remove('child_list.txt') reproduction.crossover(crossover_list, input_data.region_map, input_data.rod_list) for i in xrange(len(single_mutation_list)): active_rods = reproduction.return_active_rod_list( single_mutation_list[i], input_data.region_map) reproduction.single_mutation(single_mutation_list[i], active_rods, input_data.region_map, input_data.rod_list) for i in xrange(len(double_mutation_list)): active_rods = reproduction.return_active_rod_list( double_mutation_list[i], input_data.region_map) reproduction.double_mutation(double_mutation_list[i], active_rods, input_data.region_map, input_data.rod_list) new_lattice_list = reproduction.extract_lattices('child_list.txt') os.system('rm batch_* info.dat* error.dat*') lattice_count = 0
def solver1(city, populationSize, meanNumHospitals, meanHospitalRange, numHospitalsStandardDeviation=5, hospitalRangeStandardDeviation=2, maxIterations=10000, convergenceCriteria=100, crossoverRatio=0.5, mutationRatio=0.5): print("Generating starting population..") generation = random_initializer.random_population(populationSize, meanNumHospitals, meanHospitalRange, city, numHospitalsStandardDeviation, hospitalRangeStandardDeviation) iterations = 0 convergence = 0 selector = Selector(populationSize) worst, mean, best, bestIndividual = getWorstMeanBest(generation) bestIndividual = copy.deepcopy(bestIndividual) iterationsResultDict = {} iterationsResultDict[iterations] = {'Best': best, 'Worst': worst, 'Mean': mean} f1 = open("report.txt", "w") iworst = None while iterations < maxIterations and convergence < convergenceCriteria: f1.write("iteration: {}\n".format(str(iterations + 1))) f1.write("population size = {}, best individual = {}\n" .format(str(len(generation)), str(bestIndividual))) if iworst is not None: f1.write("worst = {}, mean = {}, best = {}\n".format(str(iworst), str(imean), str(ibest))) f1.write("--------------------------------------------------------------------------------------\n") crossoverGeneration = [] parents = random.sample(generation, round(len(generation)*crossoverRatio)) for parent1 in parents: parent2 = random.choice(parents) #while parent2 == parent1 and len(parents) > 1: # parent2 = random.choice(parents) child1, child2 = reproduction.crossover(parent1, parent2) crossoverGeneration.append(child1) crossoverGeneration.append(child2) parents.remove(parent1) try: parents.remove(parent2) except: pass # mutation generated solutions mutatedGeneration = [] # for each solution a random float is generated to define if a mutated child will be generated for solution in generation: mutate = random.uniform(0, 1) if mutate <= mutationRatio: # if the solution has been selected for mutation then the mutation is randomly chosen mutationType = random.randint(1, 4) if mutationType == 1: mutatedGeneration.append(mutation.flip(solution, meanHospitalRange, hospitalRangeStandardDeviation)) elif mutationType == 2: mutatedGeneration.append( mutation.generative(solution, meanHospitalRange, hospitalRangeStandardDeviation)) elif mutationType == 3: mutatedGeneration.append(mutation.destructive(solution)) else: mutatedGeneration.append(mutation.swap(solution)) generation = selector.tournament(generation + crossoverGeneration + mutatedGeneration, 10) #generation = selector.roulette_method(generation + crossoverGeneration + mutatedGeneration) iworst, imean, ibest, ibestIndividual = getWorstMeanBest(generation) iterationsResultDict[iterations] = {'Best': ibest, 'Worst': iworst, 'Mean': imean} if ibest > best: best = ibest bestIndividual = copy.deepcopy(ibestIndividual) convergence = 0 if iterations % 10 == 0: print("iterations: " + str(iterations)) iterations = iterations + 1 convergence = convergence + 1 f1.close() return bestIndividual, iterationsResultDict