# /// 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 xml.etree.ElementTree as ET
    import marimo as mo
    import matplotlib.pyplot as plt
    import numpy as np

    return ET, mo, np, plt


@app.cell
def _(mo):
    mo.md(r"""
    # Module 2.1: Kinematic Trees and Robot Description Formats

    Welcome to **Course 2**! In Course 1, every robot was a single chain of links connected end to end. Real quadrupeds, humanoids, and mobile manipulators branch outward from a root torso into multiple limbs and sensor mounts.

    In this notebook, you'll parse real **URDF XML** strings into a parent→child kinematic tree, apply joint `<origin>` offsets and `<limit>` clamps, and evaluate forward kinematics across every branch simultaneously.
    """)
    return


@app.cell
def _(ET, np):
    def build_urdf_xml(preset="arm", link_length=0.45):
        """Generate a clean planar-projected URDF XML snippet for an arm or quadruped."""
        l1 = float(link_length)
        l2 = round(l1 * 0.85, 3)
        if preset == "arm":
            return f"""<robot name="planar_arm">
  <link name="base_link"/>
  <joint name="shoulder" type="revolute">
    <parent link="base_link"/>
    <child link="upper_arm"/>
    <origin xyz="0 0 0.15" rpy="0 0 0"/>
    <limit lower="-2.4" upper="2.4"/>
  </joint>
  <link name="upper_arm"/>
  <joint name="elbow" type="revolute">
    <parent link="upper_arm"/>
    <child link="forearm"/>
    <origin xyz="{l1:.3f} 0 0" rpy="0 0 0"/>
    <limit lower="-2.6" upper="2.6"/>
  </joint>
  <link name="forearm"/>
  <joint name="wrist_fixed" type="fixed">
    <parent link="forearm"/>
    <child link="gripper_tip"/>
    <origin xyz="{l2:.3f} 0 0" rpy="0 0 0"/>
  </joint>
  <link name="gripper_tip"/>
</robot>"""
        thigh = round(l1 * 0.85, 3)
        shin = round(l1 * 0.78, 3)
        half_body = round(l1 * 0.75, 3)
        return f"""<robot name="branched_quadruped">
  <link name="torso"/>
  <joint name="rear_hip" type="revolute">
    <parent link="torso"/>
    <child link="rear_thigh"/>
    <origin xyz="-{half_body:.3f} 0 0" rpy="0 0 0"/>
    <limit lower="-2.3" upper="0.5"/>
  </joint>
  <link name="rear_thigh"/>
  <joint name="rear_knee" type="revolute">
    <parent link="rear_thigh"/>
    <child link="rear_shin"/>
    <origin xyz="{thigh:.3f} 0 0" rpy="0 0 0"/>
    <limit lower="-2.4" upper="2.4"/>
  </joint>
  <link name="rear_shin"/>
  <joint name="rear_foot_fixed" type="fixed">
    <parent link="rear_shin"/>
    <child link="rear_foot"/>
    <origin xyz="{shin:.3f} 0 0" rpy="0 0 0"/>
  </joint>
  <link name="rear_foot"/>
  <joint name="front_hip" type="revolute">
    <parent link="torso"/>
    <child link="front_thigh"/>
    <origin xyz="{half_body:.3f} 0 0" rpy="0 0 0"/>
    <limit lower="-2.3" upper="0.5"/>
  </joint>
  <link name="front_thigh"/>
  <joint name="front_knee" type="revolute">
    <parent link="front_thigh"/>
    <child link="front_shin"/>
    <origin xyz="{thigh:.3f} 0 0" rpy="0 0 0"/>
    <limit lower="-2.4" upper="2.4"/>
  </joint>
  <link name="front_shin"/>
  <joint name="front_foot_fixed" type="fixed">
    <parent link="front_shin"/>
    <child link="front_foot"/>
    <origin xyz="{shin:.3f} 0 0" rpy="0 0 0"/>
  </joint>
  <link name="front_foot"/>
</robot>"""

    def parse_urdf_tree(xml_str):
        """Parse URDF XML into links, joints, root name, and parent->children adjacency."""
        root_el = ET.fromstring(xml_str)
        links = [el.attrib["name"] for el in root_el.findall("link")]
        children_map = {name: [] for name in links}
        has_parent = set()
        joints = []

        for j in root_el.findall("joint"):
            jname = j.attrib["name"]
            jtype = j.attrib.get("type", "fixed")
            parent = j.find("parent").attrib["link"]
            child = j.find("child").attrib["link"]
            origin_el = j.find("origin")
            xyz = [0.0, 0.0, 0.0]
            if origin_el is not None and "xyz" in origin_el.attrib:
                xyz = [float(v) for v in origin_el.attrib["xyz"].split()]
            lim_el = j.find("limit")
            lower, upper = -np.pi, np.pi
            if lim_el is not None:
                lower = float(lim_el.attrib.get("lower", -np.pi))
                upper = float(lim_el.attrib.get("upper", np.pi))
            jinfo = {
                "name": jname,
                "type": jtype,
                "parent": parent,
                "child": child,
                "xyz": xyz,
                "lower": lower,
                "upper": upper,
            }
            joints.append(jinfo)
            children_map[parent].append(jinfo)
            has_parent.add(child)

        roots = [lk for lk in links if lk not in has_parent]
        return roots[0], links, joints, children_map

    def tree_fk_2d(root_name, children_map, q_map):
        """Evaluate 2D (X-Z sagittal) forward kinematics across every branch of a URDF tree."""
        poses = {root_name: (0.0, 0.45 if "torso" in root_name else 0.0, 0.0)}
        edges = []

        def dfs(parent_name):
            px, pz, p_ang = poses[parent_name]
            for j in children_map[parent_name]:
                dx, _, dz = j["xyz"]
                ox = px + dx * np.cos(p_ang) - dz * np.sin(p_ang)
                oz = pz + dx * np.sin(p_ang) + dz * np.cos(p_ang)
                raw_q = float(q_map.get(j["name"], 0.0)) if j["type"] == "revolute" else 0.0
                clamped_q = float(np.clip(raw_q, j["lower"], j["upper"]))
                c_ang = p_ang + clamped_q
                poses[j["child"]] = (ox, oz, c_ang)
                edges.append((parent_name, j["child"], j["name"], raw_q != clamped_q))
                dfs(j["child"])

        dfs(root_name)
        return poses, edges

    return build_urdf_xml, parse_urdf_tree, tree_fk_2d


