# /// 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.5: Static Force Duality and Mobile Bases

    Two geometric ideas anchor real mobile manipulators:
    1. **Static force duality (`τ = Jᵀ F`)**: the transpose of the velocity Jacobian converts an external force pushing on the hand into holding motor torques.
    2. **Wheel constraints**: differential-drive and Ackermann bases are **nonholonomic** (wheels resist sideways slip), whereas omniwheel bases are **holonomic** (`vₓ, vᵧ, ω` all independent).
    """)
    return


@app.cell
def _(np):
    def jacobian_2link(t1_deg, t2_deg, l1=0.95, l2=0.78):
        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 static_torques(J, force_xy):
        """Compute joint holding torques tau = J^T @ F."""
        return J.T @ force_xy

    def rollout_mobile_base(mode="diff-drive", p1=0.45, p2=0.85, p3=0.0, horizon=3.0, dt=0.05):
        """Roll out a 3-second planar trajectory and compute body-frame ICC."""
        track_w = 0.56
        wheelbase = 0.72
        if mode == "diff-drive":
            vx, vy, omega = 0.5 * (p1 + p2), 0.0, (p2 - p1) / track_w
        elif mode == "ackermann":
            vx, vy, omega = p1, 0.0, (p1 / wheelbase) * np.tan(np.deg2rad(p2))
        else:
            vx, vy, omega = p1, p2, p3

        x, y, th = 0.0, 0.0, 0.0
        traj = [(x, y, th)]
        for _ in range(int(horizon / dt)):
            x += (vx * np.cos(th) - vy * np.sin(th)) * dt
            y += (vx * np.sin(th) + vy * np.cos(th)) * dt
            th += omega * dt
            traj.append((x, y, th))

        icc = (-vy / omega, vx / omega) if abs(omega) > 0.03 else None
        return np.array(traj), (vx, vy, omega), icc

    return jacobian_2link, rollout_mobile_base, static_torques


@app.cell
def _(mo):
    base_dd = mo.ui.dropdown(["diff-drive", "ackermann", "omniwheel"], value="diff-drive", label="Base Type")
    p1_s = mo.ui.slider(-1.0, 1.0, step=0.05, value=0.45, label="v_left / speed / vₓ (m/s)")
    p2_s = mo.ui.slider(-35.0, 35.0, step=0.5, value=0.85, label="v_right / steer° / vᵧ")
    p3_s = mo.ui.slider(-1.5, 1.5, step=0.05, value=0.35, label="Omni ω (rad/s)")
    fx_s = mo.ui.slider(-25, 25, step=1, value=12, label="Arm Tip Force Fₓ (N)")
    fy_s = mo.ui.slider(-25, 25, step=1, value=-10, label="Arm Tip Force Fᵧ (N)")

    mo.vstack([
        mo.hstack([base_dd, p1_s, p2_s, p3_s], justify="start"),
        mo.hstack([fx_s, fy_s], justify="start"),
    ])
    return base_dd, fx_s, fy_s, p1_s, p2_s, p3_s


@app.cell
def _(
    base_dd,
    fx_s,
    fy_s,
    jacobian_2link,
    mo,
    np,
    p1_s,
    p2_s,
    p3_s,
    plt,
    rollout_mobile_base,
    static_torques,
):
    _p2_val = np.clip(p2_s.value, -1.0, 1.0) if base_dd.value != "ackermann" else p2_s.value
    _traj, (_vx, _vy, _om), _icc = rollout_mobile_base(base_dd.value, p1_s.value, _p2_val, p3_s.value)

    _J = jacobian_2link(30.0, 65.0)
    _F = np.array([float(fx_s.value), float(fy_s.value)])
    _tau = static_torques(_J, _F)

    _fig, (_ax1, _ax2) = plt.subplots(1, 2, figsize=(9.6, 4.2))
    _ax1.plot(_traj[:, 0], _traj[:, 1], "--", lw=2.5, color="#2563eb", label="3.0s rollout")
    _ax1.scatter([0.0], [0.0], s=80, color="#111827", label="Start (0,0)")
    _ax1.scatter([_traj[-1, 0]], [_traj[-1, 1]], s=70, color="#2563eb", marker="^", label="Final pose")
    if _icc is not None:
        _ax1.scatter([_icc[0]], [_icc[1]], s=90, color="#16a34a", label="ICC pivot")
        _ax1.plot([0.0, _icc[0]], [0.0, _icc[1]], ":", color="#16a34a", lw=1.5)
    _ax1.set_aspect("equal")
    _ax1.set_xlim(-2.2, 3.2)
    _ax1.set_ylim(-2.2, 2.2)
    _ax1.grid(True, alpha=0.25)
    _ax1.legend(loc="upper left", fontsize=7.5)
    _ax1.set_title(f"{base_dd.value}: twist=({_vx:.2f}, {_vy:.2f}, ω={_om:.2f})")

    _ax2.bar(["τ₁ (Shoulder)", "τ₂ (Elbow)"], _tau, color=["#2563eb" if _t >= 0 else "#dc2626" for _t in _tau])
    _ax2.axhline(0.0, color="#111827", lw=1)
    _ax2.set_ylabel("Torque (N·m)")
    _ax2.set_title(f"Arm Holding Torques τ = JᵀF for F=({fx_s.value}, {fy_s.value}) N")
    _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. **Virtual work check:** Pick any random joint velocity `q_dot = [0.7, -1.1]`, compute `v = J @ q_dot` and `tau = J.T @ F`, and verify `tau @ q_dot == F @ v` to floating-point precision.
    2. **Ackermann minimum turning radius:** Compute the turning radius `R = v / omega = L / tan(steer)` for `steer = 35°` and `L = 0.72 m`.
    """)
    return


@app.cell
def _(jacobian_2link, np, static_torques):
    # Exercise sandbox — edit and run!
    _J = jacobian_2link(40.0, 55.0)
    _F = np.array([15.0, -8.0])
    _qdot = np.array([0.7, -1.1])
    _v = _J @ _qdot
    _tau = static_torques(_J, _F)
    print(f"Joint power tau·qdot = {float(_tau @ _qdot):.6f} W  |  Tip power F·v = {float(_F @ _v):.6f} W")

    _L = 0.72
    _R_min = _L / np.tan(np.deg2rad(35.0))
    print(f"Ackermann turning radius at 35° steer: {_R_min:.3f} m")
    return


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