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