{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n\n# Route Choice with sub-area analysis\n\nIn this example, we show how to perform sub-area analysis using route choice assignment,\nfor a city in La Serena Metropolitan Area in Chile.\n\n.. admonition:: References\n\n   * :doc:`../../route_choice`\n\n.. seealso::\n    Several functions, methods, classes and modules are used in this example:\n\n    * :func:`aequilibrae.routing.graph`\n    * :func:`aequilibrae.route_choice.route_choice`\n    * :func:`aequilibrae.route_choice.sub_area`\n    * :func:`aequilibrae.matrix.aequilibrae_matrix`\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Imports\nimport itertools\nfrom os.path import join\nfrom tempfile import gettempdir\nfrom uuid import uuid4\n\nimport folium\nimport numpy as np\nimport pandas as pd\n\nfrom aequilibrae.examples import create_example\nfrom aequilibrae.utils import basic_config"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# We create the example project inside our temp folder\nfldr = 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": [
        "## Model parameters\nWe'll set the parameters for our route choice model. These are the parameters that will be\nused to calculate the utility of each path. In our example, the utility is equal to\n$distance * theta$, and the path overlap factor (PSL) is equal to $beta$.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "theta = 0.011  # Distance factor\n\nbeta = 1.1  # PSL parameter"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's build all graphs\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "network = project.road.build_network()\n# We get warnings that several fields in the project are filled with NaNs.\n# This is true, but we won't use those fields."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We grab the graph for cars\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "network.modes"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's say that utility is just a function of distance.\nSo we build our *utility* field as the $distance * theta$.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "network.links[\"utility\"] = network.links.distance * theta"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Prepare a compact graph for the project centroids.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "graph = network.build_graph(mode=\"c\", cost=\"utility\", compact=True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Mock demand matrix\n\nWe'll create a mock demand matrix with demand `10` for every zone and prepare it for computation.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from aequilibrae.matrix import AequilibraeMatrix, from_df\n\nmat = AequilibraeMatrix(index=graph.centroids, index_name=\"zones\")\nmat[\"demand\"] = np.full((graph.num_zones, graph.num_zones), 10.0)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Sub-area preparation\n\nWe need to define some polygon for out sub-area analysis, here we'll use a section of zones and\ncreate out polygon as the union of their geometry. It's best to choose a polygon that avoids\nany unnecessary intersections with links as the resource requirements of this approach grow\nquadratically with the number of links cut.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "zones_of_interest = [29, 30, 31, 32, 33, 34, 37, 38, 39, 40, 49, 50, 51, 52, 57, 58, 59, 60]\nzones = project.tables.zones.data.set_index(\"zone_id\")\nzones = zones.loc[zones_of_interest]\nzones.head()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Sub-area analysis\n\nFrom here there are two main paths to conduct a sub-area analysis, manual or automated.\nAequilibraE ships with a small class that handle most of the details regarding the implementation\nand extract of the relevant data. It also exposes all the tools necessary to conduct this analysis\nyourself if you need fine grained control.\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Automated sub-area analysis\n\nWe first construct out ``SubAreaAnalysis`` object from the graph, zones, and matrix we previously constructed, then\nconfigure the route choice assignment and execute it. From there the ``post_process`` method is able to use the route\nchoice assignment results to construct the desired demand matrix as a DataFrame. If we were interested in the original\norigin and destination IDs for each entry we could use `subarea.post_process(keep_original_ods=True)` instead. This\nwill attach the true ODs from the select link OD matrix as part of the index. However, this will create a\nsignificantly larger, but more flexible matrix.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from aequilibrae.route_choice import SubAreaAnalysis\n\nsubarea = SubAreaAnalysis(graph, zones, mat, project=project)\nsubarea.rc.set_choice_set_generation(\"lp\", max_routes=3, penalty=1.02, store_results=False)\nsubarea.rc.execute(perform_assignment=True)\ndemand = subarea.post_process()\ndemand"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We'll re-prepare our graph but with our new \"external\" ODs.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "new_centroids = np.unique(demand.reset_index()[[\"origin id\", \"destination id\"]].to_numpy().reshape(-1))\ngraph = network.build_graph(mode=\"c\", cost=\"utility\", centroids=new_centroids, compact=True)\nnew_centroids"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We can then perform an assignment using our new demand matrix on the limited graph\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from aequilibrae.route_choice import RouteChoice\n\ndemand_matrix = from_df(\n    demand.reset_index(),\n    row=\"origin id\",\n    col=\"destination id\",\n    subset=list(demand.columns),\n    index=new_centroids,\n    index_name=\"zones\",\n    sparse=True,\n)\n\nrc = RouteChoice(graph)\nrc.set_demand(demand_matrix)\nrc.set_choice_set_generation(\"lp\", max_routes=3, penalty=1.02, store_results=False, seed=123)\nrc.execute(perform_assignment=True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's take the union of the zones GeoDataFrame as a polygon\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "poly = zones.union_all()\npoly"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "And prepare the sub-area to plot.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "subarea_zone = folium.Polygon(\n    locations=[(x[1], x[0]) for x in poly.boundary.coords],\n    fill_color=\"blue\",\n    fill_opacity=0.1,\n    fill=True,\n    weight=1,\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We create a function to plot out link loads data more easily\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def plot_results(link_loads):\n    link_loads = link_loads[link_loads[\"demand_tot\"] > 0]\n    max_load = link_loads[[\"demand_tot\"]].max()\n    links = project.tables.links.data\n    loaded_links = links.merge(link_loads, on=\"link_id\", how=\"inner\")\n    factor = 10 / max_load\n\n    return loaded_links.explore(\n        color=\"red\",\n        style_kwds={\n            \"style_function\": lambda x: {\n                \"weight\": x[\"properties\"][\"demand_tot\"] * factor,\n            }\n        },\n    )"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "And plot our data!\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "map = plot_results(rc.get_load_results())\nsubarea_zone.add_to(map)\nmap"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Sub-area further preparation\n\nIt's useful later on to know which links from the network cross our polygon.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "links = project.tables.links.data\ninner_links = links[links.crosses(poly.boundary)].sort_index()\ninner_links.head()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "As well as which nodes are interior.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "nodes = project.tables.nodes.data.set_index(\"node_id\")\ninside_nodes = nodes.sjoin(zones, how=\"inner\").sort_index()\ninside_nodes.head()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's filter those network links to links retained by the graph, including links inside contracted chains,\nand create a `link_id`, `direction` multi-index.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "mapping = graph.mapping\nsource = mapping.network\nretained = mapping.network_link_to_graph >= 0\ng = pd.DataFrame(\n    {\n        \"link_id\": source.link_ids[retained],\n        \"direction\": source.directions[retained],\n        \"a_node\": source.node_ids[source.link_tails[retained]],\n        \"b_node\": source.node_ids[source.link_heads[retained]],\n    }\n)\ng = g.loc[g.link_id.isin(inner_links.link_id)].set_index([\"link_id\", \"direction\"])\ng.head()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Here we'll quickly visualise what our sub-area is looking like.\nWe'll plot the polygon from our zoning system and the links that it cuts.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "map = inner_links.explore(color=\"red\", style_kwds={\"weight\": 4})\nsubarea_zone.add_to(map)\nmap"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Manual sub-area analysis\n\nHere we'll construct and use the Route Choice class to generate our route sets,\n\nIn order to perform out analysis we need to know what OD pairs have flow that enters and/or exists\nour polygon. To do so we perform a select link analysis on all links and pairs of links that cross\nthe boundary. We create them as tuples of tuples to make represent the select link AND sets.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "entering = g.loc[~g.a_node.isin(inside_nodes.index) & g.b_node.isin(inside_nodes.index)].index\nexiting = g.loc[g.a_node.isin(inside_nodes.index) & ~g.b_node.isin(inside_nodes.index)].index\nedge_pairs = {pair: (pair,) for pair in itertools.product(entering, exiting)}\nsingle_edges = {x: ((x,),) for x in g.index}\nf\"Created: {len(edge_pairs)} edge pairs from {len(single_edges)} edges\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's prepare our graph once again\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "graph = network.build_graph(mode=\"c\", cost=\"utility\", compact=True, block_centroid_flows=False)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Graph construction has already prepared the compressed-link to network-link\nmapping. We need to supply a Graph and an AequilibraeMatrix or\nAequilibraeSparseMatrix via the ``set_demand`` method, if demand is not\nprovided link loading cannot be performed.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "rc = RouteChoice(graph)\nrc.set_demand(mat)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Here we add the union of edges as select link sets.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "rc.set_select_links(single_edges | edge_pairs)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "For the sake of demonstration we limit out demand matrix to a few OD\npairs.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "ods_pairs_of_interest = [\n    (4, 39),\n    (92, 37),\n    (31, 58),\n    (4, 19),\n    (39, 34),\n]\nods_pairs_of_interest = ods_pairs_of_interest + [(x[1], x[0]) for x in ods_pairs_of_interest]\n\n# Construct a sparse Aeq matrix for our sub-selection\ndemand = pd.DataFrame(\n    {name: [mat.mat[name, o, d] for o, d in ods_pairs_of_interest] for name in mat},\n    index=pd.MultiIndex.from_tuples(ods_pairs_of_interest, names=[\"origin id\", \"destination id\"]),\n).sort_index()\ndemand_matrix = from_df(demand.reset_index(), \"origin id\", \"destination id\", index=mat.index, sparse=True)\n\nrc = RouteChoice(graph)\nrc.set_demand(demand_matrix)\nrc.set_select_links(single_edges | edge_pairs)\nrc.demand"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Perform the assignment\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "rc.set_choice_set_generation(\"lp\", max_routes=3, penalty=1.02, store_results=False, seed=123)\nrc.execute(perform_assignment=True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We can visualise the current links loads\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "map = plot_results(rc.get_load_results())\nsubarea_zone.add_to(map)\nmap"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We'll pull out just OD matrix results as well we need it for the\npost-processing, we'll also use the returned SciPy CSR arrays directly.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "sl_od = rc.get_select_link_od_matrix_results()\nod_index = demand_matrix.index\nedge_totals = {k: sl_od[k][\"demand\"] for k in single_edges}\nedge_pair_values = {k: sl_od[k][\"demand\"] for k in edge_pairs}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "For the post processing, we are interested in the demand of OD pairs that enter or exit the\nsub-area, or do both. For the single enters and exists we can extract that information from\nthe single link select link results. We also need to map the links that cross the boundary to\nthe origin/destination node and the node that appears on the outside of the sub-area.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from collections import defaultdict\n\nentered = defaultdict(float)\nexited = defaultdict(float)\nfor (link_id, dir), v in edge_totals.items():\n    link = g.loc[link_id, dir]\n    for (o, d), load in v.todok().items():\n        o = od_index[o]\n        d = od_index[d]\n\n        o_inside = o in inside_nodes.index\n        d_inside = d in inside_nodes.index\n\n        if o_inside and not d_inside:\n            exited[o, link.b_node] += load\n        elif not o_inside and d_inside:\n            entered[link.a_node, d] += load\n        elif not o_inside and not d_inside:\n            pass"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Here he have the load that entered the sub-area\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "entered"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "and the load that exited the sub-area\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "exited"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "To find the load that both entered and exited we can look at the edge pair select link results.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "through = defaultdict(float)\nfor (l1, l2), v in edge_pair_values.items():\n    link1 = g.loc[l1]\n    link2 = g.loc[l2]\n\n    for (o, d), load in v.todok().items():\n        o = od_index[o]\n        d = od_index[d]\n        o_inside = o in inside_nodes.index\n        d_inside = d in inside_nodes.index\n\n        if not o_inside and not d_inside:\n            through[link1.a_node, link2.b_node] += load\n\nthrough"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "With these results we can construct a new demand matrix. Usually this would be now transplanted\nonto another network, however for demonstration purposes we'll reuse the same network.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "manual_od_pairs = list(entered.keys()) + list(exited.keys()) + list(through.keys())\nmanual_od_pairs = np.asarray(manual_od_pairs, dtype=np.uint64)\ndemand = pd.DataFrame(\n    list(entered.values()) + list(exited.values()) + list(through.values()),\n    index=pd.MultiIndex.from_arrays(\n        [manual_od_pairs[:, 0], manual_od_pairs[:, 1]], names=[\"origin id\", \"destination id\"]\n    ),\n    columns=[\"demand\"],\n).sort_index()\ndemand.index = demand.index.set_levels([level.astype(np.int64) for level in demand.index.levels])\ndemand.head()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We'll re-prepare our graph but with our new \"external\" ODs.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "new_centroids = np.unique(demand.reset_index()[[\"origin id\", \"destination id\"]].to_numpy(dtype=np.int64).reshape(-1))\ngraph = network.build_graph(mode=\"c\", cost=\"utility\", centroids=new_centroids, compact=True)\nnew_centroids"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Re-perform our assignment\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "rc = RouteChoice(graph)\nrc.set_demand(from_df(demand.reset_index(), \"origin id\", \"destination id\", index=new_centroids, sparse=True))\nrc.set_choice_set_generation(\"lp\", max_routes=3, penalty=1.02, store_results=False, seed=123)\nrc.execute(perform_assignment=True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "And plot the link loads for easy viewing\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "map = plot_results(rc.get_load_results())\nsubarea_zone.add_to(map)\nmap"
      ]
    },
    {
      "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
}