
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "_auto_examples/other_applications/plot_find_disconnected.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. note::
        :class: sphx-glr-download-link-note

        :ref:`Go to the end <sphx_glr_download__auto_examples_other_applications_plot_find_disconnected.py>`
        to download the full example code.

.. rst-class:: sphx-glr-example-title

.. _sphx_glr__auto_examples_other_applications_plot_find_disconnected.py:


.. _find_disconnected_links:

Finding disconnected links
==========================

In this example, we show how to find disconnected links in an AequilibraE network.

We use the Nauru example to find disconnected links.

.. GENERATED FROM PYTHON SOURCE LINES 29-33

.. seealso::
    Several functions, methods, classes and modules are used in this example:

    * :func:`aequilibrae.paths.PathResults`

.. GENERATED FROM PYTHON SOURCE LINES 35-46

.. code-block:: Python


    # Imports
    from uuid import uuid4
    from tempfile import gettempdir
    from os.path import join
    from datetime import datetime
    import pandas as pd
    import numpy as np
    from aequilibrae.utils.create_example import create_example
    from aequilibrae.paths.results import PathResults








.. GENERATED FROM PYTHON SOURCE LINES 48-58

.. code-block:: Python


    # We create an empty project on an arbitrary folder
    fldr = join(gettempdir(), uuid4().hex)

    # Let's use the Nauru example project for display
    project = create_example(fldr, "nauru")

    # Let's analyze the mode car or 'c' in our model
    mode = "c"








.. GENERATED FROM PYTHON SOURCE LINES 59-60

We need to create the graph, but before that, we need to have at least one centroid in our network.

.. GENERATED FROM PYTHON SOURCE LINES 60-82

.. code-block:: Python


    # We get an arbitrary node to set as centroid and allow for the construction of graphs
    centroid_count = project.conn.execute("select count(*) from nodes where is_centroid=1").fetchone()[0]

    if centroid_count == 0:
        arbitrary_node = project.conn.execute("select node_id from nodes limit 1").fetchone()[0]
        nodes = project.network.nodes
        nd = nodes.get(arbitrary_node)
        nd.is_centroid = 1
        nd.save()

    network = project.network
    network.build_graphs(modes=[mode])
    graph = network.graphs[mode]
    graph.set_blocked_centroid_flows(False)

    if centroid_count == 0:
        # Let's revert to setting up that node as centroid in case we had to do it

        nd.is_centroid = 0
        nd.save()








.. GENERATED FROM PYTHON SOURCE LINES 83-84

We set the graph for computation

.. GENERATED FROM PYTHON SOURCE LINES 84-87

.. code-block:: Python

    graph.set_graph("distance")
    graph.set_skimming("distance")








.. GENERATED FROM PYTHON SOURCE LINES 88-89

Get the nodes that are part of the car network

.. GENERATED FROM PYTHON SOURCE LINES 89-94

.. code-block:: Python

    missing_nodes = [
        x[0] for x in project.conn.execute(f"Select node_id from nodes where instr(modes, '{mode}')").fetchall()
    ]
    missing_nodes = np.array(missing_nodes)








.. GENERATED FROM PYTHON SOURCE LINES 95-96

And prepare the path computation structure

.. GENERATED FROM PYTHON SOURCE LINES 96-99

.. code-block:: Python

    res = PathResults()
    res.prepare(graph)








.. GENERATED FROM PYTHON SOURCE LINES 100-101

Now we can compute all the path islands we have

.. GENERATED FROM PYTHON SOURCE LINES 101-120

.. code-block:: Python


    islands = []
    idx_islands = 0

    while missing_nodes.shape[0] >= 2:
        print(datetime.now().strftime("%H:%M:%S"), f" - Computing island: {idx_islands}")
        res.reset()
        res.compute_path(missing_nodes[0], missing_nodes[1])
        res.predecessors[graph.nodes_to_indices[missing_nodes[0]]] = 0
        connected = graph.all_nodes[np.where(res.predecessors >= 0)]
        connected = np.intersect1d(missing_nodes, connected)
        missing_nodes = np.setdiff1d(missing_nodes, connected)
        print(f"    Nodes to find: {missing_nodes.shape[0]:,}")
        df = pd.DataFrame({"node_id": connected, "island": idx_islands})
        islands.append(df)
        idx_islands += 1

    print(f"\nWe found {idx_islands} islands")





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    00:40:28  - Computing island: 0
        Nodes to find: 2
    00:40:28  - Computing island: 1
        Nodes to find: 0

    We found 2 islands




.. GENERATED FROM PYTHON SOURCE LINES 121-122

Let's consolidate everything into a single DataFrame

.. GENERATED FROM PYTHON SOURCE LINES 122-127

.. code-block:: Python

    islands = pd.concat(islands)

    # And save to disk alongside our model
    islands.to_csv(join(fldr, "island_outputs_complete.csv"), index=False)








.. GENERATED FROM PYTHON SOURCE LINES 128-130

If you join the ``node_id`` field in the CSV file generated above with the ``a_node`` or ``b_node`` 
fields in the links table, you will have the corresponding links in each disjoint island found.

.. GENERATED FROM PYTHON SOURCE LINES 132-133

.. code-block:: Python

    project.close()








.. rst-class:: sphx-glr-timing

   **Total running time of the script:** (0 minutes 0.165 seconds)


.. _sphx_glr_download__auto_examples_other_applications_plot_find_disconnected.py:

.. only:: html

  .. container:: sphx-glr-footer sphx-glr-footer-example

    .. container:: sphx-glr-download sphx-glr-download-jupyter

      :download:`Download Jupyter notebook: plot_find_disconnected.ipynb <plot_find_disconnected.ipynb>`

    .. container:: sphx-glr-download sphx-glr-download-python

      :download:`Download Python source code: plot_find_disconnected.py <plot_find_disconnected.py>`

    .. container:: sphx-glr-download sphx-glr-download-zip

      :download:`Download zipped: plot_find_disconnected.zip <plot_find_disconnected.zip>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_
