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))
Пример #2
0
    def pydot_checks(self, G):
        G.add_edge('A','B')
        G.add_edge('A','C')
        G.add_edge('B','C')
        G.add_edge('A','D')
        G.add_node('E')
        P = nx.to_pydot(G)
        G2 = G.__class__(nx.from_pydot(P))
        assert_graphs_equal(G, G2)

        fname = tempfile.mktemp()
        assert_true( P.write_raw(fname) )

        Pin = pydotplus.graph_from_dot_file(fname)

        n1 = sorted([p.get_name() for p in P.get_node_list()])
        n2 = sorted([p.get_name() for p in Pin.get_node_list()])
        assert_true( n1 == n2 )

        e1=[(e.get_source(),e.get_destination()) for e in P.get_edge_list()]
        e2=[(e.get_source(),e.get_destination()) for e in Pin.get_edge_list()]
        assert_true( sorted(e1)==sorted(e2) )

        Hin = nx.drawing.nx_pydot.read_dot(fname)
        Hin = G.__class__(Hin)
        assert_graphs_equal(G, Hin)
Пример #3
0
 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)
Пример #4
0
    def test_exceptions(self):
        # _prep_create_using
        G = {"a": "a"}
        H = nx.to_networkx_graph(G)
        assert_graphs_equal(H, nx.Graph([('a', 'a')]))
        assert_raises(TypeError, to_networkx_graph, G, create_using=0.0)

        # NX graph
        class G(object):
            adj = None

        assert_raises(nx.NetworkXError, to_networkx_graph, G)

        # pygraphviz  agraph
        class G(object):
            is_strict = None

        assert_raises(nx.NetworkXError, to_networkx_graph, G)

        # Dict of [dicts, lists]
        G = {"a": 0}
        assert_raises(TypeError, to_networkx_graph, G)

        # list or generator of edges
        class G(object):
            next = None

        assert_raises(nx.NetworkXError, to_networkx_graph, G)

        # no match
        assert_raises(nx.NetworkXError, to_networkx_graph, "a")
Пример #5
0
 def test_from_edgelist_multidigraph_and_edge_attr(self):
     # example from issue #2374
     Gtrue = nx.MultiDiGraph([('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'}),
                              ('Z1', 'Z3', {'Co': 'zE', 'Mi': 9, 'St': 'Z2'}),
                              ('Z1', 'Z3', {'Co': 'zE', 'Mi': 4, 'St': 'Z3'})])
     df = pd.DataFrame.from_items([
         ('O', ['X1', 'X1', 'X1', 'X1', 'Y1', 'Y1', 'Y1', 'Y1', 'Z1', 'Z1', 'Z1', 'Z1']),
         ('D', ['X4', 'X4', 'X4', 'X4', 'Y3', 'Y3', 'Y3', 'Y3', 'Z3', 'Z3', 'Z3', 'Z3']),
         ('St', ['X1', 'X2', 'X3', 'X4', 'Y1', 'Y2', 'X2', 'Y3', 'Z1', 'X3', 'Z2', 'Z3']),
         ('Co', ['zA', 'zB', 'zB', 'zB', 'zC', 'zC', 'zC', 'zC', 'zD', 'zD', 'zE', 'zE']),
         ('Mi', [0,   54,   49,   44,    0,   34,   29,   24,    0,   14,    9,   4])])
     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)
Пример #6
0
 def test_roundtrip(self):
     # edgelist
     Gtrue = nx.Graph([(1, 1), (1, 2)])
     df = nx.to_pandas_edgelist(Gtrue)
     G = nx.from_pandas_edgelist(df)
     assert_graphs_equal(Gtrue, G)
     # adjacency
     Gtrue = nx.Graph(({
         1: {
             1: {
                 'weight': 1
             },
             2: {
                 'weight': 1
             }
         },
         2: {
             1: {
                 'weight': 1
             }
         }
     }))
     df = nx.to_pandas_adjacency(Gtrue, dtype=int)
     G = nx.from_pandas_adjacency(df)
     assert_graphs_equal(Gtrue, G)
