# /// 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.5: Feedforward & Compliant Impedance Control

    Instead of fighting physical surfaces with stiff high-gain position servos, we combine **gravity compensation feedforward** with a **virtual spring-damper** ($F = K(x_{\text{target}} - x) - B\dot{x}$) so the robot touches walls gently and safely.
    """)
    return


@app.cell
def _(np):
    def simulate_wall_contact(
        mode="compliant",
        wall_x=0.55,
        target_x=0.60,
        stiffness_k=220.0,
        damping_b=28.0,
        approach_vel=0.30,
        duration=1.2,
        dt=0.002,
    ):
        """Simulate a 1D effective-mass end-effector moving into a rigid virtual wall."""
        m_eff = 1.6
        k_wall = 12000.0
        max_force = 180.0

        k_ctrl = 4000.0 if mode == "stiff" else stiffness_k
        b_ctrl = 24.0 if mode == "stiff" else damping_b

        x = min(target_x, wall_x) - 0.02
        v = approach_vel

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

        for _k in range(steps + 1):
            penetration = max(0.0, x - wall_x)
            f_wall = k_wall * penetration
            f_ctrl = float(np.clip(k_ctrl * (target_x - x) - b_ctrl * v, -max_force, max_force))

            x_hist[_k] = x
            f_contact_hist[_k] = min(max_force, f_wall)
            if _k == steps:
                break

            accel = (f_ctrl - f_wall) / m_eff
            v += accel * dt
            x += v * dt

        return times, x_hist, f_contact_hist

    return (simulate_wall_contact,)


@app.cell
def _(mo):
    mode_ui = mo.ui.dropdown(
        {"Stiff Position Control": "stiff", "Compliant Impedance Control": "compliant"},
        value="Compliant Impedance Control",
        label="Controller Mode",
    )
    wall_ui = mo.ui.slider(0.45, 0.65, step=0.01, value=0.55, label="Wall X position (target = 0.60 m)")
    k_ui = mo.ui.slider(50, 800, step=10, value=220, label="Virtual Stiffness K (N/m)")
    b_ui = mo.ui.slider(4, 80, step=2, value=28, label="Virtual Damping B (N·s/m)")

    mo.vstack([
        mo.hstack([mode_ui, wall_ui], justify="start"),
        mo.hstack([k_ui, b_ui], justify="start"),
    ])
    return b_ui, k_ui, mode_ui, wall_ui


@app.cell
def _(b_ui, k_ui, mo, mode_ui, np, plt, simulate_wall_contact, wall_ui):
    _t, _x_c, _f_c = simulate_wall_contact(
        mode=mode_ui.value,
        wall_x=float(wall_ui.value),
        stiffness_k=float(k_ui.value),
        damping_b=float(b_ui.value),
    )
    _, _, _f_stiff = simulate_wall_contact(mode="stiff", wall_x=float(wall_ui.value))

    _steady_f = float(_f_c[-1])
    _peak_f = float(np.max(_f_c))

    _fig, (_ax1, _ax2) = plt.subplots(1, 2, figsize=(10.5, 3.8))
    _ax1.plot(_t, _x_c, lw=2.2, color="#2563eb", label="End-effector X(t)")
    _ax1.axhline(0.60, ls="--", color="#16a34a", lw=1.4, label="Target (0.60 m)")
    _ax1.axhline(float(wall_ui.value), ls=":", color="#dc2626", lw=1.6, label=f"Wall ({wall_ui.value:.2f} m)")
    _ax1.set_xlabel("Time (s)")
    _ax1.set_ylabel("Position X (m)")
    _ax1.set_title("End-Effector Motion Into Wall")
    _ax1.grid(True, alpha=0.25)
    _ax1.legend(loc="lower right", fontsize=8)

    _ax2.plot(_t, _f_c, lw=2.3, color="#2563eb" if mode_ui.value == "compliant" else "#dc2626", label=f"Active ({mode_ui.value})")
    if mode_ui.value == "compliant":
        _ax2.plot(_t, _f_stiff, lw=1.3, ls="--", color="#dc2626", alpha=0.65, label="Stiff baseline")
    _ax2.axhline(35.0, ls=":", color="#16a34a", lw=1.2, label="Safe threshold (35 N)")
    _ax2.set_xlabel("Time (s)")
    _ax2.set_ylabel("Contact Force (N)")
    _ax2.set_title(f"Steady: {_steady_f:.1f} N  |  Peak Impact: {_peak_f:.1f} N")
    _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. **Critical damping tuning:** For `m_eff = 1.6 kg` and `stiffness_k = 220 N/m`, compute the critical damping $B_{\text{crit}} = 2 \sqrt{K m_{\text{eff}}}$ and test `damping_b = 5` vs. `B_crit` in `simulate_wall_contact`.
    2. **Force vs. stiffness sweep:** With `wall_x = 0.54` (6 cm deflection), sweep `stiffness_k` from `50` to `800` N/m and plot steady-state contact force.
    """)
    return


@app.cell
def _(np, plt, simulate_wall_contact):
    # Exercise sandbox — edit and run!
    _b_crit = 2.0 * np.sqrt(220.0 * 1.6)
    _t_e, _, _f_under = simulate_wall_contact(mode="compliant", wall_x=0.55, stiffness_k=220, damping_b=5.0)
    _, _, _f_crit = simulate_wall_contact(mode="compliant", wall_x=0.55, stiffness_k=220, damping_b=float(_b_crit))
    print(f"Critical damping B_crit = {_b_crit:.1f} N·s/m | Peak force underdamped: {np.max(_f_under):.1f} N vs critically damped: {np.max(_f_crit):.1f} N")

    _fig_ex, _ax_ex = plt.subplots(figsize=(6.5, 3.2))
    _ax_ex.plot(_t_e, _f_under, color="#dc2626", lw=1.8, label="Underdamped (B = 5)")
    _ax_ex.plot(_t_e, _f_crit, color="#16a34a", lw=2.0, label=f"Critically damped (B = {_b_crit:.1f})")
    _ax_ex.set_xlabel("Time (s)")
    _ax_ex.set_ylabel("Contact Force (N)")
    _ax_ex.set_title("Exercise: Damping B Tames Impact Bounce")
    _ax_ex.grid(True, alpha=0.25)
    _ax_ex.legend(fontsize=8)
    _fig_ex
    return


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