text
stringlengths
81
112k
Calculates coverage, overlap, conflicts, and accuracy for a single LF Args: Y_p: a np.array or torch.Tensor of predicted labels Y: a np.array or torch.Tensor of true labels (if known) def single_lf_summary(Y_p, Y=None): """Calculates coverage, overlap, conflicts, and accuracy for a single LF ...
Group items by error buckets Args: gold: an array-like of gold labels (ints) pred: an array-like of predictions (ints) X: an iterable of items Returns: buckets: A dict of items where buckets[i,j] is a list of items with predicted label i and true label j. If X is Non...
A shortcut method for building a confusion matrix all at once. Args: gold: an array-like of gold labels (ints) pred: an array-like of predictions (ints) null_pred: If True, include the row corresponding to null predictions null_gold: If True, include the col corresponding to null go...
Args: gold: a np.ndarray of gold labels (ints) pred: a np.ndarray of predictions (ints) def add(self, gold, pred): """ Args: gold: a np.ndarray of gold labels (ints) pred: a np.ndarray of predictions (ints) """ self.counter.update(zip(gold...
Args: search_space: see config_generator() documentation valid_data: a tuple of Tensors (X,Y), a Dataset, or a DataLoader of X (data) and Y (labels) for the dev split init_args: (list) positional args for initializing the model train_args: (list) positiona...
Configure osmnx by setting the default global vars to desired values. Parameters --------- data_folder : string where to save and load data files logs_folder : string where to write the log files imgs_folder : string where to save figures cache_folder : string wh...
Write a message to the log file and/or print to the the console. Parameters ---------- message : string the content of the message to log level : int one of the logger.level constants name : string name of the logger filename : string name of the log file Re...
Create a logger or return the current one if already instantiated. Parameters ---------- level : int one of the logger.level constants name : string name of the logger filename : string name of the log file Returns ------- logger.logger def get_logger(level=Non...
Induce a subgraph of G. Parameters ---------- G : networkx multidigraph node_subset : list-like the subset of nodes to induce a subgraph of G Returns ------- G2 : networkx multidigraph the subgraph of G induced by node_subset def induce_subgraph(G, node_subset): """ ...
Return a subgraph of the largest weakly or strongly connected component from a directed graph. Parameters ---------- G : networkx multidigraph strongly : bool if True, return the largest strongly instead of weakly connected component Returns ------- G : networkx multidi...
Vectorized function to calculate the great-circle distance between two points or between vectors of points, using haversine. Parameters ---------- lat1 : float or array of float lng1 : float or array of float lat2 : float or array of float lng2 : float or array of float earth_radius : n...
Vectorized function to calculate the euclidean distance between two points or between vectors of points. Parameters ---------- y1 : float or array of float x1 : float or array of float y2 : float or array of float x2 : float or array of float Returns ------- distance : float or...
Return the graph node nearest to some specified (lat, lng) or (y, x) point, and optionally the distance between the node and the point. This function can use either a haversine or euclidean distance calculator. Parameters ---------- G : networkx multidigraph point : tuple The (lat, lng)...
Return the nearest edge to a pair of coordinates. Pass in a graph and a tuple with the coordinates. We first get all the edges in the graph. Secondly we compute the euclidean distance from the coordinates to the segments determined by each edge. The last step is to sort the edge segments in ascending order ...
Return the graph nodes nearest to a list of points. Pass in points as separate vectors of X and Y coordinates. The 'kdtree' method is by far the fastest with large data sets, but only finds approximate nearest nodes if working in unprojected coordinates like lat-lng (it precisely finds the nearest node ...
Return the graph edges nearest to a list of points. Pass in points as separate vectors of X and Y coordinates. The 'kdtree' method is by far the fastest with large data sets, but only finds approximate nearest edges if working in unprojected coordinates like lat-lng (it precisely finds the nearest edge ...
Redistribute the vertices on a projected LineString or MultiLineString. The distance argument is only approximate since the total distance of the linestring may not be a multiple of the preferred distance. This function works on only [Multi]LineString geometry types. This code is adapted from an answer...
Calculate the bearing between two lat-long points. Each tuple should represent (lat, lng) as decimal degrees. Parameters ---------- origin_point : tuple destination_point : tuple Returns ------- bearing : float the compass bearing in decimal degrees from the origin point ...
Calculate the compass bearing from origin node to destination node for each edge in the directed graph then add each bearing as a new edge attribute. Parameters ---------- G : networkx multidigraph Returns ------- G : networkx multidigraph def add_edge_bearings(G): """ Calculate t...
Geocode a query string to (lat, lon) with the Nominatim geocoder. Parameters ---------- query : string the query string to geocode Returns ------- point : tuple the (lat, lon) coordinates returned by the geocoder def geocode(query): """ Geocode a query string to (lat, ...
Get a list of attribute values for each edge in a path. Parameters ---------- G : networkx multidigraph route : list list of nodes in the path attribute : string the name of the attribute to get the value of for each edge. If not specified, the complete data dict is returned...
Count how many street segments emanate from each node (i.e., intersections and dead-ends) in this graph. If nodes is passed, then only count the nodes in the graph with those IDs. Parameters ---------- G : networkx multidigraph nodes : iterable the set of node IDs to get counts for Re...
Round the coordinates of a shapely Polygon to some decimal precision. Parameters ---------- p : shapely Polygon the polygon to round the coordinates of precision : int decimal precision to round coordinates to Returns ------- new_poly : shapely Polygon the polygon w...
Round the coordinates of a shapely Point to some decimal precision. Parameters ---------- pt : shapely Point the Point to round the coordinates of precision : int decimal precision to round coordinates to Returns ------- Point def round_point_coords(pt, 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 Returns ------- LineString def round_linestring_coord...
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 coordinates of precision : int decimal precision t...
Read OSM XML from input filename and return Overpass-like JSON. Parameters ---------- filename : string name of file containing OSM XML data Returns ------- OSMContentHandler object def overpass_json_from_file(filename): """ Read OSM XML from input filename and return Overpass...
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. Parameters ---------- north : float Northernmost coordinate from bounding box of the search area. south : float Southernmost coordinate from bounding box of the search area. east : float Easternmost coordinate ...
Get points of interests (POIs) from OpenStreetMap based on selected amenity types. Parameters ---------- poly : shapely.geometry.Polygon Polygon that will be used to limit the POI search. amenities : list List of amenities that will be used for finding the POIs from the selected area. ...
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 ...
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 def parse_polygonal_poi(coords, response): """ Parse areal P...
Parse points from OSM nodes. Parameters ---------- response : JSON Nodes from OSM response. Returns ------- Dict of vertex IDs and their lat, lon coordinates. def parse_osm_node(response): """ Parse points from OSM nodes. Parameters ---------- response : JSON ...
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 MultiPolygon object. relation : dict OSM 'relation' diction...
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....
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: list List of amenities that will be used for finding the POIs from the selected area. See av...
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 List of amenities that will be used for finding the POIs from ...
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 amenities : list List of amenities that will be used for f...
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 from the selected area. See available amenities...
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...
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 path : list the list of nodes in order in the ...
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 true edge endpoints, you may want to increase your ...
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 ---------- G : networkx multidigraph ...
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 where each edge intersects a perpendicular edge. These 4 nodes represen...
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 coordinate reference system of the passed-in geometry, default value (None) will set...
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 Norway. Parameters ---------- gdf : GeoDataFrame ...
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 UTM Returns ------- networkx multi...
Plot a GeoDataFrame of place boundary geometries. Parameters ---------- gdf : GeoDataFrame the gdf containing the geometries to plot fc : string or list the facecolor (or list of facecolors) for the polygons ec : string or list the edgecolor (or list of edgecolors) for the p...
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 def rgb_color_list_to_hex(color_list): """ Convert a list of RGBa colors to a list of hexadecimal color cod...
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 start in the colorspace stop : float where to end in the colorspace alpha : flo...
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 num_bins : int how many quantiles (default None assigns each node to its own bin) cmap : string ...
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-variable attribute num_bins : int how many quantiles cmap : string name of a colormap ...
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 figure or not close : bool close the figure (only if show equals False) to prevent d...
Plot a networkx spatial graph. Parameters ---------- G : networkx multidigraph bbox : tuple bounding box as north,south,east,west - if None will calculate from spatial extents of data. if passing a bbox, you probably also want to pass margin=0 to constrain it. fig_height : i...
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 if True, use the spatial geometry attribute of the edges to draw ...
Plot a route along a networkx spatial graph. Parameters ---------- G : networkx multidigraph route : list the route as a list of nodes bbox : tuple bounding box as north,south,east,west - if None will calculate from spatial extents of data. if passing a bbox, you probably al...
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 color of the edge lines edge_width : numeric width of the edge lines edge_opacity : num...
Plot a graph on an interactive folium web map. Note that anything larger than a small city can take a long time to plot and create a large web map file that is very slow to load as JavaScript. Parameters ---------- G : networkx multidigraph graph_map : folium.folium.Map if not None, pl...
Plot a route on an interactive folium web map. Parameters ---------- G : networkx multidigraph route : list the route as a list of nodes route_map : folium.folium.Map if not None, plot the route on this preexisting folium map object popup_attribute : string edge attribut...
Plot a figure-ground diagram of a street network, defaulting to one square mile. Parameters ---------- G : networkx multidigraph address : string the address to geocode as the center point if G is not passed in point : tuple the center point if address and G are not passed in ...
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, so that the parameters stay in the same order...
Retrieve a HTTP response json object from the cache. Parameters ---------- url : string the url of the request Returns ------- response_json : dict def get_from_cache(url): """ Retrieve a HTTP response json object from the cache. Parameters ---------- url : string...
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 will set with OSMnx default accept_language : str make accept-language explic...
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 Type of Nominatim query. One of the following: search, reverse or lookup pause_duration : int how...
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_duration : int how long to pause in seconds before requests, if None, will query API status ...
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 to return polygon_geojson : int request the boundary geometry...
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 for GeoDataFrame (this is used to save shapefile later) which_result : int ...
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 name attribute metadata for GeoDataFrame (this is used to save shapefile l...
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 ------- string def get_osm_filter(network_type)...
Download OSM ways and nodes within some bounding box from the Overpass API. Parameters ---------- polygon : shapely Polygon or MultiPolygon geographic shape to fetch the street network within north : float northern latitude of bounding box south : float southern latitude of ...
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 Returns ------- polygon_coord_strs : list...
Convert an OSM node element into the format for a networkx node. Parameters ---------- element : dict an OSM node element Returns ------- dict def get_node(element): """ Convert an OSM node element into the format for a networkx node. Parameters ---------- element...
Convert an OSM way element into the format for a networkx graph path. Parameters ---------- element : dict an OSM way element Returns ------- dict def get_path(element): """ Convert an OSM way element into the format for a networkx graph path. Parameters ---------- ...
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 def parse_osm_nodes_paths(osm_data): """ Construct dicts of nodes and paths w...
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 def remove_isolated_nodes(G): """ Remove from a graph all the nod...
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 to measure network distances to other nodes max_distance : int remove every node in the...
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 node inside the bbox at some point. Parameters ---------- G : networkx multidigraph nort...
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-polygons quadrat_width : numeric the linear width of the quadrats with which to cut up...
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 set of points to intersect geometry : shapely Polygon or MultiPolygon the geometry to intersect w...
Remove every node in graph that falls outside some shapely Polygon or MultiPolygon. Parameters ---------- G : networkx multidigraph polygon : Polygon or MultiPolygon only retain nodes in graph that lie within this geometry retain_all : bool if True, return the entire graph even ...
Add length (meters) attribute to each edge by great circle distance between nodes u and v. Parameters ---------- G : networkx multidigraph Returns ------- G : networkx multidigraph def add_edge_lengths(G): """ Add length (meters) attribute to each edge by great circle distance bet...
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 def add_path(G, data, one_way): """ Add a path to the graph. ...
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 ------- None def add_paths(G, paths, 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 retain_all : bool if True, return the entire graph even if it is not connected bidirectional ...
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 distance : int how many meters the north, south, east, and west sides of the bo...
Create a networkx graph from OSM data within some bounding box. Parameters ---------- north : float northern latitude of bounding box south : float southern latitude of bounding box east : float eastern longitude of bounding box west : float western longitude of ...
Create a networkx graph from OSM data within some distance of some (lat, lon) center point. Parameters ---------- center_point : tuple the (lat, lon) central point around which to construct the graph distance : int retain only those nodes within this many meters of the center of the...
Create a networkx graph from OSM data within some distance of some address. Parameters ---------- address : string the address to geocode and use as the central point around which to construct the graph distance : int retain only those nodes within this many meters of the center...
Create a networkx graph from OSM data within the spatial boundaries of the passed-in shapely polygon. Parameters ---------- polygon : shapely Polygon or MultiPolygon the shape to get network data within. coordinates should be in units of latitude-longitude degrees. network_type : st...
Create a networkx graph from OSM data within the spatial boundaries of some geocodable place(s). 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 street network using the graph_from_address f...
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 if True, create bidirectional edges for one-way streets simplify : bool if True, simplify the graph topology reta...
Download OpenStreetMap footprint data. Parameters ---------- polygon : shapely Polygon or MultiPolygon geographic shape to fetch the footprints within north : float northern latitude of bounding box south : float southern latitude of bounding box east : float eas...
Get footprint data from OSM then assemble it into a GeoDataFrame. Parameters ---------- polygon : shapely Polygon or MultiPolygon geographic shape to fetch the footprints within north : float northern latitude of bounding box south : float southern latitude of bounding box ...
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 footprint_type : string type of footprint to be downloaded. OSM tag key e.g. 'building', 'land...
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 distance in meters footprint_type : string type of footprint to be downloaded. OSM tag key...
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. footprint_type : string type of footprint to be downloaded. OSM tag key e.g. 'building'...
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 footprints using the footprints_from_address function, which geocodes the place name to a ...
Plot a GeoDataFrame of footprints. Parameters ---------- gdf : GeoDataFrame footprints fig : figure ax : axis figsize : tuple color : string the color of the footprints bgcolor : string the background color of the plot set_bounds : bool if True, set b...
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 : string your google maps elevation API key max_locations_per_batch : int max number of coordinate pairs to submit in each API c...
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 add_absolute : bool if True, also add the absolute value of the grad...