{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n\n# Assigning sparse matrices\n\nModern Activity-Based models (and even some trip-based and tour-based ones) result on incredibly sparse\ndemand matrices, which opens up a significant opportunity to save time during assignment by using early-exiting\nduring the path-computation phase of assignment.\n\nTo take advantage of this, while still computing assignment skims, AequilibraE has a built-in method to\nskim the last iteration after the assignment is done.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        ".. admonition:: Technical references\n\n  * :doc:`../../traffic_assignment/assignment_procedures`\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        ".. seealso::\n    Several functions, methods, classes and modules are used in this example:\n\n    * :func:`aequilibrae.paths.Graph`\n    * :func:`aequilibrae.paths.TrafficClass`\n    * :func:`aequilibrae.paths.TrafficAssignment`\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\nfrom aequilibrae.utils.create_example import create_example\nfrom aequilibrae.paths import TrafficAssignment, TrafficClass"
      ]
    },
    {
      "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)\nlogger = project.logger"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Traffic assignment\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We build all graphs\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "project.network.build_graphs()\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.\n\n# We grab the graph for cars\ngraph = project.network.graphs[\"c\"]\n\n# Let's say we want to minimize the free_flow_time\ngraph.set_graph(\"free_flow_time\")\n\n# And we will allow paths to be computed going through other centroids/centroid connectors\n# required for the Sioux Falls network, as all nodes are centroids\ngraph.set_blocked_centroid_flows(False)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's get the demand matrix directly from the project record, 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.list()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We get the demand matrix, and prepare it for computation\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "demand = proj_matrices.get_matrix(\"demand_omx\")\ndemand.computational_view([\"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(name=\"car\", graph=graph, matrix=demand)\n\nassig = TrafficAssignment()\n\n# We start by adding the list of traffic classes to be assigned\nassig.add_class(assigclass)\n\n# Then we set these parameters, which an only be configured after adding one class to the assignment\nassig.set_vdf(\"BPR\")  # This is not case-sensitive \n\n# Then we set the volume delay function and its parameters\nassig.set_vdf_parameters({\"alpha\": \"b\", \"beta\": \"power\"})\n\n# The capacity and free flow travel times as they exist in the graph\nassig.set_capacity_field(\"capacity\")\nassig.set_time_field(\"free_flow_time\")\n\n# And the algorithm we want to use to assign\nassig.set_algorithm(\"bfw\")\n\n# Let's set parameters that make this example run very fast\nassig.max_iter = 10\nassig.rgap_target = 0.01\n\n# we then execute the assignment\nassig.execute()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "After finishing the assignment, we can skim the last iteration\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "skims = assig.skim_congested([\"distance\"], return_matrices=True)\n\n# Skims are returned as a dictionary, with the class names as keys\n# Let's see all skims we have inside it:\nprint(skims[\"car\"].names)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We can save the skims, but we need to choose to only save the final ones, as the blended were not generated\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "assig.save_skims(\"base_year_assignment_skims\", which_ones=\"final\", format=\"omx\")"
      ]
    },
    {
      "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.10.18"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}