{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n\n# Finding disconnected links\n\nIn this example, we show how to find disconnected links in an AequilibraE network.\n\nWe use the Nauru example to find disconnected links.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        ".. seealso::\n    Several functions, methods, classes and modules are used in this example:\n\n    * :func:`aequilibrae.routing.results.path_results`\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Imports\nfrom uuid import uuid4\nfrom tempfile import gettempdir\nfrom os.path import join\nfrom datetime import datetime\nimport pandas as pd\nimport numpy as np\nfrom aequilibrae.examples import create_example\nfrom aequilibrae.routing import PathResults"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# We create an empty project on an arbitrary folder\nfldr = join(gettempdir(), uuid4().hex)\n\n# Let's use the Nauru example project for display\nproject = create_example(fldr, \"nauru\")\n\n# Let's analyse the mode car or 'c' in our model\nmode = \"c\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We can create an uncompressed graph without any centroids or changes to the project.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# We get the project nodes for reporting and load an independent network snapshot.\nnodes = project.tables.nodes\nnetwork = project.road.build_network()\n# No centroid changes need reverting: the project nodes have not been modified."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We set the graph for computation\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "graph = network.build_graph(mode=mode, cost=\"distance\", skimming=[\"distance\"], block_centroid_flows=False)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Get the nodes that are part of the car network\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "missing_nodes = nodes.data.query(\"modes.str.contains(@mode)\")[\"node_id\"].values"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Now we can compute all the path islands we have\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "islands = []\nidx_islands = 0\n\nwhile missing_nodes.shape[0] >= 2:\n    print(datetime.now().strftime(\"%H:%M:%S\"), f\" - Computing island: {idx_islands}\")\n    res = PathResults(graph, missing_nodes[0], missing_nodes[1])\n    connected = res.node_ids[res.terminal_states != res.search_results.sentinel]\n    connected = np.intersect1d(missing_nodes, connected)\n    missing_nodes = np.setdiff1d(missing_nodes, connected)\n    print(f\"    Nodes to find: {missing_nodes.shape[0]:,}\")\n    df = pd.DataFrame({\"node_id\": connected, \"island\": idx_islands})\n    islands.append(df)\n    idx_islands += 1\n\nprint(f\"\\nWe found {idx_islands} islands\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's consolidate everything into a single DataFrame\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "islands = pd.concat(islands)\n\n# And save to disk alongside our model\nislands.to_csv(join(fldr, \"island_outputs_complete.csv\"), index=False)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "If you join the ``node_id`` field in the CSV file generated above with the ``a_node`` or ``b_node`` \nfields in the links table, you will have the corresponding links in each disjoint island found.\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
}