Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,19 @@ 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
```

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
Expand Down
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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'"]

Expand All @@ -28,6 +28,7 @@ dev = [
"pytorch-kinematics>=0.7",
"ruff>=0.14",
"scikit-fmm>=2024.5.29",
"scipy>=1.11",
"tyro>=0.9",
]

Expand Down
3 changes: 2 additions & 1 deletion src/ntfields/__init__.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -10,6 +10,7 @@

__all__ = [
"Batch",
"EncodedGoalField",
"Epochs",
"Field",
"GoalField",
Expand Down
6 changes: 3 additions & 3 deletions src/ntfields/accel/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)."""
Expand Down
3 changes: 2 additions & 1 deletion src/ntfields/envs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]] = {
Expand All @@ -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"]
101 changes: 101 additions & 0 deletions src/ntfields/envs/grid.py
Original file line number Diff line number Diff line change
@@ -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()
12 changes: 6 additions & 6 deletions src/ntfields/eval/metrics.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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())
15 changes: 11 additions & 4 deletions src/ntfields/field.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)."""
Expand Down
51 changes: 51 additions & 0 deletions src/ntfields/grid.py
Original file line number Diff line number Diff line change
@@ -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)
4 changes: 2 additions & 2 deletions src/ntfields/gt/__init__.py
Original file line number Diff line number Diff line change
@@ -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"]
Loading
Loading