Submodules

anprx.core

class anprx.core.Camera(network, id, point, address=None, radius=40, max_angle=40, nsamples=100, left_handed_traffic=True)

Bases: object

A traffic camera located on the side of a drivable street.

network

nx.MultiDiGraph – a street network

id

string – a camera identifier

point

Point – location of the camera

edge

Edge – edge observed by the camera.

The edge is estimated using the method estimate_edge, and corresponds to the candidate edge that maximises the proportion of sampled points that meet the criteria (< radius and < max_angle) - max of values in p_cedges. Evidently, this value is the same for directed edges (u,v) and (v,u). Therefore, the edge (u,v) or (v,u) is picked according to which of the two traffic lanes is closer to the camera, in a left or right handed traffic system. Relative to the traffic camera (imagine it as the origin of a cartesian graph), in a left-handed traffic system, the inner traffic lane moves anticlockwise, except for roundabouts. Cameras are likely to be osbserving the inner of the two lanes to get a cleaner shot of the plate numbers (without vehicles crossing the camera’s frame - or line of sight - in the opposite direction).

address

str – address of the street observed by the camera as labelled by a human

radius

float – range of the camera, in meters. Usually limited to 50 meters

max_angle

float – max angle, in degrees, between the camera and the vehicle’s plate number, at which the ANPR camera can operate reliably. Usually up to 40 degrees

lsystem

dict

Nnodes:list of int nodes near the camera. These are composed of the nodes that are within the range the camera and nodes whose edges have a node that is within the range of the camera.
Nedges:list of Edge edges near the camera. Edges which have at least 1 node within the range of the camera.
Cedges:list of Edge edges considered as candidates for self.edge - the edge observed by the camera
Lnodes:dict( int : np.ndarray ) nnodes represented in a cartesian coordinate system, whose origin is the camera
Ledges:dict( Edge : np.ndarray ) cedges represented in a cartesian coordinate system, whose origin is the camera
p_cedges

dict(Edge : float) – proportion of sampled points from each candidate edge that meet the criteria (< radius and < max_angle)

__init__(network, id, point, address=None, radius=40, max_angle=40, nsamples=100, left_handed_traffic=True)
Parameters:
  • network (nx.MultiDiGraph) – a street network
  • id (string) – a camera identifier
  • point (Point) – location of the camera
  • address (str) – address of the street observed by the camera as labelled by a human. Used to excludes candidate edges whose address is different than this.
  • radius (int) – range of the camera, in meters. Usually limited to 50 meters.
  • max_angle (int) – max angle between the camera and the cars (plate number) travelling on the road, at which the ANPR camera can reliably operate.
  • nsamples (int) – number of road points to sample when estimating the camera’s observed edge.
  • left_handed_traffic (bool) – True if traffic flows on the left-hand side of the road, False otherwise.
class anprx.core.Point(lat, lng)

Bases: tuple

class anprx.core.BBox(north, south, east, west)

Bases: tuple

class anprx.core.RelativeMargins(north, south, east, west)

Bases: tuple

class anprx.core.Edge(u, v, k)

Bases: tuple

class anprx.core.GiantBBox(*args, **kwargs)

Bases: ValueError

core.to_point()

Converts a point represented by an n-vector to latitude and longitude.

Parameters:nvector (np.ndarray) – the n-vector of a point given by latitude and longitude
Returns:The same point given by latitude and longitude.
Return type:Point
core.to_nvector()

Converts a point represented by latitude and longitude to an n-vector.

Parameters:point (Point) – a point given by latitude and longitude
Returns:A numpy.ndarray with shape (3,), representing the same point as an n-vector (vector in 3D space).
Return type:np.ndarray
core.great_circle_distance(destination)

Computes the great_circle_distance between two points represented by nvectors.

Parameters:
  • origin (np.ndarray) – origin point nvector
  • destination (np.ndarray) – destination point nvector
Returns:

great circle distance (“as the crow flies”)

Return type:

float

core.true_bearing(destination)

Calculates the true bearing between two points represented as nvectors.

Parameters:
  • origin (np.ndarray) – origin point nvector
  • destination (np.ndarray) – destination point nvector
