# /// 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.4: Rigid-Body Equations of Motion

    Let's unpack the classic multi-joint manipulator equation piece by piece for a 2-link planar arm:

    $$M(q)\ddot{q} + C(q, \dot{q})\dot{q} + g(q) = \tau$$

    You can inspect how bending the elbow ($q_2$) transforms the shoulder's effective inertia $M_{11}(q)$, and evaluate the exact inverse dynamics torque split across inertia, Coriolis/centrifugal coupling, and gravity.
    """)
    return


@app.cell
def _(np):
    def two_link_dynamics_terms(q1, q2, dq1, dq2, ddq1, ddq2, m1=2.0, m2=1.5, l1=0.6, l2=0.5, g=9.81):
        """Compute M(q), C(q, dq)@dq, g(q), and total inverse dynamics torque tau for a 2-link point-mass arm."""
        c2 = np.cos(q2)
        s2 = np.sin(q2)

        # Mass/Inertia matrix M(q)
        m11 = m1 * l1 ** 2 + m2 * (l1 ** 2 + l2 ** 2 + 2 * l1 * l2 * c2)
        m12 = m2 * (l2 ** 2 + l1 * l2 * c2)
        m22 = m2 * (l2 ** 2)
        M = np.array([[m11, m12], [m12, m22]], dtype=float)

        # Coriolis and centrifugal coupling C(q, dq) @ dq
        h = -m2 * l1 * l2 * s2
        c_vec = np.array([
            h * (2.0 * dq1 * dq2 + dq2 ** 2),
            -h * (dq1 ** 2),
        ], dtype=float)

        # Gravity vector g(q) (q1 measured from horizontal +X, upward +Y)
        g1 = (m1 + m2) * g * l1 * np.cos(q1) + m2 * g * l2 * np.cos(q1 + q2)
        g2 = m2 * g * l2 * np.cos(q1 + q2)
        g_vec = np.array([g1, g2], dtype=float)

        ddq = np.array([ddq1, ddq2], dtype=float)
        inertial_tau = M @ ddq
        total_tau = inertial_tau + c_vec + g_vec

        return {
            "M": M,
            "inertial_tau": inertial_tau,
            "coriolis_tau": c_vec,
            "gravity_tau": g_vec,
            "total_tau": total_tau,
        }

    return (two_link_dynamics_terms,)


@app.cell
def _(mo):
    q1_ui = mo.ui.slider(-90, 90, step=5, value=15, label="Shoulder q₁ (deg)")
    q2_ui = mo.ui.slider(-160, 160, step=5, value=30, label="Elbow q₂ (deg)")
    dq1_ui = mo.ui.slider(-4.0, 4.0, step=0.2, value=1.5, label="Shoulder vel q̇₁ (rad/s)")
    dq2_ui = mo.ui.slider(-4.0, 4.0, step=0.2, value=1.0, label="Elbow vel q̇₂ (rad/s)")
    ddq1_ui = mo.ui.slider(-10.0, 10.0, step=0.5, value=3.0, label="Shoulder accel q̈₁ (rad/s²)")

    mo.vstack([
        mo.hstack([q1_ui, q2_ui], justify="start"),
        mo.hstack([dq1_ui, dq2_ui, ddq1_ui], justify="start"),
    ])
    return ddq1_ui, dq1_ui, dq2_ui, q1_ui, q2_ui


@app.cell
def _(ddq1_ui, dq1_ui, dq2_ui, mo, np, plt, q1_ui, q2_ui, two_link_dynamics_terms):
    _q1 = np.deg2rad(float(q1_ui.value))
    _q2 = np.deg2rad(float(q2_ui.value))
    _res = two_link_dynamics_terms(
        _q1, _q2, float(dq1_ui.value), float(dq2_ui.value), float(ddq1_ui.value), 0.0
    )

    _q2_sweep = np.linspace(-160, 160, 65)
    _m11_curve = [
        two_link_dynamics_terms(_q1, np.deg2rad(_a), 0, 0, 0, 0)["M"][0, 0]
        for _a in _q2_sweep
    ]

    _fig, (_ax1, _ax2) = plt.subplots(1, 2, figsize=(10.5, 3.8))

    # Left: M11(q2) variation
    _ax1.plot(_q2_sweep, _m11_curve, lw=2.3, color="#2563eb")
    _ax1.scatter([float(q2_ui.value)], [_res["M"][0, 0]], s=80, color="#dc2626", zorder=5)
    _ax1.set_xlabel("Elbow Angle q₂ (deg)")
    _ax1.set_ylabel("Shoulder Effective Inertia M₁₁(q) (kg·m²)")
    _ax1.set_title(f"Configuration-Dependent Inertia: M₁₁ = {_res['M'][0, 0]:.2f} kg·m²")
    _ax1.grid(True, alpha=0.25)

    # Right: Shoulder torque budget bar chart
    _labels = ["M(q)q̈\n(Inertia)", "C(q,q̇)q̇\n(Coriolis)", "g(q)\n(Gravity)", "Total τ₁"]
    _vals = [
        _res["inertial_tau"][0],
        _res["coriolis_tau"][0],
        _res["gravity_tau"][0],
        _res["total_tau"][0],
    ]
    _colors = ["#2563eb", "#d97706", "#dc2626", "#111827"]
    _ax2.bar(_labels, _vals, color=_colors, width=0.55)
    _ax2.axhline(0, color="#6b7280", lw=1)
    _ax2.set_ylabel("Shoulder Torque (N·m)")
    _ax2.set_title("Inverse Dynamics Shoulder Torque Breakdown")
    _ax2.grid(True, axis="y", alpha=0.25)

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


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

    1. **Folded vs. stretched inertia ratio:** Compare `M[0, 0]` when the elbow is straight (`q2 = 0°`) vs. tucked tightly (`q2 = 150°`).
    2. **Forward dynamics check:** Given `tau = np.array([15.0, 2.0])` at `(q1=0, q2=0.5, dq1=0, dq2=0)`, compute `ddq = np.linalg.solve(M, tau - c_vec - g_vec)` and verify plugging `ddq` back into `two_link_dynamics_terms` reproduces `tau`.
    """)
    return


@app.cell
def _(np, two_link_dynamics_terms):
    # Exercise sandbox — edit and run!
    _straight = two_link_dynamics_terms(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)["M"][0, 0]
    _tucked = two_link_dynamics_terms(0.0, np.deg2rad(150.0), 0.0, 0.0, 0.0, 0.0)["M"][0, 0]
    print(f"Shoulder inertia M11 -> Straight: {_straight:.3f} kg·m² | Tucked (150°): {_tucked:.3f} kg·m²")

    _dyn = two_link_dynamics_terms(0.0, 0.5, 0.0, 0.0, 0.0, 0.0)
    _tau_cmd = np.array([15.0, 2.0])
    _ddq_fwd = np.linalg.solve(_dyn["M"], _tau_cmd - _dyn["coriolis_tau"] - _dyn["gravity_tau"])
    _check = two_link_dynamics_terms(0.0, 0.5, 0.0, 0.0, _ddq_fwd[0], _ddq_fwd[1])["total_tau"]
    print(f"Forward accel ddq = {_ddq_fwd.round(3)} rad/s²  |  Inverse check tau = {_check.round(3)} N·m")
    return


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