Python networkx.is_connected() Examples

The following are 30 code examples of networkx.is_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: utils.py    From GraphRNN with MIT License 7 votes vote down vote up
def decode_graph(adj, prefix):
    adj = np.asmatrix(adj)
    G = nx.from_numpy_matrix(adj)
    # G.remove_nodes_from(nx.isolates(G))
    print('num of nodes: {}'.format(G.number_of_nodes()))
    print('num of edges: {}'.format(G.number_of_edges()))
    G_deg = nx.degree_histogram(G)
    G_deg_sum = [a * b for a, b in zip(G_deg, range(0, len(G_deg)))]
    print('average degree: {}'.format(sum(G_deg_sum) / G.number_of_nodes()))
    if nx.is_connected(G):
        print('average path length: {}'.format(nx.average_shortest_path_length(G)))
        print('average diameter: {}'.format(nx.diameter(G)))
    G_cluster = sorted(list(nx.clustering(G).values()))
    print('average clustering coefficient: {}'.format(sum(G_cluster) / len(G_cluster)))
    cycle_len = []
    cycle_all = nx.cycle_basis(G, 0)
    for item in cycle_all:
        cycle_len.append(len(item))
    print('cycles', cycle_len)
    print('cycle count', len(cycle_len))
    draw_graph(G, prefix=prefix) 
Example #2
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 #3
Source File: utils.py    From graph-generation with MIT License 6 votes vote down vote up
def decode_graph(adj, prefix):
    adj = np.asmatrix(adj)
    G = nx.from_numpy_matrix(adj)
    # G.remove_nodes_from(nx.isolates(G))
    print('num of nodes: {}'.format(G.number_of_nodes()))
    print('num of edges: {}'.format(G.number_of_edges()))
    G_deg = nx.degree_histogram(G)
    G_deg_sum = [a * b for a, b in zip(G_deg, range(0, len(G_deg)))]
    print('average degree: {}'.format(sum(G_deg_sum) / G.number_of_nodes()))
    if nx.is_connected(G):
        print('average path length: {}'.format(nx.average_shortest_path_length(G)))
        print('average diameter: {}'.format(nx.diameter(G)))
    G_cluster = sorted(list(nx.clustering(G).values()))
    print('average clustering coefficient: {}'.format(sum(G_cluster) / len(G_cluster)))
    cycle_len = []
    cycle_all = nx.cycle_basis(G, 0)
    for item in cycle_all:
        cycle_len.append(len(item))
    print('cycles', cycle_len)
    print('cycle count', len(cycle_len))
    draw_graph(G, prefix=prefix) 
Example #4
Source File: main.py    From scTDA with GNU General Public License v3.0 6 votes vote down vote up
def dendritic_graph(self):
        """
        Builds skeleton of the topological representation (used internally)
        """
        diam = networkx.diameter(self.gl)
        g3 = networkx.Graph()
        dicdend = {}
        for n in range(diam-1):
            nodedist = []
            for k in self.pl:
                dil = networkx.shortest_path_length(self.gl, self.root, k)
                if dil == n:
                    nodedist.append(str(k))
            g2 = self.gl.subgraph(nodedist)
            dicdend[n] = sorted(networkx.connected_components(g2))
            for n2, yu in enumerate(dicdend[n]):
                g3.add_node(str(n) + '_' + str(n2))
                if n > 0:
                    for n3, yu2 in enumerate(dicdend[n-1]):
                        if networkx.is_connected(self.gl.subgraph(list(yu)+list(yu2))):
                            g3.add_edge(str(n) + '_' + str(n2), str(n-1) + '_' + str(n3))
        return g3, dicdend 