Returns:

bearing (angle) between the two points, in degrees

Return type:

float

core.as_lvector(point)

Represents a Point as a vector in a (local) cartesian coordinate system, where another Point is the origin.

Consider the case of a traffic camera and nearby nodes in the road network (junctions). A nearby node can be represented as a Point with polar coordinates (r,phi), where the camera is the origin, r is the distance between the camera and the node, and phi is the bearing between the two (basis used in navigation: the 0 degrees axis is drawn vertically upwards and the angle increases for clockwise rotations). Edges (roads) in the network can be represented by vector addition. For that purpose, the point is converted and returned in cartesian coordinates, in the standard basis.

Parameters:
  • origin (Point) – point used as origin in the new coordinate system
  • point (Point) – target Point to be represented in the new coordinate system
Returns:

vector representing the target Point in the new (local) cartesian coordinate system

Return type:

np.ndarray

core.from_lvector(lvector)

Reconstruct the lat-lng point from its lvector.

Parameters:
  • origin (Point) – point used as origin in the local cartesian coordinate system
  • lvector (np.ndarray (2,)) – vector representing the target Point in the new local cartesian coordinate system
Returns:

Return type:

Point

core.get_bbox_area(unit=<Units.km: 2>, method='simple')

Calculate the area of a bounding box.

Parameters:
  • bbox (BBox) – bounding box (north, south, east, west)
  • unit (Unit) – unit of distance
  • method (string) –

    Method used to compute the area of the bounding box.

    ’simple’ - calculates the area as a rectangle using length as latitude difference and width as longitude difference corrected by mean latitude point.

    ’sins’ - calculates the area according to the method presented in http://mathfax.com/area-of-a-latitude-longitude-rectangle/ (the link is currently down).

Returns:

area in provided units

Return type:

float

core.get_meanpoint()

Calculate the geometrical meanpoint from a list of points.

Parameters:points (list of Point) – list of points
Returns:The mid or ‘mean’ point of a set of points, geometrically speaking.
Return type:Point
core.bbox_from_points(unit=<Units.km: 2>, rel_margins=RelativeMargins(north=0.025, south=0.025, east=0.025, west=0.025), min_area=0.01, max_area=10.0)

Get the bounding box that encompasses a set of points.

Parameters:
  • points (list of Point) – list of points
  • unit (Units) – unit of distance (m, km)
  • rel_margins (RelativeMargins) – margins as a proportion of latitude/longitude difference
  • min_area (float) – minimum area of bounding box in squared km
  • max_area (float) – maximum area of bounding box in squared km
Returns:

longitudes

Return type:

list of float

core.get_surrounding_network(rel_margins=RelativeMargins(north=0.025, south=0.025, east=0.025, west=0.025), min_area=0.03, max_area=10, unit=<Units.km: 2>, graph_name=None)

Get the drivable network that encompasses a set of points. Uses osmnx for this purpose.

Parameters:
  • points (list of Point) – list of points
  • rel_margins (RelativeMargins) – margins as a proportion of latitude/longitude difference
  • min_area (float) – minimum area of bounding box in squared km
  • max_area (float) – maximum area of bounding box in squared km
Returns:

a graph representing the street network

Return type:

nx.MultiDiGraph

core.edges_from_osmid(osmids)

Get the network edges that match a given osmid, for several input osmids.

Parameters:
  • network (nx.MultiDiGraph) – a street network
  • osmids (list of int) – osmids of network edge = 1+ OSM ways = road segment
Returns:

edges that match a osmid, for each input osmid

Return type:

generator of Edge

core.distance_to_edge(edge, point, method=<EdgeDistanceMethod.farthest_node: 4>)

Calculate the distance of a given point to an edge of the network (road segment)

Parameters:
  • network (nx.MultiDiGraph) – street network
  • edge (Edge) – network edge
  • point (point) – point
  • method (EdgeDistanceMethod) – metric used to compute distance to edge
Returns:

distance from point to edge according to distance metric

Return type:

float

core.get_balltree()