Пример #7
0
 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)
Пример #8
0
    def pydot_checks(self, G):
        G.add_edge('A', 'B')
        G.add_edge('A', 'C')
        G.add_edge('B', 'C')
        G.add_edge('A', 'D')
        G.add_node('E')
        P = nx.nx_pydot.to_pydot(G)
        G2 = G.__class__(nx.nx_pydot.from_pydot(P))
        assert_graphs_equal(G, G2)

        fname = tempfile.mktemp()
        assert_true(P.write_raw(fname))

        Pin = pydotplus.graph_from_dot_file(fname)

        n1 = sorted([p.get_name() for p in P.get_node_list()])
        n2 = sorted([p.get_name() for p in Pin.get_node_list()])
        assert_true(n1 == n2)

        e1 = [(e.get_source(), e.get_destination()) for e in P.get_edge_list()]
        e2 = [(e.get_source(), e.get_destination())
              for e in Pin.get_edge_list()]
        assert_true(sorted(e1) == sorted(e2))

        Hin = nx.nx_pydot.read_dot(fname)
        Hin = G.__class__(Hin)
        assert_graphs_equal(G, Hin)
Пример #9
0
 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)
 def test_edgekey_with_multigraph(self):
     df = pd.DataFrame(
         {
             "attr1": {"A": "F1", "B": "F2", "C": "F3"},
             "attr2": {"A": 1, "B": 0, "C": 0},
             "attr3": {"A": 0, "B": 1, "C": 0},
             "source": {"A": "N1", "B": "N2", "C": "N1"},
             "target": {"A": "N2", "B": "N3", "C": "N1"},
         }
     )
     Gtrue = nx.Graph(
         [
             ("N1", "N2", {"F1": {"attr2": 1, "attr3": 0}}),
             ("N2", "N3", {"F2": {"attr2": 0, "attr3": 1}}),
             ("N1", "N1", {"F3": {"attr2": 0, "attr3": 0}}),
         ]
     )
     # 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)
Пример #11
0
 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)
Пример #12
0
    def test_exceptions(self):
        # _prep_create_using
        G = {"a": "a"}
        H = nx.to_networkx_graph(G)
        assert_graphs_equal(H, nx.Graph([('a', 'a')]))
        assert_raises(TypeError, to_networkx_graph, G, create_using=0.0)

        # NX graph
        class G(object):
            adj = None

        assert_raises(nx.NetworkXError, to_networkx_graph, G)

        # pygraphviz  agraph
        class G(object):
            is_strict = None

        assert_raises(nx.NetworkXError, to_networkx_graph, G)

        # Dict of [dicts, lists]
        G = {"a": 0}
        assert_raises(TypeError, to_networkx_graph, G)

        # list or generator of edges
        class G(object):
            next = None

        assert_raises(nx.NetworkXError, to_networkx_graph, G)

        # no match
        assert_raises(nx.NetworkXError, to_networkx_graph, "a")
Пример #13
0
 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)
Пример #14
0
def test_build_transition_graph_from_df():
    expected_graph = _transition_graph()

    traj_df = pd.DataFrame(list_data1)

    graph = build_transition_graph_from_df(traj_df)

    assert_graphs_equal(expected_graph, graph)
Пример #15
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)
Пример #16
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)
Пример #17
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)
Пример #18
0
    def test_connected_components_with_size(self):
        self.assertEqual(len(self.G.connected_components_with_size(3)),
                         len([self.expected_three1, self.expected_three2]))
        # unfortunately cannot test that two lists of graphs are
        # equal, so only test length of lists here, and then that the
        # graph in the list of len=1 below is equal. Hopefully this is
        # enough.

        returned_four = self.G.connected_components_with_size(4)[0]
        nxt.assert_graphs_equal(returned_four, self.expected_four)
 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)
Пример #20
0
    def test_connected_components_with_size(self):
        self.assertEqual(len(self.G.connected_components_with_size(3)),
                         len([self.expected_three1, self.expected_three2]))
        # unfortunately cannot test that two lists of graphs are
        # equal, so only test length of lists here, and then that the
        # graph in the list of len=1 below is equal. Hopefully this is
        # enough.

        returned_four = self.G.connected_components_with_size(4)[0]
        nxt.assert_graphs_equal(returned_four, self.expected_four)
