def main(): # random.seed(0) # numpy.random.seed(0) string_length = 8 popsize = 20 # original 10 mating_pool_size = int(popsize * 0.5) # has to be even mut_rate = 0.1 # original 1 xover_rate = 0.8 # original 0.9 # initialize population population = initialization.permutation(popsize, string_length) fitness = [] print("Initial population:") for i in range(0, popsize): fitness.append(evaluation.fitness_8queen(population[i])) print(i, ":", population[i], "fitness:", fitness[i]) # pick parents parents_index = random.sample(range(0, popsize), mating_pool_size) print("Parents:") for i in range(0, len(parents_index)): print(parents_index[i], ":", population[parents_index[i]]) # reproduction offspring = [] i = 0 # offspring are generated using selected parents in the mating pool while len(offspring) < mating_pool_size: # recombination if random.random() < xover_rate: off1, off2 = recombination.permutation_cut_and_crossfill( population[parents_index[i]], population[parents_index[i + 1]]) else: off1 = population[parents_index[i]].copy() off2 = population[parents_index[i + 1]].copy() # print offspring after recombination print("After xover:") print(off1, "fitness:", evaluation.fitness_8queen(off1)) print(off2, "fitness:", evaluation.fitness_8queen(off2)) if random.random() < mut_rate: off1 = mutation.permutation_swap(off1) if random.random() < mut_rate: off2 = mutation.permutation_swap(off2) # print offspring after mutation print("After mutation:") print(off1, "fitness:", evaluation.fitness_8queen(off1)) print(off2, "fitness:", evaluation.fitness_8queen(off2)) offspring.append(off1) offspring.append(off2)
def mainTask(exchange, exchangeFit, migrate, migrateFit, procNum, migrateTo, migrateToF, migrateFrom, migrateFromF): random.seed() numpy.random.seed() popsize = 400 mating_pool_size = int(popsize * 0.5) tournament_size = 10 mut_rate = 0.2 # our mutation operator improvement is inside the main generation loop where it is updated dynamically according to our improvement formula xover_rate = 0.9 gen_limit = 500 prevFitness = [ ] # we store previous fitnesses for past generattions so that if multiple generations start pproducing the same best fitness we can stop the algorithm start_time = time.time() # this is used to calculate the runtime iteration = 0 # this is a variable used to kkeep count of how many migrations has happened , we use it to makke sure we don't try to go out of bounds when moving to population2 # initialize population cityList = [] file = open( "TSP_Uruguay_734.txt", 'r' ) # we read the file , this can be changed to any file name (sahara or canada etc) words = list(file.read().split()) for i in range(0, len(words), 3): cityList.append( City(float(words[i + 1]), float(words[i + 2]), "City", int(words[i]))) file.close() distanceList = [ ] # this is a list to precalculate distances in order for us to find them instead of calculating every time for i in range(0, len(cityList)): distToCity = [] for j in range(0, len(cityList)): distToCity.append(cityList[i].getDistance(cityList[j])) distanceList.append(distToCity) gen = 0 # initialize the generation counter population = initialization.permutation(popsize, cityList) fitness = [] for i in range(0, popsize): fitness.append(evaluation.fitness_TSP(population[i], distanceList)) print("generation", gen, ": best fitness", (1 / (max(fitness))), "average fitness", 1 / (sum(fitness) / len(fitness))) while gen < gen_limit: # pick parents parents_index = parentSelection.tournament(fitness, mating_pool_size, tournament_size) random.shuffle(parents_index) # reproduction offspring = [] offspring_fitness = [] i = 0 # initialize the counter for parents in the mating pool while len(offspring) < mating_pool_size: # recombination if random.random() < xover_rate: off1, off2 = recombination.order_cross( population[parents_index[i]], population[parents_index[i + 1]]) else: off1 = population[parents_index[i]].copy() off2 = population[parents_index[i + 1]].copy() # mutation if random.random() < mut_rate: off1 = mutation.permutation_swap(off1) if random.random() < mut_rate: off2 = mutation.permutation_swap(off2) offspring.append(off1) offspring_fitness.append(evaluation.fitness_TSP( off1, distanceList)) offspring.append(off2) offspring_fitness.append(evaluation.fitness_TSP( off2, distanceList)) i = i + 2 # update the counter # survivor selection population, fitness = survivorSelection.mu_plus_lambda( population, fitness, offspring, offspring_fitness) gen = gen + 1 mut_rate = mut_rate - (0.1 * mut_rate * (gen / gen_limit)) # improved mutation operator #Island Model chosenIndex = [] if ((gen % 10) == 0): for j in range(0, 10): # select 10 best individuals current = 0 maxIndex = 0 maxim = 0 for i in range(0, len(fitness)): current = fitness[i] if ((current > maxim) and (i not in chosenIndex)): maxim = current maxIndex = i chosenIndex.append(maxIndex) if (len(exchange) < 10): exchange.append(population[maxIndex]) exchangeFit.append(fitness[maxIndex]) else: exchange.pop(0) exchangeFit.pop(0) exchange.append(population[maxIndex]) exchangeFit.append(fitness[maxIndex]) migrateTo.append(exchange) migrateToF.append(exchangeFit) if ( procNum == 2 ): #we check to see if this is population2 before moving individuals to it , because in population 1 there is no one to migrate yet so there's no need to run this for pop 1 if ( iteration < len(migrateFromF) ): #migration start , and check if there's any more migrations left for i in range(0, popsize): for x in range(0, len(migrateFromF[iteration])): if (migrateFromF[iteration][x] > fitness[i]): population[i] = migrateFrom[iteration][x] fitness[i] = migrateFromF[iteration][x] migrateFrom[iteration] = [] migrateFromF[iteration] = [] iteration = iteration + 1 #end Island Model #generation limitation method if (len(prevFitness) < 10): prevFitness.append((1 / (max(fitness)))) else: prevFitness.pop(0) prevFitness.append((1 / (max(fitness)))) print("population: ", procNum, "generation", gen, ": best fitness", (1 / (max(fitness))), "average fitness", 1 / (sum(fitness) / len(fitness))) print("--- %s seconds ---" % (time.time() - start_time)) if (len(prevFitness) >= 10): count = 0 for i in range(0, len(prevFitness)): if ((1 / (max(fitness))) == prevFitness[i]): count = count + 1 if (count == 10): gen = gen_limit # generationn Limitation end return population, fitness
def main(): random.seed() numpy.random.seed() string_length = 8 popsize = 20 mating_pool_size = int(popsize * 0.5) # has to be even tournament_size = 3 mut_rate = 0.2 xover_rate = 0.9 gen_limit = 50 # initialize population gen = 0 # initialize the generation counter population = initialization.permutation(popsize, string_length) fitness = [] for i in range(0, popsize): fitness.append(evaluation.fitness_8queen(population[i])) print("generation", gen, ": best fitness", max(fitness), "average fitness", sum(fitness) / len(fitness)) # evolution begins while gen < gen_limit: # pick parents parents_index = parentSelection.MPS(fitness, mating_pool_size) # parents_index = parentSelection.tournament(fitness, mating_pool_size, tournament_size) # parents_index = parentSelection.random_uniform(popsize, mating_pool_size) # in order to randomly pair up parents random.shuffle(parents_index) # reproduction offspring = [] offspring_fitness = [] i = 0 # initialize the counter for parents in the mating pool # offspring are generated using selected parents in the mating pool while len(offspring) < mating_pool_size: # recombination if random.random() < xover_rate: off1, off2 = recombination.permutation_cut_and_crossfill( population[parents_index[i]], population[parents_index[i + 1]]) else: off1 = population[parents_index[i]].copy() off2 = population[parents_index[i + 1]].copy() # mutation if random.random() < mut_rate: off1 = mutation.permutation_swap(off1) if random.random() < mut_rate: off2 = mutation.permutation_swap(off2) offspring.append(off1) offspring_fitness.append(evaluation.fitness_8queen(off1)) offspring.append(off2) offspring_fitness.append(evaluation.fitness_8queen(off2)) i = i + 2 # update the counter # form the population of next generation population, fitness = survivorSelection.mu_plus_lambda( population, fitness, offspring, offspring_fitness) # population, fitness = survivorSelection.replacement(population, fitness, offspring, offspring_fitness) # population, fitness = survivorSelection.random_uniform(population, fitness, offspring, offspring_fitness) gen = gen + 1 # update the generation counter print("generation", gen, ": best fitness", max(fitness), "average fitness", sum(fitness) / len(fitness)) # evolution ends # print the final best solution(s) k = 0 for i in range(0, popsize): if fitness[i] == max(fitness): print("best solution", k, population[i], fitness[i]) k = k + 1
def main(): experiment = [ # nothing yet ] stat = ["mean", "std", "aes", "sr"] evos = 0 while evos < 20: trial = [-1, []] # [seccessed-generatiohn, best-fitness] recorded = False random.seed() numpy.random.seed() string_length = 8 popsize = 20 # original 20 mating_pool_size = int(popsize*0.5) # has to be even tournament_size = 4 mut_rate = 0.2 xover_rate = 0.9 gen_limit = 50 # initialize population gen = 0 # initialize the generation counter population = initialization.permutation(popsize, string_length) fitness = [] for i in range(0, popsize): fitness.append(evaluation.fitness_8queen(population[i])) print("generation", gen, ": best fitness", max(fitness), "average fitness", sum(fitness)/len(fitness)) # evolution begins while gen < gen_limit: # pick parents #parents_index = parentSelection.MPS(fitness, mating_pool_size) parents_index = parentSelection.tournament(fitness, mating_pool_size, tournament_size) #parents_index = parentSelection.random_uniform(popsize, mating_pool_size) # in order to randomly pair up parents random.shuffle(parents_index) # reproduction offspring =[] offspring_fitness = [] i= 0 # initialize the counter for parents in the mating pool # offspring are generated using selected parents in the mating pool while len(offspring) < mating_pool_size: # recombination if random.random() < xover_rate: off1,off2 = recombination.permutation_cut_and_crossfill(population[parents_index[i]], population[parents_index[i+1]]) else: off1 = population[parents_index[i]].copy() off2 = population[parents_index[i+1]].copy() # mutation if random.random() < mut_rate: off1 = mutation.permutation_swap(off1) if random.random() < mut_rate: off2 = mutation.permutation_swap(off2) offspring.append(off1) offspring_fitness.append(evaluation.fitness_8queen(off1)) offspring.append(off2) offspring_fitness.append(evaluation.fitness_8queen(off2)) i = i+2 # update the counter # form the population of next generation population, fitness = survivorSelection.mu_plus_lambda(population, fitness, offspring, offspring_fitness) # population, fitness = survivorSelection.replacement(population, fitness, offspring, offspring_fitness) # population, fitness = survivorSelection.random_uniform(population, fitness, offspring, offspring_fitness) gen = gen + 1 # update the generation counter print("generation", gen, ": best fitness", max(fitness), "average fitness", sum(fitness)/len(fitness)) trial[1].append( max(fitness) ) #trial[1].append( sum(fitness)/len(fitness) ) if max(fitness) == 28 and recorded == False: trial[0] = gen + 1 recorded = True # evolution ends # print the final best solution(s) k = 0 for i in range (0, popsize): if fitness[i] == max(fitness): print("best solution", k, population[i], fitness[i]) k = k+1 evos = evos + 1 experiment.append(trial) bests = [] sr = [] for trial in experiment: final = trial[1][49] bests.append(final) if trial[0] != -1: sr.append(trial[0]) stat[0] = numpy.mean(bests) stat[1] = numpy.std(bests) stat[3] = sr stat[2] = numpy.mean(stat[3]) output_file = open("trace.js", "a") output_file.write("let tourn_miu = ") output_file.write(json.dumps(experiment)) output_file.write(";\n") output_file.write("let tourn_miu_stat = ") output_file.write(json.dumps(stat)) output_file.write(";\n") output_file.close()
def main(): random.seed() numpy.random.seed() string_length = 8 popsize = 20 mating_pool_size = int(popsize * 0.5) # has to be even tournament_size = 3 mut_rate = 0.2 xover_rate = 0.9 gen_limit = 100 # initialize population cityList = [] c1 = City(2, 5, "c1") c2 = City(4, 5, "c2") c3 = City(9, 5, "c3") c4 = City(12, 10, "c4") c5 = City(20, 11, "c5") c6 = City(13, 14, "c6") c7 = City(20, 19, "c7") c8 = City(21, 12, "c8") c9 = City(210, 120, "c9") c10 = City(165, 22, "c10") c11 = City(35, 26, "c11") c12 = City(50, 50, "c12") c13 = City(205, 120, "c13") c14 = City(154, 20, "c14") c15 = City(150, 200, "c15") c16 = City(130, 150, "c16") c17 = City(135, 125, "c17") c18 = City(110, 145, "c18") c19 = City(25, 132, "c19") c20 = City(60, 124, "c20") cityList.append(c1) cityList.append(c2) cityList.append(c3) cityList.append(c4) cityList.append(c5) cityList.append(c6) cityList.append(c7) cityList.append(c8) cityList.append(c9) cityList.append(c10) cityList.append(c11) cityList.append(c12) cityList.append(c13) cityList.append(c14) cityList.append(c15) cityList.append(c16) cityList.append(c17) cityList.append(c18) cityList.append(c19) cityList.append(c20) gen = 0 # initialize the generation counter population = initialization.permutation(popsize, cityList) fitness = [] for i in range(0, popsize): fitness.append(evaluation.fitness_8queen(population[i])) print("generation", gen, ": best fitness", max(fitness), "average fitness", sum(fitness) / len(fitness)) # evolution begins while gen < gen_limit: # pick parents #parents_index = parentSelection.MPS(fitness, mating_pool_size) parents_index = parentSelection.tournament(fitness, mating_pool_size, tournament_size) # parents_index = parentSelection.random_uniform(popsize, mating_pool_size) # in order to randomly pair up parents random.shuffle(parents_index) # reproduction offspring = [] offspring_fitness = [] i = 0 # initialize the counter for parents in the mating pool # offspring are generated using selected parents in the mating pool while len(offspring) < mating_pool_size: # recombination if random.random() < xover_rate: off1, off2 = recombination.permutation_cut_and_crossfill( population[parents_index[i]], population[parents_index[i + 1]]) else: off1 = population[parents_index[i]].copy() off2 = population[parents_index[i + 1]].copy() # mutation if random.random() < mut_rate: off1 = mutation.permutation_swap(off1) if random.random() < mut_rate: off2 = mutation.permutation_swap(off2) offspring.append(off1) offspring_fitness.append(evaluation.fitness_8queen(off1)) offspring.append(off2) offspring_fitness.append(evaluation.fitness_8queen(off2)) i = i + 2 # update the counter # form the population of next generation population, fitness = survivorSelection.mu_plus_lambda( population, fitness, offspring, offspring_fitness) # population, fitness = survivorSelection.replacement(population, fitness, offspring, offspring_fitness) # population, fitness = survivorSelection.random_uniform(population, fitness, offspring, offspring_fitness) gen = gen + 1 # update the generation counter print("generation", gen, ": best fitness", max(fitness), "average fitness", sum(fitness) / len(fitness)) # evolution ends # print the final best solution(s) k = 0 for i in range(0, popsize): if fitness[i] == max(fitness): print("best solution", k) for j in range(0, len(population[i])): print("city : ", population[i][j].name, "position : (", population[i][j].x, ",", population[i][j].y, ")") print("fitness :", fitness[i]) k = k + 1
def main(): checkSysArgs() distances = load_file(sys.argv[1]) if sys.argv[1] == "WesternSahara": filename = "../TSP_WesternSahara_29.txt" elif sys.argv[1] == "Uruguay": filename = "../TSP_Uruguay_734.txt" elif sys.arg[1] == "Canada": filename = "../TSP_Canada_4663.txt" string_length = len(distances) popsize = 100 mating_pool_size = int(popsize * 0.5) # has to be even tournament_size = 6 mut_rate = 0.3 xover_rate = 0.9 gen_limit = 2500 fitnessThreshold = 20 plot_population = [] gen = 0 population = initialization.permutation(popsize, string_length) for i in range(popsize): population[i].fitness = evaluation.fitness(population[i], distances) maxFitness = 0 totalFitness = 0 prev_averageFitness = 10000 convergence_counter = 0 scramble = False gen_points = [50,100,150] while convergence_counter < 300: parents = parentSelection.tournament_sel(population, mating_pool_size, tournament_size) # parents = parentSelection.MPS(population, mating_pool_size) random.shuffle(parents) offspring = [] i = 0 while len(offspring) < mating_pool_size: # RECOMBINATION if random.random() < xover_rate: if gen < gen_points[0]: # off1, off2 = recombination.Alternating_Edges(parents[i], parents[i+1]) # off1, off2 = recombination.cut_and_crossfill(parents[i], parents[i + 1]) # off1, off2 = recombination.OrderCrossover(parents[i], parents[i + 1]) # off1, off2 = recombination.PMX(parents[i], parents[i + 1]) off1 = recombination.sequential_constructive_crossover(parents[i], parents[i+1], distances) off2 = recombination.sequential_constructive_crossover(parents[i], parents[i+1], distances) else: # off1, off2 = recombination.Alternating_Edges(parents[i], parents[i+1]) # off1, off2 = recombination.cut_and_crossfill(parents[i], parents[i + 1]) # off1, off2 = recombination.OrderCrossover(parents[i], parents[i + 1]) off1, off2 = recombination.PMX(parents[i], parents[i + 1]) # off1 = recombination.sequential_constructive_crossover(parents[i], parents[i+1], distances) # off2 = recombination.sequential_constructive_crossover(parents[i], parents[i+1], distances) else: off1 = parents[i] off2 = parents[i + 1] # MUTATION if random.random() < mut_rate: # off1 = mutation.insert(off1) off1 = mutation.inversion(off1) # off1 = mutation.random(off1) # off1 = mutation.scramble(off1) # off1 = mutation.swap(off1) if random.random() < mut_rate: # off2 = mutation.insert(off2) off2 = mutation.inversion(off2) # off2 = mutation.random(off2) # off2 = mutation.scramble(off2) # off2 = mutation.swap(off2) # FITNESS EVALUATION off1.fitness = evaluation.fitness(off1, distances) offspring.append(off1) off2.fitness = evaluation.fitness(off2, distances) offspring.append(off2) # SURVIVOR SELECTION population = survivorSelection.mu_plus_lambda(population, offspring) # population = survivorSelection.mu_lambda(population, offspring) # population = survivorSelection.round_robin_tournament(population, offspring) # population = survivorSelection.random_uniform(population, offspring) # population = survivorSelection.simulated_annealing(population, offspring) gen += 1 minPathLength = 1 / max(individual.fitness for individual in population) totalPathLengths = sum(1 / individual.fitness for individual in population) averagePathLength = totalPathLengths / len(population) if (averagePathLength - minPathLength) < 100: convergence_counter += 1 else: convergence_counter = 0 print("generation {}: Min Path {}, Average Path {}, diff {}" .format(gen, minPathLength, averagePathLength, averagePathLength -minPathLength)) k = 1 for i in range(0, popsize): if(1/population[i].fitness) == minPathLength: plot_population.append(population[i].path) print("best solution {} {} {}".format(k, population[i].path, 1/population[i].fitness)) k+=1 plot.plotTSP(plot_population[0], serializer.readFile(filename))
def main(): initialize(parse_argv()) startTime = datetime.now() print("START:") current_gen = 0 staling = 0 prevAverage = 1 ## Create initial population and calculate initial fitness population = permutation(pop_size) useHeuristic = False useSwap = False staled = False heuristicThreshold = len(population) * 0.25 swapThreshold = len(population) * 5 stalingThreshold = len(population) * 10 currentThreshold = heuristicThreshold while current_gen < gen_limit and not staled: # Switch between tourney and multi-winner-tourney here parents = tournament_selection(population, mating_pool_size, tournament_size) #parents = multi_winner_tourney_selection(population, mating_pool_size, mw_tournament_size, mw_tournament_winners) r.shuffle(parents) offspring = [] i = 0 while len(offspring) < mating_pool_size: ## Crossover if r.random() < xover_rate: xover_offspring = order_crossover( parents[i].get_city_ids(), parents[i + 1].get_city_ids()) off0 = Route(xover_offspring[0]) off1 = Route(xover_offspring[1]) else: off0 = parents[i].create_copy() off1 = parents[i + 1].create_copy() ## mutation if r.random() < mut_rate: if (useSwap): off0 = swap_mutation(off0.get_city_ids()) elif (useHeuristic): off0 = heuristic_swap(off0) else: off0 = scramble_mutation(off0.get_city_ids()) if r.random() < mut_rate: if (useSwap): off1 = swap_mutation(off1.get_city_ids()) elif (useHeuristic): off1 = heuristic_swap(off1) else: off1 = scramble_mutation(off1.get_city_ids()) ## Add new offspring offspring.append(off0) offspring.append(off1) i += 2 population = survivor_selection(population, offspring) fitness = [x.get_fitness() for x in population] average = sum(fitness) / len(fitness) bestFit = min(fitness) summaryAvgList.append(average) summaryBestList.append(bestFit) print("Generation ", current_gen) print("Best fitness: ", bestFit) print("Average fitness: ", average) if (average / prevAverage > (currentThreshold - 1) / currentThreshold and average / prevAverage < (currentThreshold + 1 / currentThreshold)): staling += 1 else: staling = 0 if (staling == staling_limit): if not useHeuristic: useHeuristic = True currentThreshold = swapThreshold print("Changed from scramble to heuristic swap!") elif not useSwap: useSwap = True currentThreshold = stalingThreshold print("Changed from heuristic to random swap!") else: staled = True staling = 0 prevAverage = average current_gen += 1 # print the final best solution(s) if (staled): print("Population staled!") else: print("Gen limit reached!") endTime = datetime.now() deltaT = endTime - startTime print("Completed in:", deltaT) # output the graphs summary.plot_avg_best_fit(summaryAvgList, summaryBestList) summary.plot_route(population[fitness.index(min(fitness))]) summary.visualize()
def run(filename): startTime = datetime.now() print("START:") current_gen = 0 staling = 0 prevAverage = 1 ## Create initial population and calculate initial fitness population = permutation(pop_size) useHeuristic = False useSwap = False staled = False heuristicThreshold = len(population) swapThreshold = len(population) * 5 stalingThreshold = len(population) * 10 currentThreshold = heuristicThreshold while current_gen < gen_limit and not staled: # Switch between tourney and multi-winner-tourney here parents = tournament_selection(population, mating_pool_size, tournament_size) #r.shuffle(parents) offspring = [] i = 0 while len(offspring) < mating_pool_size: ## Crossover if r.random() < xover_rate: xover_offspring = order_crossover( parents[i].get_city_ids(), parents[i + 1].get_city_ids()) off0 = Route(xover_offspring[0]) off1 = Route(xover_offspring[1]) else: off0 = parents[i].create_copy() off1 = parents[i + 1].create_copy() ## mutation if r.random() < mut_rate: if (useSwap): off0 = swap_mutation(off0.get_city_ids()) elif (useHeuristic): off0 = heuristic_swap(off0) else: off0 = scramble_mutation(off0.get_city_ids()) if r.random() < mut_rate: if (useSwap): off1 = swap_mutation(off1.get_city_ids()) elif (useHeuristic): off1 = heuristic_swap(off1) else: off1 = scramble_mutation(off1.get_city_ids()) offspring.append(off0) offspring.append(off1) i += 2 population = survivor_selection(population, offspring) fitness = [x.get_fitness() for x in population] average = sum(fitness) / len(fitness) bestFit = min(fitness) if (current_gen % 50 == 0): print("Generation ", current_gen) print("Best fitness: ", bestFit) print("Average fitness: ", average) if (average / prevAverage > (currentThreshold - 1) / currentThreshold and average / prevAverage < (currentThreshold + 1 / currentThreshold)): staling += 1 else: staling = 0 if (staling == staling_limit): if not useHeuristic: useHeuristic = True currentThreshold = swapThreshold print("Changed from scramble to heuristic swap!") elif not useSwap: useSwap = True currentThreshold = stalingThreshold print("Changed from heuristic to random swap!") else: staled = True staling = 0 prevAverage = average current_gen += 1 # print the final best solution(s) if (staled): print("Population staled!") endTime = datetime.now() deltaT = endTime - startTime data = { "file": filename, "elapsed_time": str(deltaT), "generation": current_gen, "best_fitness": bestFit, "avg_fitness": average } return data else: print("Gen limit reached!") endTime = datetime.now() deltaT = endTime - startTime data = { "file": filename, "elapsed_time": str(deltaT), "generation": current_gen, "best_fitness": bestFit, "avg_fitness": average } return data