Generate a BallTree for a network that allows for fast generalized N-point problems, namely nearest nodes/edges search.

Parameters:network (nx.MultiDiGraph) – a street network
Returns:a spatial index for the network
Return type:sklearn.neighbors.BallTree
core.get_nodes_in_range(points, radius, tree=None)

Get nodes whose distance is within radius meters of a point, for a bunch of points. Vectorised.

Parameters:
  • network (nx.MultiDiGraph) – street network
  • points (array-like of Point) – array of points
  • radius (float) – maximum distance in meters
  • tree (sklearn.neighbors.BallTree) – ball-tree for quick nearest-neighbor lookup using the haversine formula
Returns:

nearest nodes (ids) and distances, sorted according to points

Return type:

np.ndarray, np.ndarray

core.get_edges_in_range(nodes_in_range)

Get edges whose nodes’ distance is within radius meters of a point, for a bunch of points. Vectorised.

Parameters:
  • network (nx.MultiDiGraph) – street network
  • nodes_in_range (np.ndarray) – ids of nodes in range, for a bunch of points
Returns:

list of set of nearest edges, sorted according to input nodes

Return type:

list of list of Edge

core.filter_by_address(edges, address=[])

Filter edges by address.

Parameters:
  • network (nx.MultiDiGraph) – street network
  • edges (array-like of Edge) – array of edges
  • address (str) –
Returns:

edges or a subset of edges

Return type:

list of Edge

core.local_coordinate_system(origin, nodes, edges)

Generate a local cartesian coordinate system from a set of nodes and edges.

Parameters:
  • network (nx.MultiDiGraph) – street network
  • origin (Point) – point
  • nodes (array-like) – ids of nodes
  • edges (array-like) – edges (u,v) to represent in new cartesian coordinate system
Returns:

nodes and edges represented in the new cartesian coordinate system

Return type:

np.ndarray, np.ndarray

core.gen_lsystem(origin, radius, address=None)

Generate a local cartesian coordinate system from a street network, centered around origin, whose nodes and edges within radius are represented as points and vectors in the new coordinate system.

Parameters:
  • network (nx.MultiDiGraph) – a street network
  • origin (Point) – point representing the origin of the new coordinate system (e.g. a traffic camera).
  • radius (float) – range of the local coordinate system, in meters.
  • address (string) – only include ‘candidate’ edges that match the given address
Returns:

lsystem – local coordinate system with the following key-values

nnodes:list of int nodes near the camera. These are composed of the nodes that are within the range the camera and nodes whose edges have a node that is within the range of the camera.
nedges:list of Edge edges near the camera. Edges which have at least 1 node within the range of the camera.
cedges:list of Edge edges considered as candidates for self.edge - the edge observed by the camera
lnodes:dict( int : np.ndarray ) nnodes represented in a cartesian coordinate system, whose origin is the camera
ledges:dict( Edge : np.ndarray ) cedges represented in a cartesian coordinate system, whose origin is the camera

Return type:

dict

core.flow_of_closest_lane(v, left_handed=True)

Calculates the direction of traffic flow of the nearest lane, on the road represented by the straight line that passes through points {u,v}. This depends on whether traffic is left or righ-handed.

For instance, consider an observer watching traffic in 2 traffic lanes, running in opposite directions, between two points: point one at 45 degrees of bearing and point 2 at 135 degrees of bearing. Then, if the traffic is left-handed, the closest of the two lanes is the one for which traffic flows from point 2 to point 1. If traffic is right-handed, then traffic is flowing from point 1 to point 2 in the closest of the two lanes (in reference to the observer - the origin of the coordinate system).

Parameters:
  • u (np.ndarray (2,)) – cartesian coordinates of point 1 relative to observer
  • v (np.ndarray (2,)) – cartesian coordinates of point 2 relative to observer
  • left_handed (bool) – True if the traffic keeps to the left side of the road, false otherwise.
Returns:

(u,v) if the closest lane corresponds to traffic flowing from u to v, (v,u) otherwise.

Return type:

tuple

core.estimate_camera_edge(lsystem, nsamples=100, radius=40, max_angle=40, left_handed_traffic=True, return_samples=False)

