-
Notifications
You must be signed in to change notification settings - Fork 7
/
program.py
321 lines (269 loc) · 10.6 KB
/
program.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
import os
import sys
from type_system import Type, PolymorphicType, PrimitiveType, Arrow, List, UnknownType
from cons_list import index
from itertools import combinations_with_replacement
# dictionary { number of environment : value }
# environment: a cons list
# list = None | (value, list)
# probability: a dictionary {(G.__hash(), S) : probability}
# such that P.probability[S] is the probability that P is generated
# from the non-terminal S when the underlying PCFG is G.
# make sure hash is deterministic
hashseed = os.getenv('PYTHONHASHSEED')
if not hashseed:
os.environ['PYTHONHASHSEED'] = '0'
os.execv(sys.executable, [sys.executable] + sys.argv)
class Program:
"""
Object that represents a program: a lambda term with basic primitives
"""
def __eq__(self, other):
return (
isinstance(self, Program)
and isinstance(other, Program)
and self.type.__eq__(other.type)
and self.typeless_eq(other)
)
def typeless_eq(self, other):
b = isinstance(self, Program) and isinstance(other, Program)
b2 = (
isinstance(self, Variable)
and isinstance(other, Variable)
and self.variable == other.variable
)
b2 = b2 or (
isinstance(self, Function)
and isinstance(other, Function)
and self.function.typeless_eq(other.function)
and len(self.arguments) == len(other.arguments)
and all(
[
x.typeless_eq(y)
for x, y in zip(self.arguments, other.arguments)
]
)
)
b2 = b2 or (
isinstance(self, Lambda)
and isinstance(other, Lambda)
and self.body.typeless_eq(other.body)
)
b2 = b2 or (
isinstance(self, BasicPrimitive)
and isinstance(other, BasicPrimitive)
and self.primitive == other.primitive
)
b2 = b2 or (
isinstance(self, New)
and isinstance(other, New)
and (self.body).typeless_eq(other.body)
)
return b and b2
def __gt__(self, other):
True
def __lt__(self, other):
False
def __ge__(self, other):
True
def __le__(self, other):
False
def __hash__(self):
return self.hash
def is_constant(self):
return True
def derive_with_constants(self, constants):
return self
def make_all_constant_variations(self, constants_list):
n_constants = self.count_constants()
if n_constants == 0:
return [self]
all_possibilities = combinations_with_replacement(constants_list, n_constants)
return [self.derive_with_constants(list(possibility)) for possibility in all_possibilities]
def count_constants(self):
return 0
class Variable(Program):
def __init__(self, variable, type_=UnknownType(), probability={}):
# assert isinstance(variable, int)
self.variable = variable
# assert isinstance(type_, Type)
self.type = type_
self.hash = variable
self.probability = probability
self.evaluation = {}
def __repr__(self):
return "var" + format(self.variable)
def eval(self, dsl, environment, i):
if i in self.evaluation:
# logging.debug('Already evaluated')
return self.evaluation[i]
# logging.debug('Not yet evaluated')
try:
result = index(environment, self.variable)
self.evaluation[i] = result
return result
except (AttributeError, IndexError, ValueError, OverflowError, TypeError):
self.evaluation[i] = None
return None
def eval_naive(self, dsl, environment):
try:
result = index(environment, self.variable)
return result
except (AttributeError, IndexError, ValueError, OverflowError, TypeError):
return None
def is_constant(self):
return False
class Function(Program):
def __init__(self, function, arguments, type_=UnknownType(), probability={}):
# assert isinstance(function, Program)
self.function = function
# assert isinstance(arguments, list)
self.arguments = arguments
self.type = type_
self.hash = hash(tuple([arg.hash for arg in self.arguments] + [self.function.hash]))
self.probability = probability
self.evaluation = {}
def __repr__(self):
if len(self.arguments) == 0:
return format(self.function)
else:
s = "(" + format(self.function)
for arg in self.arguments:
s += " " + format(arg)
return s + ")"
def eval(self, dsl, environment, i):
if i in self.evaluation:
return self.evaluation[i]
try:
if len(self.arguments) == 0:
return self.function.eval(dsl, environment, i)
else:
evaluated_arguments = []
for j in range(len(self.arguments)):
e = self.arguments[j].eval(dsl, environment, i)
evaluated_arguments.append(e)
result = self.function.eval(dsl, environment, i)
for evaluated_arg in evaluated_arguments:
result = result(evaluated_arg)
self.evaluation[i] = result
return result
except (AttributeError, IndexError, ValueError, OverflowError, TypeError):
self.evaluation[i] = None
return None
def eval_naive(self, dsl, environment):
try:
if len(self.arguments) == 0:
return self.function.eval_naive(dsl, environment)
else:
evaluated_arguments = []
for j in range(len(self.arguments)):
e = self.arguments[j].eval_naive(dsl, environment)
evaluated_arguments.append(e)
result = self.function.eval_naive(dsl, environment)
for evaluated_arg in evaluated_arguments:
result = result(evaluated_arg)
return result
except (AttributeError, IndexError, ValueError, OverflowError, TypeError):
return None
def is_constant(self):
return all([self.function.is_constant()] + [arg.is_constant() for arg in self.arguments])
def count_constants(self):
return self.function.count_constants() + sum([arg.count_constants() for arg in self.arguments])
def derive_with_constants(self, constants):
return Function(self.function.derive_with_constants(constants), [argument.derive_with_constants(constants) for argument in self.arguments], self.type, self.probability)
class Lambda(Program):
def __init__(self, body, type_=UnknownType(), probability={}):
# assert isinstance(body, Program)
self.body = body
# assert isinstance(type_, Type)
self.type = type_
self.hash = hash(94135 + body.hash)
self.probability = probability
self.evaluation = {}
def __repr__(self):
s = "(lambda " + format(self.body) + ")"
return s
def eval(self, dsl, environment, i):
if i in self.evaluation:
# logging.debug('Already evaluated')
return self.evaluation[i]
# logging.debug('Not yet evaluated')
try:
result = lambda x: self.body.eval(dsl, (x, environment), i)
self.evaluation[i] = result
return result
except (AttributeError, IndexError, ValueError, OverflowError, TypeError):
self.evaluation[i] = None
return None
def eval_naive(self, dsl, environment):
try:
result = lambda x: self.body.eval_naive(dsl, (x, environment))
return result
except (AttributeError, IndexError, ValueError, OverflowError, TypeError):
return None
class BasicPrimitive(Program):
def __init__(self, primitive, type_=UnknownType(), probability={}, constant_evaluation=None):
# assert isinstance(primitive, str)
self.primitive = primitive
# assert isinstance(type_, Type)
self.type = type_
self.is_a_constant = not isinstance(type_, Arrow) and primitive.startswith("constant")
self.constant_evaluation = constant_evaluation
self.hash = hash(primitive) + self.type.hash
self.probability = probability
self.evaluation = {}
def __repr__(self):
"""
representation without type
"""
if self.is_a_constant and self.constant_evaluation:
return format(self.constant_evaluation)
return format(self.primitive)
def eval(self, dsl, environment, i):
if self.is_a_constant and self.constant_evaluation:
return self.constant_evaluation
return dsl.semantics[self.primitive]
def eval_naive(self, dsl, environment):
if self.is_a_constant and self.constant_evaluation:
return self.constant_evaluation
return dsl.semantics[self.primitive]
def count_constants(self):
return 1 if self.is_a_constant else 0
def derive_with_constants(self, constants):
if self.is_a_constant:
return BasicPrimitive(self.primitive, self.type, self.probability, constants.pop())
else:
return self
class New(Program):
def __init__(self, body, type_=UnknownType(), probability={}):
self.body = body
self.type = type_
self.hash = hash(783712 + body.hash) + type_.hash
self.probability = probability
self.evaluation = {}
def __repr__(self):
return format(self.body)
def eval(self, dsl, environment, i):
if i in self.evaluation:
# logging.debug('Already evaluated')
return self.evaluation[i]
# logging.debug('Not yet evaluated')
try:
result = self.body.eval(dsl, environment, i)
self.evaluation[i] = result
return result
except (AttributeError, IndexError, ValueError, OverflowError, TypeError):
self.evaluation[i] = None
return None
def eval_naive(self, dsl, environment):
try:
result = self.body.eval_naive(dsl, environment)
return result
except (AttributeError, IndexError, ValueError, OverflowError, TypeError):
return None
def is_constant(self):
return self.body.is_constant()
def count_constants(self):
return self.body.count_constants()
def derive_with_constants(self, constants):
return New(self.body.derive_with_constants(constants), self.type, self.probability)