# /// 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
    from matplotlib.patches import Ellipse
    import numpy as np

    return Ellipse, mo, np, plt


@app.cell
def _(mo):
    mo.md(r"""
    # Module 5.3: Kalman and Extended Kalman Filters (EKF)

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

    Here is the exact 2D Extended Kalman Filter running behind the browser sandbox: unicycle motion prediction (`F` Jacobian) paired with range-bearing landmark updates (`H` Jacobian) and Joseph-form covariance updates. Tune `Q`, `R`, and beacon dropout below to see how the **2σ covariance ellipse** stretches and snaps.
    """)
    return


@app.cell
def _(np):
    LANDMARKS = np.array([
        [-1.85, 1.35],
        [1.85, 1.35],
        [1.90, -1.30],
        [-1.85, -1.25],
    ])

    def wrap_angle(rad):
        return float((rad + np.pi) % (2.0 * np.pi) - np.pi)

    def motion_step(pose, v, w, dt=0.5):
        x, y, th = pose
        mid = th + 0.5 * w * dt
        return np.array([
            x + v * dt * np.cos(mid),
            y + v * dt * np.sin(mid),
            wrap_angle(th + w * dt),
        ])

    def ekf_predict(mu, P, v, w, q_scale=1.2, dt=0.5):
        mu_pred = motion_step(mu, v, w, dt)
        c, s = np.cos(mu[2]), np.sin(mu[2])
        F = np.array([
            [1.0, 0.0, -v * dt * s],
            [0.0, 1.0,  v * dt * c],
            [0.0, 0.0,  1.0],
        ])
        var_along = (0.11 * q_scale) ** 2
        var_cross = (0.055 * q_scale) ** 2
        var_th = (0.085 * q_scale) ** 2
        Q = np.array([
            [c * c * var_along + s * s * var_cross, c * s * (var_along - var_cross), 0.0],
            [c * s * (var_along - var_cross), s * s * var_along + c * c * var_cross, 0.0],
            [0.0, 0.0, var_th],
        ])
        P_pred = F @ P @ F.T + Q
        return mu_pred, P_pred

    def ekf_update(mu, P, landmark, z, r_scale=1.0):
        dx = landmark[0] - mu[0]
        dy = landmark[1] - mu[1]
        q = max(1e-4, dx * dx + dy * dy)
        r_hat = float(np.sqrt(q))
        b_hat = wrap_angle(np.arctan2(dy, dx) - mu[2])

        innov = np.array([z[0] - r_hat, wrap_angle(z[1] - b_hat)])
        H = np.array([
            [-dx / r_hat, -dy / r_hat, 0.0],
            [dy / q, -dx / q, -1.0],
        ])
        R = np.diag([(0.08 * r_scale) ** 2 + 1e-5, (0.07 * r_scale) ** 2 + 1e-5])
        S = H @ P @ H.T + R
        K = P @ H.T @ np.linalg.inv(S)

        mu_new = mu + K @ innov
        mu_new[2] = wrap_angle(mu_new[2])
        I_KH = np.eye(3) - K @ H
        P_new = I_KH @ P @ I_KH.T + K @ R @ K.T
        return mu_new, P_new, K, innov

    def run_ekf_rollout(steps=20, q_scale=1.2, r_scale=1.0, dropout_rate=0.0, seed=11):
        rng = np.random.default_rng(seed)
        dt = 0.5
        true_pose = np.array([-1.1, -0.7, 0.25])
        mu = true_pose.copy()
        P = np.diag([0.035, 0.025, 0.02])

        true_hist = [true_pose.copy()]
        est_hist = [mu.copy()]
        cov_hist = [P[:2, :2].copy()]
        k_hist = []

        for step in range(steps):
            phase = step % 28
            w = 0.42 if phase < 14 else 0.48
            v = 0.52 + 0.12 * np.cos((phase / 14.0) * np.pi)

            true_v = v * (1.0 + 0.06 * q_scale + rng.normal(0.0, 0.06 * q_scale))
            true_w = w + 0.08 * q_scale + rng.normal(0.0, 0.07 * q_scale)
            true_pose = motion_step(true_pose, true_v, true_w, dt)

            mu, P = ekf_predict(mu, P, v, w, q_scale=q_scale, dt=dt)

            if rng.random() >= dropout_rate:
                dists = np.linalg.norm(LANDMARKS - true_pose[:2], axis=1)
                lm = LANDMARKS[int(np.argmin(dists))]
                ldx, ldy = lm[0] - true_pose[0], lm[1] - true_pose[1]
                z = np.array([
                    np.hypot(ldx, ldy) + rng.normal(0.0, 0.08 * r_scale),
                    wrap_angle(np.arctan2(ldy, ldx) - true_pose[2] + rng.normal(0.0, 0.07 * r_scale)),
                ])
                mu, P, K, _ = ekf_update(mu, P, lm, z, r_scale=r_scale)
                k_hist.append(K)

            true_hist.append(true_pose.copy())
            est_hist.append(mu.copy())
            cov_hist.append(P[:2, :2].copy())

        return np.array(true_hist), np.array(est_hist), cov_hist, k_hist

    return LANDMARKS, ekf_predict, ekf_update, run_ekf_rollout


