def getImage(self, drawHand=False, pretty=False):
     if not drawHand:
         if not pretty:
             if self.image is not None: return self.image
             self.image = renderPlan(self.plan, pretty=pretty)
             return self.image
         else:
             return renderPlan(self.plan, pretty=True)
     else:
         if self.handImage is not None: return self.handImage
         self.handImage = renderPlan(self.plan,
                                     drawHand=self.hand,
                                     pretty=pretty)
         return self.handImage
def animateTower(exportPrefix, p):
    print(exportPrefix, p)
    from tower_common import renderPlan
    state,actions = p.evaluate([])(_empty_tower)(TowerState(history=[]))
    print(actions)
    trajectory = state.history + [state]
    print(trajectory)
    print()

    assert tuple(z for z in trajectory if not isinstance(z, TowerState) ) == tuple(actions)        

    def hd(n):
        h = 0
        for state in trajectory[:n]:
            if isinstance(state, TowerState):
                h = state.hand
        return h
    animation = [renderPlan([b for b in trajectory[:n] if not isinstance(b, TowerState)],
                            pretty=True, Lego=True,
                            drawHand=hd(n),
                            masterPlan=actions,
                            randomSeed=hash(exportPrefix))
                 for n in range(0,len(trajectory) + 1)]
    import scipy.misc
    import random
    r = random.random()
    paths = []
    for n in range(len(animation)):
        paths.append(f"{exportPrefix}_{n}.png")
        scipy.misc.imsave(paths[-1], animation[n])
    os.system(f"convert -delay 10 -loop 0 {' '.join(paths)} {exportPrefix}.gif")
 def showMany(ts):
     from pylab import imshow,show
     a = montage([renderPlan(t.plan, pretty=True, Lego=True, resolution=256,
                             drawHand=False)
                  for t in ts]) 
     imshow(a)
     show()
Esempio n. 4
0
 def exportImage(self, f, pretty=True, Lego=True, drawHand=False):
     from tower_common import renderPlan
     a = renderPlan(t.plan,
                    pretty=pretty,
                    Lego=Lego,
                    drawHand=t.hand if drawHand else None)
     import scipy.misc
     scipy.misc.imsave(f, a)
Esempio n. 5
0
def dSLDemo():
    DSL = {}
    bricks = Program.parse(
        "(lambda (lambda (tower_loopM $0 (lambda (lambda (moveHand 3 (reverseHand (tower_loopM $3 (lambda (lambda (moveHand 6 (3x1 $0)))) $0))))))))"
    )
    DSL["bricks"] = [[
        bricks.runWithArguments([x, y, _empty_tower,
                                 TowerState()])[1] for x in range(5, 5 + 4)
    ] for y in [5, 16]]
    dimensionality = {}
    dimensionality["bricks"] = 2

    bridge = Program.parse(
        "(lambda (lambda (tower_loopM $0 (lambda (lambda (#(lambda (#(lambda (lambda (lambda (tower_loopM $0 (lambda (lambda (1x3 (moveHand 4 ($3 $0))))) (moveHand 2 (3x1 $2)))))) $0 (lambda (reverseHand $0)))) (moveHand 4 $0) $3))))))"
    )
    DSL["bridge"] = [[
        bridge.runWithArguments([x, y, _empty_tower,
                                 TowerState()])[1]
        for x in range(4, 4 + 2 * 4, 2)
    ] for y in [4, 9]]
    dimensionality["bridge"] = 2

    staircase = Program.parse(
        "(lambda (tower_loopM $0 (lambda (lambda (#(lambda (lambda (tower_loopM $1 (lambda (lambda (tower_embed (lambda (#(lambda (1x3 (moveHand 4 (1x3 (reverseHand (moveHand 2 (3x1 $0))))))) $0)) $0))) $0))) $1 (moveHand 6 $0))))))"
    )
    DSL["staircase"] = [
        staircase.runWithArguments([n, _empty_tower,
                                    TowerState()])[1] for n in range(3, 5 + 3)
    ]

    images = {}
    for k, v in DSL.items():
        d = dimensionality.get(k, 1)
        if d == 1:
            i = montageMatrix(
                [[renderPlan(p, pretty=True, Lego=True) for p in v]])
        elif d == 2:
            i = montageMatrix(
                [[renderPlan(p, pretty=True, Lego=True) for p in ps]
                 for ps in v])
        else:
            assert False

        images[k] = i

    return images
