From 0af91eac3c795d9696ac0d6531bc14d456f810b2 Mon Sep 17 00:00:00 2001 From: UmbertoJr Date: Thu, 31 Oct 2019 16:17:47 +0100 Subject: [PATCH] update --- run.py | 19 +++++++++++-------- src/TSP_solver.py | 10 ++++++---- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/run.py b/run.py index e729c22..f963d58 100644 --- a/run.py +++ b/run.py @@ -5,21 +5,24 @@ import os def run(show_plots=False): # names = [name_ for name_ in os.listdir("./problems") if "tsp" in name_] names = ["ch130.tsp"] + for name in names: print("\n\n#############################") filename = f"problems/{name}" instance = Instance(filename) instance.print_info() - - solver = Solver_TSP('random') - solver(instance, return_value=False) - - print(f"the total length for the solution found is {solver.evaluate_solution()}", - f"while the optimal length is {instance.best_sol}", - f"the gap is {solver.gap} %", sep="\n") if show_plots: instance.plot_data() - solver.plot_solution() + + for method in ["random", "nearest_neighbors"]: + solver = Solver_TSP(method) + solver(instance, return_value=False) + + print(f"the total length for the solution found is {solver.found_length}", + f"while the optimal length is {instance.best_sol}", + f"the gap is {solver.gap} %", sep="\n") + if show_plots: + solver.plot_solution() if __name__ == '__main__': diff --git a/src/TSP_solver.py b/src/TSP_solver.py index 93316ed..3a0a882 100644 --- a/src/TSP_solver.py +++ b/src/TSP_solver.py @@ -17,11 +17,13 @@ class Solver_TSP: def __call__(self, instance_, verbose=True, return_value=True): self.instance = instance_ if verbose: - print("### solving ####") + print(f"### solving with {self.method}####") self.solution = self.available_methods[self.method](instance_) assert self.check_if_solution_is_valid(self.solution), "Error the solution is not valid" + self.evaluate_solution() + self._gap() if verbose: - print("### solution found ####") + print(f"### solution found with {self.gap} ####") self._gap() if return_value: return self.solution @@ -50,7 +52,7 @@ class Solver_TSP: 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) + plt.title(f"{self.instance.name} with gap {self.gap}") ordered_points = self.instance.points[self.solution] plt.plot(ordered_points[:, 1], ordered_points[:, 2], 'b-') plt.show() @@ -68,7 +70,7 @@ class Solver_TSP: else: return 0 - def evaluate_solution(self, return_value=True): + def evaluate_solution(self, return_value=False): total_length = 0 starting_node = self.solution[0] from_node = starting_node