Python networkx.number_of_nodes() Examples

The following are 30 code examples of networkx.number_of_nodes(). 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: test_expanders.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def test_margulis_gabber_galil_graph():
    try:
        # Scipy is required for conversion to an adjacency matrix.
        # We also use scipy for computing the eigenvalues,
        # but this second use could be done using only numpy.
        import numpy as np
        import scipy.linalg
        has_scipy = True
    except ImportError as e:
        has_scipy = False
    for n in 2, 3, 5, 6, 10:
        g = margulis_gabber_galil_graph(n)
        assert_equal(number_of_nodes(g), n*n)
        for node in g:
            assert_equal(g.degree(node), 8)
            assert_equal(len(node), 2)
            for i in node:
                assert_equal(int(i), i)
                assert_true(0 <= i < n)
        if has_scipy:
            # Eigenvalues are already sorted using the scipy eigvalsh,
            # but the implementation in numpy does not guarantee order.
            w = sorted(scipy.linalg.eigvalsh(adjacency_matrix(g).A))
            assert_less(w[-2], 5*np.sqrt(2)) 
Example #2
Source File: test_expanders.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_margulis_gabber_galil_graph():
    try:
        # Scipy is required for conversion to an adjacency matrix.
        # We also use scipy for computing the eigenvalues,
        # but this second use could be done using only numpy.
        import numpy as np
        import scipy.linalg
        has_scipy = True
    except ImportError as e:
        has_scipy = False
    for n in 2, 3, 5, 6, 10:
        g = margulis_gabber_galil_graph(n)
        assert_equal(number_of_nodes(g), n*n)
        for node in g:
            assert_equal(g.degree(node), 8)
            assert_equal(len(node), 2)
            for i in node:
                assert_equal(int(i), i)
                assert_true(0 <= i < n)
        if has_scipy:
            # Eigenvalues are already sorted using the scipy eigvalsh,
            # but the implementation in numpy does not guarantee order.
            w = sorted(scipy.linalg.eigvalsh(adjacency_matrix(g).A))
            assert_less(w[-2], 5*np.sqrt(2)) 
Example #3
Source File: historical_tests.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_iterators(self):
        G = self.G()
        G.add_edges_from([('A', 'B'), ('A', 'C'), ('B', 'D'),
                          ('C', 'B'), ('C', 'D')])
        G.add_nodes_from('GJK')
        assert_equal(sorted(G.nodes()),
                     ['A', 'B', 'C', 'D', 'G', 'J', 'K'])
        assert_edges_equal(G.edges(),
                           [('A', 'B'), ('A', 'C'), ('B', 'D'), ('C', 'B'), ('C', 'D')])

        assert_equal(sorted([v for k, v in G.degree()]),
                     [0, 0, 0, 2, 2, 3, 3])
        assert_equal(sorted(G.degree(), key=str),
                     [('A', 2), ('B', 3), ('C', 3), ('D', 2),
                      ('G', 0), ('J', 0), ('K', 0)])
        assert_equal(sorted(G.neighbors('A')), ['B', 'C'])
        assert_raises(nx.NetworkXError, G.neighbors, 'X')
        G.clear()
        assert_equal(nx.number_of_nodes(G), 0)
        assert_equal(nx.number_of_edges(G), 0) 
Example #4
Source File: historical_tests.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_iterators(self):
        G=self.G()
        G.add_edges_from([('A', 'B'), ('A', 'C'), ('B', 'D'), 
                          ('C', 'B'), ('C', 'D')])
        G.add_nodes_from('GJK')
        assert_equal(sorted(G.nodes_iter()),
                     ['A', 'B', 'C', 'D', 'G', 'J', 'K'])
        assert_edges_equal(G.edges_iter(),
        [('A', 'B'), ('A', 'C'), ('B', 'D'), ('C', 'B'), ('C', 'D')])

        assert_equal(sorted([v for k,v in G.degree_iter()]),
                     [0, 0, 0, 2, 2, 3, 3])
        assert_equal(sorted(G.degree_iter(),key=str),
                     [('A', 2), ('B', 3), ('C', 3), ('D', 2), 
                      ('G', 0), ('J', 0), ('K', 0)])
        assert_equal(sorted(G.neighbors_iter('A')),['B', 'C'])
        assert_raises(nx.NetworkXError,G.neighbors_iter,'X')
        G.clear()
        assert_equal(nx.number_of_nodes(G),0)
        assert_equal(nx.number_of_edges(G),0) 