Example #5
Source File: test_cuts.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def test_octahedral_cutset():
    G=nx.octahedral_graph()
    for flow_func in flow_funcs:
        kwargs = dict(flow_func=flow_func)
        # edge cuts
        edge_cut = nx.minimum_edge_cut(G, **kwargs)
        assert_equal(4, len(edge_cut), msg=msg.format(flow_func.__name__))
        H = G.copy()
        H.remove_edges_from(edge_cut)
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
        # node cuts
        node_cut = nx.minimum_node_cut(G, **kwargs)
        assert_equal(4, len(node_cut), msg=msg.format(flow_func.__name__))
        H = G.copy()
        H.remove_nodes_from(node_cut)
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__)) 
Example #6
Source File: test_cuts.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def test_petersen_cutset():
    G = nx.petersen_graph()
    for flow_func in flow_funcs:
        kwargs = dict(flow_func=flow_func)
        # edge cuts
        edge_cut = nx.minimum_edge_cut(G, **kwargs)
        assert_equal(3, len(edge_cut), msg=msg.format(flow_func.__name__))
        H = G.copy()
        H.remove_edges_from(edge_cut)
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
        # node cuts
        node_cut = nx.minimum_node_cut(G, **kwargs)
        assert_equal(3, len(node_cut), msg=msg.format(flow_func.__name__))
        H = G.copy()
        H.remove_nodes_from(node_cut)
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__)) 
Example #7
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 #8
Source File: test_cuts.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_petersen_cutset():
    G = nx.petersen_graph()
    for flow_func in flow_funcs:
        kwargs = dict(flow_func=flow_func)
        # edge cuts
        edge_cut = nx.minimum_edge_cut(G, **kwargs)
        assert_equal(3, len(edge_cut), msg=msg.format(flow_func.__name__))
        H = G.copy()
        H.remove_edges_from(edge_cut)
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
        # node cuts
        node_cut = nx.minimum_node_cut(G, **kwargs)
        assert_equal(3, len(node_cut), msg=msg.format(flow_func.__name__))
        H = G.copy()
        H.remove_nodes_from(node_cut)
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__)) 
Example #9
Source File: test_cuts.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_icosahedral_cutset():
    G=nx.icosahedral_graph()
    for flow_func in flow_funcs:
        kwargs = dict(flow_func=flow_func)
        # edge cuts
        edge_cut = nx.minimum_edge_cut(G, **kwargs)
        assert_equal(5, len(edge_cut), msg=msg.format(flow_func.__name__))
        H = G.copy()
        H.remove_edges_from(edge_cut)
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
        # node cuts
        node_cut = nx.minimum_node_cut(G, **kwargs)
        assert_equal(5, len(node_cut), msg=msg.format(flow_func.__name__))
        H = G.copy()
        H.remove_nodes_from(node_cut)
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__)) 
Example #10
Source File: test_cuts.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_icosahedral_cutset():
    G = nx.icosahedral_graph()
    for flow_func in flow_funcs:
        kwargs = dict(flow_func=flow_func)
        # edge cuts
        edge_cut = nx.minimum_edge_cut(G, **kwargs)
        assert_equal(5, len(edge_cut), msg=msg.format(flow_func.__name__))
        H = G.copy()
        H.remove_edges_from(edge_cut)
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
        # node cuts
        node_cut = nx.minimum_node_cut(G, **kwargs)
        assert_equal(5, len(node_cut), msg=msg.format(flow_func.__name__))
        H = G.copy()
        H.remove_nodes_from(node_cut)
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__)) 
Example #11
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 #12
Source File: test_cuts.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_petersen_cutset():
    G = nx.petersen_graph()
    for flow_func in flow_funcs:
        kwargs = dict(flow_func=flow_func)
        # edge cuts
        edge_cut = nx.minimum_edge_cut(G, **kwargs)
        assert_equal(3, len(edge_cut), msg=msg.format(flow_func.__name__))
        H = G.copy()
        H.remove_edges_from(edge_cut)
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
        # node cuts
        node_cut = nx.minimum_node_cut(G, **kwargs)
        assert_equal(3, len(node_cut), msg=msg.format(flow_func.__name__))
        H = G.copy()
        H.remove_nodes_from(node_cut)
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__)) 
Example #13
Source File: graphcoloring.py    From pyDcop with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def generate_scalefree_graph(variables_count, m_edge, allow_subgraph):
    if not allow_subgraph:
        graph = nx.barabasi_albert_graph(variables_count, m_edge)
        is_connected = nx.is_connected(graph)
        while not is_connected:
            graph = nx.barabasi_albert_graph(variables_count, m_edge)
            is_connected = nx.is_connected(graph)
    else:
        graph = nx.barabasi_albert_graph(variables_count, m_edge)

    # In the obtained graph, low rank nodes will have a much higher edge count
    # than high rank nodes. We shuffle the nodes names to avoid this effect:
    new_nodes = list(range(variables_count))
    random.shuffle(new_nodes)
    node_mapping = {n: nn for n, nn in zip(graph.nodes, new_nodes)}

    new_graph = nx.Graph((node_mapping[e1], node_mapping[e2]) for e1, e2 in graph.edges)
    return new_graph 
