def selection(gs: list, k: int): gs1 = [] s = 0 for i in gs: fitness = fitness_function(i) gs1.append([i, fitness]) s += fitness gs1.sort(key=lambda x: -x[1]) for i in gs1: i[1] = (i[1] * 100) / s g = [] #since, k= 8 for i in range(k // 2): x = np.random.randint(0, 50) #selecting first one in pair for j in gs1: if x - j[1] < 0: g.append(j[0]) break x -= j[1] #selecting second one in pair r = g[-1] while g[-1] == r: x = np.random.randint(0, 50) for j in gs1: if x - j[1] < 0: r = j[0] break x -= j[1] g.append(r) return g
def reduction(self): Fit = fitness_function() for x in xrange(0,len(self.descendants)): if self.descendants[x]['value'] > Fit.min and self.descendants[x]['value'] <= Fit.max: self.population.append(self.descendants[x]) self.population.sort(reverse=True) self.population = self.population[:self.pop_size]
def reduction(self): Fit = fitness_function() for x in xrange(0, len(self.descendants)): if self.descendants[x]['value'] > Fit.min and self.descendants[x][ 'value'] <= Fit.max: self.population.append(self.descendants[x]) self.population.sort(reverse=True) self.population = self.population[:self.pop_size]
def pop_max(self): Fit = fitness_function() print '####################################################' print 'Макс. значение популяции в точке x=', print self.population[0]['value'] print 'f(x)=', print self.population[0]['fitness'],' / ',Fit.optium print '[ min / max ] [', print self.population[-1]['value'],';',self.population[0]['value'],']' print '####################################################' print print
def pop_max(self): Fit = fitness_function() print '####################################################' print 'Макс. значение популяции в точке x=', print self.population[0]['value'] print 'f(x)=', print self.population[0]['fitness'], ' / ', Fit.optium print '[ min / max ] [', print self.population[-1]['value'], ';', self.population[0][ 'value'], ']' print '####################################################' print print
def mutation(self): Fit = fitness_function() for x in xrange(0,len(self.descendants)): chromosome = float_to_binary( self.descendants[x]['value']) gen = random.randint(0,63) if chromosome[gen] == '0': chromosome = chromosome[:gen] + '1' + chromosome[gen+1:] else: chromosome = chromosome[:gen] + '0' + chromosome[gen+1:] self.descendants[x]['value'] = binary_to_float(chromosome) self.descendants[x]['fitness'] = Fit.f(self.descendants[x]['value'])
def genetic_algorithm(): gs = [] k = 30 for i in range(k): gs.append(random_generation()) for _ in range(1000): gs1 = selection(gs, k) for i in range(0, len(gs1), 2): gs1[i], gs1[i + 1] = crossover(gs1[i], gs1[i + 1]) for i in range(len(gs1)): gs1[i] = mutation(gs1[i]) gs = gs1[:] gs.sort(key=lambda x: -fitness_function(x)) m = fitness_function(gs[0]) s = gs[0] if m == 243: print( "5 Best solution along with their fitnesses of the final population" ) print("Sudoku 1: Solution Found!!") printSudoku(s) print("Fitness Value: {}".format(fitness_function(gs[0]))) for j in range(1, 5): print("Sudoku {}:".format(j + 1)) printSudoku(gs[i]) print("Fitness Value: {}".format(fitness_function(gs[i]))) break else: print( "5 Best solution along with their fitnesses of the final population" ) for i in range(5): print("Sudoku {}:".format(i + 1)) printSudoku(gs[i]) print("Fitness Value: {}".format(fitness_function(gs[i]))) print('')
def mutation(self): Fit = fitness_function() for x in xrange(0, len(self.descendants)): chromosome = float_to_binary(self.descendants[x]['value']) gen = random.randint(0, 63) if chromosome[gen] == '0': chromosome = chromosome[:gen] + '1' + chromosome[gen + 1:] else: chromosome = chromosome[:gen] + '0' + chromosome[gen + 1:] self.descendants[x]['value'] = binary_to_float(chromosome) self.descendants[x]['fitness'] = Fit.f( self.descendants[x]['value'])
def __init__(self, size, parents_n): self.pop_size = size if parents_n > 100: parents_n = 100 self.parents_num = parents_n while size > 0: Fit = fitness_function() person = {} person['value'] = Fit.min + random.random() * (Fit.max - Fit.min) person['fitness'] = Fit.f(person['value']) size -= 1 self.population.append(person) self.population.sort(reverse=True)
def __init__(self,size,parents_n): self.pop_size = size if parents_n > 100: parents_n = 100 self.parents_num = parents_n while size > 0: Fit = fitness_function() person = {} person['value'] = Fit.min + random.random() * (Fit.max-Fit.min) person['fitness'] = Fit.f(person['value']) size -= 1 self.population.append(person) self.population.sort(reverse=True)
def vrp_ga(m=0.2, gen=500, N=100, best_N=5, setup=1, plot_folder="plots/"): """ Complete function, optimizing the vehicle routing problem using genetic algorithms and a custom crossover/mutation part. Args m mutation probability gen number of generation (iterations) N population size (must be divisable by 4) best_N plotting the N best individuals each generation setup number of setup (currently 1 and 2) plot_folder path to save plots """ if N % 4 != 0: raise ValueError( "[!] 'N' (population size) has to be dividedable by 4!") history = np.zeros((gen, best_N)) # create one test member, to load task # cap = capacity of trucks in list # demands = demands of cities # dist = distance matrix # tc = transportation costs of trucks _, cap, demands, dist, tc = complete_init(task_nr=setup) ##### initialization # create a list for our population with N elements, with multiple # possible setups as numpy arrays # [instead of doing a list of 2d arrays, we do one 3d array, where the # first dimension stands for the members] # population has 3 dimensions: members x trucks x cities population = np.zeros((N, len(cap), len(demands))) # fill the population array for i in range(N): population[i] = complete_init(task_nr=setup)[0] for gen_idx in tqdm(range(gen)): ##### fitness permutations = np.array( [permute_way(member, dist, demands, cap) for member in population]) fitness_scores = np.array([ fitness_function(dist, permutation, member, tc) for permutation, member in zip(permutations, population) ]) history[gen_idx] = sorted(fitness_scores)[-best_N:] ##### selection selected_indx = roulette_wheel_selection(fitness_scores, int(N / 2)) selected_members = population[selected_indx] np.random.shuffle(selected_members) ##### crossover children = vrp_crossover(selected_members, cap, demands) ##### mutation for i, child in enumerate(children): if random.uniform(0, 1) < m: children[i] = mutate(child, cap) ##### replacement population = replacement(population, children, mode="delete-all", n=len(children), based_on_fitness=True, fitness_old=fitness_scores) ##### plotting plt.figure() plt.plot(history) plt.xlabel("Generations") plt.savefig(plot_folder + "history" + strftime("%Y-%m-%d %H:%M:%S", gmtime()) + ".png") plt.show()