Estimate the edge of the road network that the camera is observing.

Points are sampled from each candidate edge and filtered based on whether the distance and angle to the camera is below the allowed maximum or not. With this, we can calculate the proportion of sampled points that fit this criteria and pick the edge(s) that maximises this proportion.

Parameters:
  • network (nx.MultiDiGraph) – a street network
  • lsystem (dict) – local coordinate system obtained using gen_lsystem
  • nsamples (int) – number of road points to sample when estimating the camera’s observed edge.
  • radius (int) – range of the camera, in meters. Usually limited to 50 meters.
  • max_angle (int) – max angle between the camera and the cars (plate number) travelling on the road, at which the ANPR camera can reliably operate.
  • left_handed_traffic (bool) – True if traffic flows on the left-hand side of the road, False otherwise.
  • return_samples (bool) – True if you want the sampled points to be returned together with the estimated edge and calculated proportions
Returns:

camera_edge, p_cedges, samples – the estimated camera edge, the calculated proportions for each of the candidate edges and, if return_samples, a dict with the sampled point for each candidate edge

Return type:

Edge, dict, dict

core.get_dead_end_nodes()

Get nodes representing dead ends in the street network.

These are not necessarily nodes with degree of 1, in the undirected representation of the street network,

Parameters:network (nx.MultiDiGraph) – A street network
Returns:network – The same network, but without dead end nodes and edges
Return type:nx.MultiDiGraph
core.remove_dead_end_nodes()

Remove nodes, and corresponding edges, representing dead ends in the street network.

Parameters:network (nx.MultiDiGraph) – A street network
Returns:network – The same network, but without dead end nodes and edges
Return type:nx.MultiDiGraph
core.add_address_details(drop_keys=['place_id', 'license', 'osm_type', 'osm_id', ' lat', 'lon', 'display_name', 'country', 'country_code', 'state', 'state_district', 'county', 'city'], email=None)

Lookup and the address details of every edge in the network and add them as attributes.

Depending on the size of the network, this method may incur a large number of requests and time to run. If anprx.settings[‘cache’] is set to True, as is by default, responses will be cached and subsequent calls to this method, for the same or intersecting networks, should be faster.

Parameters:
  • network (nx.MultiDiGraph) – A street network
  • drop_keys (list) – keys to ignore from the nominatim response containing address details
  • email (string) – Valid email address in case you are making a large number of requests
Returns:

network – The same network, but with additional edge attributes

Return type:

nx.MultiDiGraph

core.enrich_network(clean_dead_ends=True, elevation_api_key=None, drop_keys=['place_id', 'license', 'osm_type', 'osmid', ' lat', 'lon', 'display_name', 'country', 'country_code', 'state', 'state_district', 'county', 'city'], email=None, postcode_delim=' ')

Enrich a street network by adding further attributes to the edges in the network. These can then be used in clustering, compression, graph embeddings, shortest paths, etc.

Depending on the size of the network, this method may incur a large number of requests and time to run. If anprx.settings[‘cache’] is set to True, as is by default, responses will be cached and subsequent calls to this method, for the same or intersecting networks, should be faster.

Parameters:
  • network (nx.MultiDiGraph) – a street network
  • clean_dead_ends (bool) – true if dead end nodes should be removed from the graph
  • elevation_api_key (string) – Google API key necessary to access the Elevation API. If None, elevation.
  • drop_keys (list) – keys to ignore from the nominatim response containing address details
  • email (string) – Valid email address in case you are making a large number of requests.
  • postcode_delim (string) – postcode delimiter used to split the main postcode into two parts: outer and inner. Use None to skip postcode splitting.
Returns:

network – The same network, but with additional edge attributes

Return type:

nx.MultiDiGraph

anprx.plot

