# /// 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.5: Sim-to-Real Transfer & Hierarchical VLA Systems

    Real hardware rarely matches your CAD mass, lab floor friction, or zero-delay simulator timing (**Sim-to-Real** gap). Here we compare:

    - **Nominal Policy:** tuned strictly for `friction = 1.0x`, `mass = 1.0x`, `latency = 0 ms`.
    - **DR (*Domain-Randomized*) Policy:** trained over wide physical ranges with an online history buffer that adapts to payload sag, traction limits, and sensor lag.

    Plus, in the exercise below, you can inspect how a **Hierarchical VLA** (*Vision-Language-Action*) meta-controller stitches slow semantic language subgoals into a fast 50 Hz low-level skill.

    > **Interactive Model Note:** Rather than running a multi-gigabyte neural VLA or GPU physics binary in the browser, `simulate_transfer` runs an **instant analytical behavioral model** of delayed 2D dynamics, Coulomb traction slip, and online payload adaptation so every slider responds in real time in browser WASM.

    ### Python & NumPy Decoder
    - **Ring-buffer delay `idx = max(0, i - delay_steps)`:** Reading `x_hist[idx]` instead of `x_hist[i]` feeds the controller stale sensor data from `latency_ms` milliseconds ago — the #1 cause of real-world Sim-to-Real oscillation!
    - **`np.sign(fx_cmd)`:** Returns `-1.0`, `0.0`, or `+1.0` (the direction of the requested horizontal force) when clamping push force at the floor's Coulomb traction limit `friction * mass * g`.
    - **RMS (*Root-Mean-Square*) error `sqrt(mean(err**2))`:** Standard trajectory tracking metric in centimeters, mapped through a smooth logistic curve `100 / (1 + exp(...))` to estimate task success probability.
    """)
    return


@app.cell
def _(np):
    def ref_trajectory(t: float, duration: float = 2.4):
        """Smooth minimum-jerk forward carry / step reference (x, z)."""
        s = float(np.clip(t / duration, 0.0, 1.0))
        s_smooth = 10.0 * s**3 - 15.0 * s**4 + 6.0 * s**5
        return np.array([1.2 * s_smooth, 0.36 * np.sin(np.pi * s)])

    def simulate_transfer(
        policy_kind: str,
        friction: float = 0.60,
        mass: float = 1.45,
        latency_ms: int = 28,
        duration: float = 2.4,
    ):
        """Analytical behavioral model of Sim-to-Real transfer under friction, mass, and latency shifts."""
        dt = 0.002
        total_steps = int(round(duration / dt))
        delay_steps = int(round(latency_ms / 2))

        is_dr = policy_kind == "Domain-Randomized"
        kp = 42.0 if is_dr else 66.0
        kd = 14.5 if is_dr else 10.5
        gravity = 9.81

        x, z = 0.0, 0.0
        vx, vz = 0.0, 0.0
        est_mass_offset = 0.0

        x_hist, z_hist, vx_hist, vz_hist = [], [], [], []
        refs, execs = [], []
        sq_err_sum = 0.0
        max_err = 0.0

        for i in range(total_steps + 1):
            t = i * dt
            r = ref_trajectory(t, duration)
            r_next = ref_trajectory(min(duration, t + dt), duration)
            v_ref = (r_next - r) / dt

            x_hist.append(x)
            z_hist.append(z)
            vx_hist.append(vx)
            vz_hist.append(vz)

            idx = max(0, i - delay_steps)
            x_obs, z_obs = x_hist[idx], z_hist[idx]
            vx_obs, vz_obs = vx_hist[idx], vz_hist[idx]

            if is_dr:
                est_mass_offset = float(
                    np.clip(est_mass_offset + 1.6 * (r[1] - z_obs) * dt, -0.8, 1.4)
                )

            pred_lead = min(0.03, latency_ms * 0.00055) if is_dr else 0.0
            x_pred = x_obs + vx_obs * pred_lead
            z_pred = z_obs + vz_obs * pred_lead

            fx_cmd = kp * (r[0] - x_pred) + kd * (v_ref[0] - vx_obs)
            fz_cmd = (
                kp * (r[1] - z_pred)
                + kd * (v_ref[1] - vz_obs)
                + gravity * (1.0 + (est_mass_offset if is_dr else 0.0))
            )
            if is_dr:
                fx_cmd = float(np.clip(fx_cmd, -6.2, 6.2))

            max_traction = friction * mass * gravity * 0.42
            if abs(fx_cmd) > max_traction:
                slip_scale = 0.65 if is_dr else 0.35
                ax = (np.sign(fx_cmd) * max_traction * slip_scale) / mass
                ax += (0.25 if is_dr else 0.90) * np.sin(t * 28.0) * (1.0 - friction)
            else:
                ax = fx_cmd / mass

            az = (fz_cmd - mass * gravity) / mass
            vx = (vx + ax * dt) * 0.9985
            vz = (vz + az * dt) * 0.9985
            x += vx * dt
            z = max(-0.18, z + vz * dt)

            err = float(np.hypot(x - r[0], z - r[1]))
            sq_err_sum += err * err
            max_err = max(max_err, err)

            if i % 15 == 0 or i == total_steps:
                refs.append(r)
                execs.append([x, z])

        rms_cm = float(np.sqrt(sq_err_sum / (total_steps + 1)) * 100.0)
        peak_cm = max_err * 100.0
        penalty = rms_cm * 0.72 + peak_cm * 0.28
        success_prob = float(100.0 / (1.0 + np.exp((penalty - 7.8) / 2.2)))
        return np.array(refs), np.array(execs), rms_cm, peak_cm, success_prob

    return ref_trajectory, simulate_transfer


@app.cell
def _(mo):
    policy_kind = mo.ui.dropdown(
        ["Nominal", "Domain-Randomized"],
        value="Domain-Randomized",
        label="Policy",
    )
    friction = mo.ui.slider(0.3, 1.6, step=0.05, value=0.60, label="Floor friction (x)")
    mass = mo.ui.slider(0.5, 2.2, step=0.05, value=1.45, label="Payload mass (x)")
    latency_ms = mo.ui.slider(0, 60, step=2, value=28, label="Control latency (ms)")
    mo.vstack([
        mo.hstack([policy_kind, friction], justify="start"),
        mo.hstack([mass, latency_ms], justify="start"),
    ])
    return friction, latency_ms, mass, policy_kind


@app.cell
def _(friction, latency_ms, mass, mo, np, plt, policy_kind, simulate_transfer):
    _refs, _execs, _rms, _peak, _prob = simulate_transfer(
        policy_kind.value,
        friction=friction.value,
        mass=mass.value,
        latency_ms=latency_ms.value,
    )

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

    # Left: target vs executed trajectory
    _ax1.axhline(0.0, color="#64748b", lw=1.2, alpha=0.6)
    _ax1.plot(_refs[:, 0], _refs[:, 1], "--", lw=2.0, color="#475569", label="Target reference")
    _c = "#16a34a" if _prob >= 75 else ("#d97706" if _prob >= 45 else "#dc2626")
    _ax1.plot(_execs[:, 0], _execs[:, 1], lw=2.8, color=_c, label=f"Executed ({policy_kind.value})")
    _ax1.scatter([_refs[-1, 0]], [_refs[-1, 1]], s=90, facecolors="none", edgecolors="#475569", lw=1.8)
    _ax1.scatter([_execs[-1, 0]], [_execs[-1, 1]], s=60, color=_c, zorder=5)
    _ax1.set_xlim(-0.08, 1.32)
    _ax1.set_ylim(-0.15, 0.48)
    _ax1.set_xlabel("Forward X (m)")
    _ax1.set_ylabel("Height Z (m)")
    _ax1.set_title(f"Transfer Rollout | Success Prob: {_prob:.0f}%")
    _ax1.grid(True, alpha=0.25)
    _ax1.legend(loc="upper right", fontsize=8)

    # Right: payload mass sweep comparing Nominal vs Domain-Randomized
    _masses = np.linspace(0.5, 2.2, 18)
    _nom_probs = [
        simulate_transfer("Nominal", friction.value, float(_m), latency_ms.value)[4]
        for _m in _masses
    ]
    _dr_probs = [
        simulate_transfer("Domain-Randomized", friction.value, float(_m), latency_ms.value)[4]
        for _m in _masses
    ]
    _ax2.plot(_masses, _nom_probs, "--o", ms=4, color="#dc2626", label="Nominal Policy")
    _ax2.plot(_masses, _dr_probs, "-o", ms=4, color="#0891b2", label="Domain-Randomized Policy")
    _ax2.axvline(mass.value, color="#64748b", linestyle=":", lw=1.4, label="Current mass")
    _ax2.set_xlabel("Test-time payload mass multiplier (x)")
    _ax2.set_ylabel("Success probability (%)")
    _ax2.set_ylim(-5, 105)
    _ax2.set_title("Generalization Across Unseen Payload Mass")
    _ax2.grid(True, alpha=0.25)
    _ax2.legend(loc="lower left", fontsize=8)

    _summary = mo.md(
        f"**`{policy_kind.value}` Policy Metrics:** RMS Tracking Error = `{_rms:.1f} cm` | "
        f"Peak Deviation = `{_peak:.1f} cm` | Predicted Success = `{_prob:.0f}%`"
    )
    mo.vstack([_fig, _summary])
    return


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

    1. **Find the Nominal latency cliff:** Sweep `latency_ms` from `0` to `60 ms` at `friction=1.0`, `mass=1.0` and print where `Nominal` drops below `70%` success vs. `Domain-Randomized`.
    2. **Hierarchical VLA subgoal router:** Inspect the 4-stage VLA meta-controller below (`approach_mug -> clear_bowl -> place_coaster -> retract_home`), where each semantic stage carries its own payload mass (`1.0x` empty gripper vs. `1.55x` holding a full mug!). Compare overall 4-stage compound success (`prod(stage_probs)`) between `Nominal` and `Domain-Randomized`!

    <details>
    <summary>💡 Hint for Exercise 2</summary>

    In multi-step manipulation, stage probabilities multiply (`P_all = P_1 * P_2 * P_3 * P_4`)! Even if a `Nominal` policy gets `~65%` on each individual stage, `0.65 ** 4 ≈ 18%` end-to-end task completion — which is why robust low-level DR skills (`>85%` per stage) are critical underneath a high-level VLA planner.
    </details>
    """)
    return


