import numpy as np
import pandas as pd
from aequilibrae.routing.cython.a_star import a_star as run_a_star
from aequilibrae.routing.cython.a_star import validate_scale
from aequilibrae.routing.cython.dijkstra import available_heaps, dijkstra
from aequilibrae.routing.cython.search_query import SearchQuery
from aequilibrae.routing.cython.search_results import SearchResults
from aequilibrae.routing.cython.skimming import skimming
from aequilibrae.routing.cython.workspaces import AStarWorkspace, SearchWorkspace, SkimmingWorkspace
from aequilibrae.routing.graph import Graph
from aequilibrae.routing.path_heuristics import HEURISTICS, make_heuristic_context
[docs]
class PathResults:
"""Path computation result holder.
``path`` contains local graph-link indices. Use ``get_network_links()`` to
obtain physical link IDs and directions, expanding any contracted chains.
``path_nodes`` and ``milepost`` describe the retained graph nodes on the path.
.. code-block:: python
>>> 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()
"""
def __init__(
self,
graph: Graph,
origin: int,
destination: int,
early_exit: bool = False,
a_star: bool = False,
heuristic: str | None = None,
heap: str | None = None,
*,
coordinates: pd.DataFrame | None = None,
heuristic_scale: float | None = None,
) -> None:
"""
Prepare graph data and compute the initial path.
:Arguments:
**graph** (:obj:`Graph`): Prepared graph with a cost field.
**origin** (:obj:`int`): External ID of the path origin.
**destination** (:obj:`int`): External ID of the initial destination.
**early_exit** (:obj:`bool`): Stop after finalising the destination.
**a_star** (:obj:`bool`): Whether to use A* for this search.
**heuristic** (:obj:`str` or None): ``euclidean`` (default) or ``haversine``.
**heap** (:obj:`str` or None): Priority queue implementation to use.
**coordinates** (:obj:`pandas.DataFrame`, optional): Planar ``x`` and ``y`` columns for Euclidean A*,
or ``lon`` and ``lat`` columns in degrees for Haversine A*, indexed by external node ID.
Required for either A* heuristic. Coordinates are not retained by the graph.
**heuristic_scale** (:obj:`float` or None): Explicit nonnegative, finite coefficient required for
A*. Converts coordinate distance into cost units. A value above a consistent bound can give non-shortest
paths. Use ``estimate_heuristic_scale`` to calculate a conservative coefficient.
:Raises:
**KeyError**: If an external node ID is not in the graph.
**ValueError**: If required A* coordinates or the explicit scale are invalid.
"""
self._check_search_options(a_star, heuristic, heap, heuristic_scale)
self._heap = "4ary"
self._heuristic = "euclidean"
self.set_graph_data(graph, coordinates=coordinates)
if heap is not None:
self.set_heap(heap)
if heuristic is not None:
self.set_heuristic(heuristic)
self.compute_path(
origin,
destination,
early_exit=early_exit,
a_star=a_star,
heuristic=heuristic,
heuristic_scale=heuristic_scale,
)
@staticmethod
def _check_search_options(a_star, heuristic, heap, heuristic_scale):
if heuristic is not None and heuristic not in HEURISTICS:
raise ValueError(f"heuristic must be one of {list(HEURISTICS)}")
if a_star or heuristic_scale is not None:
validate_scale(heuristic_scale)
if heap is not None and heap not in available_heaps():
raise ValueError(f"heap must be one of {available_heaps()}")
[docs]
def set_graph_data(self, graph: Graph, *, coordinates: pd.DataFrame | None = None) -> None:
"""
Prepare graph data for path and skim computation.
:Arguments:
**graph** (:obj:`Graph`): Prepared graph with a cost field. Fixed topology, mappings and skim fields are
shared.
**coordinates** (:obj:`pandas.DataFrame`, optional): ``x`` and ``y`` columns for Euclidean A*, or ``lon``
and ``lat`` columns in degrees for Haversine A*, indexed by external node ID. Copied for later searches.
: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.
"""
if not isinstance(graph, Graph):
raise TypeError("graph must be a Graph built by Network.build_graph()")
costs = graph.cost.copy()
costs.flags.writeable = False
context = graph.routing.with_costs(costs)
skim_context = graph.skimming
coordinates = coordinates.copy() if coordinates is not None else None
self.context = context
self._mapping = graph.mapping
self._coordinates = coordinates
self._a_star_context = None
self._a_star_context_key = None
self.nodes = context.node_count
self.links = context.link_count
self.num_skims = len(skim_context.field_names)
self.search_results = SearchResults(self.nodes, context.state_count, self.links)
self._workspace = None
self._skimming = skim_context
self._skim_workspace = (
SkimmingWorkspace(context.state_count, skim_context.additive_field_count)
if skim_context.additive_field_count
else None
)
self.skims = skim_context.make_outputs(self.nodes) if self.num_skims else None
self.reset()
[docs]
def compute_path(
self,
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:
"""
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_trace`` will search again if needed. For A*, a scale above a consistent bound can give non-shortest
paths. Use :func:`aequilibrae.routing.estimate_heuristic_scale` to calculate a conservative coefficient before
searching.
:Arguments:
**origin** (:obj:`int`): External ID of the search origin.
**destination** (:obj:`int`): External ID of the traced destination.
**early_exit** (:obj:`bool`): Stop after finalising the destination.
**a_star** (:obj:`bool`): Whether to use A* for this search.
**heuristic** (:obj:`str` or None): ``euclidean`` or ``haversine``. None uses the selection from
:meth:`set_heuristic`.
**heap** (:obj:`str` or None): Priority queue implementation to use.
**heuristic_scale** (:obj:`float` or None): Finite, nonnegative coefficient required for A*.
: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.
"""
self._check_search_options(a_star, heuristic, heap, heuristic_scale)
selected_heap = self._heap if heap is None else heap
selected_heuristic = self._heuristic if heuristic is None else heuristic
origin_index = self._mapping.graph_node(origin)
destination_index = self._mapping.graph_node(destination)
targets = None
if early_exit or a_star:
targets = np.zeros(self.nodes, dtype=bool)
targets[destination_index] = True
query = SearchQuery(self.nodes, origin_index, targets)
if a_star:
heuristic_scale = validate_scale(heuristic_scale)
key = (selected_heuristic, heuristic_scale)
if self._a_star_context_key != key:
self._a_star_context = make_heuristic_context(
self.node_ids,
self._coordinates,
selected_heuristic,
heuristic_scale,
)
self._a_star_context_key = key
if not isinstance(self._workspace, AStarWorkspace) or self._workspace.heap != selected_heap:
self._workspace = AStarWorkspace(self.nodes, self.context.state_count, heap=selected_heap)
run_a_star(
self.context,
query,
destination_index,
self._a_star_context,
self.search_results,
self._workspace,
)
else:
if (
self._workspace is None
or isinstance(self._workspace, AStarWorkspace)
or self._workspace.heap != selected_heap
):
self._workspace = SearchWorkspace(self.nodes, self.context.state_count, heap=selected_heap)
dijkstra(self.context, query, self.search_results, self._workspace)
self.origin = origin
self.destination = destination
self.early_exit = early_exit or a_star
self.a_star = a_star
self._search_heap = selected_heap
self._search_heuristic = selected_heuristic
self._search_scale = heuristic_scale
if self.skims is not None:
skimming(self.search_results, self._skimming, self._skim_workspace, self.skims)
self._trace(destination_index)
[docs]
def update_trace(self, destination: int) -> None:
"""
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** (:obj:`int`): External ID of the new destination.
:Returns:
``None``. ``path``, ``path_nodes`` and ``milepost`` are replaced for the requested destination.
:Raises:
**RuntimeError**: If no search has been performed.
**KeyError**: If the destination is not in the prepared graph.
"""
index = self._mapping.graph_node(destination)
results = self.search_results
if results.origin is None:
raise RuntimeError("Compute a path before updating its trace")
assert self.origin is not None
if not results.reachable_to(index) and not results.exhausted:
self.compute_path(
self.origin,
destination,
early_exit=self.early_exit,
a_star=self.a_star,
heuristic=self._search_heuristic,
heuristic_scale=self._search_scale,
heap=self._search_heap,
)
return
self.destination = destination
self._trace(index)
def _trace(self, destination: int) -> None:
results = self.search_results
states = results.path_states_to(destination)
if states.size == 0:
self._clear_path()
return
links = results.connectors[states[1:]]
self.path = links
nodes = np.empty(links.size + 1, dtype=np.uintp)
nodes[0] = results.origin
nodes[1:] = self.context.heads[links]
self.path_nodes = self._mapping.network_node(nodes)
# Stored labels preserve the cost of each actual arrival, including turns.
self.milepost = results.distances[states]
[docs]
def get_network_links(self) -> tuple[np.ndarray, np.ndarray] | None:
"""
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. Returns ``None`` when no path is available, and two empty
arrays for a path from a node to itself.
"""
if self.path is None:
return None
return self._mapping.expand_links(self.path)
def _clear_path(self) -> None:
self.path = None
self.path_nodes = None
self.milepost = None
[docs]
def reset(self) -> None:
"""
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.
"""
self.search_results.reset()
if self.skims is not None:
self.skims.reset()
self._clear_path()
self.origin = None
self.destination = None
self.early_exit = False
self.a_star = False
self._search_heap = None
self._search_heuristic = None
self._search_scale = None
[docs]
def set_heap(self, heap: str) -> None:
"""Select the priority queue implementation used for path computation.
:Arguments:
**heap** (:obj:`str`): Name returned by :meth:`get_heaps`.
:Returns:
``None``. The selected heap is used by subsequent searches.
"""
if heap not in available_heaps():
raise ValueError(f"heap must be one of {available_heaps()}")
self._heap = heap
[docs]
def get_heaps(self) -> list[str]:
"""Return the available priority queue implementation names.
:Returns:
:obj:`list[str]`: Names accepted by :meth:`set_heap`.
"""
return available_heaps()
[docs]
def set_heuristic(self, heuristic: str) -> None:
"""Select the heuristic used by A* path computation.
:Arguments:
**heuristic** (:obj:`str`): Name returned by :meth:`get_heuristics`.
:Returns:
``None``. The selected heuristic is used by subsequent A* searches.
"""
if heuristic not in HEURISTICS:
raise ValueError(f"heuristic must be one of {list(HEURISTICS)}")
self._heuristic = heuristic
[docs]
def get_heuristics(self) -> list[str]:
"""Return the available A* heuristic names.
:Returns:
:obj:`list[str]`: Names accepted by :meth:`set_heuristic`.
"""
return list(HEURISTICS)
@property
def node_ids(self) -> np.ndarray:
"""External node IDs in context and skim destination order."""
return self._mapping.network_node(np.arange(self.nodes, dtype=np.intp))
@property
def predecessors(self) -> np.ndarray:
return self.search_results.predecessors
@property
def connectors(self) -> np.ndarray:
return self.search_results.connectors
@property
def settlement_order(self) -> np.ndarray:
return self.search_results.settlement_order
@property
def terminal_states(self) -> np.ndarray:
return self.search_results.terminal_states
@property
def distances(self) -> np.ndarray:
return self.search_results.distances
@property
def turn_costs(self) -> np.ndarray:
return self.search_results.turn_costs