Esempio n. 1
0
    def test_simple_graphs(self):
        for dest, source in [
            (to_dict_of_dicts, from_dict_of_dicts),
            (to_dict_of_lists, from_dict_of_lists),
        ]:
            G = barbell_graph(10, 3)
            G.graph = {}
            dod = dest(G)

            # Dict of [dicts, lists]
            GG = source(dod)
            assert graphs_equal(G, GG)
            GW = to_networkx_graph(dod)
            assert graphs_equal(G, GW)
            GI = nx.Graph(dod)
            assert graphs_equal(G, GI)

            # With nodelist keyword
            P4 = nx.path_graph(4)
            P3 = nx.path_graph(3)
            P4.graph = {}
            P3.graph = {}
            dod = dest(P4, nodelist=[0, 1, 2])
            Gdod = nx.Graph(dod)
            assert graphs_equal(Gdod, P3)
 def test_roundtrip(self, graph):
     # edgelist
     Gtrue = graph([(1, 1), (1, 2)])
     df = nx.to_pandas_edgelist(Gtrue)
     G = nx.from_pandas_edgelist(df, create_using=graph)
     assert graphs_equal(Gtrue, G)
     # adjacency
     adj = {1: {1: {"weight": 1}, 2: {"weight": 1}}, 2: {1: {"weight": 1}}}
     Gtrue = graph(adj)
     df = nx.to_pandas_adjacency(Gtrue, dtype=int)
     G = nx.from_pandas_adjacency(df, create_using=graph)
     assert graphs_equal(Gtrue, G)
Esempio n. 3
0
 def test_round_trip_empty_graph(self):
     G = nx.Graph()
     A = nx.nx_agraph.to_agraph(G)
     H = nx.nx_agraph.from_agraph(A)
     # assert graphs_equal(G, H)
     AA = nx.nx_agraph.to_agraph(H)
     HH = nx.nx_agraph.from_agraph(AA)
     assert graphs_equal(H, HH)
     G.graph["graph"] = {}
     G.graph["node"] = {}
     G.graph["edge"] = {}
     assert graphs_equal(G, HH)
Esempio n. 4
0
def test_from_scipy_sparse_matrix_formats(sparse_format):
    """Test all formats supported by _generate_weighted_edges."""
    # trinode complete graph with non-uniform edge weights
    expected = nx.Graph()
    expected.add_edges_from([
        (0, 1, {
            "weight": 3
        }),
        (0, 2, {
            "weight": 2
        }),
        (1, 0, {
            "weight": 3
        }),
        (1, 2, {
            "weight": 1
        }),
        (2, 0, {
            "weight": 2
        }),
        (2, 1, {
            "weight": 1
        }),
    ])
    A = sp.sparse.coo_matrix([[0, 3, 2], [3, 0, 1],
                              [2, 1, 0]]).asformat(sparse_format)
    assert graphs_equal(expected, nx.from_scipy_sparse_matrix(A))
Esempio n. 5
0
 def test_read_write(self):
     G = nx.MultiGraph()
     G.graph["name"] = "G"
     G.add_edge("1", "2", key="0")  # read assumes strings
     fh = StringIO()
     nx.nx_pydot.write_dot(G, fh)
     fh.seek(0)
     H = nx.nx_pydot.read_dot(fh)
     assert graphs_equal(G, H)
Esempio n. 6
0
def assert_graphs_equal(graph1, graph2):
    warnings.warn(
        (
            "`assert_graphs_equal` is deprecated and will be removed in version 3.0.\n"
            "Use `from networkx.utils import graphs_equal` and `assert graphs_equal` instead.\n"
        ),
        DeprecationWarning,
    )
    assert graphs_equal(graph1, graph2)
Esempio n. 7
0
    def test_symmetric(self):
        """Tests that a symmetric array has edges added only once to an
        undirected multigraph when using :func:`networkx.from_numpy_array`.

        """
        A = np.array([[0, 1], [1, 0]])
        G = nx.from_numpy_array(A, create_using=nx.MultiGraph)
        expected = nx.MultiGraph()
        expected.add_edge(0, 1, weight=1)
        assert graphs_equal(G, expected)
 def test_unicode(self):
     G = nx.Graph()
     name1 = chr(2344) + chr(123) + chr(6543)
     name2 = chr(5543) + chr(1543) + chr(324)
     G.add_edge(name1, "Radiohead", **{name2: 3})
     fd, fname = tempfile.mkstemp()
     nx.write_edgelist(G, fname)
     H = nx.read_edgelist(fname)
     assert graphs_equal(G, H)
     os.close(fd)
     os.unlink(fname)
 def test_latin1(self):
     G = nx.Graph()
     name1 = "Bj" + chr(246) + "rk"
     name2 = chr(220) + "ber"
     G.add_edge(name1, "Radiohead", **{name2: 3})
     fd, fname = tempfile.mkstemp()
     nx.write_edgelist(G, fname, encoding="latin-1")
     H = nx.read_edgelist(fname, encoding="latin-1")
     assert graphs_equal(G, H)
     os.close(fd)
     os.unlink(fname)