anprx.plot.plot_camera(camera, bbox_side=100, show_camera=True, camera_color='#FFFFFF', camera_marker='*', camera_markersize=10, annotate_camera=True, draw_radius=False, fig_height=6, fig_width=None, margin=0.02, bgcolor='k', node_color='#999999', node_edgecolor='none', node_zorder=2, node_size=50, node_alpha=1, edge_color='#555555', edge_linewidth=1.5, edge_alpha=1, probability_cmap=<sphinx.ext.autodoc.importer._MockObject object>, show_colorbar_label=True, draw_colorbar=True, draw_arrow=False, color_near_nodes=True, color_candidate_edges=True, nn_color='#66B3BA', nedge_color='#D0CE7C', labels_color='white', annotate_nn_id=False, annotate_nn_distance=True, adjust_text=True, save=False, file_format='png', filename=None, dpi=300)

Plot the camera on a networkx spatial graph.

Parameters:
  • bbox_side (int) – half the length of one side of the bbox (a square) in which to plot the camera. This value should usually be kept within small scales (hundreds of meters), otherwise near nodes and candidate edges become imperceptible.
  • camera_color (string) – the color of the point representing the location of the camera
  • camera_marker (string) – marker used to represent the camera
  • camera_markersize (int) – the size of the marker representing the camera
  • annotate_camera (True) – whether to annotate the camera or not using its id
  • draw_radius (bool) – whether to draw (kind of) a circle representing the range of the camera
  • bgcolor (string) – the background color of the figure and axis - passed to osmnx’s plot_graph
  • node_color (string) – the color of the nodes - passed to osmnx’s plot_graph
  • node_edgecolor (string) – the color of the node’s marker’s border - passed to osmnx’s plot_graph
  • node_zorder (int) – zorder to plot nodes, edges are always 2, so make node_zorder 1 to plot nodes beneath them or 3 to plot nodes atop them - passed to osmnx’s plot_graph
  • node_size (int) – the size of the nodes - passed to osmnx’s plot_graph
  • node_alpha (float) – the opacity of the nodes - passed to osmnx’s plot_graph
  • edge_color (string) – the color of the edges’ lines - passed to osmnx’s plot_graph
  • edge_linewidth (float) – the width of the edges’ lines - passed to osmnx’s plot_graph
  • edge_alpha (float) – the opacity of the edges’ lines - passed to osmnx’s plot_graph
  • probability_cmap (matplotlib colormap) – Colormap used to color candidate edges by probability of observation.
  • show_colorbar_label (bool) – whether to set the label of the colorbar or not
  • draw_colorbar (bool) – whether to plot a colorbar as a legend for probability_cmap
  • nn_color (string) – the color of near nodes - these are not necessarily in range of the camera, but they are part of edges that do
  • nedge_color (string) – the color of candidate edges - nearby edges filtered by address or other condition
  • labels_color (string) – the color of labels used to annotate nearby nodes
  • annotate_nn_id (bool) – whether the text annotating near nodes should include their id
  • annotate_nn_distance (bool) – whether the text annotating near nodes should include their distance from the camera
  • adjust_text (bool) – whether to optimise the location of the annotations, using adjustText.adjust_text, so that overlaps are avoided. Notice that this incurs considerable computational cost. Turning this feature off will result in much faster plotting.
  • save (bool) – whether to save the figure in the app folder’s images directory
  • file_format (string) – format of the image
  • filename (string) – filename of the figure to be saved. The default value is the camera’s id.
  • dpi (int) – resolution of the image
Returns:

fig, ax

Return type:

tuple

anprx.animate

anprx.animate.animate_camera(camera, bbox_side=100, camera_color='#FFFFFF', camera_marker='*', camera_markersize=10, annotate_camera=True, draw_radius=False, fig_height=9, fig_width=9, margin=0.02, bgcolor='k', node_color='#999999', node_edgecolor='none', node_zorder=2, node_size=50, node_alpha=1, edge_color='#555555', edge_linewidth=1.5, edge_alpha=1, labels_fontsize=8, probability_cmap=<sphinx.ext.autodoc.importer._MockObject object>, show_colorbar_label=True, draw_colorbar=True, nn_color='#66B3BA', nedge_color='#D0CE7C', labels_color='white', annotate_nn_id=False, annotate_nn_distance=True, adjust_text=True, save_as='mp4', filename=None, dpi=320, time_per_scene=5000, time_per_frame=250, progress=True, colorbar_rect=[0.125, 0.2, 0.2, 0.02], colorbar_ticks_fontsize=6, show_subtitle=True, subtitle_placement=(0.0, 0.05), subtitle_fontsize=12, sample_point_size=4, sample_valid_color='green', sample_invalid_color='red')

