from time import time as t import numpy as np import matplotlib.pyplot as plt from aco.ant_colony import ant_colony_opt class TSPSolver: def __init__(self, problem_instance): self.duration = np.inf self.found_length = np.inf self.solved = False self.problem_instance = problem_instance self.solution = None def compute_solution(self, verbose=True, return_value=True): self.solved = False if verbose: print(f"### solving with 'C++ ant colony optimization' ####") start_time = t() self.solution = ant_colony_opt(self.problem_instance) if not self.check_if_solution_is_valid(): print(f"Error the solution of 'C++ ant colony optimization'" f" for problem {self.problem_instance.name} is not valid") if return_value: return False end_time = t() self.duration = np.around(end_time - start_time, 3) self.solved = True self.evaluate_solution() self._gap() if return_value: return self.solution def plot_solution(self): assert self.solved, "You can't plot the solution, you need to compute it first!" plt.figure(figsize=(8, 8)) self._gap() plt.title(f"{self.problem_instance.name} solved with 'C++ ant colony optimization'" f" solver, gap {self.gap}") ordered_points = self.problem_instance.points[self.solution] plt.plot(ordered_points[:, 1], ordered_points[:, 2], 'b-') plt.show() def check_if_solution_is_valid(self): rights_values = np.sum( [self.check_validation(i, self.solution[:-1]) for i in np.arange(self.problem_instance.nPoints)]) return rights_values == self.problem_instance.nPoints def check_validation(self, node, solution): if np.sum(solution == node) == 1: return 1 else: return 0 def evaluate_solution(self, return_value=False): total_length = 0 starting_node = self.solution[0] from_node = starting_node for node in self.solution[1:]: total_length += self.problem_instance.dist_matrix[from_node, node] from_node = node self.found_length = total_length if return_value: return total_length def pass_and_check_if_solution_is_valid(self, solution): rights_values = np.sum( [self.check_validation(i, solution[:-1]) for i in np.arange(self.problem_instance.nPoints)]) return rights_values == self.problem_instance.nPoints def _gap(self): self.evaluate_solution(return_value=False) self.gap = np.round( ((self.found_length - self.problem_instance.best_sol) / self.problem_instance.best_sol) * 100, 2)