# /// 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.3: Standardized Arm Conventions (DH vs. Product of Exponentials)

    Industrial datasheets love **Denavit-Hartenberg (DH)** tables — four parameters `(a, α, d, θ)` per link. Modern robotics libraries love **Product of Exponentials (PoE)** — define one home pose `M` at `q = 0` and describe every joint by its 6D screw axis `S_i = (ω_i, v_i)` in the base frame.

    Here you can compute a 3-DOF spatial arm (`base yaw + shoulder pitch + elbow pitch`) using **both** conventions side-by-side and verify numerically that they land on the exact same 4×4 pose matrix `T`.
    """)
    return


@app.cell
def _(np):
    def dh_transform(a, alpha, d, theta):
        """Standard Denavit-Hartenberg 4x4 homogeneous transform."""
        ct, st = np.cos(theta), np.sin(theta)
        ca, sa = np.cos(alpha), np.sin(alpha)
        return np.array([
            [ct, -st * ca, st * sa, a * ct],
            [st, ct * ca, -ct * sa, a * st],
            [0.0, sa, ca, d],
            [0.0, 0.0, 0.0, 1.0],
        ])

    def skew(v):
        return np.array([
            [0.0, -v[2], v[1]],
            [v[2], 0.0, -v[0]],
            [-v[1], v[0], 0.0],
        ])

    def screw_exp(omega, v, theta):
        """4x4 matrix exponential exp([S] * theta) for a unit screw axis S = (omega, v)."""
        w_hat = skew(omega)
        R = np.eye(3) + np.sin(theta) * w_hat + (1.0 - np.cos(theta)) * (w_hat @ w_hat)
        G = np.eye(3) * theta + (1.0 - np.cos(theta)) * w_hat + (theta - np.sin(theta)) * (w_hat @ w_hat)
        p = G @ v
        T = np.eye(4)
        T[:3, :3] = R
        T[:3, 3] = p
        return T

    def fk_dh_3dof(q, d1=0.35, l1=0.60, l2=0.50):
        """3-DOF spatial arm (waist yaw, shoulder pitch, elbow pitch) via standard DH."""
        T1 = dh_transform(0.0, np.pi / 2, d1, q[0])
        T2 = dh_transform(l1, 0.0, 0.0, q[1])
        T3 = dh_transform(l2, 0.0, 0.0, q[2])
        p0 = np.array([0.0, 0.0, 0.0])
        p1 = T1[:3, 3]
        p2 = (T1 @ T2)[:3, 3]
        T_ee = T1 @ T2 @ T3
        return T_ee, np.array([p0, p1, p2, T_ee[:3, 3]])

    def fk_poe_3dof(q, d1=0.35, l1=0.60, l2=0.50):
        """Exact same 3-DOF arm using Product of Exponentials in the space frame."""
        # At q = (0, 0, 0), arm points straight along +X at height z = d1
        M = np.array([
            [1.0, 0.0, 0.0, l1 + l2],
            [0.0, 0.0, -1.0, 0.0],
            [0.0, 1.0, 0.0, d1],
            [0.0, 0.0, 0.0, 1.0],
        ])
        # Screw 1: waist yaw around +Z through (0, 0, 0)
        w1 = np.array([0.0, 0.0, 1.0])
        v1 = -np.cross(w1, np.array([0.0, 0.0, 0.0]))
        # Screw 2: shoulder pitch around +Y (at q=0) through (0, 0, d1)
        w2 = np.array([0.0, -1.0, 0.0])
        v2 = -np.cross(w2, np.array([0.0, 0.0, d1]))
        # Screw 3: elbow pitch around +Y (at q=0) through (l1, 0, d1)
        w3 = np.array([0.0, -1.0, 0.0])
        v3 = -np.cross(w3, np.array([l1, 0.0, d1]))

        T = screw_exp(w1, v1, q[0]) @ screw_exp(w2, v2, q[1]) @ screw_exp(w3, v3, q[2]) @ M
        return T

    return fk_dh_3dof, fk_poe_3dof, screw_exp


@app.cell
def _(mo):
    q1_s = mo.ui.slider(-150, 150, step=5, value=35, label="Waist yaw q₁ (deg)")
    q2_s = mo.ui.slider(-30, 140, step=5, value=40, label="Shoulder pitch q₂ (deg)")
    q3_s = mo.ui.slider(-140, 140, step=5, value=-55, label="Elbow pitch q₃ (deg)")

    mo.hstack([q1_s, q2_s, q3_s], justify="start")
    return q1_s, q2_s, q3_s


@app.cell
def _(fk_dh_3dof, fk_poe_3dof, mo, np, plt, q1_s, q2_s, q3_s):
    _q = np.deg2rad([q1_s.value, q2_s.value, q3_s.value])
    _T_dh, _pts = fk_dh_3dof(_q)
    _T_poe = fk_poe_3dof(_q)
    _max_diff = float(np.max(np.abs(_T_dh - _T_poe)))

    _fig = plt.figure(figsize=(6.4, 4.8))
    _ax = _fig.add_subplot(111, projection="3d")
    _ax.plot(_pts[:, 0], _pts[:, 1], _pts[:, 2], "-o", lw=3, ms=7, color="#111827", label="Arm links")
    _ax.scatter([_pts[-1, 0]], [_pts[-1, 1]], [_pts[-1, 2]], s=80, color="#2563eb", label="End-effector")

    # Draw end-effector axes from T_poe
    _ee = _T_poe[:3, 3]
    for _col, _clr in enumerate(["#dc2626", "#16a34a", "#2563eb"]):
        _axis = 0.22 * _T_poe[:3, _col]
        _ax.plot([_ee[0], _ee[0] + _axis[0]], [_ee[1], _ee[1] + _axis[1]], [_ee[2], _ee[2] + _axis[2]], color=_clr, lw=2)

    _ax.set_xlim(-1.1, 1.1)
    _ax.set_ylim(-1.1, 1.1)
    _ax.set_zlim(0.0, 1.4)
    _ax.set_xlabel("X (m)")
    _ax.set_ylabel("Y (m)")
    _ax.set_zlabel("Z (m)")
    _ax.set_title(f"max |T_DH - T_PoE| = {_max_diff:.2e}  |  EE = ({_ee[0]:.2f}, {_ee[1]:.2f}, {_ee[2]:.2f}) m")

    mo.vstack([
        _fig,
        mo.md(f"**Pose match check (`np.allclose`):** `{np.allclose(_T_dh, _T_poe)}` (max entrywise diff `{_max_diff:.2e}`)"),
    ])
    return


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

    1. **Inspect the home posture (`q = [0, 0, 0]`):** Run `fk_dh_3dof([0, 0, 0])` and verify that the 4×4 matrix equals `M` inside `fk_poe_3dof`.
    2. **Add a 4th wrist roll joint using PoE:** Using `screw_exp` with `w4 = [1, 0, 0]` through `(l1 + l2, 0, d1)`, multiply `screw_exp(w4, v4, q4)` right before `@ M` — notice you don't have to touch a single intermediate frame!
    """)
    return


@app.cell
def _(fk_dh_3dof, fk_poe_3dof, np, screw_exp):
    # Exercise sandbox — edit and run!
    _T0_dh, _ = fk_dh_3dof([0.0, 0.0, 0.0])
    _T0_poe = fk_poe_3dof([0.0, 0.0, 0.0])
    print("At home pose q=(0,0,0), max |T_DH - T_PoE| =", np.max(np.abs(_T0_dh - _T0_poe)))

    # 4th joint: wrist roll around +X at (1.10, 0, 0.35)
    _w4 = np.array([1.0, 0.0, 0.0])
    _v4 = -np.cross(_w4, np.array([1.10, 0.0, 0.35]))
    _T4 = _T0_poe @ np.eye(4)
    _T_with_roll = screw_exp(_w4, _v4, np.deg2rad(45)) @ _T4
    print("Tip position after 45° home wrist roll:", np.round(_T_with_roll[:3, 3], 4))
    return


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