Пример #1
0
 def test_complete_graph(self):
     G = nx.complete_graph(4)
     p = nx.builtin.voterank(G)
     assert p == [0, 1, 2]
     G = nx.complete_graph(5)
     p = nx.builtin.voterank(G)
     assert p == [0, 1, 2, 3]
Пример #2
0
 def test_zero_personalization_vector(self):
     G = nx.complete_graph(4)
     personalize = {0: 0, 1: 0, 2: 0, 3: 0}
     pytest.raises(ZeroDivisionError,
                   nx.builtin.pagerank,
                   G,
                   personalization=personalize)
Пример #3
0
    def test_hamiltonian_path(self):
        from itertools import permutations

        G = nx.complete_graph(4)
        paths = [list(p) for p in hamiltonian_path(G, 0)]
        exact = [[0] + list(p) for p in permutations([1, 2, 3], 3)]
        assert sorted(paths) == sorted(exact)
 def test_normalized_K5(self):
     """Edge betweenness centrality: K5"""
     G = nx.complete_graph(5)
     b = nx.edge_betweenness_centrality(G, weight=None, normalized=True)
     b_answer = dict.fromkeys(G.edges(), 1 / 10)
     for n in sorted(G.edges()):
         assert almost_equal(b[n], b_answer[n])
 def test_K5(self):
     """Betweenness centrality: K5"""
     G = nx.complete_graph(5)
     b = nx.builtin.betweenness_centrality(G, weight=None, normalized=False)
     b_answer = {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}
     for n in sorted(G):
         assert almost_equal(b[n], b_answer[n])
Пример #6
0
def test_selfloops(graph_type):
    G = nx.complete_graph(3, create_using=graph_type)
    G.add_edge(0, 0)
    assert nodes_equal(nx.nodes_with_selfloops(G), [0])
    assert edges_equal(nx.selfloop_edges(G), [(0, 0)])
    assert edges_equal(nx.selfloop_edges(G, data=True), [(0, 0, {})])
    assert nx.number_of_selfloops(G) == 1
