a3d8c85962296639f5d2fc53ff84d6df4c2f9d5e
[picoclvr.git] / escape.py
1 #!/usr/bin/env python
2
3 # Any copyright is dedicated to the Public Domain.
4 # https://creativecommons.org/publicdomain/zero/1.0/
5
6 # Written by Francois Fleuret <francois@fleuret.org>
7
8 import torch
9
10 from torch.nn import functional as F
11
12 ######################################################################
13
14 nb_states_codes = 5
15 nb_actions_codes = 5
16 nb_rewards_codes = 3
17 nb_lookahead_rewards_codes = 3
18
19 first_states_code = 0
20 first_actions_code = first_states_code + nb_states_codes
21 first_rewards_code = first_actions_code + nb_actions_codes
22 first_lookahead_rewards_code = first_rewards_code + nb_rewards_codes
23 nb_codes = first_lookahead_rewards_code + nb_lookahead_rewards_codes
24
25 ######################################################################
26
27
28 def state2code(r):
29     return r + first_states_code
30
31
32 def code2state(r):
33     return r - first_states_code
34
35
36 def action2code(r):
37     return r + first_actions_code
38
39
40 def code2action(r):
41     return r - first_actions_code
42
43
44 def reward2code(r):
45     return r + 1 + first_rewards_code
46
47
48 def code2reward(r):
49     return r - first_rewards_code - 1
50
51
52 def lookahead_reward2code(r):
53     return r + 1 + first_lookahead_rewards_code
54
55
56 def code2lookahead_reward(r):
57     return r - first_lookahead_rewards_code - 1
58
59
60 ######################################################################
61
62
63 def generate_episodes(nb, height=6, width=6, T=10, nb_walls=3, nb_coins=3):
64     rnd = torch.rand(nb, height, width)
65     rnd[:, 0, :] = 0
66     rnd[:, -1, :] = 0
67     rnd[:, :, 0] = 0
68     rnd[:, :, -1] = 0
69     wall = 0
70     for k in range(nb_walls):
71         wall = wall + (
72             rnd.flatten(1).argmax(dim=1)[:, None]
73             == torch.arange(rnd.flatten(1).size(1))[None, :]
74         ).long().reshape(rnd.size())
75
76         rnd = rnd * (1 - wall.clamp(max=1))
77
78     rnd = torch.rand(nb, height, width)
79     coins = torch.zeros(nb, T, height, width, dtype=torch.int64)
80     rnd = rnd * (1 - wall.clamp(max=1))
81     for k in range(nb_coins):
82         coins[:, 0] = coins[:, 0] + (
83             rnd.flatten(1).argmax(dim=1)[:, None]
84             == torch.arange(rnd.flatten(1).size(1))[None, :]
85         ).long().reshape(rnd.size())
86
87         rnd = rnd * (1 - coins[:, 0].clamp(max=1))
88
89     states = wall[:, None, :, :].expand(-1, T, -1, -1).clone()
90
91     agent = torch.zeros(states.size(), dtype=torch.int64)
92     agent[:, 0, 0, 0] = 1
93     agent_actions = torch.randint(5, (nb, T))
94     rewards = torch.zeros(nb, T, dtype=torch.int64)
95
96     monster = torch.zeros(states.size(), dtype=torch.int64)
97     monster[:, 0, -1, -1] = 1
98     monster_actions = torch.randint(5, (nb, T))
99
100     all_moves = agent.new(nb, 5, height, width)
101     for t in range(T - 1):
102         all_moves.zero_()
103         all_moves[:, 0] = agent[:, t]
104         all_moves[:, 1, 1:, :] = agent[:, t, :-1, :]
105         all_moves[:, 2, :-1, :] = agent[:, t, 1:, :]
106         all_moves[:, 3, :, 1:] = agent[:, t, :, :-1]
107         all_moves[:, 4, :, :-1] = agent[:, t, :, 1:]
108         a = F.one_hot(agent_actions[:, t], num_classes=5)[:, :, None, None]
109         after_move = (all_moves * a).sum(dim=1)
110         collision = (
111             (after_move * (1 - wall) * (1 - monster[:, t]))
112             .flatten(1)
113             .sum(dim=1)[:, None, None]
114             == 0
115         ).long()
116         agent[:, t + 1] = collision * agent[:, t] + (1 - collision) * after_move
117
118         all_moves.zero_()
119         all_moves[:, 0] = monster[:, t]
120         all_moves[:, 1, 1:, :] = monster[:, t, :-1, :]
121         all_moves[:, 2, :-1, :] = monster[:, t, 1:, :]
122         all_moves[:, 3, :, 1:] = monster[:, t, :, :-1]
123         all_moves[:, 4, :, :-1] = monster[:, t, :, 1:]
124         a = F.one_hot(monster_actions[:, t], num_classes=5)[:, :, None, None]
125         after_move = (all_moves * a).sum(dim=1)
126         collision = (
127             (after_move * (1 - wall) * (1 - agent[:, t + 1]))
128             .flatten(1)
129             .sum(dim=1)[:, None, None]
130             == 0
131         ).long()
132         monster[:, t + 1] = collision * monster[:, t] + (1 - collision) * after_move
133
134         hit = (
135             (agent[:, t + 1, 1:, :] * monster[:, t + 1, :-1, :]).flatten(1).sum(dim=1)
136             + (agent[:, t + 1, :-1, :] * monster[:, t + 1, 1:, :]).flatten(1).sum(dim=1)
137             + (agent[:, t + 1, :, 1:] * monster[:, t + 1, :, :-1]).flatten(1).sum(dim=1)
138             + (agent[:, t + 1, :, :-1] * monster[:, t + 1, :, 1:]).flatten(1).sum(dim=1)
139         )
140         hit = (hit > 0).long()
141
142         # assert hit.min() == 0 and hit.max() <= 1
143
144         got_coin = (agent[:, t + 1] * coins[:, t]).flatten(1).sum(dim=1)
145         coins[:, t + 1] = coins[:, t] * (1 - agent[:, t + 1])
146
147         rewards[:, t + 1] = -hit + (1 - hit) * got_coin
148
149     states = states + 2 * agent + 3 * monster + 4 * coins
150
151     return states, agent_actions, rewards
152
153
154 ######################################################################
155
156
157 def episodes2seq(states, actions, rewards):
158     neg = rewards.new_zeros(rewards.size())
159     pos = rewards.new_zeros(rewards.size())
160     for t in range(neg.size(1) - 1):
161         neg[:, t] = rewards[:, t:].min(dim=-1).values
162         pos[:, t] = rewards[:, t:].max(dim=-1).values
163     s = (neg < 0).long() * neg + (neg >= 0).long() * pos
164
165     return torch.cat(
166         [
167             lookahead_reward2code(s[:, :, None]),
168             state2code(states.flatten(2)),
169             action2code(actions[:, :, None]),
170             reward2code(rewards[:, :, None]),
171         ],
172         dim=2,
173     ).flatten(1)
174
175
176 def seq2episodes(seq, height, width):
177     seq = seq.reshape(seq.size(0), -1, height * width + 3)
178     lookahead_rewards = code2lookahead_reward(seq[:, :, 0])
179     states = code2state(seq[:, :, 1 : height * width + 1])
180     states = states.reshape(states.size(0), states.size(1), height, width)
181     actions = code2action(seq[:, :, height * width + 1])
182     rewards = code2reward(seq[:, :, height * width + 2])
183     return lookahead_rewards, states, actions, rewards
184
185
186 def seq2str(seq):
187     def token2str(t):
188         if t >= first_states_code and t < first_states_code + nb_states_codes:
189             return " #@T$"[t - first_states_code]
190         elif t >= first_actions_code and t < first_actions_code + nb_actions_codes:
191             return "ISNEW"[t - first_actions_code]
192         elif t >= first_rewards_code and t < first_rewards_code + nb_rewards_codes:
193             return "-0+"[t - first_rewards_code]
194         elif (
195             t >= first_lookahead_rewards_code
196             and t < first_lookahead_rewards_code + nb_lookahead_rewards_codes
197         ):
198             return "n.p"[t - first_lookahead_rewards_code]
199         else:
200             return "?"
201
202     return ["".join([token2str(x.item()) for x in row]) for row in seq]
203
204
205 ######################################################################
206
207
208 def episodes2str(
209     lookahead_rewards, states, actions, rewards, unicode=False, ansi_colors=False
210 ):
211     if unicode:
212         symbols = "·█@T$"
213         # vert, hori, cross, thin_hori = "║", "═", "╬", "─"
214         vert, hori, cross, thin_vert, thin_hori = "┃", "━", "╋", "│", "─"
215     else:
216         symbols = " #@T$"
217         vert, hori, cross, thin_vert, thin_hori = "|", "-", "+", "|", "-"
218
219     hline = (cross + hori * states.size(-1)) * states.size(1) + cross + "\n"
220
221     result = hline
222
223     for n in range(states.size(0)):
224
225         def state_symbol(v):
226             v = v.item()
227             return "?" if v < 0 or v >= len(symbols) else symbols[v]
228
229         for i in range(states.size(2)):
230             result += (
231                 vert
232                 + vert.join(
233                     ["".join([state_symbol(v) for v in row]) for row in states[n, :, i]]
234                 )
235                 + vert
236                 + "\n"
237             )
238
239         # result += (vert + thin_hori * states.size(-1)) * states.size(1) + vert + "\n"
240
241         def status_bar(a, r, lr=None):
242             a, r = a.item(), r.item()
243             sb_a = "ISNEW"[a] if a >= 0 and a < 5 else "?"
244             sb_r = "- +"[r + 1] if r in {-1, 0, 1} else "?"
245             if lr is None:
246                 sb_lr = ""
247             else:
248                 lr = lr.item()
249                 sb_lr = "n p"[lr + 1] if lr in {-1, 0, 1} else "?"
250             return (
251                 sb_a
252                 + "/"
253                 + sb_r
254                 + " " * (states.size(-1) - 1 - len(sb_a + sb_r + sb_lr))
255                 + sb_lr
256             )
257
258         result += (
259             vert
260             + vert.join(
261                 [
262                     status_bar(a, r, lr)
263                     for a, r, lr in zip(actions[n], rewards[n], lookahead_rewards[n])
264                 ]
265             )
266             + vert
267             + "\n"
268         )
269
270         result += hline
271
272     if ansi_colors:
273         for u, c in [("$", 31), ("@", 32)]:
274             result = result.replace(u, f"\u001b[{c}m{u}\u001b[0m")
275
276     return result
277
278
279 ######################################################################
280
281 if __name__ == "__main__":
282     nb, height, width, T, nb_walls = 5, 5, 7, 10, 5
283     states, actions, rewards = generate_episodes(nb, height, width, T, nb_walls)
284     seq = episodes2seq(states, actions, rewards)
285     lr, s, a, r = seq2episodes(seq, height, width)
286     print(episodes2str(lr, s, a, r, unicode=True, ansi_colors=True))
287     # print()
288     # for s in seq2str(seq):
289     # print(s)