# /// 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 4.1: Open-Loop vs. Closed-Loop Feedback

    Welcome to **Module 4.1**. Here we simulate a real gravity-loaded single-link robot arm to see why blind open-loop motor torques sag when the payload changes or someone bumps the link — and how closing a feedback loop with an error signal fixes it.
    """)
    return


@app.cell
def _(np):
    def simulate_open_vs_closed(
        mode="closed",
        kp=24.0,
        kd=3.5,
        payload_extra_kg=0.0,
        disturbance_poke=False,
        target_deg=25.0,
        duration=4.0,
        dt=0.005,
    ):
        """Simulate a 1-link arm under open-loop (calibrated torque) vs closed-loop PD control."""
        m_nominal = 1.2
        m_total = m_nominal + payload_extra_kg
        length = 0.7
        g = 9.81
        inertia = 0.65 + payload_extra_kg * (length ** 2)
        b_viscous = 0.35

        target_rad = np.deg2rad(target_deg)
        theta = np.deg2rad(-60.0)
        omega = 0.0

        # Open-loop assumes nominal mass at target angle (blind guess!)
        tau_open_guess = m_nominal * g * length * np.cos(target_rad)

        steps = int(round(duration / dt))
        times = np.linspace(0.0, duration, steps + 1)
        thetas_deg = np.zeros(steps + 1)
        torques = np.zeros(steps + 1)

        for _k in range(steps + 1):
            t_now = times[_k]
            thetas_deg[_k] = np.rad2deg(theta)

            if mode == "open":
                tau_motor = tau_open_guess
            else:
                err = target_rad - theta
                tau_motor = float(np.clip(kp * err - kd * omega, -40.0, 40.0))

            torques[_k] = tau_motor
            if _k == steps:
                break

            tau_dist = -9.0 if (disturbance_poke and 2.0 <= t_now <= 2.35) else 0.0
            tau_grav = m_total * g * length * np.cos(theta)
            alpha = (tau_motor - tau_grav - b_viscous * omega + tau_dist) / inertia

            # Midpoint (RK2) step
            theta_mid = theta + 0.5 * dt * omega
            omega_mid = omega + 0.5 * dt * alpha
            if mode == "open":
                tau_mid = tau_open_guess
            else:
                tau_mid = float(np.clip(kp * (target_rad - theta_mid) - kd * omega_mid, -40.0, 40.0))
            tau_grav_mid = m_total * g * length * np.cos(theta_mid)
            alpha_mid = (tau_mid - tau_grav_mid - b_viscous * omega_mid + tau_dist) / inertia

            theta += dt * omega_mid
            omega += dt * alpha_mid

        return times, thetas_deg, torques

    return (simulate_open_vs_closed,)


@app.cell
def _(mo):
    control_mode = mo.ui.dropdown(
        {"Closed-Loop Feedback (PD)": "closed", "Open-Loop (Fixed Calibrated Torque)": "open"},
        value="Closed-Loop Feedback (PD)",
        label="Controller Mode",
    )
    kp_slider = mo.ui.slider(0, 60, step=2, value=24, label="Feedback Gain Kp")
    extra_payload = mo.ui.slider(0.0, 1.0, step=0.1, value=0.0, label="Extra Gripper Payload (kg)")
    poke_toggle = mo.ui.checkbox(value=True, label="Inject disturbance poke at t = 2.0 s")

    mo.vstack([
        mo.hstack([control_mode, poke_toggle], justify="start"),
        mo.hstack([kp_slider, extra_payload], justify="start"),
    ])
    return control_mode, extra_payload, kp_slider, poke_toggle


@app.cell
def _(
    control_mode,
    extra_payload,
    kp_slider,
    mo,
    plt,
    poke_toggle,
    simulate_open_vs_closed,
):
    _t, _th, _tau = simulate_open_vs_closed(
        mode=control_mode.value,
        kp=float(kp_slider.value),
        kd=3.5,
        payload_extra_kg=float(extra_payload.value),
        disturbance_poke=bool(poke_toggle.value),
    )

    _fig, (_ax1, _ax2) = plt.subplots(1, 2, figsize=(10, 4))
    _ax1.plot(_t, _th, lw=2.3, color="#2563eb", label="Measured θ(t)")
    _ax1.axhline(25.0, ls="--", color="#16a34a", lw=1.5, label="Target (+25°)")
    if poke_toggle.value:
        _ax1.axvspan(2.0, 2.35, color="#dc2626", alpha=0.15, label="Poke disturbance")
    _ax1.set_ylim(-100, 60)
    _ax1.set_xlabel("Time (s)")
    _ax1.set_ylabel("Angle (deg)")
    _ax1.set_title(f"Arm Angle ({control_mode.value.upper()})  |  Final err = {25.0 - _th[-1]:+.1f}°")
    _ax1.grid(True, alpha=0.25)
    _ax1.legend(loc="lower right", fontsize=8)

    _ax2.plot(_t, _tau, lw=2.0, color="#dc2626")
    _ax2.set_xlabel("Time (s)")
    _ax2.set_ylabel("Motor Torque (N·m)")
    _ax2.set_title("Commanded Motor Torque")
    _ax2.grid(True, alpha=0.25)

    plt.tight_layout()
    mo.vstack([_fig])
    return


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

    1. **Payload mismatch test:** Run `simulate_open_vs_closed` with `payload_extra_kg=0.5` in both `"open"` and `"closed"` modes (no poke) and compare their final steady-state angles.
    2. **Gain vs. droop curve:** Sweep `kp` from `5` to `60` in `"closed"` mode with `payload_extra_kg=0.0` and plot the steady-state error `25.0 - thetas[-1]` vs. `kp`.
    """)
    return


@app.cell
def _(np, plt, simulate_open_vs_closed):
    # Exercise sandbox — edit and run!
    _, _th_open, _ = simulate_open_vs_closed(mode="open", payload_extra_kg=0.5, disturbance_poke=False)
    _, _th_closed, _ = simulate_open_vs_closed(mode="closed", kp=30.0, payload_extra_kg=0.5, disturbance_poke=False)
    print(f"With +0.5 kg payload -> Open-loop settled at {_th_open[-1]:.1f}°, Closed-loop at {_th_closed[-1]:.1f}°")

    _kp_vals = np.linspace(5, 60, 12)
    _errs = []
    for _kp in _kp_vals:
        _, _th_sweep, _ = simulate_open_vs_closed(mode="closed", kp=float(_kp), kd=3.5, disturbance_poke=False)
        _errs.append(25.0 - _th_sweep[-1])

    _fig_ex, _ax_ex = plt.subplots(figsize=(6, 3.4))
    _ax_ex.plot(_kp_vals, _errs, "-o", color="#2563eb")
    _ax_ex.set_xlabel("Proportional Gain Kp")
    _ax_ex.set_ylabel("Steady-State Droop (deg)")
    _ax_ex.set_title("Exercise: Higher Kp Shrinks Gravity Droop")
    _ax_ex.grid(True, alpha=0.25)
    _fig_ex
    return


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