# /// 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 2.4: Differential Kinematics and Jacobians

    The Jacobian matrix `J(q)` translates joint speeds `q̇` into end-effector velocity `v = J(q) q̇`. Looking at the singular values of `J(q)` draws the **velocity manipulability ellipse** — and reveals why trying to invert `J` directly near a stretched-out singularity causes motor speeds to explode.
    """)
    return


@app.cell
def _(np):
    def fk_2link(t1_deg, t2_deg, l1=0.95, l2=0.78):
        r1 = np.deg2rad(t1_deg)
        r12 = np.deg2rad(t1_deg + t2_deg)
        elbow = np.array([l1 * np.cos(r1), l1 * np.sin(r1)])
        tip = elbow + np.array([l2 * np.cos(r12), l2 * np.sin(r12)])
        return elbow, tip

    def jacobian_2link(t1_deg, t2_deg, l1=0.95, l2=0.78):
        """Exact 2x2 planar velocity Jacobian J(q)."""
        r1 = np.deg2rad(t1_deg)
        r12 = np.deg2rad(t1_deg + t2_deg)
        return np.array([
            [-l1 * np.sin(r1) - l2 * np.sin(r12), -l2 * np.sin(r12)],
            [l1 * np.cos(r1) + l2 * np.cos(r12), l2 * np.cos(r12)],
        ])

    def manipulability_ellipse(J):
        """Compute singular values and principal axis angle from J @ J.T."""
        U, S, _ = np.linalg.svd(J)
        angle_rad = np.arctan2(U[1, 0], U[0, 0])
        return S[0], S[1], angle_rad

    def solve_joint_velocities(J, v_des, lam=0.12):
        """Compare un-damped J^-1 v against Damped Least Squares (DLS)."""
        try:
            qdot_raw = np.linalg.solve(J, v_des)
        except np.linalg.LinAlgError:
            qdot_raw = np.array([np.inf, np.inf])
        qdot_dls = J.T @ np.linalg.solve(J @ J.T + (lam**2) * np.eye(2), v_des)
        return qdot_raw, qdot_dls

    return fk_2link, jacobian_2link, manipulability_ellipse, solve_joint_velocities


@app.cell
def _(mo):
    t1_s = mo.ui.slider(-140, 140, step=2, value=30, label="Shoulder θ₁ (deg)")
    t2_s = mo.ui.slider(-170, 170, step=1, value=60, label="Elbow θ₂ (deg)")
    vx_s = mo.ui.slider(-1.0, 1.0, step=0.05, value=0.4, label="Desired vₓ (m/s)")
    vy_s = mo.ui.slider(-1.0, 1.0, step=0.05, value=0.2, label="Desired vᵧ (m/s)")
    lam_s = mo.ui.slider(0.01, 0.40, step=0.01, value=0.12, label="Damping λ (DLS)")

    mo.vstack([
        mo.hstack([t1_s, t2_s, lam_s], justify="start"),
        mo.hstack([vx_s, vy_s], justify="start"),
    ])
    return lam_s, t1_s, t2_s, vx_s, vy_s


@app.cell
def _(
    fk_2link,
    jacobian_2link,
    lam_s,
    manipulability_ellipse,
    mo,
    np,
    plt,
    solve_joint_velocities,
    t1_s,
    t2_s,
    vx_s,
    vy_s,
):
    _elbow, _tip = fk_2link(t1_s.value, t2_s.value)
    _J = jacobian_2link(t1_s.value, t2_s.value)
    _s_max, _s_min, _ang = manipulability_ellipse(_J)
    _v_des = np.array([vx_s.value, vy_s.value])
    _qdot_raw, _qdot_dls = solve_joint_velocities(_J, _v_des, lam=lam_s.value)

    _ts = np.linspace(0, 2 * np.pi, 100)
    _scale_e = 0.25
    _ex = _scale_e * _s_max * np.cos(_ts)
    _ey = _scale_e * _s_min * np.sin(_ts)
    _rx = _tip[0] + _ex * np.cos(_ang) - _ey * np.sin(_ang)
    _ry = _tip[1] + _ex * np.sin(_ang) + _ey * np.cos(_ang)

    _fig, (_ax1, _ax2) = plt.subplots(1, 2, figsize=(9.6, 4.2))
    _ax1.add_patch(plt.Circle((0, 0), 1.73, color="#9ca3af", fill=False, ls="--", alpha=0.5))
    _ax1.fill(_rx, _ry, color="#16a34a", alpha=0.22, label="Manipulability ellipse")
    _ax1.plot(_rx, _ry, color="#16a34a", lw=1.8)
    _ax1.plot([0, _elbow[0], _tip[0]], [0, _elbow[1], _tip[1]], "-o", lw=3.2, ms=7, color="#111827")
    _ax1.quiver(_tip[0], _tip[1], _v_des[0], _v_des[1], angles="xy", scale_units="xy", scale=2.2, color="#dc2626", label="v_des")
    _ax1.set_aspect("equal")
    _ax1.set_xlim(-1.95, 1.95)
    _ax1.set_ylim(-1.95, 1.95)
    _ax1.grid(True, alpha=0.25)
    _ax1.legend(loc="upper left", fontsize=8)
    _ratio = _s_min / max(_s_max, 1e-9)
    _ax1.set_title(f"σ_min / σ_max = {_ratio:.2f} {'(NEAR SINGULARITY)' if _ratio < 0.2 else ''}")

    _labels = ["q̇₁ (Raw J⁻¹)", "q̇₂ (Raw J⁻¹)", "q̇₁ (DLS)", "q̇₂ (DLS)"]
    _vals = np.clip([abs(_qdot_raw[0]), abs(_qdot_raw[1]), abs(_qdot_dls[0]), abs(_qdot_dls[1])], 0, 15)
    _colors = ["#dc2626", "#dc2626", "#2563eb", "#2563eb"]
    _ax2.bar(_labels, _vals, color=_colors)
    _ax2.set_ylabel("|Joint Speed| (rad/s, clipped at 15)")
    _ax2.set_title("Raw Inverse vs. Damped Least Squares")
    _ax2.grid(True, axis="y", alpha=0.25)

    mo.vstack([_fig])
    return


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

    1. **Finite-difference check:** Perturb `t1_deg` and `t2_deg` by `eps = 1e-5` rad in `fk_2link` and verify that `(tip_plus - tip_minus) / (2 * eps)` matches `jacobian_2link` to 8+ decimal places.
    2. **Peak manipulability angle:** Sweep `t2_deg` from `5°` to `175°` and plot the manipulability index `w = σ_max * σ_min` — at what elbow angle does the arm have maximum agility?
    """)
    return


