def dfs(graph, vehicles, camera_nodes): data = {} for vehicle in vehicles: #print(vehicle) visited = [] stack = [] parents = {} start_node = list(filter(lambda edge: edge == vehicle, graph.edges))[0][1] data[str(start_node)] = {"neighbor_cams" :[]} #print(list(G.neighbors(start_node))) stack.append(start_node) while len(stack) != 0: node = stack.pop() if node not in visited: visited.append(node) #print(list(G.neighbors(node))) print("NODe " + str(node)) custom_neighbors = list(G.neighbors(node)) print(custom_neighbors) for neighbor in custom_neighbors: #print(neighbor) if neighbor in camera_nodes.values(): camera_id = list(camera_nodes.keys())[list(camera_nodes.values()).index(neighbor)] camera = list(filter(lambda list_camera: list_camera['id'] == camera_id, cameras))[0] #print(camera) if "is_active" not in camera or "is_active" in camera and camera["is_active"] is not False: parents[str(neighbor)] = str(node) data[str(start_node)]["neighbor_cams"].append({"cam_id" : neighbor, "route": backtrace_route(parents, str(neighbor), str(start_node))}) else: parents[str(neighbor)] = str(node) stack.append(neighbor) #print(custom_neighbors) elif neighbor not in stack and neighbor not in visited: parents[str(neighbor)] = str(node) stack.append(neighbor) #print("Parents : {}".format(json.dumps(parents, indent=4, sort_keys=True))) labels = [list(camera_nodes.keys())[list(camera_nodes.values()).index(node)] if node in camera_nodes.values() else "" for node in G.nodes] nc = ['r' if node in camera_nodes.values() else 'b' for node in G.nodes] route_list = [neighbor_cam["route"] for neighbor_cam in data[str(start_node)]["neighbor_cams"]] ox.plot_graph_routes(G,routes=route_list, node_color=nc,node_zorder=3, orig_dest_node_color = ['r', 'k']*len(route_list)) print(camera_nodes.values()) return data
def test_routing_folium(): G = ox.graph_from_address(address=address, dist=500, dist_type="bbox", network_type="bike") # give each node a random elevation then calculate edge grades randm = np.random.random(size=len(G)) elevs = {n: e for n, e in zip(G.nodes(), randm)} nx.set_node_attributes(G, name="elevation", values=elevs) G = ox.add_edge_grades(G, add_absolute=True) # give each edge speed and travel time attributes G = ox.add_edge_speeds(G) G = ox.add_edge_travel_times(G) orig_node = list(G.nodes())[5] dest_node = list(G.nodes())[-5] orig_pt = (G.nodes[orig_node]["y"], G.nodes[orig_node]["x"]) dest_pt = (G.nodes[dest_node]["y"], G.nodes[dest_node]["x"]) route = nx.shortest_path(G, orig_node, dest_node, weight="travel_time") attributes = ox.utils_graph.get_route_edge_attributes( G, route, "travel_time") fig, ax = ox.plot_graph_route(G, route, save=True, filename="route", file_format="png") fig, ax = ox.plot_graph_route( G, route, origin_point=orig_pt, destination_point=dest_pt, save=True, filename="route", file_format="png", ) # test multiple routes fig, ax = ox.plot_graph_routes(G, [route, route]) # test folium gm = ox.plot_graph_folium(G, popup_attribute="name") rm = ox.plot_route_folium(G, route) # test calling folium plotters with FeatureGroup instead of Map, and extra kwargs fg = folium.FeatureGroup(name="legend name", show=True) gm = ox.plot_graph_folium(G, graph_map=fg) assert isinstance(gm, folium.FeatureGroup) rm = ox.plot_route_folium(G, route, route_color="g", route_map=fg, tooltip="x") assert isinstance(rm, folium.FeatureGroup)
def find_refuge(self, people=None, show_map=0): """ for each person, assign the refuge, route, and road :param people: :return: """ if people is None: people = self.people all_routes = [] for p in people: person = people[p] person.get_target() # find refuges and routes if person.refuge is not None: # person is generated at the exactly place as the refuge, if person.ifArrived(): person.refuge.add_person(person) else: road = self.roads[(person.route[0], person.route[1], 0)] pos = road.length * np.random.uniform(0, 1) road.add_person(person, pos) person.status = 1 all_routes.append(person.route) else: person.stay() if show_map == 1: fig, ax = ox.plot_graph_routes(self.graph, all_routes, fig_height=12) self.show(ax) self.show_refuge(ax)
def map_routes(self, df): routes = [] for i in range(len(df)): r = df.iloc[i]['Path'] routes.append(r) colors = ['r', 'b', 'y', 'm', 'c'] colors = colors[0:len(routes)] route_colors = [] count = 0 for i in range(len(routes)): if count != len(routes) - 1: route_colors += ([colors[i]] * (len(routes[i]) - 1)) count += 1 else: route_colors += ([colors[i]] * len(routes[i])) node_colors = [] for i in range(len(routes)): node_colors += (['k'] + [colors[i]]) fig, ax = ox.plot_graph_routes(my_graph, routes, route_color=route_colors, orig_dest_node_color=node_colors, node_size=0)
def test_routing_folium(): # calculate shortest path and plot as static image and leaflet web map import networkx as nx G = ox.graph_from_address('398 N. Sicily Pl., Chandler, Arizona', distance=800, network_type='drive') origin = (33.307792, -111.894940) destination = (33.312994, -111.894998) origin_node = ox.get_nearest_node(G, origin) destination_node = ox.get_nearest_node(G, destination, method='euclidean') route = nx.shortest_path(G, origin_node, destination_node) attributes = ox.get_route_edge_attributes(G, route, 'length') fig, ax = ox.plot_graph_route(G, route, save=True, filename='route', file_format='png') fig, ax = ox.plot_graph_route(G, route, origin_point=origin, destination_point=destination, save=True, filename='route', file_format='png') # test multiple routes fig, ax = ox.plot_graph_routes(G, [route, route]) graph_map = ox.plot_graph_folium(G, popup_attribute='name') route_map = ox.plot_route_folium(G, route)
def test_routing(): G = ox.graph_from_address(address=address, dist=500, dist_type="bbox", network_type="bike") # give each edge speed and travel time attributes G = ox.add_edge_speeds(G) G = ox.add_edge_speeds(G, hwy_speeds={"motorway": 100}) G = ox.add_edge_travel_times(G) orig_x = np.array([-122.404771]) dest_x = np.array([-122.401429]) orig_y = np.array([37.794302]) dest_y = np.array([37.794987]) orig_node = ox.distance.nearest_nodes(G, orig_x, orig_y)[0] dest_node = ox.distance.nearest_nodes(G, dest_x, dest_y)[0] route = ox.shortest_path(G, orig_node, dest_node, weight="travel_time") attributes = ox.utils_graph.get_route_edge_attributes(G, route) attributes = ox.utils_graph.get_route_edge_attributes( G, route, "travel_time") fig, ax = ox.plot_graph_route(G, route, save=True) # test multiple origins-destinations n = 5 nodes = np.array(G.nodes) origs = np.random.choice(nodes, size=n, replace=True) dests = np.random.choice(nodes, size=n, replace=True) paths1 = ox.shortest_path(G, origs, dests, weight="length", cpus=1) paths2 = ox.shortest_path(G, origs, dests, weight="length", cpus=2) paths3 = ox.shortest_path(G, origs, dests, weight="length", cpus=None) assert paths1 == paths2 == paths3 # test k shortest paths routes = ox.k_shortest_paths(G, orig_node, dest_node, k=2, weight="travel_time") fig, ax = ox.plot_graph_routes(G, list(routes)) # test folium with keyword arguments to pass to folium.PolyLine gm = ox.plot_graph_folium(G, popup_attribute="name", color="#333333", weight=5, opacity=0.7) rm = ox.plot_route_folium(G, route, color="#cc0000", weight=5, opacity=0.7) # test calling folium plotters with FeatureGroup instead of Map, and extra kwargs fg = folium.FeatureGroup(name="legend name", show=True) gm = ox.plot_graph_folium(G, graph_map=fg) assert isinstance(gm, folium.FeatureGroup) rm = ox.plot_route_folium(G, route, route_map=fg, tooltip="x") assert isinstance(rm, folium.FeatureGroup)
def plot_routes(self, routes, fig_height=10): """ Create_mdg() appears to be nondeterministic. routes is a list of routes. Each route is a list of nodes traversed in order. routes = None picks two routes of length 1 and plots those. """ MDG = self.create_mdg() if routes: ox.plot_graph_routes(MDG, routes, fig_height=fig_height) else: first_node_list = [list(MDG.edges)[0][0], list(MDG.edges)[0][1]] second_node_list = [list(MDG.edges)[1][0], list(MDG.edges)[1][1]] routes = [first_node_list, second_node_list] ox.plot_graph_routes(MDG, routes, fig_height=fig_height)
def test_routing(): G = ox.graph_from_address(address=address, dist=500, dist_type="bbox", network_type="bike") # give each node a random elevation then calculate edge grades randm = np.random.random(size=len(G)) elevs = {n: e for n, e in zip(G.nodes(), randm)} nx.set_node_attributes(G, name="elevation", values=elevs) G = ox.add_edge_grades(G, add_absolute=True) # give each edge speed and travel time attributes G = ox.add_edge_speeds(G) G = ox.add_edge_speeds(G, hwy_speeds={"motorway": 100}) G = ox.add_edge_travel_times(G) orig_node = list(G.nodes())[5] dest_node = list(G.nodes())[-5] orig_pt = (G.nodes[orig_node]["y"], G.nodes[orig_node]["x"]) dest_pt = (G.nodes[dest_node]["y"], G.nodes[dest_node]["x"]) route = ox.shortest_path(G, orig_node, dest_node, weight="travel_time") attributes = ox.utils_graph.get_route_edge_attributes(G, route) attributes = ox.utils_graph.get_route_edge_attributes( G, route, "travel_time") fig, ax = ox.plot_graph_route(G, route, save=True) fig, ax = ox.plot_graph_route(G, route, save=True) # test multiple routes routes = ox.k_shortest_paths(G, orig_node, dest_node, k=2, weight="travel_time") fig, ax = ox.plot_graph_routes(G, list(routes)) # test folium with keyword arguments to pass to folium.PolyLine gm = ox.plot_graph_folium(G, popup_attribute="name", color="#333333", weight=5, opacity=0.7) rm = ox.plot_route_folium(G, route, color="#cc0000", weight=5, opacity=0.7) # test calling folium plotters with FeatureGroup instead of Map, and extra kwargs fg = folium.FeatureGroup(name="legend name", show=True) gm = ox.plot_graph_folium(G, graph_map=fg) assert isinstance(gm, folium.FeatureGroup) rm = ox.plot_route_folium(G, route, route_map=fg, tooltip="x") assert isinstance(rm, folium.FeatureGroup)
def pltfromdoc(doc): import networkx as nx import osmnx as ox ox.config(use_cache=True, log_console=True) listofroutes = [] for row in doc: listofroutes.append(row["route"]) G = ox.graph_from_place('Cologne', network_type='bike') ox.plot_graph_routes(G, listofroutes, fig_height=15, node_size=1, route_linewidth=1, route_alpha=0.4, orig_dest_node_size=10, orig_dest_node_color='r', node_alpha=0.2, save=True, filename="graphbikes", file_format="png")
def plot_two_routes(self, graph, route1, route2, src_lat_long, destination_lat_long): #self.plot_path(lat, long, src_lat_long, destination_lat_long) # create route colors rc1 = ['r'] * (len(route1) - 1) rc2 = ['b'] * len(route2) rc = rc1 + rc2 nc = ['r', 'r', 'b', 'b'] # plot the routes fig, ax = ox.plot_graph_routes(graph, [route1, route2], route_color=rc, orig_dest_node_color=nc, node_size=0)
def shortest_safest(origin, destination): route1 = ox.shortest_path(G, origin, destination, weight='danger_weight') #safest road route2 = ox.shortest_path(G, origin, destination, weight='length') #shortest road fig, ax = ox.plot_graph_routes(G, routes=[route1, route2], route_colors=['r', 'y'], route_linewidth=6, node_size=0) return fig
def plot_routes(self, area_of_interest): boundary = area_of_interest.Boundary() lon = [] lat = [] for i in range(boundary.GetPointCount()): x, y, not_needed = boundary.GetPoint(i) lon.append(x) lat.append(y) east = max(lon)+1 west = min(lon)-1 north = max(lat)+1 south = min(lat)-1 fig, ax = ox.plot_graph_routes(self.map, self.route_cache, route_color='b', route_alpha=1, bbox=(north, south, east, west))
def plot_two_route(self, graph, route1, route2, src_lat_long, destination_lat_long, filename): rc1 = ['r'] * (len(route1) - 1) rc2 = ['b'] * len(route2) rc = rc1 + rc2 nc = ['r', 'r', 'b', 'b'] fig, ax = ox.plot_graph_routes(graph, [route1, route2], route_color=rc, orig_dest_node_color=nc, node_size=0, show=False, close=False, save=True, filename=filename)
def plot_route(fn): dataframe = pd.read_csv(fn) loa = list(dataframe['Location']) routes = [] for index, address in enumerate(loa): if index + 1 <= len(loa) - 1: origin = ox.utils.geocode(address) destination = ox.utils.geocode(loa[index + 1]) origin_node = ox.get_nearest_node(G, origin) destination_node = ox.get_nearest_node(G, destination) route = nx.shortest_path(G, origin_node, destination_node, weight='length') routes.append(route) ox.plot_graph_routes(G, routes, orig_dest_node_color='b')
def visualise(G, results): # Visualise result # for i in range(len(results)): routes = results[i] colors = np.array(["r", "y", "b", "g", "w"] * 5)[0:len(routes)] fig, ax = ox.plot_graph_routes(G, routes, route_colors=colors, route_linewidth=4, node_size=10, show=False, close=False) fig.suptitle('Car_{} routes'.format(i)) plt.show() return fig, ax
def plot_all_routes(G, origin, destination): routes = [ get_route_by_length(G, origin, destination), get_route_by_time(G, origin, destination), get_route_by_risk(G, origin, destination) ] rc = ['r', 'b', 'g'] return ox.plot_graph_routes(G, bgcolor='white', node_size=1.0, node_color='gray', edge_color='gray', routes=routes, route_colors=rc, dpi=300, figsize=(15, 15))
def plot_graph(self): if len(self.route_list) > 1: try: fig, ax = ox.plot_graph_routes( self.G, self.filtered, node_size=0, ) except: print("Error with the routes, number of routes:", len(self.route_list)) else: fig, ax = ox.plot_graph_route( self.G, self.route_list[0], node_size=0, )
def visualise_solution(graph, routes): """[summary] Args:ca graph ([type]): [description] routes ([type]): [description] Returns: [type]: [description] """ colors = np.array(["r", "y", "b", "g", "w"] * 10)[0:len(routes)] fig, axes = ox.plot_graph_routes(graph, routes, route_colors=colors, route_linewidth=4, node_size=10, show=False, close=False) fig.suptitle('Optimal routes'.format()) plt.show() return fig, axes
def plot_two_routes(self): # Plots the shortest route and safest route on the same map for comparison purposes and prints the total length of # both routes orig_node = ox.get_nearest_node(self.G, self.start) dest_node = ox.get_nearest_node(self.G, self.end) route1 = nx.shortest_path(self.G, orig_node, dest_node, weight='length') route2 = nx.shortest_path(self.G, orig_node, dest_node, weight='weight') print( 'Shortest Path Length:', nx.shortest_path_length(self.G, orig_node, dest_node, weight='length')) print( 'Safer Path Length:', nx.shortest_path_length(self.G, orig_node, dest_node, weight='weight')) rc1 = ['r'] * (len(route1) - 1) rc2 = ['b'] * len(route2) rc = rc1 + rc2 nc = ['r', 'r', 'b', 'b'] # plot the routes fig, ax = ox.plot_graph_routes(self.G, [route1, route2], bbox=self.bbox, route_color=rc, orig_dest_node_color=nc, node_size=0, fig_height=15)
def plot_routes(G, Groutes): """ Produce overlain plot of **G** and **Groutes** with specified style below. Parameters ---------- G: graph :ref:`Input graph<Input Graph>` from OSMnx query. Groutes: list Routes from **G** for each edge in **P**. Returns ------- fig: figure object Figure handle for plotting ax: axes object Axes handle for plotting """ fig, ax = ox.plot_graph_routes(G, Groutes, route_color='r', route_alpha=0.8, route_linewidth=2, node_size=0, edge_color='k', edge_linewidth=0.5, edge_alpha=0.5, orig_dest_node_size=0, orig_dest_node_alpha=0.0, fig_height=9, fig_width=6) return fig, ax
def plot_graph_routes(g, routes, filename, show=True, save=False, output_dir=''): if output_dir: filepath = os.path.join(output_dir, filename + '.png') else: filepath = None if len(routes) == 0: return ox.plot_graph(g, filepath=filepath, node_size=2, save=save, show=show) elif len(routes) == 1: return ox.plot_graph_route(g, route=routes[0], route_color="#F9A825", route_linewidth=1, orig_dest_size=5, node_size=2, filepath=filepath, save=save, show=show) else: return ox.plot_graph_routes(g, routes=routes, route_colors="#F9A825", route_linewidth=1, orig_dest_size=5, node_size=2, filepath=filepath, save=save, show=show)
def test_routing_folium(): # calculate shortest path and plot as static image and leaflet web map G = ox.graph_from_address(address=address, dist=500, dist_type="bbox", network_type="bike") # give each node a random elevation then calculate edge grades randm = np.random.random(size=len(G.nodes())) elevs = {n: e for n, e in zip(G.nodes(), randm)} nx.set_node_attributes(G, name="elevation", values=elevs) G = ox.add_edge_grades(G, add_absolute=True) orig_node = list(G.nodes())[5] dest_node = list(G.nodes())[-5] orig_pt = (G.nodes[orig_node]["y"], G.nodes[orig_node]["x"]) dest_pt = (G.nodes[dest_node]["y"], G.nodes[dest_node]["x"]) route = nx.shortest_path(G, orig_node, dest_node) attributes = ox.utils_graph.get_route_edge_attributes(G, route, "length") fig, ax = ox.plot_graph_route(G, route, save=True, filename="route", file_format="png") fig, ax = ox.plot_graph_route( G, route, origin_point=orig_pt, destination_point=dest_pt, save=True, filename="route", file_format="png", ) # test multiple routes fig, ax = ox.plot_graph_routes(G, [route, route]) graph_map = ox.plot_graph_folium(G, popup_attribute="name") route_map = ox.plot_route_folium(G, route)
def plotPathList(self, pathList, filename): fig, ax = ox.plot_graph_routes(self.graph, pathList, route_colors=['g', 'r', 'b'], node_size=5) fig.savefig(filename)
def main(): print('Welcome to ScenicRoute app!') print('\nLoading routes graph...') graph = nx.read_gpickle("places/zamosc.gpickle") graph_proj = ox.project_graph(graph) nodes_proj, edges_proj = ox.graph_to_gdfs(graph_proj, nodes=True, edges=True) print('DONE') lon_max = nodes_proj['lon'].max() lon_min = nodes_proj['lon'].min() l_long = lon_max - lon_min lat_max = nodes_proj['lat'].max() lat_min = nodes_proj['lat'].min() l_lat = lat_max - lat_min mode = input('\nDo you want to run demonstration mode? [y/n]\t') if mode == 'n': print('\nAvailable longitudes:\t' + str(lon_min) + '-' + str(lon_max)) print('Available latitudes:\t' + str(lat_min) + '-' + str(lat_max)) if input('\nUse default lat and lon? [y/n]\t') == 'n': print('\nSpecify desired start and end points:') start_lon = float(input('Type start longitude:\t')) start_lat = float(input('Type start latitude:\t')) end_lon = float(input('Type end longitude:\t')) end_lat = float(input('Type end latitude:\t')) else: alfa1 = 0.3 beta1 = 0.6 alfa2 = 0.7 beta2 = 0.4 start_lon = float(lon_min + alfa1 * l_long) start_lat = float(lat_min + beta1 * l_lat) end_lon = float(lon_min + alfa2 * l_long) end_lat = float(lat_min + beta2 * l_lat) else: alfa1 = 0.3 beta1 = 0.6 alfa2 = 0.7 beta2 = 0.4 start_lon = float(lon_min + alfa1 * l_long) start_lat = float(lat_min + beta1 * l_lat) end_lon = float(lon_min + alfa2 * l_long) end_lat = float(lat_min + beta2 * l_lat) print('\nFinding shortest route...') start_point, start_node = find_nearest_node(graph, start_lat, start_lon) end_point, end_node = find_nearest_node(graph, end_lat, end_lon) route = nx.shortest_path(G=graph, source=start_node, target=end_node, weight='length') route_length = nx.shortest_path_length(G=graph, source=start_node, target=end_node, weight='length') print('Shortest route length:\t' + str(route_length) + ' meters') print('DONE') scenic_routes1 = generate_scenic_routes(graph, lon_min, lat_min, l_long, l_lat, 10, 'sparse') scenic_routes2 = generate_scenic_routes(graph, lon_min, lat_min, l_long, l_lat, 10, 'cumulated') scenic_routes3 = generate_scenic_routes(graph, lon_min, lat_min, l_long, l_lat, 10, 'far') scenic_routes4 = generate_scenic_routes(graph, lon_min, lat_min, l_long, l_lat, 10, 'long') scenic_types = { 'sparse': scenic_routes1, 'cumulated': scenic_routes2, 'far': scenic_routes3, 'long': scenic_routes4 } scenic_routes_list = [ scenic_types['sparse'], scenic_types['cumulated'], scenic_types['far'] ] if mode == 'n': print('\nAvailable types of scenic routes:') print('1 - sparse') print('2 - cumulated') print('3 - far') print('4 - long') typee = input('Type number of desired type:\t') types = {1: 'sparse', 2: 'cumulated', 3: 'far', 4: 'long'} scenic_routes = scenic_types[types[int(typee)]] print('\nScenic routes parameters preference:') if input('Use default? [y/n]\t') == 'n': max_extra_dist = float(input('Type max extra distance [m]:\t')) minimum_scenic_length = float( input('Type min scenic distance [m]:\t')) else: max_extra_dist = float(6700) minimum_scenic_length = float(3000) print('DONE') if input( '\n Do you want max extra distance to be hard limitation? [y/n]:\t' ) == 'n': maximum_length = 100000 else: maximum_length = route_length + max_extra_dist the_route_closest, scenic_routes_visited_closest = build_a_route_with_closest_scenic_routes( graph, start_node, end_node, scenic_routes, minimum_scenic_length, maximum_length) print( "\nFound route and sum of scenic routes - closest scenic route algorithm" ) print(the_route_closest.length(), sum([sr.length() for sr in scenic_routes_visited_closest])) the_route_longest, scenic_routes_visited_longest = build_a_route_with_longest_scenic_routes( graph, start_node, end_node, scenic_routes, minimum_scenic_length, maximum_length) print( "\nFound route and sum of scenic routes - longest scenic route algorithm" ) print(the_route_longest.length(), sum([sr.length() for sr in scenic_routes_visited_longest])) the_route_astar, scenic_routes_visited_astar = build_a_route_with_astar_scenic_routes( graph, start_node, end_node, scenic_routes, minimum_scenic_length, maximum_length) print( "\nFound route and sum of scenic routes - a star scenic route algorithm" ) print(the_route_astar.length(), sum([sr.length() for sr in scenic_routes_visited_astar])) scenic_routes_nodes_lists = [s.nodes() for s in scenic_routes] print('\nClose maps to continue...') fig, ax = ox.plot_graph_route(graph, route, show=False, close=False) fig_closest, ax_closest = ox.plot_graph_route( graph, the_route_closest.nodes(), show=False, close=False ) # nie dziala wyswietlanie, z jakiegos powodu niektore wierzcholki nie wystepuja w krawedziach grafu fig_longest, ax_longest = ox.plot_graph_route( graph, the_route_longest.nodes(), show=False, close=False) fig_astar, ax_astar = ox.plot_graph_route(graph, the_route_astar.nodes(), show=False, close=False) fig_sc, ax_sc = ox.plot_graph_routes(graph, scenic_routes_nodes_lists, route_color='y', show=False, close=False) plt.show() else: minimum_scenic_length = 3000 maximum_length_hard = route_length + 6700 print('\nCalculating routes...') for maximum_length in [maximum_length_hard, 100000]: print('Maximum length of route:') print(maximum_length_hard) for scenic_type, scenic_routes in scenic_types.items(): if scenic_routes not in scenic_routes_list: continue print('\nType of scenic routes: ' + scenic_type) the_route_closest, scenic_routes_visited_closest = build_a_route_with_closest_scenic_routes( graph, start_node, end_node, scenic_routes, minimum_scenic_length, maximum_length) print( "\nFound route and sum of scenic routes - closest scenic route algorithm" ) print( the_route_closest.length(), sum([sr.length() for sr in scenic_routes_visited_closest])) the_route_longest, scenic_routes_visited_longest = build_a_route_with_longest_scenic_routes( graph, start_node, end_node, scenic_routes, minimum_scenic_length, maximum_length) print( "\nFound route and sum of scenic routes - longest scenic route algorithm" ) print( the_route_longest.length(), sum([sr.length() for sr in scenic_routes_visited_longest])) the_route_astar, scenic_routes_visited_astar = build_a_route_with_astar_scenic_routes( graph, start_node, end_node, scenic_routes, minimum_scenic_length, maximum_length) print( "\nFound route and sum of scenic routes - a star scenic route algorithm" ) print(the_route_astar.length(), sum([sr.length() for sr in scenic_routes_visited_astar])) scenic_routes_nodes_lists = [s.nodes() for s in scenic_routes] print('\nClose maps to continue...') fig, ax = ox.plot_graph_route(graph, route, show=False, close=False) fig_closest, ax_closest = ox.plot_graph_route( graph, the_route_closest.nodes(), show=False, close=False ) #nie dziala wyswietlanie, z jakiegos powodu niektore wierzcholki nie wystepuja w krawedziach grafu fig_longest, ax_longest = ox.plot_graph_route( graph, the_route_longest.nodes(), show=False, close=False) fig_astar, ax_astar = ox.plot_graph_route( graph, the_route_astar.nodes(), show=False, close=False) fig_sc, ax_sc = ox.plot_graph_routes(graph, scenic_routes_nodes_lists, route_color='y', show=False, close=False) plt.show() print("\nGood bye!")
for path in nx.all_simple_paths(G=graph_proj, source=orig_node, target=target_node): # print(path) route.append(path) if count == 10: break count += 1 # ----------------------------------------------------------------> plottina graph for visualization ec = ox.get_edge_colors_by_attr(graph_proj, attr='length') # ox.set_title("new1") ox.plot_graph(graph_proj, edge_color=ec) fig, ax = ox.plot_graph_routes(graph_proj, route, edge_color='#ffffff') plt.title("Different paths between source and destination") plt.tight_layout() #--------------------------------------------------------------------->Future work<------------------------------------------------- ''' As we found the paths between source and destination which are randomly selected, we will do this for specific source and destinastion and based on the paths we got and the information of GPS we will get to know the affected paths (finding the affected path is: we will send our rescue team to all the paths we found and get the information from them). From the remaining paths we will get to know the properties like distance, type of road(National Highways or State Highways or Normal), Based on this information we will send our rescue vehicle. '''
def drawRoutes(self, graph, routes, colors): self.figure, self.ax = ox.plot_graph_routes(graph, routes, show=False, close=True, route_color=colors[0]) self.draw() self.refrashRect()
def plot_graph_routes(self, routes: List[List], **kwargs): # ox.plot_graph_routes can not print one route if len(routes) > 1: ox.plot_graph_routes(self.G, routes=routes, **kwargs) elif len(routes) == 1: ox.plot_graph_route(self.G, route=routes[0], **kwargs)
edges_to_remove.append((new_u, new_v)) #G.remove_edges_from(edges_to_remove) # ox.plot_graph(G, node_color=nc) # #print("After reverse removal : " + str(len(G.edges))) # #select edge at random for vehicle #vehicle_edge = random.choice(list(G.edges)) #print("Random vehicle edge : {}".format(vehicle_edge)) vehicles = [] for edge in list(G.edges): vehicles.append(edge) print(vehicles) ec = ['k' if edge in vehicles else 'b' for edge in G.edges] notified_cams = dfs(G, vehicles, camera_nodes) print("Cameras notified: {}".format( json.dumps(notified_cams, indent=4, sort_keys=True))) route_list = [] for vehicle, data in notified_cams.items(): route_list = data["route"] ox.plot_graph_routes(G, routes=route_list, node_color=nc, edge_color=ec, node_zorder=3, orig_dest_node_color=['r', 'k'] * len(route_list)) print("--- %s seconds ---" % (time.time() - start_time))
print("average time to generate dijkstra path: ", (t1 - t0) / 100, ", length = ", d_len) t0 = time.time() for i in range(0, 100): distances = a_star_get_distance_euclidean(Gc, source_node, target_node) ae_path, ae_len = a_star_get_path(Gc, source_node, target_node, distances) t1 = time.time() print("average time to generate euclidean astar path: ", (t1 - t0) / 100, ", length = ", ae_len) t0 = time.time() for i in range(0, 100): distances = a_star_get_distance_manhattan(Gc, source_node, target_node) am_path, am_len = a_star_get_path(Gc, source_node, target_node, distances) t1 = time.time() print("average time to generate manhattan astar path: ", (t1 - t0) / 100, ", length = ", am_len) t0 = time.time() for i in range(0, 100): route = nx.shortest_path(G=Gc, source=source_node, target=target_node, weight='length') t1 = time.time() print("average time for library to find shortest path: ", (t1 - t0) / 100) print("manhattan is off by ", am_len - ae_len, "meters, which is ", (am_len - ae_len) / ae_len, "%") fig, ax = ox.plot_graph_routes(Gc, [d_path, ae_path, am_path, route], route_colors=["red", "blue", "green", "yellow"])
5702799331, 1812252645, 280692710, 5581936615, 14956520, 208359407, 4200738804, 141606902, 519026686 } print('start double expansoin A*!') print(orig_node, dest_node) # start = time.time() # multimodal_double_expansion_astar = MultiModalDoubleExpansionAStar() # routes, secs = multimodal_double_expansion_astar.get_best_path(G, orig_node, dest_node, bss_nodes) # # end = time.time() # print(end - start) # # print(routes) # print(secs) # osmnx.plot_graph_routes(G, routes, node_size=0) start = time.time() multimodal_double_expansion_astar_one_queue = MultiModalDoubleExpansionAStarOneQueue( ) routes, secs = multimodal_double_expansion_astar_one_queue.get_best_path( G, orig_node, dest_node, bss_nodes, double_expansion_one_queue_callback) end = time.time() print(end - start) print(routes) print(secs) osmnx.plot_graph_routes(G, routes, node_size=0)