Example #5
Source File: test_expanders.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_margulis_gabber_galil_graph():
    try:
        # Scipy is required for conversion to an adjacency matrix.
        # We also use scipy for computing the eigenvalues,
        # but this second use could be done using only numpy.
        import numpy as np
        import scipy.linalg
        has_scipy = True
    except ImportError as e:
        has_scipy = False
    for n in 2, 3, 5, 6, 10:
        g = margulis_gabber_galil_graph(n)
        assert_equal(number_of_nodes(g), n * n)
        for node in g:
            assert_equal(g.degree(node), 8)
            assert_equal(len(node), 2)
            for i in node:
                assert_equal(int(i), i)
                assert_true(0 <= i < n)
        if has_scipy:
            # Eigenvalues are already sorted using the scipy eigvalsh,
            # but the implementation in numpy does not guarantee order.
            w = sorted(scipy.linalg.eigvalsh(adjacency_matrix(g).A))
            assert_less(w[-2], 5 * np.sqrt(2)) 
Example #6
Source File: historical_tests.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def test_iterators(self):
        G = self.G()
        G.add_edges_from([('A', 'B'), ('A', 'C'), ('B', 'D'),
                          ('C', 'B'), ('C', 'D')])
        G.add_nodes_from('GJK')
        assert_equal(sorted(G.nodes()),
                     ['A', 'B', 'C', 'D', 'G', 'J', 'K'])
        assert_edges_equal(G.edges(),
                           [('A', 'B'), ('A', 'C'), ('B', 'D'), ('C', 'B'), ('C', 'D')])

        assert_equal(sorted([v for k, v in G.degree()]),
                     [0, 0, 0, 2, 2, 3, 3])
        assert_equal(sorted(G.degree(), key=str),
                     [('A', 2), ('B', 3), ('C', 3), ('D', 2),
                      ('G', 0), ('J', 0), ('K', 0)])
        assert_equal(sorted(G.neighbors('A')), ['B', 'C'])
        assert_raises(nx.NetworkXError, G.neighbors, 'X')
        G.clear()
        assert_equal(nx.number_of_nodes(G), 0)
        assert_equal(nx.number_of_edges(G), 0) 
Example #7
Source File: topology.py    From vitrage with Apache License 2.0 6 votes vote down vote up
def as_tree(graph, root=OPENSTACK_CLUSTER, reverse=False):
        if nx.__version__ >= '2.0':
            linked_graph = json_graph.node_link_graph(
                graph, attrs={'name': 'graph_index'})
        else:
            linked_graph = json_graph.node_link_graph(graph)
        if 0 == nx.number_of_nodes(linked_graph):
            return {}
        if reverse:
            linked_graph = linked_graph.reverse()
        if nx.__version__ >= '2.0':
            return json_graph.tree_data(
                linked_graph,
                root=root,
                attrs={'id': 'graph_index', 'children': 'children'})
        else:
            return json_graph.tree_data(linked_graph, root=root) 
Example #8
Source File: synthetic_structsim.py    From gnn-model-explainer with Apache License 2.0 6 votes vote down vote up
def tree(start, height, r=2, role_start=0):
    """Builds a balanced r-tree of height h
    INPUT:
    -------------
    start       :    starting index for the shape
    height      :    int height of the tree 
    r           :    int number of branches per node 
    role_start  :    starting index for the roles
    OUTPUT:
    -------------
    graph       :    a tree shape graph, with ids beginning at start
    roles       :    list of the roles of the nodes (indexed starting at role_start)
    """
    graph = nx.balanced_tree(r, height)
    roles = [0] * graph.number_of_nodes()
    return graph, roles 