Example #14
Source File: test_cuts.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_brandes_erlebach_book():
    # Figure 1 chapter 7: Connectivity
    # http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf
    G = nx.Graph()
    G.add_edges_from([(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 6), (3, 4),
                      (3, 6), (4, 6), (4, 7), (5, 7), (6, 8), (6, 9), (7, 8),
                      (7, 10), (8, 11), (9, 10), (9, 11), (10, 11)])
    for flow_func in flow_funcs:
        kwargs = dict(flow_func=flow_func)
        # edge cutsets
        assert_equal(3, len(nx.minimum_edge_cut(G, 1, 11, **kwargs)),
                     msg=msg.format(flow_func.__name__))
        edge_cut = nx.minimum_edge_cut(G, **kwargs)
        # Node 5 has only two edges
        assert_equal(2, len(edge_cut), msg=msg.format(flow_func.__name__))
        H = G.copy()
        H.remove_edges_from(edge_cut)
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
        # node cuts
        assert_equal(set([6, 7]), minimum_st_node_cut(G, 1, 11, **kwargs),
                     msg=msg.format(flow_func.__name__))
        assert_equal(set([6, 7]), nx.minimum_node_cut(G, 1, 11, **kwargs),
                     msg=msg.format(flow_func.__name__))
        node_cut = nx.minimum_node_cut(G, **kwargs)
        assert_equal(2, len(node_cut), msg=msg.format(flow_func.__name__))
        H = G.copy()
        H.remove_nodes_from(node_cut)
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__)) 
Example #15
Source File: test_cuts.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def _generate_no_biconnected(max_attempts=50):
    attempts = 0
    while True:
        G = nx.fast_gnp_random_graph(100,0.0575)
        if nx.is_connected(G) and not nx.is_biconnected(G):
            attempts = 0
            yield G
        else:
            if attempts >= max_attempts:
                msg = "Tried %d times: no suitable Graph."%attempts
                raise Exception(msg % max_attempts)
            else:
                attempts += 1 
Example #16
Source File: test_connected.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_is_connected(self):
        assert_true(nx.is_connected(self.grid))
        G = nx.Graph()
        G.add_nodes_from([1, 2])
        assert_false(nx.is_connected(G)) 
Example #17
Source File: connected.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def is_connected(G):
    """Return True if the graph is connected, false otherwise.

    Parameters
    ----------
    G : NetworkX Graph
       An undirected graph.

    Returns
    -------
    connected : bool
      True if the graph is connected, false otherwise.

    Raises
    ------
    NetworkXNotImplemented:
        If G is undirected.

    Examples
    --------
    >>> G = nx.path_graph(4)
    >>> print(nx.is_connected(G))
    True

    See Also
    --------
    is_strongly_connected
    is_weakly_connected
    is_semiconnected
    is_biconnected
    connected_components

    Notes
    -----
    For undirected graphs only.

    """
    if len(G) == 0:
        raise nx.NetworkXPointlessConcept('Connectivity is undefined ',
                                          'for the null graph.')
    return len(set(_plain_bfs(G, arbitrary_element(G)))) == len(G) 
Example #18
Source File: random_graphs.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def connected_watts_strogatz_graph(n, k, p, tries=100, seed=None):
    """Returns a connected Watts–Strogatz small-world graph.

    Attempts to generate a connected graph by repeated generation of
    Watts–Strogatz small-world graphs.  An exception is raised if the maximum
    number of tries is exceeded.

    Parameters
    ----------
    n : int
        The number of nodes
    k : int
        Each node is joined with its `k` nearest neighbors in a ring
        topology.
    p : float
        The probability of rewiring each edge
    tries : int
        Number of attempts to generate a connected graph.
    seed : int, optional
         The seed for random number generator.

    See Also
    --------
    newman_watts_strogatz_graph()
    watts_strogatz_graph()

    """
    for i in range(tries):
        G = watts_strogatz_graph(n, k, p, seed)
        if nx.is_connected(G):
            return G
    raise nx.NetworkXError('Maximum number of tries exceeded') 
