def concorde_tsp(points, time_bound=3.0, return_ids=False): """ Calculate TSP route using pyconcorde. args: points: (N, 2) numpy array return_ids: bool - also return route node ids returns: tour_points: (N, 2) numpy array tour_ids: ordering of points """ norm = "EUC_2D" solver = TSPSolver.from_data(points[:, 0], points[:, 1], norm) solution = solver.solve(time_bound=time_bound, verbose=False) tour_ids = solution.tour tour_points = [] for idx in tour_ids: tour_points.append(points[idx, :]) tour_points = np.array(tour_points) if return_ids: return tour_points, tour_ids else: return tour_points
def exact(tsp): points = tsp.points * 1000 n, d = points.shape if d != 2: raise Exception(f"Concorde solver currently only supports 2D points. {d}D points given.") xs = points[:, 0] ys = points[:, 1] norm_type = "EUC_2D" with stdout_redirected(), stderr_redirected(): concorde_tsp_instance = TSPSolver.from_data(xs, ys, norm_type) tour, val, success, foundtour, hit_timebound = concorde_tsp_instance.solve() if not success: print("WARNING: Concorde solver failed.") if not foundtour: print("WARNING: Concorde solver did not find a tour.") if hit_timebound: print("WARNING: Concorde solver ran out of time.") tour = tour.tolist() tour.append(tour[0]) tour_len = tsp.tour_length(tour) return tour, tour_len
def solve_it(input_data): lines = input_data.split('\n') node_count = int(lines[0]) if node_count > 1500: return solve_it_ortools(input_data) a = [] b = [] for line in lines[1:-1]: # skipping last line which is blank in data files node1, node2 = line.split() a.append(float(node1)) b.append(float(node2)) data = pd.DataFrame({"A": a, "B": b}) # data.index += 1 # Instantiate solver solver = TSPSolver.from_data(data.A, data.B, norm="EUC_2D") tour_data = solver.solve() assert tour_data.success solution = data.iloc[tour_data.tour] out = ' '.join(str(solution.index[i]) for i in range(len(solution))) output_data = f"{tour_data.optimal_value} {0}\n" output_data += f"{out}" return output_data
def solve_tsp(df, start_pt): df_r = df.copy() to_begin(df_r, start_pt) solver = TSPSolver.from_data(df_r.X, df_r.Y, norm="EUC_2D") tour_c = solver.solve(time_bound=60.0, verbose=True, random_seed=44) for j in range(len(df)): df.iloc[j] = df_r.iloc[tour_c[0][j]]
def compute_example(self): """ Compute pairs (Adjacency, Optimal Tour) """ try: g, W = GENERATOR_FUNCTIONS[self.generative_model](self.n_vertices) except KeyError: raise ValueError('Generative model {} not supported'.format( self.generative_model)) xs = [g.nodes[node]['pos'][0] for node in g.nodes] ys = [g.nodes[node]['pos'][1] for node in g.nodes] problem = TSPSolver.from_data( [self.coeff * elt for elt in xs], [self.coeff * elt for elt in ys], self.distance ) #1e8 because Concorde truncates the distance to the nearest integer solution = problem.solve(verbose=False) assert solution.success, "Couldn't find solution!" #print(W) B = distance_matrix_tensor_representation(W) SOL = torch.zeros((self.n_vertices, self.n_vertices), dtype=torch.int64) prec = solution.tour[-1] for i in range(self.n_vertices): curr = solution.tour[i] SOL[curr, prec] = 1 SOL[prec, curr] = 1 prec = curr return (B, SOL, (xs, ys))
def generate_data(self, num_samples, num_nodes, num_neighbors=-1, file_name=None, seed=0): """ return graph dataset """ np.random.seed(seed) set_nodes_coord = np.random.random([num_samples, num_nodes, 2]) graphs, labels = [], [] start_time = time.time() for nodes_coord in set_nodes_coord: #compute complete graph g = dgl.transform.knn_graph(th.tensor(nodes_coord), num_nodes) solver = TSPSolver.from_data(nodes_coord[:, 0], nodes_coord[:, 1], norm="GEO") solution = solver.solve() nodes_coord = th.tensor(nodes_coord).float() g.ndata['coord'] = nodes_coord graphs.append(g) labels.append(solution.tour) graph_labels = {'tsp_tours': th.tensor(labels).long()} save_graphs(file_name, graphs, graph_labels) end_time = time.time() - start_time print( f"Completed generation of {num_samples} samples of TSP{num_nodes}." ) print(f"Total time: {end_time/60:.1f}min") print(f"Average time: {(end_time/60)/num_samples:.2f}min") print(f"Saved at {file_name}") return graphs, graph_labels
def solve_tsp(dat_file, time_bound=60, verbose=True, norm="EUC_2D", seed=42): image_np = np.load(dat_file) cities = pd.DataFrame(image_np, columns=["X", "Y"]) # solve the TSP. solver = TSPSolver.from_data(cities.X, cities.Y, norm="EUC_2D") t = time.time() tour_data = solver.solve(time_bound=60, verbose=True, random_seed=42) print(f"Finding solution took: {time.time()-t}") print(f"Found Tour: {tour_data.found_tour}") return cities, tour_data
def pool_operation(input_b, it): from concorde.tsp import TSPSolver import os # Concorde solver = TSPSolver.from_data(input_b[it, :, 0] * 1000, input_b[it, :, 1] * 1000, norm="EUC_2D") # Find tour solution = solver.solve() return solution.tour
def generate_data(self, num_samples, num_nodes, node_dim=2, num_neighbors=-1, file_name=None, seed=0): """ return graph dataset """ np.random.seed(seed) set_nodes_coord = np.random.random([num_samples, num_nodes, node_dim]) graphs, labels = [], [] start_time = time.time() for nodes_coord in set_nodes_coord: #compute complete graph g = dgl.transform.knn_graph(th.tensor(nodes_coord), num_nodes) solver = TSPSolver.from_data(nodes_coord[:, 0], nodes_coord[:, 1], norm="GEO") solution = solver.solve() nodes_coord = th.tensor(nodes_coord).float() g.ndata['coord'] = nodes_coord g.apply_edges(fn.u_sub_v('coord', 'coord', 'e')) #distance g.edata['e'] = th.norm(g.edata['e'], dim=1) #neighbors embedding e_tags = th.zeros(g.number_of_edges(), 3).float() e_tags[:, 0] = 1. if num_neighbors != -1: knn = dgl.transform.knn_graph(nodes_coord, num_neighbors) #remove self loop knn = dgl.transform.remove_self_loop(knn) src, dst = knn.edges() edge_nb = g.edge_ids(src, dst) e_tags[edge_nb, :] = th.tensor([0., 1., 0.]) #for self loop self_loop_id = g.edge_ids(list(range(num_nodes)), list(range(num_nodes))) e_tags[self_loop_id, :] = th.tensor([0., 0., 1.]) g.edata['e'] = th.cat((g.edata['e'].unsqueeze(1), e_tags), dim=1) graphs.append(g) labels.append(solution.tour) graph_labels = {'tsp_tours': th.tensor(labels).long()} save_graphs(file_name, graphs, graph_labels) end_time = time.time() - start_time print( f"Completed generation of {num_samples} samples of TSP{num_nodes}." ) print(f"Total time: {end_time/60:.1f}min") print(f"Average time: {(end_time/60)/num_samples:.2f}min") print(f"Saved at {file_name}") return graphs, graph_labels
def solve(inst): # precision factor pr = 1 if np.mean(np.abs(np.array(inst))) < 100: pr = 1e-3 # solve inst = np.array(inst) slr = TSPSolver.from_data(inst[:, 0] / pr, inst[:, 1] / pr, 'EUC_2D') res = slr.solve(verbose=False) return res.tour, res.optimal_value
def test_from_data(self): # Given xs = [1, 2, 3] ys = [4, 5, 6] name = "testdataset" norm = "EUC_2D" # When datagroup = TSPSolver.from_data(xs, ys, norm, name) # Then self.assertIsNotNone(datagroup._data) self.assertEqual(datagroup._ncount, 3) nptest.assert_allclose(datagroup.x, xs) nptest.assert_allclose(datagroup.y, ys)
def generate_data(self): points_list = [] solutions = [] opt_dists = [] data_iter = tqdm(range(self.data_size), unit='data') for i, _ in enumerate(data_iter): data_iter.set_description('Generating data points %i/%i' % (i + 1, self.data_size)) points = np.array(self.data[i]) points_list.append(points) # solutions_iter: for tqdm solutions_iter = tqdm(points_list, unit='solve') if self.solve: for i, points in enumerate(solutions_iter): solutions_iter.set_description('Solved %i/%i' % (i + 1, len(points_list))) points_scaled = points * 10000 solver = TSPSolver.from_data(points_scaled[:, 0], points_scaled[:, 1], 'EUC_2D') sol = solver.solve(time_bound=-1, verbose=False) opt_tour, opt_dist = sol.tour, sol.optimal_value / 10000 solutions.append(opt_tour) opt_dists.append(opt_dist) else: solutions = None opt_dists = None if self.solve: print(' [*] Avg Optimal Tour {:.5f} +- {:.5f}'.format( np.mean(opt_dists), 2 * np.std(opt_dists) / np.sqrt(len(opt_dists)))) data = { 'Points': points_list, 'OptTour': solutions, 'OptDistance': opt_dists } df = pd.DataFrame(data) df.to_json(path_or_buf='data/att-TSP' + str(self.n_points) + '-data-test' + '.json')
def solve(inst): # precision factor pr = 1e-3 # # shut output, not working # stdout = sys.stdout # sys.stdout = open(os.devnull, 'w') # solve slr = TSPSolver.from_data(inst[:, 0] / pr, inst[:, 1] / pr, 'EUC_2D') res = slr.solve(verbose=False) # # redirect output # sys.stdout = stdout return res.tour, res.optimal_value
def concorde(self, time): """ Solve the problem with concorde solver. Without penalization of prime cities. """ x = [c.x for c in self.stops[:-1]] y = [c.y for c in self.stops[:-1]] # Instantiate solver solver = TSPSolver.from_data(x, y, norm="EUC_2D") # solve tour_data = solver.solve(time_bound=float(time), verbose=True, random_seed=42) # Reorder the route with concorde solution order = np.append(tour_data.tour,[0]) new_route = [self.stops[i] for i in order] self.stops = new_route
def test_module(): gs = GeneticSolver(gene_type=OptimizableTour, N=200, mutation_rate=0.2) places = gs.population[0].places xs = [p.x for p in places] ys = [p.x for p in places] print(xs) print(ys) solver = TSPSolver.from_data(xs=xs, ys=ys, norm="EUC_2D") solution = solver.solve() print(solution.optimal_value) print(solution.tour) for i in range(1000): gs.evolve() ff = [f.fitness() for f in gs.population] print(ff)
def generate_data(self): points_list = [] solutions = [] opt_dists = [] data_iter = tqdm(range(self.data_size), unit='data') for i, _ in enumerate(data_iter): data_iter.set_description('Generating data points %i/%i' % (i + 1, self.data_size)) points = np.random.random((self.n_points, 2)) points_list.append(points) # solutions_iter: for tqdm solutions_iter = tqdm(points_list, unit='solve') if self.solve: for i, points in enumerate(solutions_iter): solutions_iter.set_description('Solved %i/%i' % (i + 1, len(points_list))) points_scaled = points * 10000 solver = TSPSolver.from_data(points_scaled[:, 0], points_scaled[:, 1], 'EUC_2D') sol = solver.solve(time_bound=-1, verbose=True) opt_tour, opt_dist = sol.tour, sol.optimal_value / 10000 solutions.append(opt_tour) opt_dists.append(opt_dist) else: solutions = None opt_dists = None data = { 'Points': points_list, 'OptTour': solutions, 'OptDistance': opt_dists } df = pd.DataFrame(data) df.to_json(path_or_buf='data/data_test' + str(self.n_points) + '.json')
def generate_data(num_samples: int, graph_size: int, dataset_name: str): points_list = [] solutions = [] opt_dists = [] data_iter = tqdm(range(num_samples), unit="data") for i, _ in enumerate(data_iter): data_iter.set_description("Generating data points %i/%i" % (i + 1, num_samples)) points = torch.empty(size=(graph_size, 2)).uniform_(0, 1) points_list.append(points) # solutions_iter: for tqdm solutions_iter = tqdm(points_list, unit="solve") for i, points in enumerate(solutions_iter): solutions_iter.set_description("Solved %i/%i" % (i + 1, len(points_list))) points_scaled = points.numpy() * FLOAT_SCALE solver = TSPSolver.from_data(points_scaled[:, 0], points_scaled[:, 1], "EUC_2D") sol = solver.solve(time_bound=-1, verbose=False) opt_tour, opt_dist = sol.tour, sol.optimal_value / FLOAT_SCALE solutions.append(opt_tour) opt_dists.append(opt_dist) data = { "Points": points_list, "OptTour": solutions, "OptDistance": opt_dists } file_name = f"tsp_{graph_size}_{dataset_name}_{num_samples}.pt" path = os.path.join(os.getcwd(), file_name) torch.save(data, path)
ax.autoscale() plt.show() told=tol(df) print(i,' : ',df.CityId[0],'->',df.CityId[len(df)-1],'dist : ',told) #--------------- solver the tsp for centers --------------------- north_pole = df[df['CityId']==0] n_index=north_pole.mclust to_begin(centers,int(n_index)) centers = pd.concat([centers,pd.DataFrame(columns=['start_point','end_point'])],sort=False) solver = TSPSolver.from_data( centers.X, centers.Y, norm="EUC_2D" ) tour_data = solver.solve(time_bound = 60.0, verbose = True, random_seed = 42) centers_c=centers.copy() for i in range(len(centers)): print (tour_data[0][i]) centers.iloc[i]=centers_c.iloc[tour_data[0][i]] ''' for j in range(len(df)): df.iloc[j]=df_r.iloc[tour_c[0][j]]
for i in range(len(df)): obj.append(distance(df.iloc[i][['X', 'Y']], mean)) dest = df.iloc[obj.index(min(obj))]['CityId'] print('min=', dest) return dest north_pole = df[df['CityId'] == 0] n_p = north_pole[['mclust', 'X', 'Y']] route = n_p.append(centers, ignore_index=True) route = route.append(n_p, ignore_index=True) route = pd.concat( [route, pd.DataFrame(columns=['tour_data', 'start_point', 'end_point'])], sort=False) solver = TSPSolver.from_data(route.X, route.Y, norm="EUC_2D") tour_data = solver.solve( time_bound=60.0, verbose=True, random_seed=42 ) # solve() doesn't seem to respect time_bound for certain values? route['tour_data'] = tour_data[0] route.sort_values(by=['tour_data'], inplace=True) route = route.reset_index(drop=True) b = route.iloc[n_cluster].mclust coord = nearest_point(df[df['mclust'] == b], north_pole[['X', 'Y']]) route.loc[n_cluster, 'end_point'] = coord for i in range(1, len(route) - 1): a = int(route.iloc[i].mclust) b = int(route.iloc[i - 1].mclust)
anneal.calc_max_distance() config_at_init_time = list(-np.ones(anneal.NCITY, dtype=np.int)) config_at_init_time[0] = 1 print "start..." t0 = time.clock() # solve by concorde list_x = list() list_y = list() for i in range(len(anneal.POINT)): list_x.append(anneal.POINT[i][0]) list_y.append(anneal.POINT[i][1]) solver = TSPSolver.from_data(list_x, list_y, norm="EUC_2D") optimal_tour = solver.solve() # extract positions of optimal tour optimal_length = optimal_tour.optimal_value optimal_pos_x = list() optimal_pos_y = list() for i in range(len(anneal.POINT)): optimal_pos_x.append(anneal.POINT[optimal_tour.tour[i]][0]) optimal_pos_y.append(anneal.POINT[optimal_tour.tour[i]][1]) # prepare for figure fig, ax = plt.subplots(1, 1) lines, = ax.plot(list(), list(), lw=2.0) np.random.seed(100)
from concorde.tsp import TSPSolver from time import time pointsList = [] for line in open("density_points.txt", "r").readlines(): currentPoints = [] for element in line[1:-3].split("), "): currentPoints.append( (int(element[1:].split(",")[0]), int(element[1:].split(",")[1]))) pointsList.append(currentPoints) solutions = [] times = [] for element in pointsList: print("\n\nMOVING ON TO ", len(solutions)) print("\n\n") solver = TSPSolver.from_data(*zip(*element), "EUC_2D") start = time() solution = solver.solve() while not solution.found_tour: pass #wait until we find tour totalTime = time() - start solutions.append(solution.tour) times.append(totalTime) output = open("density_output_solutions.txt", "w") timeOut = open("density_output_time.txt", "w") for sol, time in zip(solutions, times): outputStream = "[" for element in sol: outputStream += str(element) + ", " output.write(outputStream[:-2] + "]\n")
# Pretty print the run args pp.pprint(vars(opts)) with open(opts.filename, "w") as f: start_time = time.time() for b_idx in range(opts.num_samples // opts.batch_size): num_nodes = np.random.randint(low=opts.min_nodes, high=opts.max_nodes + 1) assert opts.min_nodes <= num_nodes <= opts.max_nodes idx = 0 while idx < opts.batch_size: nodes_coord = np.random.random([num_nodes, 2]) solver = TSPSolver.from_data(nodes_coord[:, 0], nodes_coord[:, 1], norm="GEO") solution = solver.solve() # Only write instances with valid solutions if (np.sort(solution.tour) == np.arange(num_nodes)).all(): f.write(" ".join( str(x) + str(" ") + str(y) for x, y in nodes_coord)) f.write(str(" ") + str('output') + str(" ")) f.write( str(" ").join( str(node_idx + 1) for node_idx in solution.tour)) f.write(str(" ") + str(solution.tour[0] + 1) + str(" ")) f.write("\n") idx += 1 assert idx == opts.batch_size
import numpy as np from dataGenerator import DataGenerator from configuration import get_config from concorde.tsp import TSPSolver config = get_config() dataset = DataGenerator() real_tour_concorde = {} real_len_concorde = [] for i in tqdm(range(1000)): # test instance seed_ = 1 + i input_batch, dist_batch = dataset.create_batch(1, config.graph_dimension, config.dimension, seed=seed_) # Concorde solver = TSPSolver.from_data(input_batch[0, :, 0] * 1000, input_batch[0, :, 1] * 1000, norm="EUC_2D") # Find tour solution = solver.solve() real_len_concorde.append(solution.optimal_value / 1000) print("Creation COMPLETED !") np.savetxt("risultati/concorde_len_TSP" + str(config.graph_dimension) + ".txt", real_len_concorde)
def tspn(points): # OLD METHOD # tsp = TSP() # tsp.read_data(points) # sol = NN_solver() # tsp.get_approx_solution(sol) # tsp.plot_solution('NN_solver') # sol = TwoOpt_solver(list(a.tours.values())[0],500) # tsp.get_approx_solution(sol) # tsp.plot_solution('TwoOpt_solver') # best_tour = tsp.get_best_solution() points = points[0:, 0:2] points_pd = pd.DataFrame({'x': points[:, 0], 'y': points[:, 1]}) # Instantiate solver solver = TSPSolver.from_data(points[0:, 0], points[0:, 1], norm="EUC_2D") # Find tour tour_data = solver.solve() assert tour_data.success solution = points_pd.iloc[tour_data.tour] print("Optimal tour:") print(u' -> '.join('{r.x}, {r.y}'.format(r=row) for _, row in solution.iterrows())) ## PLOTTING # ax = plt.axes([0, 0, 1, 1], projection=ccrs.LambertConformal()) # ax.set_extent([-125, -66.5, 20, 50], ccrs.Geodetic()) # # shapename = 'tour' # # states_shp = shpreader.natural_earth(resolution='110m', # # category='cultural', name=shapename) # # ax.background_patch.set_visible(False) # # ax.outline_patch.set_visible(False) # # tour = sgeom.LineString(list(zip(solution.x, solution.y))) # # capitals = sgeom.MultiPoint(list(zip(solution.x, solution.y))) # # for state in shpreader.Reader(states_shp).geometries(): # # facecolor = [0.9375, 0.9375, 0.859375] # # edgecolor = 'black' # # ax.add_geometries([state], ccrs.PlateCarree(), # # facecolor=facecolor, edgecolor=edgecolor) # # ax.add_geometries([tour], ccrs.PlateCarree(), # # facecolor='none', edgecolor='red') # for x, y in zip(solution.x, solution.y): # ax.plot(y, x, 'ro') # plt.savefig("optimal_tour.png", bbox_inches='tight') # plt.show() tspn_plot(solution)
def solve(self, solver_type=None, auto_add_mc_stats=False, raise_error_invalid=True): self.update_solver(solver_type) nstops = len(self.stops) assert nstops, "no stops to attempt to connect" assert (isinstance(self.dist_mat_all, np.ndarray) and isinstance(self.dist_mat_edge_limited, np.ndarray) and (self.dist_mat_all.shape[0] >= nstops) and (self.dist_mat_edge_limited.shape[0] >= nstops)), ( "invalid distance matrix") noncompute_return = (None, None, None) qa_solution = None if ((self.solver_type in self.solutions) and self.solutions[self.solver_type]['is_valid_for_stops']): valid = expnd_valid = True else: valid = expnd_valid = False route = [] points = np.asarray(self.stops) if self.debug: print(f'finding approximate best routes for {len(points)} ' f'stops via {self.solver_type}') if self.debug > 1: print(points) runtime = points_skipped = 0 if self.solver_type != 'quick_adjust': startt = time() if self.solver_type == 'concorde': imp_fail_str = None try: from concorde.tsp import TSPSolver except ImportError as ie: imp_fail_str = import_failed( 'concorde', 'https://github.com/nickrose/pyconcorde') if self.fail_on_solver_import: raise ImportError(imp_fail_str) else: warnings.warn(imp_fail_str) self.solver_type = default_solver startt = time() else: if self.debug > 2: print('alt solver module: import successful') x, y = (np.asarray( self.stop_locations[self.stops, 0].reshape( len(self.stops)).tolist()[0]), np.asarray( self.stop_locations[self.stops, 1].reshape( len(self.stops)).tolist()[0])) solver = TSPSolver.from_data(x, y, 'EUC_2D') solution = solver.solve() valid = solution.found_tour if self.debug > 2: print( f'[{self.solver_type}]: valid: ' f'{solution.found_tour}, optimal_value: ' f'{solution.optimal_value:.4f}, tour indexed ' f'stops: {solution.tour}') if valid: route = np.asarray(self.stops)[solution.tour] if self.debug > 2: print(f' tour: {route}') route = route.tolist() route.append(points[0]) route = np.asarray(route) if self.solver_type == 'random': route = random_traveling_salesman(points, self.dist_mat_all, avg_edges=None, start=0, end=0, debug=max( 0, self.debug - 2)) elif self.solver_type == 'greedy_NN': route = nn_greedy_traveling_salesman(points, self.dist_mat_all, start=0, end=0, debug=max( 0, self.debug - 2)) elif self.solver_type == 'greedy_NN_recourse': route = nn_greedy_recourse_traveling_salesman( points, self.dist_mat_all, start=0, end=0, debug=max(0, self.debug - 2), revisit_ndecisions=self.recourse_revisits) runtime += (time() - startt) if self.debug > 1: print(f'routes [{self.solver_type:7s}]', route) if not (valid) and len(route): valid = check_valid_path(points, route, self.dist_mat_all, solver=self.solver_type, raiseError=raise_error_invalid) try: startt = time() route_expand, subroutes = connect_route_points_via_dijkstra( route, self.dist_mat_edge_limited, debug=self.debug) runtime += (time() - startt) except RuntimeError as rte: if self.debug: print(str(rte)) print('skipping this solve') points_skipped = ( len(self.solutions[self.solver_type]['added_points']) if ((self.solver_type in self.solutions) and ('added_points' in self.solutions[self.solver_type])) else len(points)) else: if len(self.solutions) == 0: if self.is_monte_carlo_test: return else: if self.debug > 1: print('no previous solutions to update, try ' 'another solver') return noncompute_return if 'concorde' in self.solutions: qa_solution = 'concorde' elif 'greedy_NN' in self.solutions: qa_solution = 'greedy_NN' elif 'greedy_NN_recourse' in self.solutions: qa_solution = 'greedy_NN_recourse' else: # we just need a previous saved solution qa_solution = list(self.solutions.keys())[0] # find the two nearest points and recalculate the Dijkstra # sub-paths startt = time() route, subroutes, route_expand, points_skipped, valid = \ quick_adjust_route( self.solutions[qa_solution]['route'], self.solutions[qa_solution]['subroutes'], self.solutions[qa_solution]['added_points'], self.dist_mat_all, self.dist_mat_edge_limited, debug=self.debug) runtime += (time() - startt) if self.debug > 2: print(f'check expanded path for "{self.solver_type}" solver') print(f'points skipped in expansion of path: {points_skipped}') if not (points_skipped) and route_expand is not None: expnd_valid, revisit_frac = check_valid_path( points, route_expand, self.dist_mat_edge_limited, solver=self.solver_type, allow_between_stops=True, raiseError=raise_error_invalid) else: revisit_frac = None if (valid and expnd_valid) or not (raise_error_invalid): if (qa_solution is not None and 'added_points' in self.solutions[qa_solution]): ref_added_points = self.solutions[qa_solution][ 'added_points'] else: ref_added_points = None is_update = ( ((self.solver_type in self.solutions) and ('added_points' in self.solutions[self.solver_type]) or (qa_solution is not None and 'added_points' in self.solutions[qa_solution]))) self.solutions[self.solver_type] = dict( is_valid_for_stops=(valid and expnd_valid), dist_basic=(total_distance(route, self.dist_mat_all) if valid else None), dist_expand=(total_distance(route_expand, self.dist_mat_edge_limited) if expnd_valid else None), route=(route if valid else (self.solutions[self.solver_type]['route'] if (is_update and qa_solution is None) else None)), route_expand=(route_expand if expnd_valid else ( self.solutions[self.solver_type]['route_expand'] if (is_update and qa_solution is None) else None)), subroutes=(subroutes if expnd_valid else ( self.solutions[self.solver_type]['subroutes'] if (is_update and qa_solution is None) else None)), runtime=runtime, points_skipped=points_skipped, is_update=is_update, revisit_frac=revisit_frac, recourse_revisits=self.recourse_revisits) if self.is_monte_carlo_test and auto_add_mc_stats: self.mc_stats = self.all_route_stats( solver_type=self.solver_type, stats=self.mc_stats) if ref_added_points: self.solutions[ self.solver_type]['qa_previous_solve'] = qa_solution self.solutions[self.solver_type].update( dict(ref_added_points=ref_added_points)) if not (self.is_monte_carlo_test): if self.debug: dist_basic = self.solutions[self.solver_type]['dist_basic'] dist_expand = self.solutions[self.solver_type]['dist_expand'] print( f"{self.solver_type} algorithm " f"{('' if qa_solution is None else '(using prev solution: ' + qa_solution + ')')}" ) print( f" runtime : {self.solutions[self.solver_type]['runtime']:.3f}s" ) print( f" route dist : [coarse: {dist_basic:.3f}, fine: {dist_expand:.3f}]" ) print(f" validity : [{valid}] expanded[{expnd_valid}]") print( f" revisit_frac: [{self.solutions[self.solver_type]['revisit_frac']:.3f}]" ) if valid and expnd_valid: return (self.solutions[self.solver_type]['route'], self.solutions[self.solver_type]['route_expand'], self.solutions[self.solver_type]['revisit_frac']) else: return noncompute_return
opts = parser.parse_args() if opts.filename is None: opts.filename = f"tsp{opts.num_nodes}_concorde_new.txt" # Pretty print the run args pp.pprint(vars(opts)) set_nodes_coord = np.random.random( [opts.num_samples, opts.num_nodes, opts.node_dim]) scaled_set_nodes_coord = 1000 * set_nodes_coord with open(opts.filename, "w") as f: start_time = time.time() for i, nodes_coord in enumerate(scaled_set_nodes_coord): solver = TSPSolver.from_data(nodes_coord[:, 0], nodes_coord[:, 1], norm="EUC_2D") solution = solver.solve() f.write(" ".join( str(x) + str(" ") + str(y) for x, y in set_nodes_coord[i])) f.write(str(" ") + str('output') + str(" ")) f.write( str(" ").join(str(node_idx + 1) for node_idx in solution.tour)) f.write(str(" ") + str(solution.tour[0] + 1) + str(" ")) f.write("\n") end_time = time.time() - start_time print( f"Completed generation of {opts.num_samples} samples of TSP{opts.num_nodes}." ) print(f"Total time: {end_time/3600:.1f}h")
from concorde.tsp import TSPSolver from matplotlib import collections as mc import numpy as np import pandas as pd import time import pylab as pl import os import pickle import gzip from operator import itemgetter import math cities = pd.read_csv('input/cities.csv') # Instantiate solver solver = TSPSolver.from_data([int(x * 1000) for x in cities.X], [int(y * 1000) for y in cities.Y], norm="EUC_2D") print("starting ...") t = time.time() tour_data = solver.solve( verbose=False ) # solve() doesn't seem to respect time_bound for certain values? print(time.time() - t) print(tour_data.found_tour) pd.DataFrame({ 'Path': np.append(tour_data.tour, [0]) }).to_csv('submission_concord_full.csv', index=False) print("end ...")\
from concorde.tsp import TSPSolver from matplotlib import collections as mc import numpy as np import pandas as pd import time import pylab as pl cities = pd.read_csv('../input/cities.csv') # Instantiate solver solver = TSPSolver.from_data(cities.X, cities.Y, norm="EUC_2D") t = time.time() tour_data = solver.solve( time_bound=60.0, verbose=True, random_seed=42 ) # solve() doesn't seem to respect time_bound for certain values? print(time.time() - t) print(tour_data.found_tour) pd.DataFrame({ 'Path': np.append(tour_data.tour, [0]) }).to_csv('submission.csv', index=False) # Plot tour lines = [[(cities.X[tour_data.tour[i]], cities.Y[tour_data.tour[i]]), (cities.X[tour_data.tour[i + 1]], cities.Y[tour_data.tour[i + 1]])] for i in range(0, len(cities) - 1)] lc = mc.LineCollection(lines, linewidths=2) fig, ax = pl.subplots(figsize=(20, 20)) ax.set_aspect('equal') ax.add_collection(lc) ax.autoscale()
def nearest_point(df,mean): obj= [] for i in range(len(df)) : obj.append(distance(df.iloc[i][['X','Y']],mean)) dest=df.iloc[obj.index(min(obj))]['CityId'] print('min=',dest) return dest north_pole = df[df['CityId']==0] n_p=north_pole[['mclust','X','Y']] route=n_p.append(centers,ignore_index=True) route=route.append(n_p,ignore_index=True) centers = pd.concat([centers,pd.DataFrame(columns=['start_point','end_point'])],sort=False) solver = TSPSolver.from_data( route.X, route.Y, norm="EUC_2D" ) #--------------- solver the tsp for centers --------------------- tour_data = solver.solve(time_bound = 60.0, verbose = True, random_seed = 42) centers_c=centers.copy() for i in range(len(centers)): print (tour_data[0][i+1]-1) centers.iloc[i]=centers_c.iloc[tour_data[0][i+1]-1] for i in range(1,n_cluster): a=int(centers.iloc[i].mclust) b=int(centers.iloc[i-1].mclust) print ('a',a,'b',b) coord=nearest_point(df[df['mclust']==a],centers.iloc[b][['X','Y']]) centers.loc[i,'start_point']=coord
def generate_instance(): for dim in [10, 20, 30]: ic = TSP_Instance_Creator('random', seed=123, dimension=dim) solver = TSPSolver.from_data(ic.points[:, 1], ic.points[:, 2], norm="EUC_2D") solution = solver.solve() save_new_tsplib(f"myTSP_dim{dim}.tsp", ic.points, solution)