Пример #21
0
 def test_from_edgelist_multi_attr_incl_target(self):
     Gtrue = nx.Graph(
         [
             ("E", "C", {0: "C", "b": "E", "weight": 10}),
             ("B", "A", {0: "B", "b": "A", "weight": 7}),
             ("A", "D", {0: "A", "b": "D", "weight": 4}),
         ]
     )
     G = nx.from_pandas_edgelist(self.df, 0, "b", [0, "b", "weight"])
     assert_graphs_equal(G, Gtrue)
Пример #22
0
 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)
Пример #23
0
 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)
Пример #24
0
 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)
Пример #25
0
 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)
Пример #26
0
 def test_roundtrip(self):
     # edgelist
     Gtrue = nx.Graph([(1, 1), (1, 2)])
     df = nx.to_pandas_edgelist(Gtrue)
     G = nx.from_pandas_edgelist(df)
     assert_graphs_equal(Gtrue, G)
     # adjacency
     Gtrue = nx.Graph(({1: {1: {'weight': 1}, 2: {'weight': 1}}, 2: {1: {'weight': 1}}}))
     df = nx.to_pandas_adjacency(Gtrue, dtype=int)
     G = nx.from_pandas_adjacency(df)
     assert_graphs_equal(Gtrue, G)
 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)
Пример #28
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 = 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)
Пример #29
0
 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_multiline_adjlist(G, fname, encoding="latin-1")
     H = nx.read_multiline_adjlist(fname, encoding="latin-1")
     assert_graphs_equal(G, H)
     os.close(fd)
     os.unlink(fname)
Пример #30
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 = 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_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)
Пример #32
0
 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)
Пример #33
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))
Пример #34
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)
Пример #35
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))
Пример #36
0
 def test_round_trip(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)
Пример #37
0
 def test_round_trip(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)
Пример #38
0
 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)
Пример #39
0
 def test_latin1(self):
     G = nx.Graph()
     name1 = "Bj" + chr(246) + "rk"
     name2 = chr(220) + "ber"
     G.add_edge(name1, "Radiohead", **{name2: 3})
     G.add_node(name1, bipartite=0)
     G.add_node("Radiohead", bipartite=1)
     fd, fname = tempfile.mkstemp()
     bipartite.write_edgelist(G, fname, encoding="latin-1")
     H = bipartite.read_edgelist(fname, encoding="latin-1")
     assert_graphs_equal(G, H)
     os.close(fd)
     os.unlink(fname)
Пример #40
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 = 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)
Пример #41
0
 def test_unicode(self):
     G = nx.Graph()
     try:  # Python 3.x
         name1 = chr(2344) + chr(123) + chr(6543)
         name2 = chr(5543) + chr(1543) + chr(324)
     except ValueError:  # Python 2.6+
         name1 = unichr(2344) + unichr(123) + unichr(6543)
         name2 = unichr(5543) + unichr(1543) + unichr(324)
     G.add_edge(name1, 'Radiohead', **{name2: 3})
     fd, fname = tempfile.mkstemp()
     nx.write_multiline_adjlist(G, fname)
     H = nx.read_multiline_adjlist(fname)
     assert_graphs_equal(G, H)
     os.close(fd)
     os.unlink(fname)
Пример #42
0
 def test_latin1(self):
     G = nx.Graph()
     try:  # Python 3.x
         blurb = chr(1245)  # just to trigger the exception
         name1 = 'Bj' + chr(246) + 'rk'
         name2 = chr(220) + 'ber'
     except ValueError:  # Python 2.6+
         name1 = 'Bj' + unichr(246) + 'rk'
         name2 = unichr(220) + 'ber'
     G.add_edge(name1, 'Radiohead', **{name2: 3})
     fd, fname = tempfile.mkstemp()
     nx.write_multiline_adjlist(G, fname, encoding='latin-1')
     H = nx.read_multiline_adjlist(fname, encoding='latin-1')
     assert_graphs_equal(G, H)
     os.close(fd)
     os.unlink(fname)
