def main(): startTime1 = datetime.now() #to get the time elapsed gen_limit = 10000 f = "TSP_WesternSahara_29.txt" # f = "TSP_Uruguay_734.txt" # f = "TSP_Canada_4663.txt" tournament_size = 50 mut_rate = 0.2 xover_rate = 0.7 pop_size = 1000 mating_pool_size = int(pop_size * 0.5) #has to be divisible by 2 no_change = int(pop_size * 0.25) chrom_length = 29 # chrom_length = 734 # chrom_length = 4663 change = False gen_ = [] best_fit = [ ] #to store the best fitness using tournament for parent selection gen = 0 cities = readFile(f, chrom_length) dists = distances(cities) population = [] #population = setCities(pop_size, chrom_length) points = Cluster(chrom_length, cities, 4) #new_points = two_Opt(points,dists) for i in range(pop_size): population.append(points) fitness1 = [] for ind in range(pop_size): fitness1.append(fitness(dists, population[ind])) print("Starting Fitness: ", min(fitness1)) gen_.append(gen) best_fit.append(min(fitness1)) last_min = min(fitness1) same_fit = 0 while gen < gen_limit: parents_index = parentSelection.tournament(fitness1, mating_pool_size, tournament_size) random.shuffle(parents_index) offspring = [] offspring_fitness = [] i = 0 while len(offspring) < mating_pool_size: startTime2 = datetime.now() if random.random() < xover_rate: off1, off2 = order_crossover(population[parents_index[i]], population[parents_index[i + 1]]) ## if change: ## off1, off2 = m_order(population[parents_index[i]], population[parents_index[i+1]], dists) ## else: ## off1, off2 = greedyCrossover(population[parents_index[i]], population[parents_index[i+1]]) ## #off1, off2 = order_crossover(population[parents_index[i]], population[parents_index[i+1]]) else: off1 = population[parents_index[i]].copy() off2 = population[parents_index[i + 1]].copy() if random.random() < mut_rate: if change: off1 = mutation.inversion_mutation(off1) else: off1 = mutation.swap_mutate(off1) if random.random() < mut_rate: if change: off2 = mutation.inversion_mutation(off2) else: off2 = mutation.swap_mutate(off2) offspring.append(off1) offspring_fitness.append(fitness(dists, off1)) offspring.append(off2) offspring_fitness.append(fitness(dists, off2)) i += 2 population, fitness1 = survivor_selection.mu_plus_lambda( population, fitness1, offspring, offspring_fitness) gen += 1 gen_.append(gen) minim = min(fitness1) #print(gen, minim) indi = fitness1.index(min(fitness1)) best_fit.append(min(fitness1)) individual = population[indi] my_time = 0 if minim == last_min: same_fit += 1 else: last_min = min(fitness1) same_fit = 0 if change == True and same_fit == no_change: print("Stopped at Generation: ", gen) break if same_fit == no_change: change = True same_fit = 0 print("Changed to inversion Mutation at Generation: ", gen) #print('\n Time Elapsed in General: ', datetime.now() - startTime1) print("Ending Fitness: ", minim) print('\n Time Elapsed in General: ', datetime.now() - startTime1) mycity = city_xy(individual, cities) make_bar.make_Bar(gen_, best_fit) make_bar.make_Plot(mycity)
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 = 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(): 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 # 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)) # 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