# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "marimo",
#     "numpy",
#     "matplotlib",
# ]
# ///

import marimo

__generated_with = "0.26.0"
app = marimo.App(width="medium")


@app.cell
def _():
    import marimo as mo
    import matplotlib.pyplot as plt
    import numpy as np

    return mo, np, plt


@app.cell
def _(mo):
    mo.md(r"""
    # Module 6.3: Imitation Learning & Behavior Cloning

    In human teleoperation, two subtle failure modes show up as soon as you deploy a cloned policy:

    1. **Compounding Covariate Shift:** tiny execution errors nudge the robot off the demonstrated path; unseen states cause slightly worse predictions, growing error over the episode.
    2. **Multimodal Mode Averaging:** if human demos go *either* left *or* right around a mug, a plain MSE regression model predicts the average — steering straight into the obstacle!

    Here we compare **Single-Step MSE**, **Action Chunking (MSE)**, and a **Diffusion-Style Multimodal Policy (Chunked)**.
    """)
    return


@app.cell
def _(np):
    OBSTACLE_CENTER = np.array([0.0, 0.50])
    OBSTACLE_RADIUS = 0.16

    def generate_human_demos(n_per_mode: int = 12, left_ratio: float = 0.5, steps: int = 40, seed: int = 0):
        """Generate bimodal 2D demonstrations routing left or right around a central obstacle."""
        rng = np.random.default_rng(seed)
        t = np.linspace(0.0, 1.0, steps)
        demos = []
        n_total = 2 * n_per_mode
        n_left = int(round(n_total * left_ratio))
        for idx in range(n_total):
            side = -1.0 if idx < n_left else 1.0
            amp = side * (0.34 + rng.normal(0.0, 0.025))
            xs = amp * np.sin(np.pi * t) + rng.normal(0.0, 0.008, size=steps)
            ys = t + rng.normal(0.0, 0.005, size=steps)
            demos.append(np.stack([xs, ys], axis=1))
        return np.array(demos)

    def rollout_imitation_policy(
        policy_type: str,
        chunk_size: int = 8,
        exec_noise: float = 0.015,
        left_ratio: float = 0.5,
        seed: int = 12,
    ):
        """Roll out BC / ACT / Diffusion-style multimodal policy around the obstacle."""
        rng = np.random.default_rng(seed)
        demos = generate_human_demos(left_ratio=left_ratio, seed=3)
        steps = demos.shape[1] - 1
        dt = 1.0 / steps

        # Nominal single-mode expert reference for covariate-shift comparison
        pos = np.array([0.0, 0.0])
        traj = [pos.copy()]
        drift_errs = [0.0]

        # Diffusion policy samples one consistent mode (left or right) at t=0 via denoising
        chosen_mode = -1.0 if rng.random() < left_ratio else 1.0
        chunk_buffer = []

        for step in range(steps):
            t_cur = step / steps
            if len(chunk_buffer) == 0:
                horizon = 1 if policy_type == "Single-Step MSE" else int(chunk_size)
                horizon = max(1, min(horizon, steps - step))

                # Nearest neighbors in dataset at current y-progress
                demo_pts = demos[:, step, :]
                dists = np.linalg.norm(demo_pts - pos, axis=1)

                if policy_type == "Diffusion Policy (Chunked)":
                    # Condition on one coherent mode instead of averaging left & right
                    mode_mask = (demos[:, steps // 2, 0] * chosen_mode) > 0
                    mode_demos = demos[mode_mask] if np.any(mode_mask) else demos
                    idx_best = int(np.argmin(np.linalg.norm(mode_demos[:, step, :] - pos, axis=1)))
                    ref_slice = mode_demos[idx_best, step : step + horizon + 1, :]
                else:
                    # Plain MSE averages nearby demonstrations (catastrophic between modes!)
                    weights = np.exp(-dists**2 / 0.18)
                    weights /= np.sum(weights) + 1e-8
                    mean_traj = np.tensordot(weights, demos[:, step : step + horizon + 1, :], axes=(0, 0))
                    ref_slice = mean_traj

                # Build open-loop action chunk relative to current pose
                for k in range(horizon):
                    action = ref_slice[k + 1] - ref_slice[k]
                    # Covariate-shift bias grows when single-step closed-loop hits OOD states
                    if policy_type == "Single-Step MSE":
                        ood_push = 0.25 * (pos[0] - ref_slice[0, 0])
                        action = action + np.array([ood_push * dt * 4.0, 0.0])
                    chunk_buffer.append(action)

            act = chunk_buffer.pop(0)
            pos = pos + act + rng.normal(0.0, exec_noise, size=2)
            traj.append(pos.copy())

            # Measure deviation from nearest valid human mode
            ideal_x = chosen_mode * 0.34 * np.sin(np.pi * ((step + 1) / steps))
            ideal_y = (step + 1) / steps
            drift_errs.append(float(np.hypot(pos[0] - ideal_x, pos[1] - ideal_y)))

        traj_arr = np.array(traj)
        min_obs_dist = float(np.min(np.linalg.norm(traj_arr - OBSTACLE_CENTER, axis=1)))
        collided = min_obs_dist < OBSTACLE_RADIUS
        return demos, traj_arr, np.array(drift_errs), collided, min_obs_dist

    return (
        OBSTACLE_CENTER,
        OBSTACLE_RADIUS,
        generate_human_demos,
        rollout_imitation_policy,
    )


@app.cell
def _(mo):
    policy_type = mo.ui.dropdown(
        ["Single-Step MSE", "Action Chunking (MSE)", "Diffusion Policy (Chunked)"],
        value="Diffusion Policy (Chunked)",
        label="Imitation policy",
    )
    chunk_size = mo.ui.slider(1, 16, step=1, value=8, label="Chunk horizon (H)")
    exec_noise = mo.ui.slider(0.0, 0.05, step=0.005, value=0.015, label="Execution noise (m)")
    mo.hstack([policy_type, chunk_size, exec_noise], justify="start")
    return chunk_size, exec_noise, policy_type


@app.cell
def _(
    OBSTACLE_CENTER,
    OBSTACLE_RADIUS,
    chunk_size,
    exec_noise,
    mo,
    plt,
    policy_type,
    rollout_imitation_policy,
):
    _demos, _traj, _errs, _collided, _min_dist = rollout_imitation_policy(
        policy_type.value,
        chunk_size=chunk_size.value,
        exec_noise=exec_noise.value,
    )

    _fig, (_ax1, _ax2) = plt.subplots(1, 2, figsize=(10.2, 4.2))

    # Left: bimodal demos + policy rollout around central obstacle
    for _d in _demos:
        _ax1.plot(_d[:, 0], _d[:, 1], color="#94a3b8", lw=1.0, alpha=0.45)

    _obs_circle = plt.Circle(
        (OBSTACLE_CENTER[0], OBSTACLE_CENTER[1]),
        OBSTACLE_RADIUS,
        color="#ef4444",
        alpha=0.25,
        ec="#dc2626",
        lw=2,
        label="Obstacle (mug)",
    )
    _ax1.add_patch(_obs_circle)

    _roll_color = "#dc2626" if _collided else "#0891b2"
    _ax1.plot(_traj[:, 0], _traj[:, 1], color=_roll_color, lw=3.0, label=f"{policy_type.value}")
    _ax1.scatter([0.0], [0.0], color="#111827", s=50, zorder=5, label="Start")
    _ax1.scatter([0.0], [1.0], color="#16a34a", marker="*", s=140, zorder=5, label="Goal")
    _ax1.set_aspect("equal")
    _ax1.set_xlim(-0.55, 0.55)
    _ax1.set_ylim(-0.08, 1.08)
    _ax1.set_xlabel("X (m)")
    _ax1.set_ylabel("Y (m)")
    _ax1.set_title("Multimodal Demos vs. Policy Rollout")
    _ax1.grid(True, alpha=0.25)
    _ax1.legend(loc="upper right", fontsize=7.5)

    # Right: error curve over steps comparing single-step vs chunked
    _, _, _errs_single, _, _ = rollout_imitation_policy(
        "Single-Step MSE", chunk_size=1, exec_noise=exec_noise.value
    )
    _, _, _errs_diff, _, _ = rollout_imitation_policy(
        "Diffusion Policy (Chunked)", chunk_size=chunk_size.value, exec_noise=exec_noise.value
    )
    _ax2.plot(_errs_single * 100.0, color="#ef4444", lw=2, linestyle="--", label="Single-Step MSE")
    _ax2.plot(_errs_diff * 100.0, color="#0891b2", lw=2.4, label=f"Diffusion (H={chunk_size.value})")
    _ax2.set_xlabel("Episode step t")
    _ax2.set_ylabel("Path Deviation (cm)")
    _ax2.set_title("Covariate Shift & Mode Error Over Time")
    _ax2.grid(True, alpha=0.25)
    _ax2.legend(fontsize=8)

    _status = "COLLISION (mode-averaged into obstacle!)" if _collided else "CLEAR (cleanly committed to one mode)"
    _summary = mo.md(
        f"**Status:** `{_status}` | Min clearance to obstacle center: `{_min_dist*100:.1f} cm` "
        f"(obstacle radius `{OBSTACLE_RADIUS*100:.0f} cm`)"
    )
    mo.vstack([_fig, _summary])
    return


@app.cell
def _(mo):
    mo.md(r"""
    ## Try this on your own

    1. **Bias the dataset (`left_ratio = 0.8`):** Call `rollout_imitation_policy("Action Chunking (MSE)", left_ratio=0.8)` and check whether MSE regression still clips the obstacle when 80% of demos go left.
    2. **Chunk horizon sweep:** Loop `chunk_size` over `[1, 2, 4, 8, 12, 16]` for `"Diffusion Policy (Chunked)"` under `exec_noise = 0.025` and compare final path deviations.
    """)
    return


@app.cell
def _(np, rollout_imitation_policy):
    # Exercise sandbox — edit and run!
    _, _, _, _col_bias, _dist_bias = rollout_imitation_policy(
        "Action Chunking (MSE)", chunk_size=8, exec_noise=0.015, left_ratio=0.8
    )
    print(f"80/20 MSE Action Chunking collided={_col_bias}, min clearance={_dist_bias*100:.1f} cm")

    for _h in [1, 2, 4, 8, 12, 16]:
        _errs_h = [
            rollout_imitation_policy(
                "Diffusion Policy (Chunked)", chunk_size=_h, exec_noise=0.025, seed=_s
            )[2][-1] * 100.0
            for _s in range(10)
        ]
        print(f"H={_h:2d} -> mean final deviation: {np.mean(_errs_h):.2f} cm")
    return


if __name__ == "__main__":
    app.run()
