-
Notifications
You must be signed in to change notification settings - Fork 17
/
DSL.py
1177 lines (1053 loc) · 48.3 KB
/
DSL.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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from language import Rectangle,Circle,Line,AbsolutePoint,Sequence
from utilities import *
#from fastRender import fastRender
from render import render
import re
import itertools as iterationTools
import numpy as np
import random
class EvaluationError(Exception):
pass
def reflectPoint(rx,ry,px,py):
if rx != None: return (rx - px,py)
if ry != None: return (px,ry - py)
assert False
def reflect(x = None,y = None):
def reflector(stuff):
return stuff + [ o.reflect(x = x,y = y) for o in stuff ]
return reflector
def addFeatures(fs):
composite = {}
for f in fs:
for k in f:
composite[k] = composite.get(k,0) + f[k]
return composite
class AbstractionVariable():
def __init__(self,v): self.v = v
def __eq__(self,o): return isinstance(o,AbstractionVariable) and self.v == o.v
def __str__(self): return "__v__(%d)"%(self.v)
class Environment():
def __init__(self,b = []): self.bindings = b
def lookup(self,x):
for k,v in self.bindings:
if k == x: return v
return None
def extend(self,x,y = None):
if y == None: x,y = AbstractionVariable(len(self.bindings)),x
return Environment(self.bindings + [(x,y)]), x
def __str__(self):
return "Environment([%s])"%(", ".join([ "%s -> %s"%(k,v) for k,v in self.bindings ]))
def makeVariableWithValue(self,z):
for k,v in self.bindings:
if v == z: return k,self
e,v = self.extend(z)
return v,e
def abstractConstant(self,n,m):
if n == m: return (m,self)
return self.makeVariableWithValue((n,m))
def getTypes(self):
t = []
for _,(x,y) in self.bindings:
if isinstance(x,int):
assert isinstance(y,int)
t.append(int)
elif x in ['x','y']:
assert y in ['x','y']
t.append(str)
return t
def randomInstantiation(self):
b = []
for v,(x,y) in self.bindings:
if isinstance(x,int):
assert isinstance(y,int)
average = (x + y)/2.0
standardDeviation = (((x - average)**2 + (y - average)**2)/2.0)**(0.5)
z = int(np.random.normal(loc = average,
scale = standardDeviation))
if z == 0 and x != 0 and y != 0:
z = random.choice([-1,1])
b.append((v,z))
elif x in ['x','y']:
assert y in ['x','y']
b.append((v,random.choice(['x','y'])))
return Environment(b)
def firstInstantiation(self):
return Environment([(v,x) for v,(x,y) in self.bindings ])
def secondInstantiation(self):
return Environment([(v,y) for v,(x,y) in self.bindings ])
class EnumerationEnvironment():
def __init__(self, goal, progress, variableRanges):
self.variableRanges = variableRanges
self.goal = goal
self.progress = progress
self.difference = goal - progress
def introduceFreeVariable(self,fv):
e = dict(self.variableRanges)
e[fv] = None
return EnumerationEnvironment(self.goal, self.progress, e)
class AbstractionFailure(Exception):
pass
class LinearExpression():
def __init__(self, m,x,b):
self.m = m
self.x = x
self.b = b
if x == None: assert m == 0
if isinstance(m,int) and m == 0: assert x == None
def __str__(self):
if self.x == None: return str(self.b)
return '(%s*%s + %s)'%(self.m,self.x,self.b)
def pretty(self):
if self.m == 0: return str(self.b)
if self.b == 0:
return "%s * %s"%(self.m,self.x)
else:
return "%s * %s + %s"%(self.m,self.x,self.b)
def __eq__(self,o): return isinstance(o,LinearExpression) and self.m == o.m and self.x == o.x and self.b == o.b
def __ne__(self,o): return not (self == o)
def evaluate(self,e):
if self.x == None: return self.b
value = e.lookup(self.x)
if value == None: raise EvaluationError('Unbound variable')
return self.m*value + self.b
def freeVariables(self):
if x == None: return []
return [x]
def canonicalKey(self): return (self.m,self.x,self.b)
def canonical(self): return self
@staticmethod
def enumerate(freeVariables = [], maximumIntercept = 15, maximumSlope = 5):
for b in range(maximumIntercept):
yield LinearExpression(0,None,b)
for v in freeVariables:
for m in range(-maximumSlope,maximumSlope + 1):
if m != 0: yield LinearExpression(m,v,b)
def abstract(self,other,e):
if self.x != other.x: raise AbstractionFailure('')
def abstractNumber(n,m,e_):
if n == m: return (n,e_)
for k,(n_,m_) in e_.bindings:
if n_ == n and m_ == m: return (k,e_)
e_,newVariable = e_.extend((n,m))
return (newVariable,e_)
m,e = abstractNumber(self.m,other.m,e)
b,e = abstractNumber(self.b,other.b,e)
return LinearExpression(m,self.x,b),e
def substitute(self,e):
m = e.lookup(self.m)
if m == None: m = self.m
b = e.lookup(self.b)
if b == None: b = self.b
return LinearExpression(m,self.x,b)
def offset(self,o):
return LinearExpression(self.m,self.x,self.b+o)
class RelativeExpression():
orientations = {'n':'North',
'w':'West',
'e':'East',
's':'South'}
def __init__(self, index, orientation):
self.index = index
assert orientation in RelativeExpression.orientations.keys()
self.orientation = orientation
def __str__(self):
return '%s(%d)'%(RelativeExpression.orientations[self.orientation],self.index)
def pretty(self): return str(self)
def __eq__(self,o):
return isinstance(o,RelativeExpression) and o.index == self.index and o.orientation == self.orientation
def abstract(self,other,e):
index,e = e.abstractConstant(self.index, other.index)
orientation,e = e.abstractConstant(self.orientation, other.orientation)
return RelativeExpression(index, orientation),e
def substitute(self,e):
raise Exception('not implemented: relative expression substitution')
class Primitive():
def pretty(self):
arguments = self.arguments
if self.k == 'line':
arguments = arguments[:4] + ["arrow = %s"%arguments[4],"solid = %s"%arguments[5]]
p = '%s(%s)'%(self.k,",".join([ (a if isinstance(a,str) else a.pretty())
for a in arguments]))
return p.replace(',arrow',',\narrow')
def __init__(self, k, *arguments):
self.k = k
self.arguments = list(arguments)
def __str__(self): return "Primitive(%s)"%(", ".join(map(str,[self.k] + self.arguments)))
def hoistReflection(self):
return
yield
def evaluate(self,e): return set([self.evaluate_(e)])
def evaluate_(self,e):
if self.k == 'circle':
return Circle.absolute(self.arguments[0].evaluate(e),
self.arguments[1].evaluate(e))
if self.k == 'rectangle':
return Rectangle.absolute(self.arguments[0].evaluate(e),
self.arguments[1].evaluate(e),
self.arguments[2].evaluate(e),
self.arguments[3].evaluate(e))
if self.k == 'line':
arrow = self.arguments[4]
solid = self.arguments[5]
if isinstance(arrow,str): assert False
if isinstance(solid,str): assert False
return Line.absolute(self.arguments[0].evaluate(e),
self.arguments[1].evaluate(e),
self.arguments[2].evaluate(e),
self.arguments[3].evaluate(e),
arrow = arrow,
solid = solid)
raise Exception('unknown primitives when evaluating')
def fixStringParameters(self):
if self.k == 'line':
arguments = list(self.arguments)
arrow = self.arguments[4]
solid = self.arguments[5]
if isinstance(arrow,str): arguments[4] = 'True' in arrow
if isinstance(solid,str): arguments[5] = 'True' in solid
return Primitive(self.k, *arguments)
else: return self
def extrapolations(self): yield self
def explode(self):
return self
def features(self):
return {'primitives':1,
'lines':int('line' in self.k),
'rectangle':int('rectangle' in self.k),
'circles':int('circle' in self.k)}
def rewrites(self):
return
yield
def removeDeadCode(self): return self
def canonicalKey(self): return tuple([self.k] + [ a if isinstance(a,(str,bool)) else a.canonicalKey() for a in self.arguments ])
def canonical(self): return self
def mapExpression(self,l):
return Primitive(self.k, *[ (l(a) if isinstance(a,LinearExpression) else a) for a in self.arguments ])
@staticmethod
def enumerate(environment):
if any([isinstance(x,Circle) for x in environment.difference ]):
for x in LinearExpression.enumerate(environment.variableRanges.keys()):
for y in LinearExpression.enumerate(environment.variableRanges.keys()):
yield Primitive("circle",x,y)
def enumerateNeighbors(self,e):
return
yield
def walk(self):
yield self
def cost(self): return 1
def abstract(self,other,e):
if isinstance(other,Primitive) and self.k == other.k:
arguments = []
for p,q in zip(self.arguments, other.arguments):
if isinstance(p,LinearExpression):
assert isinstance(q,LinearExpression)
a,e = p.abstract(q,e)
arguments.append(a)
else: arguments.append(p)
return Primitive(self.k,*arguments),e
raise AbstractionFailure('different primitives')
def substitute(self,e):
return Primitive(self.k, *[ (a.substitute(e) if isinstance(a,LinearExpression) else a) for a in self.arguments ])
def depth(self): return 1
class Reflection():
def pretty(self):
return "reflect(%s = %s)\n%s"%(self.axis,self.coordinate,
indent(self.body.pretty()))
def __init__(self, axis, coordinate, body):
self.axis = axis
self.coordinate = coordinate
self.body = body
def removeDeadCode(self):
body = self.body.removeDeadCode()
return Reflection(self.axis, self.coordinate, body)
def evaluate(self,environment):
body = self.body.evaluate(environment)
return body | set([ x.reflect(self.axis,self.coordinate) for x in body ])
def fixStringParameters(self):
return Reflection(self.axis,
self.coordinate,
self.body.fixStringParameters())
@staticmethod
def enumerate(environment, maximumCoordinate = 16):
for c in range(maximumCoordinate):
yield Reflection('x', c, Block([]))
yield Reflection('y', c, Block([]))
def enumerateNeighbors(self,environment):
for n in self.body.enumerateNeighbors(environment):
yield Reflection(self.axis,self.coordinate,n)
def hoistReflection(self):
for j,p in enumerate(self.body.items):
if isinstance(p,Primitive):
newBlock = list(self.body.items)
del newBlock[j]
newBlock = Block(newBlock)
yield Block([p,Reflection(self.axis,self.coordinate,newBlock)])
def canonicalKey(self):
return (self.axis,self.coordinate,self.body.canonicalKey())
def canonical(self):
return Reflection(self.axis, self.coordinate, self.body.canonical())
def __str__(self):
return "Reflection(%s,%s,%s)"%(self.axis, self.coordinate,self.body)
def extrapolations(self):
for b in self.body.extrapolations():
yield Reflection(self.axis, self.coordinate, b)
def explode(self):
return Reflection(self.axis, self.coordinate, self.body.explode())
def features(self):
return addFeatures([{'reflections':1,
'reflectionsX':int('x' == self.axis),
'reflectionsY':int('y' == self.axis)},
self.body.features()])
def rewrites(self):
for b in self.body.rewrites():
yield Reflection(self.axis,self.coordinate,b)
def mapExpression(self,l):
return Reflection(self.axis, self.coordinate, self.body.mapExpression(l))
def walk(self):
yield self
for w in self.body.walk():
yield w
def cost(self):
return 1 + self.body.cost()
def abstract(self,other,e):
if not isinstance(other, Reflection): raise AbstractionFailure('abstracting a reflection with a not reflection')
if self.axis == other.axis: axis = self.axis
else: axis,e = e.makeVariableWithValue((self.axis,other.axis))
if self.coordinate == other.coordinate: coordinate = self.coordinate
else: coordinate,e = e.makeVariableWithValue((self.coordinate, other.coordinate))
body,e = self.body.abstract(other.body,e)
return Reflection(axis, coordinate, body),e
def substitute(self,e):
axis = e.lookup(self.axis)
if axis == None: axis = self.axis
coordinate = e.lookup(self.coordinate)
if coordinate == None: coordinate = self.coordinate
return Reflection(axis, coordinate, self.body.substitute(e))
def depth(self): return 1 + self.body.depth()
class Loop():
def pretty(self):
p = "for (%s < %s)\n"%(self.v,self.bound)
if self.boundary != None:
p += indent("if (%s > 0)\n%s\n\n"%(self.v,indent(self.boundary.pretty())))
p += "%s"%(indent(self.body.pretty()))
return p
def __init__(self, v, bound, body, boundary = None, lowerBound = 0):
self.v = v
self.bound = bound
self.body = body
self.boundary = boundary
self.lowerBound = lowerBound
def evaluate(self,environment):
accumulator = set([])
for j in range(self.lowerBound, self.bound.evaluate(environment)):
environmentp = environment.extend(self.v,j)[0]
if j > self.lowerBound and self.boundary != None:
accumulator|= self.boundary.evaluate(environmentp)
accumulator|= self.body.evaluate(environmentp)
return accumulator
def fixStringParameters(self):
return Loop(self.v, self.bound,
self.body.fixStringParameters(),
boundary = None if self.boundary is None else self.boundary.fixStringParameters(),
lowerBound=self.lowerBound)
def removeDeadCode(self):
body = self.body.removeDeadCode()
boundary = self.boundary.removeDeadCode() if self.boundary != None else None
if boundary != None and boundary.items == []: boundary = None
return Loop(self.v, self.bound, body, boundary = boundary, lowerBound = self.lowerBound)
def canonicalKey(self):
return (self.v,
self.bound.canonicalKey(),
self.body.canonicalKey(),
self.boundary.canonicalKey() if self.boundary else None,
self.lowerBound)
def canonical(self):
return Loop(self.v,self.bound.canonical(),self.body.canonical(),
self.boundary and self.boundary.canonical(),
self.lowerBound)
def hoistReflection(self):
for h in self.body.hoistReflection():
yield Loop(self.v,self.bound,h,boundary = self.boundary,lowerBound = self.lowerBound)
if self.boundary != None:
for h in self.boundary.hoistReflection():
yield Loop(self.v,self.bound,self.body,boundary = h,lowerBound = self.lowerBound)
def __str__(self):
if self.boundary != None:
return "Loop(%s, %s, %s, %s, boundary = %s)"%(self.v,self.lowerBound, self.bound,self.body,self.boundary)
return "Loop(%s, %s, %s, %s)"%(self.v,self.lowerBound, self.bound,self.body)
def extrapolations(self):
for b in self.body.extrapolations():
for boundary in ([None] if self.boundary == None else self.boundary.extrapolations()):
for ub,lb in [(1,0),(0,1),(1,1),(0,0)]:
yield Loop(self.v, self.bound.offset(ub), b,
lowerBound = self.lowerBound - lb,
boundary = boundary)
def explode(self):
shrapnel = [ Loop(self.v,self.bound,bodyExpression.explode(),lowerBound = self.lowerBound)
for bodyExpression in self.body.items ]
if self.boundary != None:
shrapnel += [ Loop(self.v,self.bound,Block([]),lowerBound = self.lowerBound,
boundary = bodyExpression.explode())
for bodyExpression in self.boundary.items ]
return Block(shrapnel)
def features(self):
f2 = int(str(self.bound) == '2')
f3 = int(str(self.bound) == '3')
f4 = int(str(self.bound) == '4')
return addFeatures([{'loops':1,
'2': f2,
'3': f3,
'4': f4,
'boundary': int(self.boundary != None),
'variableLoopBound': int(f2 == 0 and f3 == 0 and f4 == 0)},
self.body.features(),
self.boundary.features() if self.boundary != None else {}])
def rewrites(self):
for b in self.body.rewrites():
yield Loop(self.v, self.bound, b, self.boundary, self.lowerBound)
if self.boundary != None:
for b in self.boundary.rewrites():
yield Loop(self.v, self.bound, self.body, b, self.lowerBound)
def mergeWithOtherLoop(self,other):
assert self.v == other.v and self.lowerBound == other.lowerBound
boundary = self.boundary
if other.boundary != None:
if boundary == None: boundary = other.boundary
else: boundary = Block(self.boundary.items + other.boundary.items)
body = Block(self.body.items + other.body.items)
return Loop(self.v, self.bound, body, boundary, self.lowerBound)
def mergeWithOtherLoopDifferentBounds(self,other):
assert self.bound.b == other.bound.b + 1
assert self.v == other.v and self.lowerBound == other.lowerBound
assert other.boundary == None
boundary = other.body.mapExpression(lambda l: LinearExpression(l.m,l.x,l.b-l.m) if l.x == self.v else l).items
if self.boundary != None: boundary = boundary + self.boundary.items
return Loop(self.v, self.bound, self.body, Block(boundary), self.lowerBound)
def mapExpression(self,l):
return Loop(self.v, l(self.bound), self.body.mapExpression(l),
None if self.boundary == None else self.boundary.mapExpression(l),
self.lowerBound)
def walk(self):
yield self
for x in self.body.walk(): yield x
if self.boundary != None:
for x in self.boundary.walk(): yield x
def cost(self):
cost = self.body.cost()
if self.boundary != None:
cost += self.boundary.cost()
if self.bound.m == 0 and self.bound.b == 2: cost += 1
return cost + 1
def abstract(self,other,e):
if not isinstance(other,Loop) or self.v != other.v or ((other.boundary == None) != (self.boundary == None)):
raise AbstractionFailure('Loop abstraction')
assert self.lowerBound == 0 and other.lowerBound == 0
bound,e = self.bound.abstract(other.bound,e)
body,e = self.body.abstract(other.body,e)
if self.boundary == None: boundary = None
else: boundary,e = self.boundary.abstract(other.boundary,e)
return Loop(self.v,bound, body, boundary),e
def substitute(self,e):
return Loop(self.v,
self.bound.substitute(e),
self.body.substitute(e),
None if self.boundary == None else self.boundary.substitute(e),
self.lowerBound)
def depth(self): return 1 + max(self.body.depth(),
0 if self.boundary == None else self.boundary.depth())
@staticmethod
def enumerate(environment):
vs = ['i','j']
if len(environment.variableRanges) < 2:
v = vs[len(environment.variableRanges)]
for bound in LinearExpression.enumerate(environment.variableRanges.keys(),
maximumIntercept = 4,
maximumSlope = 2):
if bound.m == 0 and bound.b < 2: continue
yield Loop(v, bound, Block([]), boundary = None)#Block([]))
def enumerateNeighbors(self,environment):
environment = environment.introduceFreeVariable(self.v)
for body in self.body.enumerateNeighbors(environment):
yield Loop(self.v,self.bound,body,boundary = self.boundary)
if self.boundary != None:
for boundary in self.boundary.enumerateNeighbors(environment):
yield Loop(self.v,self.bound,self.body,boundary = boundary)
else:
yield Loop(self.v,self.bound,self.body,boundary = Block([]))
class Block():
def pretty(self): return "\n".join([x.pretty() for x in self.items ])
def convertToSequence(self):
e = Environment([])
return Sequence([x for p in self.items for x in p.evaluate(e) ])
def __init__(self, items): self.items = items
def __str__(self): return "Block([%s])"%(", ".join(map(str,self.items)))
def __repr__(self): return str(self)
def evaluate(self,environment):
accumulator = set([])
for x in self.items: accumulator|= x.evaluate(environment)
return accumulator
def canonicalKey(self): return tuple([ x.canonicalKey() for x in self.items ])
def canonical(self):
return Block(list(sorted((x.canonical() for x in self.items),
key = lambda y: y.canonicalKey())))
def extrapolations(self):
if self.items == []: yield self
else:
for e in self.items[0].extrapolations():
for s in Block(self.items[1:]).extrapolations():
yield Block([e] + s.items)
def explode(self):
return Block([ x.explode() for x in self.items ])
def features(self):
return addFeatures([ x.features() for x in self.items ])
def hoistReflection(self):
for j,x in enumerate(self.items):
for y in x.hoistReflection():
copy = list(self.items)
copy[j] = y
yield Block(copy)
def fixStringParameters(self):
return Block([x.fixStringParameters() for x in self.items ])
def fixReflections(self,target):
distance = self.convertToSequence() - target
if distance == 0: return self
candidates = [self] + list(self.hoistReflection())
sequences = [k.convertToSequence() for k in candidates ]
distances = [target - s for s in sequences ]
best = min(range(len(distances)),key = lambda k: distances[k])
if distances[best] == distance: return self
return candidates[best].fixReflections(target)
def removeDeadCode(self):
items = [ x.removeDeadCode() for x in self.items ]
keptItems = []
for x in items:
if isinstance(x,Reflection) and x.body.items != []: keptItems.append(x)
elif isinstance(x,Loop) and (x.body.items != [] or (x.boundary != None and x.boundary.items != [])):
keptItems.append(x)
elif isinstance(x,Primitive):
keptItems.append(x)
return Block(keptItems)
def rewriteUpToDepth(self,d):
rewrites = [[self]]
for _ in range(d):
rewrites.append([ r for b in rewrites[-1]
for r in b.rewrites() ])
return [ r for rs in rewrites for r in rs ]
def rewrites(self):
for j,x in enumerate(self.items):
for r in x.rewrites():
newItems = list(self.items)
newItems[j] = r
yield Block(newItems)
for j,x in enumerate(self.items):
for k,y in enumerate(self.items):
if not (j < k): continue
if isinstance(x,Loop) and isinstance(y,Loop):
if x.bound == y.bound and x.lowerBound == y.lowerBound:
newLoop = x.mergeWithOtherLoop(y)
newItems = list(self.items)
newItems[j] = newLoop
del newItems[k]
yield Block(newItems)
if x.bound.m == y.bound.m and x.bound.x == y.bound.x and abs(x.bound.b - y.bound.b) == 1:
# make it so that y is the one with fewer iterations
if x.bound.b < y.bound.b: x,y = y,x
if y.boundary != None: continue
newLoop = x.mergeWithOtherLoopDifferentBounds(y)
newItems = list(self.items)
newItems[j] = newLoop
del newItems[k]
yield Block(newItems)
if isinstance(x,Reflection) and isinstance(y,Reflection):
if (x.axis,x.coordinate) == (y.axis,y.coordinate):
newItems = list(self.items)
newItems[j] = Reflection(x.axis, x.coordinate, Block(x.body.items + y.body.items))
del newItems[k]
yield Block(newItems)
def mapExpression(self,l):
return Block([x.mapExpression(l) for x in self.items ])
def walk(self):
yield self
for x in self.items:
for y in x.walk():
yield y
def usedCoefficients(self):
xs = []
ys = []
for child in self.walk():
if isinstance(child,Primitive):
if child.k == 'circle':
xs.append(child.arguments[0].m)
ys.append(child.arguments[1].m)
if child.k == 'rectangle' or child.k == 'line':
xs.append(child.arguments[0].m)
ys.append(child.arguments[1].m)
xs.append(child.arguments[2].m)
ys.append(child.arguments[3].m)
return set([c for c in xs if c != 0 ]),set([c for c in ys if c != 0 ])
def usedReflections(self):
xs = []
ys = []
for child in self.walk():
if isinstance(child,Reflection):
if 'x' == child.axis:
xs.append(child.coordinate)
else:
ys.append(child.coordinate)
return set(xs),set(ys)
def cost(self): return sum([x.cost() for x in self.items ])
def totalCost(self):
# cost taking into account the used coefficients & used boundaries
c = self.cost()
xs,ys = self.usedCoefficients()
boundaryCount = 0
for x in self.walk():
if isinstance(x,Loop) and x.boundary != None: boundaryCount += 1
boundaryCount = 0
return 3*c + max(len(xs) - 1, 0) + max(len(ys) - 1, 0) + boundaryCount
def optimizeUsingRewrites(self,d = 4):
candidates = self.rewriteUpToDepth(d)
scoredCandidates = [ (c.totalCost(),c) for c in candidates ]
return min(scoredCandidates)
def abstract(self,other,e):
assert isinstance(other,Block)
# We need to try removing stuff from the blocks to make them the same length.
# For each way of removing stuff to make than the same length,
# we have to consider every permutation of the block elements.
# This is only efficient as long as the block bodies are small,
# which holds in practice.
for l in range(min(len(self.items),len(other.items)),0,-1):
for p in iterationTools.combinations(self.items,l):
for q in iterationTools.permutations(other.items,l):
try:
e_ = e
items = []
for x,y in zip(p,q):
a,e_ = x.abstract(y,e_)
items.append(a)
return Block(items),e_
except AbstractionFailure: pass
raise AbstractionFailure
def substitute(self,e):
return Block([x.substitute(e) for x in self.items ])
def usedLoops(self):
for x in self.walk():
if isinstance(x,Loop):
yield {'depth': {'i':0,'j':1}[x.v],
'coefficient': x.bound.m,
'variable': {'i':0,'j':1,None:None}[x.bound.x],
'intercept': x.bound.b}
def depth(self):
return max([x.depth() for x in self.items ] + [0])
def enumerateNeighbors(self, environment):
# todo: canonical form: [primitives, reflections, loops]
for l in Loop.enumerate(environment):
yield Block([l] + self.items)
for r in Reflection.enumerate(environment):
yield Block([r] + self.items)
for p in Primitive.enumerate(environment):
yield Block([p] + self.items)
for j,x in enumerate(self.items):
for n in x.enumerateNeighbors(environment):
yield Block(self.items[:j] + [n] + self.items[j+1:])
# return something that resembles a syntax tree, built using the above classes
def parseSketchOutput(output, environment = None, loopDepth = 0, coefficients = None):
commands = []
# variable bindings introduced by the sketch: we have to resolve them
environment = {} if environment == None else environment
# global coefficients for linear transformations
coefficients = {} if coefficients == None else coefficients
output = output.split('\n')
def getBlock(name, startingIndex, startingDepth = 0):
d = startingDepth
while d > -1:
if 'dummyStart' in output[startingIndex] and name in output[startingIndex]:
d += 1
elif 'dummyEnd' in output[startingIndex] and name in output[startingIndex]:
d -= 1
startingIndex += 1
return startingIndex
def getBoundary(startingIndex):
while True:
if 'dummyStartBoundary' in output[startingIndex]:
return getBlock('Boundary', startingIndex + 1)
if 'dummyStartLoop' in output[startingIndex]:
return None
if 'dummyEndLoop' in output[startingIndex]:
return None
startingIndex += 1
j = 0
while j < len(output):
l = output[j]
if 'void renderSpecification' in l: break
m = re.search('validate[X|Y]\((.*), (.*)\);',l)
if m:
environment[m.group(2)] = m.group(1)
j += 1
continue
m = re.search('int\[[0-9]\] coefficients([1|2]) = {([,0-9\-]+)};',l)
if m:
coefficients[int(m.group(1))] = map(int,m.group(2).split(","))
# apply the environment
for v in sorted(environment.keys(), key = lambda v: -len(v)):
l = l.replace(v,environment[v])
# Apply the coefficients
if 'coefficients' in l:
for k in coefficients:
for coefficientIndex,coefficientValue in enumerate(coefficients[k]):
pattern = '\(coefficients%s[^\[]*\[%d\]\)'%(k,coefficientIndex)
# print "Substituting the following pattern",pattern
# print "For the following value",coefficientValue
lp = re.sub(pattern, str(coefficientValue), l)
# if l != lp:
# print "changed it to",lp
l = lp
pattern = '\(\(\(shapeIdentity == 0\) && \(cx.* == (.+)\)\) && \(cy.* == (.+)\)\)'
m = re.search(pattern,l)
if m:
x = parseExpression(m.group(1))
y = parseExpression(m.group(2))
commands += [Primitive('circle',x,y)]
j += 1
continue
pattern = 'shapeIdentity == 1\) && \((.*) == lx1.*\)\) && \((.*) == ly1.*\)\) && \((.*) == lx2.*\)\) && \((.*) == ly2.*\)\) && \(([01]) == dashed\)\) && \(([01]) == arrow'
m = re.search(pattern,l)
if m:
if False:
print "Reading line!"
print l
for index in range(5): print "index",index,"\t",m.group(index),'\t',parseExpression(m.group(index))
commands += [Primitive('line',
parseExpression(m.group(1)),
parseExpression(m.group(2)),
parseExpression(m.group(3)),
parseExpression(m.group(4)),
# arrow
m.group(6) == '1',
# solid
m.group(5) == '0')]
j += 1
continue
pattern = '\(\(\(\(\(shapeIdentity == 2\) && \((.+) == rx1.*\)\) && \((.+) == ry1.*\)\) && \((.+) == rx2.*\)\) && \((.+) == ry2.*\)\)'
m = re.search(pattern,l)
if m:
# print m,m.group(1),m.group(2),m.group(3),m.group(4)
commands += [Primitive('rectangle',
parseExpression(m.group(1)),
parseExpression(m.group(2)),
parseExpression(m.group(3)),
parseExpression(m.group(4)))]
j += 1
continue
pattern = 'for\(int (.*) = 0; .* < (.*); .* = .* \+ 1\)'
m = re.search(pattern,l)
if m and (not ('reflectionIndex' in m.group(1))):
boundaryIndex = getBoundary(j + 1)
if boundaryIndex != None:
boundary = "\n".join(output[(j+1):boundaryIndex])
boundary = parseSketchOutput(boundary, environment, loopDepth + 1, coefficients)
j = boundaryIndex
else:
boundary = None
bodyIndex = getBlock('Loop', j+1)
body = "\n".join(output[(j+1):bodyIndex])
j = bodyIndex
bound = parseExpression(m.group(2))
body = parseSketchOutput(body, environment, loopDepth + 1, coefficients)
v = ['i','j'][loopDepth]
if v == 'j' and boundary != None and False:
print "INNERLOOP"
print '\n'.join(output)
print "ENDOFINNERLOOP"
commands += [Loop(v, bound, body, boundary)]
continue
pattern = 'dummyStartReflection\(([0-9]+), ([0-9]+)\)'
m = re.search(pattern,l)
if m:
bodyIndex = getBlock('Reflection', j+1)
body = "\n".join(output[(j+1):bodyIndex])
j = bodyIndex
x = int(m.group(1))
y = int(m.group(2))
axis = 'x' if y == 0 else 'y'
coordinate = max([x,y])
commands += [Reflection(axis, coordinate,
parseSketchOutput(body, environment, loopDepth, coefficients))]
j += 1
return Block(commands)
def parseExpression(e):
#print "parsing expression",e
try: return LinearExpression(0,None,int(e))
except:
factor = re.search('([\-0-9]+) \* ',e)
if factor != None: factor = int(factor.group(1))
else: # try negative number
factor = re.search('\(-\(([0-9]+)\)\) \* ',e)
if factor != None: factor = -int(factor.group(1))
offset = re.search(' \+ ([\-0-9]+)',e)
if offset != None: offset = int(offset.group(1))
variable = re.search('\[(\d)\]',e)
if variable != None: variable = ['i','j'][int(variable.group(1))]
if factor == None:
factor = 1
if offset == None: offset = 0
if variable == None:
print("FATAL: parsing expression: could not find variable.")
print e
print("^^^^")
assert False
#print "Parsed into:",LinearExpression(factor,variable,offset)
return LinearExpression(factor,variable,offset)
def renderEvaluation(s, exportTo = None):
parse = evaluate(eval(s))
x0 = min([x for l in parse.lines for x in l.usedXCoordinates() ])
y0 = min([y for l in parse.lines for y in l.usedYCoordinates() ])
x1 = max([x for l in parse.lines for x in l.usedXCoordinates() ])
y1 = max([y for l in parse.lines for y in l.usedYCoordinates() ])
render([parse.TikZ()],showImage = exportTo == None,exportTo = exportTo,canvas = (x1+1,y1+1), x0y0 = (x0 - 1,y0 - 1))
icingModelOutput = '''void render (int shapeIdentity, int cx, int cy, int lx1, int ly1, int lx2, int ly2, bit dashed, bit arrow, int rx1, int ry1, int rx2, int ry2, ref bit _out) implements renderSpecification/*tmpzqJj8W.sk:209*/
{
_out = 0;
assume (((shapeIdentity == 0) || (shapeIdentity == 1)) || (shapeIdentity == 2)): "Assume at tmpzqJj8W.sk:210"; //Assume at tmpzqJj8W.sk:210
assume (shapeIdentity != 2): "Assume at tmpzqJj8W.sk:212"; //Assume at tmpzqJj8W.sk:212
assume (!(dashed)): "Assume at tmpzqJj8W.sk:216"; //Assume at tmpzqJj8W.sk:216
assume (!(arrow)): "Assume at tmpzqJj8W.sk:217"; //Assume at tmpzqJj8W.sk:217
int[2] coefficients1 = {-3,28};
int[2] coefficients2 = {-3,24};
int[0] environment = {};
int[1] coefficients1_0 = coefficients1[0::1];
int[1] coefficients2_0 = coefficients2[0::1];
dummyStartLoop();
int loop_body_cost = 0;
bit _pac_sc_s15_s17 = 0;
for(int j = 0; j < 3; j = j + 1)/*Canonical*/
{
assert (j < 4); //Assert at tmpzqJj8W.sk:96 (1334757887901394789)
bit _pac_sc_s31 = _pac_sc_s15_s17;
if(!(_pac_sc_s15_s17))/*tmpzqJj8W.sk:103*/
{
int[1] _pac_sc_s31_s33 = {0};
push(0, environment, j, _pac_sc_s31_s33);
dummyStartLoop();
int loop_body_cost_0 = 0;
int boundary_cost = 0;
bit _pac_sc_s15_s17_0 = 0;
for(int j_0 = 0; j_0 < 3; j_0 = j_0 + 1)/*Canonical*/
{
assert (j_0 < 4); //Assert at tmpzqJj8W.sk:96 (-4325113148049933570)
if(((j_0 > 0) && 1) && 1)/*tmpzqJj8W.sk:97*/
{
dummyStartBoundary();
bit _pac_sc_s26 = _pac_sc_s15_s17_0;
if(!(_pac_sc_s15_s17_0))/*tmpzqJj8W.sk:99*/
{
int[2] _pac_sc_s26_s28 = {0,0};
push(1, _pac_sc_s31_s33, j_0, _pac_sc_s26_s28);
int x_s39 = 0;
validateX(((coefficients1_0[0]) * (_pac_sc_s26_s28[1])) + 8, x_s39);
int y_s43 = 0;
validateY(((coefficients2_0[0]) * (_pac_sc_s26_s28[0])) + 7, y_s43);
int x2_s47 = 0;
validateX(((coefficients1_0[0]) * (_pac_sc_s26_s28[1])) + 9, x2_s47);
int y2_s51 = 0;
validateY(((coefficients2_0[0]) * (_pac_sc_s26_s28[0])) + 7, y2_s51);
assert ((x_s39 == x2_s47) || (y_s43 == y2_s51)); //Assert at tmpzqJj8W.sk:137 (2109344902378156491)
bit _pac_sc_s26_s30 = 0 || (((((((shapeIdentity == 1) && (x_s39 == lx1)) && (y_s43 == ly1)) && (x2_s47 == lx2)) && (y2_s51 == ly2)) && (0 == dashed)) && (0 == arrow));
int x_s39_0 = 0;
validateX(((coefficients1_0[0]) * (_pac_sc_s26_s28[0])) + 7, x_s39_0);
int y_s43_0 = 0;
validateY(((coefficients2_0[0]) * (_pac_sc_s26_s28[1])) + 8, y_s43_0);
int x2_s47_0 = 0;
validateX(((coefficients1_0[0]) * (_pac_sc_s26_s28[0])) + 7, x2_s47_0);
int y2_s51_0 = 0;
validateY(((coefficients2_0[0]) * (_pac_sc_s26_s28[1])) + 9, y2_s51_0);
assert ((x_s39_0 == x2_s47_0) || (y_s43_0 == y2_s51_0)); //Assert at tmpzqJj8W.sk:137 (8471357942716875626)
boundary_cost = 2;
_pac_sc_s26_s30 = _pac_sc_s26_s30 || (((((((shapeIdentity == 1) && (x_s39_0 == lx1)) && (y_s43_0 == ly1)) && (x2_s47_0 == lx2)) && (y2_s51_0 == ly2)) && (0 == dashed)) && (0 == arrow));
_pac_sc_s26 = _pac_sc_s26_s30;
}
_pac_sc_s15_s17_0 = _pac_sc_s26;
dummyEndBoundary();
}
bit _pac_sc_s31_0 = _pac_sc_s15_s17_0;
if(!(_pac_sc_s15_s17_0))/*tmpzqJj8W.sk:103*/
{
int[2] _pac_sc_s31_s33_0 = {0,0};
push(1, _pac_sc_s31_s33, j_0, _pac_sc_s31_s33_0);
int x_s39_1 = 0;
validateX(((coefficients1_0[0]) * (_pac_sc_s31_s33_0[1])) + 7, x_s39_1);
int y_s43_1 = 0;