This commit is contained in:
UmbertoJr 2019-10-23 21:07:20 +02:00
parent 2d709b8c42
commit 7ac6af5900
4 changed files with 152 additions and 0 deletions

72
code/TSP_solver.py Normal file
View file

@ -0,0 +1,72 @@
import numpy as np
from matplotlib import pyplot as plt
from numpy.core._multiarray_umath import ndarray
class Solver_TSP:
solution: ndarray
found_length: float
def __init__(self, method):
self.available_methods = {"random": self.random_method, "nearest_neighbors": self.nn}
self.method = method
self.solved = False
assert method in self.available_methods, f"the {method} method is not available currently."
def __call__(self, instance_, verbose=True):
self.instance = instance_
if verbose:
print("### solving ####")
self.solution = self.available_methods[self.method](instance_)
assert self.check_if_solution_is_valid(self.solution), "Error the solution is not valid"
if verbose:
print("### solution found ####")
self._gap()
return self.solution
def random_method(self, instance_):
n = int(instance_.nPoints)
self.solution = np.random.choice(np.arange(n), size=n, replace=False)
self.solved = True
return self.solution
def nn(self, instance_):
pass
def plot_solution(self):
assert self.solved, "You can't plot the solution, you need to solve it first!"
plt.figure(figsize=(8, 8))
plt.title(self.instance.name)
ordered_points = self.instance.points[self.solution]
plt.plot(ordered_points[:, 1], ordered_points[:, 2], 'b-')
def check_if_solution_is_valid(self, solution):
rights_values = np.sum([self.check_validation(i, solution) for i in np.arange(self.instance.nPoints)])
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
def evaluate_solution(self, return_value=True):
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
total_length += self.instance.dist_matrix[from_node, starting_node]
self.found_length = total_length
if return_value:
return total_length
def _gap(self):
self.evaluate_solution(return_value=False)
self.gap = np.round((self.found_length - self.instance.best_sol) / self.instance.best_sol * 100, 2)

2
code/__init__.py Normal file
View file

@ -0,0 +1,2 @@
from code.TSP_solver import *
from code.io_tsp import *

63
code/io_tsp.py Normal file
View file

@ -0,0 +1,63 @@
import numpy as np
from typing import List
from matplotlib import pyplot as plt
from numpy.core._multiarray_umath import ndarray
class Instance:
nPoints: int
best_sol: int
name: str
lines: List[str]
dist_matrix: ndarray
points: ndarray
def __init__(self, name_tsp):
self.read_instance(name_tsp)
def read_instance(self, name_tsp):
# read raw data
file_object = open(name_tsp)
data = file_object.read()
file_object.close()
self.lines = data.splitlines()
# store data set information
self.name = self.lines[0].split(' ')[2]
self.nPoints = np.int(self.lines[3].split(' ')[2])
self.best_sol = np.int(self.lines[5].split(' ')[2])
# read all data points and store them
self.points = np.zeros((self.nPoints, 3))
for i in range(self.nPoints):
line_i = self.lines[7 + i].split(' ')
self.points[i, 0] = line_i[0]
self.points[i, 1] = line_i[1]
self.points[i, 2] = line_i[2]
self.create_dist_matrix()
def print_info(self):
print('name: ' + self.name)
print('nPoints: ' + str(self.nPoints))
print('best_sol: ' + str(self.best_sol))
def plot_data(self):
plt.figure(figsize=(8, 8))
plt.title(self.name)
plt.scatter(self.points[:, 1], self.points[:, 2])
plt.show()
@staticmethod
def distance_euc(zi, zj):
xi, xj = zi[0], zj[0]
yi, yj = zi[0], zj[0]
return round(np.sqrt((xi - xj) ** 2 + (yi - yj) ** 2))
def create_dist_matrix(self):
self.dist_matrix = np.zeros((self.nPoints, self.nPoints))
for i in range(self.nPoints):
for j in range(i, self.nPoints):
self.dist_matrix[i, j] = self.distance_euc(self.points[i][1:3], self.points[j][1:3])

15
run.py Normal file
View file

@ -0,0 +1,15 @@
from code import *
def run():
names = [name_ for name_ in os.listdir("./problems") if "tsp" in name_]
for name in names:
filename = f"problems/{name}"
instance = Instance(filename)
instance.print_info()
print(" --- ")
instance.plot_data()
if __name__ == '__main__':
run()