@app.cell
def _(fk_2link, jacobian_2link, manipulability_ellipse, np):
    # Exercise sandbox — edit and run!
    _eps_deg = 1e-4
    _eps_rad = np.deg2rad(_eps_deg)
    _t1, _t2 = 30.0, 60.0
    _, _p1_plus = fk_2link(_t1 + _eps_deg, _t2)
    _, _p1_minus = fk_2link(_t1 - _eps_deg, _t2)
    _, _p2_plus = fk_2link(_t1, _t2 + _eps_deg)
    _, _p2_minus = fk_2link(_t1, _t2 - _eps_deg)

    _J_num = np.column_stack([(_p1_plus - _p1_minus) / (2 * _eps_rad), (_p2_plus - _p2_minus) / (2 * _eps_rad)])
    _J_ana = jacobian_2link(_t1, _t2)
    print("Max |J_analytic - J_numeric| =", np.max(np.abs(_J_ana - _J_num)))

    _angles = np.linspace(5, 175, 35)
    _areas = [manipulability_ellipse(jacobian_2link(30.0, _a))[0] * manipulability_ellipse(jacobian_2link(30.0, _a))[1] for _a in _angles]
    _best_ang = _angles[int(np.argmax(_areas))]
    print(f"Peak manipulability area at elbow angle θ₂ ≈ {_best_ang:.1f}°")
    return


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