-
Notifications
You must be signed in to change notification settings - Fork 6
/
tests.py
338 lines (279 loc) · 12.3 KB
/
tests.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import itertools
import math
import numpy as np
import os
import scipy.stats as stats
import shutil
import tempfile
import unittest
import networkx as nx
from nose.tools import *
# tempdir for tests that require writing.
TMPDIR = None
def assert_distribution(f, mean, std, p=.1):
vals = [ ]
for N in [10, 20, 50, 100, 500]:
while len(vals) < N:
vals.append(f())
#print vals
smean, sstd = np.mean(vals), np.std(vals)
if sstd == 0:
sstd = 1e-6
t = (mean - smean) / float(sstd / math.sqrt(len(vals)))
t = -abs(t)
print t, mean, smean, sstd
p1 = stats.t.cdf(t, len(vals)-1)
assert p1 == abs(p1)
p2 = 2*p1
print "p:", p2
if p2 > p:
print "passed with N=%s"%N
return True # test passed
raise AssertionError("Test failed, %s!=%s(std=%s) (%s !< %s) with %s samples"%(mean, smean, sstd, p, p2, N))
def test_assert_dist():
assert_distribution(stats.norm(0).rvs, 0, 1)
def assert_compnents(g, n=1):
n_ccs = nx.number_connected_components(g)
if n != n_ccs:
raise AssertionError("Number of connected components wrong: %s!=%s (%s)"%(
n, n_ccs, [len(cc) for cc in ccs]))
def test():
f = lambda : 1
assert_distribution(f, 1, 0)
import bm
def assert_all_managed(bm):
"""Check each pair of nodes and make sure that its link is managed.
Iterate through all pairs of nodes, and for all managers of the
benchmark object, make sure that exactly one manager claims to be
managing its link."""
for a, b in itertools.combinations(bm.g.nodes_iter(), 2):
found = False
managed_by = [mgr.manages(a, b) for mgr in bm.managers]
# True sums to one, False to zero. Each node should be
# managed by exactly one manager.
if sum(managed_by) != 1:
raise AssertionError('Nodes %s and %s are not managed (%s)'%(
a, b, managed_by))
def test_all_managed():
assert_all_managed(bm.get_model('StdGrow' ))
assert_all_managed(bm.get_model('StdMerge'))
assert_all_managed(bm.get_model('StdMixed'))
assert_all_managed(bm.get_model('StdGrow' , q=8))
assert_all_managed(bm.get_model('StdMerge', q=8))
assert_all_managed(bm.get_model('StdMixed', q=8))
class _TestRandom(unittest.TestCase):
model_name = None
def test_size(self):
M = bm.get_model(self.model_name)
assert len(M.t(0)) == 128
def test_all_managed(self):
assert_all_managed(bm.get_model(self.model_name))
assert_all_managed(bm.get_model(self.model_name, q=8))
assert_all_managed(bm.get_model(self.model_name, p_in=.5, p_out=.5))
def test_random(self):
#class Binom():
# def __init__(self, n, p):
# self.n, self.p = n, p
# def rvs(self):
# return int(round(self.n*self.p))
#import scipy.stats
#scipy.stats.binom = Binom
def getM():
return bm.get_model(self.model_name, p_in=.5, p_out=.5)
assert_distribution(lambda: getM().t(0).number_of_edges(),
128*127/2 * .5, std=None, p=.01)
def getM():
return bm.get_model(self.model_name, p_in=.6, p_out=.6)
assert_distribution(lambda: getM().t(0).number_of_edges(),
128*127/2 * .6, std=None, p=.01)
def getM():
return bm.get_model(self.model_name, p_in=.6, p_out=.6, q=8)
assert_distribution(lambda: getM().t(0).number_of_edges(),
256*255/2 * .6, std=None, p=.01)
def getM():
return bm.get_model(self.model_name, p_in=.6, p_out=.6)
assert_distribution(lambda: getM().t(50).number_of_edges(),
128*127/2 * .6, std=None, p=.01)
def getM():
return bm.get_model(self.model_name, p_in=.6, p_out=.6)
assert_distribution(lambda: getM().t(75).number_of_edges(),
128*127/2 * .6, std=None, p=.01)
def getM():
return bm.get_model(self.model_name, p_in=.6, p_out=.6)
assert_distribution(lambda: getM().t(25).number_of_edges(),
128*127/2 * .6, std=None, p=.01)
def test_random_k(self):
"""Test that specification of k= works in random cases."""
def getM():
return bm.get_model(self.model_name, p_in='k=20', p_out='k=20')
assert_distribution(lambda: getM().t(0).number_of_edges(),
128*(20*4) * .5, std=None, p=.01)
def getM():
return bm.get_model(self.model_name, p_in='k=15', p_out='k=15')
assert_distribution(lambda: getM().t(0).number_of_edges(),
(128*(15*4)) * .5, std=None, p=.01)
def getM():
return bm.get_model(self.model_name, p_in='k=15', p_out='ktot=45')
assert_distribution(lambda: getM().t(0).number_of_edges(),
(128*(15*4)) * .5, std=None, p=.01)
# cli
k = 20
def getM():
return bm.main_argv(['X', self.model_name, '--k_in=%d'%k, '--k_out=%d'%k])[0]
assert_distribution(lambda: getM().t(0).number_of_edges(),
(128*(k*4)) * .5, std=None, p=.01)
def getM():
return bm.main_argv(['X', self.model_name, '--k_in=%d'%k, '--k_out_tot=60'])[0]
assert_distribution(lambda: getM().t(0).number_of_edges(),
(128*(k*4)) * .5, std=None, p=.01)
def test_ccs(self):
M = bm.get_model(self.model_name, p_in=.5, p_out=0)
g = M.t(0)
assert_compnents(g, getattr(self, 'n_ccs', 4))
g = M.t(50)
assert_compnents(g, getattr(self, 'n_ccs', 4))
g = M.t(25)
assert_compnents(g, getattr(self, 'n_ccs_off', 4))
def test_num_comms(self):
M = bm.get_model(self.model_name, p_in=.5, p_out=0)
assert_equal(len(M.comms(0)), 4)
assert_equal(len(M.comms(25)), 4)
assert_equal(len(M.comms(50)), 4)
assert_equal(len(M.comms(85)), 4)
assert_equal(len(M.comms(100)), 4)
def test_output_bynode(self):
"""Ensure that main writes output: bynode"""
tmpdir = tempfile.mkdtemp(prefix='dynbench-', dir=TMPDIR)
try:
M = bm.main(argv=[bm.__file__, self.model_name,
tmpdir+'/output-1', # outdir
'--comm-format=bynode',
'--graph-format=edgelist',
])
assert_equal(len(os.listdir(tmpdir)), 202,
"202 files should be written (%s actual)"%len(os.listdir(tmpdir)))
comms = M.comms(2)
for line in open(tmpdir+'/output-1.t00002.comms'):
if line.startswith("#"): continue
n, c = line.split()
assert int(n) in comms[int(c)]
finally:
shutil.rmtree(tmpdir)
def test_output_oneline(self):
"""Ensure that main writes output: oneline"""
tmpdir = tempfile.mkdtemp(prefix='dynbench-', dir=TMPDIR)
try:
M = bm.main(argv=[bm.__file__, self.model_name,
tmpdir+'/output-1', # outdir
'--comm-format=oneline',
'--graph-format=tedgelist',
])
# 102 files written: 101 from communities and 1 for graph.
assert_equal(len(os.listdir(tmpdir)), 102,
"102 files should be written (%s actual)"%len(os.listdir(tmpdir)))
comms = M.comms(2)
for line in open(tmpdir+'/output-1.t00002.comms'):
if line.startswith('# label: '):
c = line[9:]
if line.startswith("#"): continue
nodes = line.split()
for n in nodes:
assert int(n) in comms[int(c)]
finally:
shutil.rmtree(tmpdir)
def test_seed(self):
"""Test that seeding does """
argv = [bm.__file__, self.model_name,
'--p_in=.5', '--p_out=.1']
import random
random.seed(10)
M1a, args = bm.main_argv(argv=argv+['--seed=51'])
random.seed(10)
M2, args = bm.main_argv(argv=argv+['--seed=965'])
random.seed(10)
M1b, args = bm.main_argv(argv=argv+['--seed=51'])
def edgeset(g):
print len(g), g.number_of_edges()
return set(frozenset((a, b)) for a,b in g.edges_iter())
assert_equal( edgeset(M1a.t(5)), edgeset(M1b.t(5)))
#assert_not_equal(edgeset(M2.t(5) ), edgeset(M1a.t(5)))
#assert_not_equal(edgeset(M2.t(5) ), edgeset(M1b.t(5)))
class TestMerge(_TestRandom):
model_name = 'StdMerge'
n_ccs = 3 # 3 conected components
n_ccs_off = 2
def test_ccs(self):
M = bm.get_model(self.model_name, p_in=.5, p_out=0)
g = M.t(0); assert_compnents(g, 3)
g = M.t(50); assert_compnents(g, 3)
g = M.t(25); assert_compnents(g, 2)
def test_num_comms(self):
M = bm.get_model(self.model_name, p_in=.5, p_out=0)
assert_equal(len(M.comms(0)), 3)
assert_equal(len(M.comms(25)), 4)
assert_equal(len(M.comms(50)), 3)
assert_equal(len(M.comms(75)), 4)
assert_equal(len(M.comms(100)), 3)
def test_det_limit(self):
Mnd = bm.get_model(self.model_name, p_in=.5, p_out=0,
opts=dict(no_det_limit=True))
Md = bm.get_model(self.model_name, p_in=.5, p_out=0,
opts=dict(no_det_limit=False))
# Test the command line no-det-limit option works.
argv = [bm.__file__, self.model_name, '/nonexistant', # outdir
'--graph-format=null','--comm-format=null']
Mnd2, args = bm.main_argv(argv=argv+['--no-det-limit'])
# Default shourd be detectability limit.
Md2, args = bm.main_argv(argv=argv)
assert_equal(len(Mnd.comms(0)), 3)
assert_equal(len(Mnd.comms(1)), 4)
assert_equal(len(Md.comms(0)), 3)
assert_equal(len(Md.comms(1)), 3)
assert_equal(len(Mnd2.comms(0)), 3)
assert_equal(len(Mnd2.comms(1)), 4)
assert_equal(len(Md2.comms(0)), 3)
assert_equal(len(Md2.comms(1)), 3)
#tmpdir = tempfile.mkdtemp(prefix='dynbench-')
#try:
def test_k(self):
"""Test that specification of k= works in specific cases."""
def getM():
return bm.get_model(self.model_name, p_in='k=10', p_out='k=5')
assert_distribution(lambda: getM().t(0).number_of_edges(),
(64*(10)+64*(5*3) + 64*(10*2)+64*(5*2) ) * .5, std=None, p=.01)
def test_Gnm(self):
M = bm.get_model(self.model_name, p_in=.5, p_out=.5,
opts=dict(Gnm=True))
edges = M.t(0).number_of_edges()
expected_edges = 128*127 / 2 * .5
assert_almost_equals(edges, expected_edges, delta=5)
class TestGrow(_TestRandom):
model_name = 'StdGrow'
def test_ccs(self):
M = bm.get_model(self.model_name, p_in=.5, p_out=0)
g = M.t(0); assert_compnents(g, 4)
g = M.t(50); assert_compnents(g, 4)
g = M.t(25); assert_compnents(g, 4)
def test_k(self):
"""Test that specification of k= works in specific cases."""
def getM():
return bm.get_model(self.model_name, p_in='k=20', p_out='k=5')
assert_distribution(lambda: getM().t(0).number_of_edges(),
(128*(20)+128*(5*3) ) * .5, std=None, p=.01)
p_in = 20./31 ; p_out=5./32
assert_distribution(lambda: getM().t(25).number_of_edges(),
(p_in*48*47 * 2 + p_in*16*15 * 2 + p_out*64*64*2 + p_out*16*48*2*2 ) * .5, std=None, p=.01)
class TestMixed(_TestRandom):
model_name = 'StdMixed'
def test_ccs(self):
M = bm.get_model(self.model_name, p_in=.5, p_out=0)
g = M.t(0); assert_compnents(g, 4)
g = M.t(50); assert_compnents(g, 3)
g = M.t(25); assert_compnents(g, 3)
def test_num_comms(self):
M = bm.get_model(self.model_name, p_in=.5, p_out=0)
assert_equal(len(M.comms(0)), 4)
assert_equal(len(M.comms(25)), 4)
assert_equal(len(M.comms(50)), 3)
assert_equal(len(M.comms(85)), 4)
assert_equal(len(M.comms(100)), 4)