示例#1
0
    def setup_method(cls):
        G = nx.Graph()
        G.add_nodes_from([0, 1], fish='one')
        G.add_nodes_from([2, 3], fish='two')
        G.add_nodes_from([4], fish='red')
        G.add_nodes_from([5], fish='blue')
        G.add_edges_from([(0, 1), (2, 3), (0, 4), (2, 5)])
        cls.G = G

        D = nx.DiGraph()
        D.add_nodes_from([0, 1], fish='one')
        D.add_nodes_from([2, 3], fish='two')
        D.add_nodes_from([4], fish='red')
        D.add_nodes_from([5], fish='blue')
        D.add_edges_from([(0, 1), (2, 3), (0, 4), (2, 5)])
        cls.D = D

        S = nx.Graph()
        S.add_nodes_from([0, 1], fish='one')
        S.add_nodes_from([2, 3], fish='two')
        S.add_nodes_from([4], fish='red')
        S.add_nodes_from([5], fish='blue')
        S.add_edge(0, 0)
        S.add_edge(2, 2)
        cls.S = S
示例#2
0
    def test_specified_methods(self):
        G = nx.Graph()
        nx.add_cycle(G, range(7), weight=2)
        ans = nx.average_shortest_path_length(G,
                                              weight="weight",
                                              method="dijkstra")
        assert almost_equal(ans, 4)
        ans = nx.average_shortest_path_length(G,
                                              weight="weight",
                                              method="bellman-ford")
        assert almost_equal(ans, 4)
        ans = nx.average_shortest_path_length(G,
                                              weight="weight",
                                              method="floyd-warshall")
        assert almost_equal(ans, 4)

        G = nx.Graph()
        nx.add_path(G, range(5), weight=2)
        ans = nx.average_shortest_path_length(G,
                                              weight="weight",
                                              method="dijkstra")
        assert almost_equal(ans, 4)
        ans = nx.average_shortest_path_length(G,
                                              weight="weight",
                                              method="bellman-ford")
        assert almost_equal(ans, 4)
        ans = nx.average_shortest_path_length(G,
                                              weight="weight",
                                              method="floyd-warshall")
        assert almost_equal(ans, 4)
    def setup_method(self):
        N = nx.Graph()
        N.add_nodes_from([0, 1], margin=-2)
        N.add_nodes_from([2, 3], margin=-2)
        N.add_nodes_from([4], margin=-3)
        N.add_nodes_from([5], margin=-4)
        N.add_edges_from([(0, 1), (2, 3), (0, 4), (2, 5)])
        self.N = N

        F = nx.Graph()
        F.add_node(1, margin=0.5)
        F.add_nodes_from([0, 2, 3], margin=1.5)
        F.add_edges_from([(0, 3), (1, 3), (2, 3)], weight=0.5)
        F.add_edge(0, 2, weight=1)
        self.F = F

        M = nx.Graph()
        M.add_nodes_from([1, 2], margin=-1)
        M.add_nodes_from([3], margin=1)
        M.add_nodes_from([4], margin=2)
        M.add_edges_from([(3, 4), (1, 2), (1, 3)])
        self.M = M

        P = nx.DiGraph()
        P.add_nodes_from([1, 2], margin=-1)
        P.add_nodes_from([3], margin=1)
        P.add_nodes_from([4], margin=2)
        P.add_edges_from([(3, 4), (1, 2), (1, 3)])
        self.P = P
示例#4
0
    def test_graph(self):
        g = nx.cycle_graph(10)
        G = nx.Graph()
        G.add_nodes_from(g)
        G.add_weighted_edges_from((u, v, u) for u, v in g.edges())

        # Dict of dicts
        dod = to_dict_of_dicts(G)
        GG = from_dict_of_dicts(dod, create_using=nx.Graph)
        assert nodes_equal(sorted(G.nodes()), sorted(GG.nodes()))
        assert edges_equal(sorted(G.edges()), sorted(GG.edges()))
        GW = to_networkx_graph(dod, create_using=nx.Graph)
        assert nodes_equal(sorted(G.nodes()), sorted(GW.nodes()))
        assert edges_equal(sorted(G.edges()), sorted(GW.edges()))
        GI = nx.Graph(dod)
        assert nodes_equal(sorted(G.nodes()), sorted(GI.nodes()))
        assert edges_equal(sorted(G.edges()), sorted(GI.edges()))

        # Dict of lists
        dol = to_dict_of_lists(G)
        GG = from_dict_of_lists(dol, create_using=nx.Graph)
        # dict of lists throws away edge data so set it to none
        enone = [(u, v, {}) for (u, v, d) in G.edges(data=True)]
        assert nodes_equal(sorted(G.nodes()), sorted(GG.nodes()))
        assert edges_equal(enone, sorted(GG.edges(data=True)))
        GW = to_networkx_graph(dol, create_using=nx.Graph)
        assert nodes_equal(sorted(G.nodes()), sorted(GW.nodes()))
        assert edges_equal(enone, sorted(GW.edges(data=True)))
        GI = nx.Graph(dol)
        assert nodes_equal(sorted(G.nodes()), sorted(GI.nodes()))
        assert edges_equal(enone, sorted(GI.edges(data=True)))
