"""
=============================================================================
CMU 11-777 · 附录 A1 共享模块：gridrl.py —— 格子世界：按一句话走到对的物体上，只靠奖励来学
=============================================================================

【这个模块是干什么的】
    第 17 讲的智能体是看示范学的（行为克隆）：每一步都有专家告诉它"应该往哪走"。这个附录换一种学法——
    **没有示范，只有奖励**：走到对的物体上 +1，走到错的物体上 −1，其他时候 0。智能体要自己去试，
    从试出来的奖励里学会"听这句话、看这张图、该往哪走"。这就是强化学习（reinforcement learning, RL）。

    为了把注意力放在"怎么从奖励里学"上，这里的世界是**离散**的、感知是**理想**的：
        状态     5 × 5 个格子，放 4 个物体（形状 × 颜色，用第 1 讲的词表），智能体站在某个空格子上
        观察     每个格子的"理想检测结果"（形状 one-hot 4 维 + 颜色 one-hot 4 维），以智能体为中心截一个
                 9 × 9 的窗口（再加 1 个"世界外面"的通道）= 9 个通道 × 9 × 9；外加一句指令 "go to the red circle"
                 （第 17 讲已经处理过从像素里认物体；这里用理想的感知，好让每个实验只差在"学法"上）
        动作     上、下、左、右（撞墙就原地不动）
        奖励     走进目标物体所在的格子 +1，走进别的物体 −1，两种情况任务都结束；其他步 0；
                 最多走 HORIZON = 20 步，走不到就 0
        折扣     γ = 0.9：越早拿到奖励越值钱（§1.3 解释为什么一定要折扣）
    干扰物是故意挑的：一个和目标**同色不同形**，一个**同形不同色**——只看颜色或只看形状，最多对一半。

    整个世界的转移和奖励都是确定的、写得出来的，所以每个学出来的策略都能和**精确的最优解**比
    （价值迭代算出来的 V*、Q*）——这是本附录所有实验的"标准答案"。

【主要接口 API】
    GRID, N_CELLS, ACTIONS, GAMMA, HORIZON, R_TARGET, R_WRONG     世界的常数
    COMBOS, HELD_OUT, TRAIN_COMBOS                               16 种物体；留作测试的 4 种组合
    Layout / sample_layout(rng, ...)                             一个任务：物体、目标、起点（可以有墙）
    DEMO_LAYOUT                                                  代码 01–03 共用的一个手工任务
    instruction(layout, rng, p_synonym)                          指令的词列表
    tables(layout)                                               确定性的转移表 nxt[s, a]、奖励 rew[s, a]、终止 term[s]
    value_iteration / policy_iteration / evaluate_policy         已知 MDP 的精确解法
    shortest_dist(layout)                                        绕开别的物体、到目标的最短步数（检查 V* 用）
    run_policy(layout, act_fn, ...)                              按一个策略走一遍
    BatchEnv                                                     一批并行的随机任务（深度强化学习用）
    encode_words(tokens) / WORDS                                 指令 → 词编号
    ascii_layout(layout, ...)                                    字符画：物体、价值、策略的箭头、走过的路

【运行方式】
    python3 gridrl.py      # 自检：一个任务的字符画、价值迭代 vs 策略迭代、V* 和最短路的关系（约 1 秒）
"""

from collections import deque
from dataclasses import dataclass, field

import numpy as np

import course_path

course_path.use("lecture01")

import scene_world as sw                  # noqa: E402

GRID = 5
N_CELLS = GRID * GRID
ACTIONS = ((-1, 0), (1, 0), (0, -1), (0, 1))          # (行的变化, 列的变化)：上、下、左、右
N_ACTIONS = len(ACTIONS)
ACTION_ZH = ("上", "下", "左", "右")
ARROWS = ("^", "v", "<", ">")
GAMMA = 0.9
HORIZON = 20
R_TARGET, R_WRONG = 1.0, -1.0
N_OBJ = 4

