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

135 lines
5.3 KiB
Python
Raw Normal View History

2019-10-23 19:07:20 +00:00
import numpy as np
from matplotlib import pyplot as plt
from numpy.core._multiarray_umath import ndarray
2019-11-09 15:19:04 +00:00
from src.utils import *
2019-10-23 19:07:20 +00:00
class Solver_TSP:
solution: ndarray
found_length: float
def __init__(self, method):
2019-10-31 15:26:12 +00:00
self.available_methods = {"random": self.random_method, "nearest_neighbors": self.nn,
2019-11-09 15:19:38 +00:00
"best_nn": self.best_nn, "multi_fragment": self.mf}
2019-10-23 19:07:20 +00:00
self.method = method
self.solved = False
assert method in self.available_methods, f"the {method} method is not available currently."
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-10-31 15:19:43 +00:00
print(f"### solving with {self.method} ####")
2019-10-23 19:07:20 +00:00
self.solution = self.available_methods[self.method](instance_)
assert self.check_if_solution_is_valid(self.solution), "Error the solution is not valid"
2019-10-31 15:17:47 +00:00
self.evaluate_solution()
self._gap()
2019-10-23 19:07:20 +00:00
if verbose:
2019-10-31 15:19:43 +00:00
print(f"### solution found with {self.gap} % gap ####")
2019-10-23 19:07:20 +00:00
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 random_method(self, instance_):
n = int(instance_.nPoints)
2019-10-31 15:00:34 +00:00
solution = np.random.choice(np.arange(n), size=n, replace=False)
self.solution = np.concatenate([solution, [solution[0]]])
2019-10-23 19:07:20 +00:00
self.solved = True
return self.solution
2019-10-29 12:28:47 +00:00
def nn(self, instance_, starting_node=0):
2019-10-31 10:57:26 +00:00
dist_matrix = np.copy(instance_.dist_matrix)
n = int(instance_.nPoints)
2019-10-31 15:54:17 +00:00
node = starting_node
2019-10-31 10:57:26 +00:00
tour = [node]
2019-10-31 15:32:43 +00:00
for _ in range(n - 1):
for new_node in np.argsort(dist_matrix[node]):
if new_node not in tour:
tour.append(new_node)
node = new_node
break
2019-10-31 14:49:48 +00:00
tour.append(starting_node)
2019-10-31 10:57:26 +00:00
self.solution = np.array(tour)
self.solved = True
return self.solution
2019-10-23 19:07:20 +00:00
2019-10-31 15:26:12 +00:00
def best_nn(self, instance_):
solutions, lens = [], []
for start in range(self.instance.nPoints):
new_solution = self.nn(instance_, starting_node=start)
solutions.append(new_solution)
assert self.check_if_solution_is_valid(new_solution), "error on best_nn method"
lens.append(self.evaluate_solution(return_value=True))
self.solution = solutions[np.argmin(lens)]
self.solved = True
return self.solution
2019-11-09 15:19:04 +00:00
def mf(self, instance):
mat = np.copy(instance.dist_matrix)
mat = np.triu(mat)
mat[mat == 0] = 100000
solution = {str(i): [] for i in range(instance.nPoints)}
start_list = [i for i in range(instance.nPoints)]
inside = 0
for el in np.argsort(mat.flatten()):
node1, node2 = el // instance.nPoints, el % instance.nPoints
possible_edge = [node1, node2]
if multi_fragment.check_if_available(node1, node2, solution):
if multi_fragment.check_if_not_close(possible_edge, solution, instance.nPoints):
# print("entrato", inside)
solution[str(node1)].append(node2)
solution[str(node2)].append(node1)
if len(solution[str(node1)]) == 2:
start_list.remove(node1)
if len(solution[str(node2)]) == 2:
start_list.remove(node2)
inside += 1
# print(node1, node2, inside)
if inside == instance.nPoints - 1:
# print(f"ricostruire la solutione da {start_list}",
# f"vicini di questi due nodi {[solution[str(i)] for i in start_list]}")
solution = multi_fragment.create_solution(start_list, solution, instance.nPoints)
self.solution = solution
self.solved = True
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-04 05:44:32 +00:00
plt.title(f"{self.instance.name} solved with {self.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)