Python networkx.empty_graph() Examples

The following are 30 code examples of networkx.empty_graph(). 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: mol_graph.py    From hgraph2graph with MIT License 6 votes vote down vote up
def tree_decomp(self):
        clusters = self.clusters
        graph = nx.empty_graph( len(clusters) )
        for atom, nei_cls in enumerate(self.atom_cls):
            if len(nei_cls) <= 1: continue
            inter = set(self.clusters[nei_cls[0]])
            for cid in nei_cls:
                inter = inter & set(self.clusters[cid])
            assert len(inter) >= 1

            if len(nei_cls) > 2 and len(inter) == 1: # two rings + one bond has problem!
                clusters.append([atom])
                c2 = len(clusters) - 1
                graph.add_node(c2)
                for c1 in nei_cls:
                    graph.add_edge(c1, c2, weight = 100)
            else:
                for i,c1 in enumerate(nei_cls):
                    for c2 in nei_cls[i + 1:]:
                        union = set(clusters[c1]) | set(clusters[c2])
                        graph.add_edge(c1, c2, weight = len(union))

        n, m = len(graph.nodes), len(graph.edges)
        assert n - m <= 1 #must be connected
        return graph if n - m == 1 else nx.maximum_spanning_tree(graph) 
Example #2
Source File: test_classic.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_wheel_graph(self):
        for n, G in [(0, null_graph()), (1, empty_graph(1)),
                     (2, path_graph(2)), (3, complete_graph(3)),
                     (4, complete_graph(4))]:
            g=wheel_graph(n)
            assert_true(is_isomorphic( g, G))

        assert_equal(g.name, 'wheel_graph(4)')

        g=wheel_graph(10)
        assert_equal(sorted(list(g.degree().values())),
                     [3, 3, 3, 3, 3, 3, 3, 3, 3, 9])

        assert_raises(networkx.exception.NetworkXError,
                      wheel_graph, 10, create_using=DiGraph())

        mg=wheel_graph(10, create_using=MultiGraph())
        assert_equal(mg.edges(), g.edges()) 
Example #3
Source File: convert.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def from_edgelist(edgelist, create_using=None):
    """Returns a graph from a list of edges.

    Parameters
    ----------
    edgelist : list or iterator
      Edge tuples

    create_using : NetworkX graph constructor, optional (default=nx.Graph)
        Graph type to create. If graph instance, then cleared before populated.

    Examples
    --------
    >>> edgelist = [(0, 1)] # single edge (0,1)
    >>> G = nx.from_edgelist(edgelist)

    or

    >>> G = nx.Graph(edgelist) # use Graph constructor

    """
    G = nx.empty_graph(0, create_using)
    G.add_edges_from(edgelist)
    return G 
Example #4
Source File: test_classic.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_path_graph(self):
        p=path_graph(0)
        assert_true(is_isomorphic(p, null_graph()))
        assert_equal(p.name, 'path_graph(0)')

        p=path_graph(1)
        assert_true(is_isomorphic( p, empty_graph(1)))
        assert_equal(p.name, 'path_graph(1)')

        p=path_graph(10)
        assert_true(is_connected(p))
        assert_equal(sorted(list(p.degree().values())),
                     [1, 1, 2, 2, 2, 2, 2, 2, 2, 2])
        assert_equal(p.order()-1, p.size())

        dp=path_graph(3, create_using=DiGraph())
        assert_true(dp.has_edge(0,1))
        assert_false(dp.has_edge(1,0))

        mp=path_graph(10, create_using=MultiGraph())
        assert_true(mp.edges()==p.edges()) 
Example #5
Source File: test_layout.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_empty_graph(self):
        G = nx.empty_graph()
        vpos = nx.random_layout(G, center=(1, 1))
        assert_equal(vpos, {})
        vpos = nx.circular_layout(G, center=(1, 1))
        assert_equal(vpos, {})
        vpos = nx.planar_layout(G, center=(1, 1))
        assert_equal(vpos, {})
        vpos = nx.bipartite_layout(G, G)
        assert_equal(vpos, {})
        vpos = nx.spring_layout(G, center=(1, 1))
        assert_equal(vpos, {})
        vpos = nx.fruchterman_reingold_layout(G, center=(1, 1))
        assert_equal(vpos, {})
        vpos = nx.spectral_layout(G, center=(1, 1))
        assert_equal(vpos, {})
        vpos = nx.shell_layout(G, center=(1, 1))
        assert_equal(vpos, {}) 
