import random import matplotlib.pyplot as plt # type: ignore from tsp import TSP from tsp_plotter import TSPPlotter random.seed(1) def hill_climb_with_k_opt(tsp, tour, k, plotter): fails_before_quit = 2000 fails = 0 sol = tour score = tsp.score(tour) while fails < fails_before_quit: new_sol = tsp.k_opt(sol, k) new_score = tsp.score(new_sol) if new_score < score: sol = new_sol score = new_score plotter.show_tour(sol) plotter.add_to_score_line(score) plotter.update_best(score) plt.pause(0.0001) fails = 0 else: fails += 1 return sol, score tsp = TSP.from_file("tsp100.txt") plotter = TSPPlotter() while True: sol = tsp.random_grasp_tour(0.2) sol, score = hill_climb_with_k_opt(tsp, sol, 2, plotter) plotter.show_tour(sol) plotter.add_to_score_line(score) plotter.update_best(score) plt.pause(0.0001)