# /// 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 5.5: Simultaneous Localization and Mapping (SLAM)

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

    When a robot maps an unknown courtyard without GPS, small odometry drift tears the map apart by the time it walks full circle. Below, we build a **2D Pose Graph** from drifting odometry edges, attach mapped wall landmarks to each pose, and run **Gauss-Newton pose graph relaxation** with a **loop-closure constraint** to watch both the trajectory and the mapped room snap shut cleanly.
    """)
    return


@app.cell
def _(np):
    def build_drifting_loop(n_poses=24, drift_per_step=(0.035, 0.018)):
        """Generate true closed loop poses, drifting odometry edges, and attached wall beacons."""
        angles = np.linspace(0.0, 2.0 * np.pi, n_poses, endpoint=False)
        true_xy = np.column_stack([2.2 * np.cos(angles), 1.6 * np.sin(angles)])

        # Local wall landmarks visible near each pose (shifted outward from loop)
        local_landmarks = np.column_stack([0.85 * np.cos(angles), 0.85 * np.sin(angles)])

        # Sequential odometry edges with systematic drift
        odom_edges = np.diff(true_xy, axis=0) + np.array(drift_per_step)
        drifted_xy = np.vstack([true_xy[0], true_xy[0] + np.cumsum(odom_edges, axis=0)])

        # Loop closure constraint: pose N-1 back to pose 0
        true_closure = true_xy[0] - true_xy[-1]
        return true_xy, drifted_xy, odom_edges, true_closure, local_landmarks

    def solve_pose_graph(drifted_xy, odom_edges, loop_closure, loop_weight=50.0, anchor_weight=200.0):
        """Solve linear 2D pose graph least squares: min ||A x - b||^2."""
        n = len(drifted_xy)
        # Unknowns: 2*n (x_0, y_0, ..., x_{n-1}, y_{n-1})
        rows = []
        rhs = []

        # Anchor pose 0 at origin of true frame
        for d in range(2):
            r = np.zeros(2 * n)
            r[d] = np.sqrt(anchor_weight)
            rows.append(r)
            rhs.append(np.sqrt(anchor_weight) * drifted_xy[0, d])

        # Sequential odometry constraints: x_{i+1} - x_i = odom_edges[i]
        for i in range(n - 1):
            for d in range(2):
                r = np.zeros(2 * n)
                r[2 * i + d] = -1.0
                r[2 * (i + 1) + d] = 1.0
                rows.append(r)
                rhs.append(odom_edges[i, d])

        # Loop closure edge: x_0 - x_{n-1} = loop_closure
        if loop_weight > 0.0:
            w = np.sqrt(loop_weight)
            for d in range(2):
                r = np.zeros(2 * n)
                r[2 * (n - 1) + d] = -w
                r[d] = w
                rows.append(r)
                rhs.append(w * loop_closure[d])

        A = np.array(rows)
        b = np.array(rhs)
        x_opt, _, _, _ = np.linalg.lstsq(A, b, rcond=None)
        return x_opt.reshape(n, 2)

    return build_drifting_loop, solve_pose_graph


@app.cell
def _(mo):
    drift_slider = mo.ui.slider(0.0, 0.08, step=0.01, value=0.04, label="Odometry drift per step (m)")
    loop_toggle = mo.ui.checkbox(value=True, label="Enable loop closure edge")
    weight_slider = mo.ui.slider(1.0, 100.0, step=5.0, value=50.0, label="Loop closure weight")

    mo.vstack([
        mo.hstack([drift_slider, weight_slider], justify="start"),
        loop_toggle,
    ])
    return drift_slider, loop_toggle, weight_slider


@app.cell
def _(
    build_drifting_loop,
    drift_slider,
    loop_toggle,
    mo,
    np,
    plt,
    solve_pose_graph,
    weight_slider,
):
    _true_xy, _drifted_xy, _odom, _closure, _lm_off = build_drifting_loop(
        n_poses=24,
        drift_per_step=(drift_slider.value, 0.55 * drift_slider.value),
    )
    _w = weight_slider.value if loop_toggle.value else 0.0
    _opt_xy = solve_pose_graph(_drifted_xy, _odom, _closure, loop_weight=_w)

    _true_map = _true_xy + _lm_off
    _opt_map = _opt_xy + _lm_off

    _gap_before = float(np.linalg.norm((_drifted_xy[0] - _drifted_xy[-1]) - _closure))
    _gap_after = float(np.linalg.norm((_opt_xy[0] - _opt_xy[-1]) - _closure))
    _rmse = float(np.sqrt(np.mean(np.sum((_opt_xy - _true_xy) ** 2, axis=1))))

    _fig, _ax = plt.subplots(figsize=(7.6, 5.0))
    _ax.plot(_true_xy[:, 0], _true_xy[:, 1], ":", lw=1.8, color="#16a34a", label="True path")
    _ax.plot(_drifted_xy[:, 0], _drifted_xy[:, 1], "--", lw=1.8, color="#dc2626", alpha=0.75, label=f"Raw odometry (gap={_gap_before:.2f} m)")
    _ax.plot(_opt_xy[:, 0], _opt_xy[:, 1], "-o", ms=4, lw=2.2, color="#2563eb", label=f"Optimized SLAM (RMSE={_rmse:.2f} m)")

    _ax.scatter(_true_map[:, 0], _true_map[:, 1], marker="s", s=24, color="#16a34a", alpha=0.35, label="True wall landmarks")
    _ax.scatter(_opt_map[:, 0], _opt_map[:, 1], marker="x", s=34, color="#2563eb", label="SLAM mapped landmarks")

    if loop_toggle.value:
        _ax.plot(
            [_opt_xy[-1, 0], _opt_xy[0, 0]],
            [_opt_xy[-1, 1], _opt_xy[0, 1]],
            lw=2.5,
            color="#7c3aed",
            label=f"Loop closure edge (residual={_gap_after:.2f} m)",
        )

    _ax.set_aspect("equal")
    _ax.grid(True, alpha=0.25)
    _ax.set_xlabel("x (m)")
    _ax.set_ylabel("y (m)")
    _ax.set_title("2D Pose Graph Relaxation & Map Alignment")
    _ax.legend(loc="best", fontsize=7.8)
    plt.tight_layout()
    mo.vstack([_fig])
    return


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

    1. **Loop weight trade-off:** Sweep `loop_weight` across `[0.5, 5.0, 50.0, 500.0]` in the cell below and print both the final loop closure gap and the trajectory RMSE against ground truth. Why does a tiny loop weight leave the loop slightly open?
    2. **False loop closure (perceptual aliasing):** Pass a wrong `loop_closure + np.array([1.8, -1.2])` into `solve_pose_graph` and plot what happens to the map. Notice why real SLAM front-ends use strict outlier rejection (RANSAC / robust kernels) before trusting a loop closure!
    """)
    return