Example #6
Source File: classic.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def ladder_graph(n,create_using=None):
    """Return the Ladder graph of length n.

    This is two rows of n nodes, with
    each pair connected by a single edge.

    Node labels are the integers 0 to 2*n - 1.

    """
    if create_using is not None and create_using.is_directed():
        raise nx.NetworkXError("Directed Graph not supported")
    G=empty_graph(2*n,create_using)
    G.name="ladder_graph_(%d)"%n
    G.add_edges_from([(v,v+1) for v in range(n-1)])
    G.add_edges_from([(v,v+1) for v in range(n,2*n-1)])
    G.add_edges_from([(v,v+n) for v in range(n)])
    return G 
Example #7
Source File: test_distance_measures.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_eccentricity(self):
        assert_equal(networkx.eccentricity(self.G,1),6)
        e=networkx.eccentricity(self.G)
        assert_equal(e[1],6)
        sp=networkx.shortest_path_length(self.G)
        e=networkx.eccentricity(self.G,sp=sp)
        assert_equal(e[1],6)
        e=networkx.eccentricity(self.G,v=1)
        assert_equal(e,6)
        e=networkx.eccentricity(self.G,v=[1,1])  #This behavior changed in version 1.8 (ticket #739)
        assert_equal(e[1],6)
        e=networkx.eccentricity(self.G,v=[1,2])
        assert_equal(e[1],6)
        # test against graph with one node
        G=networkx.path_graph(1)
        e=networkx.eccentricity(G)
        assert_equal(e[0],0)
        e=networkx.eccentricity(G,v=0)
        assert_equal(e,0)
        assert_raises(networkx.NetworkXError, networkx.eccentricity, G, 1)
        # test against empty graph
        G=networkx.empty_graph()
        e=networkx.eccentricity(G)
        assert_equal(e,{}) 
Example #8
Source File: test_distance_measures.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_eccentricity(self):
        assert_equal(networkx.eccentricity(self.G, 1), 6)
        e = networkx.eccentricity(self.G)
        assert_equal(e[1], 6)
        sp = dict(networkx.shortest_path_length(self.G))
        e = networkx.eccentricity(self.G, sp=sp)
        assert_equal(e[1], 6)
        e = networkx.eccentricity(self.G, v=1)
        assert_equal(e, 6)
        # This behavior changed in version 1.8 (ticket #739)
        e = networkx.eccentricity(self.G, v=[1, 1])
        assert_equal(e[1], 6)
        e = networkx.eccentricity(self.G, v=[1, 2])
        assert_equal(e[1], 6)
        # test against graph with one node
        G = networkx.path_graph(1)
        e = networkx.eccentricity(G)
        assert_equal(e[0], 0)
        e = networkx.eccentricity(G, v=0)
        assert_equal(e, 0)
        assert_raises(networkx.NetworkXError, networkx.eccentricity, G, 1)
        # test against empty graph
        G = networkx.empty_graph()
        e = networkx.eccentricity(G)
        assert_equal(e, {}) 
Example #9
Source File: classic.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def ladder_graph(n, create_using=None):
    """Returns the Ladder graph of length n.

    This is two paths of n nodes, with
    each pair connected by a single edge.

    Node labels are the integers 0 to 2*n - 1.

    """
    G = empty_graph(2 * n, create_using)
    if G.is_directed():
        raise NetworkXError("Directed Graph not supported")
    G.add_edges_from(pairwise(range(n)))
    G.add_edges_from(pairwise(range(n, 2 * n)))
    G.add_edges_from((v, v + n) for v in range(n))
    return G 
