-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_programs_from_string.py
More file actions
440 lines (403 loc) · 16.5 KB
/
Copy pathcreate_programs_from_string.py
File metadata and controls
440 lines (403 loc) · 16.5 KB
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
import re
from program import Function
# Define function to parse the DSL query
def parse_dsl_string_new(rule):
"""
Parse a DSL-like rule, extracting the predicate and arguments.
Supports:
AT_LEAST_1 1 IS_RED
AT_LEAST_1(1, IS_RED)
(AT_LEAST_1 1 IS_RED)
(AND (EVEN_1 IS_RED) (ODD_2 IS_BLOCK IS_PYRAMID))
EITHER_OR 1 2
"""
rule = rule.strip()
# Strip outer parentheses if they wrap the whole expression
if rule.startswith("(") and rule.endswith(")"):
depth = 0
for i, ch in enumerate(rule):
if ch == "(":
depth += 1
elif ch == ")":
depth -= 1
if depth == 0 and i != len(rule) - 1:
break
else:
rule = rule[1:-1].strip()
# Predicate is first token (until space or '(')
predicate = ""
rest = ""
for i, ch in enumerate(rule):
if ch.isspace() or ch == "(":
predicate = rule[:i]
rest = rule[i:]
break
else:
return rule, []
predicate = predicate.strip()
rest = rest.strip()
# Remove surrounding parentheses from arguments
if rest.startswith("(") and rest.endswith(")"):
rest = rest[1:-1].strip()
args = []
cur = ""
depth = 0
for ch in rest:
if ch in "([": depth += 1
elif ch in ")]": depth -= 1
if (ch == "," or ch.isspace()) and depth == 0:
if cur.strip():
args.append(cur.strip())
cur = ""
else:
cur += ch
if cur.strip():
args.append(cur.strip())
return predicate, args
# Define function to parse the DSL query
def parse_dsl_string(rule):
"""
Parse a DSL-like rule, extracting the predicate and arguments.
Example input: "at_least(yellow, pyramid, 1, Structure)"
"""
rule = rule.strip()
# --- Case 1: Lisp-style, e.g. (AND (AT_LEAST_1 1 IS_PYRAMID) ...)
if rule.startswith("(") and rule.endswith(")"):
# Strip outer parentheses
inner = rule[1:-1].strip()
else:
inner = rule
# First token is predicate
tokens = inner.split(maxsplit=1)
if len(tokens) == 1:
return tokens[0], []
predicate, rest = tokens
# Split rest into top-level arguments
args = []
paren_depth = 0
cur = ""
for ch in rest:
if ch == "(":
paren_depth += 1
cur += ch
elif ch == ")":
paren_depth -= 1
cur += ch
elif ch.isspace() and paren_depth == 0:
if cur.strip():
args.append(cur.strip())
cur = ""
else:
cur += ch
if cur.strip():
args.append(cur.strip())
return predicate, args
# Example function to convert the Prolog query into DSL semantics
def convert_string_to_dsl(rule_string, cfg) -> Function:
predicate, args = parse_dsl_string(rule_string)
if predicate == 'ALL_THREE_SHAPES':
return Function(cfg.lookup['ALL_THREE_SHAPES'], [])
if predicate == 'ALL_THREE_COLORS':
return Function(cfg.lookup['ALL_THREE_COLORS'], [])
if predicate == 'AT_LEAST_2':
if len(args) == 3: # AT_LEAST with color, shape, and count
count, pred1, pred2 = args
count = int(count) # Convert count to integer
# Create Function with valid Program arguments
return Function(cfg.lookup['AT_LEAST_2'], [
cfg.lookup[f'constant_{count}'],
Function(cfg.lookup[pred1], []),
Function(cfg.lookup[pred2], []),
])
else:
raise ValueError(f"Invalid number of arguments for at_least: {len(args)}")
if predicate == 'AT_LEAST_1':
if len(args) == 2: # at_least with color and count
count, pred1 = args
count = int(count) # Convert count to integer
return Function(cfg.lookup['AT_LEAST_1'], [
cfg.lookup[f'constant_{count}'],
Function(cfg.lookup[pred1], []),
])
else:
raise ValueError(f"Invalid number of arguments for at_least: {len(args)}")
if predicate == 'MAJORITY_2':
if len(args) == 2: # AT_LEAST with color, shape, and count
pred1, pred2 = args
# Create Function with valid Program arguments
return Function(cfg.lookup['MAJORITY_2'], [
Function(cfg.lookup[pred1], []),
Function(cfg.lookup[pred2], []),
])
else:
raise ValueError(f"Invalid number of arguments for at_least: {len(args)}")
if predicate == 'MAJORITY_1':
if len(args) == 1: # at_least with color and count
pred1 = args[0]
return Function(cfg.lookup['MAJORITY_1'], [
Function(cfg.lookup[pred1], []),
])
else:
raise ValueError(f"Invalid number of arguments for at_least: {len(args)}")
elif predicate == 'ALL_2':
if len(args) == 2: # AT_LEAST with color, shape, and count
pred1, pred2 = args
# Create Function with valid Program arguments
return Function(cfg.lookup['ALL_2'], [
Function(cfg.lookup[pred1], []),
Function(cfg.lookup[pred2], []),
])
else:
raise ValueError(f"Invalid number of arguments for at_least: {len(args)}")
elif predicate == 'ALL_1':
if len(args) == 1: # at_least with color and count
pred1 = args[0]
return Function(cfg.lookup['ALL_1'], [
Function(cfg.lookup[pred1], []),
])
else:
raise ValueError(f"Invalid number of arguments for at_least: {len(args)}")
elif predicate == 'SAME_AMOUNT':
if len(args) == 2:
pred1, pred2 = args
# Create Function with valid Program arguments
return Function(cfg.lookup['SAME_AMOUNT'], [
Function(cfg.lookup[pred1], []),
Function(cfg.lookup[pred2], []),
])
else:
raise ValueError(f"Invalid number of arguments for same_amount: {len(args)}")
elif predicate == 'EXACTLY_2':
if len(args) == 3: # exactly with color, shape, and count
count, pred1, pred2 = args
count = int(count) # Convert count to integer
# Create Function with valid Program arguments
return Function(cfg.lookup['EXACTLY_2'], [
cfg.lookup[f'constant_{count}'],
Function(cfg.lookup[pred1], []),
Function(cfg.lookup[pred2], []),
])
else:
raise ValueError(f"Invalid number of arguments for exactly: {len(args)}")
elif predicate == 'EXACTLY_1':
if len(args) == 2: # exactly with color and count
count, pred1 = args
count = int(count) # Convert count to integer
return Function(cfg.lookup['EXACTLY_1'], [
cfg.lookup[f'constant_{count}'],
Function(cfg.lookup[pred1], []),
])
else:
raise ValueError(f"Invalid number of arguments for exactly: {len(args)}")
elif predicate == 'ZERO_1':
if len(args) == 1:
pred = args[0]
# Create Function with valid Program arguments
return Function(cfg.lookup['ZERO_1'], [
Function(cfg.lookup[pred], []),
])
else:
raise ValueError(f"Invalid number of arguments for zero: {len(args)}")
elif predicate == 'ZERO_2':
if len(args) == 2:
pred1, pred2 = args
return Function(cfg.lookup['ZERO_2'], [
Function(cfg.lookup[pred1], []),
Function(cfg.lookup[pred2], []),
])
else:
raise ValueError(f"Invalid number of arguments for zero: {len(args)}")
elif predicate == 'EXCLUSIVELY':
if len(args) == 1: # exactly with color, shape, and count
pred = args[0]
# Create Function with valid Program arguments
return Function(cfg.lookup['EXCLUSIVELY'], [
Function(cfg.lookup[pred], []),
])
else:
raise ValueError(f"Invalid number of arguments for exclusively: {len(args)}")
elif predicate == 'AND':
# Handle 'and' predicate by combining two rules
subquery0 = args[0].strip('[]')
subquery1 = args[1].strip('[]')
rule1 = convert_string_to_dsl(subquery0, cfg)
rule2 = convert_string_to_dsl(subquery1, cfg)
return Function(cfg.lookup['AND'], [rule1, rule2])
elif predicate == 'OR':
# Handle 'or' predicate by combining two rules
subquery0 = args[0].strip('[]')
subquery1 = args[1].strip('[]')
rule1 = convert_string_to_dsl(subquery0, cfg)
rule2 = convert_string_to_dsl(subquery1, cfg)
return Function(cfg.lookup['OR'], [rule1, rule2])
elif predicate == 'EITHER_OR':
# Handle 'either_or' predicate
n1, n2 = args
n1 = int(n1)
n2 = int(n2)
return Function(cfg.lookup['EITHER_OR'], [cfg.lookup[f'constant_{n1}'], cfg.lookup[f'constant_{n2}']])
elif predicate == 'ODD':
# Handle 'odd_number_of' predicate
if len(args) == 0: # odd_number_of with no predicate
return Function(cfg.lookup['ODD'], [])
else:
raise ValueError(f"Invalid number of arguments for odd_number_of: {len(args)}")
elif predicate == 'ODD_1':
if len(args) == 1: # odd_number_of with one predicate
attr = args[0]
return Function(cfg.lookup['ODD_1'], [Function(cfg.lookup[attr], [])])
else:
raise ValueError(f"Invalid number of arguments for odd_number_of: {len(args)}")
elif predicate == 'ODD_2':
if len(args) == 2: # odd_number_of with two predicates (e.g. touching)
pred1, pred2 = args
return Function(cfg.lookup['ODD_2'], [
Function(cfg.lookup[pred1], []),
Function(cfg.lookup[pred2], []),
])
else:
raise ValueError(f"Invalid number of arguments for odd_number_of: {len(args)}")
elif predicate == 'EVEN':
if len(args) == 0: # even_number_of with no predicate
return Function(cfg.lookup['EVEN'], [])
else:
raise ValueError(f"Invalid number of arguments for even_number_of: {len(args)}")
elif predicate == 'EVEN_1':
if len(args) == 1: # even_number_of with one predicate
attr = args[0]
return Function(cfg.lookup['EVEN_1'], [Function(cfg.lookup[attr], [])])
else:
raise ValueError(f"Invalid number of arguments for even_number_of: {len(args)}")
elif predicate == 'EVEN_2':
if len(args) == 2: # even_number_of with two predicates (e.g. touching)
pred1, pred2 = args
return Function(cfg.lookup['EVEN_2'], [
Function(cfg.lookup[pred1], []),
Function(cfg.lookup[pred2], []),
])
else:
raise ValueError(f"Invalid number of arguments for even_number_of: {len(args)}")
elif predicate == 'AT_LEAST_INTERACTION':
if len(args) == 2:
count, interaction_args = args
interaction, args = parse_dsl_string(interaction_args)
pred1, pred2 = args
count = int(count) # Convert count to integer
return Function(cfg.lookup['AT_LEAST_INTERACTION'], [
cfg.lookup[f'constant_{count}'],
Function(cfg.lookup[interaction.upper()],
[
Function(cfg.lookup[pred1.upper()], []),
Function(cfg.lookup[pred2.upper()], []),
])
])
else:
raise ValueError(f"Invalid number of arguments for at_least_interaction: {len(args)}, {args}")
elif predicate == 'EXACTLY_INTERACTION':
if len(args) == 2:
count, interaction_args = args
interaction, args = parse_dsl_string(interaction_args)
pred1, pred2 = args
count = int(count) # Convert count to integer
return Function(cfg.lookup['EXACTLY_INTERACTION'], [
cfg.lookup[f'constant_{count}'],
Function(cfg.lookup[interaction.upper()],
[
Function(cfg.lookup[pred1.upper()], []),
Function(cfg.lookup[pred2.upper()], []),
])
])
else:
raise ValueError(f"Invalid number of arguments for exactly_interaction: {len(args)}")
elif predicate == 'ODD_INTERACTION':
if len(args) == 1:
interaction, args = parse_dsl_string(args[0])
pred1, pred2 = args
return Function(cfg.lookup['ODD_INTERACTION'], [
Function(cfg.lookup[interaction.upper()],
[
Function(cfg.lookup[pred1.upper()], []),
Function(cfg.lookup[pred2.upper()], []),
])
])
else:
raise ValueError(f"Invalid number of arguments for odd_number_of_interaction: {len(args)}")
elif predicate == 'EVEN_INTERACTION':
# Handle 'even_number_of_interaction' predicate
if len(args) == 1:
interaction, args = parse_dsl_string(args[0])
pred1, pred2 = args
return Function(cfg.lookup['EVEN_INTERACTION'], [
Function(cfg.lookup[interaction.upper()],
[
Function(cfg.lookup[pred1.upper()], []),
Function(cfg.lookup[pred2.upper()], []),
])
])
else:
raise ValueError(f"Invalid number of arguments for even_number_of_interaction: {len(args)}")
elif predicate == 'MAJORITY_INTERACTION':
# Handle 'even_number_of_interaction' predicate
if len(args) == 1:
interaction, args = parse_dsl_string(args[0])
pred1, pred2 = args
return Function(cfg.lookup['MAJORITY_INTERACTION'], [
Function(cfg.lookup[interaction.upper()],
[
Function(cfg.lookup[pred1.upper()], []),
Function(cfg.lookup[pred2.upper()], []),
])
])
else:
raise ValueError(f"Invalid number of arguments for majority_interaction: {len(args)}")
elif predicate == 'MORE_THAN':
# Handle 'more_than' predicate
pred1, pred2 = args
return Function(cfg.lookup['MORE_THAN'], [
Function(cfg.lookup[pred1.upper()], []),
Function(cfg.lookup[pred2.upper()], []),
])
elif predicate == 'MORE_OR_EQUAL_THAN':
# Handle 'more_than' predicate
pred1, pred2 = args
return Function(cfg.lookup['MORE_OR_EQUAL_THAN'], [
Function(cfg.lookup[pred1.upper()], []),
Function(cfg.lookup[pred2.upper()], []),
])
elif predicate == 'EITHER':
# Handle 'either' predicate
n1, n2 = args
n1 = int(n1)
n2 = int(n2)
return Function(cfg.lookup['EITHER'], [
cfg.lookup[f'constant_{n1}'],
cfg.lookup[f'constant_{n2}']
])
elif predicate == 'LENGTH':
# Handle 'either' predicate
n = args
n1 = int(n[0])
return Function(cfg.lookup['LENGTH'], [
cfg.lookup[f'constant_{n1}']
])
else:
raise ValueError(f"Unsupported predicate: {predicate}")
# zendo_dsl = dsl.DSL(zendo.semantics, zendo.primitive_types, None)
# type_request = Arrow(List(zendo.PIECE), BOOL)
# cfg = zendo_dsl.DSL_to_CFG(
# type_request, max_program_depth=5)
# # Example Prolog queries
# prolog_query1 = "(AT_LEAST_1 3 IS_RED)"
# prolog_query2 = "(AND (AT_LEAST_1 1 IS_PYRAMID) (AT_LEAST_1 3 IS_RED))"
# prolog_query3 = "(AND (AT_LEAST_1 1 IS_PYRAMID) (OR (AT_LEAST_1 1 IS_WEDGE) (AT_LEAST_INTERACTION 1 (ON_TOP_OF IS_BLOCK IS_BLOCK))))"
# prolog_query4 = "(AND (EXACTLY_1 1 IS_PYRAMID) (AT_LEAST_1 3 IS_RED))"
# # Convert them to DSL
# converted_query1 = convert_string_to_dsl(prolog_query1, cfg)
# converted_query2 = convert_string_to_dsl(prolog_query2, cfg)
# converted_query3 = convert_string_to_dsl(prolog_query3, cfg)
# converted_query4 = convert_string_to_dsl(prolog_query4, cfg)
# # Print the results
# print("Converted Query 1:", converted_query1)
# print("Converted Query 2:", converted_query2)
# print("Converted Query 3:", converted_query3)
# print("Converted Query 4:", converted_query4)