Generate an animation explaining the edge estimation procedure for the camera on a networkx spatial graph. The generated animation is not

Total number of scenes, in the animation, is 6 + number of candidate edges.

Parameters:
  • bbox_side (int) – half the length of one side of the bbox (a square) in which to plot the camera. This value should usually be kept within small scales (hundreds of meters), otherwise near nodes and candidate edges become imperceptible.
  • camera_color (string) – the color of the point representing the location of the camera
  • camera_marker (string) – marker used to represent the camera
  • camera_markersize (int) – the size of the marker representing the camera
  • annotate_camera (True) – whether to annotate the camera or not using its id
  • draw_radius (bool) – whether to draw (kind of) a circle representing the range of the camera
  • bgcolor (string) – the background color of the figure and axis - passed to osmnx’s plot_graph
  • node_color (string) – the color of the nodes - passed to osmnx’s plot_graph
  • node_edgecolor (string) – the color of the node’s marker’s border - passed to osmnx’s plot_graph
  • node_zorder (int) – zorder to plot nodes, edges are always 2, so make node_zorder 1 to plot nodes beneath them or 3 to plot nodes atop them - passed to osmnx’s plot_graph
  • node_size (int) – the size of the nodes - passed to osmnx’s plot_graph
  • node_alpha (float) – the opacity of the nodes - passed to osmnx’s plot_graph
  • edge_color (string) – the color of the edges’ lines - passed to osmnx’s plot_graph
  • edge_linewidth (float) – the width of the edges’ lines - passed to osmnx’s plot_graph
  • edge_alpha (float) – the opacity of the edges’ lines - passed to osmnx’s plot_graph
  • probability_cmap (matplotlib colormap) – Colormap used to color candidate edges by probability of observation.
  • show_colorbar_label (bool) – whether to set the label of the colorbar or not
  • draw_colorbar (bool) – whether to plot a colorbar as a legend for probability_cmap
  • nn_color (string) – the color of near nodes - these are not necessarily in range of the camera, but they are part of edges that do
  • nedge_color (string) – the color of candidate edges - nearby edges filtered by address or other condition
  • labels_color (string) – the color of labels used to annotate nearby nodes
  • annotate_nn_id (bool) – whether the text annotating near nodes should include their id
  • annotate_nn_distance (bool) – whether the text annotating near nodes should include their distance from the camera
  • adjust_text (bool) – whether to optimise the location of the annotations, using adjustText.adjust_text, so that overlaps are avoided. Notice that this incurs considerable computational cost. Turning this feature off will result in much faster plotting.
  • save_as (string) – format in which to save the animation in the app folder’s images directory. Choose ‘mp4’ to save the animation in mp4 format, using ffmpeg, ‘gif’ to save the animation in gif format, using imagemagick, or any other value to skip saving the animation.
  • filename (string) – filename of the figure to be saved. The default value is the camera’s id.
  • dpi (int) – resolution of the image, if saving the animation in ‘mp4’ format.
  • time_per_scene (int) – time per scene in milliseconds
  • time_per_frame (int) – time per frame in milliseconds. If time_per_scene = 250, then each scene has 20 frames. Most scenes just repeat the same frame, except the scenes for candidate edges - which plot a new sampled point per frame.
  • progress (bool) – if True then a bar will show the current progress of generating the animation.
  • colorbar_rect (list) – rectangle position of the colorbar as used by matplotlib.figure.add_axes
  • labels_fontsize (int) – fontsize of generic text labels (nodes, camera, colorbar)
  • colorbar_ticks_fontsize (int) – fontsize of colorbar ticks text
  • show_subtitle (bool) – if True show a text box explaining each scene
  • subtitle_placement (tuple) – (x,y) coordinates, in transformed axis, of where to place the subtitle text
  • subtitle_fontsize (int) – fontsize of subtitle text
  • sample_point_size (int) – marker size of points sampled in candidate edges
  • sample_point_valid_color (string) – color of sample points, in candidate edges, that fit the criteria: < camera.radius and < camera.max_angle
  • sample_invalid_color (string) – color of sample points, in candidate edges, that don’t fit the criteria: < camera.radius and < camera.max_angle
