# /// 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.3: Transform Networks (TF Trees)

    Packing translation and rotation into a single 3×3 **homogeneous matrix** lets us store every parent-child relationship in a tree and ask: *"Where is frame A expressed inside frame B?"*
    """)
    return


@app.cell
def _(np):
    def make_se2(x, y, theta_rad):
        """Construct a 3x3 SE(2) homogeneous transform matrix."""
        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 invert_se2(T):
        """Exact rigid-body inverse of a 3x3 SE(2) transform."""
        R = T[:2, :2]
        t = T[:2, 2]
        inv = np.eye(3, dtype=float)
        inv[:2, :2] = R.T
        inv[:2, 2] = -(R.T @ t)
        return inv

    class TFTree:
        """Minimal directed transform tree supporting shortest-path chaining & inversion."""

        def __init__(self, root="world"):
            self.root = root
            self.parents = {root: None}
            self.edges = {}  # child -> (parent, T_parent_to_child)

        def add_edge(self, parent, child, T_parent_to_child):
            self.parents[child] = parent
            self.edges[child] = (parent, T_parent_to_child)

        def path_to_root(self, node):
            path = []
            cur = node
            while cur is not None:
                path.append(cur)
                cur = self.parents[cur]
            return list(reversed(path))

        def lookup(self, target_frame, source_frame):
            """Return T_target<-source and a readable list of chained steps."""
            p_tgt = self.path_to_root(target_frame)
            p_src = self.path_to_root(source_frame)
            lca = 0
            while (
                lca + 1 < len(p_tgt)
                and lca + 1 < len(p_src)
                and p_tgt[lca + 1] == p_src[lca + 1]
            ):
                lca += 1

            T = np.eye(3, dtype=float)
            steps = []
            for i in range(len(p_tgt) - 1, lca, -1):
                child = p_tgt[i]
                parent, T_p_c = self.edges[child]
                T = T @ invert_se2(T_p_c)
                steps.append(f"(T_{parent}->{child})^-1")

            for i in range(lca, len(p_src) - 1):
                child = p_src[i + 1]
                parent, T_p_c = self.edges[child]
                T = T @ T_p_c
                steps.append(f"T_{parent}->{child}")

            return T, steps

    return TFTree, invert_se2, make_se2


@app.cell
def _(mo):
    _frames = ["world", "base", "shoulder", "wrist", "camera", "table", "mug"]
    source_dd = mo.ui.dropdown(_frames, value="mug", label="Express frame")
    target_dd = mo.ui.dropdown(_frames, value="camera", label="Inside frame")
    shoulder_deg = mo.ui.slider(-20, 110, step=5, value=42, label="Shoulder (deg)")
    wrist_deg = mo.ui.slider(-90, 90, step=5, value=-32, label="Wrist (deg)")

    mo.vstack([
        mo.hstack([source_dd, target_dd], justify="start"),
        mo.hstack([shoulder_deg, wrist_deg], justify="start"),
    ])
    return shoulder_deg, source_dd, target_dd, wrist_deg


@app.cell
def _(TFTree, make_se2, mo, np, plt, shoulder_deg, source_dd, target_dd, wrist_deg):
    _tree = TFTree("world")
    _tree.add_edge("world", "base", make_se2(-0.9, 0.0, 0.0))
    _tree.add_edge("base", "shoulder", make_se2(0.0, 0.25, np.deg2rad(shoulder_deg.value)))
    _tree.add_edge("shoulder", "wrist", make_se2(0.95, 0.0, np.deg2rad(wrist_deg.value)))
    _tree.add_edge("wrist", "camera", make_se2(0.22, 0.14, np.deg2rad(-15.0)))
    _tree.add_edge("world", "table", make_se2(0.95, 0.35, 0.0))
    _tree.add_edge("table", "mug", make_se2(0.25, 0.18, np.deg2rad(18.0)))

    _T_rel, _steps = _tree.lookup(target_dd.value, source_dd.value)
    _dx, _dy = _T_rel[0, 2], _T_rel[1, 2]
    _ang = np.rad2deg(np.arctan2(_T_rel[1, 0], _T_rel[0, 0]))

    # Plot world-frame positions of arm & mug
    _world_pts = {
        _name: _tree.lookup("world", _name)[0][:2, 2]
        for _name in ["base", "shoulder", "wrist", "camera", "table", "mug"]
    }
    _fig, _ax = plt.subplots(figsize=(6.2, 3.8))
    _arm_chain = [_world_pts[k] for k in ["base", "shoulder", "wrist", "camera"]]
    _ax.plot([p[0] for p in _arm_chain], [p[1] for p in _arm_chain], "-o", lw=3, color="#111827")
    _ax.scatter([_world_pts["mug"][0]], [_world_pts["mug"][1]], s=140, marker="s", color="#f97316", label="mug")
    _ax.scatter([_world_pts["camera"][0]], [_world_pts["camera"][1]], s=90, color="#2563eb", label="camera")
    _ax.set_aspect("equal")
    _ax.set_xlim(-1.4, 1.8)
    _ax.set_ylim(-0.3, 1.5)
    _ax.grid(True, alpha=0.25)
    _ax.legend(loc="upper left", fontsize=8)
    _ax.set_title(f"{source_dd.value} in {target_dd.value}: ({_dx:.2f}, {_dy:.2f}) m, {_ang:.1f}°")

    _chain_str = " · ".join(_steps) if _steps else "Identity"
    mo.vstack([
        _fig,
        mo.md(f"**Lookup chain:** `{_chain_str}`"),
    ])
    return


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

    1. **Add a `gripper_tip` frame:** Attach a new child frame `"gripper_tip"` to `"wrist"` at `(0.28, 0.0, 0.0)` and look up where `"mug"` is in `"gripper_tip"`.
    2. **Check inverse symmetry:** Verify that `tree.lookup("camera", "mug")[0] @ tree.lookup("mug", "camera")[0]` equals the 3×3 identity matrix.
    """)
    return


@app.cell
def _(TFTree, make_se2, np):
    # Exercise sandbox — edit and run!
    _ex_tree = TFTree("world")
    _ex_tree.add_edge("world", "base", make_se2(-0.9, 0.0, 0.0))
    _ex_tree.add_edge("base", "shoulder", make_se2(0.0, 0.25, np.deg2rad(42)))
    _ex_tree.add_edge("shoulder", "wrist", make_se2(0.95, 0.0, np.deg2rad(-32)))
    _ex_tree.add_edge("wrist", "camera", make_se2(0.22, 0.14, np.deg2rad(-15)))
    _ex_tree.add_edge("wrist", "gripper_tip", make_se2(0.28, 0.0, 0.0))
    _ex_tree.add_edge("world", "table", make_se2(0.95, 0.35, 0.0))
    _ex_tree.add_edge("table", "mug", make_se2(0.25, 0.18, np.deg2rad(18)))

    _T_ab, _ = _ex_tree.lookup("camera", "mug")
    _T_ba, _ = _ex_tree.lookup("mug", "camera")
    assert np.allclose(_T_ab @ _T_ba, np.eye(3))

    _T_tip_mug, _ = _ex_tree.lookup("gripper_tip", "mug")
    print("Mug in gripper_tip frame (x, y):", np.round(_T_tip_mug[:2, 2], 3))
    return


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