"""Plan-level safety review.
Every plan passes two checks before it can run:
1. per-step limits (allowed actions, distances, angles, speeds, waits, clearances, plan length);
2. a kinematic rollout of the whole plan from the current pose, so that a sequence of individually
harmless steps cannot leave the workspace.
In ``reject`` mode one violation rejects the whole plan: executing only the remaining steps would
leave the robot somewhere the user did not ask for.
In ``clamp`` mode out-of-range values are clipped and reported.
"""
from __future__ import annotations
import math
from collections.abc import Sequence
from dataclasses import dataclass, field
from .config import ReLIConfig
from .types import Action, Pose2D, wrap_angle
@dataclass
class Rollout:
end: Pose2D
path_length_m: float = 0.0
unmodelled: list[str] = field(default_factory=list) # perception-dependent steps
[docs]
@dataclass
class SafetyReport:
actions: list[Action] = field(default_factory=list)
violations: list[str] = field(default_factory=list)
adjustments: list[str] = field(default_factory=list)
rollout: Rollout | None = None
@property
def ok(self) -> bool:
return not self.violations
[docs]
class SafetyGuard:
def __init__(self, cfg: ReLIConfig):
self.cfg = cfg
self.s = cfg.safety
self.lim = cfg.robot.limits
# -------------------------------------------------------------- public
def review(self, primitives: Sequence[Action], pose: Pose2D) -> SafetyReport:
report = SafetyReport()
if not self.s.enabled:
report.actions = list(primitives)
report.rollout = self._rollout(report.actions, pose, report)
return report
if len(primitives) > self.s.max_plan_steps:
report.violations.append(
f"the plan has {len(primitives)} steps (limit {self.s.max_plan_steps})"
)
return report
for i, a in enumerate(primitives, 1):
checked = self._check_step(i, a, report)
if checked is not None:
report.actions.append(checked)
if report.violations:
return report
report.rollout = self._rollout(report.actions, pose, report)
return report
[docs]
def goal_allowed(self, x: float, y: float) -> bool:
"""Check a goal resolved at execution time (e.g. an object position)."""
ws = self.s.workspace
return not (self.s.enabled and ws) or (
ws.x_min <= x <= ws.x_max and ws.y_min <= y <= ws.y_max
)
# ------------------------------------------------------------ per step
def _check_step(self, i: int, a: Action, report: SafetyReport) -> Action | None:
if (
self.s.allowed_actions is not None
and a.name not in self.s.allowed_actions
and a.name != "STOP"
):
report.violations.append(f"step {i}: action {a.name} is not allowed")
return None
params = dict(a.params)
bounds = {
"distance": (0.0, self.s.max_distance_m, "m"),
"side_length": (0.0, self.s.max_distance_m, "m"),
"angle": (0.0, self.s.max_turn_deg, "deg"),
"duration": (0.0, self.s.max_wait_s, "s"),
"speed": (self.lim.linear_speed_min, self.lim.linear_speed_max, "m/s"),
"angular_speed": (1.0, self.lim.angular_speed_max_deg, "deg/s"),
}
if a.name == "ARC" and params.get("radius") is not None:
arc_len = params["radius"] * math.radians(params.get("angle") or 360.0)
if arc_len > self.s.max_distance_m:
report.violations.append(
f"step {i}: arc length {arc_len:.1f} m exceeds {self.s.max_distance_m} m"
)
return None
for key, (lo, hi, unit) in bounds.items():
value = params.get(key)
if value is None:
continue
if lo <= value <= hi:
continue
if self.s.on_violation == "clamp":
params[key] = min(max(value, lo), hi)
report.adjustments.append(f"step {i}: {key} {value:g} -> {params[key]:g} {unit}")
else:
report.violations.append(
f"step {i} ({a.name}): {key} {value:g} {unit} is outside [{lo:g}, {hi:g}]"
)
return None
clearance = params.get("clearance")
if clearance is not None and clearance < self.s.min_clearance_m:
if self.s.on_violation == "clamp":
params["clearance"] = self.s.min_clearance_m
report.adjustments.append(
f"step {i}: clearance raised to {self.s.min_clearance_m} m"
)
else:
report.violations.append(
f"step {i}: clearance {clearance} m is below {self.s.min_clearance_m} m"
)
return None
return Action(a.name, params)
# ------------------------------------------------------------- rollout
def _rollout(self, actions: Sequence[Action], start: Pose2D, report: SafetyReport) -> Rollout:
x, y, yaw = start.x, start.y, start.yaw
r = Rollout(end=start)
step = self.s.rollout_step_m
for i, a in enumerate(actions, 1):
if a.name == "MOVE":
d = a.params["distance"] * (-1 if a.get("direction") == "backward" else 1)
n = max(1, math.ceil(abs(d) / step))
for _ in range(n):
x += d / n * math.cos(yaw)
y += d / n * math.sin(yaw)
if not self._inside(x, y, i, a, report):
break
r.path_length_m += abs(d)
elif a.name == "TURN":
sign = 1 if a.get("direction", "left") == "left" else -1
yaw = wrap_angle(yaw + sign * math.radians(a.params["angle"]))
elif a.name == "ARC":
radius = a.params["radius"]
sweep = math.radians(a.get("angle", 360.0))
sign = 1 if a.get("direction", "left") == "left" else -1
n = max(4, math.ceil(radius * sweep / step))
for _ in range(n):
dpsi = sign * sweep / n
x += radius * sign * (math.sin(yaw + dpsi) - math.sin(yaw))
y -= radius * sign * (math.cos(yaw + dpsi) - math.cos(yaw))
yaw = wrap_angle(yaw + dpsi)
if not self._inside(x, y, i, a, report):
break
r.path_length_m += radius * sweep
elif a.name in ("GO_TO_COORDINATES", "GO_TO_DESTINATION"):
goal = self._goal(a)
if goal is None:
r.unmodelled.append(f"{i}:{a.name}")
continue
gx, gy, gyaw = goal
if not self._inside(gx, gy, i, a, report):
break
r.path_length_m += math.hypot(gx - x, gy - y) # lower bound
yaw = gyaw if gyaw is not None else math.atan2(gy - y, gx - x)
x, y = gx, gy
elif a.name in ("GO_TO_OBJECT", "FACE_OBJECT", "CIRCLE_OBJECT"):
r.unmodelled.append(f"{i}:{a.name}")
if report.violations:
break
r.end = Pose2D(x, y, yaw)
return r
def _goal(self, a: Action) -> tuple[float, float, float | None] | None:
if a.name == "GO_TO_COORDINATES":
yaw = a.get("yaw")
return a.params["x"], a.params["y"], (math.radians(yaw) if yaw is not None else None)
dest = self.cfg.destinations.get(a.params.get("destination", ""))
if dest is None:
return None
return dest.x, dest.y, (math.radians(dest.yaw_deg) if dest.yaw_deg is not None else None)
def _inside(self, x: float, y: float, i: int, a: Action, report: SafetyReport) -> bool:
ws = self.s.workspace
if not self.s.enabled or ws is None:
return True
if ws.x_min <= x <= ws.x_max and ws.y_min <= y <= ws.y_max:
return True
report.violations.append(
f"step {i} ({a.name}) would leave the workspace at ({x:.2f}, {y:.2f})"
)
return False