def tsp(knoten, graph): small_graph = np.array([[ graph[knoten[index]][knoten[j]].distanz for j in range(0, len(knoten)) ] for index in range(0, len(knoten))]) permutation, distance = solve_tsp_dynamic_programming(small_graph) return [knoten[p] for p in permutation if knoten[p]]
async def get_route(places_ids: List[int], lat: float, lon: float): places = await data.get_places_by_ids(places_ids) if len(places) <= 1: return [] sources = np.array([[lat, lon]]) i = 0 for place in places: print('index', i) i += 1 print('id', place['id']) place_coords = np.array([[place['lat'], place['lon']]]) sources = np.concatenate((sources, place_coords)) distance_matrix = great_circle_distance_matrix(sources) permutation, distance = solve_tsp_dynamic_programming(distance_matrix) print(permutation) route = [] for place_index in permutation[1:]: print('index', place_index - 1) print('id', places[place_index - 1]['id']) route.append(places[place_index - 1]) return [Place(**place) for place in places]
def test_solution_is_optimal( self, distance_matrix, expected_permutation, expected_distance ): """This exact method should return an optimal solution""" permutation, distance = solve_tsp_dynamic_programming(distance_matrix) assert permutation == expected_permutation assert distance == expected_distance
def test_solution_has_all_nodes(self, distance_matrix): """Check if the solution has all input nodes in any order """ permutation, _ = solve_tsp_dynamic_programming(distance_matrix) n = distance_matrix.shape[0] assert len(permutation) == n assert set(permutation) == set(range(n))
def rota_mais_curta(dic_capitais, lista_produtos, modal): #Matriz de distâncias entre as cidades matriz_dist = [] #Vetor de distância para São Paulo especificamente dist_sp = [0] #Monta vetor de distância para SP for produto in lista_produtos: d = calcular_distancia(dic_capitais, 'Sao Paulo', produto["destino"], modal) dist_sp.append(d) matriz_dist.append(dist_sp) #Monta vetor de distância para cada cidade for produto in lista_produtos: vetor_dist = [] d = calcular_distancia(dic_capitais, 'Sao Paulo', produto["destino"], modal) vetor_dist.append(d) for outro_prod in lista_produtos: if produto["destino"] == outro_prod["destino"]: d = 0 else: d = calcular_distancia(dic_capitais, produto["destino"], outro_prod["destino"], modal) vetor_dist.append(d) matriz_dist.append(vetor_dist) #Transforma numa matriz np np_matriz_dist = np.array(matriz_dist) #Calcula rota mais curta, com cada cidade (nó) representado por números rota, distancia_total = solve_tsp_dynamic_programming(np_matriz_dist) #Dicionário para traduzir os números para nomes de cidade dic_rota = {0 : 'Sao Paulo'} #Monta dicionário for i in range(1, len(lista_produtos) + 1): dic_rota[i] = lista_produtos[i - 1]["destino"] rota_nomes = [] for num in rota: rota_nomes.append(dic_rota[num]) #Retorna uma lista com as cidades que devem ser visitadas, em ordem e #começando por São Paulo return rota_nomes
def solveTSP(locations): graph = [] print("---------------locations-------------------") print(locations) print("---------------locations-------------------") for i in range(len(locations)): item = [] for j in range(len(locations)): item.append(geodesic(locations[i], locations[j]).km) graph.append(item) distance_matrix = np.array(graph) permutation, distance = solve_tsp_dynamic_programming(distance_matrix) res = [] index = 0 print("---------------permutation-------------------") print(permutation) print("---------------permutation-------------------") for i in permutation: if i == 0: break index = index + 1 print("---------------index-------------------") print(index) print("---------------index-------------------") for i in range(len(permutation)): res.append({ "lat" : locations[(permutation[index+i])%len(locations)][0], "lng" : locations[(permutation[index+i])%len(locations)][1] }) print("---------------res-------------------") print(res) print("---------------res-------------------") return {"locations":res, "distance": distance}
def shortest_path(distance_matrix): distance_matrix[:, 0] = 0 permutation, distance = solve_tsp_dynamic_programming(distance_matrix) return permutation, distance
from TripsAggregaters import * from python_tsp.exact import solve_tsp_dynamic_programming import numpy i = 0 while (i < number_of_groups): newDistanceArray = numpy.array(gtrips[i].distance_matrix) permutation, distance = solve_tsp_dynamic_programming(newDistanceArray) i = i + 1 print(distance)
def step(positions, visited, costs): new_positions = [] for cost, pos in positions: for m in [m for m in neighbors(*pos) if m not in visited]: visited.add(m) new_positions.append((cost + 1, m)) if t[m] > 0: costs[t[m]] = cost + 1 return new_positions def BFS(start=1): start_pos = list(zip(*np.where(t == start)))[0] visited, positions, costs = {start_pos}, [(0, start_pos)], {start: 0} while positions: positions = step(positions, visited, costs) return costs DIR = pathlib.Path(__file__).parent.absolute() t = read() if __name__ == "__main__": cost = np.zeros((t[t < 10].max(), t[t < 10].max()), dtype=np.uint32) for i in range(t[t < 10].max()): for j, c in BFS(i + 1).items(): cost[i, j - 1] = c roundtrip = solve_tsp_dynamic_programming(cost)[1] cost[:, 0] = 0 print(solve_tsp_dynamic_programming(cost)[1]) print(roundtrip)
def text_order_in_frame(text_boxes: List[Dict[str, Any]]) -> List[str]: if len(text_boxes) == 0: return [] id_to_text = {} for text in text_boxes: id = text["@id"] id_to_text[id] = text["#text"] frames_dict = {} x_max = -1 x_min = 2000 y_max = -1 y_min = 2000 # Find the min for frame in text_boxes: if int(frame["@xmin"]) < x_min: x_min = int(frame["@xmin"]) if int(frame["@ymin"]) < y_min: y_min = int(frame["@ymin"]) if int(frame["@xmax"]) > x_max: x_max = int(frame["@xmax"]) if int(frame["@ymax"]) > y_max: y_max = int(frame["@ymax"]) for frame in text_boxes: id = frame["@id"] topright = (int(frame["@xmax"]), int(frame["@ymin"])) botleft = (int(frame["@xmin"]), int(frame["@ymax"])) n_tr = (round((topright[0] - x_min)), round((topright[1] - y_min))) n_bl = (round((botleft[0] - x_min)), round((botleft[1] - y_min))) next_center = ((n_tr[0] + n_bl[0]) / 2, (n_tr[1] + n_bl[0]) / 2) frames_dict[id] = (n_tr, n_bl, next_center) toprightmost = list(frames_dict.keys())[0] toprightmostvalue = ( (y_max - y_min) - frames_dict[toprightmost][0][1]) + frames_dict[toprightmost][0][0] for id, (tr, bl, c) in frames_dict.items(): value = ((y_max - y_min) - tr[1]) + tr[0] if value == toprightmostvalue and tr[1] < frames_dict[toprightmost][0][ 1]: toprightmost = id elif value > toprightmostvalue: toprightmost = id toprightmostvalue = value idx_to_id = {0: toprightmost} i = 1 for id, (tr, bl, c) in frames_dict.items(): if id == toprightmost: continue idx_to_id[i] = id i += 1 sources = [] for i in range(len(idx_to_id)): sources.append(frames_dict[idx_to_id[i]][2]) distance_matrix = great_circle_distance_matrix(np.array(sources)) distance_matrix[:, 0] = 0 if len(sources) > 20: text_box_order, _ = solve_tsp_simulated_annealing(distance_matrix) else: text_box_order, _ = solve_tsp_dynamic_programming(distance_matrix) final_order = [] for idx in text_box_order: final_order.append(id_to_text[idx_to_id[idx]]) return final_order
def get_solution(locations): distance_matrix = euclidean_distance_matrix(locations) return solve_tsp_dynamic_programming(distance_matrix)
testpts_alphabets = [ 'Start', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K' ] df = pd.DataFrame(testpts_coords, columns=['xcoord', 'ycoord'], index=testpts_alphabets) dist_mat = pd.DataFrame(distance_matrix(df.values, df.values), index=df.index, columns=df.index) dist_mat_test = dist_mat dist_mat = dist_mat.to_numpy() permutation, distance = solve_tsp_dynamic_programming(dist_mat) shortest_route = [] for each_pt in permutation: shortest_route.append(testpts_alphabets[each_pt]) print('\nShortest Route:', shortest_route) print('Distance:', distance, '\n') # Testing if indeed, that is the shortest distance computed # proposed_route = [ # 'Start', # 'A', 'B', 'C', 'D', 'E', # 'F', 'G', 'H', 'I', 'J', # 'K' # ] proposed_route = [
def minimum_route_distance_calculator(self): newDistanceArray = numpy.array(self.distance_matrix) permutation, distance = solve_tsp_dynamic_programming(newDistanceArray) self.minimum_route_distance = distance self.minimum_route = permutation
def optimal_permutation(self): return solve_tsp_dynamic_programming(self.goal_matrix)
best_neighbor, best_neighbor_path = neighbors(matrix, neighbor) if current_path < global_path: global_path = current_path global_solution = current_solution current_solution = random_solution(matrix, initial_point) current_path = calculate_distance(matrix, current_solution) neighbor = neighbors(matrix, current_solution)[0] best_neighbor, best_neighbor_path = neighbors(matrix, neighbor) return global_path, global_solution, time.time() - start_time sources = np.array([[40.73024833, -73.79440675], [41.47362495, -73.92783272], [41.26591, -73.21026228], [41.3249908, -73.507788]]) distance_with_numba, b, c = best_solution(sources) print(distance_with_numba) from python_tsp.distances import euclidean_distance_matrix from python_tsp.exact import solve_tsp_dynamic_programming distance_matrix = euclidean_distance_matrix(sources) permutation, distance_without_numba = solve_tsp_dynamic_programming( distance_matrix) def test_distance(): assert np.linalg.norm(distance_without_numba - distance_with_numba) < 1e-3
import numpy as np import pathlib from python_tsp.exact import solve_tsp_dynamic_programming def read(): with open(DIR / "input") as f: s = (f.read() if teststr == "" else teststr).splitlines() ns, costs = {}, {} for i in s: p1 = ns.get(i.split(" ")[0], len(ns)) ns[i.split(" ")[0]] = p1 p2 = ns.get(i.split(" ")[2], len(ns)) ns[i.split(" ")[2]] = p2 c = int(i.split(" ")[-1]) costs[(p1, p2)] = c A = np.zeros((len(ns) + 1, len(ns) + 1)) # + float("inf") for tup, c in costs.items(): A[tup[0] + 1, tup[1] + 1] = A[tup[1] + 1, tup[0] + 1] = c return A teststr = """""" DIR = pathlib.Path(__file__).parent.absolute() A = read() if __name__ == "__main__": print(int(solve_tsp_dynamic_programming(A)[1])) print(-int(solve_tsp_dynamic_programming(-A)[1]))