Returns:

anim

Return type:

FuncAnimation

anprx.nominatim

anprx.nominatim.lookup_address(osmids, entity, drop_keys=['place_id', 'license', 'osm_type', 'osm_id', ' lat', 'lon', 'display_name', 'country', 'country_code', 'state', 'state_district', 'county', 'city'], email=None)

Lookup the address of multiple OSM ids that share the same entity type.

Parameters:
  • osmids (array-like) – OSMids for address lookup. Hard limit of 50 ids as indicated in wiki.openstreetmap.org/wiki/Nominatim
  • drop_keys (list) – keys to ignore from the nominatim response containing address details
  • entity (string) – OSM entity of osmids. Valid values are ‘N’ for Node, ‘W’ for Way and ‘R’ for Relation.
  • email (string) – Valid email address in case you are making a large number of requests.
Returns:

details – Address details for each input osmid

Return type:

list of dict

anprx.nominatim.search_address(address, email=None)

Find the OpenStreetMap ways that match a given address.

Parameters:
  • address (string) – Address to search for
  • email (string) – Valid email address in case you are making a large number of requests.
Returns:

List of osm ids for ways that match the given address query

Return type:

list of int

anprx.helpers

anprx.helpers.angle_between(v1, v2)

Calculate the acute angle, in degrees, between two vectors. Vectorised for an array of vectors.

Parameters:
  • v1 (np.ndarray) – first vectors of each pair of vectors
  • v2 (np.ndarray) – second vectors of each pair of vectors
Returns:

acute angles between each pair of vectors

Return type:

np.ndarray

anprx.helpers.as_undirected(edges)

Represent a directed edge as undirected.

Parameters:edges (array-like of Edge) – array of directed edges (u,v,k)
Returns:
Return type:list of tuples
anprx.helpers.chunks(l, n)

Yield successive n-sized chunks from l.

Parameters:
  • l (list) –
  • n (size of chunk) –
Returns:

Return type:

generator

anprx.helpers.dot2d(v1, v2, method='einsum')

Vectorised dot product for 2d vectors.

Parameters:
  • v1 (np.ndarray) – vectors on the left side of the dot product
  • v2 (np.ndarray) – vectors on the right side of the dot product
  • method (string) – method used to compute the dot product between each pair of members in v1,v2. One of {‘einsum’, ‘loop’}
Returns:

result of the dot products

Return type:

np.ndarray

anprx.helpers.edges_with_all_properties(G, properties)

Find edges that match always in all property sets: (key, values)

Parameters:
  • G (nx.MultiDiGraph) – a (multidi)graph
  • properties (dict(str : set)) – properties of edges to filter by
Returns:

generator of edges

Return type:

generator of (u,v,k)

anprx.helpers.edges_with_at_least_one_property(G, properties)

Find edges that match at least once in all property sets: (key, values)

Parameters:
  • G (nx.MultiDiGraph) – a (multidi)graph
  • properties (dict(str : set)) – properties of edges to filter by
Returns:

generator of edges

Return type:

generator of (u,v,k)

anprx.helpers.edges_with_properties(G, properties, match_by=<PropertiesFilter.all: 1>)

Get edges with given properties

Parameters:
  • G (nx.MultiDiGraph) – a (multidi)graph
  • properties (dict(str : set)) – properties of edges to filter by
  • match_by (int) – One of const.FILTER_PROPERTIES.
Returns:

generator of edges

Return type:

generator of (u,v,k)

anprx.helpers.flatten(list_)

Flatten a list of objects which may contain other lists as elements.

Parameters:list (object) – list
Returns:
Return type:generator
anprx.helpers.flatten_dict(dict_, parent_key='', sep='_', inherit_parent_key=True)