Example #19
Source File: test_treewidth.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_tree_decomp(graph, decomp):
    """Check if the given tree decomposition is valid."""
    for x in graph.nodes():
        appear_once = False
        for bag in decomp.nodes():
            if x in bag:
                appear_once = True
                break
        ok_(appear_once)

    # Check if each connected pair of nodes are at least once together in a bag
    for (x, y) in graph.edges():
        appear_together = False
        for bag in decomp.nodes():
            if x in bag and y in bag:
                appear_together = True
                break
        ok_(appear_together)

    # Check if the nodes associated with vertex v form a connected subset of T
    for v in graph.nodes():
        subset = []
        for bag in decomp.nodes():
            if v in bag:
                subset.append(bag)
        sub_graph = decomp.subgraph(subset)
        ok_(nx.is_connected(sub_graph)) 
Example #20
Source File: test_connectivity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _generate_no_biconnected(max_attempts=50):
    attempts = 0
    while True:
        G = nx.fast_gnp_random_graph(100, 0.0575, seed=42)
        if nx.is_connected(G) and not nx.is_biconnected(G):
            attempts = 0
            yield G
        else:
            if attempts >= max_attempts:
                msg = "Tried %d times: no suitable Graph."
                raise Exception(msg % max_attempts)
            else:
                attempts += 1 
Example #21
Source File: test_cuts.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_edge_cutset_random_graphs():
    for flow_func in flow_funcs:
        for i in range(3):
            G = nx.fast_gnp_random_graph(50, 0.25, seed=42)
            if not nx.is_connected(G):
                ccs = iter(nx.connected_components(G))
                start = arbitrary_element(next(ccs))
                G.add_edges_from((start, arbitrary_element(c)) for c in ccs)
            cutset = nx.minimum_edge_cut(G, flow_func=flow_func)
            assert_equal(nx.edge_connectivity(G), len(cutset),
                         msg=msg.format(flow_func.__name__))
            G.remove_edges_from(cutset)
            assert_false(nx.is_connected(G), msg=msg.format(flow_func.__name__)) 
Example #22
Source File: test_cuts.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_node_cutset_random_graphs():
    for flow_func in flow_funcs:
        for i in range(3):
            G = nx.fast_gnp_random_graph(50, 0.25, seed=42)
            if not nx.is_connected(G):
                ccs = iter(nx.connected_components(G))
                start = arbitrary_element(next(ccs))
                G.add_edges_from((start, arbitrary_element(c)) for c in ccs)
            cutset = nx.minimum_node_cut(G, flow_func=flow_func)
            assert_equal(nx.node_connectivity(G), len(cutset),
                         msg=msg.format(flow_func.__name__))
            G.remove_nodes_from(cutset)
            assert_false(nx.is_connected(G), msg=msg.format(flow_func.__name__)) 
Example #23
Source File: graphcoloring.py    From pyDcop with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate_random_graph(variables_count, p_edge, allow_subgraph):
    if not allow_subgraph:
        graph = nx.gnp_random_graph(variables_count, p_edge)
        is_connected = nx.is_connected(graph)
        while not is_connected:
            graph = nx.gnp_random_graph(variables_count, p_edge)
            is_connected = nx.is_connected(graph)
    else:
        graph = nx.gnp_random_graph(variables_count, p_edge)
    return graph 
