This repository has been archived on 2021-10-31. You can view files and clone it, but cannot push or open issues or pull requests.
AICup/src/TSP_solver.py

127 lines
5.4 KiB
Python
Raw Normal View History

2019-11-18 07:04:42 +00:00
from time import time as t
2019-11-18 07:15:29 +00:00
import numpy as np
2019-11-18 07:28:06 +00:00
import matplotlib.pyplot as plt
2020-09-25 11:20:28 +00:00
2020-09-25 11:38:17 +00:00
from src.two_opt import loop2opt
from src.two_dot_five_opt import loop2dot5opt
from src.simulated_annealing import sa
2020-09-25 11:20:28 +00:00
from src.constructive_algorithms import random_method, nearest_neighbor, best_nearest_neighbor, multi_fragment_mf
from src.ant_colony import ant_colony_opt
2019-11-09 15:41:14 +00:00
# available_solvers = {"random": random_method,
# "nearest_neighbors": nearest_neighbor,
# "best_nn": best_nearest_neighbor,
# "multi_fragment": multi_fragment_mf
# }
2020-09-28 07:30:21 +00:00
available_improvers = {"2-opt": loop2opt,
"2.5-opt": loop2dot5opt,
"simulated_annealing": sa}
2019-10-23 19:07:20 +00:00
# available_solvers = {}
# for i in range(1, 10):
# for j in range(1, 10):
# available_solvers["aco_" + str(i) + "_" + str(j)] = ant_colony_opt(i/10, j)
available_solvers = {"aco": ant_colony_opt}
2019-10-23 19:07:20 +00:00
2020-10-19 15:25:30 +00:00
class TSPSolver:
def __init__(self, algorithm_name, problem_instance, passed_avail_solvers=None, passed_avail_improvers=None):
2020-09-28 09:22:14 +00:00
# assert algorithm_name in available_solvers, f"the {algorithm_name} initializer is not available currently."
2020-10-19 15:25:30 +00:00
if passed_avail_improvers is None:
passed_avail_improvers = available_improvers
if passed_avail_solvers is None:
passed_avail_solvers = available_solvers
self.available_improvers = passed_avail_improvers
self.available_solvers = passed_avail_solvers
2020-09-28 07:30:21 +00:00
self.duration = np.inf
2020-09-28 10:13:53 +00:00
self.found_length = np.inf
2020-09-28 07:30:21 +00:00
self.algorithm_name = algorithm_name
self.algorithms = [algorithm_name]
self.name_method = "initialized with " + algorithm_name
2019-10-23 19:07:20 +00:00
self.solved = False
2020-09-28 07:30:21 +00:00
self.problem_instance = problem_instance
2020-09-28 09:07:19 +00:00
self.solution = None
2019-11-18 07:04:42 +00:00
def bind(self, local_or_meta):
2020-10-19 15:25:30 +00:00
assert local_or_meta in self.available_improvers, f"the {local_or_meta} method is not available currently."
2020-09-28 07:30:21 +00:00
self.algorithms.append(local_or_meta)
2019-12-02 07:54:34 +00:00
self.name_method += ", improved with " + local_or_meta
def pop(self):
2020-09-28 07:30:21 +00:00
self.algorithms.pop()
2019-12-02 08:24:08 +00:00
self.name_method = self.name_method[::-1][self.name_method[::-1].find("improved"[::-1]) + len("improved") + 2:][
2019-12-02 07:54:34 +00:00
::-1]
2019-10-23 19:07:20 +00:00
2020-09-28 07:30:21 +00:00
def compute_solution(self, verbose=True, return_value=True):
2019-11-04 05:43:54 +00:00
self.solved = False
2019-10-23 19:07:20 +00:00
if verbose:
2020-09-28 07:30:21 +00:00
print(f"### solving with {self.algorithms} ####")
start_time = t()
2020-10-19 15:25:30 +00:00
self.solution = self.available_solvers[self.algorithms[0]](self.problem_instance)
if not self.check_if_solution_is_valid():
2020-11-01 18:24:26 +00:00
print(f"Error the solution of {self.algorithm_name} for problem {self.problem_instance.name} is not valid")
if return_value:
return False
2020-09-28 07:30:21 +00:00
for i in range(1, len(self.algorithms)):
2020-11-01 18:24:26 +00:00
improver = self.algorithms[i]
self.solution = self.available_improvers[improver](self.solution, self.problem_instance)
if not self.check_if_solution_is_valid():
2020-11-22 19:40:02 +00:00
print(
f"Error the solution of {self.algorithm_name} with {improver} for problem {self.problem_instance.name} is not valid")
2020-11-01 18:24:26 +00:00
if return_value:
return False
2019-11-18 07:04:42 +00:00
2020-09-28 07:30:21 +00:00
end_time = t()
self.duration = np.around(end_time - start_time, 3)
2019-11-18 07:28:06 +00:00
self.solved = True
2019-10-31 15:17:47 +00:00
self.evaluate_solution()
self._gap()
2019-10-23 19:15:35 +00:00
if return_value:
return self.solution
2019-10-23 19:07:20 +00:00
def plot_solution(self):
2020-09-28 07:30:21 +00:00
assert self.solved, "You can't plot the solution, you need to compute it first!"
2019-10-23 19:07:20 +00:00
plt.figure(figsize=(8, 8))
2019-11-04 05:43:54 +00:00
self._gap()
2020-09-28 07:30:21 +00:00
plt.title(f"{self.problem_instance.name} solved with {self.name_method} solver, gap {self.gap}")
ordered_points = self.problem_instance.points[self.solution]
2019-10-23 19:07:20 +00:00
plt.plot(ordered_points[:, 1], ordered_points[:, 2], 'b-')
2019-10-31 15:08:29 +00:00
plt.show()
2019-10-23 19:07:20 +00:00
2020-10-19 15:25:30 +00:00
def check_if_solution_is_valid(self):
2020-09-28 09:07:19 +00:00
rights_values = np.sum(
2020-11-22 19:40:02 +00:00
[self.check_validation(i, self.solution[:-1]) for i in np.arange(self.problem_instance.nPoints)])
2020-11-01 18:24:26 +00:00
# rights_values = np.sum(
# [1 if np.sum(self.solution[:-1] == i) == 1 else 0 for i in np.arange(self.problem_instance.nPoints)])
2020-11-22 19:40:02 +00:00
return rights_values == self.problem_instance.nPoints
2020-09-28 07:30:21 +00:00
2020-11-01 18:24:26 +00:00
def check_validation(self, node, solution):
if np.sum(solution == node) == 1:
return 1
else:
return 0
2019-10-23 19:07:20 +00:00
2019-10-31 15:17:47 +00:00
def evaluate_solution(self, return_value=False):
2019-10-23 19:07:20 +00:00
total_length = 0
starting_node = self.solution[0]
from_node = starting_node
for node in self.solution[1:]:
2020-09-28 07:30:21 +00:00
total_length += self.problem_instance.dist_matrix[from_node, node]
2019-10-23 19:07:20 +00:00
from_node = node
self.found_length = total_length
if return_value:
return total_length
2020-11-22 19:40:02 +00:00
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)])
# rights_values = np.sum(
# [1 if np.sum(solution[:-1] == i) == 1 else 0 for i in np.arange(self.problem_instance.nPoints)])
return rights_values == self.problem_instance.nPoints
2019-10-23 19:07:20 +00:00
def _gap(self):
self.evaluate_solution(return_value=False)
2020-09-28 07:30:21 +00:00
self.gap = np.round(
((self.found_length - self.problem_instance.best_sol) / self.problem_instance.best_sol) * 100, 2)