# /// 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.4: Particle Filters and Global Localization

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

    This notebook implements **Monte Carlo Localization (MCL)** in the same symmetric two-corridor floorplan from the sandbox. Watch how particles hold **two competing corridor hypotheses** until the robot passes the right-hand alcove — and test how random particle injection recovers from a **kidnapped robot** jump.
    """)
    return


@app.cell
def _(np):
    FLOORPLAN = np.array([
        [0.4, 0.6],
        [9.4, 0.6],
        [9.4, 2.2],
        [2.0, 2.2],
        [2.0, 3.8],
        [7.4, 3.8],
        [7.4, 2.7],
        [9.0, 2.7],
        [9.0, 3.8],
        [9.4, 3.8],
        [9.4, 5.4],
        [0.4, 5.4],
    ])

    def is_free(x, y, margin=0.16):
        in_spine = (0.4 + margin <= x <= 2.0 - margin) and (0.6 + margin <= y <= 5.4 - margin)
        in_top = (2.0 - margin <= x <= 9.4 - margin) and (3.8 + margin <= y <= 5.4 - margin)
        in_bot = (2.0 - margin <= x <= 9.4 - margin) and (0.6 + margin <= y <= 2.2 - margin)
        in_alcove = (7.4 + margin <= x <= 9.0 - margin) and (2.7 + margin <= y <= 3.8 - margin)
        return in_spine or in_top or in_bot or in_alcove

    def cast_ray(ox, oy, angle, max_range=10.0):
        dx, dy = np.cos(angle), np.sin(angle)
        best_t = max_range
        n_verts = len(FLOORPLAN)
        for i in range(n_verts):
            ax, ay = FLOORPLAN[i]
            bx, by = FLOORPLAN[(i + 1) % n_verts]
            sx, sy = bx - ax, by - ay
            denom = dx * sy - dy * sx
            if abs(denom) < 1e-8:
                continue
            qpx, qpy = ax - ox, ay - oy
            t = (qpx * sy - qpy * sx) / denom
            u = (qpx * dy - qpy * dx) / denom
            if 0.0 <= t < best_t and -1e-6 <= u <= 1.0 + 1e-6:
                best_t = t
        return best_t

    def sense_lidar(pose, num_rays=8):
        angles = pose[2] + np.linspace(0.0, 2.0 * np.pi, num_rays, endpoint=False)
        return np.array([cast_ray(pose[0], pose[1], a) for a in angles])

    def sample_free_particles(n_particles, rng):
        pts = []
        headings = [0.0, 0.5 * np.pi, np.pi, -0.5 * np.pi]
        while len(pts) < n_particles:
            x = float(rng.uniform(0.55, 9.25))
            y = float(rng.uniform(0.75, 5.25))
            if is_free(x, y):
                th = float(rng.choice(headings) + rng.uniform(-0.12, 0.12))
                pts.append([x, y, th])
        return np.array(pts)

    def run_mcl(n_particles=120, steps=6, kidnap_at=None, inject_frac=0.08, seed=7):
        rng = np.random.default_rng(seed)
        particles = sample_free_particles(n_particles, rng)
        weights = np.full(n_particles, 1.0 / n_particles)

        path = [
            np.array([2.6, 4.6, 0.0]),
            np.array([3.6, 4.6, 0.0]),
            np.array([4.6, 4.6, 0.0]),
            np.array([5.6, 4.6, 0.0]),
            np.array([6.6, 4.6, 0.0]),
            np.array([7.6, 4.6, 0.0]),
            np.array([8.2, 4.2, -0.5 * np.pi]),
            np.array([8.2, 3.3, -0.5 * np.pi]),
            np.array([8.2, 4.6, np.pi]),
            np.array([6.6, 4.6, np.pi]),
        ]

        true_pose = path[0].copy()
        neff_hist = [float(n_particles)]

        for s in range(1, steps + 1):
            if kidnap_at is not None and s == kidnap_at:
                next_true = np.array([5.2, 1.4, 0.0])
            else:
                next_true = path[min(s, len(path) - 1)].copy()

            ds = float(np.hypot(next_true[0] - true_pose[0], next_true[1] - true_pose[1]))
            dth = float((next_true[2] - true_pose[2] + np.pi) % (2.0 * np.pi) - np.pi)
            if kidnap_at is not None and s == kidnap_at:
                ds, dth = 0.8, 0.0
            true_pose = next_true

            z_scan = sense_lidar(true_pose)
            raw_lik = np.zeros(n_particles)
            for i in range(n_particles):
                noisy_ds = max(0.0, ds + rng.normal(0.0, 0.1))
                nx = particles[i, 0] + noisy_ds * np.cos(particles[i, 2])
                ny = particles[i, 1] + noisy_ds * np.sin(particles[i, 2])
                nth = (particles[i, 2] + dth + rng.normal(0.0, np.deg2rad(6.0)) + np.pi) % (2.0 * np.pi) - np.pi
                if is_free(nx, ny, margin=0.08):
                    particles[i] = [nx, ny, nth]
                    p_scan = sense_lidar(particles[i])
                    mse = float(np.mean((z_scan - p_scan) ** 2))
                    raw_lik[i] = np.exp(-0.5 * mse / (0.55 ** 2))
                else:
                    raw_lik[i] = 1e-7

            weights = weights * np.maximum(raw_lik, 1e-7)
            weights /= weights.sum()
            n_eff = float(1.0 / np.sum(weights ** 2))
            neff_hist.append(n_eff)

            # Systematic resample + adaptive random injection
            n_rand = int(round(n_particles * (0.35 if raw_lik.mean() < 0.08 else inject_frac)))
            n_keep = n_particles - n_rand
            cdf = np.cumsum(weights)
            cdf[-1] = 1.0
            u0 = rng.uniform(0.0, 1.0 / max(1, n_keep))
            targets = u0 + np.arange(n_keep) / max(1, n_keep)
            idx = np.searchsorted(cdf, targets)
            kept = particles[idx].copy()
            kept[:, 0] += rng.normal(0.0, 0.06, size=n_keep)
            kept[:, 1] += rng.normal(0.0, 0.06, size=n_keep)
            if n_rand > 0:
                rand_pts = sample_free_particles(n_rand, rng)
                particles = np.vstack([kept, rand_pts])
            else:
                particles = kept
            weights = np.full(n_particles, 1.0 / n_particles)

        return true_pose, particles, weights, neff_hist

    return FLOORPLAN, run_mcl, sense_lidar


@app.cell
def _(mo):
    steps_slider = mo.ui.slider(0, 9, step=1, value=3, label="Move + Sense + Resample steps")
    n_slider = mo.ui.slider(40, 240, step=20, value=120, label="Particle count N")
    kidnap_cb = mo.ui.checkbox(value=False, label="Kidnap robot at step 4 (jump to bottom corridor)")

    mo.vstack([
        mo.hstack([steps_slider, n_slider], justify="start"),
        kidnap_cb,
    ])
    return kidnap_cb, n_slider, steps_slider


@app.cell
def _(
    FLOORPLAN,
    kidnap_cb,
    mo,
    n_slider,
    np,
    plt,
    run_mcl,
    sense_lidar,
    steps_slider,
):
    _kidnap_step = 4 if kidnap_cb.value else None
    _true_p, _pts, _w, _neff = run_mcl(
        n_particles=n_slider.value,
        steps=steps_slider.value,
        kidnap_at=_kidnap_step,
    )
    _scan = sense_lidar(_true_p)

    _fig, _ax = plt.subplots(figsize=(8.4, 4.4))
    _poly = np.vstack([FLOORPLAN, FLOORPLAN[0]])
    _ax.plot(_poly[:, 0], _poly[:, 1], lw=2.2, color="#111827")

    for _k, _dist in enumerate(_scan):
        _ang = _true_p[2] + _k * (2.0 * np.pi / len(_scan))
        _ax.plot(
            [_true_p[0], _true_p[0] + _dist * np.cos(_ang)],
            [_true_p[1], _true_p[1] + _dist * np.sin(_ang)],
            "--",
            lw=1.0,
            color="#16a34a",
            alpha=0.45,
        )

    _ax.scatter(_pts[:, 0], _pts[:, 1], s=26, color="#2563eb", alpha=0.65, label=f"{len(_pts)} particles")
    _ax.scatter([_true_p[0]], [_true_p[1]], s=110, color="#16a34a", edgecolor="#111827", zorder=5, label="True robot")
    _ax.set_aspect("equal")
    _ax.set_xlim(0.0, 9.8)
    _ax.set_ylim(0.2, 5.8)
    _ax.set_title(f"Step {steps_slider.value}  |  Last N_eff before resample = {_neff[-1]:.1f}")
    _ax.legend(loc="center", fontsize=8)
    _ax.grid(True, alpha=0.2)
    plt.tight_layout()
    mo.vstack([_fig])
    return


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

    1. **Watch bimodal symmetry break:** Inspect steps 2, 5, and 7 in the cell below and print what fraction of particles sit in the top corridor (`y > 3.0`) vs. the bottom corridor (`y < 3.0`).
    2. **Why random injection matters for kidnapping:** Compare `inject_frac=0.0` vs. `inject_frac=0.08` when `kidnap_at=4` over 9 steps. Does the filter recover without fresh random particles?
    """)
    return


@app.cell
def _(np, run_mcl):
    # Exercise sandbox — edit and run this cell!
    for _step in [2, 5, 7]:
        _, _pts_s, _, _ = run_mcl(n_particles=140, steps=_step, seed=7)
        _top_frac = float(np.mean(_pts_s[:, 1] > 3.0))
        print(f"Step {_step}: top corridor = {_top_frac:.0%}, bottom corridor = {1 - _top_frac:.0%}")

    for _inj in [0.0, 0.08]:
        _tp, _pts_k, _, _ = run_mcl(n_particles=140, steps=9, kidnap_at=4, inject_frac=_inj, seed=7)
        _err = float(np.linalg.norm(_pts_k[:, :2].mean(axis=0) - _tp[:2]))
        print(f"Kidnapped @ step 4 with inject_frac={_inj}: final mean error @ step 9 = {_err:.2f} m")
    return


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