{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n\n# Path computation\n\nIn this example, we show how to perform path computation for Coquimbo, a city in La Serena Metropolitan Area in Chile.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        ".. seealso::\n    Several functions, methods, classes and modules are used in this example:\n\n    * :func:`aequilibrae.routing.graph`\n    * :func:`aequilibrae.routing.results.path_results`\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 geopandas as gpd\n\nfrom aequilibrae.routing import estimate_heuristic_scale\nfrom aequilibrae.examples import create_example\nfrom aequilibrae.utils import basic_config"
      ]
    },
    {
      "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)\n\nproject = create_example(fldr, \"coquimbo\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# We'll also apply a basic logging configuration.\n\nbasic_config()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Path Computation\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Load the network snapshot\nWe get warnings that several fields in the project are filled with ``NaN``s.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "network = project.road.build_network()\n# This is true, but we won't use those fields."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We build the graph for cars, minimise distance, and skim time and distance.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "graph = network.build_graph(mode=\"c\", cost=\"distance\", skimming=[\"travel_time\", \"distance\"])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "we'll also see what modes are available.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "network.modes"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's create a path results object from the graph and compute a path from\nnode 32343 (near the airport) to 22041 (near Fort Lambert, overlooking Coquimbo Bay).\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "res = graph.compute_path(32343, 22041)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Computing paths directly from the graph is more straightforward, though we could\nalternatively use the ``PathResults`` class to achieve the same result.\n\nfrom aequilibrae.routing import PathResults\nres = PathResults(graph, 32343, 22041)\n\n``graph.compute_path`` has already performed this setup above.\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We can get the sequence of nodes we traverse\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "res.path_nodes"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We can get the physical link IDs and directions we traverse.\n``res.path`` contains local graph-link indices instead.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "res.get_network_links()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We can get the mileposts for our sequence of nodes\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "res.milepost"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Additionally, you can also provide ``early_exit=True`` or ``a_star=True`` to `compute_path` to adjust its\npath-finding behaviour.\n\nProviding ``early_exit=True`` allows you to quit the path-finding procedure once it discovers the destination. This\nsetup works better for topographically close origin-destination pairs.  However, exiting early may cause subsequent\ncalls to ``update_trace`` to recompute the tree in cases where it typically wouldn't.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "res = graph.compute_path(32343, 22041, early_exit=True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "To guide the search towards the destination, provide ``a_star=True`` to use `A*` with a heuristic. ``update_trace``\nreuses finalised paths, or searches again if needed, retaining the algorithm, heuristic, scale and heap.  Note that\na_star takes precedence over early_exit. Euclidean distance needs node coordinates projected to a suitable local CRS\nand a scale parameter to transform it into a cost value.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "lonlat = network.lonlat\npoints = gpd.GeoSeries(gpd.points_from_xy(lonlat.lon, lonlat.lat), index=lonlat.index, crs=4326)\npoints = points.to_crs(points.estimate_utm_crs())\ncoordinates = points.get_coordinates()\n\nscale = estimate_heuristic_scale(graph, coordinates)\nres = graph.compute_path(32343, 22041, a_star=True, coordinates=coordinates, heuristic_scale=scale)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "If you are using `a_star`, it is possible to use different heuristics to compute the path.\nBy default, a Euclidean heuristic is used, and we can view the available heuristics via:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "res.get_heuristics()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "To use geographic distance without projecting the coordinates, choose \"haversine\". Pass the network's\nlongitude/latitude data explicitly to both the scale estimator and the search.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "scale = estimate_heuristic_scale(graph, lonlat, heuristic=\"haversine\")\nres = graph.compute_path(\n    32343, 22041, a_star=True, heuristic=\"haversine\", coordinates=lonlat, heuristic_scale=scale\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Suppose you want to adjust the path to the University of La Serena instead of Fort Lambert.  It is possible to adjust\nthe existing path computation for this alteration. The following code allows both `early_exit` and `A*` settings to\npersist when calling ``update_trace``. If you\u2019d like to adjust them for subsequent path re-computations, call\n``compute_path`` with the desired settings. Notice that this procedure is much faster when you have large networks and\nthe search for the previous destination happened to include the new destination.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "res.update_trace(73131)\n\nres.path_nodes"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "If you want to show the path in Python.\n\nWe do NOT recommend this, though... It is very slow for real networks.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "links = project.tables.links.data.set_index(\"link_id\")\nlink_ids, directions = res.get_network_links()\nlinks = links.loc[link_ids]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "links.explore(color=\"blue\", style_kwds={\"weight\": 5})"
      ]
    },
    {
      "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
}