# /// 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.4: Reinforcement Learning & Reward Shaping

    In Reinforcement Learning, the policy optimizes *exactly* what your reward equation asks for — loopholes included. Here we inspect a 2D reaching reward landscape with four common terms:

    $$r_t = -w_{\text{dist}}\,\|p_t - p_{\text{goal}}\| + R_{\text{goal}}\,\mathbb{I}[\text{in goal}] - w_{\text{act}}\,\|a_t\|^2 - w_{\text{rate}}\,\|a_t - a_{t-1}\|^2$$

    Watch how tweaking those weights flips an optimal policy between **Clean Reach**, **Lazy / Reward Hacking**, and **Overshoot / Oscillating**.
    """)
    return


@app.cell
def _(np):
    START_POS = np.array([-0.78, -0.72])
    GOAL_POS = np.array([0.70, 0.60])
    GOAL_R = 0.14

    def simulate_rl_reach(
        dense_w: float = 1.4,
        sparse_bonus: float = 10.0,
        action_pen: float = 0.30,
        action_rate_pen: float = 0.25,
        start_pos=None,
    ):
        """Simulate greedy optimal-control reaching shaped by RL reward weights."""
        start = START_POS.copy() if start_pos is None else np.array(start_pos, dtype=float)
        guided_benefit = dense_w * 1.35 + (
            sparse_bonus * 0.06 if dense_w >= 0.15 else sparse_bonus * 0.012
        )
        cost_scale = 0.12 + action_pen * 1.4
        drive_ratio = guided_benefit / cost_scale

        if dense_w < 0.18 or drive_ratio < 0.72:
            diagnosis = "Lazy / Reward Hacking"
        elif action_pen < 0.14 and (dense_w >= 1.1 or sparse_bonus >= 11.0):
            diagnosis = "Overshoot / Oscillating"
        else:
            diagnosis = "Clean Reach"

        dt = 0.1
        steps = 46
        pos = start.copy()
        vel = np.zeros(2)
        prev_acc = np.zeros(2)

        effort = 1.0 if diagnosis != "Lazy / Reward Hacking" else float(np.clip((drive_ratio - 0.15) * 0.55, 0.0, 0.42))
        if diagnosis == "Overshoot / Oscillating":
            kp = 6.2 + dense_w * 1.8 + sparse_bonus * 0.08
            kd = 0.32 + action_pen * 1.8 + action_rate_pen * 0.9
            max_acc = 4.8
        elif diagnosis == "Lazy / Reward Hacking":
            kp = 1.6 * effort
            kd = 3.4
            max_acc = 2.6
        else:
            kp = 2.8 + dense_w * 0.75
            kd = 2.3 + action_pen * 1.45 + action_rate_pen * 0.7
            max_acc = 2.6

        traj = [pos.copy()]
        rewards = []
        speeds = [0.0]
        action_jerks = []

        for t in range(steps):
            delta = GOAL_POS - pos
            drift = (
                np.array([0.08 * np.sin(t * 0.45), 0.08 * np.cos(t * 0.35)])
                if dense_w < 0.18
                else np.zeros(2)
            )
            acc = kp * delta - kd * vel + drift
            if diagnosis == "Lazy / Reward Hacking" and t > 7:
                acc *= 0.25

            mag = np.linalg.norm(acc)
            if mag > max_acc:
                acc = acc * (max_acc / mag)

            # Smoothness filter from action-rate penalty
            alpha = 1.0 / (1.0 + action_rate_pen * 1.5)
            acc = alpha * acc + (1.0 - alpha) * prev_acc

            vel = (vel + acc * dt) * 0.96
            pos = np.clip(pos + vel * dt, -1.05, 1.05)

            dist = float(np.linalg.norm(GOAL_POS - pos))
            in_goal = dist <= GOAL_R
            jerk_sq = float(np.sum((acc - prev_acc) ** 2))
            step_r = (
                -dense_w * dist
                - action_pen * float(np.sum(acc**2)) * 0.25
                - action_rate_pen * jerk_sq * 0.15
                + (sparse_bonus * 0.25 if in_goal else 0.0)
            )

            prev_acc = acc.copy()
            traj.append(pos.copy())
            rewards.append(step_r)
            speeds.append(float(np.linalg.norm(vel)))
            action_jerks.append(float(np.sqrt(jerk_sq)))

        return (
            np.array(traj),
            np.array(rewards),
            np.array(speeds),
            np.array(action_jerks),
            diagnosis,
            float(np.sum(rewards)),
            float(np.linalg.norm(GOAL_POS - pos)),
        )

    return GOAL_POS, GOAL_R, START_POS, simulate_rl_reach


@app.cell
def _(mo):
    dense_w = mo.ui.slider(0.0, 3.0, step=0.1, value=1.4, label="Dense distance weight")
    sparse_bonus = mo.ui.slider(0.0, 25.0, step=0.5, value=10.0, label="Sparse goal bonus")
    action_pen = mo.ui.slider(0.0, 2.5, step=0.05, value=0.30, label="Energy / action penalty")
    action_rate_pen = mo.ui.slider(0.0, 1.5, step=0.05, value=0.25, label="Action-rate penalty")
    mo.vstack([
        mo.hstack([dense_w, sparse_bonus], justify="start"),
        mo.hstack([action_pen, action_rate_pen], justify="start"),
    ])
    return action_pen, action_rate_pen, dense_w, sparse_bonus


@app.cell
def _(
    GOAL_POS,
    GOAL_R,
    START_POS,
    action_pen,
    action_rate_pen,
    dense_w,
    mo,
    np,
    plt,
    simulate_rl_reach,
    sparse_bonus,
):
    _traj, _rews, _speeds, _jerks, _diag, _ret, _fdist = simulate_rl_reach(
        dense_w.value, sparse_bonus.value, action_pen.value, action_rate_pen.value
    )

    _grid_vals = np.linspace(-1.1, 1.1, 45)
    _gx, _gy = np.meshgrid(_grid_vals, _grid_vals)
    _dist_grid = np.hypot(_gx - GOAL_POS[0], _gy - GOAL_POS[1])
    _r_grid = -dense_w.value * _dist_grid + np.where(
        _dist_grid <= GOAL_R, sparse_bonus.value * 0.25, 0.0
    )

    _diag_colors = {
        "Clean Reach": "#16a34a",
        "Lazy / Reward Hacking": "#d97706",
        "Overshoot / Oscillating": "#dc2626",
    }
    _c = _diag_colors[_diag]

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

    _im = _ax1.contourf(_gx, _gy, _r_grid, levels=20, cmap="YlGnBu", alpha=0.85)
    _goal_patch = plt.Circle((GOAL_POS[0], GOAL_POS[1]), GOAL_R, color="#16a34a", alpha=0.3, ec="#15803d", lw=2)
    _ax1.add_patch(_goal_patch)
    _ax1.plot(_traj[:, 0], _traj[:, 1], "-o", ms=3, lw=2.5, color=_c, label=_diag)
    _ax1.scatter([START_POS[0]], [START_POS[1]], s=70, color="#111827", zorder=5, label="Start")
    _ax1.set_aspect("equal")
    _ax1.set_xlim(-1.1, 1.1)
    _ax1.set_ylim(-1.1, 1.1)
    _ax1.set_title(f"Diagnosis: {_diag}")
    _ax1.set_xlabel("x (m)")
    _ax1.set_ylabel("y (m)")
    _ax1.legend(loc="upper left", fontsize=8)

    _ax2.plot(_rews, lw=2, color="#2563eb", label="Step reward r_t")
    _ax2.plot(_speeds, lw=1.8, linestyle="--", color="#0891b2", label="Speed ||v_t|| (m/s)")
    _ax2.plot(_jerks, lw=1.5, linestyle=":", color="#dc2626", label="Action delta ||Δa_t||")
    _ax2.set_xlabel("Step t")
    _ax2.set_title("Per-Step Reward, Speed & Action Smoothness")
    _ax2.grid(True, alpha=0.25)
    _ax2.legend(fontsize=8)

    _summary = mo.md(
        f"**Diagnosis:** `{_diag}` | **Total Return:** `{_ret:.1f}` | "
        f"**Final Goal Dist:** `{_fdist:.2f} m` | **Mean Action Jerk:** `{np.mean(_jerks):.3f}`"
    )
    mo.vstack([_fig, _summary])
    return


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

    1. **Map the reward phase diagram:** Sweep `dense_w` across `[0.2, 0.6, 1.0, 1.6, 2.4]` and `action_pen` across `[0.05, 0.3, 0.8, 1.5, 2.2]` to see where `Clean Reach` lives between `Lazy / Reward Hacking` and `Overshoot / Oscillating`.
    2. **Curriculum staging test:** Test starting far away at `start_pos=(-1.0, -1.0)` vs. close `start_pos=(0.3, 0.25)` with `dense_w = 0.1` — notice why sparse-only RL struggles until a curriculum brings early stages closer to the goal.
    """)
    return


@app.cell
def _(simulate_rl_reach):
    # Exercise sandbox — edit and run!
    _dense_list = [0.2, 0.8, 1.5, 2.4]
    _act_list = [0.05, 0.30, 1.00, 2.00]
    for _dw in _dense_list:
        _row_str = f"dense={_dw:.1f}: "
        for _ap in _act_list:
            _, _, _, _, _d_ex, _r_ex, _ = simulate_rl_reach(_dw, 10.0, _ap, 0.25)
            _tag = "CLEAN" if _d_ex == "Clean Reach" else ("LAZY " if "Lazy" in _d_ex else "OSCIL")
            _row_str += f"[act={_ap:.2f} -> {_tag} ({_r_ex:5.1f})]  "
        print(_row_str)

    _, _, _, _, _d_far, _, _dist_far = simulate_rl_reach(0.1, 12.0, 0.2, 0.2, start_pos=(-1.0, -1.0))
    print(f"\nSparse-ish curriculum check from (-1, -1): {_d_far}, final dist={_dist_far:.2f} m")
    return


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