def test_modify_path_first_node(self): tsp1 = tsp( [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [200, 14, 15, 16]], 12, 13) init_cost = 2 + 7 + 12 + 200 tsp1.path = [0, 1, 2, 3, 0] nodes = (0, 1) tsp1.cost = tsp1.calc_cost() tsp1.modify_path(nodes) new_cost = 5 + 3 + 12 + 14 self.assertEqual(tsp1.cost, new_cost) self.assertEqual(tsp1.path, [1, 0, 2, 3, 1]) tsp1 = tsp( [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [200, 14, 15, 16]], 12, 13) init_cost = 2 + 7 + 12 + 200 tsp1.path = [0, 1, 2, 3, 0] nodes = (1, 0) tsp1.cost = tsp1.calc_cost() tsp1.modify_path(nodes) new_cost = 5 + 3 + 12 + 14 self.assertEqual(tsp1.cost, new_cost) self.assertEqual(tsp1.path, [1, 0, 2, 3, 1])
def opt_road(points): points = points.numpy() if points.ndim == 2: solution = tsp.tsp(points) roads = np.array(solution[1]) return roads batch = points.shape[0] roads = [] for i in range(batch): solution = tsp.tsp(points[i]) roads.append(solution[1]) return np.array(roads)
def _run(self): # 读出选择的城市与起始城市 selected = [item.get() for item in self.v] if selected[-1]: selected = [1] * (len(selected) - 1) else: del selected[-1] try: start_city = int(self.textStr.get()) except ValueError: start_city = -1 if sum(selected) <= 2: self.show_dis['text'] = 'Error: 城市数过少' return input_cities = [] for i in range(len(self.cities)): if selected[i]: input_cities.append(self.cities[i]) if start_city == -1: start_city = i # 计算并绘制图像 self.clean_canvas(start_city) self.show_dis['text'] = '计算中' self.root.update() ans = tsp(input_cities) self.draw_ans(input_cities, ans.dna) self.show_dis['text'] = 'distance: {}'.format(ans.distance)
def optimize(self): r = range(self.size) dist = {(i, j): self.graph[i][j] for i in r for j in r} t = tsp.tsp(r, dist) dist = t[0] # shortest distance path = t[1] # path return dist, path
def solve_it(input_data): # Modify this code to run your optimization algorithm # parse the input lines = input_data.split('\n') nodeCount = int(lines[0]) points = [] for i in range(1, nodeCount+1): line = lines[i] parts = line.split() points.append(Point(float(parts[0]), float(parts[1]))) # build a trivial solution # visit the nodes in the order they appear in the file import tsp solution = tsp.tsp(points) # solution = range(0, nodeCount) # calculate the length of the tour obj = length(points[solution[-1]], points[solution[0]]) for index in range(0, nodeCount-1): obj += length(points[solution[index]], points[solution[index+1]]) # prepare the solution in the specified output format output_data = str(obj) + ' ' + str(0) + '\n' output_data += ' '.join(map(str, solution)) return output_data
def TSPWithStartAndEnd(distances, sites, start, end): sites.append("dummy") for stop in sites: distances[("dummy", stop)] = BIGVALUE distances[(stop, "dummy")] = BIGVALUE distances[("dummy", "dummy")] = 0 distances[("dummy", start)] = 0 distances[(end, "dummy")] = 0 newDistances = {} for i in range(len(sites)): for j in range(len(sites)): newDistances[(i, j)] = distances[(sites[i], sites[j])] tspResults = tsp.tsp(list(range(len(sites))), newDistances) route = tspResults[1] cost = tspResults[0] route = [sites[x] for x in route] routeNoDummy = route[route.index("dummy") + 1:] + route[:route.index("dummy"):] return routeNoDummy, cost
def test(points, baseline_path, short_path): """Test the tsp function on points. baseline_path is the length of a simple solution. short_path is the length of a good solution. Your solution should run for at most 30 seconds and should return a path of length less than than baseline_path (the only exception is when baseline_path is almost equal to short_path; in this case, it is OK to return a path of similar length). The score you get depends on how short your path is. The score is the returned value of the function. """ print("Baseline path: ", baseline_path) print("Short path: ", short_path) n = points[0] path = tsp(points) assert len(path) == n + 1, "The route must contain n + 1 points." assert path[0] == 1 == path[-1], "The route should start and end at point 1." assert set(path) == set(range(1, n + 1)), "The route must contain all n points." length = get_length(path, points) print("Your path: ", length) if length <= short_path + 0.00001: # If your path is just slightly longer than short_path or shorter, you get 10. return 10.0 if length >= baseline_path: # If it is the same as the baseline or longer, you get 1. return 1 # Otherwise, the number of points you get depends on how close your path is to short_path. return math.ceil((baseline_path-length) / (baseline_path-short_path) * 10)
def travel(city1, city2): print('Provide input 0 anytime to reset\n') print('Mode of Transport\n1. Train\n2. Flight\n3. Bus\n') userInput = int(input()) transport(userInput) time.sleep(2) print('Looking for Hotel Price\n') hotelSelect(city2) print('Averaging City Travel Cost') time.sleep(2) print('Cheking CAB Rates') time.sleep(3) print('Cab rate is INR 50 for first 2 KM rest INR 30/KM') time.sleep(2) print('These are the Famous Destinations in Mumbai : \n') print(mumbaiDest) print('Applying TSP Algorithm\n') r = range(len(mumbai)) dist = {(i, j): mumbai[i][j] for i in r for j in r} sol = tsp.tsp(r, dist) ans = '' for i in sol[1]: ans += mumbaiDest[str(i)] + ' -> ' time.sleep(2) print('This could be your path : \n') print(ans[:-2]) time.sleep(3) print('Calculating your Total Cost now :\n') print('Total Cost in INR : ', 1800 + 2700 + 3500) print('Script Ended')
def gaussian(): maximum_baseline_m = 200.0e3 mean = [0.0, 0.0] rho = 0.0 # correlation between x and y sigma_x = 1.0 sigma_y = 1.0 cov = [[sigma_x ** 2, rho * sigma_x * sigma_y], [rho * sigma_y * sigma_x, sigma_y ** 2]] num_points = 50 samples = numpy.random.multivariate_normal(mean, cov, num_points) print(samples.shape) points = list() for s in samples: points.append(tuple(s)) t = tsp.tsp(points) t.solve(keep_files=True) # Plotting xy_extent = numpy.abs(samples).max() fig = pyplot.figure(figsize=(8, 8)) ax = fig.add_subplot(111) ax.plot(samples[:, 0], samples[:, 1], ".") circle = pyplot.Circle((0, 0), xy_extent, color="r", fill=False, alpha=1.0, linewidth=1.0, linestyle="--") ax.add_artist(circle) ax.grid(True) ax.set_xlim(-xy_extent * 1.1, xy_extent * 1.1) ax.set_ylim(-xy_extent * 1.1, xy_extent * 1.1) pyplot.show()
def testInitialization(self): with self.assertRaises(TypeError): tsp([[12]], 'test', 23.4) #tests temp with self.assertRaises(TypeError): tsp([[12]], 12, 'test') #tests beta with self.assertRaises(TypeError): tsp({'hi': 12, 'no': 12}, 23.523, 1) #tests distance matrix with self.assertRaises(IndexError): tsp([12.2, 31, 2, 3], 1, 24.3) #tests for list of
def test_choose_nodes(self): tspA = tsp([[12, 13, 14], [12, 121, 2], [1, 2, 3]], 12, 13) tspA.path = tspA.generate_random_path() node1, node2 = tspA.choose_nodes() truth = (node1 == 0 or node1 == 1 or node1 == 2) and (node2 == 0 or node2 == 1 or node2 == 2) and (node1 != node2) self.assertTrue(truth)
def construct_tsp(costs): print( "Solving traveling salesman problem. Did you know this is NP-hard? COME ON, GIVE ME A SEC!" ) r = range(len(costs)) dist = {(i, j): costs[i][j] for i in r for j in r} tsp_result = tsp.tsp(r, dist) return tsp_result[1]
def hello_world(mat): r = range(len(mat)) # Dictionary of distance dist = {(i, j): mat[i][j] for i in r for j in r} a = tsp.tsp(r, dist) b = json.dumps({"answer": [str(x) for x in a[1][1:-1]]}) print(b) return json.dumps({"answer": [str(x) for x in a[1][1:-1]]})
def test_assigment(self): test_cases_path = 'shortest_path_revisited_np_problems/week2/assigment/' test__files = get_test_inputs(test_cases_path) for test_input in test__files: print("Testing Assigment: " + test_input) test_case = read_graph(test_input, sep=" ") test_result = tsp(test_case) final_answer = get_assignment_answer(test_result) print("Assigment {} Answer: {}".format(test_input, final_answer)) print("Test OK")
def test_cousera_test_cases(self): test_cases_path = 'shortest_path_revisited_np_problems/week2/test_cases/' test__files = get_test_inputs(test_cases_path) for test_input in test__files: print("Testing " + test_input) test_case = read_graph(test_input, sep=" ") expected = read_output(test_input) test_result = tsp(test_case) final_answer = get_assignment_answer(test_result) self.assertEqual(expected, final_answer) print("Test OK")
def uhc(inString): graph = Graph(inString, weighted=False, directed=False) # If there are two vertices, our conversion won't work correctly, # so treat this as a special case. if len(graph) == 2: return 'no' # Convert to an equivalent weighted graph. graph.convertToWeighted() newGraphString = str(graph) cycle = tsp(newGraphString) return cycle
def get(self): loc = self.request.GET['loc'] r, wps = tsp(loc) logging.info("r {0}".format(r)) s = "/".join(r) s = "https://www.google.com/maps/dir/" + s self.response.write('<a href="{0}">{0}</a>'.format(s))
def TSP_clusters(cost_matrix): r = range(len(cost_matrix)) # Dictionary of distance dist = {(i, j): cost_matrix[i][j] for i in r for j in r} l = tsp.tsp(r, dist) first = l[1][0] last = l[1][-1] d = l[0] - cost_matrix[last][first] for i in range(len(l[1])): l[1][i] = l[1][i] + 1 ret = [l[1], d] #path, distance return ret
def generate_itinerary(self, pois, hotel_lat_lon=None): #assume hotel is dictionary of in the style of {'latitude': 50.085133, 'longitude': 14.424776} #if not provided, the hotel is assumed to be at the mean location of the pois. #pois are list of pois generated by amadeus #result is a dictionary, that has: # result['path'] is the path to be taken, indexed by pois # result['travel_time'] is the matrix of travel times from a poi (row) to another poi (col). Note, indexes are shifted up by 1 due to hotel being added as index 0. # result['dist_matrix'] is the distances matrix returned by google. if hotel_lat_lon is None: hotel_lat_lon = self.get_mean_location(pois) #convert pois to lat long poi_latlon = self.poi_latlon = [ pois[i]['geoCode'] for i in range(len(pois)) ] #saved for future reference #collate full_latlon = [hotel_lat_lon] + poi_latlon num_of_points = len(full_latlon) #generate distance matrix from google dist_matrix = self.gmaps.distance_matrix(full_latlon, full_latlon, mode='transit') #generate summary of travel times (each number is the number of seconds of travel) travel_time = [[ dist_matrix['rows'][o]['elements'][d]['duration']['value'] for d in range(num_of_points) ] for o in range(num_of_points)] #convert to dictionary r = range(len(travel_time)) cost = {(i, j): travel_time[i][j] for i in r for j in r} #solve travelling salesman problem (totaltime, path) = tsp.tsp(r, cost) #correct index, because hotel was added at point 0 poi_path = [loc - 1 for loc in path[1:]] result = dict() result['path'] = [int(x) for x in poi_path] result['dist_matrix'] = dist_matrix result['travel_time'] = travel_time logger.debug(f"itinerary {result}") result['travel_time'] = travel_time return result
def main(): VRP_cost = 0 VRP_Route = [] for k in range(nber_of_vehicles): n = len(Repartition[1][k]) res = str(Repartition[1][k])[1:-1] Intres = [int(u) for u in res if u.isdigit()] Intres.insert(0, depot) ResCity = [cityList[int(u)] for u in res if u.isdigit()] ResCity.insert(0, cityList[depot]) for k in range(3): bestRoute = geneticAlgorithmPlot(population=ResCity, popSize=100, eliteSize=20, mutationRate=0.01, generations=500) bestRouteList = [] sX = [] sY = [] IndexRoute = [] for j in range(len(bestRoute)): bestRouteList.append((bestRoute[j].x, bestRoute[j].y)) sX.append(bestRoute[j].x) sY.append(bestRoute[j].y) IndexRoute.append(key_list[val_list.index(bestRouteList[j])]) sX.append(bestRoute[0].x) sY.append(bestRoute[0].y) #plotPath(sX, sY) #print(IndexRoute) crowd.append(IndexRoute) #print(agg_matrix(crowd)) agg = agg_matrix(crowd) Inv_Agg = np.zeros((n, n)) for k in range(n): for j in range(n): Inv_Agg[k, j] = 1 - sc.betaincinv(2.8, 3.2, agg[k, j] / n) r = range(n) dist = {(i, j): Inv_Agg[i, j] for i in r for j in r} aggRoute = tsp.tsp(r, dist)[1] sortedaggRoute = [Intres[i] for i in aggRoute] #import pdb; pdb.set_trace() cost = 0 for u in range(n - 1): cost += City.distance(ResCity[u], ResCity[u + 1]) cost += City.distance(ResCity[n - 1], ResCity[0]) #import pdb; pdb.set_trace() VRP_cost += cost VRP_Route.append(sortedaggRoute) print(VRP_Route, VRP_cost) '''
def test_random(self): print( "\n \n \n BEGINNING FINAL TEST ------------------------ \n \n \n") tsp1 = tsp([[200, 2, 300, 400], [500, 600, 2, 800], [900, 100, 110, 12], [13, 142, 153, 116]], 900, -1.1, debug=True) path = tsp1.find_path_random(num_its=10000) cost = tsp1.calc_cost(path) print("Final Path: " + str(path)) print("Final Cost: " + str(cost)) self.assertEqual(cost, 2 + 2 + 12 + 13)
def path(st_ll): df = pd.read_csv('db/datall.csv') df = df[1:] name = list(df['name']) lat = list(df['latitude']) lon = list(df['longitude']) name.insert(0, 'truck_starting_point') lat.insert(0, st_ll[0]) lon.insert(0, st_ll[1]) print(name, lat, lon) a = [] a1 = [] for i in range(len(name)): b = [] for j in range(len(name)): b.append(name[i] + name[j]) if (name[j] == name[-1]): a.append(b) break print(a) for i in range(len(lat)): b1 = [] for j in range(len(lat)): k = km(lat1=lat[i], lon1=lon[i], lat2=lat[j], lon2=lon[j]) b1.append(k) if (j == len(lat) - 1): a1.append(b1) break print(a1) r = range(len(a1)) dist = {(i, j): a1[i][j] for i in r for j in r} print(tsp.tsp(r, dist)) path = tsp.tsp(r, dist) path_length = path[0] + a1[len(name) - 1][0] path_f = [path_length, path[1]] graph1(lat=lat, lon=lon, name=name) graph2(lat=lat, lon=lon, name=name, path=path) return path_f
def display_tsp(img_name): img_origin = cv2.imread(img_name, 2) ''' list_tsp=[] for i in range(K): list_tsp.append([]) for i in range(len(X)): list_tsp[X_label[i]].append(X[i]) for i in range(K): print(i,"번째: ",list_tsp[i],len(list_tsp[i])) ''' f1 = open("saved_data_k.txt", 'r') f2 = open("saved_data_sep.txt", 'r') K = int(f1.readline()) X_label = f2.read() f1.close() f2.close() list_tsp = ast.literal_eval(X_label) tsped_point = [] print(list_tsp) route_file = open('route.txt', 'w') for i in range(K): temp = [] img = cv2.imread(img_name) color = list(np.random.random(size=3) * 255) tsp_path_adj = init_adj(list_tsp[i], img_name) '''for j in range(len(tsp_path_adj)): print(j,":",tsp_path_adj[j])''' r = range(len(tsp_path_adj)) # Dictionary of distance dist = {(m, j): tsp_path_adj[m][j] for m in r for j in r} path_len, path = tsp.tsp(r, dist) print(path) for j in range(len(path)): print(j, "번째:", path[j], list_tsp[i][j]) temp.append(list_tsp[i][j]) print(temp) tsped_point.append(temp) for j in range(len(path) - 1): print(path[j], path[j + 1]) route = (astar(img_origin, tuple(list_tsp[i][path[j]]), tuple(list_tsp[i][path[j + 1]]))) print("route:", route) for l, k in route: img[k][l] = color cv2.imwrite('route%d.png' % (i), img) print('출력: ' + str(tsped_point)) route_file.write(str(tsped_point)) route_file.close()
def test_modify_path_interior_nodes(self): tsp1 = tsp( [[1, 2, 3, 4], [5, 6, 300, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 12, 13) init_cost = 2 + 300 + 12 + 13 tsp1.path = [0, 1, 2, 3, 0] nodes = (1, 2) tsp1.cost = tsp1.calc_cost() self.assertEqual(init_cost, tsp1.cost) tsp1.modify_path(nodes) new_cost = 3 + 10 + 8 + 13 self.assertEqual(tsp1.cost, new_cost) self.assertEqual(tsp1.path, [0, 2, 1, 3, 0])
def get(self): if 'loc' not in self.request.GET: loc = '58.394146, 15.555303' else: loc = self.request.GET['loc'] r, wps = tsp(loc) logging.info("r {0}".format(r)) s = "/".join(r) s = "https://www.google.com/maps/dir/" + s template = env.get_template('map.html') self.response.write(template.render(route_url=s))
def defined_route(location_list): args = list(location_list) args.pop() location_list = "".join(args) args = str(location_list).split("$") gmaps = googlemaps.Client(key="AIzaSyDPhqx7w-aEmxQZyk3s2gKY9WaMZYqi1CQ") dict_latitude = {} dict_longitude = {} distance_dict = {} tsp_as_json = {} distance_bw2_matrix = [] way_of_travel = [] def get_distance(location_source, location_destination): distance_matrix = gmaps.distance_matrix(location_source, location_destination) print distance_matrix if distance_matrix['rows'][0]['elements'][0][ 'status'] == 'ZERO_RESULTS': return "No results for " + distance_matrix['origin_addresses'][ 0] + " and " + distance_matrix['destination_addresses'][0] else: if "," in distance_matrix['rows'][0]['elements'][0]['distance'][ 'text'].split(" ")[0]: temp = distance_matrix['rows'][0]['elements'][0]['distance'][ 'text'].split(" ")[0].split(",") return float(temp[0] + temp[1]) else: return float(distance_matrix['rows'][0]['elements'][0] ['distance']['text'].split(" ")[0]) for i in range(len(args)): for j in range(len(args)): if i == j: distance_bw2_matrix.append(0) else: distance_bw2_matrix.append(get_distance(args[i], args[j])) distance_bw2_matrix = reshape(distance_bw2_matrix, (len(args), len(args))) r = range(len(distance_bw2_matrix)) dist = {(i, j): distance_bw2_matrix[i][j] for i in r for j in r} tsp_list = list((tsp.tsp(r, dist))) for x in tsp_list[1]: way_of_travel.append(args[x]) tsp_as_json['distance'] = str(tsp_list[0]) for x in range(1, len(way_of_travel) + 1): tsp_as_json[x] = str(way_of_travel[x - 1]) return json.dumps(tsp_as_json)
def tsp(self): # Edge case: check for no stitches if len(self.multi_node_graph) == 0: return 0 # Dictionary of distance r = range(len(self.multi_node_graph)) dist = {(i, j): self.multi_node_graph[i][j] for i in r for j in r} route_length, tour = tsp.tsp(r, dist) # Calculate excess distance -- every duplicate node needs distance excess = 0 for v in self.pattern: excess += 2 * len(self.pattern[v]) # Return length without excess return route_length - excess
def run(self, matriz): r = range(len(matriz)) # Dicionário de distâncias dist = {} for i in r: dist[(i, i)] = 0 for j, valor in enumerate(matriz[i]): dist[(i, j + i + 1)] = valor dist[(j + i + 1, i)] = valor s = range(len(matriz) + 1) startTime = time.time() result = tsp.tsp(s, dist) execTime = time.time() - startTime tsp_lista = result[1] tsp_resultante = [x + 1 for x in tsp_lista] return execTime, int(result[0]), tsp_resultante
def solve_it(input_data, method="", oporation="", solo=False, default=True): # Modify this code to run your optimization algorithm # parse the input lines = input_data.split('\n') nodeCount = int(lines[0]) points = [] for i in range(1, nodeCount + 1): line = lines[i] parts = line.split() points.append(Point(float(parts[0]), float(parts[1]))) if len(points) > 30000 and default: print("greedy") return greedy(points) NPproblem_tsp = tsp.tsp(points) if default: if len(points) > 200: approx = NPproblem_tsp.christofides() return print_solution(NPproblem_tsp, approx, "simulatedAnneling") else: approx = NPproblem_tsp.gurobi_method() return approx if method == 'approximation2': approx = NPproblem_tsp.approximation2() elif method == 'christofides': approx = NPproblem_tsp.christofides() elif method == 'antSystem': Hormigas = AntSystem.AntSystem(points, 1, 2, 0.02, 10, nodeCount, nodeCount) algo = Hormigas.calcule_route() return verbose(algo[1], algo[0]) elif method == 'gurobi': approx = NPproblem_tsp.gurobi_method() return approx else: approx = NPproblem_tsp.christofides() if solo: return verbose(approx[1], approx[0]) else: return print_solution(NPproblem_tsp, approx, oporation)
def simulate_routes(field_size,num_groups,num_stops): ''' Return a dict routes, containing a list of coordinates for a survey tour for each group. ''' found_valid_route = False while not found_valid_route: # first choose random points across the fields all_stops = numpy.random.rand(num_stops,2) all_stops[:,0] = all_stops[:,0]*field_size[0] all_stops[:,1] = all_stops[:,1]*field_size[1] centroids = numpy.random.rand(num_groups,2) centroids[:,0] = centroids[:,0]*field_size[0] centroids[:,1] = centroids[:,1]*field_size[1] # split the points up into three groups, according to nearest among three points. # (split the field up according to a voronoi diagram) stops_in_group = {} origin = numpy.array([field_size[0]/2, field_size[1]/2]) for g in range(num_groups): stops_in_group[g] = [origin] for s in range(num_stops): dists = numpy.zeros(num_groups) for g in range(num_groups): delta = all_stops[s,:] - centroids[g,:] dists[g] = numpy.dot(delta,delta) stops_in_group[dists.argmin()].append(all_stops[s,:]) # order the points in each group by solving a small TSP routes = {} for g in range(num_groups): route_indices = numpy.array(tsp.tsp(stops_in_group[g])) routes[g] = numpy.array(stops_in_group[g]) start_index = numpy.nonzero(route_indices==0)[0][0] indices_in_order = route_indices[start_index:len(route_indices)] indices_in_order = numpy.append(indices_in_order,route_indices[0:start_index+1]) routes[g] = routes[g][indices_in_order,:] # check that all routes are non-trivial found_valid_route = True for g in range(num_groups): if len(routes[g][:,0])<4: found_valid_route = False return routes
def defined_route(location_list): args = [] args = str(location_list).split(",") gmaps = googlemaps.Client(key = "Your api key.") dict_latitude = {} dict_longitude = {} distance_dict = {} tsp_as_json = {} distance_bw2_matrix = [] way_of_travel = [] for x in range(len(args)): geocode_result = gmaps.geocode(args[x]) latitude = geocode_result[0]['geometry']['location']['lat'] longitude = geocode_result[0]['geometry']['location']['lng'] dict_latitude[args[x]] = latitude dict_longitude[args[x]] = longitude def get_distance(location_source, location_destination): distance_matrix = gmaps.distance_matrix(location_source, location_destination) if distance_matrix['rows'][0]['elements'][0]['status'] == 'ZERO_RESULTS': return "No results for " + distance_matrix['origin_addresses'][0] + " and " + distance_matrix['destination_addresses'][0] else: if "," in distance_matrix['rows'][0]['elements'][0]['distance']['text'].split(" ")[0]: temp = distance_matrix['rows'][0]['elements'][0]['distance']['text'].split(" ")[0].split(",") return float(temp[0]+temp[1]) else: return float(distance_matrix['rows'][0]['elements'][0]['distance']['text'].split(" ")[0]) for i in range(len(args)): for j in range(len(args)): if i==j: distance_bw2_matrix.append(0) else: distance_bw2_matrix.append(get_distance(args[i], args[j])) distance_bw2_matrix = reshape(distance_bw2_matrix,(len(args),len(args))) r = range(len(distance_bw2_matrix)) dist = {(i, j): distance_bw2_matrix[i][j] for i in r for j in r} tsp_list = list((tsp.tsp(r, dist))) for x in tsp_list[1]: way_of_travel.append(args[x]) tsp_as_json['distance'] = str(tsp_list[0]) tsp_as_json['way_of_travel'] = str(way_of_travel) return json.dumps(tsp_as_json)
def koordinates(n): ls = [] if n == 1: x = input("Adjon meg egy koordinátát','-vel elválasztva:") print("1") if n == 2: for i in range(n): x = input("Adjon meg egy koordinátát','-vel elválasztva:") print("1,2") if n == 3: a = input("Adjon meg egy koordinátát','-vel elválasztva:") ax ,ay = a.split(",") ax = int(ax) ay = int(ay) b = input("Adjon meg egy koordinátát','-vel elválasztva:") bx,by = b.split(",") bx = int(bx) by = int(by) c = input("Adjon meg egy koordinátát','-vel elválasztva:") cx, cy = c.split(",") cx = int(cx) cy= int(cy) s1 = min(abs(ax - bx),abs(ay - by)) s2 = min(abs(ax-cx),abs(ay-cy)) s3 = min(abs(bx-cx),abs(by-cy)) ls = [s1,s2,s3] if max(ls) == s1: print("1,3,2") if max(ls) == s2: print("1,2,3") if max(ls) == s3: print("2,1,3") else: for i in range(n): x = input("Adjon meg egy koordinátát','-vel elválasztva:") z,y = x.split(",") z=int(z) y=int(y) ls.append((z,y)) t = tsp.tsp(tuple(ls)) t = t[1] for i in t: print(i+1,end=",")
def tspPath(inString): graphStr, source, dest = [x.strip() for x in inString.split(";")] graph = Graph(graphStr, weighted=True, directed=False) # If there are two vertices, our conversion won't work correctly, # so treat this as a special case. if len(graph) == 2: if graph.containsEdge(Edge([source, dest])): return str(Path([source, dest])) else: return 'no' # add an overwhelmingly negative edge from source to dest, thus # forcing that to be part of a shortest Ham cycle. sumOfWeights = graph.sumEdgeWeights() fakeEdge = Edge([source, dest]) if graph.containsEdge(fakeEdge) == True: graph.removeEdge(fakeEdge) graph.addEdge(fakeEdge, -sumOfWeights) tspSoln = tsp(str(graph)) # print('graph', graph) # print('tspSoln', tspSoln) if tspSoln == 'no': return 'no' # convert from string to Path object tspSoln = Path.fromString(tspSoln) rotatedSoln = tspSoln.rotateToFront(source) if rotatedSoln[-1] != dest: # Probably oriented the wrong way (or else fakeEdge wasn't # used -- see below). Reverse then rotate source to front # again rotatedSoln = rotatedSoln.reverse().rotateToFront(source) # If dest still isn't at the end of the cycle, then the orginal graph didn't # have a Ham path from source to dest (but it did have a Ham # cycle -- a cycle that did *not* include fakeEdge). if rotatedSoln[-1] != dest: return 'no' else: return str(rotatedSoln)
def main(): randojson = "" points_of_interest = [] points_of_interest_orig = [] starting_point = { 'lat': 60.344230, 'lng': 24.836719, 'name': "STARTING POINT" } # Ride with GPS JSON with open('rando.json') as randofile: randojson = json.load(randofile) points_of_interest_orig = randojson['points_of_interest'] points_of_interest_orig.insert(0, starting_point) # Limit the area for point in points_of_interest_orig: if point['lng'] > 24.506857123730356 and point[ 'lng'] < 26.835505390216667: points_of_interest.append(point) coordinates = [] for point in points_of_interest: lat = point['lat'] lng = point['lng'] latlng = (lat, lng) xy = project_to_meters(lat, lng) coordinates.append(xy) print("Calculating the order...") distance, best_state = tsp.tsp(coordinates) for state in best_state: print(points_of_interest[state]['name']) print('The best state found is: ', best_state) print('The distance at the best state is: ', distance)
def main(): for k in range(2): bestRoute = geneticAlgorithmPlot(population=cityList, popSize=100, eliteSize=20, mutationRate=0.01, generations=500) bestRouteList = [] sX = [] sY = [] IndexRoute = [] for j in range(len(bestRoute)): bestRouteList.append((bestRoute[j].x, bestRoute[j].y)) sX.append(bestRoute[j].x) sY.append(bestRoute[j].y) #import pdb; pdb.set_trace() IndexRoute.append(key_list[val_list.index(bestRouteList[j])]) sX.append(bestRoute[0].x) sY.append(bestRoute[0].y) #plotPath(sX, sY) #print(IndexRoute) crowd.append(IndexRoute) #print(agg_matrix(crowd)) #import pdb; pdb.set_trace() agg = agg_matrix(crowd) Inv_Agg = np.zeros((n, n)) for k in range(n): for j in range(n): Inv_Agg[k, j] = 1 - sc.betaincinv(2.8, 3.2, agg[k, j] / n) r = range(n) dist = {(i, j): Inv_Agg[i, j] for i in r for j in r} aggRoute = tsp.tsp(r, dist)[1] cost = 0 for u in range(n - 1): cost += R_D[aggRoute[u], aggRoute[u + 1]] cost += R_D[n - 1, 0] print(aggRoute, cost) '''
def route_builder(route_info, stop): def append_graph(route_info, stop): # initiate geocoder wrapper geolocator = Nominatim() # get the geocode object from the geopy to convert these string addresses to there respective lat/lon coordinates source = geolocator.geocode(route_info.address_q.get()) destination = geolocator.geocode(route_info.address_q.get()) # both source and destination cannot be none as if they are none, this means that the addresses inputted were in the wrong format # and no geocode could be found for the addresses if source and destination: print("Valid Source and Destination") if route_info.ordered_list: current_location = route_info.ordered_list[0] else: # default location to start the program, approximately in the middle of the city current_location = geolocator.geocode("10127 121 St NW, Edmonton, AB") current_location = find_vertex(route_info.coord, mult_coords(current_location.latitude),mult_coords(current_location.longitude)) route_info.name_vert_dict[current_location] = "10127 121 St NW, Edmonton, AB" route_info.sd_list.add(current_location) # find the closest vertices in the graph for the source and destination, thereafter find the least cost path through dijkstra's algorithm source = find_vertex(route_info.coord, mult_coords(source.latitude),mult_coords(source.longitude)) destination = find_vertex(route_info.coord, mult_coords(destination.latitude), mult_coords(destination.longitude)) # store the name of the location corresponding to the vertice route_info.name_vert_dict[source] = route_info.s_name_text route_info.name_vert_dict[destination] = route_info.d_name_text min_path, path_dist = least_cost_path(route_info.g, route_info.coord, source, destination, cost_distance) temp_list = copy.deepcopy(set(route_info.sd_list)) # create an edge with the least cost path between all prior source and destinations using dijkstra's algorithm for vert in temp_list: # source to vert temp_min_path, temp_path_dist = least_cost_path(route_info.g, route_info.coord, min_path[0], vert, cost_distance) route_info.route_graph.add_edge(min_path[0], vert, temp_path_dist[1]) route_info.path_dict[(min_path[0], vert)] = temp_min_path # vert to start temp_min_path, temp_path_dist = least_cost_path(route_info.g, route_info.coord, vert, min_path[0], cost_distance) route_info.route_graph.add_edge(vert, min_path[0], temp_path_dist[1]) route_info.path_dict[(vert, min_path[0])] = temp_min_path # destination to vert temp_min_path, temp_path_dist = least_cost_path(route_info.g, route_info.coord, min_path[-1], vert, cost_distance) route_info.route_graph.add_edge(min_path[-1], vert, temp_path_dist[1]) route_info.path_dict[(min_path[-1], vert)] = temp_min_path # vert to destination temp_min_path, temp_path_dist = least_cost_path(route_info.g, route_info.coord, vert, min_path[-1], cost_distance) route_info.route_graph.add_edge(vert, min_path[-1], temp_path_dist[1]) route_info.path_dict[(vert, min_path[-1])] = temp_min_path # create final edge from source to destination route_info.route_graph.add_edge(min_path[0],min_path[-1],path_dist[1]) # add to destination dictionary, destination is key and source is value to ensure that source always comes before destination in tsp route_info.sd_dict[min_path[-1]] = min_path[0] # save the associated least cost path waypoints to the path dictionary route_info.path_dict[(min_path[0], min_path[-1])] = min_path # add the source vertex to the source destination list route_info.sd_list.add(source) # add the destination vertex to the source destination list route_info.sd_list.add(destination) # return the value used for the current location during calculation return current_location # call the append new source and destination function current_location = append_graph(route_info, stop) # if while calculating the last append graph, another request was made add the new source, destination before calculating the tsp while stop.isSet(): current_location = append_graph(route_info, stop) stop = threading.Event() # list of vertices to find tsp between, with the starting location as the current location temp_set = route_info.sd_list try: temp_set.remove(current_location) except: print("Past the next waypoint") # find the tsp from starting from the current location final_path, final_dist = tsp(current_location, frozenset(temp_set), route_info) final_path.reverse() # depending on the location of the car will the next starting path from the where the car currently is will be decided if current_location in route_info.waypoints: prior_waypoints = route_info.waypoints[0:route_info.waypoints.index(current_location)] elif route_info.waypoints: # if the car passes the next waypoint intended for by the time the route is calculated return to waypoint then go on ts path # this is assuming that the car will not exceed the point by much, a simplification on drawing route_info.master_path.reverse() prior_waypoints = route_info.master_path[route_info.master_path.index(route_info.waypoints[0]):] else: prior_waypoints = [] temp = final_path[0] # make final waypoint path for driving route_info.waypoints = prior_waypoints + route_info.path_dict[temp][0:] route_info.ordered_list = [] route_info.ordered_list.append(temp[0]) final_path.remove(temp) # create ordered list of source and destinations to check off for x in final_path: route_info.ordered_list.append(x[0]) route_info.waypoints = route_info.waypoints + route_info.path_dict[x][1:] route_info.ordered_list.append(final_path[-1][1]) # ready to draw and drive the new path route_info.new_path = True return
points = zip(*points) plt.scatter(points[0], points[1]) def loadPoints(f): points = [] first_line = f.readline() for line in f.readlines(): p = [float(i) for i in line.split()] points.append((p[0], p[1])) return points def plotThread(points, path): plotPoints(points) plotPath(points, path) plt.show() if __name__ == "__main__": f = open(sys.argv[1]) points = loadPoints(f) f.close() plotPoints(points) path = tsp.tsp(points) obj = tsp.distance(points[path[-1]], points[path[0]]) for index in range(0, len(points) - 1): obj += tsp.distance(points[path[index]], points[path[index + 1]]) print obj print path