def test_get_network_methods(): from shapely import wkt # graph from bounding box north, south, east, west = 37.79, 37.78, -122.41, -122.43 G1 = ox.graph_from_bbox(north, south, east, west, network_type='drive_service') G1 = ox.graph_from_bbox(north, south, east, west, network_type='drive_service', truncate_by_edge=True) # graph from point location_point = (37.791427, -122.410018) bbox = ox.bbox_from_point(location_point, project_utm=True) G2 = ox.graph_from_point(location_point, distance=750, distance_type='bbox', network_type='drive') G3 = ox.graph_from_point(location_point, distance=500, distance_type='network') # graph from address G4 = ox.graph_from_address(address='350 5th Ave, New York, NY', distance=1000, distance_type='network', network_type='bike') # graph from list of places places = ['Los Altos, California, USA', {'city':'Los Altos Hills', 'state':'California'}, 'Loyola, California'] G5 = ox.graph_from_place(places, network_type='all', clean_periphery=False) # graph from polygon polygon = wkt.loads('POLYGON ((-122.418083 37.754154, -122.418082 37.766028, -122.410909 37.766028, -122.410908 37.754154, -122.418083 37.754154))') G6 = ox.graph_from_polygon(polygon, network_type='walk') # test custom query filter filtr = ('["area"!~"yes"]' '["highway"!~"motor|proposed|construction|abandoned|platform|raceway"]' '["foot"!~"no"]' '["service"!~"private"]' '["access"!~"private"]') G = ox.graph_from_point(location_point, network_type='walk', custom_filter=filtr)
def detect_drive_network_from_point(lat=13.14633, lon=77.514386, distance=2000, save=True, filename='icts2000'): G = ox.graph_from_point((lat, lon), distance=distance, network_type='drive', simplify=False) hwy_types = ['primary', 'motorway', 'trunk'] gdf = ox.graph_to_gdfs(G, nodes=False) mask = ~gdf['highway'].map(lambda x: isinstance(x, str) and x in hwy_types) edges = zip(gdf[mask]['u'], gdf[mask]['v'], gdf[mask]['key']) G.remove_edges_from(edges) G = ox.remove_isolated_nodes(G) G_projected = ox.project_graph(G) filename += '-' + str(distance) fig, ax = ox.plot_graph(G_projected, show=False, save=save, filename=filename, file_format='svg') plt.scatter(*utm.from_latlon(lat, lon)[:2]) plt.show() ox.save_graphml(G, filename=filename + '.graphml') return G
def test_stats(): # create graph, add bearings, project it G = ox.graph_from_point(location_point, dist=500, network_type="drive") G = ox.add_edge_bearings(G) G_proj = ox.project_graph(G) # calculate stats stats = ox.basic_stats(G) stats = ox.basic_stats(G, area=1000) stats = ox.basic_stats(G_proj, area=1000, clean_intersects=True, tolerance=15, circuity_dist="euclidean") # calculate extended stats stats = ox.extended_stats(G, connectivity=True, anc=False, ecc=True, bc=True, cc=True) # test cleaning and rebuilding graph G_clean = ox.consolidate_intersections(G_proj, tolerance=10, rebuild_graph=True, dead_ends=True)
def shortestPathNavigation(userLoc, destinLoc): """ :type userLoc: List[float] of size 2 :type destinLoc: List[float] of size 2 """ G = ox.graph_from_point(userLoc, distance = 2000, distance_type = 'network', network_type = 'walk') Gnodes = G.nodes() # Get the nearest node in the system of the given location origin_node = ox.get_nearest_node(G, userLoc) destin_node = ox.get_nearest_node(G, destinLoc) # Get the lat&lng of the approximated location origin_point, destin_point = [[Gnodes[i]['y'],Gnodes[i]['x']] for i in [origin_node, destin_node]] # Get the shortest route's nodes' indices route = nx.shortest_path(G, origin_node,destin_node, weight = 'length') fig,ax = ox.plot_graph_route(G,route,origin_point = origin_point, destination_point = destin_point) # Get the shortest route's lat&lng the_route = [[G.nodes()[i]['y'],G.nodes()[i]['x']] for i in route] # Create map and add markers of origin&destin to the map m = folium.Map(location = userLoc, zoom_start = 13) marker_cluster = folium.MarkerCluster().add_to(m) folium.Marker(origin_point, popup = 'Origin').add_to(marker_cluster) folium.Marker(destin_point, popup = 'Dest').add_to(marker_cluster) # Add the shortest path to the map shortest_path = folium.PolyLine(the_route).add_to(m) # More parameters: #weight=15,#color='#8EE9FF' # Show the map return m
def GenerateIsoPoints(lon, lat, time, speed): ''' Function generates points cloud of isochrone from OSM depending on route type. Returns list of points. ''' distance = speed * 1000 / 60 * time * 1.5 streets_graph = ox.graph_from_point([lat, lon], distance=distance, network_type=route, simplify=False) center_node = ox.get_nearest_node(streets_graph, (lat, lon), method='euclidean') streets_graph.add_node('dummy', osmid=999999999, x=lon, y=lat) dummy_length = geopy.distance.vincenty((streets_graph.node['dummy']['y'], streets_graph.node['dummy']['x']), (streets_graph.node[center_node]['y'], streets_graph.node[center_node]['x'])).m streets_graph.add_edge('dummy', center_node, length=dummy_length) projected_graph = ox.project_graph(streets_graph) travel_speed = speed meters_per_minute = travel_speed * 1000 / 60 for u, v, k, data in projected_graph.edges(data=True, keys=True): data['time'] = data['length'] / meters_per_minute subgraph = nx.ego_graph(projected_graph, center_node, radius=time, distance='time') node_points = [[data['lon'], data['lat']] for node, data in subgraph.nodes(data=True)] points = np.array(node_points) return points
def __init__(self, center_lat=47.608013, center_long=-122.335167, dist=1000): center_pt = (center_lat, center_long) G = ox.graph_from_point(center_pt, distance=dist, network_type='drive') #G = ox.graph_from_place(place) self.G = G self.node_map = self.set_intersections(G) #dictionary of nodes self.edge_map = self.set_roads(G, self.node_map) #dictionary of edges
def test_stats(): # create graph, add bearings, project it location_point = (37.791427, -122.410018) G = ox.graph_from_point(location_point, distance=500, distance_type='network') G = ox.add_edge_bearings(G) G_proj = ox.project_graph(G) # calculate stats stats1 = ox.basic_stats(G) stats2 = ox.basic_stats(G, area=1000) stats3 = ox.basic_stats(G_proj, area=1000, clean_intersects=True, tolerance=15, circuity_dist='euclidean') try: stats4 = ox.extended_stats(G, connectivity=True, anc=True, ecc=True, bc=True, cc=True) except NetworkXNotImplemented as e: warnings.warn( "Testing coordinates results in a MultiDigraph, and extended stats are not available for it" ) warnings.warn(e.args)
def test_plots(): G = ox.graph_from_point(location_point, dist=500, network_type="drive") # test getting colors co = ox.plot.get_colors(n=5, return_hex=True) nc = ox.plot.get_node_colors_by_attr(G, "x") ec = ox.plot.get_edge_colors_by_attr(G, "length", num_bins=5) # plot and save to disk filepath = Path(ox.settings.data_folder) / "test.svg" fig, ax = ox.plot_graph(G, show=False, save=True, close=True, filepath=filepath) fig, ax = ox.plot_graph( G, figsize=(5, 5), bgcolor="y", dpi=180, node_color="k", node_size=5, node_alpha=0.1, node_edgecolor="b", node_zorder=5, edge_color="r", edge_linewidth=2, edge_alpha=0.1, show=False, save=True, close=True, ) # figure-ground plots fig, ax = ox.plot_figure_ground(G=G) fig, ax = ox.plot_figure_ground(point=location_point, dist=500, network_type="drive") fig, ax = ox.plot_figure_ground(address=address, dist=500, network_type="bike")
def make_graph(lat, lng, distance): ''' Make initial graph of accident area from lat, lng, return graph, plot, and bounding box of area plotted ''' # get graph of accident area G = ox.graph_from_point((lat, lng), dist=distance, dist_type='bbox', network_type='drive', retain_all=True, simplify=False) #create fig my_dpi = 192 pixels = 400 fig = plt.figure(figsize=(pixels / my_dpi, pixels / my_dpi), dpi=my_dpi, constrained_layout=True) ax = fig.add_subplot() #add graph to plot ox.plot_graph(G, node_size=0, edge_color='black', ax=ax, show=False) bbox = get_bbox(ax) return fig, ax, G, bbox
def test_network_saving_loading(): # save graph as shapefile and geopackage G = ox.graph_from_place(place1, network_type="drive") ox.save_graph_shapefile(G) ox.save_graph_geopackage(G) # save/load graph as graphml file ox.save_graphml(G, gephi=True) ox.save_graphml(G, gephi=False) filepath = os.path.join(ox.settings.data_folder, "graph.graphml") G2 = ox.load_graphml(filepath) # verify everything in G is equivalent in G2 for (n1, d1), (n2, d2) in zip(G.nodes(data=True), G2.nodes(data=True)): assert n1 == n2 assert d1 == d2 for (u1, v1, k1, d1), (u2, v2, k2, d2) in zip(G.edges(keys=True, data=True), G2.edges(keys=True, data=True)): assert u1 == u2 assert v1 == v2 assert k1 == k2 assert tuple(d1.keys()) == tuple(d2.keys()) assert tuple(d1.values()) == tuple(d2.values()) for (k1, v1), (k2, v2) in zip(G.graph.items(), G2.graph.items()): assert k1 == k2 assert v1 == v2 assert tuple(G.graph["streets_per_node"].keys()) == tuple( G2.graph["streets_per_node"].keys()) assert tuple(G.graph["streets_per_node"].values()) == tuple( G2.graph["streets_per_node"].values()) # test custom data types nd = {"osmid": str} ed = {"length": str, "osmid": float} G2 = ox.load_graphml(filepath, node_dtypes=nd, edge_dtypes=ed) # test osm xml output default_all_oneway = ox.settings.all_oneway ox.settings.all_oneway = True G = ox.graph_from_point(location_point, dist=500, network_type="drive") ox.save_graph_xml(G, merge_edges=False) # test osm xml output merge edges ox.save_graph_xml(G, merge_edges=True, edge_tag_aggs=[("length", "sum")]) # test osm xml output from gdfs nodes, edges = ox.graph_to_gdfs(G) ox.save_graph_xml([nodes, edges]) # test ordered nodes from way df = pd.DataFrame({ "u": [54, 2, 5, 3, 10, 19, 20], "v": [76, 3, 8, 10, 5, 20, 15] }) ordered_nodes = ox.io._get_unique_nodes_ordered_from_way(df) assert ordered_nodes == [2, 3, 10, 5, 8] ox.settings.all_oneway = default_all_oneway
def download_graph(loc_list, **kwargs): simplify = kwargs.get("simplify",True) # get rid of non-important nodes? auto_bbox = kwargs.get("auto_bbox",True) # auto query polygon bbox show_plot = kwargs.get("show_plot",True) distance = kwargs.get("distance",20000) print("osmnx download_graph()...") if isinstance(loc_list,list) and isinstance(loc_list[0],float) and len(loc_list)>2: # [lats,latn,lngw,lnge] north=loc_list[1] south=loc_list[0] east=loc_list[3] west=loc_list[2] G=ox.graph_from_bbox(north,south,east,west,network_type='drive',simplify=simplify) elif isinstance(loc_list,list) and isinstance(loc_list[0],float) and len(loc_list)==2:# [lat,lng] G=ox.graph_from_point(loc_list, distance=distance,network_type='drive',simplify=simplify) elif isinstance(loc_list, str) or (isinstance(loc_list,list) and isinstance(loc_list[0], str)): if auto_bbox: # addr or [addr1,addr2,] use auto bbox G=ox.graph_from_place(loc_list,network_type='drive',simplify=simplify)# No-distance arg else: # addr or [addr1,addr2,] use distance G=ox.graph_from_address(loc_list,network_type='drive',distance=distance,simplify=simplify) else: print(__file__+" download_graph() input error: ",loc_list) return None if show_plot and iprint and Has_Display: if iprint>=2: print("download_graph showing downloaded graph...") fig, ax = ox.plot_graph(G) if not simplify: simplify_graph(G) if iprint>=2: print ox.basic_stats(G) return G
def get_distance_to_closest_road(self, lat, lon): ''' Returns the distance in metres from the nearest road - 1km radius i.e. closest road type, closest distance, ''' try: G = ox.graph_from_point((lat, lon), dist=1000, network_type='drive') gdf = ox.graph_to_gdfs(G, nodes=False, fill_edge_geometry=True) gdf.to_crs(epsg=3310, inplace=True) gdf = gdf.reset_index( ) ## to ensure the values of u & v are in the columns # convert point to utm in order to get distance in metres wgs84_pt = Point(lon, lat) wgs84 = pyproj.CRS('EPSG:4326') utm = pyproj.CRS('EPSG:3310') project = pyproj.Transformer.from_crs(wgs84, utm, always_xy=True).transform utm_point = transform(project, wgs84_pt) roads = gdf[['geometry', 'u', 'v', 'highway']].values.tolist() roads_with_distances = [(road, utm_point.distance(road[0])) for road in roads] roads_with_distances = sorted(roads_with_distances, key=lambda x: x[1]) closest_road = roads_with_distances[0] closest_distance = round(closest_road[1], 2) except Exception as ex: #closest_road_type = None closest_distance = None print(ex) return closest_distance
def get_distance_to_closest_trunk(self, lat, lon): ''' Returns the distance in metres from the nearest trunk road - 10km radius ''' try: G = ox.graph_from_point((lat, lon), dist=30000, network_type='drive') gdf = ox.graph_to_gdfs(G, nodes=False, fill_edge_geometry=True) gdf.to_crs(epsg=3310, inplace=True) new_gdf = gdf[gdf['highway'] == 'trunk'] if new_gdf.shape[0] == 0: closest_distance = None else: wgs84_pt = Point(lon, lat) wgs84 = pyproj.CRS('EPSG:4326') utm = pyproj.CRS('EPSG:3310') project = pyproj.Transformer.from_crs(wgs84, utm, always_xy=True).transform utm_point = transform(project, wgs84_pt) roads = new_gdf[['geometry', 'u', 'v']].values.tolist() roads_with_distances = [(road, utm_point.distance(road[0])) for road in roads] roads_with_distances = sorted(roads_with_distances, key=lambda x: x[1]) closest_road = roads_with_distances[0] closest_distance = round(closest_road[1], 2) except: closest_distance = None return closest_distance
def get_nearest_streetnames(location_tuple, distFromPoint=50): """This function retrieves the nearest streets of a coordinate tuple (lat, lon). Currently set to drive network. Edit the parameters in line 40 to fit your preferences.""" try: G = ox.graph_from_point(location_tuple, network_type='drive', distance=distFromPoint) G = ox.project_graph(G) ints = ox.clean_intersections(G) gdf = gpd.GeoDataFrame(ints, columns=['geometry'], crs=G.graph['crs']) X = gdf['geometry'].map(lambda pt: pt.coords[0][0]) Y = gdf['geometry'].map(lambda pt: pt.coords[0][1]) nodes = ox.get_nearest_nodes(G, X, Y, method='kdtree') streetnames = [] for n in nodes: for nbr in nx.neighbors(G, n): for d in G.get_edge_data(n, nbr).values(): if 'name' in d: if type(d['name']) == str: streetnames.append(d['name']) elif type(d['name']) == list: for name in d['name']: streetnames.append(name) streetnames = list(set(streetnames)) except: streetnames = [] return streetnames
def mshift(toy_map): # toy_map = Map(CENTER_LAT, CENTER_LONG, DISTANCE_FROM_CENTER) G = ox.graph_from_point(CENTER_POINT, DISTANCE_FROM_CENTER, network_type='drive') V = list(toy_map.node_map.values()) # for lcustering , need a table or dict with loc and weight import numpy as np from sklearn.cluster import MeanShift, estimate_bandwidth def V_cls(V): V_cls = [] for v in V: x = v.x y = v.y loc = (y, x) # Lat & Long V_cls.append(loc) return (V_cls) bandwidth = estimate_bandwidth(V_cls(V)) ms = MeanShift(bandwidth=bandwidth, bin_seeding=True) ms.fit()
def test_find_nearest(): # get graph and x/y coords to search G = ox.graph_from_point(location_point, dist=500, network_type="drive") Gp = ox.project_graph(G) points = ox.utils_geo.sample_points(ox.get_undirected(Gp), 5) X = points.x Y = points.y # get nearest node nn, d = ox.get_nearest_node(Gp, location_point, method="euclidean", return_dist=True) nn = ox.get_nearest_node(Gp, location_point, method="euclidean", return_dist=False) # get nearest nodes nn1, dist1 = ox.get_nearest_nodes(G, X, Y, return_dist=True) nn2, dist2 = ox.get_nearest_nodes(Gp, X, Y, method="kdtree", return_dist=True) nn3, dist3 = ox.get_nearest_nodes(G, X, Y, method="balltree", return_dist=True) nn4 = ox.get_nearest_nodes(G, X, Y) nn5 = ox.get_nearest_nodes(Gp, X, Y, method="kdtree") nn6 = ox.get_nearest_nodes(G, X, Y, method="balltree") # get nearest edge u, v, k, g, d = ox.get_nearest_edge(Gp, location_point, return_geom=True, return_dist=True) u, v, k, g = ox.get_nearest_edge(Gp, location_point, return_geom=True) u, v, k, d = ox.get_nearest_edge(Gp, location_point, return_dist=True) u, v, k = ox.get_nearest_edge(Gp, location_point) # get nearest edges ne0 = ox.distance.nearest_edges(Gp, X, Y, interpolate=50) ne1 = ox.get_nearest_edges(Gp, X, Y) ne2 = ox.get_nearest_edges(Gp, X, Y, method="kdtree") ne3 = ox.get_nearest_edges(G, X, Y, method="balltree", dist=0.0001)
def test_stats(): # create graph, add bearings, project it location_point = (37.791427, -122.410018) G = ox.graph_from_point(location_point, distance=500, distance_type='network') G = ox.add_edge_bearings(G) G_proj = ox.project_graph(G) # calculate stats stats1 = ox.basic_stats(G) stats2 = ox.basic_stats(G, area=1000) stats3 = ox.basic_stats(G_proj, area=1000, clean_intersects=True, tolerance=15, circuity_dist='euclidean') # calculate extended stats stats4 = ox.extended_stats(G, connectivity=True, anc=False, ecc=True, bc=True, cc=True)
def osm_graph_from_point(point, distance, network_type, simplify): """ Import an OSM graph of an area around the location point. The import is done with the distance_type parameter set to 'bbox'. :param point: (lon, lat) point :param distance: distance around point :param network_type: osm network type :param simplify: boolean indicating if the graph should be simplified :return: a networkx graph """ if point is None or distance is None: print( "The point and distance parameters must be specified when importing graph from point." ) exit(1) # reverse the point coordinates (osmnx takes (lat, lon) coordinates) point = (point[1], point[0]) return ox.graph_from_point(point, dist=distance, dist_type="bbox", network_type=network_type, simplify=simplify)
def create_graph(self, loc, dist, transport_mode = 'walk', loc_type = 'address'): G = None if loc_type == "address": G = ox.graph_from_address(loc, dist=dist, network_type=transport_mode) elif loc_type == "points": G = ox.graph_from_point(loc, dist=dist, network_type=transport_mode ) return G
def ox_shortest_path(midmap, origin, destination): """osmnx计算最短路径""" """midmap:地图中点经纬度wgs64 origin:起始点经纬度wgs64 destination:终点经纬度wgs64""" # city = ox.gdf_from_place('闵行区,Shanghai,China') # ox.plot_shape(ox.project_gdf(city)) # ox.plot_graph(ox.graph_from_place("闵行区,上海市,中国")) G = ox.graph_from_point(midmap, distance=700, network_type='drive_service', \ simplify=False) # 取消简化 即显示非相交的节点 为了获取弯道的多个节点 # ox.plot_graph(G) # 接著我們給定原點跟目的地的坐標,然後計算其node的編號 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) # ox.plot_graph_route(G, route) distance = nx.shortest_path_length(G, origin_node, destination_node) # print(route) # print(len(route)) # x = G.nodes[route[0]] # 确定节点属性 'y': 31.0249842, 'x': 121.4355697, 'osmid': 1439718495, 'highway': 'crossing'} # path = [origin] path = [] for i in range(len(route)): x = G.nodes[route[i]]['x'] y = G.nodes[route[i]]['y'] path.append((y, x)) # path.append(destination) # print(path) # print(len(path)) return path
def create_graph(loc, dist, transport_mode, loc_type="address"): """Transport mode = ‘walk’, ‘bike’, ‘drive’, ‘drive_service’, ‘all’, ‘all_private’, ‘none’""" if loc_type == "address": G = ox.graph_from_address(loc, dist=dist, network_type=transport_mode) elif loc_type == "points": G = ox.graph_from_point(loc, dist=dist, network_type=transport_mode ) return G
def test_stats(): location_point = (37.791427, -122.410018) G = ox.graph_from_point(location_point, distance=500, distance_type='network') stats1 = ox.basic_stats(G) stats1 = ox.basic_stats(G, area=1000) stats2 = ox.extended_stats(G, connectivity=True, anc=True, ecc=True, bc=True, cc=True)
def test_network_saving_loading(): # save graph as shapefile and geopackage G = ox.graph_from_place(place1, network_type="drive") ox.save_graph_shapefile(G) ox.save_graph_geopackage(G) # save/load graph as graphml file ox.save_graphml(G, gephi=True) ox.save_graphml(G, gephi=False) filepath = os.path.join(ox.settings.data_folder, "graph.graphml") G = ox.load_graphml(filepath, node_type=str) # test osm xml output default_all_oneway = ox.settings.all_oneway ox.settings.all_oneway = True G = ox.graph_from_point(location_point, dist=500, network_type="drive") ox.save_graph_xml(G, merge_edges=False) # test osm xml output merge edges ox.save_graph_xml(G, merge_edges=True, edge_tag_aggs=[("length", "sum")]) # test osm xml output from gdfs nodes, edges = ox.graph_to_gdfs(G) ox.save_graph_xml([nodes, edges]) # test ordered nodes from way df = pd.DataFrame({ "u": [54, 2, 5, 3, 10, 19, 20], "v": [76, 3, 8, 10, 5, 20, 15] }) ordered_nodes = ox.io._get_unique_nodes_ordered_from_way(df) assert ordered_nodes == [2, 3, 10, 5, 8] ox.settings.all_oneway = default_all_oneway
def loadOSMnxMap(file=None, download=False, saveMap=False): point1 = (45.1904, 5.7607) #todo load point from given gpx distance = 1000 distance_type_var = 'network' network_type_var = 'walk' print("============== Loading map ==================") if (not file and not download): print('No map specified') elif (file): graph = osmnx.load_graphml(filename=file, folder=None) print("Map loaded") g, a = osmnx.plot_graph(graph, show=False, close=False) return g, a elif (download): graph = osmnx.graph_from_point(point1, distance, distance_type=distance_type_var, network_type=network_type_var) if (saveMap): osmnx.save_graphml(graph, filename='map.hraphml') print('Map saved') print("Map loaded") return osmnx.plot_graph(graph, show=False, close=False) return None, None
def test_find_nearest(): # get graph G = ox.graph_from_point(location_point, dist=500, network_type="drive") # convert graph to node/edge GeoDataFrames and back again gdf_nodes, gdf_edges = ox.graph_to_gdfs( G, nodes=True, edges=True, node_geometry=True, fill_edge_geometry=True ) assert len(gdf_nodes) == len(G) assert len(gdf_edges) == len(G.edges(keys=True)) G = ox.graph_from_gdfs(gdf_nodes, gdf_edges) assert len(gdf_nodes) == len(G) assert len(gdf_edges) == len(G.edges(keys=True)) # get nearest node nn, d = ox.get_nearest_node(G, location_point, method="euclidean", return_dist=True) # get nearest nodes: haversine, kdtree, balltree X = gdf_nodes["x"].head() Y = gdf_nodes["y"].head() nn1 = ox.get_nearest_nodes(G, X, Y) nn2 = ox.get_nearest_nodes(G, X, Y, method="kdtree") nn3 = ox.get_nearest_nodes(G, X, Y, method="balltree") # get nearest edge u, v, k, g, d = ox.get_nearest_edge(G, location_point, return_geom=True, return_dist=True) # get nearest edges: haversine, kdtree, balltree ne1 = ox.get_nearest_edges(G, X, Y) ne2 = ox.get_nearest_edges(G, X, Y, method="kdtree") ne3 = ox.get_nearest_edges(G, X, Y, method="balltree", dist=0.0001)
def cost_matrix(self, num_points): """ Creates a cost matrix for the model to later minimize (cost function must be defined first). For now just return the distance between the points. FUTURE : Use Google API (optimized performance, but costs). For now using osmnx algorithm for calculating shortest paths from a graph (dijkstra algorithm) Params -------------- num_points : int (how much data you want) Returns ------------ """ latitude, longitude, demand = self.generate_demand(num_points) lat_lon = tuple(zip(latitude, longitude)) g = ox.graph_from_point((-12.0432, -77.0141), distance=500) matrix = np.zeros((num_points, num_points)) for row in range(num_points): temp1 = ox.get_nearest_node(g, lat_lon[row]) for column in range(num_points): temp2 = ox.get_nearest_node(g, lat_lon[column]) distance = nx.shortest_path_length(g, source=temp1, target=temp2) matrix[row, column] = distance return matrix, lat_lon, demand
def get_shortest_path(self, start_location, end_location): """ Returns the route(list of nodes) that minimiz the number of edges between the start and end location. Params: start_location: tuple (lat,long) end_location: tuple (lat,long) Returns: lat_longs: List of [lon,lat] in the route """ if not self.init: # bbox=self.get_bounding_box(start_location,end_location) # self.G = ox.graph_from_bbox(bbox[0],bbox[1],bbox[2],bbox[3],network_type='walk', simplify=False) self.G = ox.graph_from_point(start_location, distance=10000, simplify=False, network_type='walk') p.dump(self.G, open("graph.p", "wb")) self.init = True print("Saved Graph") G = self.G start_node = ox.get_nearest_node(G, point=start_location) end_node = ox.get_nearest_node(G, point=end_location) route = nx.shortest_path(G, start_node, end_node) lat_longs = [[G.node[route_node]['x'], G.node[route_node]['y']] for route_node in route] return lat_longs
def test_find_nearest(): # get graph G = ox.graph_from_point(location_point, dist=500, network_type="drive") # get nearest node nn, d = ox.get_nearest_node(G, location_point, method="euclidean", return_dist=True) # get nearest nodes: haversine, kdtree, balltree gdf_nodes = ox.graph_to_gdfs(G, edges=False) X = gdf_nodes["x"].head() Y = gdf_nodes["y"].head() nn1, dist1 = ox.get_nearest_nodes(G, X, Y, return_dist=True) nn2, dist2 = ox.get_nearest_nodes(G, X, Y, method="kdtree", return_dist=True) nn3, dist3 = ox.get_nearest_nodes(G, X, Y, method="balltree", return_dist=True) nn4 = ox.get_nearest_nodes(G, X, Y) nn5 = ox.get_nearest_nodes(G, X, Y, method="kdtree") nn6 = ox.get_nearest_nodes(G, X, Y, method="balltree") # get nearest edge u, v, k, g, d = ox.get_nearest_edge(G, location_point, return_geom=True, return_dist=True) # get nearest edges: haversine, kdtree, balltree ne1 = ox.get_nearest_edges(G, X, Y) ne2 = ox.get_nearest_edges(G, X, Y, method="kdtree") ne3 = ox.get_nearest_edges(G, X, Y, method="balltree", dist=0.0001)
def __init__(self, score_func="aging"): self.node_values = [] self.frame = 0 self.data = [] self.G = ox.graph_from_point((12.985660, 77.645015), distance=2000, network_type='drive') metro = self.G.node.get(1563273556) offices = [ self.G.node.get(6536735148), self.G.node.get(6536735146), self.G.node.get(1132680459), self.G.node.get(1132675346), self.G.node.get(1339408165), self.G.node.get(1328155440), self.G.node.get(1500759513), self.G.node.get(1485686869), self.G.node.get(3885545484), self.G.node.get(1808901710), ] self.fixed_points = list(offices) self.fixed_points.append(metro) self.plot_trucks = None self.plot_scooters = None # get north, south, east, west values either from bbox parameter or from the # spatial extent of the edges' geometries self.edges = ox.graph_to_gdfs(self.G, nodes=False, fill_edge_geometry=True) west, south, east, north = self.edges.total_bounds # if caller did not pass in a fig_width, calculate it proportionately from # the fig_height and bounding box aspect ratio bbox_aspect_ratio = (north - south) / (east - west) fig_height = 12 # in inches fig_width = fig_height / bbox_aspect_ratio # create simulation object self.scooters = SimulateScooters(self.G, offices, metro) self.trucks = SimulateTrucks(self.G, offices, metro) if score_func == "aging": self.score_func = self.trucks.best_aging_score elif score_func == "greedy": self.score_func = self.trucks.best_greedy_score else: self.score_func = self.trucks.best_combined_score # create the figure and axis self.fig, self.ax = plt.subplots(figsize=(fig_width, fig_height), facecolor='w') # initialize animation function with setup plot, attach update plot function for each frame self.ani = animation.FuncAnimation(self.fig, self.update_plot, frames=BounceSimulation.FRAMES, init_func=self.setup_plot, blit=False)
def _fetch_from_remote(self, type_, cache_path): if type_ == 'graph': graph = ox.graph_from_point(self._center, self._distance, network_type=self._type) self._store_graph_cache(graph, cache_path) return graph elif type_ == 'footprint': gdf = ox.footprints_from_point(self._center, self._distance) self._store_footprint_cache(gdf, cache_path) return gdf
def test_get_network_methods(): import geopandas as gpd north, south, east, west = 37.79, 37.78, -122.41, -122.43 G1 = ox.graph_from_bbox(north, south, east, west, network_type='drive_service') G1 = ox.graph_from_bbox(north, south, east, west, network_type='drive_service', truncate_by_edge=True) location_point = (37.791427, -122.410018) bbox = ox.bbox_from_point(location_point, project_utm=True) G2 = ox.graph_from_point(location_point, distance=750, distance_type='bbox', network_type='drive') G3 = ox.graph_from_point(location_point, distance=500, distance_type='network') G4 = ox.graph_from_address(address='350 5th Ave, New York, NY', distance=1000, distance_type='network', network_type='bike') places = [ 'Los Altos, California, USA', { 'city': 'Los Altos Hills', 'state': 'California' }, 'Loyola, California' ] G5 = ox.graph_from_place(places, network_type='all', clean_periphery=False) calif = gpd.read_file('examples/input_data/ZillowNeighborhoods-CA') mission_district = calif[(calif['CITY'] == 'San Francisco') & (calif['NAME'] == 'Mission')] polygon = mission_district['geometry'].iloc[0] G6 = ox.graph_from_polygon(polygon, network_type='walk')
def test_stats(): # create graph, add bearings, project it location_point = (37.791427, -122.410018) G = ox.graph_from_point(location_point, distance=500, distance_type='network') G = ox.add_edge_bearings(G) G_proj = ox.project_graph(G) # calculate stats stats1 = ox.basic_stats(G) stats2 = ox.basic_stats(G, area=1000) stats3 = ox.basic_stats(G_proj, area=1000, clean_intersects=True, tolerance=15, circuity_dist='euclidean') stats4 = ox.extended_stats(G, connectivity=True, anc=True, ecc=True, bc=True, cc=True)