{
  "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": [
        "Imports\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from 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": "markdown",
      "metadata": {},
      "source": [
        "We create an empty project on an arbitrary folder\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fldr = 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\ncentroid_count = project.conn.execute(\"select count(*) from nodes where is_centroid=1\").fetchone()[0]\n\nif centroid_count == 0:\n    arbitrary_node = project.conn.execute(\"select node_id from nodes limit 1\").fetchone()[0]\n    nodes = project.network.nodes\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\")\n\n# Get the nodes that are part of the car network\nmissing_nodes = [\n    x[0] for x in project.conn.execute(f\"Select node_id from nodes where instr(modes, '{mode}')\").fetchall()\n]\nmissing_nodes = np.array(missing_nodes)\n\n# And prepare the path computation structure\nres = 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": [
        "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 fields\nin 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.9.16"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}