Esempio n. 6
0
def visualizePrimitives(primitives, fn=None):
    from itertools import product
    from tower_common import renderPlan
    #from pylab import imshow,show

    from towerPrimitives import TowerContinuation, _left, _right, _loop, _embed, _empty_tower, TowerState
    _13 = Program.parse("1x3").value
    _31 = Program.parse("3x1").value

    r = lambda n, k: _right(2 * n)(k)
    l = lambda n, k: _left(2 * n)(k)
    _e = _embed
    _lp = lambda n, b, k: _loop(n)(b)(k)
    _arch = lambda k: l(1, _13(r(2, _13(l(1, _31(k))))))
    _tallArch = lambda h, z, k: _lp(h, lambda _: _13(r(2, _13(l(2, z)))),
                                    r(1, _31(k)))

    matrix = []
    for p in primitives:
        if not p.isInvented: continue
        eprint(p, ":", p.tp)
        t = p.tp
        if t.returns() != ttower: continue

        def argumentChoices(t):
            if t == ttower:
                return [_empty_tower]
            elif t == tint:
                return list(range(5))
            elif t == arrow(ttower, ttower):
                return [_arch, _13, _31]
            else:
                return []

        ts = []
        for arguments in product(
                *[argumentChoices(t) for t in t.functionArguments()]):
            t = p.evaluate([])
            for a in arguments:
                t = t(a)
            t = t(TowerState())[1]
            ts.append(t)

        if ts == []: continue

        matrix.append([renderPlan(p, pretty=True) for p in ts])

    # Only visualize if it has something to visualize.
    if len(matrix) > 0:
        matrix = montageMatrix(matrix)
        # imshow(matrix)

        import scipy.misc
        scipy.misc.imsave(fn, matrix)
        #    show()
    else:
        eprint("Tried to visualize primitives, but none to visualize.")
Esempio n. 7
0
 def exportMany(f, ts, shuffle=True, columns=None):
     ts = list(ts)
     if shuffle: random.shuffle(ts)
     a = montage([
         renderPlan(t.plan, pretty=True, Lego=True, resolution=256)
         for t in ts
     ],
                 columns=columns)
     import scipy.misc
     scipy.misc.imsave(f, a)
 def exportMany(f, ts, shuffle=True, columns=None):
     import numpy as np
     
     ts = list(ts)
     if shuffle:
         assert all( t is not None for t in ts  )
         random.shuffle(ts)
     a = montage([renderPlan(t.plan, pretty=True, Lego=True, resolution=256) if t is not None \
                  else np.zeros((256,256,3))
                  for t in ts],
                 columns=columns)        
     import imageio
     imageio.imwrite(f, a)
Esempio n. 9
0
def visualizeSolutions(solutions, export, tasks=None):
    from tower_common import renderPlan

    if tasks is None:
        tasks = list(solutions.keys())
        tasks.sort(key=lambda t: len(t.plan))

    matrix = []
    for t in tasks:
        i = renderPlan(centerTower(t.plan), pretty=True, Lego=True)
        if solutions[t].empty: i = i / 3.
        matrix.append(i)

    # Only visualize if it has something to visualize.
    if len(matrix) > 0:
        matrix = montage(matrix)
        import scipy.misc
        scipy.misc.imsave(export, matrix)
    else:
        eprint("Tried to visualize solutions, but none to visualize.")
Esempio n. 10
0
def dreamOfTowers(grammar, prefix, N=250, montage=True):
    from tower_common import renderPlan

    request = arrow(ttower, ttower)
    randomTowers = [
        tuple(centerTower(t)) for _ in range(N) for program in
        [grammar.sample(request, maximumDepth=12, maxAttempts=100)]
        if program is not None
        for t in [executeTower(program, timeout=0.5) or []]
        if len(t) >= 1 and len(t) < 100 and towerLength(t) <= 360.
    ]
    matrix = [renderPlan(p, Lego=True, pretty=True) for p in randomTowers]

    # Only visualize if it has something to visualize.
    if len(matrix) > 0:
        import scipy.misc
        if montage:
            matrix = montageMatrix(matrix)
            scipy.misc.imsave('%s.png' % prefix, matrix)
        else:
            for n, i in enumerate(matrix):
                scipy.misc.imsave(f'{prefix}/{n}.png', i)
    else:
        eprint("Tried to visualize dreams, but none to visualize.")
Esempio n. 11
0
 def animate(self):
     from tower_common import renderPlan
     from pylab import imshow, show
     a = renderPlan(self.plan)
     imshow(a)
     show()
 def exportImage(self, f, pretty=True, Lego=True, drawHand=False):
     a = renderPlan(self.plan,
                    pretty=pretty, Lego=Lego,
                    drawHand=t.hand if drawHand else None)
     import imageio
     imageio.imwrite(f, a)
 def animate(self):
     from pylab import imshow,show
     a = renderPlan(self.plan)
     imshow(a)
     show()