Shortest paths and matrices¶
Overview¶
The routing functions compute the cost of the shortest path, the path itself or both, from one source, from a set
of sources or between sets of origins and destinations. The cost is the sum of an edge column: time_min
(travel time in minutes, the default) or length_meter (network distance in metres). Every function takes an
UrbanGraph and returns pandas tables labelled by node ids or by the labels of the input objects.
Function |
Result |
|---|---|
Costs and paths from one node to every reachable node, or to the requested targets |
|
The same from a set of sources taken as one: every node gets the cost from its nearest source |
|
The nearest source of every node and the cost from it |
|
One independent row per source |
|
Costs or paths between origins and destinations: all pairs, or the pairs matched by position |
|
|
|
The edges of a node path, in order and with their geometry |
One path between two nodes, alternative routes and the k shortest routes are described in Routes between two points.
Inputs¶
Sources, origins and destinations are node ids (source_node, source_nodes, origins_nodes,
destination_nodes) or tables of objects (gdf_sources, gdf_origins, gdf_destinations). A table with
a graph_node_id column (the name is set by graph_node_column) is used as is; otherwise every geometry is
matched to its nearest graph node with nearest_nodes(). Objects matched to the same node share one search, and
the results keep the labels and the order of the input rows, duplicates included. To measure from the exact
position of an object on an edge, insert it into the graph first with project_objects2urban_graph()
(see Graph operations).
cutoff limits the cost of a path (inclusive, in the units of weight); nodes beyond it are not reached.
threshold is an alias of cutoff on the matrix functions. reverse=True searches against the edge
directions of a directed graph: the costs are then those of the paths from every node to the source.
Method¶
The graph is turned into a compressed sparse row (CSR) adjacency matrix of the selected weight. Parallel edges between two nodes, in either orientation of an undirected graph, are merged into one arc with the smallest cost. The matrix and its Rust copy are cached on the graph and reused for the same weight until the edge weights, directions or ends change (see The UrbanGraph model).
Every unique source runs one Dijkstra search in the Rust extension,
iduedu._rust. The searches of different sources run in parallel threads (max_workers, one per CPU by default) and stop once every requested target is settled or the next node lies beyondcutoff.An all-to-all matrix with fewer unique destinations than origins is computed from the destinations on the reversed graph, and the result is transposed back. A pairwise matrix (
mode="pairwise") searches only the pairs it needs; when most origins occur once, it runs one point-to-point search per pair (see Routes between two points).Costs are summed in float32.
dtypesets the type of the returned table only.
Outputs¶
output selects what a function returns:
"distances": costs, in a sparse pandas table by default. Unreachable pairs and pairs beyondcutoffholdinf; a node reached from itself costs0, and so do paths over zero-cost edges."paths": a sparse table of node paths. Each cell is a list of node ids from the source to the target, orNonewhen the target is not reached."both": aShortestPathResultwithdistancesandpathsfrom the same searches.
od_matrix() in frame format returns a table with the origins as rows and the destinations as columns. In pairwise mode the
table has a (origin, destination) index and one column, dist or path. Single-source and multi-source
results are Series indexed by node id; with target_nodes=None they contain the reachable nodes only. The tables
keep the node of every input object in attrs (origin_nodes, destination_nodes or source_nodes).
multi_source_dijkstra_nearest_source() returns the columns source_node (graph node id of the nearest
source) and dist; equal costs go to the source that comes first in the graph’s node order.
Use distance_format="dense" with output="distances" or output="both" to get a NumPy array with
np.inf for unreachable or out-of-cutoff pairs. For example, graph.od_matrix(origins_nodes=origins,
destination_nodes=targets, distance_format="dense", output="both", path_storage="lazy") stores the array
on result.distances. Array positions follow input order, including duplicates, and match get_path_at
and the pandas path table. Pairwise, single-source and multi-source dense arrays have one value per row.
All-to-all OD and parallel searches also support distance_format="sparse", a SciPy CSR array that
stores reachable costs, including explicit zeros. Never call eliminate_zeros. Use .tocoo() for
the row, col and data arrays. With target_nodes=None, parallel and single- or multi-source
arrays cover all nodes in graph.nodes_gdf order. The eager path table then also spans all nodes, so
prefer path_storage="lazy" for individual route lookups.
path_to_edges() turns a node path into the GeoDataFrame of its edges with the columns path_order,
path_u and path_v. Between parallel edges it takes the cheapest one by weight, as the search does, and
reverses the geometry of an edge travelled against its direction.
result = graph.od_matrix(
gdf_origins=buildings,
gdf_destinations=schools,
weight="time_min",
cutoff=30,
output="both",
)
result.distances # minutes, inf beyond 30
path = result.get_path(buildings.index[0], schools.index[0])
edges = graph.path_to_edges(path) # geometry of the route
Paths on demand¶
With output="both" and path_storage="lazy" the result keeps the search trees (the parent of every settled
node) and builds a path only when it is asked for: result.get_path(origin, destination) for one path,
result.paths for the whole table. Labels repeated in the input are reached by position with
result.get_path_at(row, column). The trees are copies, so a later change of the graph does not change saved
paths. A tree holds every node its search settled, so lazy storage saves memory when many paths share their
trees and only some of them are read.
Large matrices¶
batch_size limits the number of searches that run at the same time; the returned table and the kept trees still
hold every row. iter_od_matrix() takes the same arguments as od_matrix() and yields the result in blocks
of batch_size origin rows, so that each block can be written out and released:
import pandas as pd
nearest = []
for block in graph.iter_od_matrix(
gdf_origins=buildings, gdf_destinations=schools, cutoff=30, batch_size=2048
):
nearest.append(block.sparse.to_dense().min(axis=1)) # minutes to the nearest school
nearest = pd.concat(nearest)
Objects are matched to nodes once for all blocks. The graph must not change while the blocks are read. Each block
keeps its node mapping in attrs, and pandas compares attrs when it concatenates tables: clear them
(block.attrs = {}) before concatenating the blocks themselves.
Functions¶
Search from one node; return distances, paths, or both from one traversal. |
|
Search from the nearest member of one combined source set. |
|
Return nearest source_node and dist columns for each reachable node. |
|
Run independent searches, sharing work for sources mapped to the same node. |
|
Compute OD distances, node routes, or both with one search per unique source. |
|
Yield OD results in origin-row blocks, using the same options as od_matrix. |
|
Distances and paths from the same Dijkstra searches. |
|
Return one shortest node route, or [] when unreachable or beyond cutoff. |
|
Convert an ordered node path to ordered graph edges. |
Figures¶
Intermodal graph of Vasilyevsky Island (walking and public transport). Left: single_source_dijkstra()
from one place with cutoff=30 minutes; every street node is coloured by its travel time. Right:
multi_source_dijkstra_nearest_source() from the entrances of the three subway stations; every street node
takes the colour of the station whose entrance it reaches first.¶
Limitations¶
Costs are those stored on the edges: travel times do not depend on the time of day, turns cost nothing and public-transport waits are averages (see Public transport from OpenStreetMap and Public transport from GTFS).
Objects matched to their nearest node are placed at that node; the distance from the object to the node is not added. Project the objects onto the edges when it matters.
Equal-cost paths are resolved by the order of the search, so two runs of different functions can return different paths of the same cost.