# /// 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.5: Inverse Kinematics (Geometric & CCD)

    Working backward from a desired hand coordinate `(x*, y*)` to joint angles introduces three classic quirks: **elbow-up vs. elbow-down ambiguity**, **unreachable targets**, and **singularities** where the arm stretches straight.
    """)
    return


@app.cell
def _(np):
    def fk2(t1_deg, t2_deg, l1=1.05, l2=0.85):
        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 solve_ik_geometric(tx, ty, l1=1.05, l2=0.85, branch="down"):
        """Closed-form 2-link IK via law of cosines with reachability clamping."""
        r = np.hypot(tx, ty)
        max_r, min_r = l1 + l2, abs(l1 - l2)
        unreachable = r > max_r or r < min_r
        clamped_r = np.clip(r if r > 1e-6 else 1e-6, min_r + 1e-4, max_r - 1e-4)

        cos2 = np.clip((clamped_r**2 - l1**2 - l2**2) / (2 * l1 * l2), -1.0, 1.0)
        t2_rad = (-1.0 if branch == "up" else 1.0) * np.arccos(cos2)
        t1_rad = np.arctan2(ty, tx) - np.arctan2(l2 * np.sin(t2_rad), l1 + l2 * np.cos(t2_rad))
        return np.rad2deg(t1_rad), np.rad2deg(t2_rad), unreachable

    def solve_ik_ccd(tx, ty, l1=1.05, l2=0.85, init_angles=(115.0, -125.0), iterations=8):
        """Iterative Cyclic Coordinate Descent solver returning angle and error history."""
        t1, t2 = float(init_angles[0]), float(init_angles[1])
        history = []

        def wrap(deg):
            return ((deg + 180.0) % 360.0) - 180.0

        for _ in range(iterations + 1):
            elbow, tip = fk2(t1, t2, l1, l2)
            err = float(np.hypot(tip[0] - tx, tip[1] - ty))
            history.append((t1, t2, err))

            # Update joint 2 (elbow)
            d2 = np.rad2deg(
                np.arctan2(ty - elbow[1], tx - elbow[0])
                - np.arctan2(tip[1] - elbow[1], tip[0] - elbow[0])
            )
            t2 = wrap(t2 + d2)

            # Update joint 1 (shoulder)
            _, tip1 = fk2(t1, t2, l1, l2)
            d1 = np.rad2deg(np.arctan2(ty, tx) - np.arctan2(tip1[1], tip1[0]))
            t1 = wrap(t1 + d1)

        return history

    return fk2, solve_ik_ccd, solve_ik_geometric


@app.cell
def _(mo):
    tx_s = mo.ui.slider(-2.0, 2.0, step=0.05, value=1.25, label="Target X (m)")
    ty_s = mo.ui.slider(-1.6, 1.8, step=0.05, value=0.75, label="Target Y (m)")
    branch_dd = mo.ui.dropdown(["down", "up"], value="down", label="Geometric branch")
    ccd_steps = mo.ui.slider(0, 20, step=1, value=5, label="CCD iterations")

    mo.vstack([
        mo.hstack([tx_s, ty_s], justify="start"),
        mo.hstack([branch_dd, ccd_steps], justify="start"),
    ])
    return branch_dd, ccd_steps, tx_s, ty_s


@app.cell
def _(
    branch_dd,
    ccd_steps,
    fk2,
    mo,
    plt,
    solve_ik_ccd,
    solve_ik_geometric,
    tx_s,
    ty_s,
):
    _tx, _ty = tx_s.value, ty_s.value
    _t1, _t2, _unreach = solve_ik_geometric(_tx, _ty, branch=branch_dd.value)
    _alt_t1, _alt_t2, _ = solve_ik_geometric(_tx, _ty, branch="up" if branch_dd.value == "down" else "down")
    _elbow, _tip = fk2(_t1, _t2)
    _alt_elbow, _alt_tip = fk2(_alt_t1, _alt_t2)

    _ccd_hist = solve_ik_ccd(_tx, _ty, iterations=ccd_steps.value)
    _errors = [row[2] for row in _ccd_hist]

    _fig, (_ax1, _ax2) = plt.subplots(1, 2, figsize=(9.5, 4.2))
    _ax1.add_patch(plt.Circle((0, 0), 1.9, color="#2563eb", fill=False, ls="--", alpha=0.45))
    if not _unreach:
        _ax1.plot([0, _alt_elbow[0], _alt_tip[0]], [0, _alt_elbow[1], _alt_tip[1]], "--o", color="#9ca3af", alpha=0.6, label="Alternate branch")
    _ax1.plot([0, _elbow[0], _tip[0]], [0, _elbow[1], _tip[1]], "-o", lw=3, color="#111827", label=f"Solved ({branch_dd.value})")
    _ax1.scatter([_tx], [_ty], marker="x", s=110, color="#dc2626" if _unreach else "#f97316", lw=2.5, label="Target")
    _ax1.set_aspect("equal")
    _ax1.set_xlim(-2.1, 2.1)
    _ax1.set_ylim(-2.1, 2.1)
    _ax1.grid(True, alpha=0.25)
    _ax1.legend(loc="upper left", fontsize=7.5)
    _ax1.set_title("Unreachable target (clamped)" if _unreach else f"θ₁={_t1:.1f}°, θ₂={_t2:.1f}°")

    _ax2.bar(range(len(_errors)), _errors, color="#2563eb")
    _ax2.set_xlabel("CCD Iteration")
    _ax2.set_ylabel("Tip Error (m)")
    _ax2.set_title(f"CCD Final Error: {_errors[-1]:.4f} m")
    _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. **Singularity boundary:** Call `solve_ik_geometric(1.90, 0.0)` where `r == l1 + l2`. Compare the `"up"` and `"down"` branches — why are they identical?
    2. **3-link CCD:** Copy `solve_ik_ccd` and extend it to loop backward from joint 3 → joint 2 → joint 1 for a 3-link arm.
    """)
    return


@app.cell
def _(solve_ik_geometric):
    # Exercise sandbox — edit and run!
    _down = solve_ik_geometric(1.90, 0.0, branch="down")
    _up = solve_ik_geometric(1.90, 0.0, branch="up")
    print("At outer boundary r = L1 + L2:")
    print("  Elbow-down:", round(_down[0], 3), round(_down[1], 3))
    print("  Elbow-up:  ", round(_up[0], 3), round(_up[1], 3))
    return


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