INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Given label matrix L and labels Y, compute the covariance.
Args:
L: (np.array) [n, d] The augmented (indicator) label matrix
Y: (np.array int) [n] The true labels in {1,...,k} | def compute_inv_covariance(L_aug, Y, k, p):
"""Given label matrix L and labels Y, compute the covariance.
Args:
L: (np.array) [n, d] The augmented (indicator) label matrix
Y: (np.array int) [n] The true labels in {1,...,k}
"""
return np.linalg.inv(compute_covariance(L_aug, Y, k, p)) |
Pretty printing for numpy matrix X | def print_matrix(X, decimals=1):
"""Pretty printing for numpy matrix X"""
for row in np.round(X, decimals=decimals):
print(row) |
Returns an indicator vector where ith element = 1 if x_i is labeled by
at least two LFs that give it disagreeing labels. | def _conflicted_data_points(L):
"""Returns an indicator vector where ith element = 1 if x_i is labeled by
at least two LFs that give it disagreeing labels."""
m = sparse.diags(np.ravel(L.max(axis=1).todense()))
return np.ravel(np.max(m @ (L != 0) != L, axis=1).astype(int).todense()) |
Return the polarities of each LF based on evidence in a label matrix.
Args:
L: an n x m scipy.sparse matrix where L_{i,j} is the label given by the
jth LF to the ith candidate | def lf_polarities(L):
"""Return the polarities of each LF based on evidence in a label matrix.
Args:
L: an n x m scipy.sparse matrix where L_{i,j} is the label given by the
jth LF to the ith candidate
"""
polarities = [sorted(list(set(L[:, i].data))) for i in range(L.shape[1])]
... |
Return the **fraction of items each LF labels that are also labeled by at
least one other LF.**
Note that the maximum possible overlap fraction for an LF is the LF's
coverage, unless `normalize_by_coverage=True`, in which case it is 1.
Args:
L: an n x m scipy.sparse matrix where L_{i,j} is th... | def lf_overlaps(L, normalize_by_coverage=False):
"""Return the **fraction of items each LF labels that are also labeled by at
least one other LF.**
Note that the maximum possible overlap fraction for an LF is the LF's
coverage, unless `normalize_by_coverage=True`, in which case it is 1.
Args:
... |
Return the **fraction of items each LF labels that are also given a
different (non-abstain) label by at least one other LF.**
Note that the maximum possible conflict fraction for an LF is the LF's
overlaps fraction, unless `normalize_by_overlaps=True`, in which case it
is 1.
Args:
... | def lf_conflicts(L, normalize_by_overlaps=False):
"""Return the **fraction of items each LF labels that are also given a
different (non-abstain) label by at least one other LF.**
Note that the maximum possible conflict fraction for an LF is the LF's
overlaps fraction, unless `normalize_by_overlaps=... |
Return the **empirical accuracy** against a set of labels Y (e.g. dev
set) for each LF.
Args:
L: an n x m scipy.sparse matrix where L_{i,j} is the label given by the
jth LF to the ith candidate
Y: an [n] or [n, 1] np.ndarray of gold labels | def lf_empirical_accuracies(L, Y):
"""Return the **empirical accuracy** against a set of labels Y (e.g. dev
set) for each LF.
Args:
L: an n x m scipy.sparse matrix where L_{i,j} is the label given by the
jth LF to the ith candidate
Y: an [n] or [n, 1] np.ndarray of gold labels
... |
Returns a pandas DataFrame with the various per-LF statistics.
Args:
L: an n x m scipy.sparse matrix where L_{i,j} is the label given by the
jth LF to the ith candidate
Y: an [n] or [n, 1] np.ndarray of gold labels.
If provided, the empirical accuracy for each LF will be cal... | def lf_summary(L, Y=None, lf_names=None, est_accs=None):
"""Returns a pandas DataFrame with the various per-LF statistics.
Args:
L: an n x m scipy.sparse matrix where L_{i,j} is the label given by the
jth LF to the ith candidate
Y: an [n] or [n, 1] np.ndarray of gold labels.
... |
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
Args:
Y_p: a np.array or torch.Tensor of predicted labels
Y: a np.array or torch.Tensor of true labels (if known)
"""
L = sparse.csr_matrix(arraylike_to_numpy(Y_p).reshape(-1, 1)... |
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... | def error_buckets(gold, pred, X=None):
"""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
p... |
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... | def confusion_matrix(
gold, pred, null_pred=False, null_gold=False, normalize=False, pretty_print=True
):
"""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, i... |
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, pred)) |
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... | def search(
self,
search_space,
valid_data,
init_args=[],
train_args=[],
init_kwargs={},
train_kwargs={},
module_args={},
module_kwargs={},
max_search=None,
shuffle=True,
verbose=True,
clean_up=True,
seed=Non... |
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... | def config(data_folder=settings.data_folder,
logs_folder=settings.logs_folder,
imgs_folder=settings.imgs_folder,
cache_folder=settings.cache_folder,
use_cache=settings.use_cache,
log_file=settings.log_file,
log_console=settings.log_console,
lo... |
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... | def log(message, level=None, name=None, filename=None):
"""
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 t... |
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=None, name=None, filename=None):
"""
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
... |
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):
"""
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... |
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... | def get_largest_component(G, strongly=False):
"""
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
c... |
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... | def great_circle_vec(lat1, lng1, lat2, lng2, earth_radius=6371009):
"""
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 :... |
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... | def euclidean_dist_vec(y1, x1, y2, x2):
"""
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 fl... |
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)... | def get_nearest_node(G, point, method='haversine', return_dist=False):
"""
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
... |
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 ... | def get_nearest_edge(G, point):
"""
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 t... |
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 ... | def get_nearest_nodes(G, X, Y, method=None):
"""
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 coordinat... |
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 ... | def get_nearest_edges(G, X, Y, method=None, dist=0.0001):
"""
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 unprojec... |
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... | def redistribute_vertices(geom, dist):
"""
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
geome... |
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
... | def get_bearing(origin_point, destination_point):
"""
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 c... |
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 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
"""
... |
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, lon) with the Nominatim geocoder.
Parameters
----------
query : string
the query string to geocode
Returns
-------
point : tuple
the (lat, lon) coordinates returned by the geocoder
"""
# send the query to ... |
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... | def get_route_edge_attributes(G, route, attribute=None, minimize_key='length', retrieve_default=None):
"""
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 na... |
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... | def count_streets_per_node(G, nodes=None):
"""
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 : iterabl... |
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... | def round_polygon_coords(p, precision):
"""
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
-------
... |
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 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
-------
Po... |
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_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.
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... | 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.
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-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.
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 ... | 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.
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.
... | 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 ... | 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.
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 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.
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
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)
Parameters
----------
gdf : gpd.GeoDataFrame
GeoDataFrame with Polygon geometries that should be converted into a MultiPolygon object.
relation : dict
OSM 'relation' diction... | 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.... | 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.
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... | 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.
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 ... | 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.
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... | 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.
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... | 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... | 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.
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 ... | 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.
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 ... | 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.
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
... | 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... |
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... | 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... |
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... | 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 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... | 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 ... |
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
... | 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... |
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... | 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.
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 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.
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... | 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.
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
... | 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.
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
... | 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.
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... | 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.
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... | 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.
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
... | 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.
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... | 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.
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... | 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.
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... | 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.
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... | 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.
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
... | 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... |
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
the url of the request
Returns
-------
response_json : dict
"""
# if the tool is configured to use the cache
if settings.use_cache:
# determi... |
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... | 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... |
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... | 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.
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... | 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.
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 ... | 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.
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... | 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.
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
... | 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.
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... | 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.
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):
"""
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.
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 ... | 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.
Parameters
----------
geometry : shapely Polygon or MultiPolygon
the geometry to extract exterior coordinates from
Returns
-------
polygon_coord_strs : list | 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.
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 : 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.
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
----------
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.
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 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).
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 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.
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... | 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.
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... | 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.
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... | 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.
Parameters
----------
gdf : GeoDataFrame
the set of points to intersect
geometry : shapely Polygon or MultiPolygon
the geometry to intersect w... | 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.
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 ... | 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.
Parameters
----------
G : networkx multidigraph
Returns
-------
G : networkx multidigraph | 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.
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.
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.
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):
"""
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.
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 ... | 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.
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... | 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.
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 ... | 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.
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... | 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.
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... | 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.
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... | 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).
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... | 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.
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... | 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.
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... | 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
----------
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.