{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n\n# Traffic assignment with turn penalty and prohibition\n\nIn this example, we run static traffic assignment for Sioux Falls in two scenarios:\n\n1. Base case (no custom turn restrictions)\n2. Custom turn controls with:\n   - a turn penalty from link 7 to link 36\n   - a turn prohibition from link 24 to link 19\n\nAll turn directions are 1 and node-based U-turn transitions are allowed.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        ".. admonition:: References\n\n  * :doc:`../../static_traffic_assignment`\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        ".. seealso::\n    Several functions, methods, classes and modules are used in this example:\n\n    * :func:`aequilibrae.routing.Network.build_graph`\n    * :func:`aequilibrae.traffic.TrafficClass`\n    * :func:`aequilibrae.traffic.TrafficAssignment`\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Imports\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from dataclasses import replace\nfrom os.path import join\nfrom tempfile import gettempdir\nfrom uuid import uuid4\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nfrom aequilibrae.traffic import TrafficAssignment\nfrom aequilibrae.traffic import TrafficClass\nfrom aequilibrae.traffic.vdf import bpr\nfrom aequilibrae.examples import create_example\n\n\ndef run_assignment(network, matrix):\n    \"\"\"Runs a single-class traffic assignment and returns link flow results.\"\"\"\n    traffic_class = TrafficClass(\n        name=\"car\",\n        mode=\"c\",\n        cost=\"free_flow_time\",\n        demand=matrix,\n        graph_options={\"block_centroid_flows\": False},\n    )\n    assignment = TrafficAssignment(\n        network=network,\n        classes=[traffic_class],\n        time_field=\"free_flow_time\",\n        capacity_field=\"capacity\",\n        vdf=bpr,\n        name_mapping={\"alpha\": \"b\", \"beta\": \"power\"},\n        algorithm=\"bfw\",\n    )\n    assignment.execute(max_iterations=100, rgap=1e-2)\n\n    return assignment.results()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We create the Sioux Falls example project inside our temp folder.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fldr = join(gettempdir(), uuid4().hex)\nproject = create_example(fldr, \"sioux_falls\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Load the network and demand matrix.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "network = replace(project.road.build_network(), allow_uturns=True)\n\nmatrix = project.matrices.get_matrix(\"demand.omx\", subset=[\"matrix\"])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Base assignment.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "base_flows = run_assignment(network, matrix)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Apply turn controls in memory as node triples equivalent to:\n- a turn penalty from link 7 to link 36 (dir=1)\n- a turn prohibition from link 24 to link 19 (dir=1)\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "links = project.tables.links.data.set_index(\"link_id\")\nturn_restrictions = pd.DataFrame(\n    {\n        \"from_node\": [int(links.loc[7, \"a_node\"]), int(links.loc[24, \"a_node\"])],\n        \"via_node\": [int(links.loc[7, \"b_node\"]), int(links.loc[24, \"b_node\"])],\n        \"to_node\": [int(links.loc[36, \"b_node\"]), int(links.loc[19, \"b_node\"])],\n        \"penalty\": [5.0, np.nan],  # 5.0 minutes penalty, and one prohibited turn\n    }\n)\n# Network configuration is fixed so we will create a validated replacement with the new turns.\nnetwork = replace(network, turn_restrictions=turn_restrictions)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Assignment with custom turn controls.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "restricted_flows = run_assignment(network, matrix)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Plot flows for both cases and the difference.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "links = project.tables.links.data.set_index(\"link_id\")\n\nplot_df = (\n    links[[\"geometry\"]]\n    .join(base_flows[[\"matrix_tot\"]].rename(columns={\"matrix_tot\": \"base_flow\"}))\n    .join(restricted_flows[[\"matrix_tot\"]].rename(columns={\"matrix_tot\": \"restricted_flow\"}))\n)\nplot_df[\"difference\"] = plot_df[\"restricted_flow\"] - plot_df[\"base_flow\"]\n\nmax_base = max(plot_df[\"base_flow\"].max(), 1e-9)\nmax_restricted = max(plot_df[\"restricted_flow\"].max(), 1e-9)\nmax_diff = max(np.abs(plot_df[\"difference\"]).max(), 1e-9)\n\nfig, axes = plt.subplots(1, 3, figsize=(18, 6))\n\nplot_df.plot(\n    ax=axes[0],\n    linewidth=4 * plot_df[\"base_flow\"] / max_base,\n    color=\"tab:blue\",\n)\naxes[0].set_title(\"Base assignment flow\")\naxes[0].set_axis_off()\n\nplot_df.plot(\n    ax=axes[1],\n    linewidth=4 * plot_df[\"restricted_flow\"] / max_restricted,\n    color=\"tab:green\",\n)\naxes[1].set_title(\"With turn penalty/prohibition\")\naxes[1].set_axis_off()\n\nplot_df.plot(\n    ax=axes[2],\n    linewidth=3 * np.abs(plot_df[\"difference\"]) / max_diff,\n    color=\"lightgray\",\n)\n\nplot_df.loc[plot_df[\"difference\"] >= 0].plot(\n    ax=axes[2],\n    linewidth=3 * np.abs(plot_df.loc[plot_df[\"difference\"] >= 0, \"difference\"]) / max_diff,\n    color=\"tab:red\",\n)\n\nplot_df.loc[plot_df[\"difference\"] < 0].plot(\n    ax=axes[2],\n    linewidth=3 * np.abs(plot_df.loc[plot_df[\"difference\"] < 0, \"difference\"]) / max_diff,\n    color=\"tab:purple\",\n)\n\naxes[2].set_title(\"Flow difference (restricted - base)\")\naxes[2].set_axis_off()\n\nplt.tight_layout()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Close the project.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "project.close()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.11.18"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}