COMBOS = tuple((s, c) for s in range(len(sw.SHAPES)) for c in range(len(sw.COLORS)))    # 16 种 (形状, 颜色)
HELD_OUT = ((0, 1), (1, 2), (2, 3), (3, 0))           # 绿圆、蓝方块、黄三角、红十字：每种形状、每种颜色各出现一次
TRAIN_COMBOS = tuple(c for c in COMBOS if c not in HELD_OUT)
SHAPE_NAME = ("circle", "square", "triangle", "cross")
SHAPE_SYNONYM = ("ball", "box", "triangle", "plus")   # 三角没有同义词（和第 1、17 讲一致）
WORDS = ("<pad>", "go", "to", "the") + sw.COLORS + SHAPE_NAME + ("ball", "box", "plus")
WORD_ID = {w: i for i, w in enumerate(WORDS)}
N_CHANNELS = 9                                        # 形状 4 + 颜色 4 + "世界外面" 1（以智能体为中心的视角）
VIEW = 2 * GRID - 1                                   # 以智能体为中心的窗口：9 × 9


@dataclass(frozen=True)
class Layout:
    """
    一个任务。

    【字段】
        objects：((格子, 形状, 颜色), ...)；格子按阅读顺序编号 0..n²−1（行 = cell // n，列 = cell % n）
        target：(形状, 颜色)——指令要找的那个物体（场景里恰好一个）
        start：智能体的起点（空格子）
        n：边长（默认 5；附录的奖励塑形实验用更大的房间）
        walls：墙所在的格子（走不进去；默认没有）
    """
    objects: tuple
    target: tuple
    start: int
    n: int = GRID
    walls: frozenset = field(default_factory=frozenset)

    def object_at(self):
        """{格子: (形状, 颜色)}。"""
        return {cell: (s, c) for cell, s, c in self.objects}


# 代码 01–03 共用的一个手工设计的任务：目标（红圆）被蓝十字和红方块挡住了左边和下面，只能从上面绕过去
DEMO_LAYOUT = Layout(objects=((9, 0, 0), (8, 3, 2), (14, 1, 0), (17, 0, 2)), target=(0, 0), start=20)


def sample_layout(rng, targets=COMBOS, pool=COMBOS, n_obj=N_OBJ, n=GRID, hard=True):
    """
    采样一个任务。

    【思路】先从 targets 里挑目标；hard=True 时再放一个"同色不同形"、一个"同形不同色"的干扰物
        （从 pool 里挑；挑不到就跳过），其余的干扰物从 pool 里随机挑（所有物体两两不同）；
        最后随机挑 n_obj + 1 个不同的格子：前 n_obj 个放物体，最后一个是起点。
    【参数】rng：np.random.Generator；targets：可以当目标的组合；pool：可以当干扰物的组合；
        n_obj：物体个数（≥ 1）；n：边长；hard：要不要故意放"只差一个属性"的干扰物
    【返回】Layout
    【边界】pool 里不够 n_obj − 1 个不同的干扰物时抛出 ValueError。
    """
    target = targets[int(rng.integers(len(targets)))]
    chosen = [target]
    if hard:
        for same in (lambda c: c[1] == target[1], lambda c: c[0] == target[0]):   # 同色、同形
            options = [c for c in pool if same(c) and c not in chosen]
            if options and len(chosen) < n_obj:
                chosen.append(options[int(rng.integers(len(options)))])
    rest = [c for c in pool if c not in chosen]
    if len(rest) < n_obj - len(chosen):
        raise ValueError("干扰物不够")
    for i in rng.choice(len(rest), size=n_obj - len(chosen), replace=False):
        chosen.append(rest[int(i)])
    cells = rng.choice(n * n, size=n_obj + 1, replace=False)
    objects = tuple((int(cells[k]), chosen[k][0], chosen[k][1]) for k in range(n_obj))
    return Layout(objects=objects, target=target, start=int(cells[-1]), n=n)


