Statistics
| Branch: | Revision:

iof-tools / networkxMiCe / networkx-master / networkx / tests / test_convert_scipy.py @ 5cef0f13

History | View | Annotate | Download (9.35 KB)

1
from nose import SkipTest
2
from nose.tools import assert_raises, assert_true, raises
3

    
4
import networkx as nx
5
from networkx.testing import assert_graphs_equal
6
from networkx.generators.classic import barbell_graph, cycle_graph, path_graph
7

    
8

    
9
class TestConvertNumpy(object):
10
    @classmethod
11
    def setupClass(cls):
12
        global np, sp, sparse, np_assert_equal
13
        try:
14
            import numpy as np
15
            import scipy as sp
16
            import scipy.sparse as sparse
17
            np_assert_equal = np.testing.assert_equal
18
        except ImportError:
19
            raise SkipTest('SciPy sparse library not available.')
20

    
21
    def __init__(self):
22
        self.G1 = barbell_graph(10, 3)
23
        self.G2 = cycle_graph(10, create_using=nx.DiGraph)
24

    
25
        self.G3 = self.create_weighted(nx.Graph())
26
        self.G4 = self.create_weighted(nx.DiGraph())
27

    
28
    def test_exceptions(self):
29
        class G(object):
30
            format = None
31

    
32
        assert_raises(nx.NetworkXError, nx.to_networkx_graph, G)
33

    
34
    def create_weighted(self, G):
35
        g = cycle_graph(4)
36
        e = list(g.edges())
37
        source = [u for u, v in e]
38
        dest = [v for u, v in e]
39
        weight = [s + 10 for s in source]
40
        ex = zip(source, dest, weight)
41
        G.add_weighted_edges_from(ex)
42
        return G
43

    
44
    def assert_isomorphic(self, G1, G2):
45
        assert_true(nx.is_isomorphic(G1, G2))
46

    
47
    def identity_conversion(self, G, A, create_using):
48
        GG = nx.from_scipy_sparse_matrix(A, create_using=create_using)
49
        self.assert_isomorphic(G, GG)
50

    
51
        GW = nx.to_networkx_graph(A, create_using=create_using)
52
        self.assert_isomorphic(G, GW)
53

    
54
        GI = nx.empty_graph(0, create_using).__class__(A)
55
        self.assert_isomorphic(G, GI)
56

    
57
        ACSR = A.tocsr()
58
        GI = nx.empty_graph(0, create_using).__class__(ACSR)
59
        self.assert_isomorphic(G, GI)
60

    
61
        ACOO = A.tocoo()
62
        GI = nx.empty_graph(0, create_using).__class__(ACOO)
63
        self.assert_isomorphic(G, GI)
64

    
65
        ACSC = A.tocsc()
66
        GI = nx.empty_graph(0, create_using).__class__(ACSC)
67
        self.assert_isomorphic(G, GI)
68

    
69
        AD = A.todense()
70
        GI = nx.empty_graph(0, create_using).__class__(AD)
71
        self.assert_isomorphic(G, GI)
72

    
73
        AA = A.toarray()
74
        GI = nx.empty_graph(0, create_using).__class__(AA)
75
        self.assert_isomorphic(G, GI)
76

    
77
    def test_shape(self):
78
        "Conversion from non-square sparse array."
79
        A = sp.sparse.lil_matrix([[1, 2, 3], [4, 5, 6]])
80
        assert_raises(nx.NetworkXError, nx.from_scipy_sparse_matrix, A)
81

    
82
    def test_identity_graph_matrix(self):
83
        "Conversion from graph to sparse matrix to graph."
84
        A = nx.to_scipy_sparse_matrix(self.G1)
85
        self.identity_conversion(self.G1, A, nx.Graph())
86

    
87
    def test_identity_digraph_matrix(self):
88
        "Conversion from digraph to sparse matrix to digraph."
89
        A = nx.to_scipy_sparse_matrix(self.G2)
90
        self.identity_conversion(self.G2, A, nx.DiGraph())
91

    
92
    def test_identity_weighted_graph_matrix(self):