Пример #7
0
def watts_strogatz_graph(n, k, p, seed=None):
    if k > n:
        raise nx.NetworkXError("k>n, choose smaller k or larger n")

    # If k == n, the graph is complete not Watts-Strogatz
    if k == n:
        return nx.complete_graph(n)

    G = nx.Graph()
    nodes = list(range(n))  # nodes are labeled 0 to n-1
    # connect each node to k/2 neighbors
    for j in range(1, k // 2 + 1):
        targets = nodes[j:] + nodes[0:j]  # first j nodes are now last in list
        G.add_edges_from(zip(nodes, targets))
    # rewire edges from each node
    # loop over all nodes in order (label) and neighbors in order (distance)
    # no self loops or multiple edges allowed
    for j in range(1, k // 2 + 1):  # outer loop is neighbors
        targets = nodes[j:] + nodes[0:j]  # first j nodes are now last in list
        # inner loop in node order
        for u, v in zip(nodes, targets):
            if seed.random() < p:
                w = seed.choice(nodes)
                # Enforce no self-loops or multiple edges
                while w == u or G.has_edge(u, w):
                    w = seed.choice(nodes)
                    if G.degree(u) >= n - 1:
                        break  # skip this rewiring
                else:
                    G.remove_edge(u, v)
                    G.add_edge(u, w)
    return G
Пример #8
0
def newman_watts_strogatz_graph(n, k, p, seed=None):
    if k > n:
        raise nx.NetworkXError("k>=n, choose smaller k or larger n")

    # If k == n the graph return is a complete graph
    if k == n:
        return nx.complete_graph(n)

    G = empty_graph(n)
    nlist = list(G.nodes())
    fromv = nlist
    # connect the k/2 neighbors
    for j in range(1, k // 2 + 1):
        tov = fromv[j:] + fromv[0:j]  # the first j are now last
        for i, value in enumerate(fromv):
            G.add_edge(value, tov[i])
    # for each edge u-v, with probability p, randomly select existing
    # node w and add new edge u-w
    e = list(G.edges())
    for (u, v) in e:
        if seed.random() < p:
            w = seed.choice(nlist)
            # no self-loops and reject if edge u-w exists
            # is that the correct NWS model?
            while w == u or G.has_edge(u, w):
                w = seed.choice(nlist)
                if G.degree(u) >= n - 1:
                    break  # skip this rewiring
            else:
                G.add_edge(u, w)
    return G
Пример #9
0
def test_selfloops_removal(graph_type):
    G = nx.complete_graph(3, create_using=graph_type)
    G.add_edge(0, 0)
    G.remove_edges_from(nx.selfloop_edges(G, keys=True))
    G.add_edge(0, 0)
    G.remove_edges_from(nx.selfloop_edges(G, data=True))
    G.add_edge(0, 0)
    G.remove_edges_from(nx.selfloop_edges(G, keys=True, data=True))
Пример #10
0
    def test_is_at_free(self):
        is_at_free = nx.asteroidal.is_at_free

        cycle = nx.cycle_graph(6)
        assert not is_at_free(cycle)

        path = nx.path_graph(6)
        assert is_at_free(path)

        small_graph = nx.complete_graph(2)
        assert is_at_free(small_graph)

        petersen = nx.petersen_graph()
        assert not is_at_free(petersen)

        clique = nx.complete_graph(6)
        assert is_at_free(clique)
Пример #11
0
 def test_K5(self):
     """Katz centrality: K5"""
     G = nx.complete_graph(5)
     alpha = 0.1
     b = nx.builtin.katz_centrality(G, alpha)
     v = math.sqrt(1 / 5.0)
     b_answer = dict.fromkeys(G, v)
     for n in sorted(G):
         assert almost_equal(b[n], b_answer[n])
Пример #12
0
    def test_hamiltonian__edge_path(self):
        from itertools import permutations

        G = nx.complete_graph(4)
        paths = hamiltonian_edge_path(G, 0)
        exact = [
            list(pairwise([0] + list(p))) for p in permutations([1, 2, 3], 3)
        ]
        assert sorted(exact) == [p for p in sorted(paths)]
Пример #13
0
 def test_complete_graph(self):
     K10 = nx.complete_graph(10)
     assert sorted(nx.builtin.node_boundary(K10, [0, 1, 2])) == [3, 4, 5, 6, 7, 8, 9]
     assert sorted(nx.builtin.node_boundary(K10, [3, 4, 5])) == [0, 1, 2, 6, 7, 8, 9]
     assert sorted(nx.builtin.node_boundary(K10, [2, 3, 4, 5, 6])) == [0, 1, 7, 8, 9]
     if os.environ.get("DEPLOYMENT", None) == "standalone":
         assert nx.builtin.node_boundary(K10, [0, 1, 2], [2, 3, 4]) == {3, 4}
     else:  # num_workers=2
         assert nx.builtin.node_boundary(K10, [0, 1, 2], [2, 3, 4]) == {4, 3}
Пример #14
0
def test_selfloop_edges_attr(graph_type):
    G = nx.complete_graph(3, create_using=graph_type)
    G.add_edge(0, 0)
    G.add_edge(1, 1, weight=2)
    assert edges_equal(nx.selfloop_edges(G, data=True), [(0, 0, {}),
                                                         (1, 1, {
                                                             "weight": 2
                                                         })])
    assert edges_equal(nx.selfloop_edges(G, data="weight"), [(0, 0, None),
                                                             (1, 1, 2)])
Пример #15
0
 def test_all_simple_edge_paths_cutoff(self):
     G = nx.complete_graph(4)
     paths = nx.builtin.all_simple_edge_paths(G, 0, 1, cutoff=1)
     assert {tuple(p) for p in paths} == {((0, 1), )}
     paths = nx.builtin.all_simple_edge_paths(G, 0, 1, cutoff=2)
     assert {tuple(p)
             for p in paths} == {
                 ((0, 1), ),
                 ((0, 2), (2, 1)),
                 ((0, 3), (3, 1)),
             }
Пример #16
0
 def test_personalization(self):
     G = nx.complete_graph(4)
     personalize = {0: 1, 1: 1, 2: 4, 3: 4}
     answer = {
         0: 0.23246732615667579,
         1: 0.23246732615667579,
         2: 0.267532673843324,
         3: 0.2675326738433241,
     }
     p = nx.builtin.pagerank(G, alpha=0.85, personalization=personalize)
     for n in G:
         assert almost_equal(p[n], answer[n], places=4)
 def test_K5(self):
     """Weighted betweenness centrality: K5"""
     G = nx.complete_graph(5)
     for e in G.edges:
         G.edges[e]["weight"] = 1
     G[1][2]["weight"] = 10
     b = nx.builtin.betweenness_centrality(G,
                                           weight="weight",
                                           normalized=False)
     b_answer = {0: 0.333, 1: 0.0, 2: 0.0, 3: 0.333, 4: 0.333}
     for n in sorted(G):
         assert almost_equal(b[n], b_answer[n], 3)
Пример #18
0
 def test_incomplete_personalization(self):
     G = nx.complete_graph(4)
     personalize = {3: 1}
     answer = {
         0: 0.22077931820379187,
         1: 0.22077931820379187,
         2: 0.22077931820379187,
         3: 0.3376620453886241,
     }
     p = nx.builtin.pagerank(G, alpha=0.85, personalization=personalize)
     for n in G:
         assert almost_equal(p[n], answer[n], places=4)
Пример #19
0
    def test_K5(self):
        """Eigenvector centrality: K5"""
        G = nx.complete_graph(5)
        b = nx.builtin.eigenvector_centrality(G)
        v = math.sqrt(1 / 5.0)
        b_answer = dict.fromkeys(G, v)
        for n in sorted(G):
            assert almost_equal(b[n], b_answer[n])
        nstart = dict([(n, 1) for n in G])

        b = nx.eigenvector_centrality_numpy(G)
        for n in sorted(G):
            assert almost_equal(b[n], b_answer[n], places=3)
Пример #20
0
 def test_k5(self):
     G = nx.complete_graph(5)
     assert list(nx.builtin.clustering(G).values()) == [1, 1, 1, 1, 1]
     assert nx.builtin.average_clustering(G) == 1
     G.remove_edge(1, 2)
     assert list(dict(sorted(nx.builtin.clustering(G).items())).values()) == [
         5.0 / 6.0,
         1.0,
         1.0,
         5.0 / 6.0,
         5.0 / 6.0,
     ]
     assert nx.builtin.clustering(G, [1, 4]) == {1: 1.0, 4: 0.83333333333333337}
Пример #21
0
 def test_K5_unweighted(self):
     """Katz centrality: K5"""
     G = nx.complete_graph(5)
     alpha = 0.1
     b = nx.katz_centrality(G, alpha, weight=None)
     v = math.sqrt(1 / 5.0)
     b_answer = dict.fromkeys(G, v)
     for n in sorted(G):
         assert almost_equal(b[n], b_answer[n])
     nstart = dict([(n, 1) for n in G])
     b = nx.eigenvector_centrality_numpy(G, weight=None)
     for n in sorted(G):
         assert almost_equal(b[n], b_answer[n], places=3)
Пример #22
0
 def test_k5(self):
     G = nx.complete_graph(5)
     assert list(nx.builtin.triangles(G).values()) == [6, 6, 6, 6, 6]
     assert sum(nx.builtin.triangles(G).values()) / 3.0 == 10
     assert nx.builtin.triangles(G, 1) == 6
     G.remove_edge(1, 2)
     assert list(dict(sorted(nx.builtin.triangles(G).items())).values()) == [
         5,
         3,
         3,
         5,
         5,
     ]
     assert nx.builtin.triangles(G, 1) == 3
 def test_K5_endpoints(self):
     """Betweenness centrality: K5 endpoints"""
     G = nx.complete_graph(5)
     b = nx.builtin.betweenness_centrality(G,
                                           weight=None,
                                           normalized=False,
                                           endpoints=True)
     b_answer = {0: 4.0, 1: 4.0, 2: 4.0, 3: 4.0, 4: 4.0}
     for n in sorted(G):
         assert almost_equal(b[n], b_answer[n])
     # normalized = True case
     b = nx.builtin.betweenness_centrality(G,
                                           weight=None,
                                           normalized=True,
                                           endpoints=True)
     b_answer = {0: 0.4, 1: 0.4, 2: 0.4, 3: 0.4, 4: 0.4}
     for n in sorted(G):
         assert almost_equal(b[n], b_answer[n])
Пример #24
0
    def test_complete_graph(self):
        K10 = nx.complete_graph(10)

        def ilen(iterable):
            return sum(1 for i in iterable)

        assert ilen(nx.builtin.edge_boundary(K10, [0, 1, 2])) == 21
        assert ilen(nx.builtin.edge_boundary(K10, [3, 4, 5, 6])) == 24
        assert ilen(nx.builtin.edge_boundary(K10, [2, 3, 4, 5, 6])) == 25
        assert ilen(nx.builtin.edge_boundary(K10, [7, 8, 9])) == 21
        assert_edges_equal(
            nx.builtin.edge_boundary(K10, [3, 4, 5], [8, 9]),
            [(3, 8), (3, 9), (4, 8), (4, 9), (5, 8), (5, 9)],
        )
        assert_edges_equal(
            nx.builtin.edge_boundary(K10, [0, 1, 2], [2, 3, 4]),
            [(0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4)],
        )
Пример #25
0
    def setup_class(cls):
        cls.K = nx.krackhardt_kite_graph()
        cls.P3 = nx.path_graph(3)
        cls.P4 = nx.path_graph(4)
        cls.K5 = nx.complete_graph(5)

        cls.C4 = nx.cycle_graph(4)
        cls.T = nx.balanced_tree(r=2, h=2)
        cls.Gb = nx.Graph()
        cls.Gb.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (4, 5),
                               (3, 5)])

        F = nx.florentine_families_graph()
        cls.F = F

        cls.LM = nx.les_miserables_graph()

        # Create random undirected, unweighted graph for testing incremental version
        cls.undirected_G = nx.fast_gnp_random_graph(n=100, p=0.6, seed=123)
        cls.undirected_G_cc = nx.builtin.closeness_centrality(cls.undirected_G)
Пример #26
0
def test_selfloops():
    graphs = [nx.Graph(), nx.DiGraph()]
    for graph in graphs:
        G = nx.complete_graph(3, create_using=graph)
        G.add_edge(0, 0)
        assert_nodes_equal(nx.nodes_with_selfloops(G), [0])
        assert_edges_equal(nx.selfloop_edges(G), [(0, 0)])
        assert_edges_equal(nx.selfloop_edges(G, data=True), [(0, 0, {})])
        assert nx.number_of_selfloops(G) == 1
        # test selfloop attr
        G.add_edge(1, 1, weight=2)
        assert_edges_equal(nx.selfloop_edges(G, data=True), [(0, 0, {}),
                                                             (1, 1, {
                                                                 "weight": 2
                                                             })])
        assert_edges_equal(nx.selfloop_edges(G, data="weight"), [(0, 0, None),
                                                                 (1, 1, 2)])
        # test removing selfloops behavior vis-a-vis altering a dict while iterating
        G.add_edge(0, 0)
        G.remove_edges_from(nx.selfloop_edges(G))
        if G.is_multigraph():
            G.add_edge(0, 0)
            pytest.raises(RuntimeError, G.remove_edges_from,
                          nx.selfloop_edges(G, keys=True))
            G.add_edge(0, 0)
            pytest.raises(TypeError, G.remove_edges_from,
                          nx.selfloop_edges(G, data=True))
            G.add_edge(0, 0)
            pytest.raises(
                RuntimeError,
                G.remove_edges_from,
                nx.selfloop_edges(G, data=True, keys=True),
            )
        else:
            G.add_edge(0, 0)
            G.remove_edges_from(nx.selfloop_edges(G, keys=True))
            G.add_edge(0, 0)
            G.remove_edges_from(nx.selfloop_edges(G, data=True))
            G.add_edge(0, 0)
            G.remove_edges_from(nx.selfloop_edges(G, keys=True, data=True))
Пример #27
0
 def test_k5(self):
     G = nx.complete_graph(5, create_using=nx.DiGraph())
     assert list(nx.builtin.clustering(G, weight="weight").values()) == [
         1,
         1,
         1,
         1,
         1,
     ]
     assert nx.builtin.average_clustering(G, weight="weight") == 1
     G.remove_edge(1, 2)
     assert G.number_of_nodes() == 5
     assert list(
         dict(sorted(nx.builtin.clustering(G, weight="weight").items())).values()
     ) == [
         11.0 / 12.0,
         1.0,
         1.0,
         11.0 / 12.0,
         11.0 / 12.0,
     ]
     assert nx.builtin.clustering(G, [1, 4], weight="weight") == {
         1: 1.0,
         4: 11.0 / 12.0,
     }
     G.remove_edge(2, 1)
     assert list(
         dict(sorted(nx.builtin.clustering(G, weight="weight").items())).values()
     ) == [
         5.0 / 6.0,
         1.0,
         1.0,
         5.0 / 6.0,
         5.0 / 6.0,
     ]
     assert nx.builtin.clustering(G, [1, 4], weight="weight") == {
         1: 1.0,
         4: 0.83333333333333337,
     }
Пример #28
0
    def setup_method(self):
        # self.K = nx.krackhardt_kite_graph()
        self.P3 = nx.path_graph(3)
        self.K5 = nx.complete_graph(5)

        # F = nx.Graph()  # Florentine families
        # F.add_edge('Acciaiuoli', 'Medici')
        # F.add_edge('Castellani', 'Peruzzi')
        # F.add_edge('Castellani', 'Strozzi')
        # F.add_edge('Castellani', 'Barbadori')
        # F.add_edge('Medici', 'Barbadori')
        # F.add_edge('Medici', 'Ridolfi')
        # F.add_edge('Medici', 'Tornabuoni')
        # F.add_edge('Medici', 'Albizzi')
        # F.add_edge('Medici', 'Salviati')
        # F.add_edge('Salviati', 'Pazzi')
        # F.add_edge('Peruzzi', 'Strozzi')
        # F.add_edge('Peruzzi', 'Bischeri')
        # F.add_edge('Strozzi', 'Ridolfi')
        # F.add_edge('Strozzi', 'Bischeri')
        # F.add_edge('Ridolfi', 'Tornabuoni')
        # F.add_edge('Tornabuoni', 'Guadagni')
        # F.add_edge('Albizzi', 'Ginori')
        # F.add_edge('Albizzi', 'Guadagni')
        # F.add_edge('Bischeri', 'Guadagni')
        # F.add_edge('Guadagni', 'Lamberteschi')
        # self.F = F

        G = nx.DiGraph()
        G.add_edge(0, 5)
        G.add_edge(1, 5)
        G.add_edge(2, 5)
        G.add_edge(3, 5)
        G.add_edge(4, 5)
        G.add_edge(5, 6)
        G.add_edge(5, 7)
        G.add_edge(5, 8)
        self.G = G
Пример #29
0
 def test_k5(self):
     G = nx.complete_graph(5)
     assert nx.generalized_degree(G, 0) == {3: 4}
     G.remove_edge(0, 1)
     assert nx.generalized_degree(G, 0) == {2: 3}
Пример #30
0
 def test_k5(self):
     G = nx.complete_graph(5)
     assert list(nx.square_clustering(G).values()) == [1, 1, 1, 1, 1]