INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Round the coordinates of a shapely LineString to some decimal precision.
def round_linestring_coords(ls, precision): """ Round the coordinates of a shapely LineString to some decimal precision. Parameters ---------- ls : shapely LineString the LineString to round the coordinates of precision : int decimal precision to round coordinates to Return...
Round the coordinates of a shapely geometry to some decimal precision.
def round_shape_coords(shape, precision): """ Round the coordinates of a shapely geometry to some decimal precision. Parameters ---------- shape : shapely geometry, one of Point, MultiPoint, LineString, MultiLineString, Polygon, or MultiPolygon the geometry to round the coordina...
Read OSM XML from input filename and return Overpass - like JSON.
def overpass_json_from_file(filename): """ Read OSM XML from input filename and return Overpass-like JSON. Parameters ---------- filename : string name of file containing OSM XML data Returns ------- OSMContentHandler object """ _, ext = os.path.splitext(filename) ...
Convenience function to parse bbox - > poly
def bbox_to_poly(north, south, east, west): """ Convenience function to parse bbox -> poly """ return Polygon([(west, south), (east, south), (east, north), (west, north)])
Parse the Overpass QL query based on the list of amenities.
def parse_poi_query(north, south, east, west, amenities=None, timeout=180, maxsize=''): """ Parse the Overpass QL query based on the list of amenities. Parameters ---------- north : float Northernmost coordinate from bounding box of the search area. south : float Southernmo...
Get points of interests ( POIs ) from OpenStreetMap based on selected amenity types.
def osm_poi_download(polygon=None, amenities=None, north=None, south=None, east=None, west=None, timeout=180, max_query_area_size=50*1000*50*1000): """ Get points of interests (POIs) from OpenStreetMap based on selected amenity types. Parameters ---------- poly : shapely.geomet...
Parse node coordinates from OSM response. Some nodes are standalone points of interest others are vertices in polygonal ( areal ) POIs. Parameters ---------- osm_response: string OSM response JSON string Returns ------- coords: dict dict of node IDs and their lat lon coordinates
def parse_nodes_coords(osm_response): """ Parse node coordinates from OSM response. Some nodes are standalone points of interest, others are vertices in polygonal (areal) POIs. Parameters ---------- osm_response : string OSM response JSON string Returns ------- ...
Parse areal POI way polygons from OSM node coords.
def parse_polygonal_poi(coords, response): """ Parse areal POI way polygons from OSM node coords. Parameters ---------- coords : dict dict of node IDs and their lat, lon coordinates Returns ------- dict of POIs containing each's nodes, polygon geometry, and osmid """ i...
Parse points from OSM nodes.
def parse_osm_node(response): """ Parse points from OSM nodes. Parameters ---------- response : JSON Nodes from OSM response. Returns ------- Dict of vertex IDs and their lat, lon coordinates. """ try: point = Point(response['lon'], response['lat']) ...
Handles invalid multipolygon geometries when there exists e. g. a feature without geometry ( geometry == NaN )
def invalid_multipoly_handler(gdf, relation, way_ids): """ Handles invalid multipolygon geometries when there exists e.g. a feature without geometry (geometry == NaN) Parameters ---------- gdf : gpd.GeoDataFrame GeoDataFrame with Polygon geometries that should be converted into a Mult...
Parses the osm relations ( multipolygons ) from osm ways and nodes. See more information about relations from OSM documentation: http:// wiki. openstreetmap. org/ wiki/ Relation Parameters ---------- relations: list OSM relation items ( dictionaries ) in a list. osm_way_df: gpd. GeoDataFrame OSM way features as a GeoDa...
def parse_osm_relations(relations, osm_way_df): """ Parses the osm relations (multipolygons) from osm ways and nodes. See more information about relations from OSM documentation: http://wiki.openstreetmap.org/wiki/Relation Parameters ---------- relations : list OSM 'rela...
Parse GeoDataFrames from POI json that was returned by Overpass API.
def create_poi_gdf(polygon=None, amenities=None, north=None, south=None, east=None, west=None): """ Parse GeoDataFrames from POI json that was returned by Overpass API. Parameters ---------- polygon : shapely Polygon or MultiPolygon geographic shape to fetch the POIs within amenities: l...
Get point of interests ( POIs ) within some distance north south east and west of a lat - long point.
def pois_from_point(point, distance=None, amenities=None): """ Get point of interests (POIs) within some distance north, south, east, and west of a lat-long point. Parameters ---------- point : tuple a lat-long point distance : numeric distance in meters amenities : list...
Get OSM points of Interests within some distance north south east and west of an address.
def pois_from_address(address, distance, amenities=None): """ Get OSM points of Interests within some distance north, south, east, and west of an address. Parameters ---------- address : string the address to geocode to a lat-long point distance : numeric distance in meters ...
Get points of interest ( POIs ) within the boundaries of some place.
def pois_from_place(place, amenities=None): """ Get points of interest (POIs) within the boundaries of some place. Parameters ---------- place : string the query to geocode to get geojson boundary polygon. amenities : list List of amenities that will be used for finding the POIs...
Return True if the node is a real endpoint of an edge in the network \ otherwise False. OSM data includes lots of nodes that exist only as points \ to help streets bend around curves. An end point is a node that either: \ 1 ) is its own neighbor ie it self - loops. \ 2 ) or has no incoming edges or no outgoing edges ie...
def is_endpoint(G, node, strict=True): """ Return True if the node is a "real" endpoint of an edge in the network, \ otherwise False. OSM data includes lots of nodes that exist only as points \ to help streets bend around curves. An end point is a node that either: \ 1) is its own neighbor, ie, it s...
Recursively build a path of nodes until you hit an endpoint node.
def build_path(G, node, endpoints, path): """ Recursively build a path of nodes until you hit an endpoint node. Parameters ---------- G : networkx multidigraph node : int the current node to start from endpoints : set the set of all nodes in the graph that are endpoints ...
Create a list of all the paths to be simplified between endpoint nodes.
def get_paths_to_simplify(G, strict=True): """ Create a list of all the paths to be simplified between endpoint nodes. The path is ordered from the first endpoint, through the interstitial nodes, to the second endpoint. If your street network is in a rural area with many interstitial nodes between ...
Simplify a graph s topology by removing all nodes that are not intersections or dead - ends.
def simplify_graph(G, strict=True): """ Simplify a graph's topology by removing all nodes that are not intersections or dead-ends. Create an edge directly between the end points that encapsulate them, but retain the geometry of the original edges, saved as attribute in new edge. Parameters...
Clean - up intersections comprising clusters of nodes by merging them and returning their centroids.
def clean_intersections(G, tolerance=15, dead_ends=False): """ Clean-up intersections comprising clusters of nodes by merging them and returning their centroids. Divided roads are represented by separate centerline edges. The intersection of two divided roads thus creates 4 nodes, representing wher...
Project a shapely Polygon or MultiPolygon from lat - long to UTM or vice - versa
def project_geometry(geometry, crs=None, to_crs=None, to_latlong=False): """ Project a shapely Polygon or MultiPolygon from lat-long to UTM, or vice-versa Parameters ---------- geometry : shapely Polygon or MultiPolygon the geometry to project crs : dict the starting coordin...
Project a GeoDataFrame to the UTM zone appropriate for its geometries centroid.
def project_gdf(gdf, to_crs=None, to_latlong=False): """ Project a GeoDataFrame to the UTM zone appropriate for its geometries' centroid. The simple calculation in this function works well for most latitudes, but won't work for some far northern locations like Svalbard and parts of far northern...
Project a graph from lat - long to the UTM zone appropriate for its geographic location.
def project_graph(G, to_crs=None): """ Project a graph from lat-long to the UTM zone appropriate for its geographic location. Parameters ---------- G : networkx multidigraph the networkx graph to be projected to_crs : dict if not None, just project to this CRS instead of to ...
Plot a GeoDataFrame of place boundary geometries.
def plot_shape(gdf, fc='#cbe0f0', ec='#999999', linewidth=1, alpha=1, figsize=(6,6), margin=0.02, axis_off=True): """ Plot a GeoDataFrame of place boundary geometries. Parameters ---------- gdf : GeoDataFrame the gdf containing the geometries to plot fc : string or list ...
Convert a list of RGBa colors to a list of hexadecimal color codes.
def rgb_color_list_to_hex(color_list): """ Convert a list of RGBa colors to a list of hexadecimal color codes. Parameters ---------- color_list : list the list of RGBa colors Returns ------- color_list_hex : list """ color_list_rgb = [[int(x*255) for x in c[0:3]] for c ...
Return n - length list of RGBa colors from the passed colormap name and alpha.
def get_colors(n, cmap='viridis', start=0., stop=1., alpha=1., return_hex=False): """ Return n-length list of RGBa colors from the passed colormap name and alpha. Parameters ---------- n : int number of colors cmap : string name of a colormap start : float where to s...
Get a list of node colors by binning some continuous - variable attribute into quantiles.
def get_node_colors_by_attr(G, attr, num_bins=None, cmap='viridis', start=0, stop=1, na_color='none'): """ Get a list of node colors by binning some continuous-variable attribute into quantiles. Parameters ---------- G : networkx multidigraph attr : string the name of the attribute ...
Get a list of edge colors by binning some continuous - variable attribute into quantiles.
def get_edge_colors_by_attr(G, attr, num_bins=5, cmap='viridis', start=0, stop=1, na_color='none'): """ Get a list of edge colors by binning some continuous-variable attribute into quantiles. Parameters ---------- G : networkx multidigraph attr : string the name of the continuous-va...
Save a figure to disk and show it as specified.
def save_and_show(fig, ax, save, show, close, filename, file_format, dpi, axis_off): """ Save a figure to disk and show it, as specified. Parameters ---------- fig : figure ax : axis save : bool whether to save the figure to disk or not show : bool whether to display the...
Plot a networkx spatial graph.
def plot_graph(G, bbox=None, fig_height=6, fig_width=None, margin=0.02, axis_off=True, equal_aspect=False, bgcolor='w', show=True, save=False, close=True, file_format='png', filename='temp', dpi=300, annotate=False, node_color='#66ccff', node_size=15, node_alp...
Given a list of nodes return a list of lines that together follow the path defined by the list of nodes.
def node_list_to_coordinate_lines(G, node_list, use_geom=True): """ Given a list of nodes, return a list of lines that together follow the path defined by the list of nodes. Parameters ---------- G : networkx multidigraph route : list the route as a list of nodes use_geom : bool...
Plot a route along a networkx spatial graph.
def plot_graph_route(G, route, bbox=None, fig_height=6, fig_width=None, margin=0.02, bgcolor='w', axis_off=True, show=True, save=False, close=True, file_format='png', filename='temp', dpi=300, annotate=False, node_color='#999999', node_...
Turn a row from the gdf_edges GeoDataFrame into a folium PolyLine with attributes.
def make_folium_polyline(edge, edge_color, edge_width, edge_opacity, popup_attribute=None): """ Turn a row from the gdf_edges GeoDataFrame into a folium PolyLine with attributes. Parameters ---------- edge : GeoSeries a row from the gdf_edges GeoDataFrame edge_color : string ...
Plot a graph on an interactive folium web map.
def plot_graph_folium(G, graph_map=None, popup_attribute=None, tiles='cartodbpositron', zoom=1, fit_bounds=True, edge_color='#333333', edge_width=5, edge_opacity=1): """ Plot a graph on an interactive folium web map. Note that anything larger than a small city ca...
Plot a route on an interactive folium web map.
def plot_route_folium(G, route, route_map=None, popup_attribute=None, tiles='cartodbpositron', zoom=1, fit_bounds=True, route_color='#cc0000', route_width=5, route_opacity=1): """ Plot a route on an interactive folium web map. Parameters ---------- G : ne...
Plot a figure - ground diagram of a street network defaulting to one square mile.
def plot_figure_ground(G=None, address=None, point=None, dist=805, network_type='drive_service', street_widths=None, default_width=4, fig_length=8, edge_color='w', bgcolor='#333333', smooth_joints=True, filename=None, file_forma...
Save an HTTP response json object to the cache.
def save_to_cache(url, response_json): """ Save an HTTP response json object to the cache. If the request was sent to server via POST instead of GET, then URL should be a GET-style representation of request. Users should always pass OrderedDicts instead of dicts of parameters into request functions...
Retrieve a HTTP response json object from the cache.
def get_from_cache(url): """ Retrieve a HTTP response json object from the cache. Parameters ---------- url : string the url of the request Returns ------- response_json : dict """ # if the tool is configured to use the cache if settings.use_cache: # determi...
Update the default requests HTTP headers with OSMnx info.
def get_http_headers(user_agent=None, referer=None, accept_language=None): """ Update the default requests HTTP headers with OSMnx info. Parameters ---------- user_agent : str the user agent string, if None will set with OSMnx default referer : str the referer string, if None wi...
Send a request to the Nominatim API via HTTP GET and return the JSON response.
def nominatim_request(params, type = "search", pause_duration=1, timeout=30, error_pause_duration=180): """ Send a request to the Nominatim API via HTTP GET and return the JSON response. Parameters ---------- params : dict or OrderedDict key-value pairs of parameters type : string ...
Send a request to the Overpass API via HTTP POST and return the JSON response.
def overpass_request(data, pause_duration=None, timeout=180, error_pause_duration=None): """ Send a request to the Overpass API via HTTP POST and return the JSON response. Parameters ---------- data : dict or OrderedDict key-value pairs of parameters to post to the API pause_duratio...
Geocode a place and download its boundary geometry from OSM s Nominatim API.
def osm_polygon_download(query, limit=1, polygon_geojson=1): """ Geocode a place and download its boundary geometry from OSM's Nominatim API. Parameters ---------- query : string or dict query string or structured query dict to geocode/download limit : int max number of results ...
Create a GeoDataFrame from a single place name query.
def gdf_from_place(query, gdf_name=None, which_result=1, buffer_dist=None): """ Create a GeoDataFrame from a single place name query. Parameters ---------- query : string or dict query string or structured query dict to geocode/download gdf_name : string name attribute metadata ...
Create a GeoDataFrame from a list of place names to query.
def gdf_from_places(queries, gdf_name='unnamed', buffer_dist=None): """ Create a GeoDataFrame from a list of place names to query. Parameters ---------- queries : list list of query strings or structured query dicts to geocode/download, one at a time gdf_name : string na...
Create a filter to query OSM for the specified network type.
def get_osm_filter(network_type): """ Create a filter to query OSM for the specified network type. Parameters ---------- network_type : string {'walk', 'bike', 'drive', 'drive_service', 'all', 'all_private', 'none'} what type of street or other network to get Returns ------...
Download OSM ways and nodes within some bounding box from the Overpass API.
def osm_net_download(polygon=None, north=None, south=None, east=None, west=None, network_type='all_private', timeout=180, memory=None, max_query_area_size=50*1000*50*1000, infrastructure='way["highway"]', custom_filter=None): """ Download OSM ways a...
Extract exterior coordinates from polygon ( s ) to pass to OSM in a query by polygon. Ignore the interior ( holes ) coordinates.
def get_polygons_coordinates(geometry): """ Extract exterior coordinates from polygon(s) to pass to OSM in a query by polygon. Ignore the interior ("holes") coordinates. Parameters ---------- geometry : shapely Polygon or MultiPolygon the geometry to extract exterior coordinates from ...
Convert an OSM node element into the format for a networkx node.
def get_node(element): """ Convert an OSM node element into the format for a networkx node. Parameters ---------- element : dict an OSM node element Returns ------- dict """ node = {} node['y'] = element['lat'] node['x'] = element['lon'] node['osmid'] = ele...
Convert an OSM way element into the format for a networkx graph path.
def get_path(element): """ Convert an OSM way element into the format for a networkx graph path. Parameters ---------- element : dict an OSM way element Returns ------- dict """ path = {} path['osmid'] = element['id'] # remove any consecutive duplicate element...
Construct dicts of nodes and paths with key = osmid and value = dict of attributes.
def parse_osm_nodes_paths(osm_data): """ Construct dicts of nodes and paths with key=osmid and value=dict of attributes. Parameters ---------- osm_data : dict JSON response from from the Overpass API Returns ------- nodes, paths : tuple """ nodes = {} paths = {...
Remove from a graph all the nodes that have no incident edges ( ie node degree = 0 ).
def remove_isolated_nodes(G): """ Remove from a graph all the nodes that have no incident edges (ie, node degree = 0). Parameters ---------- G : networkx multidigraph the graph from which to remove nodes Returns ------- networkx multidigraph """ isolated_nodes = [n...
Remove everything further than some network distance from a specified node in graph.
def truncate_graph_dist(G, source_node, max_distance=1000, weight='length', retain_all=False): """ Remove everything further than some network distance from a specified node in graph. Parameters ---------- G : networkx multidigraph source_node : int the node in the graph from which ...
Remove every node in graph that falls outside a bounding box.
def truncate_graph_bbox(G, north, south, east, west, truncate_by_edge=False, retain_all=False): """ Remove every node in graph that falls outside a bounding box. Needed because overpass returns entire ways that also include nodes outside the bbox if the way (that is, a way with a single OSM ID) has a n...
Split a Polygon or MultiPolygon up into sub - polygons of a specified size using quadrats.
def quadrat_cut_geometry(geometry, quadrat_width, min_num=3, buffer_amount=1e-9): """ Split a Polygon or MultiPolygon up into sub-polygons of a specified size, using quadrats. Parameters ---------- geometry : shapely Polygon or MultiPolygon the geometry to split up into smaller sub-poly...
Intersect points with a polygon using an r - tree spatial index and cutting the polygon up into smaller sub - polygons for r - tree acceleration.
def intersect_index_quadrats(gdf, geometry, quadrat_width=0.05, min_num=3, buffer_amount=1e-9): """ Intersect points with a polygon, using an r-tree spatial index and cutting the polygon up into smaller sub-polygons for r-tree acceleration. Parameters ---------- gdf : GeoDataFrame the s...
Remove every node in graph that falls outside some shapely Polygon or MultiPolygon.
def truncate_graph_polygon(G, polygon, retain_all=False, truncate_by_edge=False, quadrat_width=0.05, min_num=3, buffer_amount=1e-9): """ Remove every node in graph that falls outside some shapely Polygon or MultiPolygon. Parameters ---------- G : networkx multidigraph polygon : Polygon or M...
Add length ( meters ) attribute to each edge by great circle distance between nodes u and v.
def add_edge_lengths(G): """ Add length (meters) attribute to each edge by great circle distance between nodes u and v. Parameters ---------- G : networkx multidigraph Returns ------- G : networkx multidigraph """ start_time = time.time() # first load all the edges' o...
Add a path to the graph.
def add_path(G, data, one_way): """ Add a path to the graph. Parameters ---------- G : networkx multidigraph data : dict the attributes of the path one_way : bool if this path is one-way or if it is bi-directional Returns ------- None """ # extract the ...
Add a collection of paths to the graph.
def add_paths(G, paths, bidirectional=False): """ Add a collection of paths to the graph. Parameters ---------- G : networkx multidigraph paths : dict the paths from OSM bidirectional : bool if True, create bidirectional edges for one-way streets Returns ------- ...
Create a networkx graph from OSM data.
def create_graph(response_jsons, name='unnamed', retain_all=False, bidirectional=False): """ Create a networkx graph from OSM data. Parameters ---------- response_jsons : list list of dicts of JSON responses from from the Overpass API name : string the name of the graph reta...
Create a bounding box some distance in each direction ( north south east and west ) from some ( lat lng ) point.
def bbox_from_point(point, distance=1000, project_utm=False, return_crs=False): """ Create a bounding box some distance in each direction (north, south, east, and west) from some (lat, lng) point. Parameters ---------- point : tuple the (lat, lon) point to create the bounding box around...
Create a networkx graph from OSM data within some bounding box.
def graph_from_bbox(north, south, east, west, network_type='all_private', simplify=True, retain_all=False, truncate_by_edge=False, name='unnamed', timeout=180, memory=None, max_query_area_size=50*1000*50*1000, clean_periphery=True, infrastr...
Create a networkx graph from OSM data within some distance of some ( lat lon ) center point.
def graph_from_point(center_point, distance=1000, distance_type='bbox', network_type='all_private', simplify=True, retain_all=False, truncate_by_edge=False, name='unnamed', timeout=180, memory=None, max_query_area_size=50*1000*50*1000, ...
Create a networkx graph from OSM data within some distance of some address.
def graph_from_address(address, distance=1000, distance_type='bbox', network_type='all_private', simplify=True, retain_all=False, truncate_by_edge=False, return_coords=False, name='unnamed', timeout=180, memory=None, max_query_a...
Create a networkx graph from OSM data within the spatial boundaries of the passed - in shapely polygon.
def graph_from_polygon(polygon, network_type='all_private', simplify=True, retain_all=False, truncate_by_edge=False, name='unnamed', timeout=180, memory=None, max_query_area_size=50*1000*50*1000, clean_periphery=True, infrastruc...
Create a networkx graph from OSM data within the spatial boundaries of some geocodable place ( s ).
def graph_from_place(query, network_type='all_private', simplify=True, retain_all=False, truncate_by_edge=False, name='unnamed', which_result=1, buffer_dist=None, timeout=180, memory=None, max_query_area_size=50*1000*50*1000, clean_periphery=True, ...
Create a networkx graph from OSM data in an XML file.
def graph_from_file(filename, bidirectional=False, simplify=True, retain_all=False, name='unnamed'): """ Create a networkx graph from OSM data in an XML file. Parameters ---------- filename : string the name of a file containing OSM XML data bidirectional : bool ...
Download OpenStreetMap footprint data.
def osm_footprints_download(polygon=None, north=None, south=None, east=None, west=None, footprint_type='building', timeout=180, memory=None, max_query_area_size=50*1000*50*1000): """ Download OpenStreetMap footprint data. Parameters ---------- ...
Get footprint data from OSM then assemble it into a GeoDataFrame.
def create_footprints_gdf(polygon=None, north=None, south=None, east=None, west=None, footprint_type='building', retain_invalid=False): """ Get footprint data from OSM then assemble it into a GeoDataFrame. Parameters ---------- polygon : shapely Polygon or MultiPolygon ...
Get footprints within some distance north south east and west of a lat - long point.
def footprints_from_point(point, distance, footprint_type='building', retain_invalid=False): """ Get footprints within some distance north, south, east, and west of a lat-long point. Parameters ---------- point : tuple a lat-long point distance : numeric distance in meters ...
Get footprints within some distance north south east and west of an address.
def footprints_from_address(address, distance, footprint_type='building', retain_invalid=False): """ Get footprints within some distance north, south, east, and west of an address. Parameters ---------- address : string the address to geocode to a lat-long point distance : numeric ...
Get footprints within some polygon.
def footprints_from_polygon(polygon, footprint_type='building', retain_invalid=False): """ Get footprints within some polygon. Parameters ---------- polygon : shapely Polygon or MultiPolygon the shape to get data within. coordinates should be in units of latitude-longitude degrees. ...
Get footprints within the boundaries of some place.
def footprints_from_place(place, footprint_type='building', retain_invalid=False): """ Get footprints within the boundaries of some place. The query must be geocodable and OSM must have polygon boundaries for the geocode result. If OSM does not have a polygon for this place, you can instead get its...
Plot a GeoDataFrame of footprints.
def plot_footprints(gdf, fig=None, ax=None, figsize=None, color='#333333', bgcolor='w', set_bounds=True, bbox=None, save=False, show=True, close=False, filename='image', file_format='png', dpi=600): """ Plot a GeoDataFrame of footprints. Parameters ---------- ...
Get the elevation ( meters ) of each node in the network and add it to the node as an attribute.
def add_node_elevations(G, api_key, max_locations_per_batch=350, pause_duration=0.02): # pragma: no cover """ Get the elevation (meters) of each node in the network and add it to the node as an attribute. Parameters ---------- G : networkx multidigraph api_key : stri...
Get the directed grade ( ie rise over run ) for each edge in the network and add it to the edge as an attribute. Nodes must have elevation attributes to use this function.
def add_edge_grades(G, add_absolute=True): # pragma: no cover """ Get the directed grade (ie, rise over run) for each edge in the network and add it to the edge as an attribute. Nodes must have elevation attributes to use this function. Parameters ---------- G : networkx multidigraph ad...
Save a GeoDataFrame of place shapes or footprints as an ESRI shapefile.
def save_gdf_shapefile(gdf, filename=None, folder=None): """ Save a GeoDataFrame of place shapes or footprints as an ESRI shapefile. Parameters ---------- gdf : GeoDataFrame the gdf to be saved filename : string what to call the shapefile (file extensions are added automatic...
Save graph nodes and edges as ESRI shapefiles to disk.
def save_graph_shapefile(G, filename='graph', folder=None, encoding='utf-8'): """ Save graph nodes and edges as ESRI shapefiles to disk. Parameters ---------- G : networkx multidigraph filename : string the name of the shapefiles (not including file extensions) folder : string ...
Save a graph as an OSM XML formatted file. NOTE: for very large networks this method can take upwards of 30 + minutes to finish.
def save_graph_osm(G, node_tags=settings.osm_xml_node_tags, node_attrs=settings.osm_xml_node_attrs, edge_tags=settings.osm_xml_way_tags, edge_attrs=settings.osm_xml_way_attrs, oneway=True, filename='graph.osm', folder=None): ...
Save graph as GraphML file to disk.
def save_graphml(G, filename='graph.graphml', folder=None, gephi=False): """ Save graph as GraphML file to disk. Parameters ---------- G : networkx multidigraph filename : string the name of the graphml file (including file extension) folder : string the folder to contain th...
Load a GraphML file from disk and convert the node/ edge attributes to correct data types.
def load_graphml(filename, folder=None, node_type=int): """ Load a GraphML file from disk and convert the node/edge attributes to correct data types. Parameters ---------- filename : string the name of the graphml file (including file extension) folder : string the folder co...
Check if two edge data dictionaries are the same based on OSM ID and geometry.
def is_duplicate_edge(data, data_other): """ Check if two edge data dictionaries are the same based on OSM ID and geometry. Parameters ---------- data : dict the first edge's data data_other : dict the second edge's data Returns ------- is_dupe : bool """ ...
Check if LineString geometries in two edges are the same in normal or reversed order of points.
def is_same_geometry(ls1, ls2): """ Check if LineString geometries in two edges are the same, in normal or reversed order of points. Parameters ---------- ls1 : LineString the first edge's geometry ls2 : LineString the second edge's geometry Returns ------- bool...
Update the keys of edges that share a u v with another edge but differ in geometry. For example two one - way streets from u to v that bow away from each other as separate streets rather than opposite direction edges of a single street. Parameters ---------- G: networkx multidigraph
def update_edge_keys(G): """ Update the keys of edges that share a u, v with another edge but differ in geometry. For example, two one-way streets from u to v that bow away from each other as separate streets, rather than opposite direction edges of a single street. Parameters --------...
Convert a directed graph to an undirected graph that maintains parallel edges if geometries differ.
def get_undirected(G): """ Convert a directed graph to an undirected graph that maintains parallel edges if geometries differ. Parameters ---------- G : networkx multidigraph Returns ------- networkx multigraph """ start_time = time.time() # set from/to nodes before m...
Convert a graph into node and/ or edge GeoDataFrames
def graph_to_gdfs(G, nodes=True, edges=True, node_geometry=True, fill_edge_geometry=True): """ Convert a graph into node and/or edge GeoDataFrames Parameters ---------- G : networkx multidigraph nodes : bool if True, convert graph nodes to a GeoDataFrame and return it edges : bool ...
Convert node and edge GeoDataFrames into a graph
def gdfs_to_graph(gdf_nodes, gdf_edges): """ Convert node and edge GeoDataFrames into a graph Parameters ---------- gdf_nodes : GeoDataFrame gdf_edges : GeoDataFrame Returns ------- networkx multidigraph """ G = nx.MultiDiGraph() G.graph['crs'] = gdf_nodes.crs G.gr...
Create a filename string in a consistent format from a place name string.
def make_shp_filename(place_name): """ Create a filename string in a consistent format from a place name string. Parameters ---------- place_name : string place name to convert into a filename Returns ------- string """ name_pieces = list(reversed(place_name.split(', ')...
Calculate basic descriptive metric and topological stats for a graph.
def basic_stats(G, area=None, clean_intersects=False, tolerance=15, circuity_dist='gc'): """ Calculate basic descriptive metric and topological stats for a graph. For an unprojected lat-lng graph, tolerance and graph units should be in degrees, and circuity_dist should be 'gc'. For a pr...
Calculate extended topological stats and metrics for a graph.
def extended_stats(G, connectivity=False, anc=False, ecc=False, bc=False, cc=False): """ Calculate extended topological stats and metrics for a graph. Many of these algorithms have an inherently high time complexity. Global topological analysis of large complex networks is extremely time consuming ...
r Solve by backward induction a: math: T - period finite horizon discrete dynamic program with stationary reward and transition probability functions: math: r and: math: q and discount factor: math: \ beta \ in [ 0 1 ].
def backward_induction(ddp, T, v_term=None): r""" Solve by backward induction a :math:`T`-period finite horizon discrete dynamic program with stationary reward and transition probability functions :math:`r` and :math:`q` and discount factor :math:`\beta \in [0, 1]`. The optimal value functions ...
Check whether s_indices and a_indices are sorted in lexicographic order.
def _has_sorted_sa_indices(s_indices, a_indices): """ Check whether `s_indices` and `a_indices` are sorted in lexicographic order. Parameters ---------- s_indices, a_indices : ndarray(ndim=1) Returns ------- bool Whether `s_indices` and `a_indices` are sorted. """ ...
Generate a_indptr ; stored in out. s_indices is assumed to be in sorted order.
def _generate_a_indptr(num_states, s_indices, out): """ Generate `a_indptr`; stored in `out`. `s_indices` is assumed to be in sorted order. Parameters ---------- num_states : scalar(int) s_indices : ndarray(int, ndim=1) out : ndarray(int, ndim=1) Length must be num_states+1. ...
Check that for every state reward is finite for some action and for the case sa_pair is True that for every state there is some action available.
def _check_action_feasibility(self): """ Check that for every state, reward is finite for some action, and for the case sa_pair is True, that for every state, there is some action available. """ # Check that for every state, reward is finite for some action R_max...
Convert this instance of DiscreteDP to SA - pair form
def to_sa_pair_form(self, sparse=True): """ Convert this instance of `DiscreteDP` to SA-pair form Parameters ---------- sparse : bool, optional(default=True) Should the `Q` matrix be stored as a sparse matrix? If true the CSR format is used Retur...
Convert this instance of DiscreteDP to the product form.
def to_product_form(self): """ Convert this instance of `DiscreteDP` to the "product" form. The product form uses the version of the init method taking `R`, `Q` and `beta`. Parameters ---------- Returns ------- ddp_sa : DiscreteDP Th...
Given a policy sigma return the reward vector R_sigma and the transition probability matrix Q_sigma.
def RQ_sigma(self, sigma): """ Given a policy `sigma`, return the reward vector `R_sigma` and the transition probability matrix `Q_sigma`. Parameters ---------- sigma : array_like(int, ndim=1) Policy vector, of length n. Returns ------- ...
The Bellman operator which computes and returns the updated value function Tv for a value function v.
def bellman_operator(self, v, Tv=None, sigma=None): """ The Bellman operator, which computes and returns the updated value function `Tv` for a value function `v`. Parameters ---------- v : array_like(float, ndim=1) Value function vector, of length n. ...
Given a policy sigma return the T_sigma operator.
def T_sigma(self, sigma): """ Given a policy `sigma`, return the T_sigma operator. Parameters ---------- sigma : array_like(int, ndim=1) Policy vector, of length n. Returns ------- callable The T_sigma operator. """ ...
Compute the v - greedy policy.
def compute_greedy(self, v, sigma=None): """ Compute the v-greedy policy. Parameters ---------- v : array_like(float, ndim=1) Value function vector, of length n. sigma : ndarray(int, ndim=1), optional(default=None) Optional output array for `sigm...