93
        """Conversion from weighted graph to sparse matrix to weighted graph."""
94
        A = nx.to_scipy_sparse_matrix(self.G3)
95
        self.identity_conversion(self.G3, A, nx.Graph())
96

    
97
    def test_identity_weighted_digraph_matrix(self):
98
        """Conversion from weighted digraph to sparse matrix to weighted digraph."""
99
        A = nx.to_scipy_sparse_matrix(self.G4)
100
        self.identity_conversion(self.G4, A, nx.DiGraph())
101

    
102
    def test_nodelist(self):
103
        """Conversion from graph to sparse matrix to graph with nodelist."""
104
        P4 = path_graph(4)
105
        P3 = path_graph(3)
106
        nodelist = list(P3.nodes())
107
        A = nx.to_scipy_sparse_matrix(P4, nodelist=nodelist)
108
        GA = nx.Graph(A)
109
        self.assert_isomorphic(GA, P3)
110

    
111
        # Make nodelist ambiguous by containing duplicates.
112
        nodelist += [nodelist[0]]
113
        assert_raises(nx.NetworkXError, nx.to_numpy_matrix, P3,
114
                      nodelist=nodelist)
115

    
116
    def test_weight_keyword(self):
117
        WP4 = nx.Graph()
118
        WP4.add_edges_from((n, n + 1, dict(weight=0.5, other=0.3))
119
                           for n in range(3))
120
        P4 = path_graph(4)
121
        A = nx.to_scipy_sparse_matrix(P4)
122
        np_assert_equal(A.todense(),
123
                        nx.to_scipy_sparse_matrix(WP4, weight=None).todense())
124
        np_assert_equal(0.5 * A.todense(),
125
                        nx.to_scipy_sparse_matrix(WP4).todense())
126
        np_assert_equal(0.3 * A.todense(),
127
                        nx.to_scipy_sparse_matrix(WP4, weight='other').todense())
128

    
129
    def test_format_keyword(self):
130
        WP4 = nx.Graph()
131
        WP4.add_edges_from((n, n + 1, dict(weight=0.5, other=0.3))
132
                           for n in range(3))
133
        P4 = path_graph(4)
134
        A = nx.to_scipy_sparse_matrix(P4, format='csr')
135
        np_assert_equal(A.todense(),
136
                        nx.to_scipy_sparse_matrix(WP4, weight=None).todense())
137

    
138
        A = nx.to_scipy_sparse_matrix(P4, format='csc')
139
        np_assert_equal(A.todense(),
140
                        nx.to_scipy_sparse_matrix(WP4, weight=None).todense())
141

    
142
        A = nx.to_scipy_sparse_matrix(P4, format='coo')
143
        np_assert_equal(A.todense(),
144
                        nx.to_scipy_sparse_matrix(WP4, weight=None).todense())
145

    
146
        A = nx.to_scipy_sparse_matrix(P4, format='bsr')
147
        np_assert_equal(A.todense(),
148
                        nx.to_scipy_sparse_matrix(WP4, weight=None).todense())
149

    
150
        A = nx.to_scipy_sparse_matrix(P4, format='lil')
151
        np_assert_equal(A.todense(),
152
                        nx.to_scipy_sparse_matrix(WP4, weight=None).todense())
153

    
154
        A = nx.to_scipy_sparse_matrix(P4, format='dia')
155
        np_assert_equal(A.todense(),
156
                        nx.to_scipy_sparse_matrix(WP4, weight=None).todense())
157

    
158
        A = nx.to_scipy_sparse_matrix(P4, format='dok')
159
        np_assert_equal(A.todense(),
160
                        nx.to_scipy_sparse_matrix(WP4, weight=None).todense())
161

    
162
    @raises(nx.NetworkXError)
163
    def test_format_keyword_raise(self):
164
        WP4 = nx.Graph()
165
        WP4.add_edges_from((n, n + 1, dict(weight=0.5, other=0.3))
166
                           for n in range(3))
167
        P4 = path_graph(4)
