"""
=============================================================================
CMU 11-777 · 附录 A2 共享模块：streams.py —— 多模态的"事件流"：看了一长串，最后被问一个问题
=============================================================================

【这个模块是干什么的】
    第 1 讲的场景世界是一张图、一句话、一段声音。这里把时间拉长：智能体一步一步地**看**到物体出现
    （第 1 讲的形状 × 颜色，出现在 3 × 3 的某个格子里）、**听**到音调，最后被问一个关于过去的问题。
    要答对，它得把该记的东西记住——这就是记忆模型要解决的问题（slides："memory to capture
    cross-modal interactions across time"）。感知是理想的（形状、颜色、格子、音调都直接给出），
    好让实验只差在"怎样记"上。

    两类数据：
    1) 同步的流（代码 01）：每一步同时有一个物体和一个音调。任务：
         recall     联想回忆：问"听到音调 k 的时候看到的是什么？"（按**内容**找；跨模态的键 → 值）
         latest     会变的信息：问"格子 c 里**最后**放的是什么？"（同一个格子会被放好几次；要按**时间**区分）
         majority   汇总：问"哪种颜色出现得最多？"（不用记住每一个，只要一个统计量）
    2) 异步的多视图流（代码 02）：每一步**可能**有物体（概率 P_IMG）、**可能**有音调（概率 P_AUD），
       两个模态各走各的。问题分两种：
         只关于一个模态     哪种颜色出现得最多？哪个音调听到得最多？
         跨模态、跨时间     最后一次听到高音之前，最后看到的物体是什么颜色？
                            最后一个红色物体之后，最先听到的是哪个音调？
                            （"之前""之后"都不含同一步：同一步既有物体又有高音时，那个物体不算"之前"）
       后两种要求把两个模态**在时间上**对上——这正是 Memory Fusion Network（Zadeh 等 2018）要解决的。

【主要接口 API】
    DX, DQ, N_TONES, T_MAX, N_CLASSES                 输入、查询的维数；类别数
    sync_batch(task, B, T, rng)                        同步的流 → (x (B, T, DX), q (B, DQ), y (B,))
    MV_TASKS, async_batch(B, T, rng, tasks)            异步的多视图流 → (img (B, T, DI), aud (B, T, DA), q, y, kind)
    describe_sync(x, q, y, task) / describe_async(...) 把一个样本写成人能读的文字

【运行方式】
    python3 streams.py      # 自检：各打印一个例子，检查标签的分布（约 1 秒）
"""

import numpy as np
import torch

import course_path

course_path.use("lecture01")

import scene_world as sw                  # noqa: E402
from console import pad                   # noqa: E402

N_TONES = 32                              # 同步的流里音调的种类（每一串里的音调两两不同，当"键"用）
T_MAX = 64
DX = 4 + 4 + 9 + N_TONES                  # 每一步：形状 4 + 颜色 4 + 格子 9 + 音调 32
DQ = N_TONES + 9 + 1                      # 查询：一个音调（recall）/ 一个格子（latest）/ "哪种颜色最多"（majority）
N_CLASSES = 16                            # 答案：16 种物体（形状 × 颜色），或 4 种颜色（用前 4 类）
SYNC_TASKS = ("recall", "latest", "majority")


def _objects(B, T, rng):
    shape = rng.integers(4, size=(B, T))
    color = rng.integers(4, size=(B, T))
    cell = rng.integers(9, size=(B, T))
    return shape, color, cell


