def set_speed(graph, german=False): # sets pre-set speed limits if german: speeds = { 'motorway': 80, 'trunk': 80, 'primary': 70, 'secondary': 50, 'motorway_link': 50, 'trunk_link': 50, 'primary_link': 50, 'secondary_link': 50 } ox.speed.add_edge_speeds(graph, hwy_speeds=speeds, fallback=50, precision=1) ox.speed.add_edge_travel_times(graph, precision=1) # takes pre-existing speed limits and fills up all unkown else: graph = ox.add_edge_speeds(graph) graph = ox.add_edge_travel_times(graph) speeds = {'residential': 35, 'secondary': 50, 'tertiary': 60} graph = ox.add_edge_speeds(graph, speeds) graph = ox.add_edge_travel_times(graph) print('Speed added..') return graph
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 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 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 travel_time(G): hwy_speeds = { 'motorway': 110, 'trunk': 80, 'primary': 80, 'secondary': 60, 'tertiary': 40, 'residential': 30, 'unclassified': 60, 'motorway_link': 80, 'trunk_link': 80, 'primary_link': 60, 'secondary_link': 40, 'tertiary_link': 40, 'living_street': 30, 'service': 30, 'pedestrian': 10, 'track': 60, 'sidewalk': 10, 'footway': 10, 'crossing': 10, 'cycleway': 20 } G = ox.add_edge_speeds(G, hwy_speeds) G = ox.add_edge_travel_times(G) return G
def pick_location(trip_type: str = "drive", most_dangerous: bool = False) -> str: """ Parameters ---------- trip_type : str Type of vehicle roads like drive (cars, motorbikes, ...), walk (pedestrian) or bikes. most_dangerous : bool Boolean that says if we are looking for the most dangerous road. Returns ------- str Message to congratulate our machine. """ # Generate the network of NYC based on the trip_type G = ox.graph_from_place("New York City, New York, USA", network_type=trip_type) G = ox.add_edge_speeds(G) G = ox.add_edge_travel_times(G) # nodes_to_csv(G, "drive_safe_node.csv") # csv file with the danger scores data_danger = pd.read_csv( r"C:\Users\Guillaume\Documents\git\nyc-navigation\CSV\street.csv") G_danger = add_edge_danger(data_danger, G, trip_type, most_dangerous) osmnx.io.save_graphml(G_danger, filepath="bike_dangerous.graphml") return "Done"
def init_graph(place): city = ox.graph_from_place(place, network_type='drive') city = ox.add_edge_speeds(city) city = ox.speed.add_edge_travel_times(city) for u, v in city.edges(): city[u][v][0]["weight"] = city.get_edge_data(u, v)[0]["length"] return city
def load_city_graph(city_name): G = ox.load_graphml('data/%s_drive_network_original.graphml' % city_name) G = nx.convert_node_labels_to_integers(G, ordering='default') G = ox.add_edge_bearings(G) G = ox.add_edge_speeds(G) G = ox.add_edge_travel_times(G) # for e in G.edges(data=True): # u, v, info = e # if type(info['highway']) == list: # info['highway'] = ":".join(info['highway']) return G
def create_tor_graph(filter_df = "None", weighted=True): G = ox.graph_from_place('Toronto, Ontario, Canada', network_type='drive') ksi_df = ksi_data_preprocessing(G, filter_df) given_df = ksi_df.groupby('G_NODE')['ACCIDENT'].apply(list).reset_index(name='ACCIDENTS') attr = given_df.set_index('G_NODE')['ACCIDENTS'].to_dict() nx.set_node_attributes(G, [], "accident_list") nx.set_node_attributes(G, attr, "accident_list") if weighted: weights = getEdgeWeights(given_df, G) nx.set_edge_attributes(G, 0, 'w') nx.set_edge_attributes(G, weights, 'w') G = ox.add_edge_speeds(G) G = ox.add_edge_travel_times(G) return G
def init_graph(place): city = ox.graph_from_place(place, network_type='drive') city = ox.add_edge_speeds(city) city = ox.speed.add_edge_travel_times(city) connected = max(nx.strongly_connected_components(city), key=len) to_remove = set() for u, v in city.edges(): if u not in connected: to_remove.add(u) if v not in connected: to_remove.add(v) city[u][v][0]["weight"] = city.get_edge_data(u, v)[0]["length"] city.remove_nodes_from(to_remove) return city
def update_routing_old(): # In the graph, get the nodes closest to the points #area = ("Namur, Wallonia, Belgium") #G = ox.graph_from_place(area, network_type='drive') #G = ox.graph_from_bbox(north=50.817, south=50.1135, east=6.4243, west= 4.9603, network_type='drive')#box around Liege province G = ox.graph_from_bbox(north=50.6497, south=59.7852, east=5.3966, west=4.29, network_type='drive') #box around Namur province # OSM data are sometime incomplete so we use the speed module of osmnx to add missing edge speeds and travel times G = ox.add_edge_speeds(G) G = ox.add_edge_travel_times(G) # Save graph to disk if you want to reuse it ox.save_graphml(G, "Namur.graphml")
def prepare_graph(self, g): """Takes in a graph, add speed and travel times, updates travel times per edge Input: graph Output: graph """ new_g = ox.add_edge_speeds(g) new_g = ox.add_edge_bearings(new_g) edges_g = ox.graph_to_gdfs(new_g, nodes=False) # Graph edges DF nodes_g = ox.graph_to_gdfs(new_g, edges=False) # Graph nodes DF edges_g_updated = self.update_speed_in_edges( edges_g) # change the speed for calamity roads edges_g_updated['travel_time2'] = edges_g_updated.apply( lambda x: self.travel_time_recalc(x), axis=1) new_graph = ox.graph_from_gdfs( nodes_g, edges_g_updated) ## Putting the DF back to the graph return new_graph, edges_g_updated
def make_graph(bounding_zone): G = ox.graph_from_polygon(bounding_zone, network_type='walk') # Project the graph from lat-long to the UTM zone appropriate for its geographic location. G = ox.project_graph(G) hwy_speeds = { "residential": 40, "unclassified": 40, "tertiary": 56, "secondary": 56, "primary": 80, "trunk": 56 } G = ox.add_edge_speeds(G, hwy_speeds) G = ox.add_edge_travel_times(G) return G
def animation_route(transport): city = ox.gdf_from_place('Montpellier, France') G = ox.graph_from_place('Montpellier, France', network_type=transport) G = ox.add_edge_speeds(G) G = ox.add_edge_travel_times(G) start = (43.61032245, 3.8966295) end = (43.6309201, 3.8611052550025553) start_node = ox.get_nearest_node(G, start) end_node = ox.get_nearest_node(G, end) route = nx.shortest_path(G, start_node, end_node) route_len = nx.shortest_path_length(G, start_node, end_node) # bounds for axis x_min, y_min, x_max, y_max = city.total_bounds fig, ax = ox.plot_graph_route(G, route, route_linewidth=1, node_size=0, edge_linewidth=0.3, show=False, close=False) city.plot(ax=ax, edgecolor='black', linewidth=0.5, alpha=0.1) ax.set(xlim=(x_min, x_max), ylim=(y_min, y_max)) sc = ax.scatter(G.nodes[route[0]]['x'], # x coordiante G.nodes[route[0]]['y'], # y coordiante s=100, c="b", alpha=1) def animate(i): x = G.nodes[route[i]]['x'] y = G.nodes[route[i]]['y'] sc.set_offsets(np.c_[x, y]) return sc anim = FuncAnimation(fig, animate, frames=route_len) anim.save('animation_weight.gif', fps=10, writer = 'imagemagick') return HTML(anim.to_jshtml())
def populate_graph(G, speeds = False): G = ox.add_edge_speeds(G) if speeds else G G = ox.add_edge_travel_times(G) G = ox.add_node_elevations(G, api_key= api_key) G = ox.add_edge_grades(G, None, None)
def save_graph(): warsaw_streets = ox.graph_from_place('Warsaw', network_type='drive') warsaw_streets = ox.add_edge_speeds(warsaw_streets) warsaw_streets = ox.add_edge_travel_times(warsaw_streets) ox.save_graphml(warsaw_streets, "warsaw.graphml")
def populate_graph(self, G, speeds = False): G = ox.add_edge_speeds(G) if speeds else G G = ox.add_node_elevations(G, api_key= api_key) G = ox.add_edge_grades(G) return G
def __init__(self, number_of_warehouses=1, number_of_hospitals=15, seed=3, max_demand=3): """ Initializer of the function. There are three types of nodes. (0) is a hospital, (1) a warehouse and (2) anything else, like cross roads. Parameters ---------- number_of_warehouses: int the number of warehouses to be considered for a given world. Needs to be smaller than number_of_nodes seed: int the random seed used to generate the world """ # Get graph and positions filepath = pathlib.Path( __file__).parent.absolute() / "Cambridge_Graph.xml" self.graph = ox.load_graphml(filepath) # self.graph = ox.project_graph(ox.io.load_graphml(filepath), to_crs="EPSG:3395") self.graph = ox.add_edge_speeds(self.graph) self.graph_type1 = ox.add_edge_travel_times(self.graph) self.graph_type2 = ox.add_edge_travel_times(self.graph) # Generate random warehouses and hospitals np.random.seed(seed) random_locations = np.random.choice(self.graph.nodes, number_of_warehouses + number_of_hospitals, replace=False) random_warehouse_locations = random_locations[:number_of_warehouses] random_hospital_locations = random_locations[number_of_warehouses:] # Set them to be readable by the object self.warehouses = list(random_warehouse_locations) self.hospitals = list(random_hospital_locations) # Label all the nodes for node in self.graph.nodes: pointer = self.graph.nodes[node] if node in random_hospital_locations: # Hospitals pointer['type'] = 0 pointer['demand1'] = np.random.randint( max_demand ) # Going to change this to between 0 and 1 for now pointer['demand2'] = np.random.randint(max_demand) pointer['priority'] = np.random.randint(1, 3) pointer['init_demand1'] = pointer['demand1'] pointer['init_demand2'] = pointer['demand2'] elif node in random_warehouse_locations: # Warehouses pointer['type'] = 1 else: # Corners pointer['type'] = 2 # Label all the edges with traffic - to get higher values change the multiplier for edge in self.graph.edges: pointer = self.graph.edges[edge] pointer['travel_time'] *= 1.0
def __init__(self, start: Union[tuple, str], end: Union[tuple, str], network_type='drive', graph_type='points'): if graph_type == 'points': self.dist = int( calcGreatCircleDistanceOnEarth(start, end) + SIGHT_RADIUS_ADDITION) self.G = ox.graph_from_point(start, dist=self.dist, network_type=network_type) else: g1, start = ox.graph_from_address(start, 20, return_coords=True) g2, end = ox.graph_from_address(end, 20, return_coords=True) self.dist = int( calcGreatCircleDistanceOnEarth(start, end) + SIGHT_RADIUS_ADDITION) self.G = ox.graph_from_point(start, dist=self.dist, network_type=network_type) self.G = ox.add_edge_speeds(self.G, hwy_speeds={ 'motorway': 130, 'trunk': 110, 'primary': 70, 'secondary': 50, 'tertiary': 50, 'unclassified': 30, 'residential': 30, 'steps': 0, 'trunk_link': 70, 'motorway_link': 70, 'primary_link': 40, 'secondary_link': 20, 'tertiary_link': 20, 'service': 10, 'living_street': 20 }, fallback=1) self.G = ox.add_edge_travel_times(self.G) g_nodes = self.G.nodes(data=True) self.start = ox.get_nearest_node(self.G, start) self.end = ox.get_nearest_node(self.G, end) print('\n-- Notice that requested coordinates are') print('---- src =', start, ', dst =', end) print('-- Actual coordinate are') print('---- src =', (g_nodes[self.start]['y'], g_nodes[self.start]['x']), ', dst =', (g_nodes[self.end]['y'], g_nodes[self.end]['x']), '\n') self.nodes = np.array(list(self.G.nodes)) self.edges = np.array(list(self.G.edges), dtype=float) w = np.ones(self.edges.shape[0], dtype=float) * inf for u, v, d in self.G.edges(data=True): w[(self.edges[:, 0] == u) & (self.edges[:, 1] == v)] = d['travel_time'] self.edges[:, 2] = w.copy() data = self.G.nodes(data=True) self.coordinates = [] for node in data: self.coordinates.append((node[1]['y'], node[1]['x'])) self.coordinates = np.array(self.coordinates) self.coordinates = self.coordinates[self.nodes.argsort()] self.nodes.sort() self.pos = nx.spring_layout(self.G) self.blocked = []
import numpy as np import geopandas as gpd import matplotlib.pyplot as plt from shapely.geometry import Point import matplotlib.animation as animation import random from geographiclib.geodesic import Geodesic import time geod = Geodesic.WGS84 G = ox.graph_from_bbox(1.3763, 1.3007, 103.6492, 103.7840, network_type='drive') #, simplify=True) G = ox.add_edge_speeds(G) G = ox.add_edge_travel_times(G) projected_graph = ox.project_graph(G, to_crs="EPSG:3395") Gc = ox.consolidate_intersections(projected_graph, dead_ends=True) edges = ox.graph_to_gdfs(ox.get_undirected(Gc), nodes=False) vehnumber = 10 routes = [] route = [] allAngleList = [] direction = [] all_route_roadnames = [] all_route_speeds = [] angleList = []
def build_mobsys(self): print('Building Mobility System') print('\t getting graph') G_drive_sim = self.get_graph_buffered_to_hw_type( self.zones.loc[self.zones['sim_area']], self.external_hw_tags, 'drive') print('getting external roads') G_drive_model = osmnx.graph_from_polygon( self.zones.loc[self.zones['model_area']].unary_union, network_type='drive', custom_filter='["highway"~"{}"]'.format('|'.join( self.external_hw_tags))) G_drive_combined = osmnx.graph.nx.compose(G_drive_model, G_drive_sim) # for edge in list(G_walk.edges): # G_walk.edges[edge]['speed_kph']=4.8 G_drive_combined = osmnx.add_edge_speeds(G_drive_combined) G_drive_combined = PreCompOsmNet.simplify_network(G_drive_combined) G_drive_combined = osmnx.add_edge_travel_times(G_drive_combined) for edge in list(G_drive_combined.edges): G_drive_combined.edges[edge][ 'travel_time_walk'] = G_drive_combined.edges[edge][ 'length'] / (4800 / 3600) G_drive_combined.edges[edge][ 'travel_time_cycle'] = G_drive_combined.edges[edge][ 'length'] / (14000 / 3600) G_drive_combined.edges[edge][ 'travel_time_pt'] = G_drive_combined.edges[edge]['length'] / ( 25000 / 3600) G_drive_combined = osmnx.utils_graph.get_undirected(G_drive_combined) # fw_pred_drive=PreCompOsmNet.pre_compute_paths(G_drive_combined) # Note: this approach will assume the same route for each mode but different travel times # For different routes, would need to compute the fw result for each mode fw_all, self.route_lengths = PreCompOsmNet.pre_compute_paths( G_drive_combined, weight_metric='length', save_route_costs=True) pre_comp_drive = PreCompOsmNet.PreCompOSMNet(G_drive_combined, fw_all) networks = { 'drive': pre_comp_drive, 'walk': pre_comp_drive, 'cycle': pre_comp_drive, 'pt': pre_comp_drive } drive_dict = { 'target_network_id': 'drive', 'travel_time_metric': 'travel_time' } walk_dict = { 'target_network_id': 'walk', 'travel_time_metric': 'travel_time_walk' } cycle_dict = { 'target_network_id': 'cycle', 'travel_time_metric': 'travel_time_cycle' } pt_dict = { 'target_network_id': 'pt', 'travel_time_metric': 'travel_time_pt' } modes = { 'drive': OpenCity.Mode(drive_dict), 'walk': OpenCity.Mode(walk_dict), 'cycle': OpenCity.Mode(cycle_dict), 'pt': OpenCity.Mode(pt_dict) } self.mob_sys = OpenCity.MobilitySystem(modes=modes, networks=networks)