{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n\n# Forecasting\n\nIn this example, we present a full forecasting workflow for the Sioux Falls example model.\n\nWe start creating the skim matrices, running the assignment for the base-year, and then\ndistributing these trips into the network. Later, we estimate a set of future demand vectors\nwhich are going to be the input of a future year assignment with select link analysis.\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.traffic.TrafficClass`\n    * :func:`aequilibrae.traffic.TrafficAssignment`\n    * :func:`aequilibrae.distribution.ipf`\n    * :func:`aequilibrae.distribution.gravity_calibration`\n    * :func:`aequilibrae.distribution.gravity_application`\n    * :func:`aequilibrae.distribution.synthetic_gravity_model`\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Imports\nfrom os.path import join\nfrom tempfile import gettempdir\nfrom uuid import uuid4\n\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)\nfldr"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# We'll also apply a basic logging configuration.\n\nbasic_config()\n\nproject.parameters"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Traffic assignment with skimming\nIn this step, we'll set the skims for the variable ``free_flow_time``, and execute the\ntraffic assignment for the base-year.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from dataclasses import replace\nfrom aequilibrae.traffic import TrafficAssignment, TrafficClass, VDF"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "network = project.road.build_network()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's get the demand matrix directly from its file, and inspect what matrices we have in the project.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "proj_matrices = project.matrices\nproj_matrices.get_available_matrices_and_metadata()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Load the demand matrix core for computation.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "demand = proj_matrices.get_matrix(\"demand.omx\", subset=[\"matrix\"])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's perform the traffic assignment\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Create the assignment class\nassigclass = TrafficClass(\n    name=\"car\",\n    mode=\"c\",\n    cost=\"free_flow_time\",\n    demand=demand,\n    skimming=[\"free_flow_time\", \"distance\"],\n    # Every node in Sioux Falls is a centroid, so paths must pass through centroids.\n    graph_options={\"block_centroid_flows\": False},\n)\n\n\nfrom aequilibrae.routing.cython.vdf_core import akcelik, bpr, bpr2, conical, delta_akcelik, delta_bpr, delta_bpr2, delta_conical, delta_inrets, inrets\n\nbpr_spec = {\n    \"alpha\": {\"fill_NA\": 0.15, \"bounds\": (0.0, float(\"inf\"))},\n    \"beta\": {\"fill_NA\": 4.0, \"bounds\": (1.0, float(\"inf\"))},\n}\nvdf = VDF(\"bpr_example\", bpr, bpr_spec, delta_bpr)\n\n# Configure the VDF, network fields, and assignment algorithm.\nassig = TrafficAssignment(\n    network=network,\n    project=project,\n    classes=[assigclass],\n    vdf=vdf,\n    name_mapping={\"alpha\": \"b\", \"beta\": \"power\"},\n    time_field=\"free_flow_time\",\n    capacity_field=\"capacity\",\n    algorithm=\"bfw\",\n)\nassig.execute(max_iterations=1000, rgap=0.001)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "After finishing the assignment, we can easily see the convergence report.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "convergence_report = assig.report()\nconvergence_report.head()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "And we can also see the results of the assignment\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "results = assig.results()\nresults.head()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We can export our results to CSV or get a Pandas DataFrame, but let's put it directly into the results database\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "assig.save_results(\"base_year_assignment\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "And save the skims\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "assig.save_skims(\"base_year_assignment_skims\", which_ones=\"all\", format=\"omx\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Trip distribution\nFirst, let's have a function to plot the Trip Length Frequency Distribution.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from math import floor, log10\n\nimport matplotlib.pyplot as plt"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def plot_tlfd(demand, skim, name):\n    plt.clf()\n    b = floor(log10(skim.shape[0]) * 10)\n    n, bins, patches = plt.hist(\n        np.nan_to_num(skim.flatten(), 0),\n        bins=b,\n        weights=np.nan_to_num(demand.flatten()),\n        density=False,\n        facecolor=\"g\",\n        alpha=0.75,\n    )\n\n    plt.xlabel(\"Trip length\")\n    plt.ylabel(\"Probability\")\n    plt.title(f\"Trip-length frequency distribution for {name}\")\n    return plt"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Calibration\nWe will calibrate synthetic gravity models using the skims for ``free_flow_time`` that we just generated\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\n\nfrom aequilibrae.distribution import GravityCalibration"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Load the demand matrix core for computation.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "demand = proj_matrices.get_matrix(\"demand.omx\", subset=[\"matrix\"])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We also need the skims we just saved into our project. We select the congested-time core.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "imped_core = \"free_flow_time_final\"\nimped = proj_matrices.get_matrix(\"base_year_assignment_skims_car.omx\", subset=[imped_core])\n\n# Where ``free_flow_time_final`` is the congested time for the last iteration.\n# Use 75% of the closest zone for intrazonal impedance.\nimpedance_values = imped[imped_core].copy()\nnp.fill_diagonal(impedance_values, 0)\nintrazonals = np.amin(\n    impedance_values, where=impedance_values > 0, initial=impedance_values.max(), axis=1\n)\nintrazonals *= 0.75\nnp.fill_diagonal(impedance_values, intrazonals)\n\n# Store the prepared core as a separate project matrix.\ndel imped[imped_core]\nimped[\"final_time_with_intrazonals\"] = impedance_values\nproj_matrices.save_matrix(\n    \"base_year_assignment_skims_car_intrazonals.omx\",\n    matrix=imped,\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's calibrate our Gravity Model\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "for function in [\"power\", \"expo\"]:\n    gc = GravityCalibration(matrix=demand, impedance=imped, function=function, nan_as_zero=True)\n    gc.calibrate()\n    model = gc.model\n    # We save the model\n    model.save(join(fldr, f\"{function}_model.mod\"))\n\n    result_core = next(iter(gc.result_matrix))\n    _ = plot_tlfd(\n        gc.result_matrix[result_core], imped[\"final_time_with_intrazonals\"], f\"{function} model\"\n    )\n\n    # We can save the result of applying the model as well\n    # We can also save the calibration report\n    with open(join(fldr, f\"{function}_convergence.log\"), \"w\") as otp:\n        for r in gc.report:\n            otp.write(r + \"\\n\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "And let's plot a trip length frequency distribution for the demand itself\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "plt = plot_tlfd(demand[\"matrix\"], imped[\"final_time_with_intrazonals\"], \"demand\")\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Forecast\nWe create a set of 'future' vectors using some random growth factors.\nWe apply the model for inverse power, as the trip frequency length distribution\n(TFLD) seems to be a better fit for the actual one.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from aequilibrae.distribution import GravityApplication, Ipf, SyntheticGravityModel"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Compute future vectors\n\nFirst thing to do is to compute the future vectors from our matrix.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "origins = np.sum(demand[\"matrix\"], axis=1)\ndestinations = np.sum(demand[\"matrix\"], axis=0)\n\n# Then grow them with some random growth between 0 and 10%, and balance them\norig = origins * (1 + np.random.rand(origins.shape[0]) / 10)\ndest = destinations * (1 + np.random.rand(origins.shape[0]) / 10)\ndest *= orig.sum() / dest.sum()\n\nvectors = pd.DataFrame({\"origins\": orig, \"destinations\": dest}, index=demand.index[:])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### IPF for the future vectors\nLet's balance the future vectors. The output of this step is going to be used later\nin the traffic assignment for future year.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "args = {\n    \"matrix\": demand,\n    \"vectors\": vectors,\n    \"column_field\": \"destinations\",\n    \"row_field\": \"origins\",\n    \"nan_as_zero\": True,\n}\n\nipf = Ipf(project=project, **args)\nipf.fit()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Save the balanced matrix into the project's matrix folder\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "ipf.save_to_project(file_name=\"demand_ipfd.omx\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Impedance\n\nLet's get the base-year assignment skim for car we created before and prepare it for computation\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "imped = proj_matrices.get_matrix(\n    \"base_year_assignment_skims_car_intrazonals.omx\", subset=[\"final_time_with_intrazonals\"]\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "If we wanted the main diagonal to not be considered...\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# np.fill_diagonal(imped[\"final_time_with_intrazonals\"], np.nan)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Now we apply the Synthetic Gravity model\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "for function in [\"power\", \"expo\"]:\n    model = SyntheticGravityModel()\n    model.load(join(fldr, f\"{function}_model.mod\"))\n\n    args = {\n        \"impedance\": imped,\n        \"vectors\": vectors,\n        \"row_field\": \"origins\",\n        \"model\": model,\n        \"column_field\": \"destinations\",\n        \"nan_as_zero\": True,\n    }\n\n    gravity = GravityApplication(project=project, **args)\n    gravity.apply()\n\n    # We get the output matrix and save it to OMX too,\n    gravity.save_to_project(file_name=f\"demand_{function}_modeled.omx\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We inspect the matrix files and verify that the new matrices are indeed there\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "proj_matrices.get_available_matrices_and_metadata()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Traffic assignment with Select Link Analysis\nWe'll perform traffic assignment for the future year.\nLet's get our future demand matrix, which corresponds to the IPF result we just saved,\nand see what is the core we ended up getting. It should be ``matrix``.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "demand = proj_matrices.get_matrix(\"demand_ipfd.omx\", subset=[\"matrix\"])\nlist(demand)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The selected matrix core is ready for computation.\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The future year assignment is quite similar to the one we did for the base-year.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# So, let's create the assignment class\nassigclass = TrafficClass(\n    name=\"car\",\n    mode=\"c\",\n    cost=\"free_flow_time\",\n    demand=demand,\n    skimming=[\"free_flow_time\", \"distance\"],\n    # Every node in Sioux Falls is a centroid, so paths must pass through centroids.\n    graph_options={\"block_centroid_flows\": False},\n)\n\n\ndef quadratic(congested_time, link_flows, fftime, capacity, cores, a, b):\n    congested_time[:] = fftime * (a * (link_flows / capacity) ** 2 + b * (link_flows / capacity) + 1)\n\n\ndef quadratic_derivative(delta, link_flows, fftime, capacity, cores, a, b):\n    delta[:] = fftime * (2 * a * (link_flows / capacity) + b) / capacity\n\n\nvdf = VDF(\n    \"quadratic\",\n    quadratic,\n    {\"a\": {\"fill_NA\": 0.15, \"bounds\": (0, float(\"inf\"))}, \"b\": {\"fill_NA\": 0.1}},\n    quadratic_derivative,\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Now we select two sets of links to execute select link analysis.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "select_links = {\n    \"Leaving node 1\": [(1, 1), (2, 1)],\n    \"Random nodes\": [(3, 1), (5, 1)],\n}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "<div class=\"alert alert-info\"><h4>Note</h4>\n\nAs we are executing the select link analysis on a particular ``TrafficClass``, we should set the\nlinks we want to analyze. The input is a dictionary with string as keys and a list of tuples as\nvalues, so that each entry represents a separate set of selected links to compute.\n\n``select_link_dict = {\"set_name\": [(link_id1, direction1), ..., (link_id, direction)]}``\n\nThe string name will name the set of links, and the list of tuples is the list of selected links\nin the form ``(link_id, direction)``, as it occurs in the `Graph <aequilibrae-graphs>`.\n\nDirection can be one of 0, 1, or -1, where 0 denotes bi-directionality.\n\n</div>\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# We call this command on the class we are analyzing with our dictionary of values\nassigclass = replace(assigclass, select_link_sets=select_links)\n\n# Configure the VDF, network fields, and assignment algorithm.\nassig = TrafficAssignment(\n    network=network,\n    project=project,\n    classes=[assigclass],\n    vdf=vdf,\n    name_mapping={\"a\": 0.15, \"b\": 1.0},\n    time_field=\"free_flow_time\",\n    capacity_field=\"capacity\",\n    algorithm=\"bfw\",\n)\nassig.execute(max_iterations=500, rgap=0.00001)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "To save our select link results, all we need to do is provide it with a name.\nIn addition to exporting the select link flows, it also exports the Select Link matrices in OMX format.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "assig.save_select_link_results(\"select_link_analysis\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "<div class=\"alert alert-info\"><h4>Note</h4>\n\nSay we just want to save our select link flows, we can call: ``assig.save_select_link_flows(\"just_flows\")``\n\nOr if we just want the select link matrices: ``assig.save_select_link_matrices(\"just_matrices\")``\n\nInternally, the ``save_select_link_results`` calls both of these methods at once.\n\n</div>\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We can export the results to CSV or AequilibraE Data, but let's put it directly into the results database\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "assig.save_results(\"future_year_assignment\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "And save the skims\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "assig.save_skims(\"future_year_assignment_skims\", which_ones=\"all\", format=\"omx\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Run convergence study\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "df = assig.report()\nx = df.iteration.values\ny = df.rgap.values\n\nfig = plt.figure()\nax = fig.add_subplot(111)\n\nplt.plot(x, y, \"k--\")\nplt.yscale(\"log\")\nplt.grid(True, which=\"both\")\nplt.xlabel(\"Iterations\")\nplt.ylabel(\"Relative Gap\")\nplt.show()"
      ]
    },
    {
      "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
}