# /// 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.3: Sampling-Based Planners (RRT & RRT*)

    Grid search scales exponentially with dimension ($N^d$), which makes 6- or 7-DOF arm planning impossible on a uniform grid. Sampling-based planners like **RRT** and **RRT\*** throw random samples into continuous space and wire collision-free local segments instead.
    """)
    return


@app.cell
def _(np):
    def get_obstacles(preset="narrow-gap"):
        """Return list of rectangular obstacles (xmin, ymin, xmax, ymax) in [0, 10] x [0, 8]."""
        if preset == "narrow-gap":
            return [
                (4.3, 0.0, 4.9, 5.1),
                (4.3, 6.1, 4.9, 8.0),
                (6.8, 2.0, 7.4, 7.0),
            ]
        return [
            (3.2, 2.0, 4.2, 6.2),
            (6.0, 1.2, 7.0, 5.5),
        ]

    def segment_free(p1, p2, obstacles, step=0.12):
        """Check whether straight segment [p1, p2] avoids all rectangular obstacles."""
        dist = float(np.linalg.norm(p2 - p1))
        n_steps = max(2, int(np.ceil(dist / step)))
        for t in np.linspace(0.0, 1.0, n_steps + 1):
            pt = p1 + t * (p2 - p1)
            if pt[0] < 0.1 or pt[0] > 9.9 or pt[1] < 0.1 or pt[1] > 7.9:
                return False
            for xmin, ymin, xmax, ymax in obstacles:
                if xmin - 0.12 <= pt[0] <= xmax + 0.12 and ymin - 0.12 <= pt[1] <= ymax + 0.12:
                    return False
        return True

    def plan_rrt(
        start,
        goal,
        obstacles,
        max_iters=450,
        step_size=0.75,
        goal_bias=0.15,
        use_rrt_star=False,
        rewire_radius=1.4,
        seed=42,
    ):
        """Run deterministic-seed RRT or RRT* in 2D continuous space."""
        rng = np.random.default_rng(seed)
        start = np.asarray(start, dtype=float)
        goal = np.asarray(goal, dtype=float)

        nodes = [start]
        parents = [-1]
        costs = [0.0]
        goal_idx = None

        for _ in range(max_iters):
            if rng.random() < goal_bias:
                sample = goal
            else:
                sample = np.array([rng.uniform(0.2, 9.8), rng.uniform(0.2, 7.8)])

            pts = np.array(nodes)
            dists = np.linalg.norm(pts - sample, axis=1)
            near_idx = int(np.argmin(dists))
            near = nodes[near_idx]
            d = float(dists[near_idx])
            if d < 1e-6:
                continue

            q_new = near + (sample - near) / d * min(step_size, d)
            if not segment_free(near, q_new, obstacles):
                continue

            best_parent = near_idx
            best_cost = costs[near_idx] + float(np.linalg.norm(q_new - near))

            if use_rrt_star:
                new_dists = np.linalg.norm(pts - q_new, axis=1)
                near_indices = np.where(new_dists <= rewire_radius)[0]
                for idx in near_indices:
                    cand_cost = costs[idx] + float(new_dists[idx])
                    if cand_cost < best_cost and segment_free(nodes[idx], q_new, obstacles):
                        best_parent = int(idx)
                        best_cost = cand_cost

            new_idx = len(nodes)
            nodes.append(q_new)
            parents.append(best_parent)
            costs.append(best_cost)

            if use_rrt_star:
                pts = np.array(nodes)
                new_dists = np.linalg.norm(pts[:-1] - q_new, axis=1)
                near_indices = np.where(new_dists <= rewire_radius)[0]
                for idx in near_indices:
                    rewired_cost = best_cost + float(new_dists[idx])
                    if rewired_cost < costs[idx] and segment_free(q_new, nodes[idx], obstacles):
                        parents[idx] = new_idx
                        costs[idx] = rewired_cost

            if float(np.linalg.norm(q_new - goal)) <= step_size and segment_free(q_new, goal, obstacles):
                if goal_idx is None:
                    goal_idx = len(nodes)
                    nodes.append(goal)
                    parents.append(new_idx)
                    costs.append(best_cost + float(np.linalg.norm(goal - q_new)))
                    if not use_rrt_star:
                        break
                elif use_rrt_star:
                    cand_g = best_cost + float(np.linalg.norm(goal - q_new))
                    if cand_g < costs[goal_idx]:
                        parents[goal_idx] = new_idx
                        costs[goal_idx] = cand_g

        path = []
        path_len = None
        if goal_idx is not None:
            cur = goal_idx
            while cur != -1:
                path.append(nodes[cur])
                cur = parents[cur]
            path.reverse()
            path_len = sum(float(np.linalg.norm(path[i] - path[i - 1])) for i in range(1, len(path)))

        return nodes, parents, path, path_len

    return get_obstacles, plan_rrt


@app.cell
def _(mo):
    planner_dd = mo.ui.dropdown(["RRT", "RRT*"], value="RRT", label="Planner")
    obs_dd = mo.ui.dropdown(["narrow-gap", "blocks"], value="narrow-gap", label="Obstacles")
    iters_s = mo.ui.slider(100, 900, step=50, value=450, label="Max samples")
    seed_s = mo.ui.slider(1, 50, step=1, value=42, label="Random seed")

    mo.vstack([
        mo.hstack([planner_dd, obs_dd], justify="start"),
        mo.hstack([iters_s, seed_s], justify="start"),
    ])
    return iters_s, obs_dd, planner_dd, seed_s


@app.cell
def _(get_obstacles, iters_s, mo, obs_dd, plan_rrt, planner_dd, plt, seed_s):
    _obs = get_obstacles(obs_dd.value)
    _start, _goal = (1.2, 4.0), (8.8, 4.0)
    _nodes, _parents, _path, _plen = plan_rrt(
        _start,
        _goal,
        _obs,
        max_iters=iters_s.value,
        use_rrt_star=(planner_dd.value == "RRT*"),
        seed=seed_s.value,
    )

    _fig, _ax = plt.subplots(figsize=(8.2, 5.2))
    for _xmin, _ymin, _xmax, _ymax in _obs:
        _ax.add_patch(
            plt.Rectangle((_xmin, _ymin), _xmax - _xmin, _ymax - _ymin, color="#374151", alpha=0.85)
        )

    for _i in range(1, len(_nodes)):
        _p_idx = _parents[_i]
        if _p_idx >= 0:
            _a, _b = _nodes[_p_idx], _nodes[_i]
            _ax.plot([_a[0], _b[0]], [_a[1], _b[1]], color="#3b82f6", lw=0.9, alpha=0.55)

    if _path:
        _px = [_pt[0] for _pt in _path]
        _py = [_pt[1] for _pt in _path]
        _ax.plot(_px, _py, color="#16a34a", lw=3, label="Final Path")

    _ax.scatter([_start[0]], [_start[1]], s=100, color="#2563eb", ec="white", lw=1.5, zorder=5, label="Start")
    _ax.scatter([_goal[0]], [_goal[1]], s=100, color="#dc2626", ec="white", lw=1.5, zorder=5, label="Goal")
    _ax.set_xlim(0, 10)
    _ax.set_ylim(0, 8)
    _ax.set_aspect("equal")
    _ax.grid(True, alpha=0.2)
    _ax.legend(loc="upper left", fontsize=8)
    _status = f"Path length = {_plen:.2f} m" if _plen is not None else "No path found yet"
    _ax.set_title(f"{planner_dd.value} ({len(_nodes)} nodes)  |  {_status}")

    mo.vstack([_fig])
    return


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

    1. **RRT vs. RRT\* optimality:** Run both `RRT` and `RRT*` with `seed=7` and `max_iters=600` on `"blocks"`. How much shorter is the RRT\* path after rewiring?
    2. **Curse of dimensionality arithmetic:** Compute in Python how many grid cells a 7-DOF arm needs at 40 bins per joint (`40**7`), and how many gigabytes of `float64` memory that single grid would consume.
    """)
    return


@app.cell
def _(get_obstacles, plan_rrt):
    # Exercise sandbox — edit and run!
    _obs_ex = get_obstacles("blocks")
    for _is_star, _label in [(False, "RRT "), (True, "RRT*")]:
        _n, _p, _path, _l = plan_rrt((1.2, 4.0), (8.8, 4.0), _obs_ex, max_iters=600, use_rrt_star=_is_star, seed=7)
        print(f"{_label} | nodes = {len(_n):3d} | path = {_l if _l else 'None'}")

    _cells_7d = 40 ** 7
    _gb = (_cells_7d * 8) / (1024 ** 3)
    print(f"7-DOF grid (40 bins/joint): {_cells_7d:,} cells ≈ {_gb:,.1f} GB")
    return


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