@app.cell
def _(mo):
    preset_dd = mo.ui.dropdown(["arm", "quadruped"], value="quadruped", label="URDF Preset")
    link_len_s = mo.ui.slider(0.25, 0.60, step=0.02, value=0.42, label="Base link length (m)")
    q_primary_s = mo.ui.slider(-140, 140, step=5, value=-65, label="Shoulder / Hip angle (deg)")
    q_secondary_s = mo.ui.slider(-140, 140, step=5, value=-45, label="Elbow / Knee angle (deg)")

    mo.vstack([
        mo.hstack([preset_dd, link_len_s], justify="start"),
        mo.hstack([q_primary_s, q_secondary_s], justify="start"),
    ])
    return link_len_s, preset_dd, q_primary_s, q_secondary_s


@app.cell
def _(
    build_urdf_xml,
    link_len_s,
    mo,
    np,
    parse_urdf_tree,
    plt,
    preset_dd,
    q_primary_s,
    q_secondary_s,
    tree_fk_2d,
):
    _xml = build_urdf_xml(preset=preset_dd.value, link_length=link_len_s.value)
    _root, _links, _joints, _cmap = parse_urdf_tree(_xml)
    _q1 = np.deg2rad(q_primary_s.value)
    _q2 = np.deg2rad(q_secondary_s.value)
    _q_map = {
        "shoulder": _q1,
        "elbow": _q2,
        "rear_hip": _q1,
        "front_hip": _q1,
        "rear_knee": _q2,
        "front_knee": _q2,
    }
    _poses, _edges = tree_fk_2d(_root, _cmap, _q_map)

    _fig, _ax = plt.subplots(figsize=(6.5, 4.5))
    for _parent, _child, _jname, _clamped in _edges:
        _px, _pz, _ = _poses[_parent]
        _cx, _cz, _ = _poses[_child]
        _color = "#dc2626" if _clamped else "#111827"
        _ax.plot([_px, _cx], [_pz, _cz], "-o", lw=3, ms=6, color=_color)
        _ax.text(0.5 * (_px + _cx), 0.5 * (_pz + _cz) + 0.03, _jname, fontsize=7.5, color="#4b5563", ha="center")

    for _lname, (_lx, _lz, _) in _poses.items():
        _ax.scatter([_lx], [_lz], s=55, color="#059669" if _lname == _root else "#2563eb", zorder=5)

    _ax.axhline(0.0, color="#9ca3af", ls="--", lw=1)
    _ax.set_aspect("equal")
    _ax.set_xlim(-0.85, 0.95)
    _ax.set_ylim(-0.4, 1.05)
    _ax.grid(True, alpha=0.25)
    _ax.set_xlabel("X (m)")
    _ax.set_ylabel("Z (m)")
    _ax.set_title(f"URDF Tree ({_root}): {len(_links)} links, {len(_joints)} joints (red = joint limit clamped)")

    mo.vstack([
        _fig,
        mo.md(f"```xml\n{_xml}\n```"),
    ])
    return


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

    1. **Add a 3rd branch (head/camera mast):** In the cell below, inject an extra `<joint name="camera_mount" type="fixed">` and `<link name="camera_head"/>` onto the `"torso"` of the quadruped URDF, then run `parse_urdf_tree` and `tree_fk_2d` to inspect its world coordinates.
    2. **Trigger a joint limit clamp:** Pass `{"shoulder": np.deg2rad(160)}` into `tree_fk_2d` on the arm URDF and check which edges return `clamped == True`.
    """)
    return


@app.cell
def _(build_urdf_xml, np, parse_urdf_tree, tree_fk_2d):
    # Exercise sandbox — edit and run!
    _base_xml = build_urdf_xml("quadruped", link_length=0.40)
    _extra = """  <joint name="camera_mount" type="fixed">
    <parent link="torso"/>
    <child link="camera_head"/>
    <origin xyz="0.32 0 0.14" rpy="0 0 0"/>
  </joint>
  <link name="camera_head"/>
</robot>"""
    _custom_xml = _base_xml.replace("</robot>", _extra)
    _r, _lks, _jts, _cm = parse_urdf_tree(_custom_xml)
    _poses, _edges = tree_fk_2d(_r, _cm, {"rear_hip": np.deg2rad(-60), "front_hip": np.deg2rad(-60)})
    print(f"Parsed {len(_lks)} links; camera_head pose = {_poses['camera_head']}")
    return


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