# /// 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.2: Coordinate Frames & Visual 2×2 Rotations

    A 2×2 rotation matrix isn't an arbitrary table of trig numbers — its two columns are literally the coordinates of the robot's local **X** and **Y** axes drawn inside the room.
    """)
    return


@app.cell
def _(np):
    def rotation_matrix_2d(theta_rad):
        """Return the 2x2 rotation matrix whose columns are local X and local Y."""
        c, s = np.cos(theta_rad), np.sin(theta_rad)
        return np.array([[c, -s], [s, c]], dtype=float)

    def world_to_robot(p_world, robot_xy, theta_rad):
        """Express a world-frame 2D point in the robot's local coordinate frame."""
        R = rotation_matrix_2d(theta_rad)
        return R.T @ (np.asarray(p_world, dtype=float) - np.asarray(robot_xy, dtype=float))

    def robot_to_world(p_robot, robot_xy, theta_rad):
        """Map a robot-local 2D point back into room (world) coordinates."""
        R = rotation_matrix_2d(theta_rad)
        return np.asarray(robot_xy, dtype=float) + R @ np.asarray(p_robot, dtype=float)

    return robot_to_world, rotation_matrix_2d, world_to_robot


@app.cell
def _(mo):
    robot_x = mo.ui.slider(-1.5, 1.5, step=0.1, value=0.8, label="Robot X (m)")
    robot_y = mo.ui.slider(-1.5, 1.5, step=0.1, value=0.5, label="Robot Y (m)")
    heading_deg = mo.ui.slider(-180, 180, step=5, value=35, label="Heading θ (deg)")
    cone_x = mo.ui.slider(-2.0, 2.5, step=0.1, value=1.9, label="Target X (m)")
    cone_y = mo.ui.slider(-2.0, 2.5, step=0.1, value=1.3, label="Target Y (m)")

    mo.vstack([
        mo.hstack([robot_x, robot_y, heading_deg], justify="start"),
        mo.hstack([cone_x, cone_y], justify="start"),
    ])
    return cone_x, cone_y, heading_deg, robot_x, robot_y


@app.cell
def _(
    cone_x,
    cone_y,
    heading_deg,
    mo,
    np,
    plt,
    robot_x,
    robot_y,
    rotation_matrix_2d,
    world_to_robot,
):
    _theta = np.deg2rad(heading_deg.value)
    _R = rotation_matrix_2d(_theta)
    _robot_xy = np.array([robot_x.value, robot_y.value])
    _p_world = np.array([cone_x.value, cone_y.value])
    _p_local = world_to_robot(_p_world, _robot_xy, _theta)

    _fig, (_ax_w, _ax_r) = plt.subplots(1, 2, figsize=(9.5, 4.2))

    # Left: Room (World) Frame
    _ax_w.axhline(0, color="#9ca3af", lw=0.8)
    _ax_w.axvline(0, color="#9ca3af", lw=0.8)
    _ax_w.quiver(*_robot_xy, _R[0, 0], _R[1, 0], angles="xy", scale_units="xy", scale=1.6, color="#dc2626", label="Local X (Col 1)")
    _ax_w.quiver(*_robot_xy, _R[0, 1], _R[1, 1], angles="xy", scale_units="xy", scale=1.6, color="#16a34a", label="Local Y (Col 2)")
    _ax_w.scatter([_p_world[0]], [_p_world[1]], marker="^", s=110, color="#f97316", label="Target P")
    _ax_w.set_xlim(-2.5, 2.8)
    _ax_w.set_ylim(-2.5, 2.8)
    _ax_w.set_aspect("equal")
    _ax_w.grid(True, alpha=0.25)
    _ax_w.legend(loc="upper left", fontsize=7.5)
    _ax_w.set_title(f"Room Frame: P = ({_p_world[0]:.2f}, {_p_world[1]:.2f})")

    # Right: Robot Local Frame
    _ax_r.axhline(0, color="#dc2626", lw=1.2, alpha=0.5)
    _ax_r.axvline(0, color="#16a34a", lw=1.2, alpha=0.5)
    _ax_r.scatter([0], [0], s=80, color="#111827", label="Robot Origin")
    _ax_r.scatter([_p_local[0]], [_p_local[1]], marker="^", s=110, color="#f97316", label="Target P")
    _ax_r.set_xlim(-2.8, 2.8)
    _ax_r.set_ylim(-2.8, 2.8)
    _ax_r.set_aspect("equal")
    _ax_r.grid(True, alpha=0.25)
    _ax_r.legend(loc="upper left", fontsize=7.5)
    _ax_r.set_title(f"Robot Frame: P = ({_p_local[0]:.2f}, {_p_local[1]:.2f})")

    _info = mo.md(
        f"**R({heading_deg.value}°)** = `[[{_R[0,0]:+.2f}, {_R[0,1]:+.2f}], [{_R[1,0]:+.2f}, {_R[1,1]:+.2f}]]`"
    )
    mo.vstack([_fig, _info])
    return


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

    1. **Verify orthogonality:** Check that `R.T @ R` equals the 2×2 identity matrix for any heading angle you pick.
    2. **Transform a LiDAR scan:** Given 5 obstacle detections measured in the robot's local frame, convert all 5 into room coordinates using `robot_to_world`.
    """)
    return


@app.cell
def _(np, robot_to_world, rotation_matrix_2d):
    # Exercise sandbox — edit and run!
    _angle = np.deg2rad(42.0)
    _R_check = rotation_matrix_2d(_angle)
    assert np.allclose(_R_check.T @ _R_check, np.eye(2))

    lidar_points_robot = np.array([
        [0.8, 0.0],
        [0.9, 0.25],
        [1.1, -0.3],
        [0.6, 0.5],
        [1.4, 0.1],
    ])
    _world_pts = np.array([robot_to_world(pt, [0.8, 0.5], _angle) for pt in lidar_points_robot])
    print("Converted LiDAR points in Room Frame:\n", np.round(_world_pts, 3))
    return


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