5 from torch.nn import functional as F
7 ######################################################################
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
18 ######################################################################
21 def generate_episodes(nb, height=6, width=6, T=10):
22 rnd = torch.rand(nb, height, width)
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))
36 states = wall[:, None, :, :].expand(-1, T, -1, -1).clone()
38 agent = torch.zeros(states.size(), dtype=torch.int64)
40 agent_actions = torch.randint(5, (nb, T))
41 rewards = torch.zeros(nb, T, dtype=torch.int64)
43 monster = torch.zeros(states.size(), dtype=torch.int64)
44 monster[:, 0, -1, -1] = 1
45 monster_actions = torch.randint(5, (nb, T))
47 all_moves = agent.new(nb, 5, height, width)
48 for t in range(T - 1):
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)
58 (after_move * (1 - wall) * (1 - monster[:, t]))
60 .sum(dim=1)[:, None, None]
63 agent[:, t + 1] = collision * agent[:, t] + (1 - collision) * after_move
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)
74 (after_move * (1 - wall) * (1 - agent[:, t + 1]))
76 .sum(dim=1)[:, None, None]
79 monster[:, t + 1] = collision * monster[:, t] + (1 - collision) * after_move
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)
87 hit = (hit > 0).long()
89 assert hit.min() == 0 and hit.max() <= 1
91 rewards[:, t + 1] = -hit + (1 - hit) * agent[:, t + 1, -1, -1]
93 states += 2 * agent + 3 * monster
95 return states, agent_actions, rewards
98 ######################################################################
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
107 states.min() >= first_state_code
108 and states.max() < first_state_code + nb_state_codes
111 actions.min() >= first_actions_code
112 and actions.max() < first_actions_code + nb_actions_codes
115 rewards.min() >= first_rewards_code
116 and rewards.max() < first_rewards_code + nb_rewards_codes
119 return torch.cat([states, actions, rewards], dim=2).flatten(1)
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
131 ######################################################################
134 def episodes2str(states, actions, rewards, unicode=False, ansi_colors=False):
137 # vert, hori, cross, thin_hori = "║", "═", "╬", "─"
138 vert, hori, cross, thin_hori = "┃", "━", "╋", "─"
141 vert, hori, cross, thin_hori = "|", "-", "+", "-"
143 hline = (cross + hori * states.size(-1)) * states.size(1) + cross + "\n"
147 for n in range(states.size(0)):
148 for i in range(states.size(2)):
153 "".join([symbols[v.item()] for v in row])
154 for row in states[n, :, i]
161 result += (vert + thin_hori * states.size(-1)) * states.size(1) + vert + "\n"
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
170 + vert.join([status_bar(a, r) for a, r in zip(actions[n], rewards[n])])
178 for u, c in [("$", 31), ("@", 32)]:
179 result = result.replace(u, f"\u001b[{c}m{u}\u001b[0m")
184 ######################################################################
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))