Example #10
Source File: classic.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def dorogovtsev_goltsev_mendes_graph(n, create_using=None):
    """Returns the hierarchically constructed Dorogovtsev-Goltsev-Mendes graph.

    n is the generation.
    See: arXiv:/cond-mat/0112143 by Dorogovtsev, Goltsev and Mendes.

    """
    G = empty_graph(0, create_using)
    if G.is_directed():
        raise NetworkXError("Directed Graph not supported")
    if G.is_multigraph():
        raise NetworkXError("Multigraph not supported")

    G.add_edge(0, 1)
    if n == 0:
        return G
    new_node = 2         # next node to be added
    for i in range(1, n + 1):  # iterate over number of generations.
        last_generation_edges = list(G.edges())
        number_of_edges_in_last_generation = len(last_generation_edges)
        for j in range(0, number_of_edges_in_last_generation):
            G.add_edge(new_node, last_generation_edges[j][0])
            G.add_edge(new_node, last_generation_edges[j][1])
            new_node += 1
    return G 
Example #11
Source File: classic.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def cycle_graph(n, create_using=None):
    """Returns the cycle graph $C_n$ of cyclically connected nodes.

    $C_n$ is a path with its two end-nodes connected.

    Parameters
    ----------
    n : int or iterable container of nodes
        If n is an integer, nodes are from `range(n)`.
        If n is a container of nodes, those nodes appear in the graph.
    create_using : NetworkX graph constructor, optional (default=nx.Graph)
       Graph type to create. If graph instance, then cleared before populated.

    Notes
    -----
    If create_using is directed, the direction is in increasing order.

    """
    n_orig, nodes = n
    G = empty_graph(nodes, create_using)
    G.add_edges_from(pairwise(nodes))
    G.add_edge(nodes[-1], nodes[0])
    return G 
Example #12
Source File: historical_tests.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_empty_subgraph(self):
        # Subgraph of an empty graph is an empty graph. test 1
        nullgraph = nx.null_graph()
        E5 = nx.empty_graph(5)
        E10 = nx.empty_graph(10)
        H = E10.subgraph([])
        assert_true(nx.is_isomorphic(H, nullgraph))
        H = E10.subgraph([1, 2, 3, 4, 5])
        assert_true(nx.is_isomorphic(H, E5)) 
Example #13
Source File: test_sparsifiers.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_spanner_invalid_stretch():
    """Check whether an invalid stretch is caught."""
    G = nx.empty_graph()
    nx.spanner(G, 0) 
Example #14
Source File: generators.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def complete_bipartite_graph(n1, n2, create_using=None):
    """Returns the complete bipartite graph `K_{n_1,n_2}`.

    Composed of two partitions with `n_1` nodes in the first
    and `n_2` nodes in the second. Each node in the first is
    connected to each node in the second.

    Parameters
    ----------
    n1 : integer
       Number of nodes for node set A.
    n2 : integer
       Number of nodes for node set B.
    create_using : NetworkX graph instance, optional
       Return graph of this type.

    Notes
    -----
    Node labels are the integers 0 to `n_1 + n_2 - 1`.

    The nodes are assigned the attribute 'bipartite' with the value 0 or 1
    to indicate which bipartite set the node belongs to.
    """
    G = nx.empty_graph(0, create_using)
    if G.is_directed():
        raise nx.NetworkXError("Directed Graph not supported")

    n1, top = n1
    n2, bottom = n2
    if isinstance(n2, numbers.Integral):
        bottom = [n1 + i for i in bottom]
    G.add_nodes_from(top, bipartite=0)
    G.add_nodes_from(bottom, bipartite=1)
    G.add_edges_from((u, v) for u in top for v in bottom)
    G.graph['name'] = "complete_bipartite_graph(%s,%s)" % (n1, n2)
    return G 
Example #15
Source File: test_second_order_centrality.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_empty(self):
        G = nx.empty_graph()
        nx.second_order_centrality(G) 
Example #16
Source File: test_coloring.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_equitable_color_empty(self):
        G = nx.empty_graph()
        coloring = nx.coloring.equitable_color(G, max_degree(G) + 1)
        assert is_equitable(G, coloring) 