Esempio n. 10
0
    def test_symmetric(self):
        """Tests that a symmetric matrix has edges added only once to an
        undirected multigraph when using
        :func:`networkx.from_scipy_sparse_matrix`.

        """
        A = sp.sparse.csr_matrix([[0, 1], [1, 0]])
        G = nx.from_scipy_sparse_matrix(A, create_using=nx.MultiGraph)
        expected = nx.MultiGraph()
        expected.add_edge(0, 1, weight=1)
        assert graphs_equal(G, expected)
 def test_from_edgelist_int_attr_name(self):
     # note: this also tests that edge_attr can be `source`
     Gtrue = nx.Graph([("E", "C", {
         0: "C"
     }), ("B", "A", {
         0: "B"
     }), ("A", "D", {
         0: "A"
     })])
     G = nx.from_pandas_edgelist(self.df, 0, "b", 0)
     assert graphs_equal(G, Gtrue)
Esempio n. 12
0
    def test_read_multiline_adjlist_1(self):
        # Unit test for https://networkx.lanl.gov/trac/ticket/252
        s = b"""# comment line
1 2
# comment line
2
3
"""
        bytesIO = io.BytesIO(s)
        G = nx.read_multiline_adjlist(bytesIO)
        adj = {"1": {"3": {}, "2": {}}, "3": {"1": {}}, "2": {"1": {}}}
        assert graphs_equal(G, nx.Graph(adj))
Esempio n. 13
0
    def test_from_scipy_sparse_matrix_parallel_edges(self):
        """Tests that the :func:`networkx.from_scipy_sparse_matrix` function
        interprets integer weights as the number of parallel edges when
        creating a multigraph.

        """
        A = sp.sparse.csr_matrix([[1, 1], [1, 2]])
        # First, with a simple graph, each integer entry in the adjacency
        # matrix is interpreted as the weight of a single edge in the graph.
        expected = nx.DiGraph()
        edges = [(0, 0), (0, 1), (1, 0)]
        expected.add_weighted_edges_from([(u, v, 1) for (u, v) in edges])
        expected.add_edge(1, 1, weight=2)
        actual = nx.from_scipy_sparse_matrix(A,
                                             parallel_edges=True,
                                             create_using=nx.DiGraph)
        assert graphs_equal(actual, expected)
        actual = nx.from_scipy_sparse_matrix(A,
                                             parallel_edges=False,
                                             create_using=nx.DiGraph)
        assert graphs_equal(actual, expected)
        # Now each integer entry in the adjacency matrix is interpreted as the
        # number of parallel edges in the graph if the appropriate keyword
        # argument is specified.
        edges = [(0, 0), (0, 1), (1, 0), (1, 1), (1, 1)]
        expected = nx.MultiDiGraph()
        expected.add_weighted_edges_from([(u, v, 1) for (u, v) in edges])
        actual = nx.from_scipy_sparse_matrix(A,
                                             parallel_edges=True,
                                             create_using=nx.MultiDiGraph)
        assert graphs_equal(actual, expected)
        expected = nx.MultiDiGraph()
        expected.add_edges_from(set(edges), weight=1)
        # The sole self-loop (edge 0) on vertex 1 should have weight 2.
        expected[1][1][0]["weight"] = 2
        actual = nx.from_scipy_sparse_matrix(A,
                                             parallel_edges=False,
                                             create_using=nx.MultiDiGraph)
        assert graphs_equal(actual, expected)
 def test_from_edgelist_all_attr(self):
     Gtrue = nx.Graph([
         ("E", "C", {
             "cost": 9,
             "weight": 10
         }),
         ("B", "A", {
             "cost": 1,
             "weight": 7
         }),
         ("A", "D", {
             "cost": 7,
             "weight": 4
         }),
     ])
     G = nx.from_pandas_edgelist(self.df, 0, "b", True)
     assert graphs_equal(G, Gtrue)
     # MultiGraph
     MGtrue = nx.MultiGraph(Gtrue)
     MGtrue.add_edge("A", "D", cost=16, weight=4)
     MG = nx.from_pandas_edgelist(self.mdf, 0, "b", True, nx.MultiGraph())
     assert graphs_equal(MG, MGtrue)
 def test_from_edgelist_one_attr(self):
     Gtrue = nx.Graph([
         ("E", "C", {
             "weight": 10
         }),
         ("B", "A", {
             "weight": 7
         }),
         ("A", "D", {
             "weight": 4
         }),
     ])
     G = nx.from_pandas_edgelist(self.df, 0, "b", "weight")
     assert graphs_equal(G, Gtrue)
 def test_edgekey_with_normal_graph_no_action(self):
     Gtrue = nx.Graph([
         ("E", "C", {
             "cost": 9,
             "weight": 10
         }),
         ("B", "A", {
             "cost": 1,
             "weight": 7
         }),
         ("A", "D", {
             "cost": 7,
             "weight": 4
         }),
     ])
     G = nx.from_pandas_edgelist(self.df, 0, "b", True, edge_key="weight")
     assert graphs_equal(G, Gtrue)