168
        nx.to_scipy_sparse_matrix(P4, format='any_other')
169

    
170
    @raises(nx.NetworkXError)
171
    def test_null_raise(self):
172
        nx.to_scipy_sparse_matrix(nx.Graph())
173

    
174
    def test_empty(self):
175
        G = nx.Graph()
176
        G.add_node(1)
177
        M = nx.to_scipy_sparse_matrix(G)
178
        np_assert_equal(M.todense(), np.matrix([[0]]))
179

    
180
    def test_ordering(self):
181
        G = nx.DiGraph()
182
        G.add_edge(1, 2)
183
        G.add_edge(2, 3)
184
        G.add_edge(3, 1)
185
        M = nx.to_scipy_sparse_matrix(G, nodelist=[3, 2, 1])
186
        np_assert_equal(M.todense(), np.matrix([[0, 0, 1], [1, 0, 0], [0, 1, 0]]))
187

    
188
    def test_selfloop_graph(self):
189
        G = nx.Graph([(1, 1)])
190
        M = nx.to_scipy_sparse_matrix(G)
191
        np_assert_equal(M.todense(), np.matrix([[1]]))
192

    
193
    def test_selfloop_digraph(self):
194
        G = nx.DiGraph([(1, 1)])
195
        M = nx.to_scipy_sparse_matrix(G)
196
        np_assert_equal(M.todense(), np.matrix([[1]]))
197

    
198
    def test_from_scipy_sparse_matrix_parallel_edges(self):
199
        """Tests that the :func:`networkx.from_scipy_sparse_matrix` function
200
        interprets integer weights as the number of parallel edges when
201
        creating a multigraph.
202

203
        """
204
        A = sparse.csr_matrix([[1, 1], [1, 2]])
205
        # First, with a simple graph, each integer entry in the adjacency
206
        # matrix is interpreted as the weight of a single edge in the graph.
207
        expected = nx.DiGraph()
208
        edges = [(0, 0), (0, 1), (1, 0)]
209
        expected.add_weighted_edges_from([(u, v, 1) for (u, v) in edges])
210
        expected.add_edge(1, 1, weight=2)
211
        actual = nx.from_scipy_sparse_matrix(A, parallel_edges=True,
212
                                             create_using=nx.DiGraph)
213
        assert_graphs_equal(actual, expected)
214
        actual = nx.from_scipy_sparse_matrix(A, parallel_edges=False,
215
                                             create_using=nx.DiGraph)
216
        assert_graphs_equal(actual, expected)
217
        # Now each integer entry in the adjacency matrix is interpreted as the
218
        # number of parallel edges in the graph if the appropriate keyword
219
        # argument is specified.
220
        edges = [(0, 0), (0, 1), (1, 0), (1, 1), (1, 1)]
221
        expected = nx.MultiDiGraph()
222
        expected.add_weighted_edges_from([(u, v, 1) for (u, v) in edges])
223
        actual = nx.from_scipy_sparse_matrix(A, parallel_edges=True,
224
                                             create_using=nx.MultiDiGraph)
225
        assert_graphs_equal(actual, expected)
226
        expected = nx.MultiDiGraph()
227
        expected.add_edges_from(set(edges), weight=1)
228
        # The sole self-loop (edge 0) on vertex 1 should have weight 2.
229
        expected[1][1][0]['weight'] = 2
230
        actual = nx.from_scipy_sparse_matrix(A, parallel_edges=False,
231
                                             create_using=nx.MultiDiGraph)
232
        assert_graphs_equal(actual, expected)
233

    
234
    def test_symmetric(self):
235
        """Tests that a symmetric matrix has edges added only once to an
236
        undirected multigraph when using
237
        :func:`networkx.from_scipy_sparse_matrix`.
238

239
        """
240
        A = sparse.csr_matrix([[0, 1], [1, 0]])
241
        G = nx.from_scipy_sparse_matrix(A, create_using=nx.MultiGraph)
242
        expected = nx.MultiGraph()
243
        expected.add_edge(0, 1, weight=1)
244
        assert_graphs_equal(G, expected)