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_state_codes = 4
15 nb_rewards_codes = 3
16 nb_actions_codes = 5
17
18 first_state_code = 0
19 first_rewards_code = first_state_code + nb_state_codes
20 first_actions_code = first_rewards_code + nb_rewards_codes
21 nb_codes = first_actions_code + nb_actions_codes
22
23 ######################################################################
24
25
26 def generate_episodes(nb, height=6, width=6, T=10):
27     rnd = torch.rand(nb, height, width)
28     rnd[:, 0, :] = 0
29     rnd[:, -1, :] = 0
30     rnd[:, :, 0] = 0
31     rnd[:, :, -1] = 0
32     wall = 0
33
34     for k in range(3):
35         wall = wall + (
36             rnd.flatten(1).argmax(dim=1)[:, None]
37             == torch.arange(rnd.flatten(1).size(1))[None, :]
38         ).long().reshape(rnd.size())
39         rnd = rnd * (1 - wall.clamp(max=1))
40
41     states = wall[:, None, :, :].expand(-1, T, -1, -1).clone()
42
43     agent = torch.zeros(states.size(), dtype=torch.int64)
44     agent[:, 0, 0, 0] = 1
45     agent_actions = torch.randint(5, (nb, T))
46     rewards = torch.zeros(nb, T, dtype=torch.int64)
47
48     monster = torch.zeros(states.size(), dtype=torch.int64)
49     monster[:, 0, -1, -1] = 1
50     monster_actions = torch.randint(5, (nb, T))
51
52     all_moves = agent.new(nb, 5, height, width)
53     for t in range(T - 1):
54         all_moves.zero_()
55         all_moves[:, 0] = agent[:, t]
56         all_moves[:, 1, 1:, :] = agent[:, t, :-1, :]
57         all_moves[:, 2, :-1, :] = agent[:, t, 1:, :]
58         all_moves[:, 3, :, 1:] = agent[:, t, :, :-1]
59         all_moves[:, 4, :, :-1] = agent[:, t, :, 1:]
60         a = F.one_hot(agent_actions[:, t], num_classes=5)[:, :, None, None]
61         after_move = (all_moves * a).sum(dim=1)
62         collision = (
63             (after_move * (1 - wall) * (1 - monster[:, t]))
64             .flatten(1)
65             .sum(dim=1)[:, None, None]
66             == 0
67         ).long()
68         agent[:, t + 1] = collision * agent[:, t] + (1 - collision) * after_move
69
70         all_moves.zero_()
71         all_moves[:, 0] = monster[:, t]
72         all_moves[:, 1, 1:, :] = monster[:, t, :-1, :]
73         all_moves[:, 2, :-1, :] = monster[:, t, 1:, :]
74         all_moves[:, 3, :, 1:] = monster[:, t, :, :-1]
75         all_moves[:, 4, :, :-1] = monster[:, t, :, 1:]
76         a = F.one_hot(monster_actions[:, t], num_classes=5)[:, :, None, None]
77         after_move = (all_moves * a).sum(dim=1)
78         collision = (
79             (after_move * (1 - wall) * (1 - agent[:, t + 1]))
80             .flatten(1)
81             .sum(dim=1)[:, None, None]
82             == 0
83         ).long()
84         monster[:, t + 1] = collision * monster[:, t] + (1 - collision) * after_move
85
86         hit = (
87             (agent[:, t + 1, 1:, :] * monster[:, t + 1, :-1, :]).flatten(1).sum(dim=1)
88             + (agent[:, t + 1, :-1, :] * monster[:, t + 1, 1:, :]).flatten(1).sum(dim=1)
89             + (agent[:, t + 1, :, 1:] * monster[:, t + 1, :, :-1]).flatten(1).sum(dim=1)
90             + (agent[:, t + 1, :, :-1] * monster[:, t + 1, :, 1:]).flatten(1).sum(dim=1)
91         )
92         hit = (hit > 0).long()
93
94         assert hit.min() == 0 and hit.max() <= 1
95
96         rewards[:, t + 1] = -hit + (1 - hit) * agent[:, t + 1, -1, -1]
97
98     states += 2 * agent + 3 * monster
99
100     return states, agent_actions, rewards
101
102
103 ######################################################################
104
105
106 def episodes2seq(states, actions, rewards):
107     states = states.flatten(2) + first_state_code
108     actions = actions[:, :, None] + first_actions_code
109     rewards = (rewards[:, :, None] + 1) + first_rewards_code
110
111     assert (
112         states.min() >= first_state_code
113         and states.max() < first_state_code + nb_state_codes
114     )
115     assert (
116         actions.min() >= first_actions_code
117         and actions.max() < first_actions_code + nb_actions_codes
118     )
119     assert (
120         rewards.min() >= first_rewards_code
121         and rewards.max() < first_rewards_code + nb_rewards_codes
122     )
123
124     return torch.cat([states, actions, rewards], dim=2).flatten(1)
125
126
127 def seq2episodes(seq, height, width):
128     seq = seq.reshape(seq.size(0), -1, height * width + 2)
129     states = seq[:, :, : height * width] - first_state_code
130     states = states.reshape(states.size(0), states.size(1), height, width)
131     actions = seq[:, :, height * width] - first_actions_code
132     rewards = seq[:, :, height * width + 1] - first_rewards_code - 1
133     return states, actions, rewards
134
135
136 ######################################################################
137
138
139 def episodes2str(states, actions, rewards, unicode=False, ansi_colors=False):
140     if unicode:
141         symbols = " █@$"
142         # vert, hori, cross, thin_hori = "║", "═", "╬", "─"
143         vert, hori, cross, thin_hori = "┃", "━", "╋", "─"
144     else:
145         symbols = " #@$"
146         vert, hori, cross, thin_hori = "|", "-", "+", "-"
147
148     hline = (cross + hori * states.size(-1)) * states.size(1) + cross + "\n"
149
150     result = hline
151
152     for n in range(states.size(0)):
153
154         def state_symbol(v):
155             v = v.item()
156             return "?" if v < 0 or v >= len(symbols) else symbols[v]
157
158         for i in range(states.size(2)):
159             result += (
160                 vert
161                 + vert.join(
162                     ["".join([state_symbol(v) for v in row]) for row in states[n, :, i]]
163                 )
164                 + vert
165                 + "\n"
166             )
167
168         result += (vert + thin_hori * states.size(-1)) * states.size(1) + vert + "\n"
169
170         def status_bar(a, r):
171             a = a.item()
172             a = "ISNEW"[a] if a >= 0 and a < 5 else "?"
173             r = "?" if r < -1 or r > 2 else ("" if r == 0 else f"{r.item()}")
174             return a + " " * (states.size(-1) - len(a) - len(r)) + r
175
176         result += (
177             vert
178             + vert.join([status_bar(a, r) for a, r in zip(actions[n], rewards[n])])
179             + vert
180             + "\n"
181         )
182
183         result += hline
184
185     if ansi_colors:
186         for u, c in [("$", 31), ("@", 32)]:
187             result = result.replace(u, f"\u001b[{c}m{u}\u001b[0m")
188
189     return result
190
191
192 ######################################################################
193
194 if __name__ == "__main__":
195     nb, height, width, T = 8, 4, 6, 20
196     states, actions, rewards = generate_episodes(nb, height, width, T)
197     seq = episodes2seq(states, actions, rewards)
198     s, a, r = seq2episodes(seq, height, width)
199     print(episodes2str(s, a, r, unicode=True, ansi_colors=True))