Esempio n. 17
0
 def test_from_edgelist_multi_attr_incl_target(self):
     Gtrue = nx.Graph([
         ("E", "C", {
             "b": "E",
             "weight": 10
         }),
         ("B", "A", {
             "b": "A",
             "weight": 7
         }),
         ("A", "D", {
             "b": "D",
             "weight": 4
         }),
     ])
     G = nx.from_pandas_edgelist(self.df, 0, "b", ["b", "weight"])
     assert graphs_equal(G, Gtrue)
 def test_from_edgelist_multi_attr(self):
     Gtrue = nx.Graph([
         ("E", "C", {
             "cost": 9,
             "weight": 10
         }),
         ("B", "A", {
             "cost": 1,
             "weight": 7
         }),
         ("A", "D", {
             "cost": 7,
             "weight": 4
         }),
     ])
     G = nx.from_pandas_edgelist(self.df, 0, "b", ["weight", "cost"])
     assert graphs_equal(G, Gtrue)
Esempio n. 19
0
 def test_protocol(self):
     for G in [
         self.G,
         self.DG,
         self.MG,
         self.MDG,
         self.fG,
         self.fDG,
         self.fMG,
         self.fMDG,
     ]:
         with tempfile.TemporaryFile() as f:
             nx.write_gpickle(G, f, 0)
             f.seek(0)
             Gin = nx.read_gpickle(f)
             assert nodes_equal(list(G.nodes(data=True)), list(Gin.nodes(data=True)))
             assert edges_equal(list(G.edges(data=True)), list(Gin.edges(data=True)))
             assert graphs_equal(G, Gin)
Esempio n. 20
0
 def test_gpickle(self):
     for G in [
         self.G,
         self.DG,
         self.MG,
         self.MDG,
         self.fG,
         self.fDG,
         self.fMG,
         self.fMDG,
     ]:
         (fd, fname) = tempfile.mkstemp()
         nx.write_gpickle(G, fname)
         Gin = nx.read_gpickle(fname)
         assert nodes_equal(list(G.nodes(data=True)), list(Gin.nodes(data=True)))
         assert edges_equal(list(G.edges(data=True)), list(Gin.edges(data=True)))
         assert graphs_equal(G, Gin)
         os.close(fd)
         os.unlink(fname)
