Update.
[picoclvr.git] / escape.py
index 7fcafaa..8066479 100755 (executable)
--- a/escape.py
+++ b/escape.py
@@ -11,19 +11,56 @@ from torch.nn import functional as F
 
 ######################################################################
 
-nb_state_codes = 4
-nb_rewards_codes = 3
+nb_states_codes = 4
 nb_actions_codes = 5
+nb_rewards_codes = 3
+nb_lookahead_rewards_codes = 3
 
-first_state_code = 0
-first_rewards_code = first_state_code + nb_state_codes
-first_actions_code = first_rewards_code + nb_rewards_codes
-nb_codes = first_actions_code + nb_actions_codes
+first_states_code = 0
+first_actions_code = first_states_code + nb_states_codes
+first_rewards_code = first_actions_code + nb_actions_codes
+first_lookahead_rewards_code = first_rewards_code + nb_rewards_codes
+nb_codes = first_lookahead_rewards_code + nb_lookahead_rewards_codes
 
 ######################################################################
 
 
-def generate_episodes(nb, height=6, width=6, T=10):
+def state2code(r):
+    return r + first_states_code
+
+
+def code2state(r):
+    return r - first_states_code
+
+
+def action2code(r):
+    return r + first_actions_code
+
+
+def code2action(r):
+    return r - first_actions_code
+
+
+def reward2code(r):
+    return r + 1 + first_rewards_code
+
+
+def code2reward(r):
+    return r - first_rewards_code - 1
+
+
+def lookahead_reward2code(r):
+    return r + 1 + first_lookahead_rewards_code
+
+
+def code2lookahead_reward(r):
+    return r - first_lookahead_rewards_code - 1
+
+
+######################################################################
+
+
+def generate_episodes(nb, height=6, width=6, T=10, nb_walls=3):
     rnd = torch.rand(nb, height, width)
     rnd[:, 0, :] = 0
     rnd[:, -1, :] = 0
@@ -31,11 +68,12 @@ def generate_episodes(nb, height=6, width=6, T=10):
     rnd[:, :, -1] = 0
     wall = 0
 
-    for k in range(3):
+    for k in range(nb_walls):
         wall = wall + (
             rnd.flatten(1).argmax(dim=1)[:, None]
             == torch.arange(rnd.flatten(1).size(1))[None, :]
         ).long().reshape(rnd.size())
+
         rnd = rnd * (1 - wall.clamp(max=1))
 
     states = wall[:, None, :, :].expand(-1, T, -1, -1).clone()
@@ -91,7 +129,7 @@ def generate_episodes(nb, height=6, width=6, T=10):
         )
         hit = (hit > 0).long()
 
-        assert hit.min() == 0 and hit.max() <= 1
+        assert hit.min() == 0 and hit.max() <= 1
 
         rewards[:, t + 1] = -hit + (1 - hit) * agent[:, t + 1, -1, -1]
 
@@ -104,75 +142,114 @@ def generate_episodes(nb, height=6, width=6, T=10):
 
 
 def episodes2seq(states, actions, rewards):
-    states = states.flatten(2) + first_state_code
-    actions = actions[:, :, None] + first_actions_code
-    rewards = (rewards[:, :, None] + 1) + first_rewards_code
-
-    assert (
-        states.min() >= first_state_code
-        and states.max() < first_state_code + nb_state_codes
-    )
-    assert (
-        actions.min() >= first_actions_code
-        and actions.max() < first_actions_code + nb_actions_codes
-    )
-    assert (
-        rewards.min() >= first_rewards_code
-        and rewards.max() < first_rewards_code + nb_rewards_codes
-    )
-
-    return torch.cat([states, actions, rewards], dim=2).flatten(1)
+    neg = rewards.new_zeros(rewards.size())
+    pos = rewards.new_zeros(rewards.size())
+    for t in range(neg.size(1) - 1):
+        neg[:, t] = rewards[:, t:].min(dim=-1).values
+        pos[:, t] = rewards[:, t:].max(dim=-1).values
+    s = (neg < 0).long() * neg + (neg >= 0).long() * pos
+
+    return torch.cat(
+        [
+            lookahead_reward2code(s[:, :, None]),
+            state2code(states.flatten(2)),
+            action2code(actions[:, :, None]),
+            reward2code(rewards[:, :, None]),
+        ],
+        dim=2,
+    ).flatten(1)
 
 
 def seq2episodes(seq, height, width):
-    seq = seq.reshape(seq.size(0), -1, height * width + 2)
-    states = seq[:, :, : height * width] - first_state_code
+    seq = seq.reshape(seq.size(0), -1, height * width + 3)
+    lookahead_rewards = code2lookahead_reward(seq[:, :, 0])
+    states = code2state(seq[:, :, 1 : height * width + 1])
     states = states.reshape(states.size(0), states.size(1), height, width)
