Skip to content

network

A routable road network with stable edge ids.

quakecascade.network

Road network: build, snap, close edges and compute travel-time matrices.

RoadNetwork wraps the CSR graph and Dijkstra kernels ported from the PlanX engine (_graphs, _paths). It keeps a stable edge id for every input line (the caller's edge_id or the input row order), so a list of closed edges produced elsewhere (for example by debris blockage) can be removed with RoadNetwork.without and the matrices before and after the event compared node for node.

Conventions
  • Coordinates are metres in a projected CRS (a GeoDataFrame's CRS is checked with quakecascade.crs.require_metric).
  • inf in a cost matrix means unreachable on the network; NaN means not computed (the origin or target could not be snapped).
  • An edge whose cost cannot be computed (unknown road class, missing value) is left out of routing and reported with edge_status = "no_cost"; it is never given a substitute cost.

Speeds have no default table: speed_by_class takes the caller's class-to-km/h mapping.

INF module-attribute

INF = float('inf')

Travel cost of a pair with no path between them.

NO_GEOMETRY module-attribute

NO_GEOMETRY = contract.missing('geometry')

Edge status: the line has no usable geometry; the edge is left out.

NO_COST module-attribute

NO_COST = contract.missing('cost')

Edge status: the cost is NaN or negative (for example an unknown road class); the edge is left out.

NO_NODE module-attribute

NO_NODE = contract.missing('node')

Snap status: the point is farther than the snapping distance from every node.

NO_XY module-attribute

NO_XY = contract.missing('xy')

Snap status: the point has no finite coordinates.

CostSpec module-attribute

CostSpec = Any

How a routing cost is given: None (length in metres), a column name, a callable f(attributes_frame, length_m) -> array or one value per line.

NodeGraph

NodeGraph(
    node_xy,
    edge_from,
    edge_to,
    edge_cost,
    edge_len,
    reverse_cost=None,
    directions=None,
)

Weighted graph over polyline endpoints; optionally directed per edge.

edge_direction holds 0 (both ways), 1 (coordinate order only) or -1 (reverse only). adj_edge maps each CSR entry back to its edge index.

num_nodes property

num_nodes

Number of graph nodes.

num_edges property

num_edges

Number of edges (one per input segment, direction kept in edge_direction).

degrees

degrees()

Out-degree per node in the CSR (an undirected edge counts once per end).

RoadNetwork

RoadNetwork(
    *,
    node_xy,
    part_from,
    part_to,
    part_len,
    part_cost,
    part_rev_cost,
    part_dir,
    part_row,
    edges,
    crs=None,
    cost_unit="",
    closed=None,
    excluded=None,
    snap_mask=None,
)

A routable road network with stable edge ids.

Build it with from_lines. Every derived network (without, largest_component) keeps the same node table, so node ids from snap stay valid across the pre- and post-event networks and a cut road shows up as inf, not as a different snap.

n_nodes property

n_nodes

Number of nodes (shared by every derived network).

n_edges property

n_edges

Number of input lines (edge ids).

edges property

edges

Per input line: id, length, costs, oneway, status, closed, routed.

closed_edge_ids property

closed_edge_ids

Edge ids removed with without.

graph property

graph

CSR graph of the routed edges (built once, cached).

from_lines classmethod

from_lines(
    lines,
    cost=None,
    *,
    reverse_cost=None,
    edge_id=None,
    oneway=None,
    snap_tolerance_m=0.01,
    crs=None,
)

Build a network from road lines.

Parameters:

Name Type Description Default
lines (GeoDataFrame, GeoSeries or sequence)

LineStrings (MultiLineStrings are split into parts that share the row's edge id) or (k, 2) coordinate arrays, in metres. A GeoDataFrame/GeoSeries must carry a metric CRS.

required
cost (None, str, callable or array_like)

Routing cost per line in the forward (coordinate) direction: None = length in metres; a column name; a callable f(attributes_frame, length_m) -> array such as speed_by_class; or one value per line. NaN or negative costs exclude the line (edge_status = "no_cost").

None
reverse_cost same as ``cost``

Cost against the coordinate order; defaults to cost.

None
edge_id str or array_like

Stable id per line (column name or values); defaults to the row position 0..n-1. Ids must be unique.

None
oneway str or array_like

Per line 0/False = both ways, 1/True = coordinate order only, -1 = reverse only.

None
snap_tolerance_m float

An end point within this distance of an existing node joins the nearest one (leader clustering, no chaining). The default 1 cm only merges digitising round-off; it does not join lines that do not touch.

0.01
crs optional

CRS of plain geometries; checked to be metric when given.

None

without

without(edge_ids, strict=True)

A new network with the given edges closed (removed from routing).

Parameters:

Name Type Description Default
edge_ids iterable

Edge ids as given to from_lines (or row positions when no edge_id was given).

required
strict bool

Raise KeyError for ids the network does not know; with False they are ignored.

True

largest_component

largest_component()

A new network keeping only the largest weakly connected component.

Nodes keep their ids; only nodes of that component remain snap targets, and edges outside it are no longer routed.

snap

snap(points_xy, max_dist_m=None)

Snap points to their nearest network node.

Parameters:

Name Type Description Default
points_xy (M, 2) array, sequence of shapely Points or GeoSeries

Coordinates in the network CRS (metres).

required
max_dist_m float

Largest accepted snap distance. Required: how far a point may be from the road graph is a property of the data, not of the method.

None

Returns:

Type Description
DataFrame

node (-1 when not snapped), snap_dist_m (NaN when not snapped), nearest_dist_m (distance to the nearest candidate node even when beyond the limit) and snap_status: computed, no_node (nearest node farther than max_dist_m or no node at all) or no_xy (non-finite input).

travel_time_matrix

travel_time_matrix(
    origins,
    targets,
    limit_s=None,
    max_snap_m=None,
    cancel=None,
)

Network cost from every origin to every target.

Parameters:

Name Type Description Default
origins node ids, (M, 2) coordinates or a <autoref identifier="quakecascade.network.RoadNetwork.snap" optional><code>snap</code></autoref> frame

Integer 1-D arrays are node ids (-1 = not snapped); coordinates are snapped with max_snap_m.

required
targets node ids, (M, 2) coordinates or a <autoref identifier="quakecascade.network.RoadNetwork.snap" optional><code>snap</code></autoref> frame

Integer 1-D arrays are node ids (-1 = not snapped); coordinates are snapped with max_snap_m.

required
limit_s float

Costs above it are inf (unreachable within the limit). The unit is the network's cost unit (seconds for a speed-based cost).

None
max_snap_m float

Snap distance for coordinate inputs (required for them).

None
cancel callable

Polled between origin blocks; see _paths.many_to_many.

None

Returns:

Type Description
(ndarray, shape(n_origins, n_targets))

inf where unreachable, NaN where the origin or target was not snapped.

nearest

nearest(origins, targets, limit_s=None, max_snap_m=None)

Cost from each origin to its nearest target, with one multi-source search.

The search starts at the targets and runs over the reversed graph, so one-way streets and direction-dependent costs (e.g. tobler_walk_cost) are measured from origin to target, exactly as travel_time_matrix(...).min(axis=1).

Returns a frame with nearest_time, nearest_target (position in targets, -1 if none) and nearest_status, with the semantics of quakecascade.access.nearest_time: computed (inf when no target is reachable); partial when some targets could not be snapped (the time is an upper bound); no_travel_time (NaN) when none of the snapped targets is reachable and some targets are unknown; no_node (NaN) for an origin that could not be snapped.

shortest_path

shortest_path(origin, target, limit_s=None)

Cost and edge ids of the shortest route between two nodes.

Returns (cost, edge_ids); (inf, []) when unreachable. A MultiLineString row traversed in several parts appears once. Node ids outside 0..n_nodes - 1 (such as -1 for an unsnapped point) raise IndexError.

build_node_graph

build_node_graph(
    polylines,
    tolerance=0.01,
    costs=None,
    reverse_costs=None,
    directions=None,
)

Build the primal graph from a list of (k_i, 2) coordinate arrays.

An endpoint within tolerance (Euclidean, in the coordinate units) of an existing node joins the nearest one; otherwise it starts a new node at its own coordinates (leader clustering: no chaining, every endpoint of a node lies within tolerance of the node). costs (optional, one per polyline) replaces length as the routing cost; the metric length is always kept. directions uses 0 = both, 1 = coordinate order only, -1 = reverse only.

component_labels

component_labels(graph)

Weak components, SciPy connected_components when available.

Both paths return the same partition; label numbers may differ.

nearest_nodes

nearest_nodes(node_xy, points, candidates=None)

Nearest node of node_xy for each of points.

Parameters:

Name Type Description Default
node_xy (N, 2) array

Node coordinates.

required
points (M, 2) array

Query coordinates; rows with a non-finite coordinate get id -1 and distance NaN.

required
candidates (N,) bool array

Only these nodes may be returned.

None

Returns:

Name Type Description
ids (M,) int64

Node id, -1 where no candidate exists or the point is not finite.

dist (M,) float64

Euclidean distance to that node (coordinate units).

weak_components

weak_components(graph)

Weak component id per node and the component count (pure Python walk).

many_to_many

many_to_many(
    indptr,
    adj,
    weights,
    n,
    sources,
    cutoff=None,
    cancel=None,
)

Distances from each source to every node, shape (len(sources), n).

Parameters:

Name Type Description Default
indptr array_like

CSR adjacency (row pointer, column index, edge weight).

required
adj array_like

CSR adjacency (row pointer, column index, edge weight).

required
weights array_like

CSR adjacency (row pointer, column index, edge weight).

required
n int

Number of nodes.

required
sources array_like of int

Source node ids.

required
cutoff float

Costs above it are reported as inf.

None
cancel callable

Polled between sources (between blocks of 256 sources on the SciPy path); when it returns True quakecascade._compat.Cancelled is raised with the rows not yet computed filled with inf.

None

multi_source

multi_source(indptr, adj, weights, n, sources, cutoff=None)

Minimum cost from any source.

Returns (dist[n], nearest_source_pos[n]); nearest_source_pos is the position in sources of the winning source (-1 where unreachable).

reconstruct_path

reconstruct_path(pred_node, pred_edge, source, target)

Walk the predecessor arrays back from target to source.

Returns (nodes, edges) in travel order (nodes has one more entry than edges); both empty when the target is unreachable.

shortest_path_tree

shortest_path_tree(
    indptr,
    adj_node,
    adj_edge,
    weights,
    n,
    source,
    cutoff=None,
)

Dijkstra with predecessor tracking for route reconstruction.

Returns (dist, pred_node, pred_edge): for every node its cost from source, the previous node on the shortest path and the id of the edge used to arrive (both -1 at the source and where unreachable). Pure heapq on purpose: it must report which parallel edge was taken, which the SciPy kernel cannot; distances equal many_to_many.

tobler_walk_speed

tobler_walk_speed(slope)

Walking speed in km/h from Tobler's hiking function.

\(v = 6\,\exp(-3.5\,|s + 0.05|)\) km/h, with s the signed grade (rise over run, a fraction, positive uphill in the direction of travel). The maximum, 6 km/h, is reached at s = -0.05.

Source: Tobler, W. (1993). Three presentations on geographical analysis and modeling. NCGIA Technical Report 93-1, Eq. on p. 2 ("hiking function"). Ported from PlanX engine/comfort.tobler_speed.

Parameters:

Name Type Description Default
slope float or array_like

Signed grade as a fraction (0.10 = 10 % uphill). NaN stays NaN.

required

speed_by_class

speed_by_class(mapping, column)

Cost callable giving travel seconds from a road-class speed mapping.

Parameters:

Name Type Description Default
mapping mapping

Road class -> free-flow speed in km/h, supplied by the caller (there is no default table: speeds are a local planning choice).

required
column str

Attribute column holding the class of each line.

required

Returns:

Type Description
callable

f(frame, length_m) -> seconds; a class missing from mapping gives NaN, so that edge is reported no_cost and not routed.

tobler_walk_cost

tobler_walk_cost(slope_column, reverse=False)

Cost callable giving walking seconds with tobler_walk_speed.

slope_column holds the signed grade in the line's coordinate order. Use reverse=True for the reverse_cost of the same network (the grade changes sign when walked the other way).