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