# /// 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.2: PID Control Intuition & Practical Tuning

    In this notebook, we dissect the three pieces of a PID controller — **P** (spring), **I** (droop remover), and **D** (shock absorber) — and test what happens when encoder noise enters the derivative term or integral windup hits a saturated motor.
    """)
    return


@app.cell
def _(np):
    def simulate_pid(
        kp=28.0,
        ki=12.0,
        kd=4.0,
        encoder_noise_deg=0.0,
        anti_windup=True,
        max_torque=40.0,
        target_deg=25.0,
        duration=4.0,
        dt=0.005,
        seed=42,
    ):
        """Simulate 1-link arm under PID control with optional encoder noise and anti-windup."""
        rng = np.random.default_rng(seed)
        m, length, g = 1.2, 0.7, 9.81
        inertia = 0.65
        b_viscous = 0.35

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

        steps = int(round(duration / dt))
        times = np.linspace(0.0, duration, steps + 1)
        thetas_deg = np.zeros(steps + 1)
        tau_p_hist = np.zeros(steps + 1)
        tau_i_hist = np.zeros(steps + 1)
        tau_d_hist = np.zeros(steps + 1)
        tau_tot_hist = np.zeros(steps + 1)

        noise_std_rad = np.deg2rad(encoder_noise_deg)

        for _k in range(steps + 1):
            thetas_deg[_k] = np.rad2deg(theta)
            meas = theta + (rng.normal(0.0, noise_std_rad) if noise_std_rad > 0 else 0.0)
            err = target_rad - meas
            vel_est = (meas - prev_meas) / dt if _k > 0 else 0.0
            prev_meas = meas

            tau_p = kp * err
            tau_i = ki * integral
            tau_d = -kd * vel_est
            raw_tau = tau_p + tau_i + tau_d
            tau_cmd = float(np.clip(raw_tau, -max_torque, max_torque))

            tau_p_hist[_k] = tau_p
            tau_i_hist[_k] = tau_i
            tau_d_hist[_k] = tau_d
            tau_tot_hist[_k] = tau_cmd

            if _k == steps:
                break

            sat_hi = raw_tau >= max_torque and err > 0
            sat_lo = raw_tau <= -max_torque and err < 0
            if not anti_windup or (not sat_hi and not sat_lo):
                integral += err * dt
                if anti_windup:
                    integral = float(np.clip(integral, -2.5, 2.5))

            tau_grav = m * g * length * np.cos(theta)
            alpha = (tau_cmd - tau_grav - b_viscous * omega) / inertia
            omega += alpha * dt
            theta += omega * dt

        return times, thetas_deg, tau_p_hist, tau_i_hist, tau_d_hist, tau_tot_hist

    return (simulate_pid,)


@app.cell
def _(mo):
    kp_ui = mo.ui.slider(0, 60, step=1, value=28, label="Kp (Proportional)")
    ki_ui = mo.ui.slider(0, 30, step=1, value=14, label="Ki (Integral)")
    kd_ui = mo.ui.slider(0, 10, step=0.2, value=4.0, label="Kd (Derivative)")
    noise_ui = mo.ui.slider(0.0, 0.5, step=0.05, value=0.0, label="Encoder noise σ (deg)")
    windup_ui = mo.ui.checkbox(value=True, label="Enable anti-windup clamp")

    mo.vstack([
        mo.hstack([kp_ui, kd_ui, ki_ui], justify="start"),
        mo.hstack([noise_ui, windup_ui], justify="start"),
    ])
    return kd_ui, ki_ui, kp_ui, noise_ui, windup_ui


@app.cell
def _(kd_ui, ki_ui, kp_ui, mo, noise_ui, np, plt, simulate_pid, windup_ui):
    _t, _th, _tp, _ti, _td, _ttot = simulate_pid(
        kp=float(kp_ui.value),
        ki=float(ki_ui.value),
        kd=float(kd_ui.value),
        encoder_noise_deg=float(noise_ui.value),
        anti_windup=bool(windup_ui.value),
    )

    _overshoot = max(0.0, float(np.max(_th)) - 25.0)
    _ss_err = 25.0 - float(_th[-1])

    _fig, (_ax1, _ax2) = plt.subplots(1, 2, figsize=(10.5, 4))
    _ax1.plot(_t, _th, lw=2.3, color="#2563eb", label="θ(t)")
    _ax1.axhline(25.0, ls="--", color="#16a34a", lw=1.5, label="Target (+25°)")
    _ax1.set_ylim(-90, 65)
    _ax1.set_xlabel("Time (s)")
    _ax1.set_ylabel("Angle (deg)")
    _ax1.set_title(f"Step Response | Overshoot: {_overshoot:.1f}° | SS Err: {_ss_err:+.2f}°")
    _ax1.grid(True, alpha=0.25)
    _ax1.legend(loc="lower right", fontsize=8)

    _ax2.plot(_t, _tp, lw=1.4, label="P term", alpha=0.85)
    _ax2.plot(_t, _ti, lw=1.4, label="I term", alpha=0.85)
    _ax2.plot(_t, _td, lw=1.4, label="D term", alpha=0.75)
    _ax2.plot(_t, _ttot, lw=2.0, color="#111827", label="Clamped Total τ")
    _ax2.set_xlabel("Time (s)")
    _ax2.set_ylabel("Torque (N·m)")
    _ax2.set_title("PID Torque Breakdown")
    _ax2.grid(True, alpha=0.25)
    _ax2.legend(loc="upper right", fontsize=8)

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


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

    1. **Derivative noise amplification:** Compare `encoder_noise_deg=0.2` with `kd=1.0` vs. `kd=8.0`. Compute the standard deviation of `tau_tot` in the final second (`t >= 3.0 s`).
    2. **Anti-windup check:** Lower `max_torque` to `12.0` N·m and compare `anti_windup=False` vs. `anti_windup=True` when `ki=25.0`.
    """)
    return


@app.cell
def _(np, plt, simulate_pid):
    # Exercise sandbox — edit and run!
    _t_n, _, _, _, _, _tau_low_d = simulate_pid(kp=28, ki=12, kd=1.0, encoder_noise_deg=0.2)
    _, _, _, _, _, _tau_hi_d = simulate_pid(kp=28, ki=12, kd=8.0, encoder_noise_deg=0.2)
    _mask = _t_n >= 3.0
    print(f"Steady torque jitter std -> Kd=1.0: {np.std(_tau_low_d[_mask]):.2f} N·m | Kd=8.0: {np.std(_tau_hi_d[_mask]):.2f} N·m")

    _fig_ex, _ax_ex = plt.subplots(figsize=(6.5, 3.2))
    _ax_ex.plot(_t_n[_mask], _tau_hi_d[_mask], lw=1.0, color="#dc2626", alpha=0.75, label="Kd = 8.0 (noisy)")
    _ax_ex.plot(_t_n[_mask], _tau_low_d[_mask], lw=1.5, color="#2563eb", label="Kd = 1.0 (calm)")
    _ax_ex.set_xlabel("Time (s)")
    _ax_ex.set_ylabel("Motor Torque (N·m)")
    _ax_ex.set_title("Exercise: Derivative Gain Amplifies Encoder Noise")
    _ax_ex.grid(True, alpha=0.25)
    _ax_ex.legend(fontsize=8)
    _fig_ex
    return


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