Submodules

anprx.core

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

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. Calculated by estimate_edge.

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

nsamples

int – number of road points to sample when estimating the camera’s observed edge.

filter_by_address

bool – if True, excludes candidate edges whose address is different than the one manually annotated by traffic engineers

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) – probability of each candidate edge that it is the edge that the camera is observing

__init__(network, id, point, address=None, radius=40, max_angle=40, nsamples=100, left_handed_traffic=True, filter_by_address=False)
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
  • 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.
  • filter_by_address (Filter) – filter nearby edges according to a criteria. For instance, using Filter.address exclude edges whose address is different than the one manually annotated by traffic engineers.
estimate_edge()

Estimate the edge of the road network that the camera is observing. Executed by __init__.

Points are sampled from each candidate edge, are filtered based on whether the distance and angle to the camera is below the maximum. The probability, that a candidate edge is the true edge, is then just the proportion of sampled points that fit this criteria.

gen_local_coord_system()

Find nearest nodes and edges, and encode them in a cartesian system whose origin is the camera. Executed by __init__.

plot(bbox_side=100, 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, 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='camera', 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
  • dpi (int) – resolution of the image
Returns:

fig, ax

Return type:

tuple

anprx.navigation

class anprx.navigation.Point(lat, lng)

Bases: tuple

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

Bases: tuple

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

Bases: tuple

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

Bases: tuple

navigation.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
navigation.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
navigation.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

navigation.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

navigation.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) – nvector of the 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

navigation.get_bbox_area(unit=<Units.km: 2>, method=<BBoxAreaMethod.simple: 1>)

Calculate the area of a bounding boxself. Choose one of two possible methods:

anpx.constants.BBoxAreaMethod.simple

Calculate the area as a rectangle using length as latitude difference and width as longitude difference corrected by mean latitude point.

anpx.constants.BBoxAreaMethod.sins

As explained in: http://mathfax.com/area-of-a-latitude-longitude-rectangle/

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

area in provided units

Return type:

float

navigation.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
navigation.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

navigation.get_surrounding_network(rel_margins=RelativeMargins(north=0.025, south=0.025, east=0.025, west=0.025), min_area=0.01, max_area=10, 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

navigation.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

navigation.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

navigation.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
navigation.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

navigation.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

navigation.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

navigation.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

anprx.nominatim

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

Find the OpenStreetMap ways that match a given address.

Parameters:
  • address – Address to search for
  • email – Valid email address in case you are making large number of
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.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.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.BBoxAreaMethod

Bases: enum.Enum

An enumeration.

simple = 1
sins = 2
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