def sync_batch(task, B, T, rng):
    """
    同步的流：每一步一个物体 + 一个音调。

    【思路】每一步的输入 x_t = [形状 one-hot, 颜色 one-hot, 格子 one-hot, 音调 one-hot]；
        一串里的 T 个音调两两不同（从 32 种里不放回地挑）。查询 q 和答案 y 按任务定：
            recall    随机挑这一串里的一步 k：q = 第 k 步的音调，y = 第 k 步的物体（形状 × 4 + 颜色）
            latest    随机挑一个出现过的格子 c：q = c，y = 格子 c 里最后一次放的物体
            majority  q = "哪种颜色最多"；y = 出现次数最多的颜色（有并列就重新抽颜色，直到没有并列）
    【参数】task ∈ SYNC_TASKS；B：批大小；T：长度（≤ N_TONES）；rng：np.random.Generator
    【返回】(x, q, y)：torch 张量，形状 (B, T, DX)、(B, DQ)、(B,)
    【边界】T > N_TONES 时音调不够分，抛出 ValueError。
    【Python 小知识】np.argsort(rng.random((B, N)), axis=1)[:, :T] 一次给每一行一个 0..N−1 的随机排列的前 T 个
        ——"每行不放回地抽 T 个"的向量化写法。
    """
    if T > N_TONES:
        raise ValueError("T 不能超过音调的种类数")
    shape, color, cell = _objects(B, T, rng)
    tones = np.argsort(rng.random((B, N_TONES)), axis=1)[:, :T]
    rows = np.arange(B)
    q = np.zeros((B, DQ), np.float32)
    if task == "recall":
        k = rng.integers(T, size=B)
        q[rows, tones[rows, k]] = 1.0
        y = shape[rows, k] * 4 + color[rows, k]
    elif task == "latest":
        k = rng.integers(T, size=B)
        c = cell[rows, k]
        q[rows, N_TONES + c] = 1.0
        last = np.where(cell == c[:, None], np.arange(T)[None, :], -1).max(axis=1)
        y = shape[rows, last] * 4 + color[rows, last]
    elif task == "majority":
        for _ in range(100):
            counts = np.stack([(color == c).sum(axis=1) for c in range(4)], axis=1)
            tie = (counts == counts.max(axis=1, keepdims=True)).sum(axis=1) > 1
            if not tie.any():
                break
            color[tie] = rng.integers(4, size=(int(tie.sum()), T))
        q[:, N_TONES + 9] = 1.0
        y = counts.argmax(axis=1)
    else:
        raise ValueError(task)
    x = np.zeros((B, T, DX), np.float32)
    bi, ti = rows[:, None], np.arange(T)[None, :]
    x[bi, ti, shape] = 1.0
    x[bi, ti, 4 + color] = 1.0
    x[bi, ti, 8 + cell] = 1.0
    x[bi, ti, 17 + tones] = 1.0
    return torch.from_numpy(x), torch.from_numpy(q), torch.from_numpy(y.astype(np.int64))


# ---------------------------------------------------------------------------
# 异步的多视图流（代码 02）
# ---------------------------------------------------------------------------

P_IMG, P_AUD = 0.5, 0.3                   # 每一步有物体 / 有音调的概率
N_PITCH = 4                               # 音调：低、中、高、最高（编号 0..3；"高音" = 2）
HIGH = 2
DI = 4 + 4 + 1                            # 图像这一路：形状 4 + 颜色 4 + "有物体" 1
DA = N_PITCH + 1                          # 声音这一路：音调 4 + "有声音" 1
MV_TASKS = ("img_majority", "aud_majority", "color_before_high", "tone_after_red")
MV_ZH = {"img_majority": "哪种颜色出现得最多（只看图）",
         "aud_majority": "哪个音调听到得最多（只听声）",
         "color_before_high": "最后一次高音之前，最后看到的物体是什么颜色（跨模态）",
         "tone_after_red": "最后一个红色物体之后，最先听到的是哪个音调（跨模态）"}
DQ_MV = len(MV_TASKS)


def _first(mask):
    """每一行第一个 True 的位置；没有就是 −1。"""
    any_ = mask.any(axis=1)
    return np.where(any_, mask.argmax(axis=1), -1)


def async_batch(B, T, rng, tasks=MV_TASKS):
    """
    异步的多视图流：两个模态各走各的，问题可能只关于一个模态，也可能要把两个模态在时间上对上。

    【思路】先随机生成两条流（物体以 P_IMG、音调以 P_AUD 的概率出现），再给每个样本随机挑一个问题类型，
        算出答案；**问题问不出来**的样本（例如从没听到高音、高音之前没有物体、没有并列唯一的最多）
        整条重新生成，直到每个样本的问题都有唯一的答案。
    【参数】B, T, rng；tasks：从哪些问题类型里挑（默认四种都有）
    【返回】(img (B, T, DI), aud (B, T, DA), q (B, DQ_MV) one-hot 的问题类型, y (B,) ∈ 0..3, kind (B,) 问题类型的编号)
    【边界】T 太短时"问得出来"的样本很少，重新生成的次数会变多（T = 20 时平均不到 2 次）。
    """
    img = np.zeros((B, T, DI), np.float32)
    aud = np.zeros((B, T, DA), np.float32)
    y = np.zeros(B, np.int64)
    kind = rng.choice([MV_TASKS.index(t) for t in tasks], size=B)
    todo = np.arange(B)
    while len(todo):
        n = len(todo)
        has_img = rng.random((n, T)) < P_IMG
        has_aud = rng.random((n, T)) < P_AUD
        shape, color = rng.integers(4, size=(n, T)), rng.integers(4, size=(n, T))
        pitch = rng.integers(N_PITCH, size=(n, T))
        ok = np.zeros(n, bool)
        ans = np.zeros(n, np.int64)
        for j in range(n):
            k = MV_TASKS[kind[todo[j]]]
            if k in ("img_majority", "aud_majority"):
                vals = color[j][has_img[j]] if k == "img_majority" else pitch[j][has_aud[j]]
                cnt = np.bincount(vals, minlength=4)
                if len(vals) and (cnt == cnt.max()).sum() == 1:
                    ok[j], ans[j] = True, int(cnt.argmax())
            elif k == "color_before_high":
                hi = np.flatnonzero(has_aud[j] & (pitch[j] == HIGH))
                if len(hi):
                    before = np.flatnonzero(has_img[j][:hi[-1]])
                    if len(before):
                        ok[j], ans[j] = True, int(color[j][before[-1]])
            else:
                red = np.flatnonzero(has_img[j] & (color[j] == 0))
                if len(red):
                    after = np.flatnonzero(has_aud[j][red[-1] + 1:])
                    if len(after):
                        ok[j], ans[j] = True, int(pitch[j][red[-1] + 1 + after[0]])
        for j in np.flatnonzero(ok):
            i = todo[j]
            img[i] = 0.0
            aud[i] = 0.0
            t = np.flatnonzero(has_img[j])
            img[i, t, shape[j, t]] = 1.0
            img[i, t, 4 + color[j, t]] = 1.0
            img[i, t, 8] = 1.0
            t = np.flatnonzero(has_aud[j])
            aud[i, t, pitch[j, t]] = 1.0
            aud[i, t, 4] = 1.0
            y[i] = ans[j]
        todo = todo[~ok]
    q = np.eye(DQ_MV, dtype=np.float32)[kind]
    return (torch.from_numpy(img), torch.from_numpy(aud), torch.from_numpy(q), torch.from_numpy(y),
            torch.from_numpy(kind))


