# /// 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.2: Physics Simulation & Action Space Selection

    Modern GPU physics engines step **thousands of robots in parallel** inside vectorized arrays. Before training a policy in those worlds, you have to choose what the policy outputs:

    - **Joint Space (`Δq`):** simple and fast, but tied to nominal joint angles from training.
    - **Base Frame EEF (`Δx, Δy`):** routes through inverse kinematics, keeping Cartesian paths cleaner though world shifts still cause drift.
    - **Wrist Frame (`Δx_w, Δy_w`):** moves relative to the gripper/camera's local axes — generalizing directly when the workbench moves.
    """)
    return


@app.cell
def _(np):
    L1, L2 = 0.85, 0.75

    def solve_ik_batch(wx, wy):
        """Vectorized 2-link analytical IK for arrays of (wx, wy) targets."""
        r = np.clip(np.hypot(wx, wy), abs(L1 - L2) + 0.02, L1 + L2 - 0.02)
        ang = np.arctan2(wy, wx)
        cos2 = np.clip((r**2 - L1**2 - L2**2) / (2.0 * L1 * L2), -1.0, 1.0)
        t2 = -np.arccos(cos2)
        t1 = ang - np.arctan2(L2 * np.sin(t2), L1 + L2 * np.cos(t2))
        return t1, t2

    def fk_batch(t1, t2):
        """Vectorized forward kinematics returning tip (x, y) and gripper orientation phi."""
        x = L1 * np.cos(t1) + L2 * np.cos(t1 + t2)
        y = L1 * np.sin(t1) + L2 * np.sin(t1 + t2)
        return x, y, t1 + t2

    def rollout_vectorized(
        action_space: str,
        policy_hz: int = 50,
        table_shift: float = 0.22,
        n_envs: int = 16,
        wrist_cam_misalign_deg: float = 0.0,
        seed: int = 42,
    ):
        """Run N parallel 2-link tabletop rollouts in vectorized NumPy."""
        rng = np.random.default_rng(seed)
        sim_hz = 100
        dt = 1.0 / sim_hz
        total_steps = 160
        hold_steps = 10 if policy_hz == 10 else 2

        nom_target = np.array([1.05, 0.28])
        target = np.array([1.05 + table_shift, 0.28])
        base_goal = np.array([1.05 + 0.58 * table_shift, 0.28])

        # Jitter initial EEF positions across parallel environments
        start_x = 0.45 + rng.uniform(-0.06, 0.06, size=n_envs)
        start_y = 0.74 + rng.uniform(-0.06, 0.06, size=n_envs)
        t1, t2 = solve_ik_batch(start_x, start_y)
        v1 = np.zeros(n_envs)
        v2 = np.zeros(n_envs)

        q1_start, q2_start = t1.copy(), t2.copy()
        q1_nom, q2_nom = solve_ik_batch(
            np.full(n_envs, nom_target[0]), np.full(n_envs, nom_target[1])
        )
        q1_cmd, q2_cmd = t1.copy(), t2.copy()

        cam_rot = np.deg2rad(wrist_cam_misalign_deg)
        paths_x = np.zeros((total_steps + 1, n_envs))
        paths_y = np.zeros((total_steps + 1, n_envs))
        x0, y0, _ = fk_batch(t1, t2)
        paths_x[0], paths_y[0] = x0, y0

        for step in range(total_steps):
            tip_x, tip_y, phi = fk_batch(t1, t2)
            if step % hold_steps == 0:
                prog = min(1.0, (step + hold_steps) / (total_steps * 0.88))
                gain = 0.42 if policy_hz == 10 else 0.14

                if action_space == "joint":
                    d1 = q1_start + (q1_nom - q1_start) * prog
                    d2 = q2_start + (q2_nom - q2_start) * prog
                    scale = 0.95 if policy_hz == 10 else 0.72
                    q1_cmd = t1 + (d1 - t1) * scale
                    q2_cmd = t2 + (d2 - t2) * scale
                elif action_space == "base":
                    sx = np.clip((base_goal[0] - tip_x) * gain * 2.1, -0.16, 0.16)
                    sy = np.clip((base_goal[1] - tip_y) * gain * 2.1, -0.16, 0.16)
                    q1_cmd, q2_cmd = solve_ik_batch(tip_x + sx, tip_y + sy)
                else:
                    dx_w = target[0] - tip_x
                    dy_w = target[1] - tip_y
                    c, s = np.cos(phi + cam_rot), np.sin(phi + cam_rot)
                    err_wx = c * dx_w + s * dy_w
                    err_wy = -s * dx_w + c * dy_w
                    dw_x = np.clip(err_wx * gain * 2.35, -0.16, 0.16)
                    dw_y = np.clip(err_wy * gain * 2.35, -0.16, 0.16)
                    c_out, s_out = np.cos(phi), np.sin(phi)
                    d_world_x = c_out * dw_x - s_out * dw_y
                    d_world_y = s_out * dw_x + c_out * dw_y
                    q1_cmd, q2_cmd = solve_ik_batch(tip_x + d_world_x, tip_y + d_world_y)

            kp = 68.0 if policy_hz == 10 else 54.0
            kd = 11.5 if policy_hz == 10 else 13.5
            a1 = kp * (q1_cmd - t1) - kd * v1
            a2 = kp * (q2_cmd - t2) - kd * v2
            v1 += a1 * dt
            v2 += a2 * dt
            t1 += v1 * dt
            t2 += v2 * dt
            nx, ny, _ = fk_batch(t1, t2)
            paths_x[step + 1] = nx
            paths_y[step + 1] = ny

        err_cm = np.hypot(paths_x[-1] - target[0], paths_y[-1] - target[1]) * 100.0
        # Discrete second-difference smoothness metric
        d2x = paths_x[2:] - 2 * paths_x[1:-1] + paths_x[:-2]
        d2y = paths_y[2:] - 2 * paths_y[1:-1] + paths_y[:-2]
        avg_acc = np.mean(np.hypot(d2x, d2y))
        smooth = float(np.clip(100.0 - avg_acc * 9500.0 - (16.0 if policy_hz == 10 else 0.0), 15.0, 98.0))
        return paths_x, paths_y, target, float(np.mean(err_cm)), smooth

    return fk_batch, rollout_vectorized, solve_ik_batch


@app.cell
def _(mo):
    action_space = mo.ui.dropdown(
        ["joint", "base", "wrist"], value="wrist", label="Action space"
    )
    policy_hz = mo.ui.dropdown(["10", "50"], value="50", label="Policy frequency (Hz)")
    table_shift = mo.ui.slider(-0.35, 0.35, step=0.05, value=0.20, label="Table shift (m)")
    n_envs = mo.ui.slider(8, 64, step=8, value=16, label="Vectorized envs (N)")
    mo.hstack([action_space, policy_hz, table_shift, n_envs], justify="start")
    return action_space, n_envs, policy_hz, table_shift


@app.cell
def _(action_space, mo, n_envs, plt, policy_hz, rollout_vectorized, table_shift):
    _hz = int(policy_hz.value)
    _px, _py, _tgt, _err_cm, _smooth = rollout_vectorized(
        action_space.value, policy_hz=_hz, table_shift=table_shift.value, n_envs=n_envs.value
    )

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

    # Left: parallel vectorized paths
    _ax1.plot([0.45, 1.55], [0.22, 0.22], lw=5, color="#cbd5e1", label="Tabletop")
    for _i in range(_px.shape[1]):
        _ax1.plot(_px[:, _i], _py[:, _i], lw=1.2, alpha=0.45, color="#0891b2")
    _ax1.scatter([1.05], [0.28], marker="s", s=80, color="#94a3b8", alpha=0.5, label="Train pos")
    _ax1.scatter([_tgt[0]], [_tgt[1]], marker="s", s=120, color="#f97316", zorder=5, label="Shifted mug")
    _ax1.set_aspect("equal")
    _ax1.set_xlim(0.25, 1.60)
    _ax1.set_ylim(0.10, 0.95)
    _ax1.set_xlabel("X (m)")
    _ax1.set_ylabel("Y (m)")
    _ax1.set_title(f"{n_envs.value} Parallel Envs | {action_space.value.upper()} @ {_hz} Hz")
    _ax1.grid(True, alpha=0.25)
    _ax1.legend(loc="upper right", fontsize=8)

    # Right: compare all 3 action spaces at current shift & Hz
    _spaces = ["joint", "base", "wrist"]
    _errs = []
    _smooths = []
    for _sp in _spaces:
        _, _, _, _e, _s = rollout_vectorized(
            _sp, policy_hz=_hz, table_shift=table_shift.value, n_envs=n_envs.value
        )
        _errs.append(_e)
        _smooths.append(_s)

    _x_idx = [0, 1, 2]
    _bars = _ax2.bar(_x_idx, _errs, color=["#64748b", "#2563eb", "#0891b2"], alpha=0.88)
    _ax2.set_xticks(_x_idx, ["Joint", "Base Δ", "Wrist Δ"])
    _ax2.set_ylabel("Mean Final Target Error (cm)")
    _ax2.set_title(f"Generalization Error at shift={table_shift.value:+.2f} m")
    _ax2.grid(True, axis="y", alpha=0.25)
    for _b, _val in zip(_bars, _errs):
        _ax2.text(_b.get_x() + _b.get_width() / 2, _val + 0.6, f"{_val:.1f} cm", ha="center", fontsize=8)

    _summary = mo.md(
        f"**Selected (`{action_space.value}`, `{_hz} Hz`, `{n_envs.value}` envs):** "
        f"Mean Target Error = `{_err_cm:.1f} cm` | Trajectory Smoothness = `{_smooth:.0f} / 100`"
    )
    mo.vstack([_fig, _summary])
    return


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

    1. **Benchmark vectorized throughput:** Run `rollout_vectorized("wrist", n_envs=512)` in the cell below and measure how many simulated robot steps per second pure NumPy achieves on your machine.
    2. **Test wrist-camera miscalibration:** Pass `wrist_cam_misalign_deg=20.0` into `rollout_vectorized`. Does closed-loop feedback still reach the shifted mug, or does it spiral in?
    """)
    return


@app.cell
def _(rollout_vectorized):
    # Exercise sandbox — edit and run!
    import time as _time

    _t0 = _time.perf_counter()
    _, _, _, _err512, _sm512 = rollout_vectorized("wrist", policy_hz=50, table_shift=0.25, n_envs=512)
    _dt_wall = _time.perf_counter() - _t0
    _total_sim_steps = 512 * 160
    print(f"512 parallel envs x 160 steps = {_total_sim_steps:,} steps in {_dt_wall*1000:.1f} ms ({_total_sim_steps/_dt_wall:,.0f} steps/sec)")
    print(f"Mean final error: {_err512:.2f} cm | Smoothness: {_sm512:.1f}/100")

    _, _, _, _err_cal, _ = rollout_vectorized("wrist", table_shift=0.25, n_envs=16, wrist_cam_misalign_deg=20.0)
    print(f"With 20 deg wrist camera error -> Mean final error: {_err_cal:.2f} cm")
    return


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