/
test_graph_tools.py
317 lines (260 loc) · 10.6 KB
/
test_graph_tools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
"""
Tests for graph_tools.py
"""
import numpy as np
from numpy.testing import assert_array_equal, assert_raises, assert_
from quantecon import DiGraph, random_tournament_graph
def list_of_array_equal(s, t):
"""
Compare two lists of ndarrays
s, t: lists of numpy.ndarrays
"""
assert_(len(s) == len(t))
all(assert_array_equal(x, y) for x, y in zip(s, t))
class Graphs:
"""Setup graphs for the tests"""
def __init__(self):
self.strongly_connected_graph_dicts = []
self.not_strongly_connected_graph_dicts = []
graph_dict = {
'A': np.array([[1, 0], [0, 1]]),
'strongly_connected_components':
[np.array([0]), np.array([1])],
'sink_strongly_connected_components':
[np.array([0]), np.array([1])],
'is_strongly_connected': False,
}
self.not_strongly_connected_graph_dicts.append(graph_dict)
graph_dict = {
'A': np.array([[1, 0, 0], [1, 0, 1], [0, 0, 1]]),
'strongly_connected_components':
[np.array([0]), np.array([1]), np.array([2])],
'sink_strongly_connected_components':
[np.array([0]), np.array([2])],
'is_strongly_connected': False,
}
self.not_strongly_connected_graph_dicts.append(graph_dict)
graph_dict = {
'A': np.array([[1, 1], [1, 1]]),
'strongly_connected_components': [np.arange(2)],
'sink_strongly_connected_components': [np.arange(2)],
'is_strongly_connected': True,
'period': 1,
'is_aperiodic': True,
'cyclic_components': [np.arange(2)],
}
self.strongly_connected_graph_dicts.append(graph_dict)
graph_dict = {
'A': np.array([[0, 1], [1, 0]]),
'strongly_connected_components': [np.arange(2)],
'sink_strongly_connected_components': [np.arange(2)],
'is_strongly_connected': True,
'period': 2,
'is_aperiodic': False,
'cyclic_components': [np.array([0]), np.array([1])],
}
self.strongly_connected_graph_dicts.append(graph_dict)
graph_dict = {
'A': np.array([[0, 1, 0, 0],
[0, 0, 1, 0],
[1, 0, 0, 1],
[0, 0, 1, 0]]),
'strongly_connected_components': [np.arange(4)],
'sink_strongly_connected_components': [np.arange(4)],
'is_strongly_connected': True,
'period': 1,
'is_aperiodic': True,
'cyclic_components': [np.arange(4)],
}
self.strongly_connected_graph_dicts.append(graph_dict)
# Weighted graph
graph_dict = {
'A': np.array([[0, 0.5], [2, 0]]),
'weighted': True,
'strongly_connected_components': [np.arange(2)],
'sink_strongly_connected_components': [np.arange(2)],
'is_strongly_connected': True,
'period': 2,
'is_aperiodic': False,
'cyclic_components': [np.array([0]), np.array([1])],
}
self.strongly_connected_graph_dicts.append(graph_dict)
# Degenrate graph with no edge
graph_dict = {
'A': np.array([[0]]),
'strongly_connected_components': [np.arange(1)],
'sink_strongly_connected_components': [np.arange(1)],
'is_strongly_connected': True,
'period': 1,
'is_aperiodic': True,
'cyclic_components': [np.array([0])],
}
self.strongly_connected_graph_dicts.append(graph_dict)
# Degenrate graph with self loop
graph_dict = {
'A': np.array([[1]]),
'strongly_connected_components': [np.arange(1)],
'sink_strongly_connected_components': [np.arange(1)],
'is_strongly_connected': True,
'period': 1,
'is_aperiodic': True,
'cyclic_components': [np.array([0])],
}
self.strongly_connected_graph_dicts.append(graph_dict)
self.graph_dicts = \
self.strongly_connected_graph_dicts + \
self.not_strongly_connected_graph_dicts
class TestDiGraph:
"""Test the methods in Digraph"""
def setup_method(self):
"""Setup Digraph instances"""
self.graphs = Graphs()
for graph_dict in self.graphs.graph_dicts:
try:
weighted = graph_dict['weighted']
except:
weighted = False
graph_dict['g'] = DiGraph(graph_dict['A'], weighted=weighted)
def test_strongly_connected_components(self):
for graph_dict in self.graphs.graph_dicts:
list_of_array_equal(
sorted(graph_dict['g'].strongly_connected_components,
key=lambda x: x[0]),
sorted(graph_dict['strongly_connected_components'],
key=lambda x: x[0])
)
def test_num_strongly_connected_components(self):
for graph_dict in self.graphs.graph_dicts:
assert_(graph_dict['g'].num_strongly_connected_components ==
len(graph_dict['strongly_connected_components']))
def test_sink_strongly_connected_components(self):
for graph_dict in self.graphs.graph_dicts:
list_of_array_equal(
sorted(graph_dict['g'].sink_strongly_connected_components,
key=lambda x: x[0]),
sorted(graph_dict['sink_strongly_connected_components'],
key=lambda x: x[0])
)
def test_num_sink_strongly_connected_components(self):
for graph_dict in self.graphs.graph_dicts:
assert_(graph_dict['g'].num_sink_strongly_connected_components ==
len(graph_dict['sink_strongly_connected_components']))
def test_is_strongly_connected(self):
for graph_dict in self.graphs.graph_dicts:
assert_(graph_dict['g'].is_strongly_connected ==
graph_dict['is_strongly_connected'])
def test_period(self):
for graph_dict in self.graphs.graph_dicts:
try:
assert_(graph_dict['g'].period == graph_dict['period'])
except NotImplementedError:
assert_(not graph_dict['g'].is_strongly_connected)
def test_is_aperiodic(self):
for graph_dict in self.graphs.graph_dicts:
try:
assert_(graph_dict['g'].is_aperiodic ==
graph_dict['is_aperiodic'])
except NotImplementedError:
assert_(not graph_dict['g'].is_strongly_connected)
def test_cyclic_components(self):
for graph_dict in self.graphs.graph_dicts:
try:
list_of_array_equal(
sorted(graph_dict['g'].cyclic_components,
key=lambda x: x[0]),
sorted(graph_dict['cyclic_components'],
key=lambda x: x[0])
)
except NotImplementedError:
assert_(not graph_dict['g'].is_strongly_connected)
def test_subgraph():
adj_matrix = [[0, 1, 0], [0, 0, 1], [1, 0, 0]]
g = DiGraph(adj_matrix)
nodes = [1, 2]
subgraph_adj_matrix = [[False, True], [False, False]]
assert_array_equal(
g.subgraph(nodes).csgraph.toarray(),
subgraph_adj_matrix
)
def test_subgraph_weighted():
adj_matrix = np.arange(3**2).reshape(3, 3)
g = DiGraph(adj_matrix, weighted=True)
nodes = [0, 1]
subgraph_adj_matrix = [[0, 1], [3, 4]]
assert_array_equal(
g.subgraph(nodes).csgraph.toarray(),
subgraph_adj_matrix
)
def test_node_labels_connected_components():
adj_matrix = [[1, 0, 0], [1, 0, 0], [0, 0, 1]]
node_labels = np.array(['a', 'b', 'c'])
g = DiGraph(adj_matrix, node_labels=node_labels)
sccs = [[0], [1], [2]]
sink_sccs = [[0], [2]]
properties = ['strongly_connected_components',
'sink_strongly_connected_components']
suffix = '_indices'
for prop0, components_ind in zip(properties, [sccs, sink_sccs]):
for return_indices in [True, False]:
if return_indices:
components = components_ind
prop = prop0 + suffix
else:
components = [node_labels[i] for i in components_ind]
prop = prop0
list_of_array_equal(
sorted(getattr(g, prop), key=lambda x: x[0]),
sorted(components, key=lambda x: x[0])
)
def test_node_labels_cyclic_components():
adj_matrix = [[0, 1], [1, 0]]
node_labels = np.array(['a', 'b'])
g = DiGraph(adj_matrix, node_labels=node_labels)
cyclic_components = [[0], [1]]
properties = ['cyclic_components']
suffix = '_indices'
for prop0, components_ind in zip(properties, [cyclic_components]):
for return_indices in [True, False]:
if return_indices:
components = components_ind
prop = prop0 + suffix
else:
components = [node_labels[i] for i in components_ind]
prop = prop0
list_of_array_equal(
sorted(getattr(g, prop), key=lambda x: x[0]),
sorted(components, key=lambda x: x[0])
)
def test_node_labels_subgraph():
adj_matrix = [[0, 1, 0], [0, 0, 1], [1, 0, 0]]
node_labels = np.array(['a', 'b', 'c'])
g = DiGraph(adj_matrix, node_labels=node_labels)
nodes = [1, 2]
assert_array_equal(
g.subgraph(nodes).node_labels,
node_labels[nodes]
)
def test_raises_value_error_non_sym():
"""Test with non symmetric input"""
assert_raises(ValueError, DiGraph, np.array([[0.4, 0.6]]))
def test_raises_non_homogeneous_node_labels():
adj_matrix = [[1, 0], [0, 1]]
node_labels = [(0, 1), 2]
assert_raises(ValueError, DiGraph, adj_matrix, node_labels=node_labels)
class TestRandomTournamentGraph:
def setup_method(self):
n = 5
g = random_tournament_graph(n)
self.adj_matrix = g.csgraph.toarray()
self.eye_bool = np.eye(n, dtype=bool)
def test_diagonal(self):
# Test no self loop
assert_(not self.adj_matrix[self.eye_bool].any())
def test_off_diagonal(self):
# Test for each pair of distinct nodes to have exactly one edge
assert_((self.adj_matrix ^ self.adj_matrix.T)[~self.eye_bool].all())
def test_random_tournament_graph_seed():
n = 7
seed = 1234
graphs = [random_tournament_graph(n, random_state=seed) for i in range(2)]
assert_array_equal(*[g.csgraph.toarray() for g in graphs])