# /// 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 3.5: Trajectory Smoothing and Time Parameterization

    A geometric path tells a robot **where** to go; a trajectory specifies **when** to be there so motors stay inside velocity, acceleration, and jerk limits. Compare a time-optimal **Trapezoidal** profile against a smooth **Minimum-Jerk (Quintic)** spline.
    """)
    return


@app.cell
def _(np):
    def trapezoidal_profile(delta_q, v_max, a_max, n_pts=250):
        """Compute time-optimal trapezoidal (or triangular) velocity profile."""
        d_ramp = (v_max ** 2) / a_max
        is_triangular = delta_q < d_ramp
        t_acc = np.sqrt(delta_q / a_max) if is_triangular else v_max / a_max
        t_cruise = 0.0 if is_triangular else (delta_q - d_ramp) / v_max
        T = 2.0 * t_acc + t_cruise

        t = np.linspace(0.0, T, n_pts)
        q = np.zeros_like(t)
        v = np.zeros_like(t)
        a = np.zeros_like(t)

        for i, ti in enumerate(t):
            if ti < t_acc:
                q[i] = 0.5 * a_max * ti ** 2
                v[i] = a_max * ti
                a[i] = a_max
            elif ti < t_acc + t_cruise:
                q[i] = 0.5 * a_max * t_acc ** 2 + v_max * (ti - t_acc)
                v[i] = v_max
                a[i] = 0.0
            else:
                tr = max(0.0, T - ti)
                q[i] = delta_q - 0.5 * a_max * tr ** 2
                v[i] = a_max * tr
                a[i] = -a_max

        j = np.gradient(a, t)
        return t, q, v, a, j, T, is_triangular

    def minimum_jerk_profile(delta_q, v_max, a_max, n_pts=250):
        """Compute minimum-jerk quintic polynomial scaled to respect v_max and a_max."""
        t_v = 1.875 * delta_q / v_max
        t_a = np.sqrt((10.0 / np.sqrt(3.0)) * delta_q / a_max)
        T = max(t_v, t_a)

        t = np.linspace(0.0, T, n_pts)
        tau = t / T
        q = delta_q * (10.0 * tau ** 3 - 15.0 * tau ** 4 + 6.0 * tau ** 5)
        v = (delta_q / T) * (30.0 * tau ** 2 - 60.0 * tau ** 3 + 30.0 * tau ** 4)
        a = (delta_q / (T ** 2)) * (60.0 * tau - 180.0 * tau ** 2 + 120.0 * tau ** 3)
        j = (delta_q / (T ** 3)) * (60.0 - 360.0 * tau + 360.0 * tau ** 2)
        return t, q, v, a, j, T

    return minimum_jerk_profile, trapezoidal_profile


@app.cell
def _(mo):
    mode_dd = mo.ui.dropdown(["Trapezoidal", "Minimum-Jerk (Quintic)", "Overlay Both"], value="Overlay Both", label="Profile")
    dq_s = mo.ui.slider(0.4, 6.0, step=0.1, value=2.5, label="Distance Δq (m)")
    vmax_s = mo.ui.slider(0.5, 4.0, step=0.1, value=1.5, label="v_max (m/s)")
    amax_s = mo.ui.slider(0.5, 6.0, step=0.1, value=2.0, label="a_max (m/s²)")

    mo.vstack([
        mo.hstack([mode_dd, dq_s], justify="start"),
        mo.hstack([vmax_s, amax_s], justify="start"),
    ])
    return amax_s, dq_s, mode_dd, vmax_s


@app.cell
def _(amax_s, dq_s, minimum_jerk_profile, mo, mode_dd, plt, trapezoidal_profile, vmax_s):
    _dq, _vmax, _amax = dq_s.value, vmax_s.value, amax_s.value
    _t_trap, _q_trap, _v_trap, _a_trap, _j_trap, _T_trap, _is_tri = trapezoidal_profile(_dq, _vmax, _amax)
    _t_q, _q_q, _v_q, _a_q, _j_q, _T_q = minimum_jerk_profile(_dq, _vmax, _amax)

    _fig, _axes = plt.subplots(4, 1, figsize=(8.5, 7.2), sharex=True)
    _labels = ["Position q (m)", "Velocity v (m/s)", "Accel a (m/s²)", "Jerk j (m/s³)"]
    _trap_curves = [_q_trap, _v_trap, _a_trap, _j_trap]
    _q_curves = [_q_q, _v_q, _a_q, _j_q]

    for _idx, _ax in enumerate(_axes):
        if mode_dd.value in ("Trapezoidal", "Overlay Both"):
            _ax.plot(_t_trap, _trap_curves[_idx], color="#2563eb", lw=2.2, label="Trapezoidal")
        if mode_dd.value in ("Minimum-Jerk (Quintic)", "Overlay Both"):
            _ax.plot(_t_q, _q_curves[_idx], color="#16a34a", lw=2.2, ls="--" if mode_dd.value == "Overlay Both" else "-", label="Minimum-Jerk")
        if _idx == 1:
            _ax.axhline(_vmax, color="#9ca3af", ls=":", lw=1.2)
        if _idx == 2:
            _ax.axhline(_amax, color="#9ca3af", ls=":", lw=1.2)
            _ax.axhline(-_amax, color="#9ca3af", ls=":", lw=1.2)
        _ax.set_ylabel(_labels[_idx], fontsize=9)
        _ax.grid(True, alpha=0.25)

    _axes[0].legend(loc="upper left", fontsize=8)
    _axes[-1].set_xlabel("Time t (s)")
    _tri_note = " (Triangular)" if _is_tri else ""
    _axes[0].set_title(
        f"Trapezoidal T = {_T_trap:.2f} s{_tri_note}  |  Minimum-Jerk T = {_T_q:.2f} s"
    )
    _fig.tight_layout()

    mo.vstack([_fig])
    return


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

    1. **Triangular collapse:** Set `Δq = 0.6`, `v_max = 2.0`, `a_max = 1.5`. Verify why `Δq < v_max² / a_max` prevents the trapezoidal profile from ever reaching `v_max`.
    2. **Compare smoothness numerically:** Compute the peak velocity, peak acceleration, and integrated squared jerk $\int j(t)^2\,dt$ of the minimum-jerk curve in the cell below.
    """)
    return


@app.cell
def _(minimum_jerk_profile, np, trapezoidal_profile):
    # Exercise sandbox — edit and run!
    _t1, _q1, _v1, _a1, _j1, _T1, _tri1 = trapezoidal_profile(0.6, 2.0, 1.5)
    print(f"Short move trapezoidal: T = {_T1:.3f} s, triangular = {_tri1}, peak v = {_v1.max():.3f} m/s")

    _t2, _q2, _v2, _a2, _j2, _T2 = minimum_jerk_profile(2.5, 1.5, 2.0)
    _jerk_cost = float(np.sum(_j2 ** 2) * (_t2[1] - _t2[0]))
    print(f"Minimum-jerk move: T = {_T2:.3f} s, peak |v| = {np.abs(_v2).max():.3f}, peak |a| = {np.abs(_a2).max():.3f}, ∫j²dt = {_jerk_cost:.2f}")
    return


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