def permute_methods(runs: int): tour2 = Selection.Tournament(2) tour3 = Selection.Tournament(3) cyclic = Crossover.DictCrossover(Crossover.cyclicCrossover) pmx = Crossover.DictCrossover(Crossover.PMX) selections = [Selection.GoodRoulette, tour2.run, tour3.run] crossovers = [cyclic.run, pmx.run] reinsertions = [Selection.BestsInParentsAndChildren, Selection.Elitism] for select in selections: for crossover in crossovers: for reinsertion in reinsertions: GA.SELECT = select GA.CROSSOVER = crossover GA.REINSERTION = reinsertion logging.info(' METHODS') logging.info('Selection: %s', select.__doc__) logging.info( 'Crossover: %s', ' Cyclic ' if crossover == cyclic.run else ' PMX ') logging.info('Reinsertion: %s', reinsertion.__doc__) before = time.time() parallel_run(GA.StandardGA, runs) after = time.time() logging.info('TIME: %s\n', round(after - before, 2))
def ga_stuff(self): population = Initialization.initialize(population_size, lower_bound, upper_bound, self.degree + 1) best_forever = population[0].copy() for current_generation in range(generations): self.sort_population(population) best_of_generation = population[0].copy() best_forever = best_of_generation.copy() if self.mse(best_of_generation) < self.mse( best_forever) else best_forever Crossover.cross(population_size // 2, population, self.x, self.y) Mutation.mutate(population, current_generation, generations, depending_factor) return best_forever
def __init__(self, params): self.epochs = params['epochs'] self.Crossover = Crossover(params['crossover_type'], params['crossover_prob']) self.Population = Population(booth_function, params['population_size'], 2, -10, 10, params['population_precision']) self.Mutation = Mutation(params['mutation_type'], params['mutation_prob']) self.Inversion = Inversion(params['inversion_type'], params['inversion_prob']) self.Selection = Selection(params['selection_type'], params['selection_prob']) self.EliteStrategy = EliteStrategy(params['elite_prob'])
def main(self, option): overall_bestfit = [] print("Please enter the maximum number of runs:") maxruns = int(input()) print("Please enter desired number of generations: ") gens = int(input()) print("Enter Population size") self.population_size = int(input()) capacity = 30 run_fitnesses = [] best_ind = [] ks_run_values = [] ks_run_weights = [] ks_run_fitness = [] for run in range(int(maxruns)): # print("Run Number %i" % run) generation = self.createPopulation(self.population_size, self.len_of_ind) #print(generation) run_fitnesses.clear() ks_weights, ks_values = self.initKnapSackVals() ks_run_weights += [ks_weights] ks_run_values += [ks_values] ks_final_fitness = [] for gen in range(int(gens)): #print("---------------------------------------------------------------") fitness_values = fit.generation_fitness_func(generation) # KnapSack part of the problem ks_fitness = Knapsack.calc_fitness_dynamic( ks_weights, ks_values, generation, self.population_size, capacity) if option == "tournament": generation = select.tournament_select( generation, self.population_size) if option == "linear": generation = select.linear_rank_select( generation, fitness_values, self.population_size) if option == 'proportionate': generation = select.proportionate_selection( generation, fitness_values, self.population_size) generation = Crossover.random_crossover( generation, self.len_of_ind, self.population_size) generation = self.mutation(generation, self.pm) ks_fitness = Knapsack.calc_fitness_dynamic( ks_weights, ks_values, generation, self.population_size) ks_final_fitness = ks_fitness #print("Knapsack Fitness Values : \n{0}".format(ks_final_fitness)) ks_run_fitness += [ks_final_fitness] print("-----------------------------------") print("Knapsack Capacity is {}".format(capacity)) print("Weights over {} runs".format(maxruns)) for i in range(len(ks_run_weights)): print(ks_run_weights[i]) print("Values over {} runs".format(maxruns)) for i in range(len(ks_run_values)): print(ks_run_values[i]) print("Fitness over {} runs".format(maxruns)) for i in range(len(ks_run_fitness)): print(ks_run_fitness[i])
def GenerateOffspring(parents): offspring = [] while (len(offspring) != len(parents)): parentA, parentB = Selection.Selection(parents) childA, childB = Crossover.Crossover(parentA, parentB) childA = Mutation.Mutation(childA) childB = Mutation.Mutation(childB) offspring.append(childA) offspring.append(childB) return offspring
def run(self): """ :return: """ offspring = [] i = 0 while len(offspring ) < self.mating_pool_size: # 2 parents -> 2 individuals p1 = self.parents[i] p2 = self.parents[i + 1] # crossover ################################################################################################ # print("crossover...") if random.random() < self.xover_rate: # off1, off2 = Crossover.COWGC(p1, p2, city_map) off1 = Crossover.order_crossover(p1, p2, city_map) off2 = Crossover.order_crossover(p1, p2, city_map) else: off1 = copy.copy(p1) off2 = copy.copy(p2) # print("crossover end") # mutation ################################################################################################# # print("Mutation...") if random.random() < self.mut_rate: off1 = Mutation.WGWWGM(p1, city_map) # off1 = Mutation.IRGIBNNM_mutation(p1, city_map) # off1 = Mutation.inversion_mutation(p1, city_map) if random.random() < self.mut_rate: off2 = Mutation.WGWWGM(p2, city_map) # off2 = Mutation.IRGIBNNM_mutation(p2, city_map) # off2 = Mutation.inversion_mutation(p2, city_map) # print("Mutation end") offspring.append(off1) offspring.append(off2) # print(len(offsprings)) i += 2 q.put(offspring) print('end')
def run(self): """ :return: """ offspring = [] i = 0 while len(offspring) < self.mating_pool_size: # 2 parents -> 2 individuals p1 = self.parents[i] p2 = self.parents[i + 1] # crossover ################################################################################################ # print("crossover...") if random.random() < self.xover_rate: # off1, off2 = Crossover.COWGC(p1, p2, city_map) off1 = Crossover.order_crossover(p1, p2, city_map) off2 = Crossover.order_crossover(p1, p2, city_map) else: off1 = copy.copy(p1) off2 = copy.copy(p2) # print("crossover end") # mutation ################################################################################################# # print("Mutation...") if random.random() < self.mut_rate: off1 = Mutation.WGWWGM(p1, city_map) # off1 = Mutation.IRGIBNNM_mutation(p1, city_map) # off1 = Mutation.inversion_mutation(p1, city_map) if random.random() < self.mut_rate: off2 = Mutation.WGWWGM(p2, city_map) # off2 = Mutation.IRGIBNNM_mutation(p2, city_map) # off2 = Mutation.inversion_mutation(p2, city_map) # print("Mutation end") offspring.append(off1) offspring.append(off2) # print(len(offsprings)) i += 2 q.put(offspring) print('end')
def initialIndividuals(self, constants): """ Creates the initial random population. Parameters: -``constants``: Config settings for the EA from the config files specified at run time """ for i in range(constants["popSize"]): if "initialCrossoverLength" in constants: cross = Crossover.Crossover( constants["initialCrossoverLength"]) else: print "ERR: initial crossover length not specified for SCX support population" individual = Individual([], i, cross) self.id = i yield individual self.individuals.append(individual)
def initialIndividuals(self, constants): """ Creates the initial population of random individuals. Parameters: -``constants``: Config settings for the EA from the config files specified at run time """ for i in range(constants["popSize"]): if "initialCrossoverLength" in constants: cross = Crossover.Crossover( constants["initialCrossoverLength"]) else: cross = None individual = Individual( self.geneType.randomGenome(constants["dimensions"]), i, cross) self.id = i yield individual self.individuals.append(individual)
def gen_report_individual(individual,dic_notas,dic_horarios): dataframe=an.create_dataframe(individual) print(dataframe) score=schdl_value(individual,dic_notas,dic_horarios) print("VALOR: "+str(score)) genotype=Crossover.create_genotype(individual) materias=[] for gen in genotype: info=gen.split("-") materia=info[0] if materia not in materias: paralelo=info[2] profesor=dic_horarios[materia][str(paralelo)]["Profesor"] rank=get_rank(profesor,materia,dic_notas) nota=np.mean(np.array(dic_notas[materia][profesor])) print("MATERIA: "+materia) print("PROFESOR: "+profesor) print("RANGO: "+str(rank)) print("NOTA: "+str(nota)) print("▀"*30) materias.append(materia)
def main(): western29 = "Cities/TSP_WesternSahara_29.txt" uruguay734 = "Cities/TSP_Uruguay_734.txt" canada4663 = "Cities/TSP_Canada_4663.txt" popsize = 2000 mating_pool_size = 300 tournament_size = 3 mut_rate = 0.2 xover_rate = 0.9 gen_limit = 100 advanced_Canada = { "description": { "instance_name": "none", "algorithm": "none", "city_all": 4663, "generation_all": gen_limit }, "evolutions": [ # nothing yet ] } advanced_Uruguay = { "description": { "instance_name": "none", "algorithm": "none", "city_all": 734, "generation_all": gen_limit }, "evolutions": [ # nothing yet ] } advanced_WesternSahara = { "description": { "instance_name": "none", "algorithm": "none", "city_all": 29, "evolution_all": 10, "generation_all": gen_limit, "generation_size": mating_pool_size }, "evolutions": [ # nothing yet ] } print(json.dumps(advanced_WesternSahara)) for evo in range(10): # Experiment # construct a trial # trial = [[{"time_cost": 0}]] print("trial", evo + 1) # t = time.time() print("Preparing for the information...") c = CityMap.CityMap(western29) city_map = c.city_map print("preparation end.") gen = 0 print("Initialize population...") init = Initialization.Population(popsize, city_map) init.evalPopulation() print("Initialization end.") # Evolution ######################################################################################################## while gen < gen_limit: # parent selection --------------------------------------------------------------------------------------------- #print("parent selection...") parents = Selection.tournament_selection(init.population[1:], mating_pool_size, tournament_size) #print("parent selection end.") offsprings = [] i = 0 while len(offsprings ) < mating_pool_size: # 2 parents -> 2 individuals p1 = parents[i] p2 = parents[i + 1] # crossover ------------------------------------------------------------------------------------------------ #print("crossover...") if random.random() < xover_rate: #off1, off2 = Crossover.COWGC(p1, p2, city_map) off1 = Crossover.order_crossover(p1, p2, city_map) off2 = Crossover.order_crossover(p1, p2, city_map) else: off1 = copy.copy(p1) off2 = copy.copy(p2) #print("crossover end") # mutation ------------------------------------------------------------------------------------------------- #print("Mutation...") if random.random() < mut_rate: off1 = Mutation.WGWWGM(p1, city_map) #off1 = Mutation.IRGIBNNM_mutation(p1, city_map) #off1 = Mutation.inversion_mutation(p1, city_map) if random.random() < mut_rate: off2 = Mutation.WGWWGM(p2, city_map) #off2 = Mutation.IRGIBNNM_mutation(p2, city_map) #off2 = Mutation.inversion_mutation(p2, city_map) #print("Mutation end") offsprings.append(off1) offsprings.append(off2) #print(len(offsprings)) i += 2 # survial selection -------------------------------------------------------------------------------------------- #print("survival selection") init.population[1:] = Selection.mu_plus_lambda( init.population[1:], offsprings) #print("survival selection end") init.evalPopulation() print("generation:", gen, " Average length:", init.AverageLength, " Longest length: ", init.worstTour.length, " shortest length:", init.bestTour.length) # construct a generation # generation = { "best-individual-sequence": init.bestTour.tour, "best-individual-distance": init.bestTour.length, "worst-individual-sequence": init.worstTour.tour, "worst-individual-distance": init.worstTour.length, "average-distance": init.AverageLength, "individual-distances": [round(distance.length) for distance in init.population ] # distance.length for distance in init.population } trial.append(generation) gen += 1 advanced_WesternSahara["evolutions"].append(trial) print("time cost:", time.time()) # here processing generating json file ############################################################################# output_file = open("advanced_WesternSahara.js", "w") output_file.write("let advanced_WesternSahara = ") output_file.write(json.dumps(advanced_WesternSahara)) output_file.close()
#parent selection #print("parent selection...") parents = Selection.tournament_selection(init.population[1:], mating_pool_size, tournament_size) #print("parent selection end.") offsprings = [] i = 0 while len(offsprings) < mating_pool_size: # 2 parents -> 2 individuals p1 = parents[i] p2 = parents[i + 1] # crossover ################################################################################################ #print("crossover...") if random.random() < xover_rate: #off1, off2 = Crossover.COWGC(p1, p2, city_map) off1, off2 = Crossover.order_crossover(p1, p2, city_map) else: off1 = copy.copy(p1) off2 = copy.copy(p2) #print("crossover end") # mutation ################################################################################################# #print("Mutation...") if random.random() < mut_rate: off1 = Mutation.WGWWGM(p1, city_map) #off1 = Mutation.WGWRGM(p1, city_map) #off1 = Mutation.IRGIBNNM_mutation(p1, city_map) #off1 = Mutation.inversion_mutation(p1, city_map) if random.random() < mut_rate: off2 = Mutation.WGWWGM(p2, city_map) #off2 = Mutation.WGWRGM(p2, city_map)
def main(): western29 = "Cities/TSP_WesternSahara_29.txt" uruguay734 = "Cities/TSP_Uruguay_734.txt" canada4663 = "Cities/TSP_Canada_4663.txt" popsize = 500 mating_pool_size = 100 tournament_size = 3 mut_rate = 0.2 xover_rate = 0.9 gen_limit = 500 print("Preparing for the information...") c = CityMap.CityMap(uruguay734) city_map = c.city_map print("preparation end.") gen = 0 print("Initialize population...") init = Initialization.Population(popsize, city_map) init.evalPopulation() print("Initialization end.") #EA algorithm while gen < gen_limit: #parent selection #print("parent selection...") parents = Selection.tournament_selection(init.population[1:], mating_pool_size, tournament_size) #print("parent selection end.") offsprings = [] i = 0 while len(offsprings) < mating_pool_size: # 2 parents -> 2 individuals p1 = parents[i] p2 = parents[i + 1] # crossover ################################################################################################ #print("crossover...") if random.random() < xover_rate: #off1, off2 = Crossover.COWGC(p1, p2, city_map) off1, off2 = Crossover.order_crossover(p1, p2, city_map) else: off1 = copy.copy(p1) off2 = copy.copy(p2) #print("crossover end") # mutation ################################################################################################# #print("Mutation...") if random.random() < mut_rate: off1 = Mutation.WGWWGM(p1, city_map) #off1 = Mutation.WGWRGM(p1, city_map) #off1 = Mutation.IRGIBNNM_mutation(p1, city_map) #off1 = Mutation.inversion_mutation(p1, city_map) if random.random() < mut_rate: off2 = Mutation.WGWWGM(p2, city_map) #off2 = Mutation.WGWRGM(p2, city_map) #off2 = Mutation.IRGIBNNM_mutation(p2, city_map) #off2 = Mutation.inversion_mutation(p2, city_map) #print("Mutation end") offsprings.append(off1) offsprings.append(off2) #print(len(offsprings)) i += 2 # survial selection ############################################################################################ #print("survival selection") init.population[1:] = Selection.mu_plus_lambda(init.population[1:], offsprings) #print("survival selection end") init.evalPopulation() print("generation:", gen, " Average length:", init.AverageLength, " Longest length: ", init.worstTour.length, " shortest length:", init.bestTour.length) gen += 1
# combined = "" # for j in range(0, len(target)): # combined = combined.join(population[i]) # # print("COMBINED IS") # # print(combined) # if (combined == target): # print("Its Done!") # sys.exit() f = Fitness.Fitness(population) fitness = f.getFitness() s = Selection.Selection(fitness) firstChoice, secondChoice, maximum = s.selectFromPop() c = Crossover.Crossover(population, firstChoice, secondChoice) population = c.crossover() m = Mutation.Mutation(population, 10) population = m.mutate() if (catch == 1): print( "--------------------------------------------------------------------" ) print("Program is finished!") print( "--------------------------------------------------------------------" ) print("Final fitness: ")
class Algorithm: def __init__(self, params): self.epochs = params['epochs'] self.Crossover = Crossover(params['crossover_type'], params['crossover_prob']) self.Population = Population(booth_function, params['population_size'], 2, -10, 10, params['population_precision']) self.Mutation = Mutation(params['mutation_type'], params['mutation_prob']) self.Inversion = Inversion(params['inversion_type'], params['inversion_prob']) self.Selection = Selection(params['selection_type'], params['selection_prob']) self.EliteStrategy = EliteStrategy(params['elite_prob']) def fill_selected_population(self, selected): new_pop = [] pop_size = self.Population.population_size for _ in range(pop_size): new_pop.append(random.choice(selected)) return np.array(new_pop) def run(self): best_value = [] avg_value = [] std_avg_value = [] best_individual = [] pop = self.Population.generate_population() time_start = time.time() for i in range(self.epochs): # print(i) # dla kazdej epoki # ocen populacje (evaluate) fitness = self.Population.evaluate_population(pop) # zapisz wartosci do wygenerowania wykresow best_value.append(fitness.min()) avg_value.append(fitness.mean()) std_avg_value.append(fitness.std()) index_best = fitness.argsort()[0] best_individual.append( self.Population.decode_population(pop)[index_best]) # zapisz % najlepszych (strategia elitarna) elite = self.EliteStrategy.elite(pop, fitness) # wybierz gatunki do crossowania (selection) selected, not_selected = self.Selection.select(pop, fitness) # krzyzowanie gatunków (cross) if self.Selection.decision != 'roulette_wheel': selected = self.fill_selected_population(selected) pop = self.Crossover.cross(selected) # mutacja i/lub inversja pop = self.Mutation.mutate(pop) pop = self.Inversion.inverse(pop) # jezeli strategia elitarna jest uzywana if elite.shape[0] != 0: # polacz najlepszy % z populacja pop = np.concatenate( (pop[:-elite.shape[0]], elite)) # , axis=0 time_execution = time.time() - time_start # print(f"Algorytm zajął {time_execution:.3f} sekund") Plot.draw_save_plot( best_value, 'Numer epoki', 'Wartość funkcji', 'Wykres wartości funkcji dla najlepszych osobników', 'best_individual') Plot.draw_save_plot(avg_value, 'Numer epoki', 'Wartość funkcji', 'Wykres średniej wartości funkcji dla populacji', 'avg_pop') Plot.draw_save_plot(std_avg_value, 'Numer epoki', 'Wartość odchylenia standardowego', 'Wykres odchylenia standardowego dla populacji', 'avg_std_pop') Files.numpy_to_csv(best_individual, 'best_individual.csv') return time_execution, best_value[-1]
mutation = Mutation.Mutation('mut_Tepl') populationGen = Population.Population('generate_new_population_Tepl') bga = BasicGeneticAlgorithm.BasicGeneticAlgorithm(generator=genPopulation_Tepl, fitness=fitness, mutation=mutation, sizeOfPopulation=10, genPopulation=populationGen, numberChromosome=NN, epoche=100, data=data) ans = bga.fit() print(ans)""" data = GenMtrx_NN() # инициализация условий задачи (считывание матрицы расстояний) NN = len(data) # считываем количество городов fitness = Fitness.Fitness('fitness_population_NN') crossover = Crossover.Crossover('crossover_NN') # Можно выбрать: inbreeding_NN, # outbreeding_NN # panmixia_NN # tournament_selection_NN # roulette_selection_NN selection = Selection.Selection('inbreeding_NN') mutation = Mutation.Mutation('insertion_deleting_mutation_NN') populationGen = Population.Population('elite_selection') bga = BasicGeneticAlgorithm.BasicGeneticAlgorithm(generator=genPopulation_NN, fitness=fitness, crossover=crossover, selection=selection, mutation=mutation, sizeOfPopulation=100, genPopulation=populationGen,
def generator(self, constants, supports=None): """ Carries out the standard evolutionary process of parent selection, evolution, and survivor selection. Parameters: -``constants``: Config settings for the EA from the config files specified at run time """ supportIndividual = None for individual in self.initialIndividuals(constants): if "MutationCoPopulation" not in constants["supportPopulations"]: # TODO Explain ranging SAfix = GeneTypes.FLT(0.001, constants["mutationStepSize"]) individual.stepSizes = SAfix.randomGenome( constants["dimensions"]) yield individual, None while True: if constants["logAvgFitness"]: print self.getAvgFitness() #print "generation" parents = self.parentSelection( self.individuals, constants["offSize"] * constants["parentsPerChild"], constants) for i in range(0, len(parents), constants["parentsPerChild"]): family = parents[i:i + constants["parentsPerChild"]] child = Individual(id=id) child.parents = [parent for parent in family] self.id += 1 #self.crossover(child, family, constants) supportIndividuals = list() if "MutationCoPopulation" in constants["supportPopulations"]: mutationSupportIndividual = supports[MutationCoPopulation]( ) #mutationSupport() rates = mutationSupportIndividual.genes supportIndividuals.append(mutationSupportIndividual) """ for r in rates: if r != constants["mutationStepSize"]: print "rates changed after creation" """ #print "mutation created" elif "MutationCoPopulation" not in constants[ "supportPopulations"]: bias = 1 / math.sqrt( 2.0 * constants["dimensions"]) * random.gauss(0, 1) tau = 1 / math.sqrt( 2.0 * math.sqrt(constants["dimensions"])) child.stepSizes = [ (sum(psteps) / len(psteps)) * math.exp(bias + tau * random.gauss(0, 1)) for psteps in zip(*[f.stepSizes for f in family]) ] SAfix.fix(child.stepSizes) rates = child.stepSizes if "SCXCoPopulation" in constants["supportPopulations"]: crossoverSupportIndividual = supports[SCXCoPopulation]( ) #crossoverSupport() #print len(crossoverSupportIndividual.crossover.genes) Crossover.scxFromSupport(child, parents, crossoverSupportIndividual, constants) #print len(crossoverSupportIndividual.crossover.genes) supportIndividuals.append(crossoverSupportIndividual) #print "crossover created" elif "SCXCoPopulation" not in constants["supportPopulations"]: self.crossover(child, family, constants) #print len(child.crossover.genes) if constants["SuCoLevel"] == "Static": rates = constants["stepSizes"] """ for r in rates: if r != constants["mutationStepSize"]: print "rates changed" """ self.mutation(child, constants, rates) self.geneType.fix(child.genes) yield child, supportIndividuals self.individuals.append(child) self.individuals = self.survivorSelection(self.individuals, constants["popSize"], constants)
def generator(self, constants, supports=None): """ Carries out the standard evolutionary process of parent selection, evolution, and survivor selection. Parameters: -``constants``: Config settings for the EA from the config files specified at run time """ supportIndividual = None for individual in self.initialIndividuals(constants): if "MutationCoPopulation" not in constants["supportPopulations"]: # TODO Explain ranging SAfix = GeneTypes.FLT(0.001, constants["mutationStepSize"]) individual.stepSizes = SAfix.randomGenome(constants["dimensions"]) yield individual, None while True: if constants["logAvgFitness"]: print self.getAvgFitness() #print "generation" parents = self.parentSelection(self.individuals, constants["offSize"] * constants["parentsPerChild"], constants) for i in range(0, len(parents), constants["parentsPerChild"]): family = parents[i:i + constants["parentsPerChild"]] child = Individual(id=id) child.parents = [parent for parent in family] self.id += 1 #self.crossover(child, family, constants) supportIndividuals = list() if "MutationCoPopulation" in constants["supportPopulations"]: mutationSupportIndividual = supports[MutationCoPopulation]() #mutationSupport() rates = mutationSupportIndividual.genes supportIndividuals.append(mutationSupportIndividual) """ for r in rates: if r != constants["mutationStepSize"]: print "rates changed after creation" """ #print "mutation created" elif "MutationCoPopulation" not in constants["supportPopulations"]: bias = 1 / math.sqrt(2.0 * constants["dimensions"]) * random.gauss(0, 1) tau = 1 / math.sqrt(2.0 * math.sqrt(constants["dimensions"])) child.stepSizes = [(sum(psteps) / len(psteps)) * math.exp(bias + tau * random.gauss(0, 1)) for psteps in zip(*[f.stepSizes for f in family])] SAfix.fix(child.stepSizes) rates = child.stepSizes if "SCXCoPopulation" in constants["supportPopulations"]: crossoverSupportIndividual = supports[SCXCoPopulation]() #crossoverSupport() #print len(crossoverSupportIndividual.crossover.genes) Crossover.scxFromSupport(child, parents, crossoverSupportIndividual, constants) #print len(crossoverSupportIndividual.crossover.genes) supportIndividuals.append(crossoverSupportIndividual) #print "crossover created" elif "SCXCoPopulation" not in constants["supportPopulations"]: self.crossover(child, family, constants) #print len(child.crossover.genes) if constants["SuCoLevel"] == "Static": rates = constants["stepSizes"] """ for r in rates: if r != constants["mutationStepSize"]: print "rates changed" """ self.mutation(child, constants, rates) self.geneType.fix(child.genes) yield child, supportIndividuals self.individuals.append(child) self.individuals = self.survivorSelection(self.individuals, constants["popSize"], constants)
def main(): western29 = "Cities/TSP_WesternSahara_29.txt" uruguay734 = "Cities/TSP_Uruguay_734.txt" canada4663 = "Cities/TSP_Canada_4663.txt" popsize = 500 mating_pool_size = 100 tournament_size = 3 mut_rate = 0.2 xover_rate = 0.9 gen_limit = 15 print("Preparing information...") c = CityMap.CityMap(western29 ) city_map = c.city_map print("preparation end.") gen = 0 init = Initialization.Population(popsize, city_map) population = init.population #EA algorithm while gen < gen_limit: #parent selection #print("parent selection...") parents = Selection.tournament_selection(population, mating_pool_size, tournament_size) #print("parent selection end.") offsprings = [] i = 0 while len(offsprings) < mating_pool_size: p1 = parents[i][0] p2 = parents[i + 1][0] #crossover #print("crossover...") if random.random() < xover_rate: off1, off2 = Crossover.COWGC(p1, p2, city_map) else: off1 = copy.copy(p1) off2 = copy.copy(p2) #print("crossover end") #mutation #print("Mutation...") if random.random() < mut_rate: off1 = Mutation.WGWWGM(p1, city_map) if random.random() < mut_rate: off2 = Mutation.WGWWGM(p2, city_map) #print("Mutation end") offsprings.append([off1, off1.fitness]) offsprings.append([off2, off2.fitness]) i += 2 #survial selection #print("survival selection") population = Selection.mu_plus_lambda(population, offsprings) #print("survival selection end") best_fitness = population[0][1] best_tour = population[0][0].tour tour_length = population[0][0].length for i in population: if i[0].length < tour_length: best_fitness = i[1] best_tour = i[0].tour tour_length = i[0].length print("generation: ", gen, " best fitness: ", best_fitness, " length: ", tour_length) gen += 1
with open(horarios_path) as hr: dic_horarios = js.load(hr) with open(notas_path) as nt: dic_notas = js.load(nt) ################################################################################ population_1 = Initialice.gen_random_population( dic_horarios, cfg.population_size) prev_pop = population_1 cant_mat = len(dic_horarios.keys()) for i in range(cfg.amount_of_generations): print("generacion "+str(i)) partners = Selection.selec_partners(prev_pop, dic_notas, dic_horarios) new_pop = Crossover.mating(partners, dic_horarios, cant_mat) prev_pop = new_pop ############################################################################## fitness_in = Selection.fitness_info(prev_pop, dic_notas, dic_horarios) ############################################################################# best_fit, mean_fit, max_tv, mean_tv, max_gap, mean_gap, max_conflicts, mean_conflicts, max_dis, mean_dis, best_indv = fitness_in strng = "" for element in fitness_in[:-1]: strng = strng+str(element)+"," fina_strng = str(i)+","+strng[:-1]+"\n" ar = open(info_dir, "a+") ar.write(fina_strng) ar.close() if best_fit > alltime_best_score: alltime_best_inidvidual = best_indv
def main(self, option): overall_bestfit = [] print("Please enter the maximum number of runs:") maxruns = int(input()) print("Please enter desired number of generations: ") gens = int(input()) print("Enter Population size") self.population_size = int(input()) run_fitnesses = [] best_ind = [] for run in range(int(maxruns)): # print("Run Number %i" % run) generation = self.createPopulation(self.population_size, self.len_of_ind) print(generation) run_fitnesses.clear() for gen in range(int(gens)): print( "---------------------------------------------------------------" ) #Genetic Algorithm part x1, x2, x3 = self.extract_genes(generation) fit_value = fit.calc_fitness_value(x1, x2, x3) run_fitnesses.append(fit_value) fitness_values = fit.generation_fitness_func(generation) if option == "tournament": generation = select.tournament_select( generation, self.population_size) if option == "linear": generation = select.linear_rank_select( generation, fitness_values, self.population_size) if option == 'proportionate': generation = select.proportionate_selection( generation, fitness_values, self.population_size) generation = Crossover.random_crossover( generation, self.len_of_ind, self.population_size) generation = self.mutation(generation, self.pm) bor, vector = analyze.best_of_run(generation, run_fitnesses) self.best_of_runs += [bor] self.best_individuals += vector print("Best of run is %i" % bor) if self.exec_start == 0: overall_bestfit = bor self.exec_start = 1 if bor < overall_bestfit: overall_bestfit = bor print("Best fitness over all runs is %i" % overall_bestfit) avg = analyze.mean(run_fitnesses) print("Average of all runs is %f" % avg) print("Best of run values:") print(self.best_of_runs) print("Standard deviation from {0} independent runs is {1}".format( maxruns, np.std(self.best_of_runs))) print("Best individuals: ") for each in range(len(self.best_individuals)): print(self.best_individuals[each])
def EA_Loop(scaling, p_selection, adult_alg, Choose_problem, z, s, pop_size, generation_limit, NSplits, Crossover_rate, mutation_rate, bit_length): # Initialise first child pool. mutate to pheno. fitness calc. # --- Initialise population with random candidate solutions. children = [] survivors = [] parents = [] if Choose_problem == 0: print("Solving the One Max problem") goal = None for i in range(pop_size): survivors.append(OM.individual(bit_length, mutation_rate, goal)) elif Choose_problem == 1: #print("Solving the LOLZ-prefix problem") for i in range(pop_size): survivors.append(LOLZ.individual(bit_length, z, mutation_rate)) elif Choose_problem == 2: print("Solving Locally Surprising Sequences") for i in range(pop_size * 10): survivors.append(SS.individual(bit_length, s, mutation_rate, False)) else: print("Solving Globally Surprising Sequences") for i in range(pop_size): survivors.append(SS.individual(bit_length, s, mutation_rate, True)) # --- Initialize generation count. Ngenerations = 1 # --- Find best individual in population. best_individual = find_best_individual(survivors) # Plot the best score in each generation plotting = [best_individual.fitness] plotting2 = [calculate_avg_std(survivors)[0]] #print("#", Ngenerations, " --- Best individual:\n", "Fitness: ", best_individual.fitness, "Genotype: ", best_individual.genotype) # --- Run as long as the best individual has fitness below 1. while (best_individual.fitness < 1.0 and Ngenerations < generation_limit): # --- Update generation count. Ngenerations += 1 # --- Make N children from the survivors of the previous generation. # Select parents. # Recombine pairs of parents. # Mutate the resulting offspring. #print("Generation: ", Ngenerations) children = C.make_children(Choose_problem, survivors, pop_size, NSplits, Crossover_rate, p_selection, scaling) #print("children made") # --- Select individuals for the next generation. # N of the best individuals survive (fitness biased). survivors = adult_alg(children, parents, pop_size) # --- Calculate average fitness and standard deviation of fitness. avg_fitness, std_fitness = calculate_avg_std(survivors) # --- Find best individual in population. best_individual = find_best_individual(survivors) # --- For plotting plotting.append(best_individual.fitness) #plotting2.append(calculate_avg_std(survivors)[0]) # --- Logging. if Ngenerations % 50 == 0: print("#", Ngenerations, "\nBest individual --- ", "Fitness: ", best_individual.fitness, "Genotype: ", best_individual.genotype, "\nAverage of fitness: ", avg_fitness, ". Standard deviation of fitness: ", std_fitness, ".\n") if best_individual.fitness == 1.0: print("#", Ngenerations, "\t Best individual is optimized!") # print("#", Ngenerations, "\nBest individual --- ", "Fitness: ", best_individual.fitness, "Genotype: ", best_individual.genotype) #if Choose_problem>1: print("Fitness: ",best_individual.fitness,"\nSequence: ", best_individual.genotype) if (best_individual.fitness == 1.0): return Ngenerations, True, plotting, plotting2 else: return Ngenerations, False, plotting, plotting2
def main(): western29 = "Cities/TSP_WesternSahara_29.txt" uruguay734 = "Cities/TSP_Uruguay_734.txt" canada4663 = "Cities/TSP_Canada_4663.txt" popsize = 1000 mating_pool_size = 800 tournament_size = 3 mut_rate = 0.2 xover_rate = 0.9 gen_limit = 100 # choose the instance you are using ################################################################################ instance_name = "WesternSahara" evolution_all = 10 source = None city_all = 0 if instance_name == "WesternSahara": city_all = 29 source = western29 if instance_name == "Uruguay": city_all = 734 source = uruguay734 if instance_name == "Canada": city_all = 4663 source = canada4663 experiment = { "description": { "instance_name": instance_name, "algorithm": "advanced", "city_all": city_all, "evolution_all": evolution_all, "generation_all": gen_limit, "generation_size": popsize }, "evolutions": [ # nothing yet ] } print(json.dumps(experiment)) for evo in range(evolution_all): # Experiment # construct a trial # trial = [{"time_cost": 0}] print("trial", evo + 1) start_time = time.time() print("Preparing for the information...") c = CityMap.CityMap(source) city_map = c.city_map print("preparation end.") gen = 0 print("Initialize population...") init = Initialization.Population(popsize, city_map) init.evalPopulation() print("Initialization end.") # Evolution ######################################################################################################## while gen < gen_limit: # parent selection --------------------------------------------------------------------------------------------- #print("parent selection...") parents = Selection.tournament_selection(init.population[1:], mating_pool_size, tournament_size) #print("parent selection end.") offsprings = [] i = 0 while len(offsprings ) < mating_pool_size: # 2 parents -> 2 individuals p1 = parents[i] p2 = parents[i + 1] # crossover ------------------------------------------------------------------------------------------------ #print("crossover...") if random.random() < xover_rate: #off1, off2 = Crossover.COWGC(p1, p2, city_map) off1, off2 = Crossover.order_crossover(p1, p2, city_map) else: off1 = copy.copy(p1) off2 = copy.copy(p2) #print("crossover end") # mutation ------------------------------------------------------------------------------------------------ #print("Mutation...") if random.random() < mut_rate: off1 = Mutation.WGWWGM(p1, city_map) #off1 = Mutation.WGWRGM(p1, city_map) #off1 = Mutation.IRGIBNNM_mutation(p1, city_map) #off1 = Mutation.inversion_mutation(p1, city_map) if random.random() < mut_rate: off2 = Mutation.WGWWGM(p2, city_map) #off2 = Mutation.WGWRGM(p2, city_map) #off2 = Mutation.IRGIBNNM_mutation(p2, city_map) #off2 = Mutation.inversion_mutation(p2, city_map) #print("Mutation end") offsprings.append(off1) offsprings.append(off2) #print(len(offsprings)) i += 2 # survial selection -------------------------------------------------------------------------------------------- #print("survival selection") init.population[1:] = Selection.mu_plus_lambda( init.population[1:], offsprings) #print("survival selection end") init.evalPopulation() print("generation:", gen, " Average length:", init.AverageLength, " Longest length: ", init.worstTour.length, " shortest length:", init.bestTour.length) # construct a generation # generation = { "best-individual-sequence": init.bestTour.tour, "best-individual-distance": init.bestTour.length, "worst-individual-sequence": init.worstTour.tour, "worst-individual-distance": init.worstTour.length, "average-distance": init.AverageLength, "individual-distances": [round(distance.length) for distance in init.population ] # distance.length for distance in init.population } trial.append(generation) gen += 1 trial[0]["time_cost"] = time.time() - start_time experiment["evolutions"].append(trial) # here processing generating json file ############################################################################# output_file = None variable_declaration = "none" if instance_name == "WesternSahara": output_file = open("advanced_WesternSahara.js", "w") variable_declaration = "let advanced_WesternSahara = " if instance_name == "Uruguay": output_file = open("advanced_Uruguay.js", "w") variable_declaration = "let advanced_Uruguay = " if instance_name == "Canada": output_file = open("advanced_Canada.js", "w") variable_declaration = "let advanced_Canada = " output_file.write(variable_declaration) output_file.write(json.dumps(experiment)) output_file.close()
def main(): western29 = "Cities/TSP_WesternSahara_29.txt" uruguay734 = "Cities/TSP_Uruguay_734.txt" canada4663 = "Cities/TSP_Canada_4663.txt" popsize = 10000 mating_pool_size = 8000 tournament_size = 3 mut_rate = 0.2 xover_rate = 0.9 gen_limit = 10000 print("Preparing for the information...") c = CityMap.CityMap(uruguay734) city_map = c.city_map print("preparation end.") gen = 0 print("Initialize population...") init = Initialization.Population(popsize, city_map) init.evalPopulation() print("Initialization end.") #EA algorithm while gen < gen_limit: #parent selection #print("parent selection...") parents = Selection.tournament_selection(init.population[1:], mating_pool_size, tournament_size) #parents = Selection.random_selection(init.population[1:], mating_pool_size) #parents = Selection.MPS(init.population[1:], mating_pool_size) offsprings = [] i = 0 while len( offsprings) < mating_pool_size: # 2 parents -> 2 individuals p1 = parents[i] p2 = parents[i + 1] # crossover ################################################################################################ #print("crossover...") if random.random() < xover_rate: #off1, off2 = Crossover.COWGC(p1, p2, city_map) off1, off2 = Crossover.order_crossover(p1, p2, city_map) else: off1 = copy.copy(p1) off2 = copy.copy(p2) #print("crossover end") # mutation ################################################################################################# #print("Mutation...") if random.random() < mut_rate: off1 = Mutation.WGWWGM(p1, city_map) #off1 = Mutation.WGWRGM(p1, city_map) #off1 = Mutation.IRGIBNNM_mutation(p1, city_map) #off1 = Mutation.inversion_mutation(p1, city_map) if random.random() < mut_rate: off2 = Mutation.WGWWGM(p2, city_map) #off2 = Mutation.WGWRGM(p2, city_map) #off2 = Mutation.IRGIBNNM_mutation(p2, city_map) #off2 = Mutation.inversion_mutation(p2, city_map) #print("Mutation end") offsprings.append(off1) offsprings.append(off2) #print(len(offsprings)) i += 2 # survial selection ############################################################################################ #print("survival selection") init.population = Selection.mu_plus_lambda(init.population, offsprings) init.evalPopulation() print("generation:", gen, " Average length:", init.AverageLength, " Longest length: ", init.worstTour.length, " shortest length:", init.bestTour.length) gen += 1