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 save_graph(target, graph_name, distance=1000, is_address=True): # Load graph from OSM if is_address: graph = ox.graph_from_address(address=target, distance=distance, network_type='drive') else: graph = ox.graph_from_place(query=target, network_type='drive') # Project graph graph_proj = ox.project_graph(graph) folder_path = path.join('graphs', graph_name) if not path.exists(folder_path): mkdir(folder_path) graph_data = graph_proj.graph serialize_dict(dictionary=graph_data, file_path=path.join(folder_path, 'graph_data.pkl.gz')) # We make the graph strongly connected to ensure that any combination of source / sink # constitutes a valid problem graph_component = ox.get_largest_component(graph_proj, strongly=True).to_directed() # Save pictures of the graph plot_road_graph(graph_component, graph_name=graph_name, file_path=path.join(folder_path, 'graph')) # Save graph ox.save_graphml(graph_component, filename='graph.graphml', folder=folder_path, gephi=True) # Save a selection of graph-wide stats. stats_file = path.join(folder_path, 'stats.csv') delete_if_exists(stats_file) n_nodes = graph_component.number_of_nodes() n_edges = graph_component.number_of_edges() avg_in_deg = np.average([d for _, d in graph_component.in_degree()]) avg_out_deg = np.average([d for _, d in graph_component.out_degree()]) diam = nx.diameter(graph_component) append_row_to_log(['Number of Nodes', n_nodes], stats_file) append_row_to_log(['Number of Edges', n_edges], stats_file) append_row_to_log(['Average In Degree', avg_in_deg], stats_file) append_row_to_log(['Average Out Degree', avg_out_deg], stats_file) append_row_to_log(['Diameter', diam], stats_file) cleaned_target = target.replace('\"', '').replace('\'', '').replace(',', '') query = '{0}; Dist: {1}'.format(cleaned_target, distance) if is_address else cleaned_target append_row_to_log(['Query', query], stats_file) return graph_component
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') graph_map = ox.plot_graph_folium(G, popup_attribute='name') route_map = ox.plot_route_folium(G, route)
def test_routing_folium(): import networkx as nx with httmock.HTTMock( get_mock_response_content('overpass-response-3.json.gz')): 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) 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') graph_map = ox.plot_graph_folium(G, popup_attribute='name') route_map = ox.plot_route_folium(G, route)
def create_intersections_db_by_zip(data): """This function creates a database of the coordinates and streets of all intersections in a mile radius of a given zipcode. Currently set to drive network and a radius of 1610m (1 mile). Edit the parameters in line 81 to fit your preferences""" d = data[1] zipcode = d[1] city = d[2] state = d[3] county = d[4] tablename = "intersections_" + str(zipcode) try: cur.execute( "CREATE TABLE " + tablename + " (zip_code TEXT, city TEXT, state TEXT, county TEXT, latlon_str TEXT);" ) latlon_array = [] streetname_array = [] latlon_array_str = "" streetname_array_str = "" try: G = ox.graph_from_address(zipcode, network_type='drive', distance=1610) G_proj = ox.project_graph(G) # clean up the intersections and extract their xy coords intersections = ox.clean_intersections(G_proj, tolerance=15, dead_ends=False) points = np.array([point.xy for point in intersections]) gdf = gpd.GeoDataFrame(geometry=intersections) gdf.crs = G_proj.graph['crs'] lonlat = ox.project_gdf(gdf, to_latlong=True) a = lonlat['geometry'].tolist() for coord in a: lon = coord.x lat = coord.y latlon_tuple = (lat, lon) # nearest_streets = get_nearest_streetnames(latlon_tuple) # streetname_array.append(nearest_streets) latlon_array.append(latlon_tuple) except: #THROW A WARNING THAT THERE IS NO LAT/LON DATA FOR THIS ZIPCODE pass latlon_array_str = str(latlon_array).strip('[]') # streetname_array_str = str(streetname_array).strip('[]') to_db = [zipcode, city, state, county, latlon_array_str] cmd = "INSERT INTO " + tablename + " (zip_code, city, state, county,latlon_str) VALUES (?, ?, ?, ?, ?);" cur.execute(cmd, to_db) for row in cur.execute("SELECT * from " + tablename): print(row) except: print(tablename + " already exists")
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 test_routing_folium(): import networkx as nx G = ox.graph_from_address('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) route = nx.shortest_path(G, origin_node, destination_node) 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') graph_map = ox.plot_graph_folium(G, popup_attribute='name') route_map = ox.plot_route_folium(G, route)
def create_graph(loc, dist, transport_mode="walk", loc_type="address"): 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 load_map(name): if os.path.exists(name): G = pickle.load(open(name, 'rb')) else: G = ox.graph_from_address('Inner Harbor Baltimore, Maryland, USA', network_type='drive') pickle.dump(G, open(name, 'wb')) return G
def graph(place_country, distance): # filter # filter out some attributes # filter = ('["highway"!~"residential|unclassified|living_street|track|abandoned|path|footway|service|pedestrian|road|' # 'raceway|cycleway|steps|construction"]') # filter = ( # '["highway"!~"residential|unclassified|living_street|track|abandoned|path|footway|service|pedestrian|road|' # 'raceway|cycleway|steps|construction|primary|secondary|tertiary"]') # filter = ( # '["highway"!~"living_street|abandoned|footway|pedestrian|raceway|cycleway|steps|construction|' # 'bus_guideway|bridleway|corridor|escape|rest_area|track|sidewalk|proposed|path"]') # filter = ( # '["highway"!~"living_street|abandoned|steps|construction|' # 'bus_guideway|bridleway|corridor|escape|rest_area|track|sidewalk|proposed|path"]') filter = ( '["highway"!~"living_street|abandoned|steps|construction|service|pedestrian|' 'bus_guideway|bridleway|corridor|escape|rest_area|track|sidewalk|proposed|path|footway"]' ) # filter = filter # import grapho (graphml) G = ox.graph_from_address(str(place_country), distance=distance, network_type='drive', custom_filter=filter) # import shapefile # G_shp = ox.gdf_from_place(place_country) # import shapefile with edges and nodes # as the data is in WGS84 format, we might first want to reproject our data into metric system # so that our map looks better with the projection of the graph data in UTM format # G_projected = ox.project_graph(G) # save street network as ESRI shapefile (includes NODES and EDGES) name_place_country = re.sub('[/," ",:]', '_', place_country) # ox.save_graph_shapefile(G_projected, filename='network_' + name_place_country + '-shape') ox.save_graphml(G, filename=name_place_country + '.graphml')
def _get_cycleways(self): """ Creates all cycleways in a city (networkx.MultiDiGraph). """ useful_tags = ox.settings.useful_tags_way + ['cycleway'] ox.config(use_cache=True, log_console=True, useful_tags_way=useful_tags) if self.query_type == 'city': if self.city_limits is True: cycleways = ox.graph_from_place(query=self.city_name, network_type='bike', simplify=False) else: cycleways = ox.graph_from_bbox(self.north, self.south, self.east, self.west, network_type='bike', simplify=False) elif self.query_type == 'address': cycleways = ox.graph_from_address(self.address, network_type='bike', dist=self.distance) non_cycleways = [ (u, v, k) for u, v, k, d in cycleways.edges(keys=True, data=True) if not ('cycleway' in d or d['highway'] == 'cycleway') ] cycleways.remove_edges_from(non_cycleways) cycleways = ox.utils_graph.remove_isolated_nodes(cycleways) return cycleways
def test_get_network_methods(): import geopandas as gpd north, south, east, west = 37.79, 37.78, -122.41, -122.43 with httmock.HTTMock(get_mock_response_content('overpass-response-6.json.gz')): G1 = ox.graph_from_bbox(north, south, east, west, network_type='drive_service') with httmock.HTTMock(get_mock_response_content()): 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) with httmock.HTTMock(get_mock_response_content('overpass-response-8.json.gz')): G2 = ox.graph_from_point(location_point, distance=750, distance_type='bbox', network_type='drive') with httmock.HTTMock(get_mock_response_content('overpass-response-9.json.gz')): G3 = ox.graph_from_point(location_point, distance=500, distance_type='network') with httmock.HTTMock(get_mock_response_content('overpass-response-10.json.gz')): 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'] with httmock.HTTMock(get_mock_response_content('overpass-response-11.json.gz')): G5 = ox.graph_from_place(places, network_type='all', clean_periphery=False) calif = gpd.read_file('tests/input_data/ZillowNeighborhoods-CA') mission_district = calif[(calif['CITY']=='San Francisco') & (calif['NAME']=='Mission')] polygon = mission_district['geometry'].iloc[0] with httmock.HTTMock(get_mock_response_content('overpass-response-12.json.gz')): G6 = ox.graph_from_polygon(polygon, network_type='walk')
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 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 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 get_map(self, name): file_path = os.path.dirname(os.path.abspath(__file__)) file_path = file_path[:len(file_path) - 7] + 'maps/' try: with open(file_path + name + '.p', 'rb') as f: self._graph = pickle.load(f) except: try: self._graph = ox.graph_from_place(name, network_type='drive') except: self._graph = ox.graph_from_address(name, distance=250, network_type='drive') with open(file_path + name + '.p', 'wb') as f: pickle.dump(self._graph, f) self._graph_proj = ox.project_graph(self._graph) self._nodes, self._edges = ox.graph_to_gdfs(self._graph_proj, nodes=True, edges=True)
def render_graph(self): Graph = ox.graph_from_address(self.address, network_type='walk', distance=self.run_distance / 2) Graph = ox.add_node_elevations(Graph, api_key=self.api_key) Graph = ox.add_edge_grades(Graph) return Graph
def _get_city_data_from_address(self): if self.city_dict['cycleways'] is True: self.cycleways = self._get_cycleways() if self.city_dict['roads'] is True: self.roads = ox.graph_from_address(self.address, network_type='drive', dist=self.distance) if self.city_dict['water'] is True: self.water = ox.geometries_from_address(self.address, tags=self.water_tags, dist=self.distance) if self.city_dict['green'] is True: self.green = ox.geometries_from_address(self.address, tags=self.green_tags, dist=self.distance) if self.city_dict['buildings'] is True: self.buildings = ox.geometries_from_address(self.address, tags={ "building": True, 'landuse': 'construction' }, dist=self.distance) if self.city_dict['railways'] is True: self.railways = ox.geometries_from_address(self.address, tags=self.railway_tags, dist=self.distance)
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 get_graph(self): self.map = ox.graph_from_address(central_address, distance=3000, network_type='bike') # Intialize all frequencies to 0 for e in self.map.edges: self.map.edges[e]['count'] = 0 for n in self.map.nodes: self.map.nodes[n]['count'] = 0
def test_get_network_methods(): # graph from bounding box _ = ox.utils_geo.bbox_from_point(location_point, project_utm=True, return_crs=True) north, south, east, west = ox.utils_geo.bbox_from_point(location_point, dist=500) G = ox.graph_from_bbox(north, south, east, west, network_type="drive") G = ox.graph_from_bbox(north, south, east, west, network_type="drive_service", truncate_by_edge=True) # truncate graph by bounding box north, south, east, west = ox.utils_geo.bbox_from_point(location_point, dist=400) G = ox.truncate.truncate_graph_bbox(G, north, south, east, west) # graph from address G = ox.graph_from_address(address=address, dist=500, dist_type="bbox", network_type="bike") # graph from list of places G = ox.graph_from_place([place1], network_type="drive", clean_periphery=False) # graph from polygon G = ox.graph_from_polygon(polygon, network_type="walk", truncate_by_edge=True) # test custom query filter cf = ( '["highway"]' '["area"!~"yes"]' '["highway"!~"motor|proposed|construction|abandoned|platform|raceway"]' '["foot"!~"no"]' '["service"!~"private"]' '["access"!~"private"]') G = ox.graph_from_point(location_point, dist=500, custom_filter=cf, dist_type="bbox", network_type="all") G = ox.graph_from_point( location_point, dist=500, dist_type="network", network_type="all_private", )
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 plot1(location, number): place = location k = number G = ox.graph_from_address(place, network_type='drive') ox.plot_graph(G, save=True, file_format='png', filename='temp2', show=False) im = Image.open('images/temp2.png') im.save('snow/static/snow/images/temp1.png', 'png')
def network_from_location(location=None, is_place=False, **kwargs): """ Load road-network-data from OpenStreetMap (OSM) via OSMnx. The network structure will be simplified by default, see: https://github.com/gboeing/osmnx-examples/blob/master/notebooks/04-simplify-graph-consolidate-nodes.ipynb """ if not location: location = "TU Berlin, Berlin, Deutschland" if is_place: return ox.graph_from_place(location, **kwargs) return ox.graph_from_address(location, **kwargs)
def process_file(data, plot_file_type, short_distance_edge_color, long_distance_edge_color, size): if size == 'S': plot_figure_height = 5 plot_figure_width = 5 plot_edge_line_width = 1.25 font_size = 64 distance_from_top = 12.5 elif size == 'M': plot_figure_height = 10 plot_figure_width = 10 plot_edge_line_width = 2.5 font_size = 128 distance_from_top = 25 else: plot_figure_height = 40 plot_figure_width = 40 plot_edge_line_width = 10 font_size = 512 distance_from_top = 100 for city in data: g = ox.graph_from_address(city.city, distance=ADDRESS_DISTANCE, distance_type=ADDRESS_DISTANCE_TYPE, network_type=ADDRESS_NETWORK_TYPE, simplify=True, name=city.city) ec = [ long_distance_edge_color if data['length'] >= 100 else short_distance_edge_color for u, v, key, data in g.edges(keys=True, data=True) ] ox.plot_graph(g, bgcolor=PLOT_BACKGROUND_COLOR, node_size=PLOT_NODE_SIZE, fig_height=plot_figure_height, fig_width=plot_figure_width, file_format=plot_file_type, dpi=PLOT_DPI, filename=city.city, save=True, edge_color=ec, edge_linewidth=plot_edge_line_width, show=False) img = get_image_file_name(city.city, plot_file_type) save_images_with_name(city.city, img, FILL, plot_file_type, font_size, distance_from_top, size)
def __init__(self, place, scale=1.0, transit=None, distance=10000, buffer=2000, type='drive'): self.vehicle_size = scale self.place = place self.transit = transit self.id = place.lower().replace(' ', '_') self.place_meta = lookup_place(place) xmin, xmax, ymin, ymax = [ float(p) for p in self.place_meta['boundingbox'] ] # lat lon self.bbox = (xmin, ymin, xmax, ymax) self.fname = '{}_{}_{}_{}'.format(self.id, type, distance, buffer) if os.path.exists(os.path.join(ox.settings.data_folder, self.fname)): logger.info('Loading existing network') G = ox.load_graphml(self.fname) else: # the first search result isn't always what we want # so keep trying until we find something that clicks # see: <https://github.com/gboeing/osmnx/issues/16> # a more likely problem is that a place is returned as a point # rather than a shape, so we fall back to `graph_from_address` try: logger.info('Downloading network') G = ox.graph_from_place(place, network_type=type, simplify=True, buffer_dist=buffer, truncate_by_edge=True) except ValueError: print('Shape was not found for "{}"'.format(place)) print('Falling back to address search at distance={}'.format( distance)) G = ox.graph_from_address(place, network_type=type, simplify=True, distance=distance + buffer, truncate_by_edge=True) G = ox.project_graph(G) ox.save_graphml(G, filename=self.fname) crs = G.graph['crs'] self.utm_proj = pyproj.Proj(crs, preserve_units=True) self.network = G self._prepare_network() self.router = Router(self)
def generate_graph_from_address(address: str, distance: int): """Prüft, ob bereits ein Graph zu der angegebenen Adresse existiert und holt diesen oder erstellt diesen je nachdem. Die distance bestimmt die Größe des Ergebnisgraphen. """ key = address + str(distance) + '-add' if graphs.get(key, "-1") != "-1": print("**** graph fetched ****") return graphs[key] else: G = ox.graph_from_address(address=address, distance=distance) graphs[key] = G print("**** graph created ****") return G
def graph_from_address_wrapper(address, distance=1000, distance_type='bbox', network_type='drive', fig_height=5, node_size=0, color='#999999'): g = ox.graph_from_address(address=address, distance=distance, distance_type=distance_type, network_type=network_type) project_and_plot(g, fig_height, node_size)
def test_get_network_methods(): # graph from bounding box north, south, east, west = ox.utils_geo.bbox_from_point(location_point, dist=500) G = ox.graph_from_bbox(north, south, east, west, network_type="drive") G = ox.graph_from_bbox(north, south, east, west, network_type="drive_service", truncate_by_edge=True) # graph from address G = ox.graph_from_address(address=address, dist=500, dist_type="bbox", network_type="bike") # graph from list of places G = ox.graph_from_place([place1], network_type="drive", clean_periphery=False) # graph from polygon G = ox.graph_from_polygon(polygon, network_type="walk", truncate_by_edge=True) # test custom query filter cf = ( '["area"!~"yes"]' '["highway"!~"motor|proposed|construction|abandoned|platform|raceway"]' '["foot"!~"no"]' '["service"!~"private"]' '["access"!~"private"]') G = ox.graph_from_point(location_point, dist=500, custom_filter=cf, dist_type="bbox", network_type="all") # test custom settings cs = '[out:json][timeout:180][date:"2019-10-28T19:20:00Z"]' G = ox.graph_from_point( location_point, dist=500, custom_settings=cs, dist_type="network", network_type="all_private", )
def test_elevation(): G = ox.graph_from_address(address=address, dist=500, dist_type="bbox", network_type="bike") rasters = list(Path("tests/input_data").glob("elevation*.tif")) # add node elevations from a single raster file (some nodes will be null) G = ox.elevation.add_node_elevations_raster(G, rasters[0], cpus=1) # add node elevations from multiple raster files G = ox.elevation.add_node_elevations_raster(G, rasters) assert pd.notnull(pd.Series(dict(G.nodes(data="elevation")))).all() # add edge grades and their absolute values G = ox.add_edge_grades(G, add_absolute=True)
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)