aequilibrae.routing#
Functions
Return the priority queue implementations. |
|
|
Calculate a conservative A* coefficient. |
Classes
|
One routing context with fixed topology and mappings to source links. |
|
A transportation network. |
|
|
|
Path computation result holder. |
Network skimming result holder. |
- class aequilibrae.routing.Graph(routing: GraphContext, mapping: GraphMapping, skimming: SkimmingContext, mode: str, cost_field: str | None = None)[source]#
One routing context with fixed topology and mappings to source links.
Create graphs with
Network.build_graph(). Network tables and construction intermediates are not retained. Routing, correspondence and skim fields belong to their respective sub-objects. Reconstruct the graph to change its configuration; routing costs can still be rebound independently of the fixed topology.- compute_path(origin: int, destination: int, **kwargs: object) PathResults[source]#
Compute a path with nodes and mileposts on this built graph.
Additional arguments are passed to
PathResults, including explicit coordinates and a heuristic scale when using A*.
- compute_skims(cores: int | None = None) NetworkSkimming[source]#
Compute centroid skims using this graph’s routing and skim contexts.
- disconnected_nodes() ndarray[source]#
Identify nodes unable to reach and be reached from the main network.
The largest strongly connected component selects the main network. Blocked centroids can be endpoints, but cannot connect other nodes through themselves. Individual turn restrictions are not considered. With no active links, only the first retained node is considered connected.
- Returns:
Disconnected external node IDs in retained graph-node order.
- selected_links(selections: Mapping[str, Iterable[tuple[int, int]]]) dict[str, ndarray[tuple[Any, ...], dtype[int64]]][source]#
Resolve named source-link selections, raising for links absent from this graph.
- set_costs(costs: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str]) None[source]#
Replace directed network costs. Positive infinity closes a link.
- property all_nodes: ndarray[tuple[Any, ...], dtype[uint64]]#
- property allow_uturns: bool#
Whether U-turns were allowed when building the routing context.
- property block_centroid_flows: bool#
Whether the build requested blocking travel through centroids.
- property centroid_count: int#
Number of centroids supplied when building the routing context.
- property centroids: ndarray[tuple[Any, ...], dtype[uint64]]#
- property compact: bool#
Whether link contraction was requested when building the mapping.
- property cost: ndarray[tuple[Any, ...], dtype[float64]]#
- cost_field: str | None = None#
- property has_turn_restrictions: bool#
- mapping: GraphMapping#
- mode: str#
- property num_links: int#
- property num_nodes: int#
- property num_zones: int#
- property remove_dead_ends: bool#
Whether dead-end removal was requested when building the mapping.
- routing: GraphContext#
- property skim_fields: list[str]#
- skimming: SkimmingContext#
- class aequilibrae.routing.Network(links: DataFrame, *, modes: str | Iterable[str] | None = None, centroids: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | None = None, turn_restrictions: DataFrame | None = None, allow_uturns: bool = False, lonlat: DataFrame | None = None)[source]#
A transportation network.
Stores link attributes, travel modes, demand centroids, node coordinates and turn restrictions. The same network can support graphs with different modes, costs, skim fields and centroid-flow policies, while retaining a consistent directed-link order for costs and reported results. Modes are single-character mode codes, not mode names.
- build_graph(mode: str, cost: str | None = None, *, centroids: ArrayLike | None = None, skimming: str | Iterable[str] = (), compact: bool = False, remove_dead_ends: bool = False, block_centroid_flows: bool = True, turn_restrictions: pd.DataFrame | None = None, allow_uturns: bool | None = None) Graph[source]#
Prepare one routing graph from the stored source tables.
modeis a single-character mode code, not a mode name. Costs use the named field.Graph.set_costs()accepts replacement arrays in directed network order, including infinity for link closures. Link contraction (compact) and dead-end removal are independent, opt-in reductions. Both retain centroids and require them to be supplied. Mappings expand every retained graph link back to its source links.
- field_values(field: str) ndarray[tuple[Any, ...], dtype[float64]][source]#
Return numeric values in the shared mapping’s directed network order.
- validate_centroids(centroids: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str]) None[source]#
- allow_uturns: bool = False#
- centroids: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | None = None#
- property directions: ndarray[tuple[Any, ...], dtype[int8]]#
- property fields: list[str]#
- property link_ids: ndarray[tuple[Any, ...], dtype[uint64]]#
- links: DataFrame#
- lonlat: DataFrame | None = None#
- mapping: NetworkMapping#
- modes: str | Iterable[str] | None = None#
- turn_restrictions: DataFrame | None = None#
- class aequilibrae.routing.NetworkSkimming(graph: Graph, origins=None, project=None)[source]#
>>> from aequilibrae.routing import NetworkSkimming >>> project = create_example(project_path) >>> graph = project.road.build_graph('c', 'distance', skimming=['distance'], compact=True) >>> skm = NetworkSkimming(graph) >>> skm.execute() # The skim report (if any error generated) is available here >>> skm.report [] # To access the in-memory skim matrix >>> matrix = skm.results.skims # Or you can save the results to disk >>> matrix.save_as_omx(project_path / 'skimming_result.omx') >>> project.close()
- set_cores(cores: int) None[source]#
Sets number of cores (threads) to be used in computation
Value of zero sets number of threads to all available in the system, while negative values indicate the number of threads to be left out of the computational effort.
Resulting number of cores will be adjusted to a minimum of zero or the maximum available in the system if the inputs result in values outside those limits
- Arguments:
cores (
int): Number of cores to be used in computation
- signal = <aequilibrae.utils.python_signal.PythonSignal object>#
- class aequilibrae.routing.PathResults(graph: Graph, origin: int, destination: int, early_exit: bool = False, a_star: bool = False, heuristic: str | None = None, heap: str | None = None, *, coordinates: DataFrame | None = None, heuristic_scale: float | None = None)[source]#
Path computation result holder.
pathcontains local graph-link indices. Useget_network_links()to obtain physical link IDs and directions, expanding any contracted chains.path_nodesandmilepostdescribe the retained graph nodes on the path.>>> from aequilibrae.routing import PathResults >>> project = create_example(project_path) >>> graph = project.road.build_graph( ... 'c', 'distance', skimming=['distance', 'free_flow_time'] ... ) >>> res = PathResults(graph, 1, 17) >>> res.update_trace(9) >>> project.close()
- compute_path(origin: int, destination: int, early_exit: bool = False, a_star: bool = False, heuristic: str | None = None, heap: str | None = None, *, heuristic_scale: float | None = None) None[source]#
Search the prepared graph and trace a path between external IDs.
With
early_exit, stop when the destination is finalised. Other missing terminals may still be reachable.update_tracewill search again if needed. For A*, a scale above a consistent bound can give non-shortest paths. Useaequilibrae.routing.estimate_heuristic_scale()to calculate a conservative coefficient before searching.- Arguments:
origin (
int): External ID of the search origin.destination (
int): External ID of the traced destination.early_exit (
bool): Stop after finalising the destination.a_star (
bool): Whether to use A* for this search.- heuristic (
stror None):euclideanorhaversine. None uses the selection from
heap (
stror None): Priority queue implementation to use.heuristic_scale (
floator None): Finite, nonnegative coefficient required for A*.- heuristic (
- Returns:
None. The search arrays, skims and traced path are updated in place.- Raises:
KeyError: If an external node ID is not in the prepared graph. ValueError: If required A* coordinates or the explicit scale are invalid.
- get_heaps() list[str][source]#
Return the available priority queue implementation names.
- Returns:
list[str]: Names accepted byset_heap().
- get_heuristics() list[str][source]#
Return the available A* heuristic names.
- Returns:
list[str]: Names accepted byset_heuristic().
- get_network_links() tuple[ndarray, ndarray] | None[source]#
Return network link IDs and directions for the currently traced path.
Compact graph links are expanded in traversal order.
- Returns:
A tuple of
(link_ids, directions)arrays, with directions +1 or -1. ReturnsNonewhen no path is available, and two empty arrays for a path from a node to itself.
- reset() None[source]#
Clear search results, paths, labels and skims in place.
- Returns:
None. Allocated result buffers and their read-only views remain valid, but contain their reset sentinel or infinity values.
- set_graph_data(graph: Graph, *, coordinates: DataFrame | None = None) None[source]#
Prepare graph data for path and skim computation.
- Arguments:
- graph (
Graph): Prepared graph with a cost field. Fixed topology, mappings and skim fields are shared.
- coordinates (
pandas.DataFrame, optional):xandycolumns for Euclidean A*, orlon and
latcolumns in degrees for Haversine A*, indexed by external node ID. Copied for later searches.
- graph (
- Returns:
None. The existing result buffers are replaced and cleared before the next search.- Raises:
- ValueError: If the graph does not have context-compatible IDs or a required node/link mapping is
invalid.
- set_heap(heap: str) None[source]#
Select the priority queue implementation used for path computation.
- Arguments:
heap (
str): Name returned byget_heaps().- Returns:
None. The selected heap is used by subsequent searches.
- set_heuristic(heuristic: str) None[source]#
Select the heuristic used by A* path computation.
- Arguments:
heuristic (
str): Name returned byget_heuristics().- Returns:
None. The selected heuristic is used by subsequent A* searches.
- update_trace(destination: int) None[source]#
Update the traced destination using the current search tree.
A partial early-exit search is rerun when it has not finalised the requested destination, retaining its algorithm, heuristic, scale and heap. A full search reuses its finalised state tree.
- Arguments:
destination (
int): External ID of the new destination.- Returns:
None.path,path_nodesandmilepostare replaced for the requested destination.- Raises:
RuntimeError: If no search has been performed. KeyError: If the destination is not in the prepared graph.
- property connectors: ndarray#
- property distances: ndarray#
- property node_ids: ndarray#
External node IDs in context and skim destination order.
- property predecessors: ndarray#
- property settlement_order: ndarray#
- property terminal_states: ndarray#
- property turn_costs: ndarray#
- class aequilibrae.routing.SkimResults[source]#
Network skimming result holder.
>>> from aequilibrae.routing import SkimResults >>> project = create_example(project_path) # Mode c is car in this project # minimize travel time # Skims travel time and distance >>> car_graph = project.road.build_graph( ... 'c', 'free_flow_time', skimming=['free_flow_time', 'distance'], compact=True ... ) >>> res = SkimResults() >>> res.prepare(car_graph) >>> res.skims.save_as_omx(project_path / "skim_matrices.omx") >>> project.close()
- prepare(graph: Graph, output: SkimmingOutputs | None = None)[source]#
Prepares the object with dimensions corresponding to the graph objects
- Arguments:
graph (
Graph): Needs to have been set with number of centroids and list of skims (if any)output (
SkimmingOutputs, Optional): Existing output buffer to share.
- aequilibrae.routing.available_heaps() list#
Return the priority queue implementations.
- aequilibrae.routing.estimate_heuristic_scale(graph, coordinates=None, *, heuristic='euclidean') float[source]#
Calculate a conservative A* coefficient.
- Arguments:
graph (
Graph): Prepared graph with a nonnegative cost field.- coordinates (
pandas.DataFrame):xandycolumns for Euclidean distance, or
lonandlatcolumns in degrees for Haversine distance, indexed by external node ID. Required for either heuristic. All retained graph nodes must be present in one common coordinate system.
heuristic (
str):euclidean(default) orhaversine.- coordinates (
- Returns:
float: The smallest finite link cost divided by its positiveendpoint distance, with a small round-off margin. Zero is returned if there are no such bounds. A zero-cost link can also force a zero scale.
This bound works for every destination, including nonnegative turn costs. It ignores turn and centroid restrictions, which can only remove paths or increase their costs. Recalculate after changing coordinates or decreasing link costs. Project geographic geometry to a suitable local CRS before supplying x/y.