# ---------------------------------------------------------------------------
# 写成人能读的文字
# ---------------------------------------------------------------------------

def _obj_zh(shape, color):
    return sw.COLOR_ZH[color] + sw.SHAPE_ZH[shape]


def describe_sync(x, q, y, task):
    """同步流的一个样本（x：(T, DX)）→ 多行文字。"""
    lines = []
    for t in range(x.shape[0]):
        s, c = int(x[t, :4].argmax()), int(x[t, 4:8].argmax())
        cell, tone = int(x[t, 8:17].argmax()), int(x[t, 17:].argmax())
        lines.append(f"    第 {t:2d} 步：{sw.ROW_ZH[cell // 3]}{sw.COL_ZH[cell % 3]}格出现{_obj_zh(s, c)}，听到音调 {tone}")
    if task == "recall":
        question = f"听到音调 {int(q[:N_TONES].argmax())} 的时候看到的是什么？"
    elif task == "latest":
        cell = int(q[N_TONES:N_TONES + 9].argmax())
        question = f"{sw.ROW_ZH[cell // 3]}{sw.COL_ZH[cell % 3]}格里最后放的是什么？"
    else:
        question = "哪种颜色出现得最多？"
    answer = _obj_zh(int(y) // 4, int(y) % 4) if task != "majority" else sw.COLOR_ZH[int(y)]
    return "\n".join(lines + [f"  问：{question}  答：{answer}"])


PITCH_ZH = ("低音", "中音", "高音", "最高音")


def describe_async(img, aud, k, y):
    """异步流的一个样本 → 一行一个时间步（没有事件的步写"·"）。"""
    lines = []
    for t in range(img.shape[0]):
        a = _obj_zh(int(img[t, :4].argmax()), int(img[t, 4:8].argmax())) if img[t, 8] else "·"
        b = PITCH_ZH[int(aud[t, :4].argmax())] if aud[t, 4] else "·"
        lines.append(f"    {t:2d}  看到 {pad(a, 6)}  听到 {b}")
    name = MV_TASKS[int(k)]
    answer = sw.COLOR_ZH[int(y)] if name in ("img_majority", "color_before_high") else PITCH_ZH[int(y)]
    return "\n".join(lines + [f"  问：{MV_ZH[name]}  答：{answer}"])


def _self_test():
    rng = np.random.default_rng(0)
    for task in SYNC_TASKS:
        x, q, y = sync_batch(task, 4000, 8, rng)
        print(f"{task:9s} 标签的种类 {len(set(y.tolist()))}，最常见的标签占 {np.bincount(y.numpy()).max() / len(y):.3f}")
    x, q, y = sync_batch("latest", 1, 6, np.random.default_rng(3))
    print(describe_sync(x[0], q[0], y[0], "latest"))
    img, aud, q, y, kind = async_batch(2000, 20, rng)
    for k in range(len(MV_TASKS)):
        yy = y[kind == k].numpy()
        print(f"{MV_TASKS[k]:18s} 样本 {len(yy)}，最常见的答案占 {np.bincount(yy, minlength=4).max() / len(yy):.3f}")
    img, aud, q, y, kind = async_batch(1, 12, np.random.default_rng(5), tasks=("color_before_high",))
    print(describe_async(img[0], aud[0], kind[0], y[0]))


if __name__ == "__main__":
    _self_test()