def instruction(layout, rng=None, p_synonym=0.0):
    """
    指令："go to the red circle"。

    【参数】layout：Layout；rng：用同义词时需要；p_synonym：把形状说成同义词（ball、box、plus）的概率
    【返回】词的列表（5 个词）
    """
    s, c = layout.target
    word = SHAPE_NAME[s]
    if rng is not None and p_synonym > 0 and rng.random() < p_synonym:
        word = SHAPE_SYNONYM[s]
    return ["go", "to", "the", sw.COLORS[c], word]


def encode_words(tokens):
    """词列表 → 编号列表（不认识的词抛出 KeyError：本附录的指令只用 WORDS 里的词）。"""
    return [WORD_ID[w] for w in tokens]


# ---------------------------------------------------------------------------
# 已知 MDP：转移表与精确解法
# ---------------------------------------------------------------------------

def tables(layout):
    """
    把一个任务写成一个**确定性**的 MDP。

    【思路】状态就是格子（n² 个）。从格子 s 做动作 a：算出下一个格子（出界或撞墙就原地不动）；
        走进有物体的格子就拿到奖励（目标 +1，别的 −1）。有物体的格子是**终止状态**：
        到了那里任务结束，之后不再有奖励（写成"自己转移到自己、奖励 0"的吸收态）。
    【返回】(nxt, rew, term)
        nxt：(S, A) 整数，下一个格子；rew：(S, A) 浮点，这一步的奖励；term：(S,) 布尔，是不是终止状态
    【边界】起点永远是空格子；墙格子本身不会被走进去（它在 nxt 里只会转移到自己，不影响结果）。
    【RL 小知识】一般的 MDP 是 P(s' | s, a) 和 R(s, a, s')；这里转移是确定的，所以一张"下一个格子"的表就够了。
    """
    n = layout.n
    objs = layout.object_at()
    S = n * n
    nxt = np.zeros((S, N_ACTIONS), dtype=np.int64)
    rew = np.zeros((S, N_ACTIONS))
    term = np.zeros(S, dtype=bool)
    for cell in objs:
        term[cell] = True
    for s in range(S):
        r, c = divmod(s, n)
        for a, (dr, dc) in enumerate(ACTIONS):
            if term[s]:
                nxt[s, a] = s
                continue
            rr, cc = r + dr, c + dc
            t = rr * n + cc
            if not (0 <= rr < n and 0 <= cc < n) or t in layout.walls:
                t = s
            nxt[s, a] = t
            if t in objs:
                rew[s, a] = R_TARGET if objs[t] == layout.target else R_WRONG
    return nxt, rew, term


def q_from_v(nxt, rew, term, V, gamma=GAMMA):
    """Q(s, a) = r(s, a) + γ · V(s')（终止状态的 Q 全是 0）。"""
    Q = rew + gamma * V[nxt] * (~term[nxt])
    Q[term] = 0.0
    return Q


def value_iteration(layout, gamma=GAMMA, tol=1e-12, max_iter=10_000, V0=None):
    """
    价值迭代：反复用贝尔曼最优方程 V(s) ← max_a [ r(s, a) + γ V(s') ] 更新，直到不再变化。

    【参数】layout；gamma：折扣；tol：两次迭代之间最大的变化小于它就停；V0：初值（默认全 0）
    【返回】(V, Q, residuals)：最优价值、最优动作价值、每次迭代的 ‖V_k − V_{k−1}‖∞
    【边界】gamma = 1 时不保证收敛（这个世界里因为有终止状态，仍会收敛；见 01 的第 3 部分）。
    【RL 小知识】贝尔曼算子是 γ-压缩映射：每迭代一次，离 V* 的最大距离至少缩小到原来的 γ 倍。
    """
    nxt, rew, term = tables(layout)
    V = np.zeros(len(term)) if V0 is None else np.array(V0, dtype=float)
    residuals = []
    for _ in range(max_iter):
        Q = q_from_v(nxt, rew, term, V, gamma)
        V_new = Q.max(axis=1)
        V_new[term] = 0.0
        residuals.append(float(np.abs(V_new - V).max()))
        V = V_new
        if residuals[-1] < tol:
            break
    return V, q_from_v(nxt, rew, term, V, gamma), residuals