Example #24
Source File: test_cuts.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_white_harary_paper():
    # Figure 1b white and harary (2001)
    # http://eclectic.ss.uci.edu/~drwhite/sm-w23.PDF
    # A graph with high adhesion (edge connectivity) and low cohesion
    # (node connectivity)
    G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4))
    G.remove_node(7)
    for i in range(4, 7):
        G.add_edge(0, i)
    G = nx.disjoint_union(G, nx.complete_graph(4))
    G.remove_node(G.order() - 1)
    for i in range(7, 10):
        G.add_edge(0, i)
    for flow_func in flow_funcs:
        kwargs = dict(flow_func=flow_func)
        # edge cuts
        edge_cut = nx.minimum_edge_cut(G, **kwargs)
        assert_equal(3, len(edge_cut), msg=msg.format(flow_func.__name__))
        H = G.copy()
        H.remove_edges_from(edge_cut)
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
        # node cuts
        node_cut = nx.minimum_node_cut(G, **kwargs)
        assert_equal(set([0]), node_cut, msg=msg.format(flow_func.__name__))
        H = G.copy()
        H.remove_nodes_from(node_cut)
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__)) 
Example #25
Source File: test_cuts.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_brandes_erlebach_book():
    # Figure 1 chapter 7: Connectivity
    # http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf
    G = nx.Graph()
    G.add_edges_from([(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 6), (3, 4),
                      (3, 6), (4, 6), (4, 7), (5, 7), (6, 8), (6, 9), (7, 8),
                      (7, 10), (8, 11), (9, 10), (9, 11), (10, 11)])
    for flow_func in flow_funcs:
        kwargs = dict(flow_func=flow_func)
        # edge cutsets
        assert_equal(3, len(nx.minimum_edge_cut(G, 1, 11, **kwargs)),
                     msg=msg.format(flow_func.__name__))
        edge_cut = nx.minimum_edge_cut(G, **kwargs)
        # Node 5 has only two edges
        assert_equal(2, len(edge_cut), msg=msg.format(flow_func.__name__))
        H = G.copy()
        H.remove_edges_from(edge_cut)
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
        # node cuts
        assert_equal(set([6, 7]), minimum_st_node_cut(G, 1, 11, **kwargs),
                     msg=msg.format(flow_func.__name__))
        assert_equal(set([6, 7]), nx.minimum_node_cut(G, 1, 11, **kwargs),
                     msg=msg.format(flow_func.__name__))
        node_cut = nx.minimum_node_cut(G, **kwargs)
        assert_equal(2, len(node_cut), msg=msg.format(flow_func.__name__))
        H = G.copy()
        H.remove_nodes_from(node_cut)
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__)) 
Example #26
Source File: test_cuts.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _generate_no_biconnected(max_attempts=50):
    attempts = 0
    while True:
        G = nx.fast_gnp_random_graph(100, 0.0575, seed=42)
        if nx.is_connected(G) and not nx.is_biconnected(G):
            attempts = 0
            yield G
        else:
            if attempts >= max_attempts:
                msg = "Tried %d times: no suitable Graph." % attempts
                raise Exception(msg % max_attempts)
            else:
                attempts += 1 
Example #27
Source File: test_kcutsets.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_alternative_flow_functions():
    graphs = [nx.grid_2d_graph(4, 4),
              nx.cycle_graph(5)]
    for G in graphs:
        node_conn = nx.node_connectivity(G)
        for flow_func in flow_funcs:
            all_cuts = nx.all_node_cuts(G, flow_func=flow_func)
            # Only test a limited number of cut sets to reduce test time.
            for cut in itertools.islice(all_cuts, MAX_CUTSETS_TO_TEST):
                assert_equal(node_conn, len(cut))
                assert_false(nx.is_connected(nx.restricted_view(G, cut, []))) 
Example #28
Source File: motif_count.py    From role2vec with GNU General Public License v3.0 5 votes vote down vote up
def enumerate_graphs(self):
        """
        Enumerating connected benchmark graphlets.
        """
        graphs = graph_atlas_g()
        self.interesting_graphs = {i: [] for i in range(2, self.args.graphlet_size+1)}
        for graph in graphs:
            if graph.number_of_nodes() > 1 and  graph.number_of_nodes() < self.args.graphlet_size+1:
                if nx.is_connected(graph):
                    self.interesting_graphs[graph.number_of_nodes()].append(graph) 
Example #29
Source File: test_kcutsets.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _check_separating_sets(G):
    for cc in nx.connected_components(G):
        if len(cc) < 3:
            continue
        Gc = G.subgraph(cc)
        node_conn = nx.node_connectivity(Gc)
        all_cuts = nx.all_node_cuts(Gc)
        # Only test a limited number of cut sets to reduce test time.
        for cut in itertools.islice(all_cuts, MAX_CUTSETS_TO_TEST):
            assert_equal(node_conn, len(cut))
            assert_false(nx.is_connected(nx.restricted_view(G, cut, []))) 
Example #30
Source File: test_connected.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_connected_raise(self):
        assert_raises(NetworkXNotImplemented, nx.connected_components, self.DG)
        assert_raises(NetworkXNotImplemented, nx.number_connected_components, self.DG)
        assert_raises(NetworkXNotImplemented, nx.node_connected_component, self.DG, 1)
        assert_raises(NetworkXNotImplemented, nx.is_connected, self.DG)
        assert_raises(nx.NetworkXPointlessConcept, nx.is_connected, nx.Graph())
        # deprecated
        assert_raises(NetworkXNotImplemented, nx.connected_component_subgraphs, self.DG)