# /// 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.1: What is a Robot, and What is Kinematics?

    Welcome to the companion Python notebook for **Module 1.1**.

    In the browser sandbox on Robotics Concepts, you saw how locking or unlocking hinges and sliders changes the shape of a robot's reachable workspace. Here, you can read the underlying geometry code, tweak it, and run your own experiments — either interactively in **molab** or cell-by-cell in **Google Colab**.
    """)
    return


@app.cell
def _(np):
    def forward_chain(joints, link_length=0.72):
        """Compute joint positions along a planar chain of revolute/prismatic joints."""
        x, y, angle = 0.0, 0.0, 0.0
        pts = [(x, y, angle)]
        for joint in joints:
            kind = joint["kind"]
            val = float(joint["value"])
            if kind == "revolute":
                angle += np.deg2rad(val)
                x += link_length * np.cos(angle)
                y += link_length * np.sin(angle)
            elif kind == "prismatic":
                x += val * np.cos(angle)
                y += val * np.sin(angle)
            else:
                raise ValueError(f"Unknown joint kind: {kind}")
            pts.append((x, y, angle))
        return pts

    def sample_reachable_cloud(joints, samples_per_dof=21, link_length=0.72):
        """Sample all configurations of unlocked joints to visualize the reachable manifold."""
        grids = []
        for j in joints:
            if j.get("locked", False):
                grids.append([float(j["value"])])
            elif j["kind"] == "revolute":
                grids.append(np.linspace(-145.0, 145.0, samples_per_dof))
            else:
                grids.append(np.linspace(0.3, 1.35, samples_per_dof))

        cloud = []
        if len(joints) == 2:
            for v0 in grids[0]:
                for v1 in grids[1]:
                    _j = [
                        {**joints[0], "value": v0},
                        {**joints[1], "value": v1},
                    ]
                    cloud.append(forward_chain(_j, link_length)[-1][:2])
        elif len(joints) == 3:
            for v0 in grids[0]:
                for v1 in grids[1]:
                    for v2 in grids[2]:
                        _j = [
                            {**joints[0], "value": v0},
                            {**joints[1], "value": v1},
                            {**joints[2], "value": v2},
                        ]
                        cloud.append(forward_chain(_j, link_length)[-1][:2])
        return np.array(cloud)

    return forward_chain, sample_reachable_cloud


@app.cell
def _(mo):
    j1_kind = mo.ui.dropdown(["revolute", "prismatic"], value="revolute", label="Joint 1 type")
    j1_locked = mo.ui.checkbox(value=False, label="Lock Joint 1")
    j1_val = mo.ui.slider(-145, 145, step=5, value=30, label="Joint 1 angle (deg)")

    j2_locked = mo.ui.checkbox(value=False, label="Lock Joint 2")
    j2_val = mo.ui.slider(-145, 145, step=5, value=-45, label="Joint 2 angle (deg)")

    mo.vstack([
        mo.hstack([j1_kind, j1_locked, j1_val], justify="start"),
        mo.hstack([j2_locked, j2_val], justify="start"),
    ])
    return j1_kind, j1_locked, j1_val, j2_locked, j2_val


@app.cell
def _(
    forward_chain,
    j1_kind,
    j1_locked,
    j1_val,
    j2_locked,
    j2_val,
    mo,
    plt,
    sample_reachable_cloud,
):
    _j1_value = float(j1_val.value) if j1_kind.value == "revolute" else 0.85
    _joints = [
        {"kind": j1_kind.value, "locked": j1_locked.value, "value": _j1_value},
        {"kind": "revolute", "locked": j2_locked.value, "value": float(j2_val.value)},
    ]
    _active_dof = sum(1 for _j in _joints if not _j["locked"])
    _pts = forward_chain(_joints)
    _cloud = sample_reachable_cloud(_joints, samples_per_dof=25 if _active_dof == 2 else 45)

    _fig, _ax = plt.subplots(figsize=(6, 5))
    _ax.scatter(_cloud[:, 0], _cloud[:, 1], s=10, alpha=0.35, color="#2563eb", label="Reachable points")
    _xs = [p[0] for p in _pts]
    _ys = [p[1] for p in _pts]
    _ax.plot(_xs, _ys, "-o", lw=3, ms=8, color="#111827", label="Arm links")
    _ax.scatter([_xs[-1]], [_ys[-1]], s=90, color="#2563eb", zorder=5, label="End-effector")
    _ax.set_aspect("equal")
    _ax.set_xlim(-1.8, 1.8)
    _ax.set_ylim(-1.8, 1.8)
    _ax.grid(True, alpha=0.25)
    _ax.legend(loc="upper left", fontsize=8)
    _ax.set_title(f"Active DOF: {_active_dof} / {len(_joints)}  |  Tip = ({_xs[-1]:.2f}, {_ys[-1]:.2f}) m")

    mo.vstack([_fig])
    return


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

    1. **Add a 3rd revolute link:** Edit the cell below to pass 3 joints into `sample_reachable_cloud(..., samples_per_dof=10)` and plot the resulting cloud. Does the outer radius grow?
    2. **Prismatic straight-line workspace:** Lock Joint 2 (`"locked": True`) and make Joint 1 `"prismatic"`. Compute the Euclidean distance between the minimum and maximum reachable tip positions.
    """)
    return


@app.cell
def _(forward_chain, np, plt, sample_reachable_cloud):
    # Exercise sandbox — edit and run this cell on your own!
    three_link_joints = [
        {"kind": "revolute", "locked": False, "value": 25},
        {"kind": "revolute", "locked": False, "value": 35},
        {"kind": "revolute", "locked": False, "value": -50},
    ]
    _cloud3 = sample_reachable_cloud(three_link_joints, samples_per_dof=10, link_length=0.55)
    _pts3 = forward_chain(three_link_joints, link_length=0.55)
    print(f"Sampled {len(_cloud3)} 3-link poses; tip at ({_pts3[-1][0]:.2f}, {_pts3[-1][1]:.2f}) m")

    _fig_ex, _ax_ex = plt.subplots(figsize=(5, 4))
    _ax_ex.scatter(_cloud3[:, 0], _cloud3[:, 1], s=4, alpha=0.25, color="#059669")
    _ax_ex.plot([p[0] for p in _pts3], [p[1] for p in _pts3], "-o", lw=2.5, color="#111827")
    _ax_ex.set_aspect("equal")
    _ax_ex.set_title("Exercise: 3-Link Reachable Cloud")
    _ax_ex.grid(True, alpha=0.25)
    _fig_ex
    return


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