{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n\n# Path computation with in-memory turn restrictions\n\nIn this example, we show how to build a new graph with turn restrictions from a network already loaded in memory.\n\nWe use the Coquimbo example and compare paths before and after prohibiting one specific turn.\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.routing.Graph.compute_path`\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Imports\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from 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.examples import create_example"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We create the 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, \"coquimbo\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Load the network snapshot and get the car graph.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "network = project.road.build_network()\ngraph = network.build_graph(mode=\"c\", cost=\"distance\", block_centroid_flows=False)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We choose origin/destination.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "origin = 32343\ndestination = 22041"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Path without turn restrictions.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "res_before = graph.compute_path(origin, destination)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Build prohibited turns from node triples sampled along the baseline path.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "path_nodes = [int(x) for x in res_before.path_nodes]\ntriples = [(path_nodes[i], path_nodes[i + 1], path_nodes[i + 2]) for i in range(max(0, len(path_nodes) - 2))]\nturn_restrictions = pd.DataFrame(\n    {\n        \"from_node\": [t[0] for t in triples[:4]],\n        \"via_node\": [t[1] for t in triples[:4]],\n        \"to_node\": [t[2] for t in triples[:4]],\n        \"penalty\": [np.nan, np.nan, np.nan, np.nan],\n    }\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Build a new graph with turn restrictions in memory, with node-based U-turns globally prohibited\n(i.e. transitions that return to the previous node).\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "graph = network.build_graph(\n    mode=\"c\", cost=\"distance\", turn_restrictions=turn_restrictions,\n    allow_uturns=False, block_centroid_flows=False,\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Path with the custom turn prohibition.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "res_after = graph.compute_path(origin, destination)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Plot both paths.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "links = project.tables.links.data.set_index(\"link_id\")\nlink_ids_before, directions_before = res_before.get_network_links()\nlink_ids_after, directions_after = res_after.get_network_links()\nlinks_before = links.loc[link_ids_before]\nlinks_after = links.loc[link_ids_after]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "m = links_before.explore(color=\"blue\", style_kwds={'weight':5})\nm = links_after.explore(m=m, color=\"red\", style_kwds={'weight':5})\n\n#%\nm"
      ]
    },
    {
      "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
}