Example #9
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_combinations():
    P5 = nx.path_graph(5)
    K3 = nx.complete_graph(3)
    G = nx.strong_product(P5, K3)
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = nx.strong_product(nx.MultiGraph(P5), K3)
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = nx.strong_product(P5, nx.MultiGraph(K3))
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = nx.strong_product(nx.MultiGraph(P5), nx.MultiGraph(K3))
    assert_equal(nx.number_of_nodes(G), 5 * 3)

    # No classic easily found classic results for strong product 
Example #10
Source File: test_product.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_strong_product_combinations():
    P5 = nx.path_graph(5)
    K3 = nx.complete_graph(3)
    G = strong_product(P5, K3)
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = strong_product(nx.MultiGraph(P5), K3)
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = strong_product(P5, nx.MultiGraph(K3))
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = strong_product(nx.MultiGraph(P5), nx.MultiGraph(K3))
    assert_equal(nx.number_of_nodes(G), 5 * 3)

    # No classic easily found classic results for strong product 
Example #11
Source File: test_atlas.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_nondecreasing_edges(self):
        # check for nondecreasing number of edges (for fixed number of
        # nodes)
        for n, group in groupby(self.GAG, key=nx.number_of_nodes):
            for m1, m2 in pairwise(map(nx.number_of_edges, group)):
                assert_less_equal(m2, m1 + 1) 
Example #12
Source File: test_function.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_number_of_nodes(self):
        assert_equal(self.G.number_of_nodes(), nx.number_of_nodes(self.G))
        assert_equal(self.DG.number_of_nodes(), nx.number_of_nodes(self.DG)) 
Example #13
Source File: test_product.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_tensor_product_size():
    P5 = nx.path_graph(5)
    K3 = nx.complete_graph(3)
    K5 = nx.complete_graph(5)

    G = nx.tensor_product(P5, K3)
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = nx.tensor_product(K3, K5)
    assert_equal(nx.number_of_nodes(G), 3 * 5) 
Example #14
Source File: test_product.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_tensor_product_combinations():
    # basic smoke test, more realistic tests would be useful
    P5 = nx.path_graph(5)
    K3 = nx.complete_graph(3)
    G = nx.tensor_product(P5, K3)
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = nx.tensor_product(P5, nx.MultiGraph(K3))
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = nx.tensor_product(nx.MultiGraph(P5), K3)
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = nx.tensor_product(nx.MultiGraph(P5), nx.MultiGraph(K3))
    assert_equal(nx.number_of_nodes(G), 5 * 3)

    G = nx.tensor_product(nx.DiGraph(P5), nx.DiGraph(K3))
    assert_equal(nx.number_of_nodes(G), 5 * 3) 
Example #15
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_size():
    # order(GXH)=order(G)*order(H)
    K5 = nx.complete_graph(5)
    P5 = nx.path_graph(5)
    K3 = nx.complete_graph(3)
    G = nx.cartesian_product(P5, K3)
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    assert_equal(nx.number_of_edges(G),
                 nx.number_of_edges(P5) * nx.number_of_nodes(K3) +
                 nx.number_of_edges(K3) * nx.number_of_nodes(P5))
    G = nx.cartesian_product(K3, K5)
    assert_equal(nx.number_of_nodes(G), 3 * 5)
    assert_equal(nx.number_of_edges(G),
                 nx.number_of_edges(K5) * nx.number_of_nodes(K3) +
                 nx.number_of_edges(K3) * nx.number_of_nodes(K5)) 
