# /// 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.1: Modular Pipelines vs. End-to-End Learning

    Welcome to Course 6! In this notebook we compare three robot control architectures on a simple tabletop reach task when perception has noise and the target object gets bumped mid-motion:

    1. **Sense–Plan–Act (Open-Loop Modular):** detects the target once upfront, plans a straight trajectory, and tracks it blindly.
    2. **Pure End-to-End Policy:** maps noisy observations directly to motor commands without a safety clamp or damped PD filter.
    3. **Hybrid Hierarchical Stack:** uses a closed-loop 20 Hz visual policy on top of a damped IK/PD controller with table-clearance safety limits.
    """)
    return


@app.cell
def _(np):
    def simulate_stack(
        mode: str,
        perception_noise_cm: float = 2.5,
        mid_episode_bump_cm: float = 8.0,
        seed: int = 7,
    ):
        """Simulate a 2D side-view tabletop reach under perception noise and mid-reach target bump."""
        rng = np.random.default_rng(seed)
        dt = 0.02
        steps = 100
        start = np.array([0.15, 0.36])
        target_init = np.array([0.85, 0.10])
        table_z = 0.05

        pos = start.copy()
        vel = np.zeros(2)
        path = [pos.copy()]
        targets = []

        # Open-loop Sense-Plan-Act freezes its perception snapshot at t = 0
        initial_est = target_init + rng.normal(0.0, perception_noise_cm / 100.0, size=2)
        safety_violations = 0

        for step in range(steps):
            t_frac = step / steps
            # Target gets bumped halfway through the reach
            current_target = target_init.copy()
            if step >= 40:
                current_target[0] += mid_episode_bump_cm / 100.0
            targets.append(current_target.copy())

            if mode == "Sense-Plan-Act":
                # Tracks rigid upfront waypoint plan toward initial noisy estimate
                waypoint = start + min(1.0, (step + 1) / 85.0) * (initial_est - start)
                acc = 36.0 * (waypoint - pos) - 10.5 * vel
            elif mode == "Pure End-to-End":
                # Direct noisy observation -> raw motor command (no damping guard or safety floor)
                obs_target = current_target + rng.normal(
                    0.0, perception_noise_cm / 100.0, size=2
                )
                raw_cmd = 30.0 * (obs_target - pos) - 3.8 * vel
                acc = np.clip(raw_cmd, -14.0, 14.0)
            else:
                # Hybrid Hierarchical: closed-loop visual correction + damped PD + table safety clamp
                obs_target = current_target + rng.normal(
                    0.0, (perception_noise_cm * 0.65) / 100.0, size=2
                )
                desired_vel = np.clip((obs_target - pos) * 3.4, -0.85, 0.85)
                if pos[1] < table_z + 0.03 and desired_vel[1] < 0:
                    # Low-level safety filter prevents slamming into tabletop
                    desired_vel[1] = max(desired_vel[1], -0.05)
                acc = 18.0 * (desired_vel - vel)

            vel = vel + acc * dt
            pos = pos + vel * dt
            if pos[1] < table_z:
                safety_violations += 1
                if mode == "Hybrid Hierarchical":
                    pos[1] = table_z
                    vel[1] = max(0.0, vel[1])
            path.append(pos.copy())

        path_arr = np.array(path)
        final_target = targets[-1]
        final_err_cm = float(np.linalg.norm(path_arr[-1] - final_target) * 100.0)
        return path_arr, final_target, final_err_cm, safety_violations

    return (simulate_stack,)


@app.cell
def _(mo):
    stack_mode = mo.ui.dropdown(
        ["Sense-Plan-Act", "Pure End-to-End", "Hybrid Hierarchical"],
        value="Hybrid Hierarchical",
        label="Control architecture",
    )
    noise_cm = mo.ui.slider(0.0, 8.0, step=0.5, value=2.5, label="Perception noise (cm)")
    bump_cm = mo.ui.slider(
        -12.0, 14.0, step=1.0, value=8.0, label="Mid-episode target bump (cm)"
    )
    mo.hstack([stack_mode, noise_cm, bump_cm], justify="start")
    return bump_cm, noise_cm, stack_mode


@app.cell
def _(bump_cm, mo, noise_cm, plt, simulate_stack, stack_mode):
    _modes = ["Sense-Plan-Act", "Pure End-to-End", "Hybrid Hierarchical"]
    _colors = {
        "Sense-Plan-Act": "#64748b",
        "Pure End-to-End": "#dc2626",
        "Hybrid Hierarchical": "#0891b2",
    }

    _fig, _ax = plt.subplots(figsize=(7.2, 4.2))
    _ax.axhspan(-0.05, 0.05, color="#cbd5e1", alpha=0.45, label="Table surface (z ≤ 0.05 m)")
    _ax.axhline(0.05, color="#475569", lw=1.5)

    _rows = []
    _final_target = None
    for _m in _modes:
        _path, _tgt, _err, _viol = simulate_stack(
            _m, perception_noise_cm=noise_cm.value, mid_episode_bump_cm=bump_cm.value
        )
        _final_target = _tgt
        _is_sel = _m == stack_mode.value
        _ax.plot(
            _path[:, 0],
            _path[:, 1],
            lw=3.0 if _is_sel else 1.5,
            alpha=1.0 if _is_sel else 0.45,
            color=_colors[_m],
            label=f"{_m} (err: {_err:.1f} cm)",
        )
        _ax.scatter([_path[-1, 0]], [_path[-1, 1]], color=_colors[_m], s=55 if _is_sel else 25, zorder=5)
        _rows.append(f"| `{_m}` | `{_err:.1f} cm` | `{_viol}` |")

    _ax.scatter([0.85], [0.10], marker="s", s=80, color="#94a3b8", alpha=0.5, label="Initial target")
    _ax.scatter([_final_target[0]], [_final_target[1]], marker="*", s=180, color="#f97316", zorder=6, label="Shifted target")
    _ax.set_xlim(0.05, 1.15)
    _ax.set_ylim(-0.02, 0.45)
    _ax.set_xlabel("X (m)")
    _ax.set_ylabel("Z height (m)")
    _ax.set_title(f"Highlighted Stack: {stack_mode.value}")
    _ax.grid(True, alpha=0.25)
    _ax.legend(loc="upper right", fontsize=8)

    _table = mo.md(
        "| Architecture | Final Miss | Table Collisions |\n| :--- | :--- | :--- |\n"
        + "\n".join(_rows)
    )
    mo.vstack([_fig, _table])
    return


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

    1. **Noise sweep across architectures:** Sweep `perception_noise_cm` from `0.0` to `8.0 cm` over 10 random seeds in the cell below and compare the mean final miss error of `Sense-Plan-Act` vs. `Hybrid Hierarchical`.
    2. **Zero bump test:** Set `mid_episode_bump_cm = 0.0` and `perception_noise_cm = 0.0`. Does `Sense-Plan-Act` match or beat the others when the world matches its assumptions?
    """)
    return


@app.cell
def _(np, plt, simulate_stack):
    # Exercise sandbox — edit and run!
    _noises = [0.0, 2.0, 4.0, 6.0, 8.0]
    _modes_ex = ["Sense-Plan-Act", "Pure End-to-End", "Hybrid Hierarchical"]
    _fig_ex, _ax_ex = plt.subplots(figsize=(6.2, 3.6))

    for _m_ex in _modes_ex:
        _means = []
        for _n in _noises:
            _errs = [
                simulate_stack(_m_ex, perception_noise_cm=_n, mid_episode_bump_cm=6.0, seed=_s)[2]
                for _s in range(10)
            ]
            _means.append(np.mean(_errs))
        _ax_ex.plot(_noises, _means, "-o", label=_m_ex)

    _ax_ex.set_xlabel("Perception noise std (cm)")
    _ax_ex.set_ylabel("Mean final target error (cm)")
    _ax_ex.set_title("Exercise: Architecture Sensitivity to Perception Noise")
    _ax_ex.grid(True, alpha=0.25)
    _ax_ex.legend(fontsize=8)
    _fig_ex
    return


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