.. _turn_restrictions: Turn Restrictions ================= AequilibraE supports turn restrictions and turn penalties for traffic assignment, path computation and route choice. This feature enables modelling of prohibited turns (e.g., no left turn signs) and turn penalties (e.g., additional time for turning movements). Overview -------- Turn restrictions in AequilibraE are stored in a dedicated database table and can be applied to graphs during path computation, traffic assignment and route choice. When turn restrictions are enabled, AequilibraE uses an arc-based Dijkstra algorithm instead of the standard node-based algorithm, which allows for modelling turn-to-turn transitions with associated costs. Database Schema --------------- Turn restrictions are stored in the ``turn_restrictions`` table with the following columns: - **restriction_id**: Unique identifier for the restriction (generated if omitted) - **from_node**: Incoming movement origin node - **via_node**: The turn node - **to_node**: Outgoing movement destination node - **penalty**: Turn penalty in time units (same as graph cost field). NULL indicates a prohibited turn. ``+inf`` is also accepted by the Python API and is normalised to NULL before storage. Negative values are not allowed. - **modes**: String with the list of modes to which the restriction applies (e.g., "ct", "c", "w"). Turn definitions are node-sequences: ``from_node -> via_node -> to_node``. Trigger Behaviour ----------------- Database triggers enforce and maintain turn restriction integrity: - node-sequence consistency is enforced - mode codes are validated against the ``modes`` table - duplicate restrictions with overlapping mode coverage are blocked - restrictions are removed or remapped when linked ``links.link_id`` records are deleted or changed When geometry support is enabled, ``turn_restrictions.geometry`` is generated for the 3-node movement and updated when movement definition or node geometry changes. See :ref:`turn_restrictions_trigger_behaviour` for network-editing details. Global U-Turn Setting --------------------- The ``allow_uturns`` setting in the ``about`` table controls whether U-turns are permitted globally in the network. By default, this is set to ``0`` (False), meaning U-turns are prohibited. U-turn detection is node-based: a transition is considered a U-turn when the next directed arc returns to the tail node of the current directed arc. When U-turns are allowed and graph compression is enabled, nodes where U-turns could occur (nodes with bidirectional links) are preserved during compression to maintain the correct turn possibilities. Usage ----- Managing Turn Restrictions ~~~~~~~~~~~~~~~~~~~~~~~~~~ Turn restrictions use the same table API as links and nodes. ``get()`` returns an immutable record, ``data`` returns a GeoDataFrame, and ``len(turns)`` counts records. Missing keys raise ``ValueError`` unless ``get()`` is given a default. Supply ``modes`` on insert. Database triggers reject missing, empty, unknown or repeated mode IDs, and overlapping restrictions for the same turn. These errors raise ``sqlite3.IntegrityError``. Modes are stored in the supplied order. Updates leave omitted fields unchanged; ``penalty=None`` prohibits the turn. Use ``project.transaction()`` to group writes. .. code-block:: python >>> project = create_example(project_path) # Sioux Falls free_flow_time is in minutes, so convert it to seconds for these examples. >>> project.tables.links.fields.add("travel_time_seconds", "Free-flow travel time in seconds", "REAL") >>> with project.db_connection as conn: ... _ = conn.execute("UPDATE links SET travel_time_seconds = free_flow_time * 60.0") # Get the turn restrictions object >>> turns = project.tables.turn_restrictions # Add a prohibited turn (penalty=None means prohibited) >>> restriction_id = turns.insert(from_node=1, via_node=2, to_node=6, modes="c") # Add a turn with a 30-second penalty >>> other_id = turns.insert(from_node=3, via_node=4, to_node=5, penalty=30.0, modes="c") # Change only the penalty >>> turns.update(restriction_id, penalty=10.0) # Get all restrictions, including their generated geometry >>> df = turns.data # Remove a specific restriction >>> turns.delete(restriction_id) # Clear all restrictions >>> turns.clear_restrictions() 1 Bulk Loading from DataFrame ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Use ``insert_from()`` to load turns from a DataFrame. It returns the inserted IDs. Use ``update_from()`` with a ``restriction_id`` column to change existing turns. Include a ``modes`` column when inserting. Both methods normalise penalties just like single-record writes and leave mode validation to the database. They roll back the whole batch if a row fails. .. code-block:: python >>> import pandas as pd >>> restrictions_df = pd.DataFrame({ ... 'from_node': [1, 2, 3], ... 'via_node': [2, 6, 4], ... 'to_node': [6, 5, 5], ... 'modes': ['c', 'c', 'c'], ... 'penalty': [None, 15.0, 30.0], # None or +inf = prohibited ... }) >>> restriction_ids = turns.insert_from(restrictions_df) Setting Global U-Turn Permission ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The U-turn setting is managed through the project's ``about`` table: .. code-block:: python >>> project.about.update("allow_uturns", infovalue="1") # Allow U-turns # Rebuild network and build graphs to apply the change >>> network = project.road.build_network() >>> graph = network.build_graph('c', cost='travel_time_seconds') Building Graphs with Turn Restrictions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When you build a network snapshot, turn restrictions are loaded from the database. .. code-block:: python >>> network = project.road.build_network() >>> graph = network.build_graph('c', cost='travel_time_seconds') # Check if a graph has turn restrictions >>> print(graph.has_turn_restrictions) True Manual Turn Restriction Setup ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You can also supply turn restrictions when building a new graph. An existing graph's topology and turn configuration cannot be changed in place: .. code-block:: python >>> import pandas as pd >>> links = project.tables.links.data.set_index("link_id") >>> turn_df = pd.DataFrame({ ... "from_node": [int(links.loc[7, "a_node"])], ... "via_node": [int(links.loc[7, "b_node"])], ... "to_node": [int(links.loc[36, "b_node"])], ... "penalty": [20.0], ... }) # Build a new graph with these turn restrictions >>> graph = network.build_graph('c', cost='travel_time_seconds', turn_restrictions=turn_df, allow_uturns=False) # Build a new graph without turn restrictions, overriding the snapshot's turns with an empty table >>> graph = network.build_graph('c', cost='travel_time_seconds', turn_restrictions=turn_df.iloc[:0]) To change the source network's turn configuration for subsequent graphs or assignments, use ``dataclasses.replace(network, turn_restrictions=turn_df)``. Network configuration fields cannot be assigned in place. Traffic Assignment with Turn Restrictions ----------------------------------------- Turn restrictions are automatically considered during traffic assignment when they are present in the source network. The assignment builds its graphs internally. The turn penalties are applied as additional time costs during the equilibration process. .. code-block:: python >>> from aequilibrae.traffic import TrafficAssignment, TrafficClass >>> from aequilibrae.traffic.vdf import bpr >>> network = project.road.build_network() >>> demand_matrix = project.matrices.get_matrix("demand.omx", subset=["matrix"]) >>> traffic_class = TrafficClass( ... mode='c', ... cost='travel_time_seconds', ... demand=demand_matrix, ... name='car', ... skimming=('travel_time_seconds',), ... ) >>> assignment = TrafficAssignment( ... network=network, ... classes=[traffic_class], ... time_field='travel_time_seconds', ... capacity_field='capacity', ... vdf=bpr, ... algorithm='bfw', ... name_mapping={'alpha': 0.15, 'beta': 4.0}, ... ) >>> _ = assignment.execute() Route Choice with Turn Restrictions ----------------------------------- Turn restrictions and turn penalties are automatically considered during route choice when they are present in the graph. They are included in generated route costs and path-size logit calculations. For imported routes, ``RouteChoice.recompute_psl()`` validates origin and destination endpoints, link connectivity and turn restrictions before recalculating costs, overlap and probabilities. For assignment from imported routes, pass ``recompute_psl=True`` to ``execute_from_pandas()`` or ``execute_from_path_files()`` to perform the same validation and recalculation. Performance Considerations -------------------------- The arc-based Dijkstra algorithm required for turn restrictions has higher memory requirements than the standard node-based algorithm (arrays are indexed by number of links rather than number of nodes). For this reason: 1. Arc-based path finding is only activated when turn restrictions are present 2. If no turn restrictions exist, the standard (faster) algorithm is used 3. Graph compression is adjusted to preserve nodes where U-turns could occur Turn Penalty Units ------------------ Turn penalties must use the same units as the graph's cost function. For traffic assignment, the class cost and assignment ``time_field`` must also use the same time units. The examples above convert the sample model's ``free_flow_time`` from minutes to ``travel_time_seconds``, so their turn penalties are in seconds. Limitations ----------- - A* path finding can be used together with turn restrictions. - Turn restrictions are defined by 3-node movement sequences (no lane-level control) - Complex turn restrictions involving multiple via-nodes are not supported