Flatten a dict of objects which may contain other dicts as elements.

Parameters:dict (object) – dict Borrowed from https://stackoverflow.com/a/6027615
Returns:
Return type:generator
anprx.helpers.is_in(value, values_set)

Computes whether an object is present in, or has at least one element that is present in, values_set. This is equivalent to computing whether two sets intersect (not disjoint), but where value does not have to be a set.

Parameters:
  • value (object) – data dictionary
  • values_set (set) – set of values
Returns:

Return type:

bool

anprx.helpers.unit_vector(v)

Calculate the unit vector of an array or bunch of arrays.

Parameters:v (np.ndarray) – vector(s)
Returns:unit vector(s) of v
Return type:np.ndarray

anprx.constants

class anprx.constants.EdgeDistanceMethod

Bases: enum.Enum

An enumeration.

closest_node = 3
farthest_node = 4
mean_of_distances = 2
sum_of_distances = 1
class anprx.constants.PropertiesFilter

Bases: enum.Enum

An enumeration.

all = 1
at_least_one = 2
class anprx.constants.Units

Bases: enum.Enum

An enumeration.

km = 2
m = 1
anprx.constants.deg2distance(unit=<Units.km: 2>)
anprx.constants.deg2sq_distance(unit=<Units.m: 1>)
anprx.constants.earth_radius(unit=<Units.m: 1>)
anprx.constants.rad2distance(unit=<Units.m: 1>)

anprx.utils

exception anprx.utils.ImmutableSetting(*args, **kwargs)

Bases: ValueError

exception anprx.utils.InvalidSetting(*args, **kwargs)

Bases: ValueError

anprx.utils.clean_logger(name='anprx')

Removes all handlers associated with a given logger

Parameters:name (string) – name of the logger
Returns:
Return type:logger.logger
anprx.utils.config(**kwargs)

Configure anprx’s settings

Parameters:**kwargs – keyword arguments that exist in settings
Raises:InvalidSetting – if keyword argument is not in settings
Returns:
Return type:None
anprx.utils.create_folders(app_folder=None, logs_folder_name=None, data_folder_name=None, cache_folder_name=None, images_folder_name=None)

Creates app folders: parent, data, logs and cache

Parameters:
  • app_folder (string) – location of main app directory
  • logs_folder_name (string) – name of folder containing logs
  • data_folder_name (string) – name of folder containing data
  • cache_folder_name (string) – name of folder containing cached http responses
  • images_folder_name (string) – name of folder containing saved images
Returns:

Return type:

None

anprx.utils.get_from_cache(url)

Retrieve a HTTP response json object from the cache.

Parameters:url (string) – the url of the request
Returns:response_json
Return type:dict
anprx.utils.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 will set with OSMnx default
  • accept_language (str) – make accept-language explicit e.g. for consistent nominatim result sorting
Returns:

headers

Return type:

dict

anprx.utils.get_logger(level=None, name='anprx', filename='anprx')

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:

Return type:

logger.logger

anprx.utils.init_osmnx()

Configure osmnx’s settings to match anprx’s settings.

anprx.utils.log(message, level=None, name='anprx', filename='anprx')

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
Returns:

Return type:

None

anprx.utils.make_str(value)

Convert a passed-in value to unicode if Python 2, or string if Python 3.

Parameters:value (any) – the value to convert to unicode/string
Returns:
Return type:unicode or string
anprx.utils.save_fig(fig, axis, filename, file_format='png', dpi=300)

Save a figure to disk.

Parameters:
  • fig (figure) –
  • axis (axis) –
  • filename (str) – name of the file
  • file_format (str) – format of the file (e.g. ‘png’, ‘jpg’, ‘svg’)
  • dpi (int) – resolution of the image file
Returns:

Return type:

None

anprx.utils.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, so that the parameters stay in the same order each time, producing the same URL string, and thus the same hash. Otherwise the cache will eventually contain multiple saved responses for the same request because the URL’s parameters appeared in a different order each time.

Parameters:
  • url (string) – the url of the request
  • response_json (dict) – the json response
Returns:

Return type:

None