-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathunit_tests.py
419 lines (358 loc) · 14.8 KB
/
unit_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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
import logging
import unittest
import random
from math import sqrt
from scipy.stats import chisquare
import dsl as dsl
from DSL.deepcoder import *
from Algorithms.heap_search import heap_search
from Algorithms.a_star import a_star
from Algorithms.sqrt_sampling import sqrt_sampling, sqrt_sampling_with_sbsur
from Algorithms.threshold_search import bounded_threshold
from program_as_list import evaluation_from_compressed
class TestSum(unittest.TestCase):
def test_programs(self):
"""
Checks the evaluation of programs
"""
p1 = BasicPrimitive("MAP")
p2 = BasicPrimitive("MAP", type_=PolymorphicType(name="test"))
# checking whether they represent the same programs and same types
self.assertTrue(str(p1) == str(p2))
self.assertTrue(p1.typeless_eq(p2))
self.assertFalse(p1.__eq__(p2))
self.assertFalse(id(p1) == id(p2))
semantics = {
"+1": lambda x: x + 1,
"MAP": lambda f: lambda l: list(map(f, l)),
}
primitive_types = {
"+1": Arrow(INT, INT),
"MAP": Arrow(Arrow(t0, t1), Arrow(List(t0), List(t1))),
}
toy_DSL = dsl.DSL(semantics, primitive_types)
p0 = Function(BasicPrimitive("+1"), [Variable(0)])
env = (2, None)
self.assertTrue(p0.eval(toy_DSL, env, 0) == 3)
p1 = Function(BasicPrimitive("MAP"), [BasicPrimitive("+1"), Variable(0)])
env = ([2, 4], None)
self.assertTrue(p1.eval(toy_DSL, env, 0) == [3, 5])
def test_construction_CFG(self):
"""
Checks the construction of a CFG from a DSL
"""
t0 = PolymorphicType("t0")
t1 = PolymorphicType("t1")
semantics = {
"RANGE": (),
"HEAD": (),
"SUCC": (),
"MAP": (),
}
primitive_types = {
"HEAD": Arrow(List(INT), INT),
"RANGE": Arrow(INT, List(INT)),
"SUCC": Arrow(INT, INT),
"MAP": Arrow(Arrow(t0, t1), Arrow(List(t0), List(t1))),
}
toy_DSL = dsl.DSL(semantics, primitive_types)
type_request = Arrow(List(INT), List(INT))
toy_CFG = toy_DSL.DSL_to_CFG(type_request)
self.assertTrue(len(toy_CFG.rules) == 14)
self.assertTrue(len(toy_CFG.rules[toy_CFG.start]) == 3)
def test_construction_PCFG1(self):
"""
Checks the construction of a PCFG from a DSL
"""
t0 = PolymorphicType("t0")
t1 = PolymorphicType("t1")
semantics = {
"RANGE": (),
"HEAD": (),
"TAIL": (),
"SUCC": (),
"PRED": (),
"MAP": (),
}
primitive_types = {
"HEAD": Arrow(List(INT), INT),
"TAIL": Arrow(List(INT), INT),
"RANGE": Arrow(INT, List(INT)),
"SUCC": Arrow(INT, INT),
"PRED": Arrow(INT, INT),
"MAP": Arrow(Arrow(t0, t1), Arrow(List(t0), List(t1))),
}
toy_DSL = dsl.DSL(semantics, primitive_types)
type_request = Arrow(List(INT), List(INT))
toy_PCFG = toy_DSL.DSL_to_Uniform_PCFG(type_request)
# checks that all non-terminal are productive
for S in toy_PCFG.rules:
assert len(toy_PCFG.rules[S]) > 0
s = sum(w for (_, w) in toy_PCFG.rules[S].values())
for P in toy_PCFG.rules[S]:
args_P, w = toy_PCFG.rules[S][P]
assert w > 0
toy_PCFG.rules[S][P] = args_P, w / s
for arg in args_P:
assert arg in toy_PCFG.rules
max_program = Function(
BasicPrimitive("MAP"),
[
BasicPrimitive("HEAD"),
Function(BasicPrimitive("MAP"), [BasicPrimitive("RANGE"), Variable(0)]),
],
)
self.assertTrue(
toy_PCFG.max_probability[toy_PCFG.start].typeless_eq(max_program)
)
for S in toy_PCFG.rules:
max_program = toy_PCFG.max_probability[S]
self.assertTrue(
max_program.probability[(toy_PCFG.__hash__(), S)]
== toy_PCFG.probability_program(S, max_program)
)
def test_construction_PCFG2(self):
"""
Checks the construction of a PCFG from a DSL
"""
deepcoder = dsl.DSL(semantics, primitive_types)
type_request = Arrow(List(INT), List(INT))
deepcoder_PCFG = deepcoder.DSL_to_Random_PCFG(type_request)
for S in deepcoder_PCFG.rules:
max_program = deepcoder_PCFG.max_probability[S]
self.assertTrue(
deepcoder_PCFG.max_probability[S].probability[
(deepcoder_PCFG.__hash__(), S)
]
== deepcoder_PCFG.probability_program(S, max_program)
)
for P in deepcoder_PCFG.rules[S]:
max_program = deepcoder_PCFG.max_probability[(S, P)]
self.assertTrue(
deepcoder_PCFG.max_probability[(S, P)].probability[
(deepcoder_PCFG.__hash__(), S)
]
== deepcoder_PCFG.probability_program(S, max_program)
)
def test_completeness_heap_search(self):
"""
Check if heap_search does not miss any program and if it outputs programs in decreasing order.
"""
N = 10_000 # number of programs to be generated by heap search
K = 1000 # number of programs to be sampled from the PCFG
deepcoder = dsl.DSL(semantics, primitive_types)
type_request = Arrow(List(INT), List(INT))
deepcoder_PCFG = deepcoder.DSL_to_Random_PCFG(type_request, alpha=0.7)
gen_heap_search = heap_search(deepcoder_PCFG)
gen_sampling = deepcoder_PCFG.sampling()
seen_sampling = set()
seen_heaps = set()
current_probability = 1
for i in range(N):
program = next(gen_heap_search)
new_probability = program.probability[
(deepcoder_PCFG.__hash__(), deepcoder_PCFG.start)
]
self.assertTrue(
program.probability[(deepcoder_PCFG.__hash__(), deepcoder_PCFG.start)]
== deepcoder_PCFG.probability_program(deepcoder_PCFG.start, program)
)
self.assertLessEqual(new_probability, current_probability)
current_probability = new_probability
seen_heaps.add(str(program))
min_proba = current_probability
while len(seen_sampling) < K:
program = next(gen_sampling)
if (
deepcoder_PCFG.probability_program(deepcoder_PCFG.start, program)
>= min_proba
):
seen_sampling.add(str(program))
diff = seen_sampling - seen_heaps
self.assertEqual(0, len(diff))
def test_completeness_a_star(self):
"""
Check if a_star does not miss any program and if it outputs programs in decreasing order.
"""
N = 10_000 # number of programs to be generated by heap search
K = 1000 # number of programs to be sampled from the PCFG
deepcoder = dsl.DSL(semantics, primitive_types)
type_request = Arrow(List(INT), List(INT))
deepcoder_PCFG = deepcoder.DSL_to_Random_PCFG(type_request, alpha=0.7)
gen_a_star = a_star(deepcoder_PCFG)
gen_sampling = deepcoder_PCFG.sampling()
seen_sampling = set()
seen_astar = set()
current_probability = 1
for i in range(N):
program = next(gen_a_star)
program = reconstruct_from_compressed(program, type_request.returns())
new_probability = deepcoder_PCFG.probability_program(
deepcoder_PCFG.start, program
)
self.assertLessEqual(new_probability, current_probability + 10e-15)
current_probability = new_probability
seen_astar.add(str(program))
min_proba = current_probability
while len(seen_sampling) < K:
program = next(gen_sampling)
if (
deepcoder_PCFG.probability_program(deepcoder_PCFG.start, program)
>= min_proba
):
seen_sampling.add(str(program))
diff = seen_sampling - seen_astar
self.assertEqual(0, len(diff))
def test_threshold_search(self):
"""
Check if threshold search does not miss any program and if it outputs programs above the given threshold
"""
deepcoder = dsl.DSL(semantics, primitive_types)
type_request = Arrow(List(INT), List(INT))
deepcoder_PCFG = deepcoder.DSL_to_Random_PCFG(type_request, alpha=0.7)
threshold = 0.00001
gen_threshold = bounded_threshold(deepcoder_PCFG, threshold)
seen_threshold = set()
while True:
try:
program = next(gen_threshold)
program = reconstruct_from_compressed(program, type_request.returns())
proba_program = deepcoder_PCFG.probability_program(
deepcoder_PCFG.start, program
)
self.assertLessEqual(threshold, proba_program)
seen_threshold.add(
str(program)
) # check if the program is above threshold
except StopIteration:
break
K = len(seen_threshold) // 5
gen_sampling = deepcoder_PCFG.sampling()
seen_sampling = set()
while len(seen_sampling) < K:
program = next(gen_sampling)
proba_t = deepcoder_PCFG.probability_program(deepcoder_PCFG.start, program)
if proba_t >= threshold:
seen_sampling.add(str(program))
diff = seen_sampling - seen_threshold
self.assertEqual(0, len(diff))
def test_sampling(self):
"""
Check if the sampling algorithm samples according to the correct probabilities using a chi_square test
"""
K = 20_000 # number of samples from the L-th first programs
L = 50 # we test the probabilities of the first L programs are ok
alpha = 0.05 # threshold to reject the "H0 hypothesis"
deepcoder = dsl.DSL(semantics, primitive_types)
type_request = Arrow(List(INT), List(INT))
deepcoder_PCFG = deepcoder.DSL_to_Random_PCFG(type_request, alpha=0.7)
gen_heap_search = heap_search(
deepcoder_PCFG
) # to generate the L first programs
gen_sampling = deepcoder_PCFG.sampling() # generator for sampling
count = {}
for _ in range(L):
program = next(gen_heap_search)
count[str(program)] = [
deepcoder_PCFG.probability_program(deepcoder_PCFG.start, program),
0,
] # expected frequencies versus observed frequencies
normalisation_factor = sum(count[program][0] for program in count)
for program in count:
count[program][0] *= K / normalisation_factor
i = 0
while i < K:
# if (100 * i // K) != (100 * (i + 1) // K):
# print(100 * (i + 1) // K, " %")
program = next(gen_sampling)
program_hashed = str(program)
if program_hashed in count:
count[program_hashed][1] += 1
i += 1
f_exp = []
f_obs = []
for p in count:
f_exp.append(count[p][0])
f_obs.append(count[p][1])
chisq, p_value = chisquare(f_obs, f_exp=f_exp)
self.assertLessEqual(alpha, p_value)
def test_sqrt_sampling(self):
"""
Check if sqrt_sampling algorithm samples according to the correct probabilities
"""
K = 1_000_000 # number of samples from the L-th first programs
L = 50 # we test the probabilities of the first L programs are ok
deepcoder = dsl.DSL(semantics, primitive_types)
type_request = Arrow(List(INT), List(INT))
deepcoder_PCFG = deepcoder.DSL_to_Random_PCFG(type_request, alpha=0.6)
gen_heap_search = heap_search(
deepcoder_PCFG
) # to generate the L first programs
gen_sqrt_sampling = sqrt_sampling(deepcoder_PCFG) # generator for sqrt sampling
count = {}
for _ in range(L):
program = next(gen_heap_search)
count[str(program)] = [
K
* sqrt(
deepcoder_PCFG.probability_program(deepcoder_PCFG.start, program)
),
0,
]
i = 0
while i < K:
program = next(gen_sqrt_sampling)
program_hashed = str(program)
if program_hashed in count:
count[program_hashed][1] += 1
i += 1
ratios = []
for p in count:
ratios.append(count[p][1] / count[p][0])
random_ratios = random.sample(ratios, 5)
for r in random_ratios:
self.assertAlmostEqual(ratios[0], r, 1)
def test_completesness_sqrt_sampling_with_sbsur(self):
"""
Check if sqrt_sampling_with_sbsur algorithm does not miss any program.
"""
try:
import sbsur
except ImportError:
return
n = 10_0000
deepcoder = dsl.DSL(semantics, primitive_types)
type_request = Arrow(List(INT), List(INT))
r = type_request.returns()
deepcoder_PCFG = deepcoder.DSL_to_Random_PCFG(type_request, alpha=0.6)
gen_sqrt_sampling = sqrt_sampling_with_sbsur(deepcoder_PCFG) # generator for sqrt sampling
seen_programs = set()
for program in gen_sqrt_sampling:
prog = reconstruct_from_compressed(program, r)
self.assertNotIn(str(prog), seen_programs)
seen_programs.add(str(prog))
if len(seen_programs) > n:
break
def test_evaluation_from_compressed(self):
"""
Check if evaluation_from_compressed evaluates correctly the programs
"""
N = 20_000 # we test against the first N programs
deepcoder = dsl.DSL(semantics, primitive_types)
type_request = Arrow(List(INT), List(INT))
deepcoder_PCFG = deepcoder.DSL_to_Random_PCFG(type_request, alpha=0.6)
gen_a_star = a_star(deepcoder_PCFG)
environment = ([2, 3, 1], ([1, 4], None))
for i in range(N):
program_compressed = next(gen_a_star)
program = reconstruct_from_compressed(
program_compressed, type_request.returns()
)
program_as_list = []
eval_from_compressed = evaluation_from_compressed(
program_compressed, deepcoder, environment, type_request.returns()
)
eval_from_program = program.eval_naive(deepcoder, environment)
self.assertEqual(eval_from_compressed, eval_from_program)
if __name__ == "__main__":
unittest.main(verbosity=2)