@app.cell
def _(np, simulate_transfer):
    # Exercise sandbox — edit and run!
    # --- Exercise 1: Worked latency cliff sweep ---
    print("[Ex 1] Latency sweep at nominal friction=1.0x, mass=1.0x:")
    for _lat in [0, 12, 24, 36, 48, 60]:
        _, _, _, _, _p_nom = simulate_transfer("Nominal", 1.0, 1.0, _lat)
        _, _, _, _, _p_dr = simulate_transfer("Domain-Randomized", 1.0, 1.0, _lat)
        print(f"  latency={_lat:2d} ms -> Nominal={_p_nom:5.1f}% | DR={_p_dr:5.1f}%")

    # --- Exercise 2: 4-Stage Hierarchical VLA Meta-Controller (including retract_home!) ---
    _vla_subgoals = [
        {"skill": "approach_mug", "target_xz": (0.35, 0.14), "mass_x": 1.00},
        {"skill": "clear_bowl", "target_xz": (0.75, 0.38), "mass_x": 1.35},
        {"skill": "place_coaster", "target_xz": (1.15, 0.05), "mass_x": 1.35},
        {"skill": "retract_home", "target_xz": (0.00, 0.25), "mass_x": 1.00},
    ]
    _slick_friction = 0.42  # Slick countertop + 36 ms camera/control lag — try tweaking!
    print(f"\n[Ex 2] 4-Stage Hierarchical VLA Plan (friction={_slick_friction}x, latency=36 ms):")
    _compound = {"Nominal": 1.0, "Domain-Randomized": 1.0}
    for _step_idx, _sg in enumerate(_vla_subgoals, start=1):
        _p_n = simulate_transfer("Nominal", _slick_friction, _sg["mass_x"], 36)[4] / 100.0
        _p_d = simulate_transfer("Domain-Randomized", _slick_friction, _sg["mass_x"], 36)[4] / 100.0
        _compound["Nominal"] *= _p_n
        _compound["Domain-Randomized"] *= _p_d
        print(
            f"  Stage {_step_idx} [{_sg['skill']:13s}] subgoal={_sg['target_xz']} (mass={_sg['mass_x']:.2f}x) "
            f"-> Nominal={_p_n*100:5.1f}% | DR={_p_d*100:5.1f}%"
        )
    assert len(_vla_subgoals) == 4 and _compound["Domain-Randomized"] > _compound["Nominal"]
    print(f"[Ex 2] End-to-end 4-stage success -> Nominal: {_compound['Nominal']*100:.1f}% | DR: {_compound['Domain-Randomized']*100:.1f}%")
    return


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