From da5d4ca8ef213c7fd3154a1a694f32c17c2aa9d2 Mon Sep 17 00:00:00 2001 From: UmbertoJr Date: Sun, 10 Nov 2019 10:42:13 +0100 Subject: [PATCH] utils --- src/utils.py | 59 ++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 50 insertions(+), 9 deletions(-) diff --git a/src/utils.py b/src/utils.py index 68fcf52..8d57da3 100644 --- a/src/utils.py +++ b/src/utils.py @@ -1,3 +1,53 @@ +import numpy as np + +def compute_lenght(solution, dist_matrix): + total_length = 0 + starting_node = solution[0] + from_node = starting_node + for node in solution[1:]: + total_length += dist_matrix[from_node, node] + from_node = node + return total_length + + +class random_initialier: + @staticmethod + def random_method(instance_): + n = int(instance_.nPoints) + solution = np.random.choice(np.arange(n), size=n, replace=False) + return np.concatenate([solution, [solution[0]]]) + + +class nearest_neighbor: + @staticmethod + def nn(instance_, starting_node=0): + dist_matrix = np.copy(instance_.dist_matrix) + n = int(instance_.nPoints) + node = starting_node + tour = [node] + 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 + tour.append(starting_node) + return np.array(tour) + + @staticmethod + 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 + + class multi_fragment: @staticmethod @@ -63,12 +113,3 @@ class multi_fragment: sol_list.append(n1) return sol_list - -def compute_lenght(solution, dist_matrix): - total_length = 0 - starting_node = solution[0] - from_node = starting_node - for node in solution[1:]: - total_length += dist_matrix[from_node, node] - from_node = node - return total_length \ No newline at end of file