{
  "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.routing.graph`\n    * :func:`aequilibrae.traffic.TrafficClass`\n    * :func:`aequilibrae.traffic.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 scipy.sparse import csr_array\n\nfrom aequilibrae.matrix import from_dict\nfrom aequilibrae.traffic import TrafficAssignment, TrafficClass\nfrom aequilibrae.traffic.vdf import bpr\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)"
      ]
    },
    {
      "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": [
        "## Traffic assignment\n\n"
      ]
    },
    {
      "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 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.get_available_matrices_and_metadata()"
      ]
    },
    {
      "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\", subset=[\"matrix\"])\n\n# Copy the named matrices into sparse float64 storage. In practise these would\n# be stored in the sparse OMX extension rather than as a dense matrix, then\n# converted to a sparse format.\ndemand = from_dict(\n    {name: csr_array(values, dtype=\"float64\") for name, values in demand.items()},\n    index=demand.index,\n)"
      ]
    },
    {
      "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\", mode=\"c\", cost=\"free_flow_time\", demand=demand, skimming=[],\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=10, rgap=0.01)"
      ]
    },
    {
      "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\"].field_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.11.18"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}