Example #17
Source File: test_connectivity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_empty_graphs():
    for k in range(5, 25, 5):
        G = nx.empty_graph(k)
        for flow_func in flow_funcs:
            assert_equal(0, nx.node_connectivity(G, flow_func=flow_func),
                         msg=msg.format(flow_func.__name__))
            assert_equal(0, nx.edge_connectivity(G, flow_func=flow_func),
                         msg=msg.format(flow_func.__name__)) 
Example #18
Source File: test_degree_centrality.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_small_graph_centrality(self):
        G = nx.empty_graph(create_using=nx.DiGraph)
        assert_equal({}, nx.degree_centrality(G))
        assert_equal({}, nx.out_degree_centrality(G))
        assert_equal({}, nx.in_degree_centrality(G))

        G = nx.empty_graph(1, create_using=nx.DiGraph)
        assert_equal({0: 1}, nx.degree_centrality(G))
        assert_equal({0: 1}, nx.out_degree_centrality(G))
        assert_equal({0: 1}, nx.in_degree_centrality(G)) 
Example #19
Source File: test_product.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_cartesian_product_null():
    null = nx.null_graph()
    empty10 = nx.empty_graph(10)
    K3 = nx.complete_graph(3)
    K10 = nx.complete_graph(10)
    P3 = nx.path_graph(3)
    P10 = nx.path_graph(10)
    # null graph
    G = nx.cartesian_product(null, null)
    assert_true(nx.is_isomorphic(G, null))
    # null_graph X anything = null_graph and v.v.
    G = nx.cartesian_product(null, empty10)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.cartesian_product(null, K3)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.cartesian_product(null, K10)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.cartesian_product(null, P3)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.cartesian_product(null, P10)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.cartesian_product(empty10, null)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.cartesian_product(K3, null)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.cartesian_product(K10, null)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.cartesian_product(P3, null)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.cartesian_product(P10, null)
    assert_true(nx.is_isomorphic(G, null)) 
Example #20
Source File: test_product.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_strong_product_null():
    null = nx.null_graph()
    empty10 = nx.empty_graph(10)
    K3 = nx.complete_graph(3)
    K10 = nx.complete_graph(10)
    P3 = nx.path_graph(3)
    P10 = nx.path_graph(10)
    # null graph
    G = nx.strong_product(null, null)
    assert_true(nx.is_isomorphic(G, null))
    # null_graph X anything = null_graph and v.v.
    G = nx.strong_product(null, empty10)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.strong_product(null, K3)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.strong_product(null, K10)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.strong_product(null, P3)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.strong_product(null, P10)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.strong_product(empty10, null)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.strong_product(K3, null)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.strong_product(K10, null)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.strong_product(P3, null)
    assert_true(nx.is_isomorphic(G, null))
    G = nx.strong_product(P10, null)
    assert_true(nx.is_isomorphic(G, null)) 
Example #21
Source File: graphviews.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generic_graph_view(G, create_using=None):
    if create_using is None:
        newG = G.__class__()
    else:
        newG = nx.empty_graph(0, create_using)
    if G.is_multigraph() != newG.is_multigraph():
        raise NetworkXError("Multigraph for G must agree with create_using")
    newG = nx.freeze(newG)

    # create view by assigning attributes from G
    newG._graph = G
    newG.graph = G.graph

    newG._node = G._node
    if newG.is_directed():
        if G.is_directed():
            newG._succ = G._succ
            newG._pred = G._pred
            newG._adj = G._succ
        else:
            newG._succ = G._adj
            newG._pred = G._adj
            newG._adj = G._adj
    elif G.is_directed():
        if G.is_multigraph():
            newG._adj = UnionMultiAdjacency(G._succ, G._pred)
        else:
            newG._adj = UnionAdjacency(G._succ, G._pred)
    else:
        newG._adj = G._adj
    return newG 
Example #22
Source File: test_biconnected.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_empty_is_biconnected():
    G = nx.empty_graph(5)
    assert_false(nx.is_biconnected(G))
    G.add_edge(0, 1)
    assert_false(nx.is_biconnected(G)) 