Пример #43
0
 def test_latin1(self):
     G = nx.Graph()
     try:  # Python 3.x
         blurb = chr(1245)  # just to trigger the exception
         name1 = "Bj" + chr(246) + "rk"
         name2 = chr(220) + "ber"
     except ValueError:  # Python 2.6+
         name1 = "Bj" + unichr(246) + "rk"
         name2 = unichr(220) + "ber"
     G.add_edge(name1, "Radiohead", {name2: 3})
     fd, fname = tempfile.mkstemp()
     nx.write_multiline_adjlist(G, fname, encoding="latin-1")
     H = nx.read_multiline_adjlist(fname, encoding="latin-1")
     assert_graphs_equal(G, H)
     os.close(fd)
     os.unlink(fname)
Пример #44
0
 def test_unicode(self):
     G = nx.Graph()
     try: # Python 3.x
         name1 = chr(2344) + chr(123) + chr(6543)
         name2 = chr(5543) + chr(1543) + chr(324)
     except ValueError: # Python 2.6+
         name1 = unichr(2344) + unichr(123) + unichr(6543)
         name2 = unichr(5543) + unichr(1543) + unichr(324)
     G.add_edge(name1, 'Radiohead', attr_dict={name2: 3})
     G.add_node(name1,bipartite=0)
     G.add_node('Radiohead',bipartite=1)
     fd, fname = tempfile.mkstemp()
     bipartite.write_edgelist(G, fname)
     H = bipartite.read_edgelist(fname)
     assert_graphs_equal(G, H)
     os.close(fd)
     os.unlink(fname)
Пример #45
0
 def test_latin1(self):
     G = nx.Graph()
     try: # Python 3.x
         blurb = chr(1245) # just to trigger the exception
         name1 = 'Bj' + chr(246) + 'rk'
         name2 = chr(220) + 'ber'
     except ValueError: # Python 2.6+
         name1 = 'Bj' + unichr(246) + 'rk'
         name2 = unichr(220) + 'ber'
     G.add_edge(name1, 'Radiohead', attr_dict={name2: 3})
     G.add_node(name1,bipartite=0)
     G.add_node('Radiohead',bipartite=1)
     fd, fname = tempfile.mkstemp()
     bipartite.write_edgelist(G, fname, encoding = 'latin-1')
     H = bipartite.read_edgelist(fname, encoding = 'latin-1')
     assert_graphs_equal(G, H)
     os.close(fd)
     os.unlink(fname)
Пример #46
0
    def test_connected_component_with_node(self):
        # "X" is a hub
        returned_three1 = self.G.connected_component_with_node("X")
        nxt.assert_graphs_equal(returned_three1, self.expected_three1)

        # "beta" is not a hub
        returned_three2 = self.G.connected_component_with_node("beta")
        nxt.assert_graphs_equal(returned_three2, self.expected_three2)

        # "A" is a hub
        returned_four = self.G.connected_component_with_node("A")
        nxt.assert_graphs_equal(returned_four, self.expected_four)
Пример #47
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)
Пример #48
0
 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)
Пример #49
0
 def test_from_edgelist_multi_attr_incl_target(self):
     Gtrue = nx.Graph([('E', 'C', {0: 'C', 'b': 'E', 'weight': 10}),
                       ('B', 'A', {0: 'B', 'b': 'A', 'weight': 7}),
                       ('A', 'D', {0: 'A', 'b': 'D', 'weight': 4})])
     G = nx.from_pandas_edgelist(self.df, 0, 'b', [0, 'b', 'weight'])
     assert_graphs_equal(G, Gtrue)
Пример #50
0
 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)
Пример #51
0
 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)
Пример #52
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_is_instance(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)

        # Serialize this "pydot.Dot" instance to a temporary file in dot format.
        fname = tempfile.mktemp()
        assert_true(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_equal(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_equal(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_equal(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)