示例#5
0
 def test_attribute_dict_integrity(self):
     # we must not replace dict-like graph data structures with dicts
     G = nx.Graph()
     G.add_nodes_from("abc")
     H = to_networkx_graph(G, create_using=nx.Graph)
     assert list(H.nodes) == list(G.nodes)
     H = nx.Graph(G)
     assert list(H.nodes) == list(G.nodes)
示例#6
0
 def setup_class(cls):
     cnlti = nx.convert_node_labels_to_integers
     Gi = cnlti(grid_2d_graph(5, 5), first_label=1, ordering="sorted")
     cls.Gi = nx.Graph(Gi)
     cls.Gs = nx.Graph()
     nx.add_path(cls.Gs, "abcdef")
     bigG = cnlti(grid_2d_graph(25, 25), first_label=1, ordering="sorted")
     cls.bigG = nx.Graph(bigG)
示例#7
0
 def test_weighted(self):
     G = nx.Graph()
     nx.add_cycle(G, range(7), weight=2)
     ans = nx.average_shortest_path_length(G, weight="weight")
     assert almost_equal(ans, 4)
     G = nx.Graph()
     nx.add_path(G, range(5), weight=2)
     ans = nx.average_shortest_path_length(G, weight="weight")
     assert almost_equal(ans, 4)
示例#8
0
 def setup_class(cls):
     # simple graph
     G = nx.Graph()
     G.add_edges_from([(0, 1), (1, 2), (1, 3), (2, 4), (3, 4)])
     cls.G = G
     # simple graph, disconnected
     D = nx.Graph()
     D.add_edges_from([(0, 1), (2, 3)])
     cls.D = D
示例#9
0
 def setup_method(self):
     # a tree
     G = nx.Graph()
     nx.add_path(G, [0, 1, 2, 3, 4, 5, 6])
     nx.add_path(G, [2, 7, 8, 9, 10])
     self.G = G
     # a disconnected graph
     D = nx.Graph()
     D.add_edges_from([(0, 1), (2, 3)])
     nx.add_path(D, [2, 7, 8, 9, 10])
     self.D = D
示例#10
0
 def setup_class(cls):
     # a tree
     G = nx.Graph()
     nx.add_path(G, [0, 1, 2, 3, 4, 5, 6])
     nx.add_path(G, [2, 7, 8, 9, 10])
     cls.G = G
     # a disconnected graph
     D = nx.Graph()
     D.add_edges_from([(0, 1), (2, 3)])
     nx.add_path(D, [2, 7, 8, 9, 10])
     cls.D = D
示例#11
0
 def test_bfs_tree_isolates(self):
     G = nx.Graph()
     G.add_node(1)
     G.add_node(2)
     T = nx.builtin.bfs_tree(G, source=1, depth_limit=10)
     assert sorted(T.nodes()) == [1]
     assert sorted(T.edges()) == []
示例#12
0
def gnm_random_graph(n, m, seed=None, directed=False):
    if directed:
        G = nx.DiGraph()
    else:
        G = nx.Graph()
    G.add_nodes_from(range(n))

    if n == 1:
        return G
    max_edges = n * (n - 1)
    if not directed:
        max_edges /= 2.0
    if m >= max_edges:
        return complete_graph(n, create_using=G)

    nlist = list(G)
    edge_count = 0
    while edge_count < m:
        # generate random edge,u,v
        u = seed.choice(nlist)
        v = seed.choice(nlist)
        if u == v:
            continue
        else:
            G.add_edge(u, v)
            edge_count = edge_count + 1
    return G
