{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n\n# Forecasting with a custom VDF\n\nIn this example, we use the built-in BPR volume-delay function (VDF) for the\nbase-year assignment in Sioux Falls. We then estimate future demand and use a\ncustom quadratic VDF for the future-year assignment with select link analysis.\n\nSee the `original forecasting example <example_usage_forecasting>` for the\nfull model setup, including gravity model calibration and trip length frequency\nplots.\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.distribution import Ipf\nfrom aequilibrae.examples import create_example\nfrom aequilibrae.traffic import VDF, TrafficAssignment, TrafficClass\nfrom aequilibrae.traffic.vdf import bpr\nfrom aequilibrae.utils import basic_config"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Base-year assignment with the built-in BPR VDF\nWe use the built-in BPR VDF to run the base-year assignment with skims for\n``free_flow_time`` and ``distance``.\n\n"
      ]
    },
    {
      "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)\nproject = create_example(fldr)\n\n# We'll also apply a basic logging configuration.\nbasic_config()\n\nnetwork = project.road.build_network()\nproj_matrices = project.matrices\n\n# Load the demand matrix core for computation.\ndemand = proj_matrices.get_matrix(\"demand.omx\", subset=[\"matrix\"])\n\n# 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# Configure the VDF, network fields, and assignment algorithm.\nassig = TrafficAssignment(\n    network=network,\n    project=project,\n    classes=[assigclass],\n    vdf=bpr,\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)\n\n# Save the results to the project database and the skims to OMX.\nassig.save_results(\"base_year_assignment\")\nassig.save_skims(\"base_year_assignment_skims\", which_ones=\"all\", format=\"omx\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Future-year demand with IPF\nWe apply random growth factors to the base-year origins and destinations, then\nbalance their totals. We use iterative proportional fitting (IPF) to fit the base-year\ndemand matrix to these future-year vectors.\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 by up to 10% and balance the totals.\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[:])\nipf = Ipf(\n    project=project,\n    matrix=demand,\n    vectors=vectors,\n    column_field=\"destinations\",\n    row_field=\"origins\",\n    nan_as_zero=True,\n)\nipf.fit()\n\n# Save the balanced matrix into the project's matrix folder.\nipf.save_to_project(file_name=\"demand_ipfd.omx\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Define a custom quadratic VDF\nThe VDF and its derivative write directly to their output arrays, ``congested_time``\nand ``delta``. See `creating_custom_vdfs` for the callable signatures and other\nways to define a custom VDF.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def 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": [
        "## Future-year assignment with the custom VDF\nWe use the demand matrix from IPF and select two sets of links for select link analysis.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "future_demand = proj_matrices.get_matrix(\"demand_ipfd.omx\", subset=[\"matrix\"])\nselect_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 analyse. The input is a dictionary with strings as keys and lists of tuples\nas values, 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": "markdown",
      "metadata": {},
      "source": [
        "We reuse the base-year traffic class settings with the future-year demand and select link sets.\nUnlike the base-year BPR assignment, which maps its parameters to network fields,\nthis assignment uses the same values of ``a`` and ``b`` on every link.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "assigclass = replace(assigclass, demand=future_demand, 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
}