@app.cell
def _(build_drifting_loop, np, plt, solve_pose_graph):
    # Exercise sandbox — edit and run this cell!
    _true_xy, _drifted_xy, _odom, _closure, _ = build_drifting_loop(n_poses=24, drift_per_step=(0.05, 0.03))
    for _lw in [0.5, 5.0, 50.0, 500.0]:
        _sol = solve_pose_graph(_drifted_xy, _odom, _closure, loop_weight=_lw)
        _gap = float(np.linalg.norm((_sol[0] - _sol[-1]) - _closure))
        _rmse = float(np.sqrt(np.mean(np.sum((_sol - _true_xy) ** 2, axis=1))))
        print(f"loop_weight={_lw:5.1f} -> residual gap={_gap:.3f} m, trajectory RMSE={_rmse:.3f} m")

    _bad_sol = solve_pose_graph(_drifted_xy, _odom, _closure + np.array([1.8, -1.2]), loop_weight=80.0)
    _fig_ex, _ax_ex = plt.subplots(figsize=(5.5, 4.0))
    _ax_ex.plot(_true_xy[:, 0], _true_xy[:, 1], ":", color="#16a34a", label="True loop")
    _ax_ex.plot(_bad_sol[:, 0], _bad_sol[:, 1], "-o", ms=3.5, color="#dc2626", label="Corrupted by false loop closure")
    _ax_ex.set_aspect("equal")
    _ax_ex.set_title("Exercise: Effect of One False Loop Closure")
    _ax_ex.grid(True, alpha=0.25)
    _ax_ex.legend(fontsize=8)
    _fig_ex
    return


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