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