Esempio n. 21
0
    def pydot_checks(self, G, prog):
        """
        Validate :mod:`pydot`-based usage of the passed NetworkX graph with the
        passed basename of an external GraphViz command (e.g., `dot`, `neato`).
        """

        # Set the name of this graph to... "G". Failing to do so will
        # subsequently trip an assertion expecting this name.
        G.graph["name"] = "G"

        # Add arbitrary nodes and edges to the passed empty graph.
        G.add_edges_from([("A", "B"), ("A", "C"), ("B", "C"), ("A", "D")])
        G.add_node("E")

        # Validate layout of this graph with the passed GraphViz command.
        graph_layout = nx.nx_pydot.pydot_layout(G, prog=prog)
        assert isinstance(graph_layout, dict)

        # Convert this graph into a "pydot.Dot" instance.
        P = nx.nx_pydot.to_pydot(G)

        # Convert this "pydot.Dot" instance back into a graph of the same type.
        G2 = G.__class__(nx.nx_pydot.from_pydot(P))

        # Validate the original and resulting graphs to be the same.
        assert graphs_equal(G, G2)

        fd, fname = tempfile.mkstemp()

        # Serialize this "pydot.Dot" instance to a temporary file in dot format
        P.write_raw(fname)

        # Deserialize a list of new "pydot.Dot" instances back from this file.
        Pin_list = pydot.graph_from_dot_file(path=fname, encoding="utf-8")

        # Validate this file to contain only one graph.
        assert len(Pin_list) == 1

        # The single "pydot.Dot" instance deserialized from this file.
        Pin = Pin_list[0]

        # Sorted list of all nodes in the original "pydot.Dot" instance.
        n1 = sorted([p.get_name() for p in P.get_node_list()])

        # Sorted list of all nodes in the deserialized "pydot.Dot" instance.
        n2 = sorted([p.get_name() for p in Pin.get_node_list()])

        # Validate these instances to contain the same nodes.
        assert n1 == n2

        # Sorted list of all edges in the original "pydot.Dot" instance.
        e1 = sorted([(e.get_source(), e.get_destination())
                     for e in P.get_edge_list()])

        # Sorted list of all edges in the original "pydot.Dot" instance.
        e2 = sorted([(e.get_source(), e.get_destination())
                     for e in Pin.get_edge_list()])

        # Validate these instances to contain the same edges.
        assert e1 == e2

        # Deserialize a new graph of the same type back from this file.
        Hin = nx.nx_pydot.read_dot(fname)
        Hin = G.__class__(Hin)

        # Validate the original and resulting graphs to be the same.
        assert graphs_equal(G, Hin)

        os.close(fd)
        os.unlink(fname)
Esempio n. 22
0
    def test_update(self):
        # specify both edges and nodes
        G = self.K3.copy()
        G.update(nodes=[3, (4, {"size": 2})], edges=[(4, 5), (6, 7, {"weight": 2})])
        nlist = [
            (0, {}),
            (1, {}),
            (2, {}),
            (3, {}),
            (4, {"size": 2}),
            (5, {}),
            (6, {}),
            (7, {}),
        ]
        assert sorted(G.nodes.data()) == nlist
        if G.is_directed():
            elist = [
                (0, 1, {}),
                (0, 2, {}),
                (1, 0, {}),
                (1, 2, {}),
                (2, 0, {}),
                (2, 1, {}),
                (4, 5, {}),
                (6, 7, {"weight": 2}),
            ]
        else:
            if os.environ.get("DEPLOYMENT", None) == "standalone":
                elist = [
                    (0, 1, {}),
                    (0, 2, {}),
                    (1, 2, {}),
                    (4, 5, {}),
                    (6, 7, {"weight": 2}),
                ]
            else:  # num_workers = 2
                elist = [
                    (0, 2, {}),
                    (1, 0, {}),
                    (1, 2, {}),
                    (5, 4, {}),
                    (7, 6, {"weight": 2}),
                ]
        assert sorted(G.edges.data()) == elist
        assert G.graph == {}

        # no keywords -- order is edges, nodes
        G = self.K3.copy()
        G.update([(4, 5), (6, 7, {"weight": 2})], [3, (4, {"size": 2})])
        assert sorted(G.nodes.data()) == nlist
        assert sorted(G.edges.data()) == elist
        assert G.graph == {}

        # update using only a graph
        G = self.Graph()
        G.graph["foo"] = "bar"
        G.add_node(2, data=4)
        G.add_edge(0, 1, weight=0.5)
        GG = G.copy()
        H = self.Graph()
        GG.update(H)
        assert graphs_equal(G, GG)
        H.update(G)
        assert graphs_equal(H, G)

        # update nodes only
        H = self.Graph()
        H.update(nodes=[3, 4])
        assert H.nodes ^ {3, 4} == set()
        assert H.size() == 0

        # update edges only
        H = self.Graph()
        H.update(edges=[(3, 4)])
        if H.is_directed():
            assert sorted(H.edges.data()) == [(3, 4, {})]
        else:
            assert sorted(H.edges.data()) in ([(3, 4, {})], [(4, 3, {})])
        assert H.size() == 1

        # No inputs -> exception
        with pytest.raises(nx.NetworkXError):
            nx.Graph().update()
 def test_from_edgelist_no_attr(self):
     Gtrue = nx.Graph([("E", "C", {}), ("B", "A", {}), ("A", "D", {})])
     G = nx.from_pandas_edgelist(self.df, 0, "b")
     assert graphs_equal(G, Gtrue)