-    actions = seq[:, :, height * width] - first_actions_code
-    rewards = seq[:, :, height * width + 1] - first_rewards_code - 1
-    return states, actions, rewards
+    actions = code2action(seq[:, :, height * width + 1])
+    rewards = code2reward(seq[:, :, height * width + 2])
+    return lookahead_rewards, states, actions, rewards
+
+
+def seq2str(seq):
+    def token2str(t):
+        if t >= first_states_code and t < first_states_code + nb_states_codes:
+            return " #@$"[t - first_states_code]
+        elif t >= first_actions_code and t < first_actions_code + nb_actions_codes:
+            return "ISNEW"[t - first_actions_code]
+        elif t >= first_rewards_code and t < first_rewards_code + nb_rewards_codes:
+            return "-0+"[t - first_rewards_code]
+        elif (
+            t >= first_lookahead_rewards_code
+            and t < first_lookahead_rewards_code + nb_lookahead_rewards_codes
+        ):
+            return "n.p"[t - first_lookahead_rewards_code]
+        else:
+            return "?"
+
+    return ["".join([token2str(x.item()) for x in row]) for row in seq]
 
 
 ######################################################################
 
 
-def episodes2str(states, actions, rewards, unicode=False, ansi_colors=False):
+def episodes2str(
+    lookahead_rewards, states, actions, rewards, unicode=False, ansi_colors=False
+):
     if unicode:
-        symbols = " █@$"
+        symbols = "·█@$"
         # vert, hori, cross, thin_hori = "║", "═", "╬", "─"
-        vert, hori, cross, thin_hori = "┃", "━", "╋", "─"
+        vert, hori, cross, thin_vert, thin_hori = "┃", "━", "╋", "│", "─"
     else:
         symbols = " #@$"
-        vert, hori, cross, thin_hori = "|", "-", "+", "-"
+        vert, hori, cross, thin_vert, thin_hori = "|", "-", "+", "|", "-"
 
     hline = (cross + hori * states.size(-1)) * states.size(1) + cross + "\n"
 
     result = hline
 
     for n in range(states.size(0)):
+
+        def state_symbol(v):
+            v = v.item()
+            return "?" if v < 0 or v >= len(symbols) else symbols[v]
+
         for i in range(states.size(2)):
             result += (
                 vert
                 + vert.join(
-                    [
-                        "".join([symbols[v.item()] for v in row])
-                        for row in states[n, :, i]
-                    ]
+                    ["".join([state_symbol(v) for v in row]) for row in states[n, :, i]]
                 )
                 + vert
                 + "\n"
             )
 
-        result += (vert + thin_hori * states.size(-1)) * states.size(1) + vert + "\n"
-
-        def status_bar(a, r):
-            a = "ISNEW"[a.item()]
-            r = "" if r == 0 else f"{r.item()}"
-            return a + " " * (states.size(-1) - len(a) - len(r)) + r
+        # result += (vert + thin_hori * states.size(-1)) * states.size(1) + vert + "\n"
+
+        def status_bar(a, r, lr=None):
+            a, r = a.item(), r.item()
+            sb_a = "ISNEW"[a] if a >= 0 and a < 5 else "?"
+            sb_r = "- +"[r + 1] if r in {-1, 0, 1} else "?"
+            if lr is None:
+                sb_lr = ""
+            else:
+                lr = lr.item()
+                sb_lr = "n p"[lr + 1] if lr in {-1, 0, 1} else "?"
+            return (
+                sb_a
+                + "/"
+                + sb_r
+                + " " * (states.size(-1) - 1 - len(sb_a + sb_r + sb_lr))
+                + sb_lr
+            )
 
         result += (
             vert
-            + vert.join([status_bar(a, r) for a, r in zip(actions[n], rewards[n])])
+            + vert.join(
+                [
+                    status_bar(a, r, lr)
+                    for a, r, lr in zip(actions[n], rewards[n], lookahead_rewards[n])
+                ]
+            )
             + vert
             + "\n"
         )
@@ -189,8 +266,11 @@ def episodes2str(states, actions, rewards, unicode=False, ansi_colors=False):
 ######################################################################
 
 if __name__ == "__main__":
-    nb, height, width, T = 8, 4, 6, 20
-    states, actions, rewards = generate_episodes(nb, height, width, T)
+    nb, height, width, T, nb_walls = 5, 5, 7, 4, 5
+    states, actions, rewards = generate_episodes(nb, height, width, T, nb_walls)
     seq = episodes2seq(states, actions, rewards)
-    s, a, r = seq2episodes(seq, height, width)
-    print(episodes2str(s, a, r, unicode=True, ansi_colors=True))
+    lr, s, a, r = seq2episodes(seq, height, width)
+    print(episodes2str(lr, s, a, r, unicode=True, ansi_colors=True))
+    print()
+    for s in seq2str(seq):
+        print(s)