diff --git a/README.md b/README.md index b9f59b3..96caba4 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ path = result.path.cpu() print(result.success, is_collision_free(problem, path), path_cost(problem, path)) gt = fmm_travel_time(problem, goal.cpu()) # ground truth (needs the [gt] extra) -print(travel_time_error(field, gt, sample_valid(problem, 500).to(device))) +print(travel_time_error(field, gt, goal, sample_valid(problem, 500).to(device))) field = ntfields.load(field.ckpt_path, device=device) # reload later from the checkpoint ``` @@ -59,6 +59,11 @@ field = ntfields.load(field.ckpt_path, device=device) # reload later from the c For many queries against one goal, `field.towards(goal)` encodes the goal once and gives `.travel_time(q)` and `.gradient(q)` for batches q; MPPI plans this way. +`ntfields.gt.FMMField(problem)` is the same FMM ground truth as a field: one cached solve per goal, interpolated +with Catmull-Rom (`interp="linear"` for multilinear), so planners and `ntfields.eval` take it in place of a trained +field. `ntfields.envs.GridEnv.from_occupancy(grid, resolution, origin)` makes an environment from an occupancy grid +(a pyrobosim or ROS map), for FMM or training. + The same run from the CLI (needs the `[cli]` extra). `--method.*` sets any field of the method's config: ```bash diff --git a/pyproject.toml b/pyproject.toml index 43fa83d..339a275 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -13,7 +13,7 @@ dependencies = [ [project.optional-dependencies] arm = ["pytorch-kinematics>=0.7"] cli = ["tyro>=0.9"] -gt = ["scikit-fmm>=2024.5.29"] +gt = ["scikit-fmm>=2024.5.29", "scipy>=1.11"] # serialized engines load only with the TensorRT they were built with; no wheels for Python 3.11 tensorrt = ["torch-tensorrt>=2.14,<2.15; python_version >= '3.12'"] @@ -28,6 +28,7 @@ dev = [ "pytorch-kinematics>=0.7", "ruff>=0.14", "scikit-fmm>=2024.5.29", + "scipy>=1.11", "tyro>=0.9", ] diff --git a/src/ntfields/__init__.py b/src/ntfields/__init__.py index 8a760ed..7f3f9e2 100644 --- a/src/ntfields/__init__.py +++ b/src/ntfields/__init__.py @@ -1,7 +1,7 @@ from ntfields.api import TrainConfig, train from ntfields.base import Batch, LossOut, Method, MethodConfig, SceneCondition, TrainState, TravelTimeModel from ntfields.checkpoint import load -from ntfields.field import Field, GoalField, TrainedField +from ntfields.field import EncodedGoalField, Field, GoalField, TrainedField from ntfields.problem import Problem from ntfields.registry import available, get_method, register from ntfields.train import Epochs, TimeLimit @@ -10,6 +10,7 @@ __all__ = [ "Batch", + "EncodedGoalField", "Epochs", "Field", "GoalField", diff --git a/src/ntfields/accel/__init__.py b/src/ntfields/accel/__init__.py index 9006c12..e083e59 100644 --- a/src/ntfields/accel/__init__.py +++ b/src/ntfields/accel/__init__.py @@ -26,7 +26,7 @@ from ntfields.accel.cuda_graphs import CudaGraphs from ntfields.base import Method -from ntfields.field import GoalField, TrainedField +from ntfields.field import EncodedGoalField, TrainedField from ntfields.inference import InferenceModel from ntfields.plan import PLANNERS, PlanResult from ntfields.problem import Problem @@ -69,10 +69,10 @@ def gradient(self, q_s: Tensor, q_g: Tensor) -> tuple[Tensor, Tensor]: _, g_s, g_g = self.inference.pair_gradient(q_s, q_g) return g_s, g_g - def towards(self, goal: Tensor) -> GoalField: + def towards(self, goal: Tensor) -> EncodedGoalField: """T(·, goal) for a goal (dim,), which is encoded once instead of once per query.""" with torch.no_grad(): - return GoalField(self.inference, self.inference.encode_goal(goal[None])) + return EncodedGoalField(self.inference, self.inference.encode_goal(goal[None])) def plan(self, start: Tensor, goal: Tensor, planner: str | None = None) -> PlanResult: """Single query with `planner` (default: the method's default planner).""" diff --git a/src/ntfields/envs/__init__.py b/src/ntfields/envs/__init__.py index df11213..30ed0f0 100644 --- a/src/ntfields/envs/__init__.py +++ b/src/ntfields/envs/__init__.py @@ -2,6 +2,7 @@ from ntfields.base import Environment from ntfields.envs.arm import ArmEnv +from ntfields.envs.grid import GridEnv from ntfields.envs.sphere_box import SphereBoxEnv PRESETS: dict[str, Callable[[], Environment]] = { @@ -21,4 +22,4 @@ def load_env(name: str) -> Environment: return PRESETS[name]() -__all__ = ["PRESETS", "ArmEnv", "SphereBoxEnv", "load_env"] +__all__ = ["PRESETS", "ArmEnv", "GridEnv", "SphereBoxEnv", "load_env"] diff --git a/src/ntfields/envs/grid.py b/src/ntfields/envs/grid.py new file mode 100644 index 0000000..3f3f1d7 --- /dev/null +++ b/src/ntfields/envs/grid.py @@ -0,0 +1,101 @@ +from collections.abc import Sequence +from dataclasses import dataclass +from typing import Self + +import numpy as np +import torch +from numpy.typing import ArrayLike +from torch import Tensor + +from ntfields.base import SceneCondition +from ntfields.grid import Interpolation, interpolate + + +@dataclass +class GridEnv: + """Point mass in an occupancy grid (2D or 3D), e.g. a map from pyrobosim or ROS. + + Array axis i is coordinate i, and cell `idx` covers `origin + idx * resolution` to `origin + (idx + 1) * + resolution`, so `bounds` is the whole map. (A ROS `OccupancyGrid`'s data is row-major (y, x): transpose it.) + + `distance` interpolates a signed distance stored at the cell centres (`sdf`): the Euclidean distance transform of + the occupancy, half a cell short, so it is 0 on the boundary between a free and an occupied cell. It is accurate + to about half a cell. Linear interpolation, the default, never overshoots, so a wall one cell thick stays a wall; + its gradient (the clearance normal training uses) jumps at cell edges, which "cubic" smooths. + """ + + bounds: Tensor # (dim, 2) + occupied: Tensor # (R_0, ..., R_{dim-1}) bool + sdf: Tensor # same shape, float64, at the cell centres + interp: Interpolation = "linear" + + @classmethod + def from_occupancy( + cls, + occupancy: ArrayLike, + resolution: float | Sequence[float], + origin: Sequence[float] | None = None, + interp: Interpolation = "linear", + ) -> Self: + """`occupancy`: nonzero = occupied (so ROS's -1, unknown, counts as occupied). `origin`: the map's lowest + corner (default 0). Needs scipy (the `gt` extra).""" + from scipy.ndimage import distance_transform_edt + + occupied = np.asarray(occupancy) != 0 + dim = occupied.ndim + if dim not in (2, 3): + raise ValueError(f"expected a 2D or 3D occupancy grid, got shape {occupied.shape}") + cell = np.broadcast_to(np.asarray(resolution, dtype=np.float64), (dim,)) + lo = np.zeros(dim) if origin is None else np.asarray(origin, dtype=np.float64) + bounds = np.stack([lo, lo + cell * occupied.shape], axis=-1) + + if not occupied.any(): + sdf = np.full(occupied.shape, np.inf) + elif occupied.all(): + sdf = np.full(occupied.shape, -np.inf) + else: + # distance_transform_edt(a) is, at each nonzero cell of a, the distance to the nearest zero cell + outside = distance_transform_edt(~occupied, sampling=cell) # free cell -> nearest occupied centre + inside = distance_transform_edt(occupied, sampling=cell) # occupied cell -> nearest free centre + half = 0.5 * cell.min() + sdf = np.where(occupied, half - inside, outside - half) # pyright: ignore[reportOperatorIssue] + return cls( + torch.tensor(bounds, dtype=torch.float32), + torch.from_numpy(occupied.copy()), + torch.from_numpy(np.asarray(sdf, dtype=np.float64)), + interp, + ) + + @property + def dim(self) -> int: + return self.bounds.shape[0] + + @property + def cell(self) -> Tensor: + """(dim,) cell side lengths.""" + lo, hi = self.bounds.double().unbind(-1) + return (hi - lo) / torch.tensor(self.occupied.shape, dtype=torch.float64) + + def distance(self, q: Tensor) -> Tensor: + """Signed distance to the nearest occupied cell (inf if there are none), clamped to the border outside.""" + if torch.isinf(self.sdf).all(): + return self.sdf.view(-1)[0].to(q).expand(q.shape[0]).clone() + half = self.cell / 2 + centres = torch.stack([self.bounds[:, 0].double() + half, self.bounds[:, 1].double() - half], dim=-1) + return interpolate(self.sdf, centres, q, self.interp) + + def in_bounds(self, q: Tensor) -> Tensor: + b = self.bounds.to(q) + return ((q >= b[:, 0]) & (q <= b[:, 1])).all(dim=-1) + + def is_valid(self, q: Tensor) -> Tensor: + """In bounds and in a free cell.""" + cell = self.cell.to(q.device) + size = torch.tensor(self.occupied.shape, device=q.device) + idx = ((q.double() - self.bounds[:, 0].to(q.device, torch.float64)) / cell).floor().long() + idx = idx.clamp(min=0).minimum(size - 1) # the upper bound belongs to the last cell + free = ~self.occupied.to(q.device)[tuple(idx.unbind(-1))] + return self.in_bounds(q) & free + + def condition(self) -> SceneCondition: + return SceneCondition() diff --git a/src/ntfields/eval/metrics.py b/src/ntfields/eval/metrics.py index 086f0fb..e24a906 100644 --- a/src/ntfields/eval/metrics.py +++ b/src/ntfields/eval/metrics.py @@ -1,8 +1,7 @@ import torch from torch import Tensor -from ntfields.field import Field -from ntfields.gt import GridField +from ntfields.field import Field, GoalField from ntfields.plan import PlanResult from ntfields.problem import Problem @@ -32,9 +31,10 @@ def plan_succeeded(problem: Problem, result: PlanResult) -> bool: return result.success and is_collision_free(problem, result.path) -def travel_time_error(field: Field, gt: GridField, starts: Tensor) -> float: - """Mean |T_field(start, goal) - T_gt(start)| over starts with a finite ground truth.""" - goals = gt.goal.to(starts).expand_as(starts) - t_gt = gt.value(starts) +def travel_time_error(field: Field, gt: GoalField, goal: Tensor, starts: Tensor) -> float: + """Mean |T_field(start, goal) - T_gt(start)| over starts with a finite reference, where `gt` is T(·, goal): e.g. + `ntfields.gt.fmm_travel_time(problem, goal)`, or any field's `towards(goal)`.""" + goals = goal.to(starts).expand_as(starts) + t_gt = gt.travel_time(starts) finite = t_gt.isfinite() return float((field.travel_time(starts, goals) - t_gt).abs()[finite].mean()) diff --git a/src/ntfields/field.py b/src/ntfields/field.py index df9803f..470d205 100644 --- a/src/ntfields/field.py +++ b/src/ntfields/field.py @@ -26,9 +26,16 @@ def gradient(self, q_s: Tensor, q_g: Tensor) -> tuple[Tensor, Tensor]: ... def towards(self, goal: Tensor) -> "GoalField": ... +class GoalField(Protocol): + """T(·, q_g) for one fixed goal: what `Field.towards` returns.""" + + def travel_time(self, q: Tensor) -> Tensor: ... # (B, dim) -> (B,) + def gradient(self, q: Tensor) -> Tensor: ... # (B, dim) -> ∇_q T (B, dim) + + @dataclass -class GoalField: - """T(·, q_g) for one goal, encoded once (see `TrainedField.towards`).""" +class EncodedGoalField: + """A network's T(·, q_g) for one goal, encoded once (see `TrainedField.towards`).""" inference: InferenceModel e_g: Tensor # inference.encode_goal(q_g) @@ -69,11 +76,11 @@ def gradient(self, q_s: Tensor, q_g: Tensor) -> tuple[Tensor, Tensor]: g_s, g_g = torch.autograd.grad(t.sum(), (q_s, q_g)) return g_s, g_g - def towards(self, goal: Tensor) -> GoalField: + def towards(self, goal: Tensor) -> EncodedGoalField: """T(·, goal) for a goal (dim,), which is encoded once instead of once per query.""" inference = autograd_inference(self.model, self.problem.env.condition()) with torch.no_grad(): - return GoalField(inference, inference.encode_goal(goal[None])) + return EncodedGoalField(inference, inference.encode_goal(goal[None])) def plan(self, start: Tensor, goal: Tensor, planner: str | None = None) -> PlanResult: """Single query with `planner` (default: the method's default planner).""" diff --git a/src/ntfields/grid.py b/src/ntfields/grid.py new file mode 100644 index 0000000..e33c62f --- /dev/null +++ b/src/ntfields/grid.py @@ -0,0 +1,51 @@ +"""Values on a regular grid of nodes (array axis i = coordinate i), interpolated between them.""" + +from typing import Literal + +import torch +import torch.nn.functional as F +from torch import Tensor + +Interpolation = Literal["linear", "cubic"] + + +def interpolate(values: Tensor, bounds: Tensor, q: Tensor, interp: Interpolation) -> Tensor: + """`values` (R_0, ..., R_{d-1}) on nodes spanning `bounds` (d, 2) end to end, at q (B, d) -> (B,) in q's dtype; + clamped to the border outside `bounds`. Differentiable in q. + + - "linear": multilinear, whose gradient jumps at every cell edge; + - "cubic": separable Catmull-Rom, which passes through the nodes and has a continuous gradient; it can overshoot + slightly next to kinks. + """ + values = values.to(q.device) + lo, hi = bounds.to(q.device, torch.float64).unbind(-1) + if interp == "linear": + u = (2 * (q.double() - lo) / (hi - lo) - 1).flip(-1) # grid_sample wants (x, y[, z]) = reversed axes + dim = q.shape[-1] + grid = u.reshape(1, -1, *[1] * (dim - 1), dim) + out = F.grid_sample(values[None, None], grid, align_corners=True, padding_mode="border").reshape(-1) + else: + out = _catmull_rom(values, (q.double() - lo) / (hi - lo)) + return out.to(q.dtype) + + +def _catmull_rom(values: Tensor, u: Tensor) -> Tensor: + """Separable Catmull-Rom interpolation of `values` (R_0, ..., R_{d-1}) at u (B, d) in [0, 1]^d (clamped), with + the edge nodes repeated past the border: 4^d taps per query, gathered at once.""" + values = values.contiguous() + device, dim = u.device, values.dim() + size = torch.tensor(values.shape, device=device) + x = u.clamp(0, 1) * (size - 1) + i0 = x.detach().floor().clamp(max=size - 2).long() + t = x - i0 + t2, t3 = t * t, t * t * t + # per axis: the 4 nodes i0-1..i0+2 and their weights, (B, d, 4) + nodes = (i0[..., None] + torch.arange(-1, 3, device=device)).clamp(min=0).minimum(size[:, None] - 1) + weights = torch.stack( + ((-t + 2 * t2 - t3) / 2, (2 - 5 * t2 + 3 * t3) / 2, (t + 4 * t2 - 3 * t3) / 2, (t3 - t2) / 2), -1 + ) + # every combination of one node per axis, (B, 4^d, d) + taps = torch.cartesian_prod(*[torch.arange(4, device=device)] * dim).reshape(-1, dim) + axes = torch.arange(dim, device=device) + flat_index = (nodes[:, axes, taps] * torch.tensor(values.stride(), device=device)).sum(-1) + return (weights[:, axes, taps].prod(-1) * values.view(-1)[flat_index]).sum(-1) diff --git a/src/ntfields/gt/__init__.py b/src/ntfields/gt/__init__.py index b3efb1b..9bdb966 100644 --- a/src/ntfields/gt/__init__.py +++ b/src/ntfields/gt/__init__.py @@ -1,3 +1,3 @@ -from ntfields.gt.fmm import GridField, fmm_travel_time +from ntfields.gt.fmm import FMMField, GridField, fmm_travel_time -__all__ = ["GridField", "fmm_travel_time"] +__all__ = ["FMMField", "GridField", "fmm_travel_time"] diff --git a/src/ntfields/gt/fmm.py b/src/ntfields/gt/fmm.py index 4c21ef9..7db46ec 100644 --- a/src/ntfields/gt/fmm.py +++ b/src/ntfields/gt/fmm.py @@ -1,10 +1,13 @@ -from dataclasses import dataclass +from collections import OrderedDict +from collections.abc import Callable +from dataclasses import dataclass, field import numpy as np import torch -import torch.nn.functional as F from torch import Tensor +from ntfields.grid import Interpolation, interpolate +from ntfields.plan import PLANNERS, PlanResult from ntfields.problem import Problem SEED_RADIUS_DX = 1.5 # skfmm needs a zero contour that encloses at least one node @@ -12,22 +15,44 @@ @dataclass class GridField: - """Travel time to `goal` on a regular grid (array axis i = coordinate i), multilinearly interpolated.""" + """Travel time to `goal` on a regular grid (array axis i = coordinate i), interpolated between the nodes (see + `ntfields.grid.interpolate`). Cubic, the default, has a continuous gradient, so descent doesn't zig-zag at cell + edges; it can overshoot slightly next to the seed and ridges. + + A `GoalField`: queries on another device than `values` copy the grid each time, so move it once with `to`. + """ values: Tensor # (R,) * dim, float64 bounds: Tensor # (dim, 2) goal: Tensor # (dim,) + interp: Interpolation = "cubic" + + @property + def device(self) -> torch.device: + return self.values.device + + def to(self, device: torch.device | str) -> "GridField": + return GridField(self.values.to(device), self.bounds.to(device), self.goal.to(device), self.interp) + + def travel_time(self, q: Tensor) -> Tensor: + """T(q, goal) (B,) for q (B, dim), clamped to the grid outside `bounds`.""" + with torch.no_grad(): + return self._interpolate(q) - def value(self, q: Tensor) -> Tensor: - lo, hi = self.bounds.to(q).unbind(-1) - u = (2 * (q - lo) / (hi - lo) - 1).flip(-1) # grid_sample wants (x, y[, z]) = reversed array axes - dim = q.shape[-1] - grid = u.reshape(1, -1, *[1] * (dim - 1), dim).double() - out = F.grid_sample(self.values[None, None].to(q.device), grid, align_corners=True, padding_mode="border") - return out.reshape(-1).to(q.dtype) + def gradient(self, q: Tensor) -> Tensor: + """∇_q T(q, goal) (B, dim), by autograd through the interpolation (0 outside `bounds`).""" + with torch.enable_grad(): + q = q.detach().requires_grad_(True) + (g,) = torch.autograd.grad(self._interpolate(q).sum(), q) + return g + def _interpolate(self, q: Tensor) -> Tensor: + return interpolate(self.values, self.bounds, q, self.interp) -def fmm_travel_time(problem: Problem, goal: Tensor, resolution: int = 201) -> GridField: + +def fmm_travel_time( + problem: Problem, goal: Tensor, resolution: int = 201, interp: Interpolation = "cubic" +) -> GridField: """Second-order fast marching of S* from `goal` (2D/3D); needs the `gt` extra (scikit-fmm).""" import skfmm @@ -42,4 +67,57 @@ def fmm_travel_time(problem: Problem, goal: Tensor, resolution: int = 201) -> Gr dist = (pts - goal.double()).norm(dim=-1).numpy() t = np.asarray(skfmm.travel_time(dist - r0, speed.numpy(), dx=dx, order=2)) # pyright: ignore[reportArgumentType] (per-axis dx is supported) t = np.where(dist <= r0, dist / s_goal, t + r0 / s_goal) - return GridField(torch.from_numpy(t), problem.env.bounds.clone(), goal.clone()) + return GridField(torch.from_numpy(t), problem.env.bounds.clone(), goal.clone(), interp) + + +@dataclass +class FMMField: + """The FMM ground truth as a `Field`: one `fmm_travel_time` solve per distinct goal, kept in an LRU cache. + + T(q_s, q_g) is symmetric (isotropic eikonal), so ∇_{q_g} T comes from the solve seeded at q_s; both directions + share the cache. Every new seed is a full solve: `gradient_bidirectional` moves both ends, so it solves twice per + step (milliseconds on a 2D grid, far more in 3D) and fills the cache with seeds it never reuses. The default + planner only moves the start. + """ + + problem: Problem + resolution: int = 201 + interp: Interpolation = "cubic" + cache_size: int = 64 + device: torch.device = field(default_factory=lambda: torch.device("cpu")) + default_planner: str = "mppi" + _cache: OrderedDict[bytes, GridField] = field(default_factory=OrderedDict, init=False, repr=False) + + def towards(self, goal: Tensor) -> GridField: + """T(·, goal) for a goal (dim,), solved on first use.""" + goal = goal.detach().to("cpu", torch.float64) + key = goal.numpy().tobytes() + if key in self._cache: + self._cache.move_to_end(key) + return self._cache[key] + gt = fmm_travel_time(self.problem, goal, self.resolution, self.interp).to(self.device) + self._cache[key] = gt + if len(self._cache) > self.cache_size: + self._cache.popitem(last=False) + return gt + + def travel_time(self, q_s: Tensor, q_g: Tensor) -> Tensor: + return self._per_seed(q_g, q_s, lambda gt, q: gt.travel_time(q), q_s.new_empty(len(q_s))) + + def gradient(self, q_s: Tensor, q_g: Tensor) -> tuple[Tensor, Tensor]: + """(∇_{q_s} T, ∇_{q_g} T).""" + g_s = self._per_seed(q_g, q_s, lambda gt, q: gt.gradient(q), torch.empty_like(q_s)) + g_g = self._per_seed(q_s, q_g, lambda gt, q: gt.gradient(q), torch.empty_like(q_g)) + return g_s, g_g + + def plan(self, start: Tensor, goal: Tensor, planner: str | None = None) -> PlanResult: + """Single query with `planner` (default: `default_planner`).""" + return PLANNERS[planner or self.default_planner](self, start, goal) + + def _per_seed(self, seeds: Tensor, q: Tensor, query: Callable[[GridField, Tensor], Tensor], out: Tensor) -> Tensor: + """`out[i] = query(towards(seeds[i]), q[i])`, one solve per distinct seed.""" + unique, inverse = torch.unique(seeds, dim=0, return_inverse=True) + for k, seed in enumerate(unique): + rows = inverse == k + out[rows] = query(self.towards(seed), q[rows]) + return out diff --git a/tests/test_end_to_end.py b/tests/test_end_to_end.py index 6877c46..169f7e4 100644 --- a/tests/test_end_to_end.py +++ b/tests/test_end_to_end.py @@ -28,7 +28,7 @@ def test_train_plan_evaluate(problem: Problem, tmp_path: Path): gt = fmm_travel_time(problem, goal, resolution=101) starts = torch.tensor([[-0.8, 0.7], [0.0, -0.8], [0.5, 0.5]]) - assert torch.isfinite(torch.tensor(travel_time_error(field, gt, starts))) + assert torch.isfinite(torch.tensor(travel_time_error(field, gt, goal, starts))) def test_cli_train(tmp_path: Path, capsys: pytest.CaptureFixture[str]): diff --git a/tests/unit/test_envs.py b/tests/unit/test_envs.py index f8787d2..3d46cee 100644 --- a/tests/unit/test_envs.py +++ b/tests/unit/test_envs.py @@ -1,6 +1,11 @@ +import numpy as np +import pytest import torch -from ntfields.envs import SphereBoxEnv, load_env +from ntfields import Problem +from ntfields.envs import GridEnv, SphereBoxEnv, load_env +from ntfields.grid import Interpolation +from ntfields.speed import Clipped def test_sphere_distance(): @@ -25,3 +30,70 @@ def test_is_valid(): def test_empty_env_is_inf(): env = load_env("box2d/empty") assert torch.isinf(env.distance(torch.zeros(3, 2))).all() + + +def _disc_grid(cell: float = 0.01, radius: float = 0.3, interp: Interpolation = "linear") -> GridEnv: + """[-1, 1]^2 with the cells whose centres lie within `radius` of the origin occupied.""" + n = round(2 / cell) + c = torch.linspace(-1 + cell / 2, 1 - cell / 2, n) + x, y = torch.meshgrid(c, c, indexing="ij") + return GridEnv.from_occupancy((x**2 + y**2 <= radius**2).numpy(), cell, origin=(-1, -1), interp=interp) + + +def test_grid_bounds_and_cells(): + env = GridEnv.from_occupancy(np.zeros((40, 20)), 0.05, origin=(1.0, -2.0)) + torch.testing.assert_close(env.bounds, torch.tensor([[1.0, 3.0], [-2.0, -1.0]])) + torch.testing.assert_close(env.cell, torch.tensor([0.05, 0.05], dtype=torch.float64)) + assert env.dim == 2 + + +@pytest.mark.parametrize("interp", ["linear", "cubic"]) +def test_grid_distance_matches_a_disc(interp: Interpolation): + env = _disc_grid(interp=interp) + q = torch.rand(2000, 2, generator=torch.Generator().manual_seed(0)) * 1.9 - 0.95 + exact = q.norm(dim=-1) - 0.3 + assert float((env.distance(q) - exact).abs().max()) < 0.01 # one cell + + +def test_grid_normals_point_away_from_the_disc(): + problem = Problem(_disc_grid(interp="cubic"), Clipped()) + q = torch.tensor([[0.5, 0.0], [0.0, -0.45], [-0.3, 0.3]]) + _, normal = problem.speed_and_normal(q) + torch.testing.assert_close(normal, torch.nn.functional.normalize(q), atol=0.05, rtol=0) + + +def test_grid_is_valid_looks_up_the_cell(): + occupancy = np.zeros((4, 3), dtype=bool) + occupancy[1, 2] = True # covers [0.5, 1.0] x [1.0, 1.5] + env = GridEnv.from_occupancy(occupancy, 0.5) + q = torch.tensor([[0.75, 1.25], [0.49, 1.25], [0.75, 0.99], [2.0, 1.5], [2.01, 0.5], [-0.01, 0.5]]) + assert env.is_valid(q).tolist() == [False, True, True, True, False, False] + + +def test_grid_sdf_is_zero_on_cell_boundaries(): + occupancy = np.zeros((10, 10), dtype=bool) + occupancy[5:, :] = True # x >= 0.5 occupied + env = GridEnv.from_occupancy(occupancy, 0.1) + q = torch.tensor([[0.5, 0.42], [0.3, 0.5], [0.8, 0.5]]) + torch.testing.assert_close(env.distance(q), torch.tensor([0.0, 0.2, -0.3]), atol=1e-6, rtol=0) + + +def test_grid_without_obstacles_is_inf(): + env = GridEnv.from_occupancy(np.zeros((8, 8)), 0.25) + assert torch.isinf(env.distance(torch.zeros(3, 2))).all() + assert env.is_valid(torch.ones(3, 2)).all() + + +def test_grid_3d_box(): + occupancy = np.zeros((20, 20, 20), dtype=bool) + occupancy[8:12, 8:12, 8:12] = True # [0.8, 1.2]^3 + env = GridEnv.from_occupancy(occupancy, 0.1) + q = torch.tensor([[1.0, 1.0, 1.0], [1.0, 1.0, 1.5], [1.6, 1.0, 1.0]]) + # half a cell short at the centre: its nearest cell centres are 0.15 deep, not 0.2 + torch.testing.assert_close(env.distance(q), torch.tensor([-0.2, 0.3, 0.4]), atol=0.05 + 1e-6, rtol=0) + assert env.is_valid(q).tolist() == [False, True, True] + + +def test_grid_rejects_1d(): + with pytest.raises(ValueError, match="2D or 3D"): + GridEnv.from_occupancy(np.zeros(10), 0.1) diff --git a/tests/unit/test_plan_eval.py b/tests/unit/test_plan_eval.py index 98e997f..b966f76 100644 --- a/tests/unit/test_plan_eval.py +++ b/tests/unit/test_plan_eval.py @@ -1,9 +1,12 @@ +import pytest import torch from ntfields import Problem, TrainedField -from ntfields.envs import load_env -from ntfields.eval import is_collision_free, path_cost, path_length, travel_time_error -from ntfields.gt import fmm_travel_time +from ntfields.envs import GridEnv, load_env +from ntfields.eval import is_collision_free, path_cost, path_length, plan_succeeded, travel_time_error +from ntfields.field import Field, GoalField +from ntfields.grid import Interpolation +from ntfields.gt import FMMField, GridField, fmm_travel_time from ntfields.methods.euclidean import Euclidean, EuclideanConfig from ntfields.plan import mppi from ntfields.registry import create @@ -23,14 +26,131 @@ def test_fmm_free_space_is_euclidean(): problem = _empty() gt = fmm_travel_time(problem, torch.tensor([0.2, -0.3]), resolution=101) q = torch.tensor([[0.9, 0.9], [-0.7, 0.1], [0.25, -0.3]], dtype=torch.float64) - torch.testing.assert_close(gt.value(q), (q - gt.goal.double()).norm(dim=-1), atol=0.01, rtol=0) - assert travel_time_error(_euclidean_field(problem), gt, q.float()) < 0.01 + torch.testing.assert_close(gt.travel_time(q), (q - gt.goal.double()).norm(dim=-1), atol=0.01, rtol=0) + assert travel_time_error(_euclidean_field(problem), gt, gt.goal, q.float()) < 0.01 + + +def test_grid_field_is_a_goal_field(): + gt: GoalField = fmm_travel_time(_empty(), torch.tensor([0.2, -0.3]), resolution=101) + assert isinstance(gt, GridField) + q = torch.tensor([[0.9, 0.9], [-0.7, 0.1]]) + assert gt.travel_time(q).dtype == q.dtype + + +@pytest.mark.parametrize("interp", ["linear", "cubic"]) +def test_grid_field_gradient_in_free_space(interp: Interpolation): + """In free space at full speed, ∇T is the unit vector away from the goal.""" + goal = torch.tensor([0.2, -0.3]) + gt = fmm_travel_time(_empty(), goal, resolution=201, interp=interp) + q = torch.tensor([[0.9, 0.9], [-0.7, 0.1], [0.6, -0.8]], dtype=torch.float64) + away = torch.nn.functional.normalize(q - goal.double(), dim=-1) + torch.testing.assert_close(gt.gradient(q), away, atol=0.03, rtol=0) + assert not gt.gradient(q).requires_grad + + +@pytest.mark.parametrize("interp", ["linear", "cubic"]) +def test_grid_field_gradient_matches_finite_differences(problem: Problem, interp: Interpolation): + gt = fmm_travel_time(problem, torch.tensor([0.6, 0.0]), resolution=101, interp=interp) + q = torch.tensor([[-0.613, 0.057], [0.031, 0.607]], dtype=torch.float64) # off grid lines, where it is smooth + h = 1e-6 + fd = torch.stack( + [(gt.travel_time(q + h * e) - gt.travel_time(q - h * e)) / (2 * h) for e in torch.eye(2, dtype=q.dtype)], dim=-1 + ) + torch.testing.assert_close(gt.gradient(q), fd, atol=1e-5, rtol=1e-5) + + +def test_cubic_passes_through_nodes(problem: Problem): + gt = fmm_travel_time(problem, torch.tensor([0.6, 0.0]), resolution=51) + nodes = torch.tensor([[-0.6, 0.12], [0.36, -0.8], [-1.0, 1.0]], dtype=torch.float64) # on the 0.04 grid + ij = ((nodes + 1) / 0.04).round().long() + torch.testing.assert_close(gt.travel_time(nodes), gt.values[ij[:, 0], ij[:, 1]]) + + +def test_cubic_gradient_is_continuous_across_cell_edges(problem: Problem): + """Linear interpolation's gradient jumps at a grid line; Catmull-Rom's doesn't.""" + edge = torch.tensor([[-0.6, 0.12]], dtype=torch.float64) # x = -0.6 is a grid line at resolution 51 + across = torch.tensor([[1e-7, 0.0]], dtype=torch.float64) + jump = {} + for interp in ("linear", "cubic"): + gt = fmm_travel_time(problem, torch.tensor([0.6, 0.0]), resolution=51, interp=interp) + jump[interp] = float((gt.gradient(edge + across) - gt.gradient(edge - across)).norm()) + assert jump["linear"] > 1e-2 + assert jump["cubic"] < 1e-5 + + +def test_cubic_reproduces_linear_functions_in_3d(): + axes = [torch.linspace(-1, 1, 11, dtype=torch.float64)] * 3 + x, y, z = torch.meshgrid(*axes, indexing="ij") + a = torch.tensor([0.5, -2.0, 1.5], dtype=torch.float64) + gt = GridField(a[0] * x + a[1] * y + a[2] * z, torch.tensor([[-1.0, 1.0]] * 3), torch.zeros(3)) + q = torch.rand(32, 3, generator=torch.Generator().manual_seed(0), dtype=torch.float64) * 1.6 - 0.8 # interior + torch.testing.assert_close(gt.travel_time(q), q @ a) + torch.testing.assert_close(gt.gradient(q), a.expand_as(q)) def test_fmm_detours_around_obstacle(problem: Problem): gt = fmm_travel_time(problem, torch.tensor([0.6, 0.0]), resolution=101) q = torch.tensor([[-0.6, 0.0]]) - assert gt.value(q) > 1.2 * 1.2 # longer than the straight line, even at full speed + assert gt.travel_time(q) > 1.2 * 1.2 # longer than the straight line, even at full speed + + +def test_fmm_field_pair_queries_match_towards(problem: Problem): + field: Field = FMMField(problem, resolution=101) + goals = torch.tensor([[0.6, 0.0], [-0.5, 0.5]]) + q_s = torch.tensor([[-0.6, 0.0], [0.7, 0.7], [0.1, -0.8], [-0.2, 0.6]]) + q_g = goals[[0, 1, 0, 1]] + expected = torch.stack([field.towards(g).travel_time(q[None])[0] for q, g in zip(q_s, q_g, strict=True)]) + torch.testing.assert_close(field.travel_time(q_s, q_g), expected) + g_s, _ = field.gradient(q_s, q_g) + torch.testing.assert_close( + g_s, torch.cat([field.towards(g).gradient(q[None]) for q, g in zip(q_s, q_g, strict=True)]) + ) + + +def test_fmm_field_caches_per_goal(problem: Problem): + field = FMMField(problem, resolution=51, cache_size=2) + a, b, c = torch.tensor([0.6, 0.0]), torch.tensor([-0.5, 0.5]), torch.tensor([0.0, -0.7]) + first = field.towards(a) + assert field.towards(a.clone()) is first + field.towards(b) + field.towards(c) + assert field.towards(a) is not first # evicted + + +def test_fmm_field_is_symmetric_and_goal_gradient_points_away_from_start(): + field = FMMField(_empty(), resolution=201) + q_s, q_g = torch.tensor([[-0.6, -0.3]]), torch.tensor([[0.5, 0.4]]) + torch.testing.assert_close(field.travel_time(q_s, q_g), field.travel_time(q_g, q_s), atol=0.01, rtol=0) + g_s, g_g = field.gradient(q_s, q_g) + torch.testing.assert_close(g_s, torch.nn.functional.normalize(q_s - q_g), atol=0.03, rtol=0) + torch.testing.assert_close(g_g, torch.nn.functional.normalize(q_g - q_s), atol=0.03, rtol=0) + + +@pytest.mark.parametrize("planner", ["mppi", "gradient_bidirectional"]) +def test_fmm_field_plans_around_obstacle(problem: Problem, planner: str): + field = FMMField(problem, resolution=101) + result = field.plan(torch.tensor([-0.6, 0.1]), torch.tensor([0.6, -0.1]), planner) + assert plan_succeeded(problem, result) + + +def test_fmm_on_a_grid_env_matches_the_sphere_env(problem: Problem): + """The one_sphere scene rasterized at 0.01: FMM on it agrees with FMM on the analytic scene, and plans in it.""" + c = torch.linspace(-0.995, 0.995, 200) + x, y = torch.meshgrid(c, c, indexing="ij") + grid = Problem(GridEnv.from_occupancy((x**2 + y**2 <= 0.09).numpy(), 0.01, origin=(-1, -1)), problem.speed) + goal = torch.tensor([0.6, -0.1]) + q = torch.tensor([[-0.6, 0.35], [-0.8, -0.6], [0.0, 0.7]]) + t_grid = fmm_travel_time(grid, goal, resolution=101).travel_time(q) + torch.testing.assert_close(t_grid, fmm_travel_time(problem, goal, resolution=101).travel_time(q), rtol=0.02, atol=0) + assert plan_succeeded(grid, FMMField(grid, resolution=101).plan(q[0], goal)) + + +def test_travel_time_error_takes_any_goal_field(problem: Problem): + goal = torch.tensor([0.6, 0.0]) + fmm = FMMField(problem, resolution=101) + starts = torch.tensor([[-0.6, 0.0], [0.0, 0.7], [0.5, -0.5]]) + assert travel_time_error(fmm, fmm.towards(goal), goal, starts) == 0.0 + assert travel_time_error(_euclidean_field(problem), fmm.towards(goal), goal, starts) > 0.1 # ignores the obstacle def test_path_metrics(problem: Problem): diff --git a/uv.lock b/uv.lock index 2518393..7b6ba46 100644 --- a/uv.lock +++ b/uv.lock @@ -1006,6 +1006,8 @@ cli = [ ] gt = [ { name = "scikit-fmm" }, + { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "scipy", version = "1.18.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, ] tensorrt = [ { name = "torch-tensorrt", marker = "python_full_version >= '3.12'" }, @@ -1019,6 +1021,8 @@ dev = [ { name = "pytorch-kinematics" }, { name = "ruff" }, { name = "scikit-fmm" }, + { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "scipy", version = "1.18.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, { name = "tyro" }, ] @@ -1028,6 +1032,7 @@ requires-dist = [ { name = "numpy", specifier = ">=1.26" }, { name = "pytorch-kinematics", marker = "extra == 'arm'", specifier = ">=0.7" }, { name = "scikit-fmm", marker = "extra == 'gt'", specifier = ">=2024.5.29" }, + { name = "scipy", marker = "extra == 'gt'", specifier = ">=1.11" }, { name = "torch", specifier = ">=2.4" }, { name = "torch-tensorrt", marker = "python_full_version >= '3.12' and extra == 'tensorrt'", specifier = ">=2.14,<2.15" }, { name = "tyro", marker = "extra == 'cli'", specifier = ">=0.9" }, @@ -1042,6 +1047,7 @@ dev = [ { name = "pytorch-kinematics", specifier = ">=0.7" }, { name = "ruff", specifier = ">=0.14" }, { name = "scikit-fmm", specifier = ">=2024.5.29" }, + { name = "scipy", specifier = ">=1.11" }, { name = "tyro", specifier = ">=0.9" }, ]