Python networkx.is_strongly_connected() Examples

The following are 18 code examples of networkx.is_strongly_connected(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module networkx , or try the search function .
Example #1
Source File: connectivity.py    From pycog with MIT License 6 votes vote down vote up
def is_connected(C):
        """
        Return `True` if the square connection matrix `C` is connected, i.e., every
        unit is reachable from every other unit, otherwise `False`.

        Note
        ----

        This function only performs the check if the NetworkX package is available:

          https://networkx.github.io/

        """
        if nx is None:
            return True

        G = nx.from_numpy_matrix(C, create_using=nx.DiGraph())
        return nx.is_strongly_connected(G) 
Example #2
Source File: test_maxflow.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def validate_cuts(G, s, t, solnValue, partition, capacity, flow_func):
    assert_true(all(n in G for n in partition[0]),
                msg=msg.format(flow_func.__name__))
    assert_true(all(n in G for n in partition[1]),
                msg=msg.format(flow_func.__name__))
    cutset = compute_cutset(G, partition)
    assert_true(all(G.has_edge(u, v) for (u, v) in cutset),
                msg=msg.format(flow_func.__name__))
    assert_equal(solnValue, sum(G[u][v][capacity] for (u, v) in cutset),
                msg=msg.format(flow_func.__name__))
    H = G.copy()
    H.remove_edges_from(cutset)
    if not G.is_directed():
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
    else:
        assert_false(nx.is_strongly_connected(H),
                     msg=msg.format(flow_func.__name__)) 
Example #3
Source File: test_maxflow.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def validate_cuts(G, s, t, solnValue, partition, capacity, flow_func):
    assert_true(all(n in G for n in partition[0]),
                msg=msg.format(flow_func.__name__))
    assert_true(all(n in G for n in partition[1]),
                msg=msg.format(flow_func.__name__))
    cutset = compute_cutset(G, partition)
    assert_true(all(G.has_edge(u, v) for (u, v) in cutset),
                msg=msg.format(flow_func.__name__))
    assert_equal(solnValue, sum(G[u][v][capacity] for (u, v) in cutset),
                msg=msg.format(flow_func.__name__))
    H = G.copy()
    H.remove_edges_from(cutset)
    if not G.is_directed():
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
    else:
        assert_false(nx.is_strongly_connected(H),
                     msg=msg.format(flow_func.__name__)) 
Example #4
Source File: test_maxflow.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def validate_cuts(G, s, t, solnValue, partition, capacity, flow_func):
    assert_true(all(n in G for n in partition[0]),
                msg=msg.format(flow_func.__name__))
    assert_true(all(n in G for n in partition[1]),
                msg=msg.format(flow_func.__name__))
    cutset = compute_cutset(G, partition)
    assert_true(all(G.has_edge(u, v) for (u, v) in cutset),
                msg=msg.format(flow_func.__name__))
    assert_equal(solnValue, sum(G[u][v][capacity] for (u, v) in cutset),
                 msg=msg.format(flow_func.__name__))
    H = G.copy()
    H.remove_edges_from(cutset)
    if not G.is_directed():
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
    else:
        assert_false(nx.is_strongly_connected(H),
                     msg=msg.format(flow_func.__name__)) 
Example #5
Source File: test_strongly_connected.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_connected_raise(self):
        G=nx.Graph()
        assert_raises(NetworkXNotImplemented, nx.strongly_connected_components, G)
        assert_raises(NetworkXNotImplemented, nx.kosaraju_strongly_connected_components, G)
        assert_raises(NetworkXNotImplemented, nx.strongly_connected_components_recursive, G)
        assert_raises(NetworkXNotImplemented, nx.strongly_connected_component_subgraphs, G)
        assert_raises(NetworkXNotImplemented, nx.is_strongly_connected, G)
        assert_raises(nx.NetworkXPointlessConcept, nx.is_strongly_connected, nx.DiGraph())
        assert_raises(NetworkXNotImplemented, nx.condensation, G) 
Example #6
Source File: test_strongly_connected.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_is_strongly_connected(self):
        for G, C in self.gc:
            if len(C) == 1:
                assert_true(nx.is_strongly_connected(G))
            else:
                assert_false(nx.is_strongly_connected(G)) 
Example #7
Source File: euler.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def is_eulerian(G):
    """Returns True if and only if `G` is Eulerian.

    A graph is *Eulerian* if it has an Eulerian circuit. An *Eulerian
    circuit* is a closed walk that includes each edge of a graph exactly
    once.

    Parameters
    ----------
    G : NetworkX graph
       A graph, either directed or undirected.

    Examples
    --------
    >>> nx.is_eulerian(nx.DiGraph({0: [3], 1: [2], 2: [3], 3: [0, 1]}))
    True
    >>> nx.is_eulerian(nx.complete_graph(5))
    True
    >>> nx.is_eulerian(nx.petersen_graph())
    False

    Notes
    -----
    If the graph is not connected (or not strongly connected, for
    directed graphs), this function returns False.

    """
    if G.is_directed():
        # Every node must have equal in degree and out degree and the
        # graph must be strongly connected
        return (all(G.in_degree(n) == G.out_degree(n) for n in G) and
                nx.is_strongly_connected(G))
    # An undirected Eulerian graph has no vertices of odd degree and
    # must be connected.
    return all(d % 2 == 0 for v, d in G.degree()) and nx.is_connected(G) 
Example #8
Source File: test_strongly_connected.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_connected_raise(self):
        G = nx.Graph()
        assert_raises(NetworkXNotImplemented, nx.strongly_connected_components, G)
        assert_raises(NetworkXNotImplemented, nx.kosaraju_strongly_connected_components, G)
        assert_raises(NetworkXNotImplemented, nx.strongly_connected_components_recursive, G)
        assert_raises(NetworkXNotImplemented, nx.is_strongly_connected, G)
        assert_raises(nx.NetworkXPointlessConcept, nx.is_strongly_connected, nx.DiGraph())
        assert_raises(NetworkXNotImplemented, nx.condensation, G)
        # deprecated
        assert_raises(NetworkXNotImplemented, nx.strongly_connected_component_subgraphs, G)

#    Commented out due to variability on Travis-CI hardware/operating systems
#    def test_linear_time(self):
#        # See Issue #2831
#        count = 100  # base case
#        dg = nx.DiGraph()
#        dg.add_nodes_from([0, 1])
#        for i in range(2, count):
#            dg.add_node(i)
#            dg.add_edge(i, 1)
#            dg.add_edge(0, i)
#        t = time.time()
#        ret = tuple(nx.strongly_connected_components(dg))
#        dt = time.time() - t
#
#        count = 200
#        dg = nx.DiGraph()
#        dg.add_nodes_from([0, 1])
#        for i in range(2, count):
#            dg.add_node(i)
#            dg.add_edge(i, 1)
#            dg.add_edge(0, i)
#        t = time.time()
#        ret = tuple(nx.strongly_connected_components(dg))
#        dt2 = time.time() - t
#        assert_less(dt2, dt * 2.3)  # should be 2 times longer for this graph 
Example #9
Source File: test_strongly_connected.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_null_graph(self):
        G = nx.DiGraph()
        assert_equal(list(nx.strongly_connected_components(G)), [])
        assert_equal(list(nx.kosaraju_strongly_connected_components(G)), [])
        assert_equal(list(nx.strongly_connected_components_recursive(G)), [])
        assert_equal(len(nx.condensation(G)), 0)
        assert_raises(nx.NetworkXPointlessConcept, nx.is_strongly_connected, nx.DiGraph()) 
Example #10
Source File: test_strongly_connected.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_is_strongly_connected(self):
        for G, C in self.gc:
            if len(C) == 1:
                assert_true(nx.is_strongly_connected(G))
            else:
                assert_false(nx.is_strongly_connected(G))

    # deprecated 
Example #11
Source File: euler.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_eulerian(G):
    """Returns True if and only if `G` is Eulerian.

    A graph is *Eulerian* if it has an Eulerian circuit. An *Eulerian
    circuit* is a closed walk that includes each edge of a graph exactly
    once.

    Parameters
    ----------
    G : NetworkX graph
       A graph, either directed or undirected.

    Examples
    --------
    >>> nx.is_eulerian(nx.DiGraph({0: [3], 1: [2], 2: [3], 3: [0, 1]}))
    True
    >>> nx.is_eulerian(nx.complete_graph(5))
    True
    >>> nx.is_eulerian(nx.petersen_graph())
    False

    Notes
    -----
    If the graph is not connected (or not strongly connected, for
    directed graphs), this function returns False.

    """
    if G.is_directed():
        # Every node must have equal in degree and out degree and the
        # graph must be strongly connected
        return (all(G.in_degree(n) == G.out_degree(n) for n in G) and
                nx.is_strongly_connected(G))
    # An undirected Eulerian graph has no vertices of odd degree and
    # must be connected.
    return all(d % 2 == 0 for v, d in G.degree()) and nx.is_connected(G) 
Example #12
Source File: test_strongly_connected.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_connected_raise(self):
        G=nx.Graph()
        assert_raises(NetworkXNotImplemented, nx.strongly_connected_components, G)
        assert_raises(NetworkXNotImplemented, nx.kosaraju_strongly_connected_components, G)
        assert_raises(NetworkXNotImplemented, nx.strongly_connected_components_recursive, G)
        assert_raises(NetworkXNotImplemented, nx.strongly_connected_component_subgraphs, G)
        assert_raises(NetworkXNotImplemented, nx.is_strongly_connected, G)
        assert_raises(nx.NetworkXPointlessConcept, nx.is_strongly_connected, nx.DiGraph())
        assert_raises(NetworkXNotImplemented, nx.condensation, G) 
Example #13
Source File: test_strongly_connected.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_is_strongly_connected(self):
        for G, C in self.gc:
            if len(C) == 1:
                assert_true(nx.is_strongly_connected(G))
            else:
                assert_false(nx.is_strongly_connected(G)) 
Example #14
Source File: euler.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def is_eulerian(G):
    """Return True if G is an Eulerian graph, False otherwise.

    An Eulerian graph is a graph with an Eulerian circuit.

    Parameters
    ----------
    G : graph
       A NetworkX Graph

    Examples
    --------
    >>> nx.is_eulerian(nx.DiGraph({0:[3], 1:[2], 2:[3], 3:[0, 1]}))
    True
    >>> nx.is_eulerian(nx.complete_graph(5))
    True
    >>> nx.is_eulerian(nx.petersen_graph())
    False

    Notes
    -----
    This implementation requires the graph to be connected
    (or strongly connected for directed graphs).
    """
    if G.is_directed():
        # Every node must have equal in degree and out degree
        for n in G.nodes_iter():
            if G.in_degree(n) != G.out_degree(n):
               return False
        # Must be strongly connected
        if not nx.is_strongly_connected(G):
            return False
    else:
        # An undirected Eulerian graph has no vertices of odd degrees
        for v,d in G.degree_iter():
            if d % 2 != 0:
                return False
        # Must be connected
        if not nx.is_connected(G):
            return False
    return True 
Example #15
Source File: test_paths.py    From peartree with MIT License 5 votes vote down vote up
def test_synthetic_network_with_custom_stops():
    # Load in the GeoJSON as a JSON and convert to a dictionary
    geojson_path = fixture('synthetic_east_bay.geojson')
    with open(geojson_path, 'r') as gjf:
        reference_geojson = json.load(gjf)

    # Add in specific, custom stops under new properties key
    custom_stops = [[-122.29225158691406, 37.80876678753658],
                    [-122.28886127471924, 37.82341261847038],
                    [-122.2701072692871, 37.83005652796547]]
    reference_geojson['features'][0]['properties']['stops'] = custom_stops

    G1 = load_synthetic_network_as_graph(reference_geojson)

    # Sanity check the outputs against the custom stops input
    assert len(list(G1.nodes())) == (len(custom_stops) + 2)
    assert len(list(G1.edges())) == (len(custom_stops) + 1)

    # Go back to the GeoJSON and set optional bidirectional flag
    reference_geojson['features'][0]['properties']['bidirectional'] = True

    G2 = load_synthetic_network_as_graph(reference_geojson)

    # We re-use the same stop nodes for both directions
    nodes = list(G2.nodes())
    assert len(nodes) == (len(custom_stops) + 2)

    # Double the number of edges as before
    edges = list(G2.edges())
    assert len(edges) == (len(custom_stops) + 1) * 2

    # But now, by asking for a bidirectional graph, we can assert strong
    assert nx.is_strongly_connected(G2) 
Example #16
Source File: test_paths.py    From peartree with MIT License 5 votes vote down vote up
def test_synthetic_network():
    # Load in the GeoJSON as a JSON and convert to a dictionary
    geojson_path = fixture('synthetic_east_bay.geojson')
    with open(geojson_path, 'r') as gjf:
        reference_geojson = json.load(gjf)

    G1 = load_synthetic_network_as_graph(reference_geojson)

    # This fixture gets broken into 15 chunks, so 15 + 1 = 16
    nodes = list(G1.nodes())
    assert len(nodes) == 16

    # And since it is one-directional, it gets the same edges as chunks
    edges = list(G1.edges())
    assert len(edges) == 15

    # Since this is a one-way graph, with no other context, the
    # graph will be weakly connected
    assert nx.is_strongly_connected(G1) is False

    # Go back to the GeoJSON and set optional bidirectional flag
    for i in range(len(reference_geojson['features'])):
        reference_geojson['features'][i]['properties']['bidirectional'] = True

    G2 = load_synthetic_network_as_graph(reference_geojson)

    # We re-use the same stop nodes for both directions
    nodes = list(G2.nodes())
    assert len(nodes) == 16

    # Double the number of edges as before
    edges = list(G2.edges())
    assert len(edges) == 15 * 2

    # But now, by asking for a bidirectional graph, we can assert strong
    assert nx.is_strongly_connected(G2) 
Example #17
Source File: utils_graph.py    From osmnx with MIT License 4 votes vote down vote up
def get_largest_component(G, strongly=False):
    """
    Get subgraph of MultiDiGraph's largest weakly/strongly connected component.

    Parameters
    ----------
    G : networkx.MultiDiGraph
        input graph
    strongly : bool
        if True, return the largest strongly instead of weakly connected
        component

    Returns
    -------
    G : networkx.MultiDiGraph
        the largest connected component subgraph from the original graph
    """
    original_len = len(list(G.nodes()))

    if strongly:
        # if the graph is not connected retain only the largest strongly connected component
        if not nx.is_strongly_connected(G):

            # get all the strongly connected components in graph then identify the largest
            sccs = nx.strongly_connected_components(G)
            largest_scc = max(sccs, key=len)
            G = induce_subgraph(G, largest_scc)

            msg = (
                f"Graph was not connected, retained only the largest strongly "
                f"connected component ({len(G)} of {original_len} total nodes)"
            )
            utils.log(msg)
    else:
        # if the graph is not connected retain only the largest weakly connected component
        if not nx.is_weakly_connected(G):

            # get all the weakly connected components in graph then identify the largest
            wccs = nx.weakly_connected_components(G)
            largest_wcc = max(wccs, key=len)
            G = induce_subgraph(G, largest_wcc)

            msg = (
                f"Graph was not connected, retained only the largest weakly "
                f"connected component ({len(G)} of {original_len} total nodes)"
            )
            utils.log(msg)

    return G 
Example #18
Source File: osmnx_funcs.py    From apls with Apache License 2.0 4 votes vote down vote up
def get_largest_component(G, strongly=False):
    """
    https://github.com/gboeing/osmnx/blob/master/osmnx/utils.py
    Return a subgraph of the largest weakly or strongly connected component
    from a directed graph.
    Parameters
    ----------
    G : networkx multidigraph
    strongly : bool
        if True, return the largest strongly instead of weakly connected
        component
    Returns
    -------
    G : networkx multidigraph
        the largest connected component subgraph from the original graph
    """

    start_time = time.time()
    original_len = len(list(G.nodes()))

    if strongly:
        # if the graph is not connected retain only the largest strongly connected component
        if not nx.is_strongly_connected(G):

            # get all the strongly connected components in graph then identify the largest
            sccs = nx.strongly_connected_components(G)
            largest_scc = max(sccs, key=len)
            G = induce_subgraph(G, largest_scc)

            msg = ('Graph was not connected, retained only the largest strongly '
                   'connected component ({:,} of {:,} total nodes) in {:.2f} seconds')
            print(msg.format(len(list(G.nodes())), original_len, time.time()-start_time))
    else:
        # if the graph is not connected retain only the largest weakly connected component
        if not nx.is_weakly_connected(G):

            # get all the weakly connected components in graph then identify the largest
            wccs = nx.weakly_connected_components(G)
            largest_wcc = max(wccs, key=len)
            G = induce_subgraph(G, largest_wcc)

            msg = ('Graph was not connected, retained only the largest weakly '
                   'connected component ({:,} of {:,} total nodes) in {:.2f} seconds')
            print(msg.format(len(list(G.nodes())), original_len, time.time()-start_time))

    return G