示例#13
0
 def setup_method(self):
     self.Graph = nx.Graph
     self.k3nodes = [0, 1, 2]
     self.k3edges = [(0, 1), (0, 2), (1, 2)]
     data_dir = os.path.expandvars("${GS_TEST_DIR}/networkx")
     self.k3 = k3_graph(data_dir, False)
     self.K3 = nx.Graph(self.k3, default_label="vertex")
示例#14
0
 def test_write_edgelist_2(self):
     fh = io.BytesIO()
     G = nx.Graph()
     G.add_edges_from([(1, 2), (2, 3)])
     nx.write_edgelist(G, fh, data=True)
     fh.seek(0)
     assert fh.read() in (b"1 2 {}\n2 3 {}\n", b"2 3 {}\n2 1 {}\n")
    def test_krackhardt_kite_graph_normalized(self):
        """Weighted betweenness centrality:
        Krackhardt kite graph normalized
        """
        G = nx.krackhardt_kite_graph()
        G = nx.Graph(G)
        for e in G.edges:
            G.edges[e]["weight"] = 1
        b_answer = {
            0: 0.023,
            1: 0.023,
            2: 0.000,
            3: 0.102,
            4: 0.000,
            5: 0.231,
            6: 0.231,
            7: 0.389,
            8: 0.222,
            9: 0.000,
        }
        b = nx.builtin.betweenness_centrality(G,
                                              weight="weight",
                                              normalized=True)

        for n in sorted(G):
            assert almost_equal(b[n], b_answer[n], 3)
示例#16
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
 def test_normalized_weighted_graph(self):
     eList = [
         (0, 1, 5),
         (0, 2, 4),
         (0, 3, 3),
         (0, 4, 2),
         (1, 2, 4),
         (1, 3, 1),
         (1, 4, 3),
         (2, 4, 5),
         (3, 4, 4),
     ]
     G = nx.Graph()
     G.add_weighted_edges_from(eList)
     b = nx.edge_betweenness_centrality(G, weight="weight", normalized=True)
     b_answer = {
         (0, 1): 0.0,
         (0, 2): 1.0,
         (0, 3): 2.0,
         (0, 4): 1.0,
         (1, 2): 2.0,
         (1, 3): 3.5,
         (1, 4): 1.5,
         (2, 4): 1.0,
         (3, 4): 0.5,
     }
     norm = len(G) * (len(G) - 1) / 2
     for n in sorted(G.edges()):
         assert almost_equal(b[n], b_answer[n])
示例#18
0
 def test_disconnected(self):
     g = nx.Graph()
     g.add_nodes_from(range(3))
     g.add_edge(0, 1)
     pytest.raises(nx.NetworkXError, nx.average_shortest_path_length, g)
     g = g.to_directed()
     pytest.raises(nx.NetworkXError, nx.average_shortest_path_length, g)
示例#19
0
 def test_lind_square_clustering(self):
     """Test C4 for figure 1 Lind et al (2005)"""
     G = nx.Graph(
         [
             (1, 2),
             (1, 3),
             (1, 6),
             (1, 7),
             (2, 4),
             (2, 5),
             (3, 4),
             (3, 5),
             (6, 7),
             (7, 8),
             (6, 8),
             (7, 9),
             (7, 10),
             (6, 11),
             (6, 12),
             (2, 13),
             (2, 14),
             (3, 15),
             (3, 16),
         ]
     )
     G1 = G.subgraph([1, 2, 3, 4, 5, 13, 14, 15, 16])
     G2 = G.subgraph([1, 6, 7, 8, 9, 10, 11, 12])
     assert nx.square_clustering(G, [1])[1] == 3 / 75.0
     assert nx.square_clustering(G1, [1])[1] == 2 / 6.0
     assert nx.square_clustering(G2, [1])[1] == 1 / 5.0
    def test_krackhardt_kite_graph(self):
        """Weighted betweenness centrality: Krackhardt kite graph"""
        G = nx.krackhardt_kite_graph()
        G = nx.Graph(G)
        for e in G.edges:
            G.edges[e]["weight"] = 1
        b_answer = {
            0: 1.667,
            1: 1.667,
            2: 0.000,
            3: 7.333,
            4: 0.000,
            5: 16.667,
            6: 16.667,
            7: 28.000,
            8: 16.000,
            9: 0.000,
        }
        for b in b_answer:
            b_answer[b] /= 2

        b = nx.builtin.betweenness_centrality(G,
                                              weight="weight",
                                              normalized=False)

        for n in sorted(G):
            assert almost_equal(b[n], b_answer[n], 3)
