# /// 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 1.4: Forward Kinematics

    Forward kinematics answers: *given joint angles, where is the end-effector?* Below we compute it **two ways** — right-triangle trigonometry and chained 3×3 homogeneous transforms — and verify they produce the exact same pose.
    """)
    return


@app.cell
def _(np):
    def fk_2link_trig(theta1_deg, theta2_deg, l1=1.1, l2=0.85):
        """Closed-form planar 2-link FK using cumulative angles and right triangles."""
        r1 = np.deg2rad(theta1_deg)
        r12 = np.deg2rad(theta1_deg + theta2_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, r12

    def se2(x, y, theta_rad):
        c, s = np.cos(theta_rad), np.sin(theta_rad)
        return np.array([[c, -s, x], [s, c, y], [0.0, 0.0, 1.0]], dtype=float)

    def fk_chain_se2(angles_deg, lengths):
        """Chain SE(2) transforms from base to tool for any N-link planar arm."""
        T = np.eye(3, dtype=float)
        positions = [T[:2, 2].copy()]
        for ang_deg, length in zip(angles_deg, lengths):
            T = T @ se2(0.0, 0.0, np.deg2rad(ang_deg)) @ se2(length, 0.0, 0.0)
            positions.append(T[:2, 2].copy())
        return np.array(positions), T

    return fk_2link_trig, fk_chain_se2


@app.cell
def _(mo):
    t1 = mo.ui.slider(-180, 180, step=2, value=34, label="θ₁ (deg)")
    t2 = mo.ui.slider(-165, 165, step=2, value=-48, label="θ₂ (deg)")
    t3 = mo.ui.slider(-165, 165, step=2, value=28, label="θ₃ (deg, 3-link)")
    use_3_link = mo.ui.checkbox(value=False, label="Enable 3rd link")
    show_triangles = mo.ui.checkbox(value=True, label="Show right-triangle legs")

    mo.vstack([
        mo.hstack([t1, t2, t3], justify="start"),
        mo.hstack([use_3_link, show_triangles], justify="start"),
    ])
    return show_triangles, t1, t2, t3, use_3_link


@app.cell
def _(
    fk_2link_trig,
    fk_chain_se2,
    mo,
    np,
    plt,
    show_triangles,
    t1,
    t2,
    t3,
    use_3_link,
):
    _l1, _l2, _l3 = 1.1, 0.85, 0.55
    _angles = [t1.value, t2.value, t3.value] if use_3_link.value else [t1.value, t2.value]
    _lengths = [_l1, _l2, _l3] if use_3_link.value else [_l1, _l2]

    _pts, _T = fk_chain_se2(_angles, _lengths)
    if not use_3_link.value:
        _, _trig_tip, _ = fk_2link_trig(t1.value, t2.value, _l1, _l2)
        assert np.allclose(_pts[-1], _trig_tip, atol=1e-9)

    _fig, _ax = plt.subplots(figsize=(6, 5))
    _reach = sum(_lengths)
    _circle = plt.Circle((0, 0), _reach, color="#2563eb", fill=False, ls="--", alpha=0.45)
    _ax.add_patch(_circle)

    if show_triangles.value:
        for _i in range(len(_pts) - 1):
            _p0, _p1 = _pts[_i], _pts[_i + 1]
            _ax.plot([_p0[0], _p1[0]], [_p0[1], _p0[1]], "--", color="#dc2626", lw=1.4)
            _ax.plot([_p1[0], _p1[0]], [_p0[1], _p1[1]], "--", color="#16a34a", lw=1.4)

    _ax.plot(_pts[:, 0], _pts[:, 1], "-o", lw=3, ms=8, color="#111827")
    _ax.scatter([_pts[-1, 0]], [_pts[-1, 1]], s=95, color="#2563eb", zorder=5)
    _ax.set_aspect("equal")
    _ax.set_xlim(-_reach - 0.3, _reach + 0.3)
    _ax.set_ylim(-_reach - 0.3, _reach + 0.3)
    _ax.grid(True, alpha=0.25)
    _ax.set_title(f"Tip = ({_pts[-1, 0]:.2f}, {_pts[-1, 1]:.2f}) m  |  φ = {sum(_angles)}°")

    mo.vstack([_fig])
    return


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

    1. **Joint-limited workspace:** Sweep `theta1` and `theta2` across `[-90°, 90°]` instead of `[-180°, 180°]` and plot the reachable workspace shape.
    2. **4-link arm:** Call `fk_chain_se2([20, 30, -40, 25], [0.8, 0.7, 0.5, 0.4])` and inspect the end-effector's 3×3 homogeneous transform matrix `T`.
    """)
    return


@app.cell
def _(fk_chain_se2, np, plt):
    # Exercise sandbox — edit and run!
    _swept = []
    for _a1 in np.linspace(-90, 90, 25):
        for _a2 in np.linspace(-90, 90, 25):
            _p, _ = fk_chain_se2([_a1, _a2], [1.1, 0.85])
            _swept.append(_p[-1])
    _swept = np.array(_swept)

    _fig_ws, _ax_ws = plt.subplots(figsize=(5, 4.2))
    _ax_ws.scatter(_swept[:, 0], _swept[:, 1], s=8, alpha=0.45, color="#2563eb")
    _ax_ws.set_aspect("equal")
    _ax_ws.grid(True, alpha=0.25)
    _ax_ws.set_title("Exercise: Joint-Limited Workspace ([-90°, 90°])")
    _fig_ws
    return


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