File size: 11,617 Bytes
020f489
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Four vectorised 10x10 grid games for the weight-reading probe.

Shared interface for every game:
  obs:     float32 [B, 5, 10, 10], flattened channel-major to [B, 500]
           ch0 agent, ch1 moving objects, ch2 reward targets, ch3 obstacles,
           ch4 previous frame of ch1 (moving objects one step ago)
  actions: 0 no-op, 1 up, 2 down, 3 left, 4 right   (row 0 is the top)
  step(a) -> obs, reward [B], done [B]; finished envs auto-reset.
"""
import numpy as np

H = W = 10
DR = np.array([0, -1, 1, 0, 0])
DC = np.array([0, 0, 0, -1, 1])


class _Base:
    max_steps = 1000

    def __init__(self, n, seed):
        self.n = n
        self.rng = np.random.default_rng(seed)
        self.t = np.zeros(n, np.int64)
        self.prev_moving = np.zeros((n, H, W), np.float32)
        self._reset(np.ones(n, bool))
        self.prev_moving[:] = self._moving()

    def reset(self):
        return self._obs()

    def _obs(self):
        o = np.zeros((self.n, 5, H, W), np.float32)
        o[:, 0] = self._agent()
        o[:, 1] = self._moving()
        o[:, 2] = self._targets()
        o[:, 3] = self._obstacles()
        o[:, 4] = self.prev_moving
        return o.reshape(self.n, 500)

    def step(self, a):
        a = np.asarray(a)
        before = self._moving()
        r, done = self._step(a)
        self.t += 1
        done = done | (self.t >= self.max_steps)
        self.prev_moving = before
        if done.any():
            self._reset(done)
            self.t[done] = 0
            self.prev_moving[done] = self._moving()[done]
        return self._obs(), r.astype(np.float32), done

    def _onehot(self, rows, cols, mask=None):
        g = np.zeros((self.n, H, W), np.float32)
        idx = np.arange(self.n)
        if mask is None:
            mask = np.ones(self.n, bool)
        g[idx[mask], rows[mask], cols[mask]] = 1
        return g


class Breakout(_Base):
    """Paddle (2 wide) on bottom row; bricks in rows 0-2; lose ball = episode end."""

    def _reset(self, m):
        k = m.sum()
        if not hasattr(self, "px"):
            n = self.n
            self.px = np.zeros(n, int); self.bx = np.zeros(n, int); self.by = np.zeros(n, int)
            self.dx = np.zeros(n, int); self.dy = np.zeros(n, int)
            self.bricks = np.zeros((n, 3, W), bool)
        self.px[m] = self.rng.integers(0, 9, k)
        self.bx[m] = self.rng.integers(0, W, k)
        self.by[m] = self.rng.integers(3, 5, k)
        self.dx[m] = self.rng.choice([-1, 1], k)
        self.dy[m] = 1
        self.bricks[m] = True

    def _step(self, a):
        n = self.n; idx = np.arange(n)
        self.px = np.clip(self.px + DC[a], 0, 8)
        r = np.zeros(n); done = np.zeros(n, bool)
        nx = self.bx + self.dx
        hitw = (nx < 0) | (nx > 9)
        self.dx[hitw] *= -1
        nx = np.where(hitw, self.bx + self.dx, nx)
        ny = self.by + self.dy
        top = ny < 0
        self.dy[top] = 1
        ny = np.where(top, self.by + 1, ny)
        inb = ny <= 2
        hitb = np.zeros(n, bool)
        hitb[inb] = self.bricks[idx[inb], ny[inb], nx[inb]]
        self.bricks[idx[hitb], ny[hitb], nx[hitb]] = False
        r[hitb] += 1
        self.dy[hitb] *= -1
        ny = np.where(hitb, self.by, ny)
        bottom = ny >= 9
        caught = bottom & ((nx == self.px) | (nx == self.px + 1))
        self.dy[caught] = -1
        ny = np.where(caught, self.by, ny)
        done |= bottom & ~caught
        self.bx, self.by = nx, ny
        cleared = ~self.bricks.reshape(n, -1).any(1)
        self.bricks[cleared] = True
        return r, done

    def _agent(self):
        g = self._onehot(np.full(self.n, 9), self.px)
        g[np.arange(self.n), 9, self.px + 1] = 1
        return g

    def _moving(self):
        return self._onehot(np.clip(self.by, 0, 9), self.bx)

    def _targets(self):
        g = np.zeros((self.n, H, W), np.float32)
        g[:, 0:3] = self.bricks
        return g

    def _obstacles(self):
        return np.zeros((self.n, H, W), np.float32)


class Pong(_Base):
    """Agent paddle (3 tall) at right column; opponent paddle (obstacle) at left."""

    def _reset(self, m):
        if not hasattr(self, "py"):
            n = self.n
            self.py = np.zeros(n, int); self.oy = np.zeros(n, int)
            self.score_a = np.zeros(n, int); self.score_o = np.zeros(n, int)
            self.bx = np.zeros(n, int); self.by = np.zeros(n, int)
            self.dx = np.zeros(n, int); self.dy = np.zeros(n, int)
        self.py[m] = 3; self.oy[m] = 3
        self.score_a[m] = 0; self.score_o[m] = 0
        self._serve(m)

    def _serve(self, m):
        k = m.sum()
        self.bx[m] = self.rng.integers(4, 6, k)
        self.by[m] = self.rng.integers(2, 8, k)
        self.dx[m] = self.rng.choice([-1, 1], k)
        self.dy[m] = self.rng.choice([-1, 1], k)

    def _step(self, a):
        n = self.n
        self.py = np.clip(self.py + DR[a], 0, 7)
        follow = self.rng.random(n) < 0.7
        centre = self.oy + 1
        mv = np.sign(self.by - centre) * follow
        self.oy = np.clip(self.oy + mv, 0, 7)
        r = np.zeros(n)
        ny = self.by + self.dy
        hw = (ny < 0) | (ny > 9)
        self.dy[hw] *= -1
        ny = np.where(hw, self.by + self.dy, ny)
        nx = self.bx + self.dx
        right = nx >= 9
        hit_a = right & (ny >= self.py) & (ny <= self.py + 2)
        left = nx <= 0
        hit_o = left & (ny >= self.oy) & (ny <= self.oy + 2)
        self.dx[hit_a | hit_o] *= -1
        nx = np.where(hit_a | hit_o, self.bx, nx)
        miss_a = right & ~hit_a
        miss_o = left & ~hit_o
        r[miss_a] -= 1; r[miss_o] += 1
        self.score_a += miss_o; self.score_o += miss_a
        self.bx, self.by = nx, ny
        point = miss_a | miss_o
        if point.any():
            self._serve(point)
        done = (self.score_a >= 5) | (self.score_o >= 5)
        return r, done

    def _agent(self):
        g = np.zeros((self.n, H, W), np.float32)
        for k in range(3):
            g[np.arange(self.n), self.py + k, 9] = 1
        return g

    def _moving(self):
        return self._onehot(self.by, np.clip(self.bx, 0, 9))

    def _targets(self):
        return np.zeros((self.n, H, W), np.float32)

    def _obstacles(self):
        g = np.zeros((self.n, H, W), np.float32)
        for k in range(3):
            g[np.arange(self.n), self.oy + k, 0] = 1
        return g


class Freeway(_Base):
    """Agent crosses 8 lanes of traffic (rows 1-8) from row 9 to row 0."""
    max_steps = 250

    def _reset(self, m):
        k = m.sum()
        if not hasattr(self, "ay"):
            n = self.n
            self.ax = np.full(n, 4); self.ay = np.zeros(n, int)
            self.carx = np.zeros((n, 8), int); self.cdir = np.zeros((n, 8), int)
            self.cper = np.ones((n, 8), int)
        self.ay[m] = 9
        self.carx[m] = self.rng.integers(0, W, (k, 8))
        self.cdir[m] = self.rng.choice([-1, 1], (k, 8))
        self.cper[m] = self.rng.integers(1, 4, (k, 8))

    def _step(self, a):
        n = self.n; idx = np.arange(n)
        self.ay = np.clip(self.ay + DR[a], 0, 9)
        moving = (self.t[:, None] % self.cper) == 0
        self.carx = (self.carx + self.cdir * moving) % W
        lane = self.ay - 1
        inlane = (lane >= 0) & (lane < 8)
        hit = np.zeros(n, bool)
        hit[inlane] = self.carx[idx[inlane], lane[inlane]] == self.ax[inlane]
        self.ay = np.where(hit, np.minimum(self.ay + 2, 9), self.ay)
        r = np.zeros(n)
        home = self.ay == 0
        r[home] = 1
        self.ay[home] = 9
        return r, np.zeros(n, bool)

    def _agent(self):
        return self._onehot(self.ay, self.ax)

    def _moving(self):
        g = np.zeros((self.n, H, W), np.float32)
        for l in range(8):
            g[np.arange(self.n), l + 1, self.carx[:, l]] = 1
        return g

    def _targets(self):
        g = np.zeros((self.n, H, W), np.float32)
        g[:, 0, :] = 1
        return g

    def _obstacles(self):
        return np.zeros((self.n, H, W), np.float32)


MAZE = [
    "##########",
    "#........#",
    "#.##..##.#",
    "#.#....#.#",
    "#...##...#",
    "#.#....#.#",
    "#.##..##.#",
    "#........#",
    "#........#",
    "##########",
]
WALLS = np.array([[c == "#" for c in row] for row in MAZE])


class PacMan(_Base):
    """Agent collects pellets in a walled maze; two ghosts chase; touching one ends the episode."""
    max_steps = 500

    def _reset(self, m):
        k = m.sum()
        if not hasattr(self, "ar"):
            n = self.n
            self.ar = np.zeros(n, int); self.ac = np.zeros(n, int)
            self.gr = np.zeros((n, 2), int); self.gc = np.zeros((n, 2), int)
            self.pel = np.zeros((n, H, W), bool)
        self.ar[m] = 8; self.ac[m] = self.rng.integers(1, 9, k)
        self.gr[m] = 1; self.gc[m] = np.stack([np.full(k, 1), np.full(k, 8)], 1)
        self.pel[m] = ~WALLS
        mi = np.where(m)[0]
        self.pel[mi, self.ar[mi], self.ac[mi]] = False

    def _step(self, a):
        n = self.n; idx = np.arange(n)
        r0, c0 = self.ar.copy(), self.ac.copy()
        nr, nc = self.ar + DR[a], self.ac + DC[a]
        ok = ~WALLS[nr, nc]
        self.ar = np.where(ok, nr, self.ar); self.ac = np.where(ok, nc, self.ac)
        r = self.pel[idx, self.ar, self.ac].astype(float)
        self.pel[idx, self.ar, self.ac] = False
        g_old_r, g_old_c = self.gr.copy(), self.gc.copy()
        for g in range(2):
            moves = self.rng.random(n) < 0.6
            cr = self.gr[:, g, None] + DR[None, 1:]
            cc = self.gc[:, g, None] + DC[None, 1:]
            valid = ~WALLS[cr, cc]
            dist = np.abs(cr - self.ar[:, None]) + np.abs(cc - self.ac[:, None])
            dist = np.where(valid, dist, 999).astype(float)
            greedy = np.argmin(dist + self.rng.random((n, 4)) * 0.1, 1)
            rnd_score = np.where(valid, self.rng.random((n, 4)), -1)
            randm = np.argmax(rnd_score, 1)
            choice = np.where(self.rng.random(n) < 0.7, greedy, randm)
            self.gr[:, g] = np.where(moves, cr[idx, choice], self.gr[:, g])
            self.gc[:, g] = np.where(moves, cc[idx, choice], self.gc[:, g])
        same = ((self.gr == self.ar[:, None]) & (self.gc == self.ac[:, None])).any(1)
        swap = ((g_old_r == self.ar[:, None]) & (g_old_c == self.ac[:, None]) &
                (self.gr == r0[:, None]) & (self.gc == c0[:, None])).any(1)
        done = same | swap
        cleared = ~self.pel.reshape(n, -1).any(1)
        self.pel[cleared] = ~WALLS
        return r, done

    def _agent(self):
        return self._onehot(self.ar, self.ac)

    def _moving(self):
        g = np.zeros((self.n, H, W), np.float32)
        for k in range(2):
            g[np.arange(self.n), self.gr[:, k], self.gc[:, k]] = 1
        return g

    def _targets(self):
        return self.pel.astype(np.float32)

    def _obstacles(self):
        return np.broadcast_to(WALLS.astype(np.float32), (self.n, H, W)).copy()


GAMES = {"breakout": Breakout, "pong": Pong, "pacman": PacMan, "freeway": Freeway}


def random_returns(name, episodes=500, seed=0):
    env = GAMES[name](64, seed)
    rng = np.random.default_rng(seed + 1)
    ep_ret = np.zeros(64); out = []
    while len(out) < episodes:
        _, r, d = env.step(rng.integers(0, 5, 64))
        ep_ret += r
        for i in np.where(d)[0]:
            out.append(ep_ret[i]); ep_ret[i] = 0
    return np.array(out[:episodes])


if __name__ == "__main__":
    for g in GAMES:
        x = random_returns(g)
        print(f"{g:9s} random: mean {x.mean():6.2f}  sd {x.std():5.2f}")