def ga_search(target, number_of_iterations=50, population_size=100): best_solution = None initial_population = generate_population(target, population_size) for iterations_counter in range(number_of_iterations): estimated_population = estimate_population(initial_population, target) # selection = sorted(estimated_population.items(), key=lambda x: x[1]) # selection = [key for key, value in estimated_population.items()] selection = select_population(estimated_population) elite_solutions = selection[:50] offsprings = crossover(elite_solutions) estimated_offsprings = estimate_population(offsprings, target) selected_offsprings = select_population(estimated_offsprings) best_solution_in_generation = selected_offsprings[0] best_solution_in_generation_score = estimate_solution(best_solution_in_generation, target) # counter1 += int(best_solution_in_generation[1]) print("Best solution in iteration {} is {} -> {}".format(iterations_counter, best_solution_in_generation, best_solution_in_generation_score)) if best_solution is None: best_solution = best_solution_in_generation if estimate_solution(best_solution_in_generation, target) < estimate_solution(best_solution, target): best_solution = best_solution_in_generation best_solution_score = estimate_solution(best_solution, target) elite_solutions.append(best_solution) initial_population = mutate_population(selection) for elites in elite_solutions: initial_population.append(elites) print("Best solution {} -> {}".format(best_solution, best_solution_score))
def simulate(target: np.ndarray) -> None: """ Start main GA loop :param target: target image """ population = generate_population(POPULATION_SIZE, target.shape, default_color=BACKGROUND_COLOR) fitness = calculate_population_fitness(population, target) start = time() print("Started evolution") for step in range(4294967296): # 2^32 parents = select_breeding_pool(population, fitness, BREEDING_INDIVIDUALS) crossover = do_crossover(parents, BREEDING_INDIVIDUALS, target.shape, CROSSOVER_INDIVIDUALS) mutation = mutate(crossover, target.shape, CROSSOVER_INDIVIDUALS, LINE_LENGTH, target) population[0:parents.shape[0], :] = parents population[parents.shape[0]:, :] = mutation fitness = calculate_population_fitness(population, target) best_ind_index = np.argmin(fitness) best_ind = population[best_ind_index] cv2.imshow("Current-min", best_ind) cv2.waitKey(1) if step % 500 == 0: print('%.6d - %.6f seconds' % (step, (time() - start)), end='\t\t') print('Fitness -\t{}'.format(np.min(fitness))) best_ind_index = np.argmin(fitness) best_ind = population[best_ind_index] cv2.imwrite(f"./out/{step}-{fitness[best_ind_index]}.jpg", best_ind)
def find_solution(): print '\n\n## Searching for the best solution ' population = generate_population(population_size, backpack_capacity) value = [] iteraction = [] best_solution = None for i in range(max_generations): fitness = calculate_fitness(population, items, max_weight) parents = parent_selection(fitness) crossovered = apply_crossover(parents, backpack_capacity, crossover_probability, mutation_probability) population = calculate_fitness(crossovered, items, max_weight) candidate, _ = find_two_fittest_individuals(population) if best_solution is None: best_solution = candidate elif candidate.value > best_solution.value: best_solution = candidate value.append(best_solution.value) iteraction.append(i) if i % 100 == 0: print '\nCurrent generation..: {}'.format(i) print 'Best solution so far: {}'.format(best_solution.value) print '\n\n## Best solution found:' print '\nWeight: {}'.format(best_solution.weight) print 'Value.: {}'.format(best_solution.value) print '\nBackpack configuration: {}'.format(best_solution.cromossome) plt.plot(iteraction, value) plt.xlabel('Generation') plt.ylabel('Value') plt.show()
import numpy as np from utils import read_fasta, estimate_population, generate_population initial_alignment_df = read_fasta(filename='dataset/BB11001-m.fa') # initial_alignment = [np.fromstring(sequence, dtype=np.uint8) for sequence in initial_alignment_df.get("sequence")] initial_alignment = [ sequence for sequence in initial_alignment_df.get("sequence") ] # initial_alignment = np.array(initial_alignment) population = generate_population(size=20, alignment=initial_alignment) print(population) print(estimate_population(population)) # # print(f'Estimated sequence value: {estimated_value}')
file[0].split(' ')[1]) wt = [float(i) for i in file[1::]] job_machine_time = JobMachine(num_jobs) jm_count = 0 for n in range(num_jobs): for p in range(num_machines): job_machine_time.set_wt(p, n, wt[jm_count]) jm_count += 1 for iteration in iterations: for pop in pop_size: population = [] for i in range(pop): population.append(generate_population(num_jobs, num_machines)) print("Population\n", population) g = GenerationTool(num_jobs, num_machines, population, job_machine_time, iteration, pop, file_name) g.calculate_individual_worktime() print("Population worktime\n") print(g.population_worktime) g.first_gen() for i in range(1, iteration + 1): g.create_new_gen(i)
def search(number_of_cities, number_of_iterations, population_size): np.random.seed(1) city_coordinates = np.random.rand(number_of_cities, 2) # city_coordinates = load_coordinates("att48_xy.txt") print(city_coordinates) distance_matrix = squareform(pdist(city_coordinates, 'euclidean')) scouts = int(population_size / 10) workers = population_size - scouts best_solution = None # global_solutions = generate_population(number_of_cities, scouts) global_solutions = generate_population(len(city_coordinates), scouts) for iterations_counter in range(number_of_iterations): estimated_global_solutions = estimate_population( global_solutions, distance_matrix) local_solutions = workers_activity(workers, estimated_global_solutions[:15], distance_matrix) estimated_local_solutions = estimate_population( local_solutions, distance_matrix) new_population_size = len(local_solutions) - len( estimated_local_solutions) new_population = generate_population(len(city_coordinates), new_population_size * 10) estimated_new_population = estimate_population(new_population, distance_matrix) for solution in estimated_new_population[:int(new_population_size / 10)]: estimated_local_solutions.append(solution) elite_solutions = estimated_local_solutions[:15] best_solution_in_generation = estimated_local_solutions[0] best_solution_in_generation_score = estimate_solution( best_solution_in_generation, distance_matrix) # print(f"Best solution in iter {iterations_counter} is {best_solution_in_generation} -> {best_solution_in_generation_score}") print( f"Best solution score in iter {iterations_counter} is {best_solution_in_generation_score}" ) print(f"Number of local solutions: {len(local_solutions)}") print( f"Number of local estimated_local_solutions: {len(estimated_local_solutions)}" ) print(f"Number of elites: {len(elite_solutions)}") if best_solution is None: best_solution = best_solution_in_generation best_solution_score = best_solution_in_generation_score if best_solution_in_generation_score < best_solution_score: best_solution = best_solution_in_generation best_solution_score = best_solution_in_generation_score # elif random.randint(1, number_of_iterations) < iterations_counter: # elite_solutions.append(best_solution_in_generation) if estimate_solution(best_solution, distance_matrix) == 0: break global_solutions = elite_solutions plotTSP(best_solution, city_coordinates) return best_solution, best_solution_score
def iteratingMain(): population = generate_population() time_step = params['TIME_STEP'] max_time = params['SIMULATION_TIME'] iterator(population, time_step, max_time)