import math import random from model.base_model import Model class MyASModel(Model): def __init__(self): super().__init__() def init(self, nodes): """ Put your initialization here. """ super().init(nodes) def getMST(self, node): MST = [] distances = [] for i in range(0, self.N): if i != node: MST.append(i) distances.append(self.dist(node, i)) return [x for _,x in sorted(zip(distances, MST))] def fit(self, max_it=1000): """ Put your iteration process here. """ MST_solutions = [] for i in range(0, self.N): solution = [i] MST_solutions.append(solution) # Breadth First: Set each city as starting point, then go to next city simultaneously for step in range(0, self.N - 1): # print("[step]", step) unvisited_list = list(range(0, self.N)) # For each search path for i in range(0, self.N): cur_city = MST_solutions[i][-1] unvisited_list = list( set(range(0, self.N)) - set(MST_solutions[i]) ) closest_neighbour = -1 min_f = math.inf for j in unvisited_list: g = self.dist(cur_city, j) sub_unvisited_list = unvisited_list.copy() sub_unvisited_list.remove(j) sub_cur_city = self.getMST(j)[0] h = 0 while len(sub_unvisited_list) > 0: if(len(unvisited_list) == 2): break else: for k in self.getMST(sub_cur_city): if k in sub_unvisited_list: h = h + self.dist(sub_cur_city, k) sub_cur_city = k sub_unvisited_list.remove(k) break # Get f(x) = g(x) + h(x) f = g + h if(f < min_f): closest_neighbour = j min_f = f MST_solutions[i].append(closest_neighbour) for i in range(0, self.N): self.fitness_list.append(self.fitness(MST_solutions[i])) self.best_solution = MST_solutions[ self.fitness_list.index(min(self.fitness_list)) ] return self.best_solution, self.fitness_list