# /// 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.1: Robot Sensors and Noise Reality

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

    In the browser sandbox, you saw how a small wheel radius error or gyroscope bias bends a closed loop out of shape. Here you can inspect the exact dead-reckoning integrator in NumPy and compare **wheel odometry drift** against **accelerometer double-integration drift**.
    """)
    return


@app.cell
def _(np):
    def wrap_angle(rad):
        return (rad + np.pi) % (2.0 * np.pi) - np.pi

    def simulate_dead_reckoning(
        shape="square",
        slip_pct=2.5,
        gyro_bias_deg=0.7,
        noise_scale=0.25,
        seed=42,
    ):
        """Simulate a closed 2D path and its dead-reckoned odometry estimate."""
        rng = np.random.default_rng(seed)
        dt = 0.2

        if shape == "square":
            increments = []
            for _ in range(4):
                for _ in range(24):
                    increments.append((3.2 / 24.0, 0.0))
                for _ in range(6):
                    increments.append((0.0, (np.pi / 2.0) / 6.0))
            tx, ty, t_th = -1.6, -1.6, 0.0
        else:
            n_steps = 120
            phi = np.linspace(0.0, 2.0 * np.pi, n_steps + 1)
            xs = 2.0 * np.sin(phi)
            ys = -1.35 * np.cos(phi)
            increments = []
            prev_h = np.arctan2(ys[1] - ys[0], xs[1] - xs[0])
            for i in range(n_steps):
                dx = xs[i + 1] - xs[i]
                dy = ys[i + 1] - ys[i]
                ds = float(np.hypot(dx, dy))
                next_h = float(np.arctan2(dy, dx))
                dth = 0.0 if i == 0 else float(wrap_angle(next_h - prev_h))
                prev_h = next_h
                increments.append((ds, dth))
            tx, ty, t_th = 0.0, -1.35, 0.0

        ex, ey, e_th = tx, ty, t_th
        true_traj = [(tx, ty, t_th)]
        est_traj = [(ex, ey, e_th)]
        times = [0.0]
        pos_errors = [0.0]

        slip_factor = 1.0 + slip_pct / 100.0
        asym_pull = (slip_pct / 100.0) * 0.14
        gyro_bias_step = np.deg2rad(gyro_bias_deg) * dt

        for idx, (ds, dth) in enumerate(increments):
            t_mid = t_th + 0.5 * dth
            tx += ds * np.cos(t_mid)
            ty += ds * np.sin(t_mid)
            t_th = float(wrap_angle(t_th + dth))

            n_ds = rng.normal(0.0, noise_scale * 0.025)
            n_dth = rng.normal(0.0, noise_scale * np.deg2rad(1.2))
            ds_meas = max(0.0, ds * slip_factor + (n_ds if ds > 0 else 0.25 * n_ds))
            dth_meas = dth + gyro_bias_step + asym_pull * ds + n_dth

            e_mid = e_th + 0.5 * dth_meas
            ex += ds_meas * np.cos(e_mid)
            ey += ds_meas * np.sin(e_mid)
            e_th = float(wrap_angle(e_th + dth_meas))

            true_traj.append((tx, ty, t_th))
            est_traj.append((ex, ey, e_th))
            times.append((idx + 1) * dt)
            pos_errors.append(float(np.hypot(ex - tx, ey - ty)))

        return (
            np.array(times),
            np.array(true_traj),
            np.array(est_traj),
            np.array(pos_errors),
        )

    def simulate_imu_double_integration(accel_bias=0.05, accel_noise=0.04, duration=15.0, dt=0.05, seed=7):
        """Show quadratic position drift when integrating a biased 1D accelerometer twice."""
        rng = np.random.default_rng(seed)
        t = np.arange(0.0, duration + 1e-9, dt)
        a_true = np.zeros_like(t)
        a_meas = a_true + accel_bias + rng.normal(0.0, accel_noise, size=len(t))
        vel = np.cumsum(a_meas) * dt
        pos = np.cumsum(vel) * dt
        return t, pos, 0.5 * accel_bias * (t ** 2)

    return simulate_dead_reckoning, simulate_imu_double_integration


@app.cell
def _(mo):
    shape_dd = mo.ui.dropdown(["square", "oval"], value="square", label="Loop path")
    slip_slider = mo.ui.slider(-6.0, 6.0, step=0.5, value=2.5, label="Wheel radius/slip error (%)")
    gyro_slider = mo.ui.slider(-2.0, 2.0, step=0.1, value=0.7, label="IMU gyro bias (deg/s)")
    noise_slider = mo.ui.slider(0.0, 1.0, step=0.05, value=0.25, label="Sensor noise scale")

    mo.vstack([
        mo.hstack([shape_dd, slip_slider], justify="start"),
        mo.hstack([gyro_slider, noise_slider], justify="start"),
    ])
    return gyro_slider, noise_slider, shape_dd, slip_slider


@app.cell
def _(
    gyro_slider,
    mo,
    noise_slider,
    plt,
    shape_dd,
    simulate_dead_reckoning,
    slip_slider,
):
    _times, _true_p, _est_p, _errs = simulate_dead_reckoning(
        shape=shape_dd.value,
        slip_pct=slip_slider.value,
        gyro_bias_deg=gyro_slider.value,
        noise_scale=noise_slider.value,
    )

    _fig, (_ax1, _ax2) = plt.subplots(1, 2, figsize=(10.5, 4.3))
    _ax1.plot(_true_p[:, 0], _true_p[:, 1], lw=2.2, color="#16a34a", label="Ground truth")
    _ax1.plot(_est_p[:, 0], _est_p[:, 1], "--", lw=2.2, color="#2563eb", label="Dead reckoning")
    _ax1.plot(
        [_true_p[-1, 0], _est_p[-1, 0]],
        [_true_p[-1, 1], _est_p[-1, 1]],
        ":",
        lw=2.0,
        color="#dc2626",
        label=f"Closure gap ({_errs[-1]:.2f} m)",
    )
    _ax1.scatter([_true_p[0, 0]], [_true_p[0, 1]], s=65, color="#16a34a", zorder=5)
    _ax1.scatter([_est_p[-1, 0]], [_est_p[-1, 1]], s=65, color="#dc2626", zorder=5)
    _ax1.set_aspect("equal")
    _ax1.set_xlabel("x (m)")
    _ax1.set_ylabel("y (m)")
    _ax1.set_title("2D Trajectory Drift")
    _ax1.grid(True, alpha=0.25)
    _ax1.legend(loc="best", fontsize=8)

    _ax2.plot(_times, _errs, lw=2.2, color="#dc2626")
    _ax2.fill_between(_times, 0, _errs, color="#dc2626", alpha=0.14)
    _ax2.set_xlabel("Time (s)")
    _ax2.set_ylabel("Position error (m)")
    _ax2.set_title(f"Cumulative Drift (final = {_errs[-1]:.2f} m)")
    _ax2.grid(True, alpha=0.25)

    plt.tight_layout()
    mo.vstack([_fig])
    return


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

    1. **Accelerometer double-integration check:** Run `simulate_imu_double_integration(accel_bias=0.05)` in the cell below (imagine a tiny 0.5% gravity tilt error on a stationary robot). How many meters does the estimate drift in just 15 seconds?
    2. **Noise vs. Bias experiment:** Set `gyro_bias_deg=0.0` and `slip_pct=0.0` in `simulate_dead_reckoning`, then run 20 random seeds with `noise_scale=0.5`. Compute the average final drift and compare it against a tiny `gyro_bias_deg=0.5` with zero noise. Which hurts more?
    """)
    return


