# /// 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 3.4: Local Reactive Obstacle Avoidance (Potential Fields & DWA)

    When unexpected obstacles appear nearby, reactive controllers steer using local forces or short velocity rollouts instead of re-planning a full global map. Compare **Artificial Potential Fields** (and see how they get trapped in **local minima**) against the **Dynamic Window Approach (DWA)**.
    """)
    return


@app.cell
def _(np):
    def potential_field_rollout(start, goal, obs_xy, obs_r, k_att=1.2, k_rep=1.6, d_inf=1.5, steps=180, dt=0.08):
        """Simulate a point robot following the negative gradient of attractive + repulsive potentials."""
        pos = np.array(start, dtype=float)
        goal = np.asarray(goal, dtype=float)
        obs = np.asarray(obs_xy, dtype=float)
        traj = [pos.copy()]

        for _ in range(steps):
            diff_goal = goal - pos
            dist_goal = float(np.linalg.norm(diff_goal))
            if dist_goal < 0.15:
                break
            f_att = k_att * (diff_goal / max(dist_goal, 1e-6))

            diff_obs = pos - obs
            dist_obs = float(np.linalg.norm(diff_obs)) - obs_r
            f_rep = np.zeros(2)
            if 0.02 < dist_obs < d_inf:
                mag = k_rep * (1.0 / dist_obs - 1.0 / d_inf) / (dist_obs ** 2)
                f_rep = mag * (diff_obs / np.linalg.norm(diff_obs))

            vel = f_att + f_rep
            speed = float(np.linalg.norm(vel))
            if speed > 1.2:
                vel = vel / speed * 1.2
            pos = pos + vel * dt
            traj.append(pos.copy())

        return np.array(traj)

    def simulate_dwa(start_pose, goal, obs_xy, obs_r, steps=150, dt=0.1):
        """Simulate a differential-drive robot using Dynamic Window Approach (v, omega) rollouts."""
        x, y, theta = float(start_pose[0]), float(start_pose[1]), float(start_pose[2])
        v, w = 0.2, 0.0
        goal = np.asarray(goal, dtype=float)
        obs = np.asarray(obs_xy, dtype=float)
        traj = [(x, y)]
        last_arcs = []

        max_v, min_v = 1.2, 0.15
        max_w = 2.2
        a_v, a_w = 1.5, 4.0
        horizon_steps = 15

        for _ in range(steps):
            if np.hypot(goal[0] - x, goal[1] - y) < 0.25:
                break

            v_lo = max(min_v, v - a_v * dt)
            v_hi = min(max_v, v + a_v * dt)
            w_lo = max(-max_w, w - a_w * dt)
            w_hi = min(max_w, w + a_w * dt)

            best_score = -np.inf
            best_vw = (min_v, 0.4)
            step_arcs = []

            for cv in np.linspace(v_lo, v_hi, 5):
                for cw in np.linspace(w_lo, w_hi, 11):
                    ax, ay, ath = x, y, theta
                    arc = [(ax, ay)]
                    min_clear = np.inf
                    crashed = False
                    for _k in range(horizon_steps):
                        ath += cw * dt
                        ax += cv * np.cos(ath) * dt
                        ay += cv * np.sin(ath) * dt
                        arc.append((ax, ay))
                        clear = float(np.hypot(ax - obs[0], ay - obs[1])) - obs_r
                        min_clear = min(min_clear, clear)
                        if clear <= 0.14:
                            crashed = True
                            break

                    step_arcs.append((arc, crashed))
                    if crashed:
                        continue

                    goal_angle = np.arctan2(goal[1] - ay, goal[0] - ax)
                    heading_err = abs((goal_angle - ath + np.pi) % (2 * np.pi) - np.pi)
                    heading_score = np.pi - heading_err
                    dist_score = -float(np.hypot(goal[0] - ax, goal[1] - ay))
                    score = 1.1 * heading_score + 0.9 * min(min_clear, 1.4) + 1.0 * cv + 1.2 * dist_score
                    if score > best_score:
                        best_score = score
                        best_vw = (float(cv), float(cw))

            last_arcs = step_arcs
            v, w = best_vw
            theta += w * dt
            x += v * np.cos(theta) * dt
            y += v * np.sin(theta) * dt
            traj.append((x, y))

        return np.array(traj), last_arcs

    return potential_field_rollout, simulate_dwa


@app.cell
def _(mo):
    method_dd = mo.ui.dropdown(["Potential Field", "DWA (Dynamic Window)"], value="Potential Field", label="Controller")
    obs_y_s = mo.ui.slider(-1.2, 1.2, step=0.05, value=0.0, label="Obstacle Y offset (m)")
    k_rep_s = mo.ui.slider(0.4, 3.0, step=0.2, value=1.6, label="Repulsion gain k_rep")

    mo.hstack([method_dd, obs_y_s, k_rep_s], justify="start")
    return k_rep_s, method_dd, obs_y_s


@app.cell
def _(k_rep_s, method_dd, mo, obs_y_s, plt, potential_field_rollout, simulate_dwa):
    _start = (0.0, 0.0)
    _goal = (6.0, 0.0)
    _obs = (3.0, obs_y_s.value)
    _obs_r = 0.65

    _fig, _ax = plt.subplots(figsize=(8.2, 4.4))
    _ax.add_patch(plt.Circle(_obs, _obs_r, color="#dc2626", alpha=0.25, ec="#dc2626", lw=2, label="Obstacle"))

    if method_dd.value == "Potential Field":
        _traj = potential_field_rollout(_start, _goal, _obs, _obs_r, k_rep=k_rep_s.value)
        _ax.plot(_traj[:, 0], _traj[:, 1], lw=2.8, color="#2563eb", label="PF Trajectory")
        _end_dist = ((_traj[-1, 0] - _goal[0]) ** 2 + (_traj[-1, 1] - _goal[1]) ** 2) ** 0.5
        _title = (
            "Potential Field: Trapped in Local Minimum!"
            if _end_dist > 0.35
            else "Potential Field: Reached Goal"
        )
    else:
        _traj, _arcs = simulate_dwa((0.0, 0.0, 0.0), _goal, _obs, _obs_r)
        for _arc, _bad in _arcs:
            _xs = [_p[0] for _p in _arc]
            _ys = [_p[1] for _p in _arc]
            _ax.plot(_xs, _ys, lw=0.8, alpha=0.35, color="#dc2626" if _bad else "#16a34a")
        _ax.plot(_traj[:, 0], _traj[:, 1], lw=2.8, color="#2563eb", label="DWA Trajectory")
        _title = "Dynamic Window Approach: Sampled Arcs Around Obstacle"

    _ax.scatter([_start[0]], [_start[1]], s=90, color="#2563eb", ec="white", zorder=5, label="Start")
    _ax.scatter([_goal[0]], [_goal[1]], s=90, color="#16a34a", ec="white", zorder=5, label="Goal")
    _ax.set_xlim(-0.5, 6.8)
    _ax.set_ylim(-2.4, 2.4)
    _ax.set_aspect("equal")
    _ax.grid(True, alpha=0.25)
    _ax.legend(loc="upper left", fontsize=8)
    _ax.set_title(_title)

    mo.vstack([_fig])
    return


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

    1. **Breaking symmetry:** With `Potential Field` selected, compare `obs_y = 0.0` (head-on dead center) to `obs_y = 0.05`. Why does a 5 cm offset completely change the outcome?
    2. **DWA clearance sweep:** Run `simulate_dwa` in the cell below at `obs_y = 0.0` and compute the minimum distance the robot maintains from the obstacle boundary.
    """)
    return


@app.cell
def _(np, potential_field_rollout, simulate_dwa):
    # Exercise sandbox — edit and run!
    _pf_zero = potential_field_rollout((0.0, 0.0), (6.0, 0.0), (3.0, 0.0), 0.65)
    _pf_nudge = potential_field_rollout((0.0, 0.0), (6.0, 0.0), (3.0, 0.05), 0.65)
    _dwa_zero, _ = simulate_dwa((0.0, 0.0, 0.0), (6.0, 0.0), (3.0, 0.0), 0.65)

    print("PF (obs_y=0.00) final pos:", np.round(_pf_zero[-1], 2))
    print("PF (obs_y=0.05) final pos:", np.round(_pf_nudge[-1], 2))
    _clearances = np.linalg.norm(_dwa_zero - np.array([3.0, 0.0]), axis=1) - 0.65
    print(f"DWA (obs_y=0.00) final pos: {np.round(_dwa_zero[-1], 2)}, min clearance = {_clearances.min():.2f} m")
    return


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