Esempio n. 24
0
def test_implementations_consistent(strings):
    """Ensure results are consistent between prefix_tree implementations."""
    assert graphs_equal(nx.prefix_tree(strings),
                        nx.prefix_tree_recursive(strings))
    def test_edgekey_with_multigraph(self):
        df = pd.DataFrame({
            "source": {
                "A": "N1",
                "B": "N2",
                "C": "N1",
                "D": "N1"
            },
            "target": {
                "A": "N2",
                "B": "N3",
                "C": "N1",
                "D": "N2"
            },
            "attr1": {
                "A": "F1",
                "B": "F2",
                "C": "F3",
                "D": "F4"
            },
            "attr2": {
                "A": 1,
                "B": 0,
                "C": 0,
                "D": 0
            },
            "attr3": {
                "A": 0,
                "B": 1,
                "C": 0,
                "D": 1
            },
        })
        Gtrue = nx.MultiGraph([
            ("N1", "N2", "F1", {
                "attr2": 1,
                "attr3": 0
            }),
            ("N2", "N3", "F2", {
                "attr2": 0,
                "attr3": 1
            }),
            ("N1", "N1", "F3", {
                "attr2": 0,
                "attr3": 0
            }),
            ("N1", "N2", "F4", {
                "attr2": 0,
                "attr3": 1
            }),
        ])
        # example from issue #4065
        G = nx.from_pandas_edgelist(
            df,
            source="source",
            target="target",
            edge_attr=["attr2", "attr3"],
            edge_key="attr1",
            create_using=nx.MultiGraph(),
        )
        assert graphs_equal(G, Gtrue)

        df_roundtrip = nx.to_pandas_edgelist(G, edge_key="attr1")
        df_roundtrip = df_roundtrip.sort_values("attr1")
        df_roundtrip.index = ["A", "B", "C", "D"]
        pd.testing.assert_frame_equal(
            df, df_roundtrip[["source", "target", "attr1", "attr2", "attr3"]])
 def test_from_edgelist_multidigraph_and_edge_attr(self):
     # example from issue #2374
     edges = [
         ("X1", "X4", {
             "Co": "zA",
             "Mi": 0,
             "St": "X1"
         }),
         ("X1", "X4", {
             "Co": "zB",
             "Mi": 54,
             "St": "X2"
         }),
         ("X1", "X4", {
             "Co": "zB",
             "Mi": 49,
             "St": "X3"
         }),
         ("X1", "X4", {
             "Co": "zB",
             "Mi": 44,
             "St": "X4"
         }),
         ("Y1", "Y3", {
             "Co": "zC",
             "Mi": 0,
             "St": "Y1"
         }),
         ("Y1", "Y3", {
             "Co": "zC",
             "Mi": 34,
             "St": "Y2"
         }),
         ("Y1", "Y3", {
             "Co": "zC",
             "Mi": 29,
             "St": "X2"
         }),
         ("Y1", "Y3", {
             "Co": "zC",
             "Mi": 24,
             "St": "Y3"
         }),
         ("Z1", "Z3", {
             "Co": "zD",
             "Mi": 0,
             "St": "Z1"
         }),
         ("Z1", "Z3", {
             "Co": "zD",
             "Mi": 14,
             "St": "X3"
         }),
     ]
     Gtrue = nx.MultiDiGraph(edges)
     data = {
         "O": ["X1", "X1", "X1", "X1", "Y1", "Y1", "Y1", "Y1", "Z1", "Z1"],
         "D": ["X4", "X4", "X4", "X4", "Y3", "Y3", "Y3", "Y3", "Z3", "Z3"],
         "St": ["X1", "X2", "X3", "X4", "Y1", "Y2", "X2", "Y3", "Z1", "X3"],
         "Co": ["zA", "zB", "zB", "zB", "zC", "zC", "zC", "zC", "zD", "zD"],
         "Mi": [0, 54, 49, 44, 0, 34, 29, 24, 0, 14],
     }
     df = pd.DataFrame.from_dict(data)
     G1 = nx.from_pandas_edgelist(df,
                                  source="O",
                                  target="D",
                                  edge_attr=True,
                                  create_using=nx.MultiDiGraph)
     G2 = nx.from_pandas_edgelist(
         df,
         source="O",
         target="D",
         edge_attr=["St", "Co", "Mi"],
         create_using=nx.MultiDiGraph,
     )
     assert graphs_equal(G1, Gtrue)
     assert graphs_equal(G2, Gtrue)
Esempio n. 27
0
 def test_round_trip_integer_nodes(self):
     G = nx.complete_graph(3)
     A = nx.nx_agraph.to_agraph(G)
     H = nx.nx_agraph.from_agraph(A)
     assert graphs_equal(G, H)