示例#21
0
    def test_weight_keyword(self):
        G = nx.Graph()
        G.add_nodes_from([0, 1, 2, 3])
        G.add_edges_from([(0, 1), (2, 3)], other=1.0)
        G.add_edge(1, 2, other=4.0)
        # G = nx.path_graph(4)
        # G[1][2]["other"] = 4
        answer = {1: 2.0, 2: 1.8}
        nd = nx.builtin.average_degree_connectivity(G, weight="other")
        assert nd == answer
        answer = {1: 2.0, 2: 1.5}
        nd = nx.builtin.average_degree_connectivity(G, weight=None)
        assert nd == answer

        D = G.to_directed()
        answer = {2: 2.0, 4: 1.8}
        nd = nx.builtin.average_degree_connectivity(D, weight="other")
        assert nd == answer

        answer = {1: 2.0, 2: 1.8}
        D = G.to_directed()
        nd = nx.builtin.average_degree_connectivity(
            D, weight="other", source="in", target="in"
        )
        assert nd == answer

        D = G.to_directed()
        nd = nx.builtin.average_degree_connectivity(
            D, weight="other", source="in", target="in"
        )
        assert nd == answer
示例#22
0
 def test_degree_barrat(self):
     # G = nx.star_graph(5)
     G = nx.Graph()
     G.add_edges_from(
         [
             (1, 0),
             (2, 0),
             (3, 0),
             (4, 0),
             (5, 0),
             (0, 1),
             (0, 2),
             (0, 3),
             (0, 4),
             (0, 5),
         ],
         weight=1,
     )
     G.add_edges_from([(5, 6), (5, 7), (5, 8), (5, 9)], weight=1)
     G.add_edge(0, 5, weight=5)
     # G[0][5]["weight"] = 5
     nd = nx.builtin.average_degree_connectivity(G)[5]
     assert nd == 1.8
     nd = nx.builtin.average_degree_connectivity(G, weight="weight")[5]
     assert nd == pytest.approx(3.222222, abs=1e-5)
示例#23
0
 def test_from_adjacency(self):
     nodelist = [1, 2]
     dftrue = pd.DataFrame(
         [[1, 1], [1, 0]], dtype=int, index=nodelist, columns=nodelist
     )
     G = nx.Graph([(1, 1), (1, 2)])
     df = nx.to_pandas_adjacency(G, dtype=int)
     pd.testing.assert_frame_equal(df, dftrue)
示例#24
0
 def setup_class(cls):
     cls.edges = [(0, 1), (0, 2), (1, 2), (2, 3), (1, 4)]
     G = nx.Graph()
     G.add_edges_from(cls.edges, weight=1)
     DG = nx.DiGraph()
     DG.add_edges_from(cls.edges, weight=1)
     cls.G = G
     cls.DG = DG
示例#25
0
def test_is_empty():
    graphs = [nx.Graph(), nx.DiGraph()]
    for G in graphs:
        assert nx.is_empty(G)
        G.add_nodes_from(range(5))
        assert nx.is_empty(G)
        G.add_edges_from([(1, 2), (3, 4)])
        assert not nx.is_empty(G)
示例#26
0
 def test_write_edgelist_4(self):
     fh = io.BytesIO()
     G = nx.Graph()
     G.add_edge(1, 2, weight=2.0)
     G.add_edge(2, 3, weight=3.0)
     nx.write_edgelist(G, fh, data=[("weight")])
     fh.seek(0)
     assert fh.read() in (b"1 2 2.0\n2 3 3.0\n", b"2 3 3.0\n2 1 2.0\n")
    def setup_class(cls):
        data_dir = os.path.expandvars("${GS_TEST_DIR}/networkx")
        p2p_dir = os.path.expandvars("${GS_TEST_DIR}")

        cls.simple = simple_label_graph(data_dir, True)
        cls.multi_simple = simple_label_multigraph(data_dir, True)
        cls.K3 = k3_graph(data_dir, False)
        cls.SG = nx.DiGraph(cls.simple, default_label="v-0")
        cls.SG.pagerank = {
            1: 0.03721197,
            2: 0.05395735,
            3: 0.04150565,
            4: 0.37508082,
            5: 0.20599833,
            6: 0.28624589,
        }
        cls.SG.auth = {
            1: 0.165000,
            2: 0.243018,
            3: 0.078017,
            4: 0.078017,
            5: 0.270943,
            6: 0.165000,
        }
        cls.SG.hub = {
            1: 0.182720,
            2: 0.0,
            3: 0.386437,
            4: 0.248121,
            5: 0.138316,
            6: 0.044404,
        }
        cls.SG.eigen = {
            1: 3.201908045277076e-06,
            2: 6.4038160905537886e-06,
            3: 3.201908045277076e-06,
            5: 0.40044823300165794,
            4: 0.6479356498234745,
            6: 0.6479356498234745,
        }
        cls.SG.katz = {
            1: 0.37871516522035104,
            2: 0.4165866814015425,
            3: 0.37871516522035104,
            5: 0.42126739520601203,
            4: 0.4255225997990211,
            6: 0.4255225997990211,
        }

        cls.p2p_31 = p2p_31_graph(p2p_dir, False)
        cls.P2P = nx.Graph(cls.p2p_31, default_label="vertex")
        cls.P2P.sssp = dict(
            pd.read_csv(
                "{}/p2p-31-sssp".format(os.path.expandvars("${GS_TEST_DIR}")),
                sep=" ",
                header=None,
                prefix="",
            ).values)