Example #16
Source File: test_product.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_lexicographic_product_combinations():
    P5 = nx.path_graph(5)
    K3 = nx.complete_graph(3)
    G = nx.lexicographic_product(P5, K3)
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = nx.lexicographic_product(nx.MultiGraph(P5), K3)
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = nx.lexicographic_product(P5, nx.MultiGraph(K3))
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = nx.lexicographic_product(nx.MultiGraph(P5), nx.MultiGraph(K3))
    assert_equal(nx.number_of_nodes(G), 5 * 3)

    # No classic easily found classic results for lexicographic product 
Example #17
Source File: test_atlas.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_sizes(self):
        G = self.GAG[0]
        assert_equal(G.number_of_nodes(), 0)
        assert_equal(G.number_of_edges(), 0)

        G = self.GAG[7]
        assert_equal(G.number_of_nodes(), 3)
        assert_equal(G.number_of_edges(), 3) 
Example #18
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_size():
    K5 = nx.complete_graph(5)
    P5 = nx.path_graph(5)
    K3 = nx.complete_graph(3)
    G = nx.strong_product(P5, K3)
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = nx.strong_product(K3, K5)
    assert_equal(nx.number_of_nodes(G), 3 * 5) 
Example #19
Source File: test_product.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_cartesian_product_size():
    # order(GXH)=order(G)*order(H)
    K5 = nx.complete_graph(5)
    P5 = nx.path_graph(5)
    K3 = nx.complete_graph(3)
    G = cartesian_product(P5, K3)
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    assert_equal(nx.number_of_edges(G),
                 nx.number_of_edges(P5) * nx.number_of_nodes(K3) +
                 nx.number_of_edges(K3) * nx.number_of_nodes(P5))
    G = cartesian_product(K3, K5)
    assert_equal(nx.number_of_nodes(G), 3 * 5)
    assert_equal(nx.number_of_edges(G),
                 nx.number_of_edges(K5) * nx.number_of_nodes(K3) +
                 nx.number_of_edges(K3) * nx.number_of_nodes(K5)) 
Example #20
Source File: test_atlas.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_sizes(self):
        G = self.GAG[0]
        assert_equal(G.number_of_nodes(), 0)
        assert_equal(G.number_of_edges(), 0)

        G = self.GAG[7]
        assert_equal(G.number_of_nodes(), 3)
        assert_equal(G.number_of_edges(), 3) 
Example #21
Source File: test_atlas.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_nondecreasing_edges(self):
        # check for nondecreasing number of edges (for fixed number of
        # nodes)
        for n, group in groupby(self.GAG, key=nx.number_of_nodes):
            for m1, m2 in pairwise(map(nx.number_of_edges, group)):
                assert_less_equal(m2, m1 + 1) 
Example #22
Source File: test_product.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_strong_product_combinations():
    P5 = nx.path_graph(5)
    K3 = nx.complete_graph(3)
    G = strong_product(P5, K3)
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = strong_product(nx.MultiGraph(P5), K3)
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = strong_product(P5, nx.MultiGraph(K3))
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = strong_product(nx.MultiGraph(P5), nx.MultiGraph(K3))
    assert_equal(nx.number_of_nodes(G), 5 * 3)

    # No classic easily found classic results for strong product 
Example #23
Source File: dag.py    From sos with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def num_nodes(self):
        return nx.number_of_nodes(self) 
Example #24
Source File: test_product.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_strong_product_size():
    K5 = nx.complete_graph(5)
    P5 = nx.path_graph(5)
    K3 = nx.complete_graph(3)
    G = strong_product(P5, K3)
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = strong_product(K3, K5)
    assert_equal(nx.number_of_nodes(G), 3 * 5) 
Example #25
Source File: test_function.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_number_of_nodes(self):
        assert_equal(self.G.number_of_nodes(), nx.number_of_nodes(self.G))
        assert_equal(self.DG.number_of_nodes(), nx.number_of_nodes(self.DG)) 
