3 # Any copyright is dedicated to the Public Domain.
4 # https://creativecommons.org/publicdomain/zero/1.0/
6 # Written by Francois Fleuret <francois@fleuret.org>
10 from torch.nn import functional as F
12 ######################################################################
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
23 ######################################################################
26 def generate_episodes(nb, height=6, width=6, T=10):
27 rnd = torch.rand(nb, height, width)
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))
41 states = wall[:, None, :, :].expand(-1, T, -1, -1).clone()
43 agent = torch.zeros(states.size(), dtype=torch.int64)
45 agent_actions = torch.randint(5, (nb, T))
46 rewards = torch.zeros(nb, T, dtype=torch.int64)
48 monster = torch.zeros(states.size(), dtype=torch.int64)
49 monster[:, 0, -1, -1] = 1
50 monster_actions = torch.randint(5, (nb, T))
52 all_moves = agent.new(nb, 5, height, width)
53 for t in range(T - 1):
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)
63 (after_move * (1 - wall) * (1 - monster[:, t]))
65 .sum(dim=1)[:, None, None]
68 agent[:, t + 1] = collision * agent[:, t] + (1 - collision) * after_move
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)
79 (after_move * (1 - wall) * (1 - agent[:, t + 1]))
81 .sum(dim=1)[:, None, None]
84 monster[:, t + 1] = collision * monster[:, t] + (1 - collision) * after_move
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)
92 hit = (hit > 0).long()
94 assert hit.min() == 0 and hit.max() <= 1
96 rewards[:, t + 1] = -hit + (1 - hit) * agent[:, t + 1, -1, -1]
98 states += 2 * agent + 3 * monster
100 return states, agent_actions, rewards
103 ######################################################################
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
112 states.min() >= first_state_code
113 and states.max() < first_state_code + nb_state_codes
116 actions.min() >= first_actions_code
117 and actions.max() < first_actions_code + nb_actions_codes
120 rewards.min() >= first_rewards_code
121 and rewards.max() < first_rewards_code + nb_rewards_codes
124 return torch.cat([states, actions, rewards], dim=2).flatten(1)
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
136 ######################################################################
139 def episodes2str(states, actions, rewards, unicode=False, ansi_colors=False):
142 # vert, hori, cross, thin_hori = "║", "═", "╬", "─"
143 vert, hori, cross, thin_hori = "┃", "━", "╋", "─"
146 vert, hori, cross, thin_hori = "|", "-", "+", "-"
148 hline = (cross + hori * states.size(-1)) * states.size(1) + cross + "\n"
152 for n in range(states.size(0)):
153 for i in range(states.size(2)):
158 "".join([symbols[v.item()] for v in row])
159 for row in states[n, :, i]
166 result += (vert + thin_hori * states.size(-1)) * states.size(1) + vert + "\n"
168 def status_bar(a, r):
169 a = "ISNEW"[a.item()]
170 r = "" if r == 0 else f"{r.item()}"
171 return a + " " * (states.size(-1) - len(a) - len(r)) + r
175 + vert.join([status_bar(a, r) for a, r in zip(actions[n], rewards[n])])
183 for u, c in [("$", 31), ("@", 32)]:
184 result = result.replace(u, f"\u001b[{c}m{u}\u001b[0m")
189 ######################################################################
191 if __name__ == "__main__":
192 nb, height, width, T = 8, 4, 6, 20
193 states, actions, rewards = generate_episodes(nb, height, width, T)
194 seq = episodes2seq(states, actions, rewards)
195 s, a, r = seq2episodes(seq, height, width)
196 print(episodes2str(s, a, r, unicode=True, ansi_colors=True))