(
dataset_name,
num_generations,
population_size,
mutation_prob,
chart,
plot,
progress_bar,
current_distance,
)
| 71 | |
| 72 | |
| 73 | def genetic_tsp( |
| 74 | dataset_name, |
| 75 | num_generations, |
| 76 | population_size, |
| 77 | mutation_prob, |
| 78 | chart, |
| 79 | plot, |
| 80 | progress_bar, |
| 81 | current_distance, |
| 82 | ): |
| 83 | global cities |
| 84 | cities = read_input(f"data/{dataset_name}") |
| 85 | |
| 86 | population = random_population(population_size, len(cities)) |
| 87 | |
| 88 | pop_fitness = [evaluate_fitness(individual) for individual in population] |
| 89 | best_solution = population[np.argmax(pop_fitness)] |
| 90 | best_distance = 1 / evaluate_fitness(best_solution) |
| 91 | |
| 92 | progress_bar.progress(0) |
| 93 | |
| 94 | current_distance.text("") |
| 95 | |
| 96 | solution = copy(best_solution) |
| 97 | solution.append(solution[0]) |
| 98 | |
| 99 | fig, ax = plt.subplots() |
| 100 | |
| 101 | ax.plot( |
| 102 | [cities[i].x for i in solution], |
| 103 | [cities[i].y for i in solution], |
| 104 | "-o", |
| 105 | ) |
| 106 | |
| 107 | plot.pyplot(fig) |
| 108 | |
| 109 | chart.line_chart() |
| 110 | |
| 111 | for gen in range(num_generations): |
| 112 | population_with_offspring = breed(population, mutation_prob) |
| 113 | population = rank_selection(population_with_offspring, population_size) |
| 114 | |
| 115 | pop_fitness = [evaluate_fitness(individual) for individual in population] |
| 116 | best_solution = population[np.argmax(pop_fitness)] |
| 117 | best_distance = 1 / evaluate_fitness(best_solution) |
| 118 | |
| 119 | progress_bar.progress(int(gen / num_generations * 100)) |
| 120 | current_distance.write(f"Current distance: {best_distance}") |
| 121 | chart.add_rows({"Distance": [best_distance]}) |
| 122 | |
| 123 | solution = copy(best_solution) |
| 124 | solution.append(solution[0]) |
| 125 | ax.clear() |
| 126 | ax.plot( |
| 127 | [cities[i].x for i in solution], |
| 128 | [cities[i].y for i in solution], |
| 129 | "-o", |
| 130 | ) |
no test coverage detected