def evaluate_policy(layout, pi, gamma=GAMMA):
    """
    策略评估：给定策略 π(a | s)（(S, A) 的概率表），精确解出 V^π。

    【思路】V^π = r_π + γ P_π V^π 是一个线性方程组：(I − γ P_π) V^π = r_π，直接解。
        终止状态的 V 固定为 0（把它们从 P_π 里去掉）。
    【返回】V^π：(S,)
    【边界】gamma = 1 且策略可能永远不终止时矩阵奇异，np.linalg.solve 会报错——这正是"不折扣"的麻烦。
    """
    nxt, rew, term = tables(layout)
    S = len(term)
    P = np.zeros((S, S))
    for a in range(N_ACTIONS):
        P[np.arange(S), nxt[:, a]] += pi[:, a]
    P[:, term] = 0.0
    P[term] = 0.0
    r_pi = (pi * rew).sum(axis=1)
    r_pi[term] = 0.0
    return np.linalg.solve(np.eye(S) - gamma * P, r_pi)


def policy_iteration(layout, gamma=GAMMA, max_iter=100):
    """
    策略迭代：评估当前策略（解线性方程）→ 对评估出的 Q 取贪心 → 直到策略不再变。

    【返回】(policy, V, history)：确定性策略（(S,) 的动作编号）、它的价值、每一轮起点的价值列表
    【边界】从"全部往上走"的策略开始；贪心时并列的动作取编号最小的，保证结果可复现。
    """
    nxt, rew, term = tables(layout)
    S = len(term)
    policy = np.zeros(S, dtype=np.int64)
    history = []
    for _ in range(max_iter):
        pi = np.eye(N_ACTIONS)[policy]
        V = evaluate_policy(layout, pi, gamma)
        history.append(float(V[layout.start]))
        Q = q_from_v(nxt, rew, term, V, gamma)
        new = Q.argmax(axis=1)
        keep = np.isclose(Q[np.arange(S), policy], Q.max(axis=1))    # 原来的动作仍然最好就不换（防止在并列间来回跳）
        new[keep] = policy[keep]
        if np.array_equal(new, policy):
            break
        policy = new
    return policy, V, history


def shortest_dist(layout):
    """
    广度优先搜索：每个格子绕开别的物体、走到目标的最少步数（走不到是 −1）。

    【用途】这个世界里，从 s 出发的最优价值恰好是 V*(s) = γ^(d(s) − 1)：第 d 步拿到 +1，折扣 d − 1 次。
    """
    nxt, _, term = tables(layout)
    objs = layout.object_at()
    goal = next(cell for cell, sc in objs.items() if sc == layout.target)
    dist = np.full(len(term), -1)
    dist[goal] = 0
    queue = deque([goal])
    while queue:                           # 反过来搜：谁走一步能到 u
        u = queue.popleft()
        for s in range(len(term)):
            if dist[s] == -1 and not term[s] and u in nxt[s]:
                dist[s] = dist[u] + 1
                queue.append(s)
    return dist


def run_policy(layout, act_fn, start=None, horizon=HORIZON):
    """
    按策略走一遍（确定性的环境，所以走一遍就知道结果）。

    【参数】act_fn(s, t) → 动作编号；start：起点（默认 layout.start）；horizon：最多走几步
    【返回】(path, total_reward)：走过的格子列表（含起点）、拿到的总奖励（不折扣）
    """
    nxt, rew, term = tables(layout)
    s = layout.start if start is None else start
    path, total = [s], 0.0
    for t in range(horizon):
        a = act_fn(s, t)
        total += rew[s, a]
        s = int(nxt[s, a])
        path.append(s)
        if term[s]:
            break
    return path, total


# ---------------------------------------------------------------------------
# 一批并行的随机任务（深度强化学习用）
# ---------------------------------------------------------------------------