Example #23
Source File: test_convert_numpy.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def identity_conversion(self, G, A, create_using):
        assert(A.sum() > 0)
        GG = nx.from_numpy_array(A, create_using=create_using)
        self.assert_equal(G, GG)
        GW = nx.to_networkx_graph(A, create_using=create_using)
        self.assert_equal(G, GW)
        GI = nx.empty_graph(0, create_using).__class__(A)
        self.assert_equal(G, GI) 
Example #24
Source File: test_convert_numpy.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def identity_conversion(self, G, A, create_using):
        assert(A.sum() > 0)
        GG = nx.from_numpy_matrix(A, create_using=create_using)
        self.assert_equal(G, GG)
        GW = nx.to_networkx_graph(A, create_using=create_using)
        self.assert_equal(G, GW)
        GI = nx.empty_graph(0, create_using).__class__(A)
        self.assert_equal(G, GI) 
Example #25
Source File: test_sparse6.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_very_large_empty_graph(self):
        G = nx.empty_graph(258049)
        result = BytesIO()
        nx.write_sparse6(G, result)
        self.assertEqual(result.getvalue(), b'>>sparse6<<:~~???~?@\n') 
Example #26
Source File: test_sparse6.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_large_empty_graph(self):
        G = nx.empty_graph(68)
        result = BytesIO()
        nx.write_sparse6(G, result)
        self.assertEqual(result.getvalue(), b'>>sparse6<<:~?@C\n') 
Example #27
Source File: test_sparse6.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_empty_graph(self):
        G = nx.empty_graph(5)
        result = BytesIO()
        nx.write_sparse6(G, result)
        self.assertEqual(result.getvalue(), b'>>sparse6<<:D\n') 
Example #28
Source File: classic.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def complete_graph(n, create_using=None):
    """ Return the complete graph `K_n` with n nodes.

    Parameters
    ----------
    n : int or iterable container of nodes
        If n is an integer, nodes are from range(n).
        If n is a container of nodes, those nodes appear in the graph.
    create_using : NetworkX graph constructor, optional (default=nx.Graph)
       Graph type to create. If graph instance, then cleared before populated.

    Examples
    --------
    >>> G = nx.complete_graph(9)
    >>> len(G)
    9
    >>> G.size()
    36
    >>> G = nx.complete_graph(range(11, 14))
    >>> list(G.nodes())
    [11, 12, 13]
    >>> G = nx.complete_graph(4, nx.DiGraph())
    >>> G.is_directed()
    True

    """
    n_name, nodes = n
    G = empty_graph(n_name, create_using)
    if len(nodes) > 1:
        if G.is_directed():
            edges = itertools.permutations(nodes, 2)
        else:
            edges = itertools.combinations(nodes, 2)
        G.add_edges_from(edges)
    return G 
Example #29
Source File: convert.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def from_dict_of_lists(d, create_using=None):
    """Returns a graph from a dictionary of lists.

    Parameters
    ----------
    d : dictionary of lists
      A dictionary of lists adjacency representation.

    create_using : NetworkX graph constructor, optional (default=nx.Graph)
        Graph type to create. If graph instance, then cleared before populated.

    Examples
    --------
    >>> dol = {0: [1]} # single edge (0,1)
    >>> G = nx.from_dict_of_lists(dol)

    or

    >>> G = nx.Graph(dol) # use Graph constructor

    """
    G = nx.empty_graph(0, create_using)
    G.add_nodes_from(d)
    if G.is_multigraph() and not G.is_directed():
        # a dict_of_lists can't show multiedges.  BUT for undirected graphs,
        # each edge shows up twice in the dict_of_lists.
        # So we need to treat this case separately.
        seen = {}
        for node, nbrlist in d.items():
            for nbr in nbrlist:
                if nbr not in seen:
                    G.add_edge(node, nbr)
            seen[node] = 1  # don't allow reverse edge to show up
    else:
        G.add_edges_from(((node, nbr) for node, nbrlist in d.items()
                          for nbr in nbrlist))
    return G 
Example #30
Source File: test_coloring.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def empty_graph():
    return nx.Graph()