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

99 lines
3.8 KiB
Python
Raw Normal View History

2019-10-23 19:07:20 +00:00
from numpy.core._multiarray_umath import ndarray
2019-11-09 15:43:54 +00:00
import os
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-09 15:43:36 +00:00
if 'AI' in os.getcwd():
2019-11-18 06:12:00 +00:00
from src import *
2019-11-09 15:43:36 +00:00
else:
2019-11-18 06:12:00 +00:00
from AI2019.src import *
2019-11-09 15:41:14 +00:00
2019-10-23 19:07:20 +00:00
class Solver_TSP:
solution: ndarray
found_length: float
2019-11-18 06:12:00 +00:00
available_initializers = {"random": random_initialier.random_method,
"nearest_neighbors": nearest_neighbor.nn,
"best_nn": nearest_neighbor.best_nn,
2019-11-18 07:04:42 +00:00
"multi_fragment": multi_fragment.mf
}
2019-10-23 19:07:20 +00:00
2019-11-18 07:04:42 +00:00
available_improvements = {"2-opt": TwoOpt.loop2opt,
"2.5-opt": TwoDotFiveOpt.loop2dot5opt}
def __init__(self, initializer):
2019-11-18 06:12:00 +00:00
# self.available_methods = {"random": self.random_method, "nearest_neighbors": self.nn,
# "best_nn": self.best_nn, "multi_fragment": self.mf}
2019-11-18 07:04:42 +00:00
self.initializer = initializer
self.methods = [initializer]
2019-11-18 07:15:29 +00:00
self.name_method = "initialize with " + initializer
2019-10-23 19:07:20 +00:00
self.solved = False
2019-11-18 07:04:42 +00:00
assert initializer in self.available_initializers, f"the {initializer} initializer is not available currently."
def bind(self, local_or_meta):
assert local_or_meta in self.available_improvements, f"the {local_or_meta} method is not available currently."
self.methods.append(local_or_meta)
2019-11-18 07:15:29 +00:00
self.name_method = ", improve with " + local_or_meta
2019-10-23 19:07:20 +00:00
2019-10-23 19:15:35 +00:00
def __call__(self, instance_, verbose=True, return_value=True):
2019-10-23 19:07:20 +00:00
self.instance = instance_
2019-11-04 05:43:54 +00:00
self.solved = False
2019-10-23 19:07:20 +00:00
if verbose:
2019-11-18 07:04:42 +00:00
print(f"### solving with {self.methods} ####")
start = t()
self.solution = self.available_initializers[self.methods[0]](instance_)
2019-10-23 19:07:20 +00:00
assert self.check_if_solution_is_valid(self.solution), "Error the solution is not valid"
2019-11-18 07:18:16 +00:00
print("init ok")
2019-11-18 07:04:42 +00:00
for i in range(1, len(self.methods)):
self.solution = self.available_improvements[self.methods[i]](self.solution, self.instance)
2019-11-18 07:21:05 +00:00
print(len(self.solution))
2019-11-18 07:04:42 +00:00
assert self.check_if_solution_is_valid(self.solution), "Error the solution is not valid"
2019-11-18 07:18:16 +00:00
print("improve ok")
2019-11-18 07:04:42 +00:00
end = t()
2019-11-18 07:15:29 +00:00
self.time_to_solve = np.around(end - start,3)
2019-10-31 15:17:47 +00:00
self.evaluate_solution()
self._gap()
2019-10-23 19:07:20 +00:00
if verbose:
2019-11-18 07:15:29 +00:00
print(f"### solution found with {self.gap} % gap in {self.time_to_solve} seconds ####")
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):
assert self.solved, "You can't plot the solution, you need to solve it first!"
plt.figure(figsize=(8, 8))
2019-11-04 05:43:54 +00:00
self._gap()
2019-11-18 07:15:29 +00:00
plt.title(f"{self.instance.name} solved with {self.name_method} solver, gap {self.gap}")
2019-10-23 19:07:20 +00:00
ordered_points = self.instance.points[self.solution]
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
def check_if_solution_is_valid(self, solution):
2019-10-31 13:25:43 +00:00
rights_values = np.sum([self.check_validation(i, solution[:-1]) for i in np.arange(self.instance.nPoints)])
2019-10-23 19:07:20 +00:00
if rights_values == self.instance.nPoints:
return True
else:
return False
def check_validation(self, node, solution):
if np.sum(solution == node) == 1:
return 1
else:
return 0
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:]:
total_length += self.instance.dist_matrix[from_node, node]
from_node = node
self.found_length = total_length
if return_value:
return total_length
def _gap(self):
self.evaluate_solution(return_value=False)
2019-10-31 15:54:17 +00:00
self.gap = np.round(((self.found_length - self.instance.best_sol) / self.instance.best_sol) * 100, 2)