-
Notifications
You must be signed in to change notification settings - Fork 6
/
API.py
159 lines (119 loc) · 4.71 KB
/
API.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
import torch
import time
class Solver:
def __init__(self, dsl):
self.dsl = dsl
pass
def _report(self, program):
l = self.loss(program)
if len(self.reportedSolutions) == 0 or self.reportedSolutions[-1].loss > l:
self.reportedSolutions.append(SearchResult(program, l, time.time() - self.startTime))
def infer(self, spec, loss, timeout):
"""
spec: specification of goal
loss: function from (spec, program) to real
timeout: maximum time to run solver, measured in seconds
returns: list of `SearchResult`s
Should take no longer than timeout seconds."""
self.reportedSolutions = []
self.startTime = time.time()
self.loss = lambda p: loss(spec, p)
with torch.no_grad():
self._infer(spec, loss, timeout)
self.loss = None # in case we need to serialize this object and loss is a lambda
return self.reportedSolutions
def _infer(self, spec, loss, timeout):
assert False, "not implemented"
class SearchResult:
def __init__(self, program, loss, time):
self.program = program
self.loss = loss
self.time = time
class ParseFailure(Exception):
"""Objects of type Program should throw this exception in their constructor if their arguments are bad"""
class DSL:
def __init__(self, operators, lexicon=None):
"""
operators: a list of classes that inherit from Program
lexicon: (optionally) a list of symbols in the serialization of programs built from those operators
"""
self.lexicon = lexicon
self.operators = operators
self.tokenToOperator = {o.token: o
for o in operators}
def __str__(self):
return "DSL({%s})"%(", ".join( f"{o.__name__} : {str(o.type)}"
for o in self.operators ))
def parseLine(self, tokens):
"""
Parses a serialized line of code into a Program object.
Returns None if the DSL cannot parse the serialized code.
"""
if len(tokens) == 0 or tokens[0] not in self.tokenToOperator: return None
f = self.tokenToOperator[tokens[0]]
ft = f.type
if ft.isArrow: # Expects arguments
# Make sure we have the right number of arguments
tokens = tokens[1:]
if len(tokens) != len(ft.arguments): return None
# Make sure that each token is an instance of the correct type
for token, argument_type in zip(tokens, ft.arguments):
if not argument_type.instance(token): return None
# Type checking succeeded - try building the object
try:
return f(*tokens)
except ParseFailure: return None
else: # Does not expect any arguments - just call the constructor with no arguments
if len(tokens) > 1: return None # got arguments when we were not expecting any
return f()
class Program:
# TODO: implement type property
def execute(self, context):
assert False, "not implemented"
def children(self):
assert False, "not implemented"
class Type():
@property
def isArrow(self): return False
@property
def isInteger(self): return False
@property
def isBase(self): return False
def returnType(self):
"""What this type indicates the expression should return. For arrows this is the right-hand side. Otherwise it is just the type."""
return self
class BaseType(Type):
def __init__(self, thing):
self.constructor = thing
def __str__(self):
return self.constructor.__name__
@property
def isBase(self): return False
def instance(self, x):
return isinstance(x, self.constructor)
class arrow(Type):
def __init__(self, *args):
assert len(args) > 1
for a in args:
assert isinstance(a, Type)
self.out = args[-1]
self.arguments = args[:-1]
def __str__(self):
return " -> ".join( str(t) for t in list(self.arguments) + [self.out] )
@property
def isArrow(self): return True
def instance(self, x):
assert False, "Cannot check whether a object is an instance of a arrow type"
def returnType(self): return self.out
class integer(Type):
def __init__(self,lower,upper):
assert type(lower) is int
assert type(upper) is int
self.upper = upper
self.lower = lower
def __str__(self):
return f"int({self.lower}, {self.upper})"
@property
def isInteger(self): return True
def instance(self, x):
return isinstance(x, int) and x >= self.lower and x <= self.upper