{
  "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.paths.PathResults`\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.utils.create_example import create_example\nfrom aequilibrae.paths.results 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 analyze the mode car or 'c' in our model\nmode = \"c\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We need to create the graph, but before that, we need to have at least one centroid in our network.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# We get an arbitrary node to set as centroid and allow for the construction of graphs\nnodes = project.network.nodes\ncentroid_count = nodes.data.query('is_centroid == 1').shape[0]\n\nif centroid_count == 0:\n    arbitrary_node = nodes.data[\"node_id\"][0]\n    nd = nodes.get(arbitrary_node)\n    nd.is_centroid = 1\n    nd.save()\n\nnetwork = project.network\nnetwork.build_graphs(modes=[mode])\ngraph = network.graphs[mode]\ngraph.set_blocked_centroid_flows(False)\n\nif centroid_count == 0:\n    # Let's revert to setting up that node as centroid in case we had to do it\n\n    nd.is_centroid = 0\n    nd.save()"
      ]
    },
    {
      "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.set_graph(\"distance\")\ngraph.set_skimming(\"distance\")"
      ]
    },
    {
      "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": [
        "And prepare the path computation structure\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "res = PathResults()\nres.prepare(graph)"
      ]
    },
    {
      "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.reset()\n    res.compute_path(missing_nodes[0], missing_nodes[1])\n    res.predecessors[graph.nodes_to_indices[missing_nodes[0]]] = 0\n    connected = graph.all_nodes[np.where(res.predecessors >= 0)]\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.10.18"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}