示例#28
0
    def test_write_with_node_attributes(self):
        # Addresses #673.
        G = nx.Graph()
        G.add_edges_from([(0, 1), (1, 2), (2, 3)])
        for i in range(4):
            G.nodes[i]["id"] = i
            G.nodes[i]["label"] = i
            G.nodes[i]["pid"] = i
            G.nodes[i]["start"] = i
            G.nodes[i]["end"] = i + 1

        if sys.version_info < (3, 8):
            expected = f"""<gexf version="1.2" xmlns="http://www.gexf.net/1.2\
draft" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:\
schemaLocation="http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/\
gexf.xsd">
  <meta lastmodifieddate="{time.strftime('%Y-%m-%d')}">
    <creator>NetworkX {nx.__version__}</creator>
  </meta>
  <graph defaultedgetype="undirected" mode="dynamic" name="" timeformat="long">
    <nodes>
      <node end="1" id="0" label="0" pid="0" start="0" />
      <node end="2" id="1" label="1" pid="1" start="1" />
      <node end="3" id="2" label="2" pid="2" start="2" />
      <node end="4" id="3" label="3" pid="3" start="3" />
    </nodes>
    <edges>
      <edge id="0" source="0" target="1" />
      <edge id="1" source="1" target="2" />
      <edge id="2" source="2" target="3" />
    </edges>
  </graph>
</gexf>"""
        else:
            expected = f"""<gexf xmlns="http://www.gexf.net/1.2draft" xmlns:xsi\
="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=\
"http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/\
gexf.xsd" version="1.2">
  <meta lastmodifieddate="{time.strftime('%Y-%m-%d')}">
    <creator>NetworkX {nx.__version__}</creator>
  </meta>
  <graph defaultedgetype="undirected" mode="dynamic" name="" timeformat="long">
    <nodes>
      <node id="0" label="0" pid="0" start="0" end="1" />
      <node id="1" label="1" pid="1" start="1" end="2" />
      <node id="2" label="2" pid="2" start="2" end="3" />
      <node id="3" label="3" pid="3" start="3" end="4" />
    </nodes>
    <edges>
      <edge source="0" target="1" id="0" />
      <edge source="1" target="2" id="1" />
      <edge source="2" target="3" id="2" />
    </edges>
  </graph>
</gexf>"""
        obtained = "\n".join(nx.generate_gexf(G))
        assert expected == obtained
示例#29
0
 def test_simple_list(self):
     G = nx.Graph()
     list_value = [[1, 2, 3], [9, 1, 2]]
     G.add_node(1, key=list_value)
     fh = io.BytesIO()
     nx.write_gexf(G, fh)
     fh.seek(0)
     H = nx.read_gexf(fh, node_type=int)
     assert H.nodes[1]["networkx_key"] == list_value
 def test_disconnected_path(self):
     """Betweenness centrality: disconnected path"""
     G = nx.Graph()
     nx.add_path(G, [0, 1, 2])
     nx.add_path(G, [3, 4, 5, 6])
     b_answer = {0: 0, 1: 1, 2: 0, 3: 0, 4: 2, 5: 2, 6: 0}
     b = nx.builtin.betweenness_centrality(G, weight=None, normalized=False)
     for n in sorted(G):
         assert almost_equal(b[n], b_answer[n])