def Simulated_annealing(transcription_matrix, no_of_empty_squares, no_of_iterations, alpha=0.1): # input: # no_of_iterations = int; number of iterations for each of individual # transcription_matrix = np.array(n,m) matrix of zeros and ones # no_of_empty_squares = int; number of squares to fill # mutation = lambda chromosome: changed_chromosome # alpha = float from 0 to 1; probability of changing solution to worse sol = np.hstack([np.ones(no_of_empty_squares), np.zeros(transcription_matrix.shape[0] - no_of_empty_squares)]) np.random.shuffle(sol) x = sol x_cost = fitness_function(x, transcription_matrix) best_val = x_cost best_individual = x for t in range(no_of_iterations): y = mutation_one(x) y_cost = fitness_function(y, transcription_matrix) if (y_cost < x_cost): x, x_cost = y, y_cost elif (np.random.rand() < np.exp(- alpha * (y_cost - x_cost) * t / no_of_iterations)): x, x_cost = y, y_cost if x_cost < best_val: best_val = x_cost best_individual = x # output: # best_val = int; fitness value of best_individual # best_individual = 1-D array return best_val, best_individual
def Random_search(no_of_iterations, transcription_matrix, no_of_empty_squares, return_best_individual=False, tqdm_mode=False): # input: # no_of_iterations = int # transcription_matrix = np.array(n,m) of zeros and ones # no_of_empty_squares = number of squares to fill # return_best_individual = bool solutions = np.zeros(no_of_iterations) sol = np.hstack([ np.ones(no_of_empty_squares), np.zeros(transcription_matrix.shape[0] - no_of_empty_squares) ]) if return_best_individual: np.random.shuffle(sol) best_individual = sol best_val = fitness_function(best_individual, transcription_matrix) solutions[0] = best_val if tqdm_mode: this_range = tqdm(range(1, no_of_iterations)) else: this_range = range(1, no_of_iterations) for i in this_range: np.random.shuffle(sol) current_individual = sol current_val = fitness_function(current_individual, transcription_matrix) if current_val < best_val: best_val = current_val best_individual = current_individual solutions[i] = current_val # output: # solutions = np.array(no_of_iterations) with score of each individual # best_individual = np.array(transcription_matrix.shape[0]); chromosome of best best_individual return solutions, best_individual else: if tqdm_mode: this_range = tqdm(range(no_of_iterations)) else: this_range = range(no_of_iterations) for i in this_range: np.random.shuffle(sol) solutions[i] = fitness_function(sol, transcription_matrix) # output: # solutions = np.array(no_of_iterations) with score of each individual return solutions
def update_problem(self, child, n, type, fit): t = 0 # 记修改的次数 if type == 1: size = self.max_neighborhood_size else: size = self.pop_size perm = get_random_list(size) for i in range(size): if type == 1: k = self.pop[n].neighbor[perm[i]] else: k = perm[i] f1 = fitness_function(self.pop[k].pop_fitness, self.pop[k].namda, self.ideal_fitness) f2 = fitness_function(fit, self.pop[k].namda, self.ideal_fitness) if f2 < f1: self.pop[k].pop_x = child self.pop[k].pop_fitness = fit t += 1 if t > self.limit: return 0
def Compound_evolutionary_algorithm(transcription_matrix, size_of_population, size_of_sudoku, max_iter=None, P=4, crossover_parameter=0.5, tqdm_mode=False, transforming_factor=0.8): # initialization of first generation population = np.zeros([size_of_population, transcription_matrix.shape[0]]) for i in range(size_of_population): population[i, np.random.randint(0, transcription_matrix.shape[0], 1)] = 1 number_of_possibilities = cumulate_data(10, size_of_sudoku, tqdm_mode=tqdm_mode)[-1, :] if not max_iter: max_iter = int(np.sum(1 / np.log10(1 / (1 - number_of_possibilities[1:])) + 1)) * P + 1 chromosome_fitness_tracking = np.zeros([size_of_population, max_iter]) number_of_ones_tracking = np.zeros([size_of_population, max_iter]) last_added_subset = np.ones(size_of_population) * (-1) founded = False winning_chromosome_val = np.inf winning_chromosome = np.empty([]) backward_time_horizon = np.zeros(size_of_population) if tqdm_mode: this_range = tqdm(range(max_iter)) else: this_range = range(max_iter) for i in this_range: for j in range(size_of_population): current_fitness = fitness_function(population[j], transcription_matrix) chromosome_fitness_tracking[j, i] = current_fitness number_of_ones_tracking[j, i] = np.sum(population[j]) if number_of_ones_tracking[j, i] == number_of_ones_tracking[j, i - 1]: backward_time_horizon[j] += 1 else: backward_time_horizon[j] = 0 if current_fitness == 0: founded = True winning_chromosome_val = current_fitness winning_chromosome = population[j] elif current_fitness < winning_chromosome_val: winning_chromosome_val = current_fitness winning_chromosome = population[j].copy() winning_chromosome[int(last_added_subset[j])] = 0 else: if np.sum(transcription_matrix[population[j].astype(bool)].sum(axis=0) > 1) == 0: last_added_subset[j] = np.random.choice(np.argwhere(population[j] == 0).flatten()) population[j, int(last_added_subset[j])] = 1 else: if last_added_subset[j] != -1: index_of_chosen_zero = np.random.choice(np.argwhere(population[j] == 0).flatten()) population[j, index_of_chosen_zero] = 1 population[j, int(last_added_subset[j])] = 0 last_added_subset[j] = index_of_chosen_zero else: index_of_chosen_zero = np.random.choice(np.argwhere(population[j] == 0).flatten()) index_of_chosen_one = np.random.choice(np.argwhere(population[j] == 1).flatten()) population[j, index_of_chosen_one] = 0 population[j, index_of_chosen_zero] = 1 last_added_subset[j] = index_of_chosen_one # crossover if not founded and backward_time_horizon[j] > limit_iteration(population[j].shape[0], np.sum(population[j]), number_of_possibilities, P=P): # roulette selection temp = chromosome_fitness_tracking[:, i - 1] + backward_time_horizon normalization_term = np.sum(np.max(temp) - temp) if normalization_term: probabilities = (np.max(temp) - temp) / np.sum(np.max(temp) - temp) else: probabilities = np.ones(size_of_population) / size_of_population id_of_chosen = np.random.choice(np.arange(size_of_population), 1, p=probabilities) chosen = population[id_of_chosen][0].copy() chosen[int(last_added_subset[id_of_chosen])] = 0 bin = binary_list_to_ids(chosen) mask = (np.random.rand(bin.shape[0]) * (1 / (1 - crossover_parameter))).astype(int).astype(bool) population[j] = ids_to_binary_list(bin[mask], transcription_matrix.shape[0]) # If individual is good enough use on it algorithm x if number_of_ones_tracking[j, i] / (size_of_sudoku ** 2) > transforming_factor: # making individual acceptable population[j, int(last_added_subset[j])] = 0 # Important part: original_indexes, transcription_matrix_new = transcription_matrix_from_partial_solution(population[j], transcription_matrix) sol = np.array(algorithm_x_first_solution(transcription_matrix_new)) # sol is either chromosome solving transcription_matrix_new or empty list if sol.size > 0: founded = True # convert solution from transcription_matrix_new - smaller matrix - to original transcription_matrix old = np.zeros(transcription_matrix.shape[0]) for i, element in enumerate(np.hstack([sol, binary_list_to_ids(population[j])])): if i < sol.shape[0]: # part of solution from algorithm_x old[i] = original_indexes[element] else: # part of solution from evolutionary algorithm old[i] = element winning_chromosome = old else: # This individual has no potential, replace him! population[j] = np.zeros(transcription_matrix.shape[0]) population[j, np.random.randint(transcription_matrix.shape[0])] = 1 last_added_subset[j] = np.random.randint(transcription_matrix.shape[0]) population[j, int(last_added_subset[j])] = 1 if founded: return chromosome_fitness_tracking[:, :i + 1], number_of_ones_tracking[:, :i + 1], winning_chromosome return chromosome_fitness_tracking, number_of_ones_tracking, winning_chromosome
def Extended_progressive_evolutionary_algorithm(transcription_matrix, size_of_population, size_of_sudoku, max_iter=None, P=4, crossover_parameter=0.5, tqdm_mode=False): # initialization of first generation population = np.zeros([size_of_population, transcription_matrix.shape[0]]) for i in range(size_of_population): population[i, np.random.randint(0, transcription_matrix.shape[0], 1)] = 1 number_of_possibilities = cumulate_data(10, size_of_sudoku, tqdm_mode=tqdm_mode)[-1, :] if not max_iter: max_iter = int( np.sum(1 / np.log10(1 / (1 - number_of_possibilities[1:])) + 1)) * P + 1 chromosome_fitness_tracking = np.zeros([size_of_population, max_iter]) number_of_ones_tracking = np.zeros([size_of_population, max_iter]) last_added_subset = np.ones(size_of_population) * (-1) founded = False winning_chromosome_val = np.inf winning_chromosome = np.empty([]) backward_time_horizon = np.zeros(size_of_population) if tqdm_mode: this_range = tqdm(range(max_iter)) else: this_range = range(max_iter) for i in this_range: for j in range(size_of_population): current_fitness = fitness_function(population[j], transcription_matrix) chromosome_fitness_tracking[j, i] = current_fitness number_of_ones_tracking[j, i] = np.sum(population[j]) if number_of_ones_tracking[j, i] == number_of_ones_tracking[j, i - 1]: backward_time_horizon[j] += 1 else: backward_time_horizon[j] = 0 if current_fitness == 0: founded = True winning_chromosome_val = current_fitness winning_chromosome = population[j] elif current_fitness < winning_chromosome_val: winning_chromosome_val = current_fitness winning_chromosome = population[j].copy() winning_chromosome[int(last_added_subset[j])] = 0 else: if np.sum(transcription_matrix[population[j].astype(bool)].sum( axis=0) > 1) == 0: last_added_subset[j] = np.random.choice( np.argwhere(population[j] == 0).flatten()) population[j, int(last_added_subset[j])] = 1 else: if last_added_subset[j] != -1: index_of_chosen_zero = np.random.choice( np.argwhere(population[j] == 0).flatten()) population[j, index_of_chosen_zero] = 1 population[j, int(last_added_subset[j])] = 0 last_added_subset[j] = index_of_chosen_zero else: index_of_chosen_zero = np.random.choice( np.argwhere(population[j] == 0).flatten()) index_of_chosen_one = np.random.choice( np.argwhere(population[j] == 1).flatten()) population[j, index_of_chosen_one] = 0 population[j, index_of_chosen_zero] = 1 last_added_subset[j] = index_of_chosen_one # crossover if not founded and backward_time_horizon[j] > limit_iteration( population[j].shape[0], np.sum(population[j]), number_of_possibilities, P=P): # roulette selection temp = chromosome_fitness_tracking[:, i - 1] + backward_time_horizon normalization_term = np.sum(np.max(temp) - temp) if normalization_term: probabilities = (np.max(temp) - temp) / np.sum(np.max(temp) - temp) else: probabilities = np.ones( size_of_population) / size_of_population id_of_chosen = np.random.choice(np.arange(size_of_population), 1, p=probabilities) chosen = population[id_of_chosen][0].copy() chosen[int(last_added_subset[id_of_chosen])] = 0 bin = binary_list_to_ids(chosen) mask = (np.random.rand(bin.shape[0]) * (1 / (1 - crossover_parameter))).astype(int).astype(bool) population[j] = ids_to_binary_list( bin[mask], transcription_matrix.shape[0]) if founded: return chromosome_fitness_tracking[:, :i + 1].astype( int), number_of_ones_tracking[:, :i + 1].astype( int), winning_chromosome.astype(int) return chromosome_fitness_tracking.astype( int), number_of_ones_tracking.astype(int), winning_chromosome.astype( int)
def Progressive_evolutionary_algorithm(transcription_matrix, size_of_population, max_iter, tqdm_mode=False): # initialization of first generation sol = np.hstack([np.ones(1), np.zeros(transcription_matrix.shape[0] - 1)]) sol = sol.astype(int) np.random.shuffle(sol) population = sol for _ in range(size_of_population - 1): np.random.shuffle(sol) population = np.vstack([population, sol]) chromosome_fitness_tracking = np.zeros([size_of_population, max_iter]) number_of_ones_tracking = np.zeros([size_of_population, max_iter]) last_added_subset = np.ones(size_of_population) * (-1) founded = False winning_chromosome = np.empty([]) if tqdm_mode: this_range = tqdm(range(max_iter)) else: this_range = range(max_iter) for i in this_range: for j in range(size_of_population): current_fitness = fitness_function(population[j], transcription_matrix) chromosome_fitness_tracking[j, i] = current_fitness number_of_ones_tracking[j, i] = np.sum(population[j]) if current_fitness == 0: print("I found it!") founded = True winning_chromosome = population[j] else: if np.sum(transcription_matrix[population[j].astype(bool)].sum( axis=0) > 1) == 0: last_added_subset[j] = np.random.choice( np.argwhere(population[j] == 0).flatten()) population[j, int(last_added_subset[j])] = 1 else: if last_added_subset[j] != -1: index_of_chosen_zero = np.random.choice( np.argwhere(population[j] == 0).flatten()) population[j, index_of_chosen_zero] = 1 population[j, int(last_added_subset[j])] = 0 last_added_subset[j] = index_of_chosen_zero else: index_of_chosen_zero = np.random.choice( np.argwhere(population[j] == 0).flatten()) index_of_chosen_one = np.random.choice( np.argwhere(population[j] == 1).flatten()) population[j, index_of_chosen_one] = 0 population[j, index_of_chosen_zero] = 1 last_added_subset[j] = index_of_chosen_one if founded: return chromosome_fitness_tracking[:, :i + 1], number_of_ones_tracking[:, : i + 1], winning_chromosome return chromosome_fitness_tracking, number_of_ones_tracking, winning_chromosome