class BatchEnv:
    """
    B 个并行的任务，每个任务结束（到了物体上或走满 HORIZON 步）就自动换一个新任务。

    【思路】每个任务的物体画成一张 (8, n, n) 的"理想检测图"（形状 4 通道 + 颜色 4 通道），
        加上智能体所在位置的 1 个通道，就是观察的图像部分；指令编成 5 个词编号。全部用 numpy 数组批量算。
    【参数】n_envs：并行的任务数 B；seed：随机种子；targets / pool / hard：传给 sample_layout；
        p_synonym：指令里用同义词的概率；layouts：给定一个任务列表时，按顺序循环使用（评估用）
    【主要方法】obs() → (grid (B, 9, 9, 9) float32, words (B, 5) int64)；step(actions) → (rewards, dones)
    【边界】自动换新任务发生在 step() 之内：step 返回的 dones[i] = True 时，第 i 个任务**已经换了**，
        之后的 obs() 是新任务的第一步观察（和常见的向量化环境一样）。
    """

    def __init__(self, n_envs, seed, targets=COMBOS, pool=COMBOS, hard=True, p_synonym=0.0, layouts=None):
        self.B = n_envs
        self.rng = np.random.default_rng(seed)
        self.targets, self.pool, self.hard, self.p_synonym = targets, pool, hard, p_synonym
        self.layouts_given, self.next_given = layouts, 0
        self.keep_final = False                        # True 时 step() 会在换新任务之前把观察存进 final_grid
        self.n = GRID
        self.static = np.zeros((self.B, 8, self.n, self.n), dtype=np.float32)
        self.kind = np.zeros((self.B, self.n * self.n), dtype=np.int8)     # 0 空，1 目标，2 别的物体
        self.words = np.zeros((self.B, 5), dtype=np.int64)
        self.pos = np.zeros(self.B, dtype=np.int64)
        self.t = np.zeros(self.B, dtype=np.int64)
        self.current = [None] * self.B
        self._padded = np.zeros((self.B, N_CHANNELS, 3 * self.n - 2, 3 * self.n - 2), dtype=np.float32)
        for i in range(self.B):
            self._reset(i)

    def _new_layout(self):
        if self.layouts_given is not None:
            lay = self.layouts_given[self.next_given % len(self.layouts_given)]
            self.next_given += 1
            return lay
        return sample_layout(self.rng, self.targets, self.pool, hard=self.hard)

    def _reset(self, i):
        lay = self._new_layout()
        self.current[i] = lay
        self.static[i] = 0.0
        self.kind[i] = 0
        for cell, s, c in lay.objects:
            r, col = divmod(cell, self.n)
            self.static[i, s, r, col] = 1.0
            self.static[i, 4 + c, r, col] = 1.0
            self.kind[i, cell] = 1 if (s, c) == lay.target else 2
        k = self.n - 1
        self._padded[i] = 0.0
        self._padded[i, 8] = 1.0
        self._padded[i, 8, k:k + self.n, k:k + self.n] = 0.0
        self._padded[i, :8, k:k + self.n, k:k + self.n] = self.static[i]
        self.words[i] = encode_words(instruction(lay, self.rng, self.p_synonym))
        self.pos[i] = lay.start
        self.t[i] = 0

    def obs(self):
        """
        以智能体为中心的观察：(B, 9, W, W)，W = 2n − 1 = 9，智能体永远在正中间 (n−1, n−1)。

        【为什么】如果观察是"世界的地图 + 智能体在哪"，网络得自己从两个位置算出"目标在我的哪个方向"——
            25 × 25 种组合，要很多样本才学得会（作者的第一版就卡在这里，固定一个目标都学不会）。
            以自己为中心，"目标在左上方"直接对应输入里一个固定的位置，往哪走就容易学了。
            （很多格子世界、Minigrid 的智能体都这样看世界；真实的机器人用的也是自己的相机。）
        【通道】形状 4 + 颜色 4 + "世界外面"1（窗口超出 5 × 5 的部分标 1，相当于墙）
        """
        W = 2 * self.n - 1
        r, c = np.divmod(self.pos, self.n)
        rows = r[:, None] + np.arange(W)[None, :]             # 在补过边的地图里，窗口的行号
        cols = c[:, None] + np.arange(W)[None, :]
        P = self._padded
        grid = P[np.arange(self.B)[:, None, None, None], np.arange(N_CHANNELS)[None, :, None, None],
                 rows[:, None, :, None], cols[:, None, None, :]]
        return grid, self.words.copy()

    def step(self, actions):
        actions = np.asarray(actions)
        r, c = np.divmod(self.pos, self.n)
        d = np.array(ACTIONS)[actions]
        rr = np.clip(r + d[:, 0], 0, self.n - 1)
        cc = np.clip(c + d[:, 1], 0, self.n - 1)
        self.pos = rr * self.n + cc
        self.t += 1
        kind = self.kind[np.arange(self.B), self.pos]
        rewards = np.where(kind == 1, R_TARGET, np.where(kind == 2, R_WRONG, 0.0)).astype(np.float32)
        dones = (kind > 0) | (self.t >= HORIZON)
        self.last_kind = kind.copy()                   # 评估时用：这一步结束是因为到了目标（1）、错的物体（2）还是走满（0）
        if self.keep_final:                            # 换新任务之前，记下这一步真正走到的地方（"时间到了"时要用）
            self.final_grid = self.obs()[0]
        for i in np.flatnonzero(dones):
            self._reset(int(i))
        return rewards, dones