Example #26
Source File: test_product.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_lexicographic_product_combinations():
    P5 = nx.path_graph(5)
    K3 = nx.complete_graph(3)
    G = lexicographic_product(P5, K3)
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = lexicographic_product(nx.MultiGraph(P5), K3)
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = lexicographic_product(P5, nx.MultiGraph(K3))
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = lexicographic_product(nx.MultiGraph(P5), nx.MultiGraph(K3))
    assert_equal(nx.number_of_nodes(G), 5 * 3)

    # No classic easily found classic results for lexicographic product 
Example #27
Source File: test_product.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_tensor_product_size():
    P5 = nx.path_graph(5)
    K3 = nx.complete_graph(3)
    K5 = nx.complete_graph(5)

    G = tensor_product(P5, K3)
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = tensor_product(K3, K5)
    assert_equal(nx.number_of_nodes(G), 3 * 5) 
Example #28
Source File: test_product.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_tensor_product_combinations():
    # basic smoke test, more realistic tests would be usefule
    P5 = nx.path_graph(5)
    K3 = nx.complete_graph(3)
    G = tensor_product(P5, K3)
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = tensor_product(P5, nx.MultiGraph(K3))
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = tensor_product(nx.MultiGraph(P5), K3)
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = tensor_product(nx.MultiGraph(P5), nx.MultiGraph(K3))
    assert_equal(nx.number_of_nodes(G), 5 * 3)

    G = tensor_product(nx.DiGraph(P5), nx.DiGraph(K3))
    assert_equal(nx.number_of_nodes(G), 5 * 3) 
Example #29
Source File: structure_data.py    From lammps_interface with MIT License 5 votes vote down vote up
def compute_cartesian_coordinates(self, cell):
        """Compute the cartesian coordinates for each atom node"""
        coord_keys = ['_atom_site_x', '_atom_site_y', '_atom_site_z']
        fcoord_keys = ['_atom_site_fract_x', '_atom_site_fract_y', '_atom_site_fract_z']
        self.coordinates = np.empty((self.number_of_nodes(), 3))
        for node, data in self.nodes_iter2(data=True):
            #TODO(pboyd) probably need more error checking..
            try:
                coordinates = np.array([float(del_parenth(data[i])) for i in coord_keys])
            except KeyError:
                coordinates = np.array([float(del_parenth(data[i])) for i in fcoord_keys])
                coordinates = np.dot(coordinates, cell.cell)
            data.update({'cartesian_coordinates':coordinates})

            self.coordinates[data['index']-1] = coordinates 
Example #30
Source File: graph_gens.py    From GEM-Benchmark with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def powerlaw_cluster_graph(N, deg, dia, dim, domain):
    '''
    Parameters of the graph:
    n (int) – the number of nodes
    m (int) – the number of random edges to add for each new node
    p (float,) – Probability of adding a triangle after adding a random edge
    Formula for m:  (m^2)- (Nm)/2 + avg_deg * (N/2) = 0  =>  From this equation we need to find m :
    p : Does not vary the average degree or diameter so much. : Higher value of p may cause average degree to overshoot intended average_deg
    so we give the control of average degree to parameter m: by setting a lower value of p: 0.1
    :return: Graph Object
    '''

    ## Calculating thof nodes: 10\nNumber of edges: 16\nAverage degree:   3.2000'
    strt_time = time()

    m = int(round((N - np.sqrt(N ** 2 - 4 * deg * N)) / 4))
    p = 0.2

    ## G at center:
    G = nx.powerlaw_cluster_graph(n=N, m=m, p=p)

    lcc, _ = graph_util.get_nk_lcc_undirected(G)

    best_G = lcc

    best_diam = nx.algorithms.diameter(best_G)

    best_avg_deg = np.mean(list(dict(nx.degree(best_G)).values()))


    end_time = time()
    print('Graph_Name: powerlaw_cluster_graph')
    print('Num_Nodes: ', nx.number_of_nodes(best_G), ' Avg_Deg : ', best_avg_deg, ' Diameter: ', best_diam)
    print('TIME: ', end_time - strt_time)
    return best_G, best_avg_deg, best_diam

#####################################################################