@app.cell
def _(mo):
    q_slider = mo.ui.slider(0.3, 3.0, step=0.1, value=1.2, label="Process noise Q scale")
    r_slider = mo.ui.slider(0.3, 3.0, step=0.1, value=1.0, label="Measurement noise R scale")
    drop_slider = mo.ui.slider(0.0, 0.9, step=0.1, value=0.0, label="Landmark dropout rate")
    steps_slider = mo.ui.slider(4, 30, step=2, value=18, label="Rollout steps")

    mo.vstack([
        mo.hstack([q_slider, r_slider], justify="start"),
        mo.hstack([drop_slider, steps_slider], justify="start"),
    ])
    return drop_slider, q_slider, r_slider, steps_slider


@app.cell
def _(
    Ellipse,
    LANDMARKS,
    drop_slider,
    mo,
    np,
    plt,
    q_slider,
    r_slider,
    run_ekf_rollout,
    steps_slider,
):
    _true_h, _est_h, _cov_h, _k_h = run_ekf_rollout(
        steps=steps_slider.value,
        q_scale=q_slider.value,
        r_scale=r_slider.value,
        dropout_rate=drop_slider.value,
    )

    _fig, _ax = plt.subplots(figsize=(7.2, 5.2))
    _ax.scatter(LANDMARKS[:, 0], LANDMARKS[:, 1], marker="^", s=110, color="#16a34a", label="Landmark beacons", zorder=5)
    for _idx, _lm in enumerate(LANDMARKS):
        _ax.text(_lm[0] + 0.08, _lm[1] + 0.06, f"L{_idx + 1}", fontsize=8.5)

    _ax.plot(_true_h[:, 0], _true_h[:, 1], lw=2.2, color="#16a34a", label="Ground truth")
    _ax.plot(_est_h[:, 0], _est_h[:, 1], "--o", ms=3.5, lw=2.0, color="#2563eb", label="EKF mean")

    # Draw 2-sigma covariance ellipses every 2 steps + final step
    for _i in range(0, len(_cov_h), 2):
        _vals, _vecs = np.linalg.eigh(_cov_h[_i])
        _order = np.argsort(_vals)[::-1]
        _vals = np.maximum(_vals[_order], 1e-6)
        _vecs = _vecs[:, _order]
        _angle = float(np.degrees(np.arctan2(_vecs[1, 0], _vecs[0, 0])))
        _w = 4.0 * float(np.sqrt(_vals[0]))
        _h = 4.0 * float(np.sqrt(_vals[1]))
        _alpha = 0.25 if _i == len(_cov_h) - 1 else 0.08
        _ell = Ellipse(xy=_est_h[_i, :2], width=_w, height=_h, angle=_angle, edgecolor="#2563eb", facecolor="#2563eb", alpha=_alpha, lw=1.2)
        _ax.add_patch(_ell)

    _final_err = float(np.linalg.norm(_est_h[-1, :2] - _true_h[-1, :2]))
    _ax.set_aspect("equal")
    _ax.set_xlim(-2.6, 2.6)
    _ax.set_ylim(-2.1, 2.1)
    _ax.grid(True, alpha=0.25)
    _ax.legend(loc="upper right", fontsize=8)
    _ax.set_title(f"2D EKF Trajectory & 2σ Ellipses  |  Final error = {_final_err:.2f} m")
    plt.tight_layout()
    mo.vstack([_fig])
    return


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

    1. **Blindfold vs. Update:** Call `ekf_predict` 6 times in a row without calling `ekf_update`, printing `np.trace(P[:2, :2])` at each step. Then call `ekf_update` once with beacon `L1` and print how much the position covariance trace drops.
    2. **Kalman Gain sensitivity:** Compare the Kalman gain `K` when `r_scale=0.3` (laser-sharp beacon) vs. `r_scale=4.0` (dusty sensor). Which entries of `K` shrink the most?
    """)
    return


@app.cell
def _(LANDMARKS, ekf_predict, ekf_update, np):
    # Exercise sandbox — edit and run this cell!
    _mu = np.array([-1.1, -0.7, 0.25])
    _P = np.diag([0.035, 0.025, 0.02])
    _traces = []
    for _step in range(6):
        _mu, _P = ekf_predict(_mu, _P, v=0.55, w=0.42, q_scale=1.5)
        _traces.append(round(float(np.trace(_P[:2, :2])), 4))
    print("Position covariance trace during 6 blind Predict steps:", _traces)

    _lm = LANDMARKS[0]
    _dx, _dy = _lm[0] - _mu[0], _lm[1] - _mu[1]
    _z_clean = np.array([np.hypot(_dx, _dy), np.arctan2(_dy, _dx) - _mu[2]])

    _, _P_sharp, _K_sharp, _ = ekf_update(_mu, _P, _lm, _z_clean, r_scale=0.3)
    _, _P_dusty, _K_dusty, _ = ekf_update(_mu, _P, _lm, _z_clean, r_scale=4.0)
    print("Trace after sharp Update (r=0.3):", round(float(np.trace(_P_sharp[:2, :2])), 4))
    print("Trace after dusty Update (r=4.0):", round(float(np.trace(_P_dusty[:2, :2])), 4))
    print("Kalman Gain norm ||K||: sharp =", round(float(np.linalg.norm(_K_sharp)), 3), "| dusty =", round(float(np.linalg.norm(_K_dusty)), 3))
    return


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