# ---------------------------------------------------------------------------
# 字符画
# ---------------------------------------------------------------------------

def ascii_layout(layout, values=None, policy=None, path=None):
    """
    字符画（每个格子 6 个字符宽）。

    【参数】values：(S,) 每个格子写一个数（例如 V*）；policy：(S,) 动作编号，画成箭头；path：走过的格子列表
    【返回】多行字符串。物体写成"颜色字母 + 形状符号"（Ro = 红圆、B# = 蓝方块、Y^ = 黄三角、Gx = 绿十字），
        目标物体加 *；起点写 S；墙写 ##；走过的格子写 ·。
    """
    n = layout.n
    objs = layout.object_at()
    on_path = set(path or [])
    lines = []
    for r in range(n):
        row = []
        for c in range(n):
            s = r * n + c
            if s in objs:
                sh, co = objs[s]
                cell = sw.COLOR_LETTER[co] + "o#^x"[sh] + ("*" if (sh, co) == layout.target else "")
            elif s in layout.walls:
                cell = "##"
            elif values is not None:
                cell = f"{values[s]:.2f}"
            elif policy is not None:
                cell = ARROWS[int(policy[s])]
            else:
                cell = "S" if s == layout.start else ("·" if s in on_path else ".")
            if values is None and policy is not None and s == layout.start and s not in objs:
                cell = "S" + ARROWS[int(policy[s])]
            row.append(cell.center(6))
        lines.append("".join(row))
    return "\n".join(lines)


def _self_test():
    rng = np.random.default_rng(0)
    lay = sample_layout(rng)
    print("指令：", " ".join(instruction(lay)))
    print(ascii_layout(lay))
    V, Q, res = value_iteration(lay)
    pol, Vp, hist = policy_iteration(lay)
    d = shortest_dist(lay)
    ok = d >= 1
    print(f"价值迭代 {len(res)} 次收敛；策略迭代 {len(hist)} 轮；两者的 V 最大差 {np.abs(V - Vp).max():.2e}")
    print(f"V*(s) 和 γ^(d−1) 的最大差（所有能走到目标的空格子）：{np.abs(V[ok] - GAMMA ** (d[ok] - 1)).max():.2e}")
    env = BatchEnv(4, seed=1)
    g, w = env.obs()
    print("BatchEnv 观察的形状：", g.shape, w.shape, "；第一个任务的指令：", " ".join(WORDS[i] for i in w[0]))


if __name__ == "__main__":
    _self_test()