@app.cell
def _(np, plt, simulate_dead_reckoning, simulate_imu_double_integration):
    # Exercise sandbox — edit and run this cell!
    _t, _pos_drift, _analytic = simulate_imu_double_integration(accel_bias=0.05, duration=15.0)
    print(f"Stationary IMU drift after 15 s (bias=0.05 m/s^2): {_pos_drift[-1]:.2f} m (analytic 1/2 b t^2 = {_analytic[-1]:.2f} m)")

    _zero_bias_drifts = [
        simulate_dead_reckoning("square", slip_pct=0.0, gyro_bias_deg=0.0, noise_scale=0.5, seed=_s)[3][-1]
        for _s in range(20)
    ]
    _pure_bias_drift = simulate_dead_reckoning("square", slip_pct=0.0, gyro_bias_deg=0.5, noise_scale=0.0)[3][-1]
    print(f"Mean zero-bias noisy drift (20 trials): {np.mean(_zero_bias_drifts):.2f} m")
    print(f"Pure 0.5 deg/s bias drift (zero noise): {_pure_bias_drift:.2f} m")

    _fig_ex, _ax_ex = plt.subplots(figsize=(6, 3.6))
    _ax_ex.plot(_t, _pos_drift, lw=2, color="#7c3aed", label="Integrated noisy accel")
    _ax_ex.plot(_t, _analytic, "--", lw=1.8, color="#111827", label=r"$\frac{1}{2} b t^2$ curve")
    _ax_ex.set_xlabel("Time (s)")
    _ax_ex.set_ylabel("Estimated distance (m)")
    _ax_ex.set_title("Exercise: Double Integration of a Biased Accelerometer")
    _ax_ex.grid(True, alpha=0.25)
    _ax_ex.legend(fontsize=8)
    _fig_ex
    return


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