Preserve installed operator workspace before consolidation
Local preservation snapshot, not a new deployment or simulation acceptance.
This commit is contained in:
@@ -0,0 +1,114 @@
|
||||
"""Vendor-neutral two-side speed intent. No transport, motor calls or body motion.
|
||||
|
||||
Positive speed is forward; positive yaw turns left. Physical adapters must
|
||||
declare how this intent maps to their actuator, including zero/coast/brake.
|
||||
"""
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
def finite(*values):
|
||||
if not all(math.isfinite(value) for value in values):
|
||||
raise ValueError("Drive values must be finite")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SideSpeeds:
|
||||
left_mps: float = 0.0
|
||||
right_mps: float = 0.0
|
||||
|
||||
def __post_init__(self):
|
||||
finite(self.left_mps, self.right_mps)
|
||||
|
||||
@classmethod
|
||||
def from_twist(cls, velocity_mps, yaw_rps, track_centres_m):
|
||||
finite(velocity_mps, yaw_rps, track_centres_m)
|
||||
if track_centres_m <= 0:
|
||||
raise ValueError("Track centre distance must be positive")
|
||||
return cls(
|
||||
velocity_mps - yaw_rps * track_centres_m / 2,
|
||||
velocity_mps + yaw_rps * track_centres_m / 2,
|
||||
)
|
||||
|
||||
def twist(self, track_centres_m):
|
||||
finite(track_centres_m)
|
||||
if track_centres_m <= 0:
|
||||
raise ValueError("Track centre distance must be positive")
|
||||
return (
|
||||
(self.left_mps + self.right_mps) / 2,
|
||||
(self.right_mps - self.left_mps) / track_centres_m,
|
||||
)
|
||||
|
||||
def bounded(self, maximum_mps):
|
||||
finite(maximum_mps)
|
||||
if maximum_mps <= 0:
|
||||
raise ValueError("Side speed limit must be positive")
|
||||
scale = max(1.0, abs(self.left_mps) / maximum_mps, abs(self.right_mps) / maximum_mps)
|
||||
return SideSpeeds(self.left_mps / scale, self.right_mps / scale)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DriveLimits:
|
||||
track_centres_m: float
|
||||
max_side_speed_mps: float
|
||||
acceleration_mps2: float
|
||||
deceleration_mps2: float
|
||||
max_step_seconds: float
|
||||
|
||||
def __post_init__(self):
|
||||
values = tuple(vars(self).values())
|
||||
finite(*values)
|
||||
if min(values) <= 0:
|
||||
raise ValueError("Drive limits must be positive")
|
||||
|
||||
|
||||
def tank_intent(left, right, limits):
|
||||
finite(left, right)
|
||||
if max(abs(left), abs(right)) > 1:
|
||||
raise ValueError("Stick inputs must be within [-1, 1]")
|
||||
return SideSpeeds(left * limits.max_side_speed_mps, right * limits.max_side_speed_mps)
|
||||
|
||||
|
||||
def arcade_intent(throttle, steering, limits, max_yaw_rps):
|
||||
finite(throttle, steering, max_yaw_rps)
|
||||
if max(abs(throttle), abs(steering)) > 1 or max_yaw_rps <= 0:
|
||||
raise ValueError("Invalid arcade input or yaw limit")
|
||||
return SideSpeeds.from_twist(
|
||||
throttle * limits.max_side_speed_mps, steering * max_yaw_rps, limits.track_centres_m
|
||||
).bounded(limits.max_side_speed_mps)
|
||||
|
||||
|
||||
class TwoSideDrive:
|
||||
"""Slew both targets on one clock, with explicit immediate zero intent.
|
||||
|
||||
Each reversing side reaches zero before accelerating in its new direction.
|
||||
The other side need not stop. A late update cannot create a large speed jump.
|
||||
This limits commands, not measured chassis acceleration or stopping distance.
|
||||
"""
|
||||
|
||||
def __init__(self, limits):
|
||||
self.limits = limits
|
||||
self.applied = SideSpeeds()
|
||||
|
||||
def step(self, requested, dt, *, stop=False):
|
||||
finite(dt)
|
||||
if dt < 0:
|
||||
raise ValueError("Drive step must not be negative")
|
||||
target = requested.bounded(self.limits.max_side_speed_mps)
|
||||
if stop or target == SideSpeeds():
|
||||
self.applied = SideSpeeds()
|
||||
return self.applied
|
||||
dt = min(dt, self.limits.max_step_seconds)
|
||||
old = (self.applied.left_mps, self.applied.right_mps)
|
||||
goal = (target.left_mps, target.right_mps)
|
||||
goal = tuple(0.0 if a * b < 0 else b for a, b in zip(old, goal, strict=True))
|
||||
fraction = 1.0
|
||||
for a, b in zip(old, goal, strict=True):
|
||||
rate = (
|
||||
self.limits.acceleration_mps2 if abs(b) > abs(a) else self.limits.deceleration_mps2
|
||||
)
|
||||
if a != b:
|
||||
fraction = min(fraction, rate * dt / abs(b - a))
|
||||
self.applied = SideSpeeds(*(a + (b - a) * fraction for a, b in zip(old, goal, strict=True)))
|
||||
return self.applied
|
||||
@@ -1196,7 +1196,7 @@ class ObservatoryRecordedJobQueue:
|
||||
A lost heartbeat does not prove GPU release. This reservation survives
|
||||
restarts and is removed only by the exact simulator's release receipt.
|
||||
"""
|
||||
if not re.fullmatch(r"airun-[a-f0-9]{32}", owner_id):
|
||||
if not re.fullmatch(r"(?:airun-[a-f0-9]{32}|aicache-[a-f0-9]{64})", owner_id):
|
||||
raise ValueError("invalid simulation resource owner")
|
||||
with self._transaction() as connection:
|
||||
existing = connection.execute(
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Named AI intent, shared by locations; runs retain their own immutable copy."""
|
||||
|
||||
import json
|
||||
import re
|
||||
import threading
|
||||
from uuid import uuid4
|
||||
|
||||
from k1link.artifacts import utc_now_iso
|
||||
from k1link.simulation.ai_polygon.composition import compose
|
||||
from k1link.simulation.ai_polygon.worlds import write_json
|
||||
|
||||
PROFILE_ID = re.compile(r"^aiprofile-[a-f0-9]{32}$")
|
||||
|
||||
|
||||
class AiProfileStore:
|
||||
def __init__(self, root, adapters):
|
||||
self.root, self.adapters = root, adapters
|
||||
self.lock = threading.RLock()
|
||||
root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
|
||||
def path(self, identity):
|
||||
if not PROFILE_ID.fullmatch(identity):
|
||||
raise FileNotFoundError(identity)
|
||||
path = self.root / (identity + ".json")
|
||||
if path.is_symlink():
|
||||
raise ValueError("AI profile must be a regular file")
|
||||
return path
|
||||
|
||||
def get(self, identity):
|
||||
return json.loads(self.path(identity).read_text())
|
||||
|
||||
def list(self):
|
||||
with self.lock:
|
||||
rows = [self.get(p.stem) for p in self.root.glob("aiprofile-*.json")]
|
||||
return sorted((r for r in rows if not r["removed"]), key=lambda r: r["name"].casefold())
|
||||
|
||||
def save(self, name, selection, *, identity=None, expected_revision=None, removed=False):
|
||||
with self.lock:
|
||||
old = self.get(identity) if identity else None
|
||||
if old and expected_revision != old["revision"]:
|
||||
raise RuntimeError("Профиль изменён в другом окне. Обновите список профилей.")
|
||||
name = (name if name is not None else old["name"]).strip()
|
||||
if not name or len(name) > 120:
|
||||
raise ValueError("Укажите название профиля длиной до 120 символов.")
|
||||
if not removed and any(r["name"].casefold() == name.casefold()
|
||||
and r["profile_id"] != identity for r in self.list()):
|
||||
raise ValueError("Профиль с таким названием уже существует.")
|
||||
# Label edits remain possible even if a provider has been uninstalled.
|
||||
composition = (compose(self.adapters, selection).selection_document()
|
||||
if selection is not None else old["composition"])
|
||||
now = utc_now_iso()
|
||||
value = dict(schema_version="missioncore.simulation-ai-profile/v1",
|
||||
profile_id=identity or "aiprofile-" + uuid4().hex,
|
||||
name=name, composition=composition, removed=removed,
|
||||
revision=old["revision"] + 1 if old else 1,
|
||||
created_at=old["created_at"] if old else now, updated_at=now)
|
||||
write_json(self.path(value["profile_id"]), value)
|
||||
return value
|
||||
@@ -0,0 +1,273 @@
|
||||
"""Dual-origin fisheye optics and rectification; never a central-camera shortcut.
|
||||
|
||||
X4 factory coefficients are unavailable. This is an explicitly ideal
|
||||
equidistant surrogate with real lens separation, circular coverage and body
|
||||
occlusion rendered by RTX. Pixel coordinates denote pixel edges (centres +.5).
|
||||
"""
|
||||
|
||||
import math
|
||||
from collections import OrderedDict
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
def axes(yaw=0.0, pitch=0.0):
|
||||
y, p = math.radians(yaw % 360), math.radians(pitch)
|
||||
return np.array(
|
||||
[
|
||||
[math.cos(y) * math.cos(p), -math.sin(y), -math.cos(y) * math.sin(p)],
|
||||
[math.sin(y) * math.cos(p), math.cos(y), -math.sin(y) * math.sin(p)],
|
||||
[math.sin(p), 0, math.cos(p)],
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def fisheye_intrinsics(spec):
|
||||
w, h = spec["image_size"]
|
||||
focal = (min(w, h) / 2 - 1) / math.radians(spec["full_fov_degrees"] / 2)
|
||||
return focal, focal, w / 2, h / 2
|
||||
|
||||
|
||||
def fisheye_project(directions, lens_axes, spec):
|
||||
local = np.einsum(
|
||||
"...i,ij->...j", np.asarray(directions), np.asarray(lens_axes), optimize=False
|
||||
)
|
||||
transverse = np.linalg.norm(local[..., 1:], axis=-1)
|
||||
theta = np.arctan2(transverse, local[..., 0])
|
||||
scale = theta / np.maximum(transverse, 1e-12)
|
||||
fx, fy, cx, cy = fisheye_intrinsics(spec)
|
||||
u, v = cx - fx * scale * local[..., 1], cy - fy * scale * local[..., 2]
|
||||
valid = (theta <= math.radians(spec["full_fov_degrees"] / 2)) & (
|
||||
np.linalg.norm(local, axis=-1) > 1e-10
|
||||
)
|
||||
return u, v, valid
|
||||
|
||||
|
||||
def fisheye_rays(u, v, lens_axes, spec):
|
||||
fx, fy, cx, cy = fisheye_intrinsics(spec)
|
||||
a, b = -(np.asarray(u) - cx) / fx, -(np.asarray(v) - cy) / fy
|
||||
theta = np.hypot(a, b)
|
||||
scale = np.sinc(theta / np.pi)
|
||||
local = np.stack((np.cos(theta), a * scale, b * scale), axis=-1)
|
||||
return local @ np.asarray(lens_axes).T
|
||||
|
||||
|
||||
def pinhole_rays(size, intrinsics):
|
||||
w, h = size
|
||||
u, v = np.meshgrid(np.arange(w) + 0.5, np.arange(h) + 0.5)
|
||||
fx, fy, cx, cy = intrinsics
|
||||
rays = np.stack((np.ones_like(u), -(u - cx) / fx, -(v - cy) / fy), axis=-1)
|
||||
return rays / np.linalg.norm(rays, axis=-1, keepdims=True)
|
||||
|
||||
|
||||
def sample_nearest(image, u, v):
|
||||
# Clamping is only an array access guard. Callers must preserve validity.
|
||||
return image[
|
||||
np.clip(v.astype(int), 0, image.shape[0] - 1), np.clip(u.astype(int), 0, image.shape[1] - 1)
|
||||
]
|
||||
|
||||
|
||||
class DualFisheye:
|
||||
def __init__(self, spec):
|
||||
self.spec = spec
|
||||
self.lens_axes = np.stack([axes(yaw) for yaw in spec["lens_yaw_degrees"]])
|
||||
w, h = spec["panorama_size"]
|
||||
longitude, latitude = np.meshgrid(
|
||||
(np.arange(w) + 0.5) * (2 * np.pi / w) - np.pi,
|
||||
np.pi / 2 - (np.arange(h) + 0.5) * (np.pi / h),
|
||||
)
|
||||
pano = np.stack(
|
||||
(
|
||||
np.cos(latitude) * np.cos(longitude),
|
||||
-np.cos(latitude) * np.sin(longitude),
|
||||
np.sin(latitude),
|
||||
),
|
||||
axis=-1,
|
||||
)
|
||||
self.panorama_map = self.mapping(pano)
|
||||
self.views = OrderedDict()
|
||||
self.feathered_views = OrderedDict()
|
||||
|
||||
def mapping(self, rays, lens=None):
|
||||
owner = np.argmax(
|
||||
np.einsum("...i,ji->...j", rays, self.lens_axes[:, :, 0], optimize=False), axis=-1
|
||||
)
|
||||
if lens is not None:
|
||||
if type(lens) is not int or lens not in (0, 1):
|
||||
raise ValueError("Invalid source lens")
|
||||
owner = np.full(owner.shape, lens)
|
||||
uv = [fisheye_project(rays, lens, self.spec) for lens in self.lens_axes]
|
||||
valid = np.zeros(owner.shape, dtype=bool)
|
||||
for i, (_, _, visible) in enumerate(uv):
|
||||
valid |= (owner == i) & visible
|
||||
# Store integer gather indices once, rather than allocating masks and
|
||||
# converting a million floating coordinates for every sensor frame.
|
||||
lookup = []
|
||||
w, h = self.spec["image_size"]
|
||||
for i, (u, v, _) in enumerate(uv):
|
||||
selected = np.flatnonzero(valid & (owner == i))
|
||||
source = np.clip(v.ravel()[selected].astype(np.int32), 0, h - 1) * w + np.clip(
|
||||
u.ravel()[selected].astype(np.int32), 0, w - 1
|
||||
)
|
||||
lookup.append((selected, source))
|
||||
return owner, uv, valid, lookup
|
||||
|
||||
def render(self, images, mapping):
|
||||
if len(images) != 2 or any(
|
||||
image.shape != (*reversed(self.spec["image_size"]), 3) or image.dtype != np.uint8
|
||||
for image in images
|
||||
):
|
||||
raise ValueError("Expected two calibrated RGB fisheye frames")
|
||||
owner, _, _, lookup = mapping
|
||||
result = np.zeros((*owner.shape, 3), dtype=np.uint8)
|
||||
flat = result.reshape(-1, 3)
|
||||
for i, (selected, source) in enumerate(lookup):
|
||||
flat[selected] = images[i].reshape(-1, 3)[source]
|
||||
return result
|
||||
|
||||
def panorama(self, images):
|
||||
return self.render(images, self.panorama_map)
|
||||
|
||||
def rectify(self, images, view_axes, size, intrinsics, *, lens=None):
|
||||
key = (tuple(np.asarray(view_axes).ravel()), tuple(size), tuple(intrinsics), lens)
|
||||
if key not in self.views:
|
||||
rays = np.einsum(
|
||||
"...i,ji->...j",
|
||||
pinhole_rays(size, intrinsics).astype(np.float32),
|
||||
np.asarray(view_axes, dtype=np.float32),
|
||||
optimize=False,
|
||||
)
|
||||
self.views[key] = self.mapping(rays, lens)
|
||||
# Eight horizon sectors plus the near-ground perspective.
|
||||
if len(self.views) > 9:
|
||||
self.views.popitem(last=False)
|
||||
self.views.move_to_end(key)
|
||||
mapping = self.views[key]
|
||||
return self.render(images, mapping), mapping[2]
|
||||
|
||||
def rectify_forward(self, images, view_axes, size, intrinsics):
|
||||
"""Stable body view with a bounded optical overlap, not a lens switch.
|
||||
|
||||
This is an ideal two-origin feather stitch, not the proprietary X4
|
||||
optical-flow stitch. Geometry projection retains both physical origins
|
||||
and their visibility/depth checks; the output is never a depth camera.
|
||||
Only the requested perspective is made, not a full panorama first.
|
||||
"""
|
||||
key = (tuple(np.asarray(view_axes).ravel()), tuple(size), tuple(intrinsics))
|
||||
if key not in self.feathered_views:
|
||||
rays = pinhole_rays(size, intrinsics).astype(np.float32) @ np.asarray(view_axes).T
|
||||
mapping = self.mapping(rays)
|
||||
affinity = rays @ self.lens_axes[:, :, 0].T
|
||||
blend = np.clip(0.5 + (affinity[..., 0] - affinity[..., 1]) /
|
||||
(4 * math.sin(math.radians(4))), 0, 1).astype(np.float32)
|
||||
uv = mapping[1]
|
||||
overlap = uv[0][2] & uv[1][2] & (blend > 0) & (blend < 1)
|
||||
indices = np.flatnonzero(overlap)
|
||||
h, w = reversed(self.spec["image_size"])
|
||||
source = [np.clip(v.ravel()[indices].astype(int), 0, h - 1) * w
|
||||
+ np.clip(u.ravel()[indices].astype(int), 0, w - 1)
|
||||
for u, v, _ in uv]
|
||||
self.feathered_views[key] = (mapping, indices, source, blend.ravel()[indices, None])
|
||||
if len(self.feathered_views) > 5:
|
||||
self.feathered_views.popitem(last=False)
|
||||
mapping, indices, source, weights = self.feathered_views[key]
|
||||
result = self.render(images, mapping)
|
||||
result.reshape(-1, 3)[indices] = np.rint(
|
||||
images[0].reshape(-1, 3)[source[0]] * weights
|
||||
+ images[1].reshape(-1, 3)[source[1]] * (1 - weights)
|
||||
).astype(np.uint8)
|
||||
return result, mapping[2]
|
||||
|
||||
|
||||
def view_toward(pose_xy, body_axes, target_xy, height, *, single_lens=False):
|
||||
"""Only the declared task chooses a digital view; no scene truth is read."""
|
||||
if target_xy is None:
|
||||
return axes(45, -20) if single_lens else axes(0, -30)
|
||||
delta = np.array([*(np.asarray(target_xy) - pose_xy), 0.0]) @ body_axes
|
||||
yaw = math.degrees(math.atan2(delta[1], delta[0]))
|
||||
# Preserve a stable forward-looking semantic view as the target approaches.
|
||||
# Pointing downward at a near/underbody goal replaces the road context with
|
||||
# the chassis itself. Near geometry belongs to the independent depth branch;
|
||||
# already observed surface remains in the causal map. Yaw still selects any
|
||||
# direction around the full panorama without turning the chassis.
|
||||
# Overlapping fixed perspective sectors give the model stable intrinsics
|
||||
# and image context. Navigation may select another sector; small changes of
|
||||
# the target must not continuously resample the same stationary road.
|
||||
# Lens sectors are centred at 45 + 90k, not at 90k. Quantize relative
|
||||
# to their actual centres: rounding first and adding 45 selected a view
|
||||
# up to 90 degrees away, steering a forward task into a side branch.
|
||||
return axes(math.floor(yaw / 90) * 90 + 45, -20) if single_lens else axes(round(yaw / 45) * 45, -20)
|
||||
|
||||
|
||||
class LensObservationViews:
|
||||
"""Seam-free lens perspectives with stable road/horizon context.
|
||||
|
||||
Each frame uses one optical centre throughout. The complementary forward
|
||||
view is acquired from the other lens; no learned label crosses a stitch.
|
||||
Near geometry remains the depth branch's responsibility. This road model
|
||||
has not been qualified on downward-looking, horizon-free views.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.index = 0
|
||||
|
||||
def choose(self, requested):
|
||||
index, self.index = self.index, self.index + 1
|
||||
if index % 4 != 3:
|
||||
return requested
|
||||
return axes((-45, 135, -135, 45)[(index // 4) % 4], -20)
|
||||
|
||||
|
||||
class ObservationViews:
|
||||
"""Survey the full rig continuously while prioritizing the task view.
|
||||
|
||||
Looking only after a blockage is too late: the chassis may already cover
|
||||
the ground that a turn needs. One model inference is performed per frame;
|
||||
near ground alternates with flanks after three task views. Range observations
|
||||
and the command watchdog remain active for every processed observation.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.index = 0
|
||||
|
||||
def choose(self, requested):
|
||||
index = self.index
|
||||
self.index += 1
|
||||
if index % 4 != 3:
|
||||
return requested
|
||||
survey = index // 4
|
||||
if survey % 2 == 0:
|
||||
# The X4 sits ahead of the chassis. This view observes the strip
|
||||
# beyond the bumper which a horizon crop omits. It uses the same
|
||||
# two lens pixels, depth/self-occlusion and semantic confidence gates.
|
||||
return axes(0, -50)
|
||||
yaw = (45, -45, 90, -90, 135, -135, 180, 0)[(survey // 2) % 8]
|
||||
return axes(yaw, -20)
|
||||
|
||||
|
||||
class TaskViewIntent:
|
||||
"""An observed local goal survives a short survey, not a task-view rejection.
|
||||
|
||||
This retains intent only. Its original capture timestamp accompanies every
|
||||
use, so the actuator watchdog cannot renew it with a later survey frame.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.observed = None
|
||||
|
||||
def remember(self, goal, target, captured_at):
|
||||
self.observed = None
|
||||
if goal is not None:
|
||||
if not math.isfinite(captured_at) or not np.isfinite(goal).all():
|
||||
raise ValueError("Invalid observed task-view goal")
|
||||
self.observed = (list(goal), tuple(target) if target is not None else None, captured_at)
|
||||
|
||||
def recall(self, target, now, deadline=0.8):
|
||||
if self.observed is None:
|
||||
return None
|
||||
goal, before_target, captured_at = self.observed
|
||||
if before_target != (tuple(target) if target is not None else None):
|
||||
return None
|
||||
if not 0 <= now - captured_at <= deadline:
|
||||
return None
|
||||
return list(goal), captured_at
|
||||
@@ -6,6 +6,7 @@ Only installed adapters are executable; selection JSON never carries code.
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
|
||||
from k1link.observatory.modular_composition import (
|
||||
@@ -24,30 +25,52 @@ def digest(value):
|
||||
def registry(adapter_root: Path) -> ModuleRegistry:
|
||||
profile = json.loads((adapter_root / "models.worker-006.json").read_text())
|
||||
models = {m["id"]: m for m in profile["models"]}
|
||||
implementation = hashlib.sha256(
|
||||
Path(__file__).with_name("inference.py").read_bytes()
|
||||
).hexdigest()
|
||||
implementation = digest(
|
||||
{
|
||||
**{name: hashlib.sha256(Path(__file__).with_name(name).read_bytes()).hexdigest()
|
||||
for name in (
|
||||
"inference.py",
|
||||
"source_projection.py",
|
||||
"run_inputs.py",
|
||||
"camera_optics.py",
|
||||
"sensor_mounts.py",
|
||||
)},
|
||||
**{name: hashlib.sha256((adapter_root / name).read_bytes()).hexdigest()
|
||||
for name in ("continuous_composition.py", "continuous_pipeline.py", "process_pipeline.py", "urban_crossing.py")},
|
||||
}
|
||||
)
|
||||
ddr, detector = models["ddrnet-goose-pytorch-reference"], models["rf_detr_large"]
|
||||
nav = profile["navigation"]
|
||||
ade = models["segformer-b2-ade150"]
|
||||
return ModuleRegistry(
|
||||
city = models["segformer-b2-cityscapes19"]
|
||||
vistas = models["mask2former-mapillary65"]
|
||||
concepts = models["sam3-litetext-surfaces"]
|
||||
installed = ModuleRegistry(
|
||||
(
|
||||
ModuleSpec(
|
||||
"simulation-ddrnet-goose",
|
||||
"DDRNet · GOOSE 64",
|
||||
"segmentation",
|
||||
ddr["image"].removeprefix("sha256:"),
|
||||
implementation,
|
||||
digest(
|
||||
{
|
||||
"client": implementation,
|
||||
"server": hashlib.sha256(
|
||||
(adapter_root / "ddrnet_server.py").read_bytes()
|
||||
).hexdigest(),
|
||||
}
|
||||
),
|
||||
ddr["checkpoint_sha256"],
|
||||
digest(
|
||||
{
|
||||
"camera": profile["camera"],
|
||||
"preprocess": ddr["preprocess"],
|
||||
"labels": profile["labels_sha256"],
|
||||
"output": "goose64-labels-and-known-square512-v2",
|
||||
}
|
||||
),
|
||||
("source.camera.rgb",),
|
||||
("segmentation.labels", "segmentation.surface"),
|
||||
("segmentation.known", "segmentation.labels", "segmentation.surface"),
|
||||
),
|
||||
ModuleSpec(
|
||||
"simulation-segformer-ade",
|
||||
@@ -69,11 +92,82 @@ def registry(adapter_root: Path) -> ModuleRegistry:
|
||||
"preprocess": ade["preprocess"],
|
||||
"config": ade["config_sha256"],
|
||||
"processor": ade["processor_sha256"],
|
||||
"output": "ade150-labels-and-bool-surface-candidate-square512-v1",
|
||||
"output": "ade150-labels-candidate-and-known-square512-v2",
|
||||
}
|
||||
),
|
||||
("source.camera.rgb",),
|
||||
("segmentation.labels", "segmentation.surface"),
|
||||
("segmentation.known", "segmentation.labels", "segmentation.surface"),
|
||||
),
|
||||
ModuleSpec(
|
||||
"simulation-segformer-cityscapes",
|
||||
"SegFormer · городские улицы",
|
||||
"segmentation",
|
||||
city["image"].removeprefix("sha256:"),
|
||||
digest(
|
||||
{
|
||||
"client": implementation,
|
||||
"taxonomy": hashlib.sha256((adapter_root / "segformer/cityscapes.json").read_bytes()).hexdigest(),
|
||||
"server": hashlib.sha256(
|
||||
(adapter_root / "segformer/server.py").read_bytes()
|
||||
).hexdigest(),
|
||||
}
|
||||
),
|
||||
city["checkpoint_sha256"],
|
||||
digest(
|
||||
{
|
||||
"camera": profile["camera"],
|
||||
"preprocess": city["preprocess"],
|
||||
"config": city["config_sha256"],
|
||||
"processor": city["processor_sha256"],
|
||||
"output": "cityscapes19-labels-candidate-and-known-square512-v2",
|
||||
}
|
||||
),
|
||||
("source.camera.rgb",),
|
||||
("segmentation.known", "segmentation.labels", "segmentation.surface"),
|
||||
),
|
||||
ModuleSpec(
|
||||
"simulation-mask2former-mapillary",
|
||||
"Mask2Former · тротуары и переходы",
|
||||
"segmentation",
|
||||
vistas["image"].removeprefix("sha256:"),
|
||||
digest(
|
||||
{
|
||||
"client": implementation,
|
||||
"taxonomy": hashlib.sha256((adapter_root / "mapillary/model.json").read_bytes()).hexdigest(),
|
||||
"server": hashlib.sha256(
|
||||
(adapter_root / "mapillary/server.py").read_bytes()
|
||||
).hexdigest(),
|
||||
}
|
||||
),
|
||||
vistas["checkpoint_sha256"],
|
||||
digest(
|
||||
{
|
||||
"camera": profile["camera"],
|
||||
"preprocess": vistas["preprocess"],
|
||||
"config": vistas["config_sha256"],
|
||||
"processor": vistas["processor_sha256"],
|
||||
"output": "mapillary65-labels-candidate-and-known-square512-v2",
|
||||
}
|
||||
),
|
||||
("source.camera.rgb",),
|
||||
("segmentation.known", "segmentation.labels", "segmentation.surface"),
|
||||
),
|
||||
ModuleSpec(
|
||||
"simulation-sam3-surfaces",
|
||||
"SAM3-LiteText · пешеходные зоны",
|
||||
"segmentation",
|
||||
concepts["image"].removeprefix("sha256:"),
|
||||
digest({
|
||||
"client": implementation,
|
||||
"server": hashlib.sha256((adapter_root / "sam3/server.py").read_bytes()).hexdigest(),
|
||||
"concepts": hashlib.sha256(Path(__file__).with_name("concept_surfaces.py").read_bytes()).hexdigest(),
|
||||
"descriptor": hashlib.sha256((adapter_root / "sam3/model.json").read_bytes()).hexdigest(),
|
||||
}),
|
||||
concepts["checkpoint_sha256"],
|
||||
digest({"camera": profile["camera"], "preprocess": concepts["preprocess"],
|
||||
"output": "concept6-labels-candidate-and-known-square512-v1"}),
|
||||
("source.camera.rgb",),
|
||||
("segmentation.known", "segmentation.labels", "segmentation.surface"),
|
||||
),
|
||||
ModuleSpec(
|
||||
"simulation-rf-detr",
|
||||
@@ -92,6 +186,24 @@ def registry(adapter_root: Path) -> ModuleRegistry:
|
||||
("source.camera.rgb",),
|
||||
("detection.boxes",),
|
||||
),
|
||||
ModuleSpec(
|
||||
"simulation-declared-route",
|
||||
"Маршрут · объявленная карта",
|
||||
"preparation",
|
||||
nav["image"].removeprefix("sha256:"),
|
||||
digest(
|
||||
{
|
||||
name: hashlib.sha256(
|
||||
Path(__file__).with_name(name).read_bytes()
|
||||
).hexdigest()
|
||||
for name in ("route_graph.py", "run_inputs.py")
|
||||
}
|
||||
),
|
||||
None,
|
||||
digest({"route": "missioncore.global-route/v1", "authority": "route-intent-only"}),
|
||||
("source.execution-inputs",),
|
||||
("navigation.route",),
|
||||
),
|
||||
ModuleSpec(
|
||||
"simulation-waypoint-mission",
|
||||
"Маршрут · контроль продвижения",
|
||||
@@ -99,29 +211,61 @@ def registry(adapter_root: Path) -> ModuleRegistry:
|
||||
nav["image"].removeprefix("sha256:"),
|
||||
digest(
|
||||
{
|
||||
"route_policy": hashlib.sha256(
|
||||
Path(__file__).with_name("route_mission.py").read_bytes()
|
||||
).hexdigest(),
|
||||
"route_feedback": hashlib.sha256(
|
||||
Path(__file__).with_name("route_feedback.py").read_bytes()
|
||||
).hexdigest(),
|
||||
"policy": hashlib.sha256(
|
||||
Path(__file__).with_name("mission_policy.py").read_bytes()
|
||||
).hexdigest(),
|
||||
"observed_recovery": hashlib.sha256(
|
||||
Path(__file__).with_name("observed_recovery.py").read_bytes()
|
||||
).hexdigest(),
|
||||
"adapter": hashlib.sha256(
|
||||
(adapter_root / "navigation_client.py").read_bytes()
|
||||
).hexdigest(),
|
||||
"observed_goals": hashlib.sha256(
|
||||
(adapter_root / "navigation/observed_goals.py").read_bytes()
|
||||
).hexdigest(),
|
||||
"semantic_surface": hashlib.sha256(
|
||||
(adapter_root / "navigation/semantic_surface.py").read_bytes()
|
||||
).hexdigest(),
|
||||
"continuous_executor": implementation,
|
||||
}
|
||||
),
|
||||
None,
|
||||
digest(
|
||||
{
|
||||
"task": "operator-metric-waypoints-v1",
|
||||
"recovery": "three-observed-reverse-and-replan-attempts-v2",
|
||||
"driving_profiles": hashlib.sha256(
|
||||
Path(__file__).with_name("driving_profiles.py").read_bytes()
|
||||
).hexdigest(),
|
||||
"recovery": "observed-sector-survey-maneuver-replan-v3",
|
||||
}
|
||||
),
|
||||
(
|
||||
"navigation.route",
|
||||
"segmentation.known",
|
||||
"segmentation.labels",
|
||||
"segmentation.surface",
|
||||
"source.camera.calibration",
|
||||
"source.lidar",
|
||||
"source.pose",
|
||||
"source.simulation-time",
|
||||
),
|
||||
("navigation.goal", "navigation.intent"),
|
||||
(
|
||||
"navigation.goal",
|
||||
"navigation.intent",
|
||||
"navigation.permissions",
|
||||
"navigation.semantic-known",
|
||||
"navigation.surface",
|
||||
),
|
||||
parameter_choices_json=canonical_bytes(
|
||||
{"environment": ["natural", "park", "urban"]}
|
||||
),
|
||||
defaults_json=canonical_bytes({"environment": "park"}),
|
||||
state_policy="causal-reset-at-source-start",
|
||||
),
|
||||
ModuleSpec(
|
||||
@@ -136,8 +280,20 @@ def registry(adapter_root: Path) -> ModuleRegistry:
|
||||
).hexdigest()
|
||||
for p in (
|
||||
adapter_root / "navigation/server.py",
|
||||
adapter_root / "navigation/continuous_control.py",
|
||||
adapter_root / "navigation/route_observation.py",
|
||||
adapter_root / "navigation/arrival_approach.py",
|
||||
adapter_root / "navigation/local_velocity_search.py",
|
||||
adapter_root / "navigation/turn_staging.py",
|
||||
adapter_root / "navigation/footprint.py",
|
||||
adapter_root / "navigation/support_surface.py",
|
||||
adapter_root / "navigation/support_policy.py",
|
||||
adapter_root / "navigation/contact_support.py",
|
||||
adapter_root / "navigation/terrain_costs.py",
|
||||
adapter_root / "navigation/observed_ground.py",
|
||||
adapter_root / "navigation/support_obstacles.py",
|
||||
adapter_root / "navigation/semantic_surface.py",
|
||||
adapter_root / "navigation/observed_space.py",
|
||||
adapter_root / "navigation/terrain_connectivity.cpp",
|
||||
adapter_root / "navigation/fastdds.xml",
|
||||
adapter_root / "navigation_client.py",
|
||||
@@ -148,8 +304,11 @@ def registry(adapter_root: Path) -> ModuleRegistry:
|
||||
digest(
|
||||
{
|
||||
"upstream": nav["upstream_commit"],
|
||||
"footprint": [1, 1],
|
||||
"inputs": "metric-occluded-range-and-rgb",
|
||||
"footprint": "execution-inputs.robot.geometry/v2",
|
||||
"run_inputs": hashlib.sha256(
|
||||
Path(__file__).with_name("run_inputs.py").read_bytes()
|
||||
).hexdigest(),
|
||||
"inputs": "metric-occluded-range-with-valid-free-rays-and-rgb-v2",
|
||||
"command": "signed-mps-rps-observed-recovery-v2",
|
||||
}
|
||||
),
|
||||
@@ -157,10 +316,14 @@ def registry(adapter_root: Path) -> ModuleRegistry:
|
||||
"detection.boxes",
|
||||
"navigation.goal",
|
||||
"navigation.intent",
|
||||
"segmentation.surface",
|
||||
"navigation.permissions",
|
||||
"navigation.semantic-known",
|
||||
"navigation.surface",
|
||||
"source.camera.calibration",
|
||||
"source.lidar",
|
||||
"source.pose",
|
||||
"source.range-rays",
|
||||
"source.simulation-time",
|
||||
),
|
||||
("motion.command", "motion.path"),
|
||||
state_policy="causal-reset-at-source-start",
|
||||
@@ -169,6 +332,28 @@ def registry(adapter_root: Path) -> ModuleRegistry:
|
||||
)
|
||||
|
||||
|
||||
if "nav2" not in profile:
|
||||
return installed
|
||||
native = profile["nav2"]
|
||||
shared = ("continuous_control.py", "footprint.py", "support_policy.py", "support_surface.py",
|
||||
"support_native.py", "terrain_costs.py", "contact_support.py", "observed_ground.py",
|
||||
"support_obstacles.py", "semantic_surface.py", "observed_space.py", "range_image.py",
|
||||
"detection_obstacles.py", "route_observation.py", "arrival_approach.py", "pcl_ground.py")
|
||||
runtime = ("configuration.py", "nodes.py", "observed_collision.py", "ros_navigation.py",
|
||||
"server.py", "terrain_node.py", "terrain_observation.py", "terrain_process.py")
|
||||
files = [adapter_root/"nav2"/name for name in runtime]
|
||||
files += [adapter_root/"navigation"/name for name in shared]
|
||||
files += [adapter_root/name for name in ("model_stack.py", "navigation_client.py", "rig_collision.py")]
|
||||
legacy = next(module for module in installed.modules if module.module_id == "simulation-cmu-navigation")
|
||||
module = replace(legacy, module_id="simulation-nav2-navigation", label="Nav2 · движение ровера",
|
||||
image_sha256=native["image"].removeprefix("sha256:"),
|
||||
implementation_sha256=digest({p.relative_to(adapter_root).as_posix():
|
||||
hashlib.sha256(p.read_bytes()).hexdigest() for p in files}),
|
||||
contract_sha256=digest(dict(runtime=native, inputs="measured-twist-first-hit-ranges/v1",
|
||||
command="native-DWB-Spin-BackUp-with-observed-rover-gates/v1")))
|
||||
return ModuleRegistry((*installed.modules, module))
|
||||
|
||||
|
||||
def compose(adapter_root: Path, selection=None):
|
||||
installed = registry(adapter_root)
|
||||
if selection is None:
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Resolve overlapping concept masks without inventing surface permission.
|
||||
|
||||
Open-vocabulary masks are independent detections, not mutually exclusive class
|
||||
probabilities. A sidewalk detection cannot override a road, crossing or wall.
|
||||
All absent concepts stay unknown; the physical ground check is independent.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
LABELS = {0: "unknown", 1: "sidewalk", 2: "carriageway", 3: "crosswalk",
|
||||
4: "wall", 5: "conflicting_concepts"}
|
||||
PROMPTS = ("sidewalk", "roadway", "crosswalk", "wall")
|
||||
|
||||
|
||||
def concept_rasters(masks):
|
||||
if set(masks) != set(PROMPTS):
|
||||
raise ValueError("Incomplete concept masks")
|
||||
values = [np.asarray(masks[key]) for key in PROMPTS]
|
||||
if any(value.dtype != bool or value.shape != (600, 800) for value in values):
|
||||
raise ValueError("Expected 800x600 boolean concept masks")
|
||||
sidewalk, road, crossing, wall = values
|
||||
labels = np.zeros((600, 800), dtype=np.uint8)
|
||||
labels[sidewalk] = 1
|
||||
labels[road] = 2
|
||||
labels[crossing] = 3
|
||||
labels[wall] = 4
|
||||
labels[sidewalk & (road | crossing | wall)] = 5
|
||||
# Inference sees the complete frame. Only its output is transformed to the
|
||||
# existing central pinhole contract, preserving metric reprojection.
|
||||
labels = np.asarray(Image.fromarray(labels).crop((100, 0, 700, 600)).resize(
|
||||
(512, 512), Image.Resampling.NEAREST))
|
||||
return labels, np.isin(labels, (1, 2, 3)), labels != 0
|
||||
@@ -3,7 +3,7 @@
|
||||
from ipaddress import ip_address, ip_network
|
||||
from typing import Annotated, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, HttpUrl, field_validator
|
||||
from pydantic import BaseModel, ConfigDict, Field, HttpUrl, field_validator, model_validator
|
||||
|
||||
|
||||
class Contract(BaseModel):
|
||||
@@ -33,7 +33,7 @@ class WorldSettings(Contract):
|
||||
] = (0, 0)
|
||||
heading_degrees: float = Field(default=0, ge=-360, le=360)
|
||||
camera_height_m: float = Field(default=0.5, ge=0.1, le=3)
|
||||
max_speed_mps: float = Field(default=0.3, ge=0.05, le=1)
|
||||
max_speed_mps: float = Field(default=0.3, ge=0.05)
|
||||
prepared: bool = False
|
||||
route_xy: list[
|
||||
tuple[
|
||||
@@ -43,13 +43,64 @@ class WorldSettings(Contract):
|
||||
] = Field(default_factory=list, max_length=32)
|
||||
|
||||
|
||||
class RoverSettings(Contract):
|
||||
"""Per-run simulation inputs; the installed robot remains immutable."""
|
||||
|
||||
schema_version: Literal["missioncore.rover-settings/v1", "missioncore.rover-settings/v2"] = "missioncore.rover-settings/v2"
|
||||
max_speed_mps: float = Field(ge=0.05)
|
||||
base_mass_kg: float = Field(ge=10, le=1000)
|
||||
payload_mass_kg: float = Field(default=0, ge=0, le=500)
|
||||
payload_height_m: float = Field(ge=0.1, le=3)
|
||||
|
||||
|
||||
class RunCreate(Contract):
|
||||
world_id: str = Field(pattern=r"^aiworld-[a-f0-9]{32}$")
|
||||
max_steps: int = Field(default=600, ge=1, le=3600, strict=True)
|
||||
robot_id: str = Field(default="dcd006-v020", pattern=r"^[a-z0-9][a-z0-9-]{0,63}$")
|
||||
robot_sha256: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$")
|
||||
# Accept cached clients' obsolete budgets, but never persist or execute
|
||||
# them. Route completion and explicit stop/error own the run lifecycle.
|
||||
max_steps: int | None = Field(default=None, ge=1, strict=True, exclude=True, deprecated=True)
|
||||
clock: Literal["lockstep", "realtime"] = "lockstep"
|
||||
start_paused: bool = False
|
||||
duration_seconds: int = Field(default=1800, ge=10, le=7200, strict=True)
|
||||
duration_seconds: int | None = Field(default=None, ge=1, strict=True, exclude=True, deprecated=True)
|
||||
composition: dict | None = None
|
||||
purpose: Literal["evaluation", "planning"] = "evaluation"
|
||||
plan_id: str | None = Field(default=None, pattern=r"^aiplan-[a-f0-9]{32}$")
|
||||
rover_settings: RoverSettings | None = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def settings_require_realtime(self):
|
||||
if self.rover_settings and (self.clock != "realtime" or self.purpose != "evaluation"):
|
||||
raise ValueError("Настройки ровера применяются к realtime-заезду.")
|
||||
return self
|
||||
|
||||
|
||||
class PlanningCommand(Contract):
|
||||
request_id: str = Field(pattern=r"^[a-f0-9]{32}$")
|
||||
action: Literal[
|
||||
"orbit", "pan", "zoom", "fly", "home", "add", "move", "delete", "clear", "clip", "undo"
|
||||
]
|
||||
point_id: str | None = Field(default=None, pattern=r"^[a-f0-9]{16}$")
|
||||
axis: Literal["x", "y", "xy"] = "xy"
|
||||
x: float = Field(default=0.5, ge=-1, le=1)
|
||||
y: float = Field(default=0.5, ge=-1, le=1)
|
||||
amount: float = Field(default=0, ge=-10000, le=10000)
|
||||
enabled: bool = True
|
||||
view_revision: int = Field(default=0, ge=0, strict=True)
|
||||
|
||||
|
||||
class PlanSave(Contract):
|
||||
name: str = Field(min_length=1, max_length=120)
|
||||
sequence: int = Field(ge=0, strict=True)
|
||||
|
||||
|
||||
class RunLibraryUpdate(Contract):
|
||||
removed: bool = Field(strict=True)
|
||||
|
||||
|
||||
class PlanLibraryUpdate(Contract):
|
||||
display_name: str | None = Field(default=None, min_length=1, max_length=120)
|
||||
removed: bool | None = Field(default=None, strict=True)
|
||||
|
||||
|
||||
class WorkerWorldCreate(WorldCreate):
|
||||
@@ -57,7 +108,7 @@ class WorkerWorldCreate(WorldCreate):
|
||||
|
||||
sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
|
||||
collider_sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
|
||||
splat_count: int = Field(ge=1, le=20_000_000, strict=True)
|
||||
splat_count: int = Field(ge=1, strict=True)
|
||||
settings: WorldSettings
|
||||
|
||||
|
||||
@@ -96,11 +147,30 @@ class WorkerHello(Contract):
|
||||
] = Field(min_length=4, max_length=4)
|
||||
profile_sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
|
||||
execution_modes: list[Literal["lockstep", "realtime"]] = ["lockstep"]
|
||||
scene_formats: list[Literal["gaussian-ply", "project-sog"]] = ["gaussian-ply"]
|
||||
rover_settings_versions: list[Literal["missioncore.rover-settings/v1", "missioncore.rover-settings/v2"]] = Field(
|
||||
default_factory=list, max_length=2
|
||||
)
|
||||
execution_inputs_versions: list[
|
||||
Literal[
|
||||
"missioncore.simulation-inputs/v1",
|
||||
"missioncore.simulation-inputs/v2",
|
||||
"missioncore.simulation-inputs/v3",
|
||||
]
|
||||
] = Field(default_factory=list, max_length=3)
|
||||
sensor_rig_versions: list[
|
||||
Literal["missioncore.simulation-sensor-rig/v2", "missioncore.simulation-sensor-rig/v3",
|
||||
"missioncore.simulation-sensor-rig/v4"]
|
||||
] = Field(default_factory=list, max_length=3)
|
||||
stream: StreamEndpoint | None = None
|
||||
robots: dict[
|
||||
Annotated[str, Field(pattern=r"^[a-zA-Z0-9_-]{1,64}$")],
|
||||
Annotated[str, Field(pattern=r"^[a-f0-9]{64}$")],
|
||||
] = Field(default_factory=dict, max_length=32)
|
||||
|
||||
|
||||
class Decision(Contract):
|
||||
speed_mps: float = Field(ge=-1, le=1)
|
||||
speed_mps: float
|
||||
yaw_rate_rps: float = Field(ge=-1, le=1)
|
||||
reason: Literal[
|
||||
"road",
|
||||
@@ -119,7 +189,7 @@ class Decision(Contract):
|
||||
|
||||
|
||||
class RunSample(Contract):
|
||||
sequence: int = Field(ge=0, le=3600, strict=True)
|
||||
sequence: int = Field(ge=0, strict=True)
|
||||
simulation_time_ns: int = Field(ge=0, strict=True)
|
||||
inference_ms: float = Field(ge=0, le=120000)
|
||||
# The snapshot is an observation BEFORE the action below is applied.
|
||||
@@ -138,7 +208,7 @@ class RunProgress(Contract):
|
||||
|
||||
|
||||
class RunApplied(Contract):
|
||||
sequence: int = Field(ge=0, le=3600, strict=True)
|
||||
sequence: int = Field(ge=0, strict=True)
|
||||
simulation_time_ns: int = Field(ge=0, strict=True)
|
||||
physics_steps: Literal[6]
|
||||
pose_xy: tuple[float, float]
|
||||
@@ -148,17 +218,135 @@ class RunApplied(Contract):
|
||||
transport_ms: float | None = Field(default=None, ge=0, le=120000)
|
||||
|
||||
|
||||
class StopSummary(Contract):
|
||||
reason: str = Field(min_length=1, max_length=80)
|
||||
events: int = Field(ge=0, strict=True)
|
||||
seconds: float = Field(ge=0)
|
||||
|
||||
|
||||
class RunSpeedSummary(Contract):
|
||||
# Report the admitted run envelope. Rover-settings/v1 retains its legacy
|
||||
# ceiling in run_robot; v2 permits every finite speed >= .05. Reports must
|
||||
# remain representable for both versions, including failed/stopped runs.
|
||||
requested_max_mps: float = Field(ge=0.05)
|
||||
measured_max_mps: float | None = Field(default=None, ge=0)
|
||||
maximum_excess_mps: float | None = Field(default=None, ge=0)
|
||||
seconds_above_requested: float | None = Field(default=None, ge=0)
|
||||
|
||||
|
||||
class SimulationChallengeResult(Contract):
|
||||
schema_version: Literal["missioncore.simulation-challenge-result/v1"]
|
||||
scenario_sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
|
||||
name: Literal["observation-loss", "observation-delay", "obstacle"]
|
||||
passed: bool = Field(strict=True)
|
||||
checks: dict[str, bool] = Field(min_length=1, max_length=32)
|
||||
metrics: dict[str, float | None] = Field(max_length=32)
|
||||
|
||||
|
||||
class SimulationReport(Contract):
|
||||
plan_id: str | None = Field(default=None, pattern=r"^aiplan-[a-f0-9]{32}$")
|
||||
plan_sha256: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$")
|
||||
# v1 remains readable. v2 counts initial zero commands and each reason
|
||||
# segment; neither version claims physical standstill from command values.
|
||||
schema_version: Literal["missioncore.simulation-report/v1", "missioncore.simulation-report/v2"]
|
||||
run_id: str = Field(pattern=r"^airun-[a-f0-9]{32}$")
|
||||
generated_at: str = Field(max_length=50)
|
||||
mission_outcome: Literal[
|
||||
"goal-reached", "time-limit", "operator-stop", "stuck", "unstable", "error", "not-evaluated"
|
||||
]
|
||||
robot_id: str | None = Field(default=None, max_length=64)
|
||||
robot_sha256: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$")
|
||||
composition_sha256: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$")
|
||||
world_sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
|
||||
runtime_sources: dict[str, Annotated[str, Field(pattern=r"^[a-f0-9]{64}$")]] = Field(
|
||||
max_length=8
|
||||
)
|
||||
simulation_seconds: float | None = Field(ge=0)
|
||||
distance_m: float | None = Field(ge=0)
|
||||
goal_error_m: float | None = Field(ge=0)
|
||||
waypoint_count: int = Field(ge=0, strict=True)
|
||||
waypoints_reached: int | None = Field(ge=0, strict=True)
|
||||
inference_count: int = Field(ge=0, strict=True)
|
||||
inference_errors: int = Field(ge=0, strict=True)
|
||||
inference_ms_p50: float | None = Field(ge=0)
|
||||
inference_ms_p95: float | None = Field(ge=0)
|
||||
stops: list[StopSummary] = Field(max_length=32)
|
||||
collision_count: int | None = Field(default=None, ge=0, strict=True)
|
||||
challenge: SimulationChallengeResult | None = None
|
||||
execution_inputs_sha256: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$")
|
||||
rover_configuration_sha256: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$")
|
||||
effective_robot_sha256: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$")
|
||||
speed: RunSpeedSummary | None = None
|
||||
report_sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
|
||||
manifest_sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
|
||||
evidence_files: int = Field(ge=1, strict=True)
|
||||
evidence_bytes: int = Field(ge=1, strict=True)
|
||||
|
||||
|
||||
class WorkerResult(Contract):
|
||||
instance_id: str = Field(pattern=r"^[a-f0-9]{32}$")
|
||||
outcome: Literal["completed", "stopped", "failed"]
|
||||
message: str = Field(default="", max_length=500)
|
||||
resources_released: Literal[True]
|
||||
report: SimulationReport | None = None
|
||||
|
||||
|
||||
class ObserverInput(Contract):
|
||||
session: str = Field(pattern=r"^[a-f0-9]{32}$")
|
||||
sequence: int = Field(ge=0, strict=True)
|
||||
orbit: tuple[
|
||||
Annotated[float, Field(ge=-10000, le=10000)], Annotated[float, Field(ge=-10000, le=10000)]
|
||||
]
|
||||
move: tuple[
|
||||
Annotated[float, Field(ge=-10000, le=10000)],
|
||||
Annotated[float, Field(ge=-10000, le=10000)],
|
||||
Annotated[float, Field(ge=-10000, le=10000)],
|
||||
]
|
||||
zoom: float = Field(ge=-10000, le=10000)
|
||||
|
||||
|
||||
class ViewControl(Contract):
|
||||
navigation: ObserverInput | None = None
|
||||
camera: Literal["follow", "overview", "camera"]
|
||||
|
||||
|
||||
MetricCoordinate = Annotated[float, Field(ge=-10000, le=10000)]
|
||||
ScreenCoordinate = Annotated[float, Field(ge=-2, le=3)]
|
||||
ScreenPoint = tuple[ScreenCoordinate, ScreenCoordinate] | None
|
||||
|
||||
|
||||
class RoutePoint(Contract):
|
||||
id: str = Field(pattern=r"^[a-f0-9]{16}$")
|
||||
position: tuple[MetricCoordinate, MetricCoordinate, MetricCoordinate]
|
||||
|
||||
|
||||
class RouteMarker(RoutePoint):
|
||||
index: int = Field(ge=0, le=32)
|
||||
base: ScreenPoint
|
||||
top: ScreenPoint
|
||||
x_axis: ScreenPoint
|
||||
y_axis: ScreenPoint
|
||||
|
||||
|
||||
class RouteOverlay(Contract):
|
||||
markers: list[RouteMarker] = Field(max_length=33)
|
||||
trace: list[ScreenPoint] = Field(max_length=256)
|
||||
active_index: int = Field(ge=0, le=33)
|
||||
view_revision: int = Field(ge=0)
|
||||
|
||||
|
||||
class PlanningState(Contract):
|
||||
sequence: int = Field(ge=0)
|
||||
view_revision: int = Field(ge=0)
|
||||
points: list[RoutePoint] = Field(max_length=33)
|
||||
error: str | None = Field(default=None, max_length=500)
|
||||
can_undo: bool
|
||||
clip_height: MetricCoordinate | None = None
|
||||
height_min: MetricCoordinate | None = None
|
||||
height_max: MetricCoordinate | None = None
|
||||
camera_moving: bool = False
|
||||
|
||||
|
||||
class RealtimeSnapshot(Contract):
|
||||
"""Bounded observation of Worker-owned state; never a physics-step receipt."""
|
||||
|
||||
@@ -182,13 +370,84 @@ class RealtimeSnapshot(Contract):
|
||||
command_age_ms: float | None = Field(default=None, ge=0)
|
||||
pose_xy: tuple[float, float]
|
||||
pose_yaw: float
|
||||
distance_m: float | None = Field(default=None, ge=0)
|
||||
speed_mps: float
|
||||
applied_speed_mps: float = Field(ge=-1, le=1)
|
||||
applied_speed_mps: float
|
||||
applied_yaw_rate_rps: float = Field(ge=-1, le=1)
|
||||
stop_reason: Literal[
|
||||
"none", "paused", "stale-camera", "stale-command", "inference-error", "unstable"
|
||||
"none", "paused", "stale-camera", "stale-command", "inference-error", "unstable",
|
||||
"stale-range", "stale-pose", "stale-perception", "control-blocked"
|
||||
]
|
||||
decision: Decision | None = None
|
||||
ai_ready: bool
|
||||
stream_ready: bool
|
||||
camera: Literal["follow", "overview", "camera"]
|
||||
route_overlay: RouteOverlay | None = None
|
||||
planning: PlanningState | None = None
|
||||
|
||||
|
||||
class LocalPlanCreate(Contract):
|
||||
cache_key: str = Field(pattern=r"^[a-f0-9]{64}$")
|
||||
draft_id: str = Field(pattern=r"^[a-f0-9]{32}$")
|
||||
sequence: int = Field(ge=0)
|
||||
name: str = Field(min_length=1, max_length=120)
|
||||
robot_id: str = Field(max_length=80)
|
||||
robot_sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
|
||||
points: list[RoutePoint] = Field(min_length=2, max_length=33)
|
||||
|
||||
|
||||
class InferenceClass(Contract):
|
||||
class_id: int = Field(ge=0, le=255, strict=True)
|
||||
label: str = Field(min_length=1, max_length=80)
|
||||
color: str = Field(pattern=r"^#[a-f0-9]{6}$")
|
||||
|
||||
|
||||
class InferenceLayer(Contract):
|
||||
id: str = Field(pattern=r"^[a-z][a-z0-9-]{0,63}$")
|
||||
kind: Literal["image", "points3d"] = "image"
|
||||
ports: list[str] = Field(default_factory=list, max_length=8)
|
||||
label: str = Field(min_length=1, max_length=80)
|
||||
jpeg: str | None = Field(
|
||||
default=None, min_length=1, max_length=100000, pattern=r"^[A-Za-z0-9+/]+={0,2}$"
|
||||
)
|
||||
image_size: tuple[int, int] | None = None
|
||||
points: list[tuple[float, float, float]] | None = Field(default=None, max_length=2048)
|
||||
source_count: int | None = Field(default=None, ge=0, le=1000000)
|
||||
frame: Literal["body-x-forward-y-left-z-up"] | None = None
|
||||
legend: list[InferenceClass] = Field(default_factory=list, max_length=8)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def payload_matches_kind(self):
|
||||
if self.kind == "image":
|
||||
if self.image_size not in (None, (400, 300), (640, 320), (320, 320)):
|
||||
raise ValueError("Unsupported preview raster size")
|
||||
if not self.jpeg or any(
|
||||
v is not None for v in (self.points, self.source_count, self.frame)
|
||||
):
|
||||
raise ValueError("Image preview requires only an image payload")
|
||||
elif (
|
||||
self.points is None
|
||||
or self.source_count is None
|
||||
or self.frame is None
|
||||
or self.jpeg
|
||||
or self.image_size
|
||||
):
|
||||
raise ValueError("Spatial preview requires points, count and coordinate frame")
|
||||
elif self.source_count < len(self.points):
|
||||
raise ValueError("Displayed points exceed source count")
|
||||
return self
|
||||
|
||||
|
||||
class InferencePreview(Contract):
|
||||
frame_id: int = Field(ge=0, strict=True)
|
||||
simulation_time_ns: int = Field(ge=0, strict=True)
|
||||
composition_sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
|
||||
environment: Literal["natural", "park", "urban"]
|
||||
layers: list[InferenceLayer] = Field(max_length=16)
|
||||
|
||||
@field_validator("layers")
|
||||
@classmethod
|
||||
def unique_layers(cls, layers):
|
||||
if len({layer.id for layer in layers}) != len(layers):
|
||||
raise ValueError("Layer IDs must be unique")
|
||||
return layers
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Immutable route-domain guard shared by planning and the continuous controller."""
|
||||
import copy
|
||||
import math
|
||||
import numpy as np
|
||||
from .route_graph import disc_permitted
|
||||
|
||||
|
||||
class CorridorControl:
|
||||
def __init__(self, corridors, no_go):
|
||||
self.corridors, self.no_go = copy.deepcopy(corridors), copy.deepcopy(no_go)
|
||||
|
||||
def command_permitted(self, pose, bounds):
|
||||
low = np.array(bounds["lower_xy_m"]) - bounds["discrepancy_xy_m"]
|
||||
high = np.array(bounds["upper_xy_m"]) + bounds["discrepancy_xy_m"]
|
||||
centre = (low + high) / 2
|
||||
radius = float(np.linalg.norm((high - low) / 2))
|
||||
x, y, z, w = pose[3:7]
|
||||
yaw = math.atan2(2*(w*z+x*y), 1-2*(y*y+z*z))
|
||||
world = np.array(pose[:2]) + np.array([[math.cos(yaw), -math.sin(yaw)],
|
||||
[math.sin(yaw), math.cos(yaw)]]) @ centre
|
||||
return disc_permitted(world, radius, self.corridors, self.no_go)
|
||||
|
||||
def regulate_command(self, pose, monitor, speed, angular):
|
||||
for scale in (1.0, 0.75, 0.5, 0.25):
|
||||
v, w = speed*scale, angular*scale
|
||||
if self.command_permitted(pose, monitor.command_bounds(v, w)):
|
||||
return v, w, scale
|
||||
return 0.0, 0.0, 0.0
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Associate detector boxes with observed obstacles, not background road pixels."""
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
def detection_proximity(points, pose, ground_pixels, covered, contact_height, *, reverse=False):
|
||||
"""Associate measured returns with detections, independent of view yaw.
|
||||
|
||||
A 2D box is not an instance mask. A range return that is both confidently
|
||||
labelled permitted ground and within 5 cm of the current contact plane is
|
||||
background, not measured object depth. This does not grant free space: all
|
||||
returns still enter the geometric obstacle/swept-support planner. Unknown
|
||||
pixels, above-ground returns, steps and gaps remain obstacle candidates.
|
||||
The near-field flag is diagnostic: movement depends on the proposed swept
|
||||
body, not the mere presence of an object beside it. Return source indices
|
||||
so the planner cannot substitute synthetic geometry for measured depth.
|
||||
"""
|
||||
points = np.asarray(points, dtype=float)
|
||||
q = np.array(pose[3:7], dtype=float, copy=True)
|
||||
q /= np.linalg.norm(q)
|
||||
x, y, z, w = q
|
||||
rotation = np.array([
|
||||
[1 - 2 * (y*y + z*z), 2 * (x*y - z*w), 2 * (x*z + y*w)],
|
||||
[2 * (x*y + z*w), 1 - 2 * (x*x + z*z), 2 * (y*z - x*w)],
|
||||
[2 * (x*z - y*w), 2 * (y*z + x*w), 1 - 2 * (x*x + y*y)],
|
||||
])
|
||||
local = (points - np.asarray(pose[:3])) @ rotation
|
||||
background = np.asarray(ground_pixels, bool) & (np.abs(local[:, 2] + contact_height) <= 0.05)
|
||||
corridor = ((-local[:, 0] if reverse else local[:, 0]) > 0) & (np.abs(local[:, 1]) < 0.8)
|
||||
near = np.asarray(covered, bool) & (np.linalg.norm(points[:, :2] - pose[:2], axis=1) < 1.5) & corridor
|
||||
return {
|
||||
"danger": bool(np.any(near & ~background)),
|
||||
"near_returns": int(near.sum()),
|
||||
"background_ground_returns": int((near & background).sum()),
|
||||
"object_or_unknown_returns": int((near & ~background).sum()),
|
||||
"hazard_indices": np.flatnonzero(np.asarray(covered, bool) & ~background).tolist(),
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Semantic permissions of the composed mission, not physical traversability.
|
||||
|
||||
ADE IDs follow the pinned ADE150 checkpoint. GOOSE IDs are resolved from the
|
||||
pinned class-name table. Unknown taxonomy/profile is an error, never permission.
|
||||
|
||||
Urban travel is restricted to pedestrian areas. A material such as asphalt or
|
||||
cobble does not establish the area's use. Entering a carriageway requires a
|
||||
separately verified pedestrian crossing; an intersection or generic road marking
|
||||
is not that evidence. The installed surface taxonomies do not provide a complete
|
||||
crossing authority, so this surface-only policy never authorizes road entry.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
|
||||
PROFILES = ("natural", "park", "urban")
|
||||
# Parks can have unpaved paths: ADE names those earth / dirt track.
|
||||
# This excludes lawns, but cannot prove that every bare-earth patch is a path.
|
||||
ADE = {"park": (6, 11, 13, 52, 91), "urban": (11, 52)}
|
||||
GOOSE = {
|
||||
"park": {"asphalt", "bikeway", "cobble", "sidewalk", "gravel", "soil", "road_marking"},
|
||||
"urban": {"sidewalk"},
|
||||
}
|
||||
|
||||
|
||||
def semantic_known(labels, segmenter_id):
|
||||
# Undefined/outlier pixels are neither positive surface nor a classified
|
||||
# barrier. They must never poison or clear the retained semantic map.
|
||||
if segmenter_id == "simulation-ddrnet-goose":
|
||||
return ~np.isin(labels, (0, 56))
|
||||
if segmenter_id == "simulation-sam3-surfaces":
|
||||
return labels != 0
|
||||
if segmenter_id in {"simulation-segformer-ade", "simulation-segformer-cityscapes", "simulation-mask2former-mapillary"}:
|
||||
return np.ones_like(labels, dtype=bool)
|
||||
raise ValueError("Unknown segmentation taxonomy")
|
||||
|
||||
|
||||
def permitted_surface(labels, candidate, profile, segmenter_id, goose_labels):
|
||||
if profile not in PROFILES:
|
||||
raise ValueError("Unknown driving profile")
|
||||
if segmenter_id not in {"simulation-ddrnet-goose", "simulation-segformer-ade", "simulation-segformer-cityscapes", "simulation-mask2former-mapillary", "simulation-sam3-surfaces"}:
|
||||
raise ValueError("Unknown segmentation taxonomy")
|
||||
if profile == "natural":
|
||||
return candidate.copy()
|
||||
if segmenter_id == "simulation-sam3-surfaces":
|
||||
# A marked crossing is evidence for a later crossing manoeuvre, not
|
||||
# blanket permission. Neither material nor model mask bypasses it.
|
||||
return candidate & (labels == 1)
|
||||
if segmenter_id == "simulation-mask2former-mapillary":
|
||||
# Only pedestrian area and sidewalk in cities. A curb cut, a marked
|
||||
# zebra or a plain crossing still needs its own manoeuvre authorization.
|
||||
return candidate & np.isin(labels, (11, 15) if profile == "urban" else (7, 9, 11, 13, 15))
|
||||
if segmenter_id == "simulation-segformer-cityscapes":
|
||||
# Functional sidewalk class; road is excluded even when both are asphalt.
|
||||
return candidate & np.isin(labels, (1,) if profile == "urban" else (0, 1))
|
||||
ids = (
|
||||
ADE[profile]
|
||||
if segmenter_id == "simulation-segformer-ade"
|
||||
else tuple(i for i, name in goose_labels.items() if name in GOOSE[profile])
|
||||
)
|
||||
return candidate & np.isin(labels, ids)
|
||||
@@ -0,0 +1,190 @@
|
||||
"""Disk-backed local editor assets, delivered through the existing private Worker link."""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from k1link.simulation.ai_polygon.plans import PlanStore
|
||||
from k1link.simulation.ai_polygon.worlds import write_json
|
||||
|
||||
FILES = {"scene.sog", "collision.glb"}
|
||||
LEGACY_FILES = {"scene.compressed.ply", "collision.glb"}
|
||||
KEY = re.compile(r"^[a-f0-9]{64}$")
|
||||
LIMIT = 512 * 1024**2
|
||||
|
||||
|
||||
class EditorCache:
|
||||
def __init__(self, root, worlds):
|
||||
self.root = Path(root) / "ai-polygon" / "editor-cache"
|
||||
self.root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
self.worlds = worlds
|
||||
self.lock = threading.RLock()
|
||||
|
||||
@staticmethod
|
||||
def identity(world):
|
||||
return {
|
||||
"version": 2,
|
||||
"world_id": world["world_id"],
|
||||
"source_sha256": world["sha256"],
|
||||
"collider_sha256": world.get("collider_sha256"),
|
||||
"settings": world["settings"],
|
||||
}
|
||||
|
||||
def directory(self, key):
|
||||
if not KEY.fullmatch(key):
|
||||
raise FileNotFoundError(key)
|
||||
path = self.root / key
|
||||
if path.is_symlink():
|
||||
raise ValueError("Invalid cache directory")
|
||||
return path
|
||||
|
||||
def get(self, key):
|
||||
with self.lock:
|
||||
path = self.directory(key)
|
||||
row = json.loads((path / "manifest.json").read_text())
|
||||
if row["key"] != key or PlanStore.digest(row["identity"]) != key:
|
||||
raise ValueError("Editor cache identity changed")
|
||||
if any(name not in FILES | LEGACY_FILES for name in row.get("files", {})):
|
||||
raise ValueError("Invalid cache asset")
|
||||
if row.get("local_scene"):
|
||||
return row
|
||||
for name, asset in row.get("files", {}).items():
|
||||
part = path / (name if row["status"] == "ready" else name + ".part")
|
||||
if not part.exists() and (path / name).exists():
|
||||
part = path / name
|
||||
asset["uploaded_bytes"] = part.stat().st_size if part.exists() else 0
|
||||
return row
|
||||
|
||||
def request(self, world_id):
|
||||
with self.lock:
|
||||
world = self.worlds.get(world_id)
|
||||
if world["status"] != "available" or not world["settings"]["prepared"]:
|
||||
raise ValueError("Сначала задайте масштаб локации.")
|
||||
identity = self.identity(world)
|
||||
key = PlanStore.digest(identity)
|
||||
path = self.directory(key)
|
||||
if (path / "manifest.json").exists():
|
||||
row = self.get(key)
|
||||
if row["status"] != "failed":
|
||||
return row
|
||||
row.update(status="queued", error=None)
|
||||
else:
|
||||
if shutil.disk_usage(self.root).free < LIMIT + 512 * 1024**2:
|
||||
raise ValueError("Недостаточно места для локальной копии сцены.")
|
||||
path.mkdir(mode=0o700, exist_ok=True)
|
||||
row = {
|
||||
"key": key,
|
||||
"identity": identity,
|
||||
"world": world,
|
||||
"status": "queued",
|
||||
"files": {},
|
||||
"error": None,
|
||||
}
|
||||
if world.get("local_scene"):
|
||||
row.update(status="ready", files=self.worlds.projects.cache_files(world),
|
||||
local_scene=world["local_scene"])
|
||||
write_json(path / "manifest.json", row)
|
||||
return row
|
||||
|
||||
def pending(self):
|
||||
with self.lock:
|
||||
for path in sorted(self.root.glob("*/manifest.json")):
|
||||
if json.loads(path.read_text())["identity"].get("version") != 2:
|
||||
continue
|
||||
row = self.get(path.parent.name)
|
||||
if row["status"] in {"queued", "preparing", "uploading"}:
|
||||
return row
|
||||
return None
|
||||
|
||||
def update(self, key, body):
|
||||
with self.lock:
|
||||
row = self.get(key)
|
||||
if row["status"] == "ready":
|
||||
return row
|
||||
path = self.directory(key)
|
||||
action = body.get("action")
|
||||
if action == "fail":
|
||||
row.update(
|
||||
status="failed",
|
||||
error="Не удалось подготовить локальную сцену. Повторите загрузку.",
|
||||
)
|
||||
elif action == "prepare":
|
||||
row.update(status="preparing", error=None)
|
||||
elif action == "manifest":
|
||||
files = body["files"]
|
||||
if (
|
||||
set(files) != FILES
|
||||
or any(
|
||||
not KEY.fullmatch(str(a.get("sha256", "")))
|
||||
or not isinstance(a.get("byte_length"), int)
|
||||
or not 0 < a["byte_length"] <= LIMIT
|
||||
for a in files.values()
|
||||
)
|
||||
or sum(a["byte_length"] for a in files.values()) > LIMIT
|
||||
):
|
||||
raise ValueError("Invalid editor assets")
|
||||
if row.get("files") and any(
|
||||
any(row["files"][n][k] != files[n][k] for k in ("sha256", "byte_length"))
|
||||
for n in FILES
|
||||
):
|
||||
raise ValueError("Editor asset identity changed during transfer")
|
||||
if (
|
||||
row["identity"].get("collider_sha256")
|
||||
and files["collision.glb"]["sha256"] != row["identity"]["collider_sha256"]
|
||||
):
|
||||
raise ValueError("Collider identity mismatch")
|
||||
row.update(files=files, status="uploading")
|
||||
elif action == "chunk":
|
||||
name = body.get("name")
|
||||
if name not in FILES or name not in row["files"] or row["status"] != "uploading":
|
||||
raise ValueError("Unknown editor asset")
|
||||
asset = row["files"][name]
|
||||
offset = asset["uploaded_bytes"]
|
||||
if body.get("offset") != offset:
|
||||
raise RuntimeError("Upload offset changed")
|
||||
payload = base64.b64decode(body["data"], validate=True)
|
||||
if (
|
||||
not 0 < len(payload) <= 512 * 1024
|
||||
or offset + len(payload) > asset["byte_length"]
|
||||
):
|
||||
raise ValueError("Invalid editor chunk")
|
||||
if shutil.disk_usage(path).free < len(payload) + 512 * 1024**2:
|
||||
raise ValueError("Недостаточно места для сцены.")
|
||||
with (path / (name + ".part")).open("ab") as stream:
|
||||
stream.write(payload)
|
||||
elif action == "complete":
|
||||
for name, asset in row["files"].items():
|
||||
file = path / (name + ".part")
|
||||
# Completion is retryable after an interrupted multi-file publication.
|
||||
if not file.exists():
|
||||
file = path / name
|
||||
if file.stat().st_size != asset["byte_length"]:
|
||||
raise ValueError("Incomplete editor asset")
|
||||
with file.open("rb") as stream:
|
||||
if hashlib.file_digest(stream, "sha256").hexdigest() != asset["sha256"]:
|
||||
file.unlink()
|
||||
raise ValueError("Editor asset checksum mismatch")
|
||||
if set(row["files"]) != FILES:
|
||||
raise ValueError("Incomplete editor manifest")
|
||||
for name in FILES:
|
||||
part = path / (name + ".part")
|
||||
if part.exists():
|
||||
part.replace(path / name)
|
||||
row.update(status="ready", error=None)
|
||||
else:
|
||||
raise ValueError("Unknown cache action")
|
||||
write_json(path / "manifest.json", row)
|
||||
return self.get(key)
|
||||
|
||||
def asset(self, key, name):
|
||||
row = self.get(key)
|
||||
if row["status"] != "ready" or name not in FILES:
|
||||
raise RuntimeError("Локальная сцена ещё загружается.")
|
||||
path = self.directory(key) / name
|
||||
if path.is_symlink() or path.stat().st_size != row["files"][name]["byte_length"]:
|
||||
raise ValueError("Cached asset changed")
|
||||
return path, row["files"][name]["sha256"]
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Lossless NPZ evidence with bounded low-effort compression.
|
||||
|
||||
NumPy's default ZIP level spends CPU needed by the camera/physics process.
|
||||
Level one preserves every array byte and ordinary np.load compatibility.
|
||||
"""
|
||||
|
||||
import zipfile
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
def save_arrays(path, **arrays):
|
||||
with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=1) as archive:
|
||||
for name, value in arrays.items():
|
||||
if not name or "/" in name or "\\" in name:
|
||||
raise ValueError("Invalid evidence array name")
|
||||
with archive.open(name + ".npy", "w", force_zip64=True) as stream:
|
||||
np.lib.format.write_array(stream, np.asanyarray(value), allow_pickle=False)
|
||||
@@ -13,12 +13,15 @@ import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
from k1link.perception.rf_detr_object_detector import (
|
||||
COCO_CLASSES,
|
||||
COCO_SPARSE_TO_CONTIGUOUS,
|
||||
RISK_CLASS_IDS,
|
||||
TritonRfDetrHttpInferenceBackend,
|
||||
preprocess_raw_kb4_rf_detr,
|
||||
)
|
||||
|
||||
from .driving_profiles import semantic_known
|
||||
|
||||
MODEL_IDS = ["ddrnet-goose-pytorch-reference", "rf_detr_large"]
|
||||
GOOSE_SURFACE_IDS = (3, 5, 7, 9, 11, 18, 21, 23, 24, 31, 40, 50, 62)
|
||||
|
||||
@@ -50,9 +53,11 @@ class ModelInference:
|
||||
ddrnet_endpoint: str,
|
||||
*,
|
||||
segmenter_id: str = "simulation-ddrnet-goose",
|
||||
source=None,
|
||||
):
|
||||
if segmenter_id not in {"simulation-ddrnet-goose", "simulation-segformer-ade"}:
|
||||
if segmenter_id not in {"simulation-ddrnet-goose", "simulation-segformer-ade", "simulation-segformer-cityscapes", "simulation-mask2former-mapillary", "simulation-sam3-surfaces"}:
|
||||
raise ValueError("Uninstalled surface provider")
|
||||
self.source = source
|
||||
self.segmenter_id = segmenter_id
|
||||
parsed = local_endpoint(ddrnet_endpoint)
|
||||
local_endpoint(endpoint)
|
||||
@@ -60,6 +65,7 @@ class ModelInference:
|
||||
labels = {int(row["label_key"]): row["class_name"] for row in csv.DictReader(stream)}
|
||||
if set(labels) != set(range(64)):
|
||||
raise ValueError("Expected the existing GOOSE fine-64 label table")
|
||||
self.labels = labels
|
||||
self.road_ids = [
|
||||
i
|
||||
for i, name in labels.items()
|
||||
@@ -95,6 +101,8 @@ class ModelInference:
|
||||
return self.surface(rgb)["segmentation.labels"]
|
||||
|
||||
def surface(self, rgb: np.ndarray):
|
||||
if self.source is not None:
|
||||
rgb = self.source.model_rgb(rgb)
|
||||
if rgb.shape != (600, 800, 3) or rgb.dtype != np.uint8:
|
||||
raise ValueError("Expected an 800x600 RGB simulation camera")
|
||||
self.connection.request(
|
||||
@@ -104,24 +112,49 @@ class ModelInference:
|
||||
headers={"Content-Type": "application/octet-stream"},
|
||||
)
|
||||
response = self.connection.getresponse()
|
||||
ade = self.segmenter_id == "simulation-segformer-ade"
|
||||
expected = 512**2 * (2 if ade else 1)
|
||||
candidate_plane = self.segmenter_id != "simulation-ddrnet-goose"
|
||||
label_count = {"simulation-ddrnet-goose": 64, "simulation-segformer-ade": 150,
|
||||
"simulation-segformer-cityscapes": 19, "simulation-mask2former-mapillary": 65,
|
||||
"simulation-sam3-surfaces": 6}[self.segmenter_id]
|
||||
expected = 512**2 * (3 if candidate_plane else 2)
|
||||
raw = response.read(expected + 1)
|
||||
if response.status != 200 or len(raw) != expected:
|
||||
raise RuntimeError("Surface provider response changed")
|
||||
mask = np.frombuffer(raw[: 512**2], dtype=np.uint8).reshape(512, 512)
|
||||
if np.any(mask >= (150 if ade else 64)):
|
||||
if np.any(mask >= label_count):
|
||||
raise RuntimeError("Surface label taxonomy changed")
|
||||
if ade:
|
||||
candidate = np.frombuffer(raw[512**2 :], dtype=np.uint8).reshape(512, 512)
|
||||
if candidate_plane:
|
||||
candidate = np.frombuffer(raw[512**2 : 2 * 512**2], dtype=np.uint8).reshape(512, 512)
|
||||
if np.any(candidate > 1):
|
||||
raise RuntimeError("Surface candidate raster changed")
|
||||
candidate = candidate.astype(bool)
|
||||
known = np.frombuffer(raw[2 * 512**2 :], dtype=np.uint8).reshape(512, 512)
|
||||
if np.any(known > 1) or np.any(candidate & ~known.astype(bool)):
|
||||
raise RuntimeError("Surface certainty raster changed")
|
||||
known = known.astype(bool)
|
||||
if self.segmenter_id == "simulation-sam3-surfaces" and (
|
||||
np.any(known != (mask != 0)) or np.any(candidate & ~np.isin(mask, (1, 2, 3)))
|
||||
):
|
||||
raise RuntimeError("Concept surface evidence is inconsistent")
|
||||
else:
|
||||
candidate = np.isin(mask, GOOSE_SURFACE_IDS)
|
||||
return {"segmentation.labels": mask.copy(), "segmentation.surface": candidate}
|
||||
known = np.frombuffer(raw[512**2 :], dtype=np.uint8).reshape(512, 512)
|
||||
if np.any(known > 1):
|
||||
raise RuntimeError("Surface certainty raster changed")
|
||||
known = known.astype(bool) & semantic_known(mask, self.segmenter_id)
|
||||
candidate = np.isin(mask, GOOSE_SURFACE_IDS) & known
|
||||
return {
|
||||
"segmentation.known": known,
|
||||
"segmentation.labels": mask.copy(),
|
||||
"segmentation.surface": candidate,
|
||||
}
|
||||
|
||||
def detect(self, rgb: np.ndarray):
|
||||
return [tuple(item["box"]) for item in self.detect_observations(rgb)]
|
||||
|
||||
def detect_observations(self, rgb: np.ndarray):
|
||||
"""Preserve detector hypotheses; a query index is not a tracked identity."""
|
||||
if self.source is not None:
|
||||
rgb = self.source.model_rgb(rgb)
|
||||
if rgb.shape != (600, 800, 3) or rgb.dtype != np.uint8:
|
||||
raise ValueError("Expected an 800x600 RGB simulation camera")
|
||||
bgr = np.ascontiguousarray(rgb[:, :, ::-1])
|
||||
@@ -141,14 +174,20 @@ class ModelInference:
|
||||
key for key, value in COCO_SPARSE_TO_CONTIGUOUS.items() if value in RISK_CLASS_IDS
|
||||
]
|
||||
scores = probabilities[:, classes].max(axis=1)
|
||||
boxes = []
|
||||
for x, y, width, height in output.boxes[0][scores >= 0.25]:
|
||||
selected = np.argmax(probabilities[:, classes], axis=1)
|
||||
observations = []
|
||||
for query in np.flatnonzero(scores >= 0.25):
|
||||
x, y, width, height = output.boxes[0][query]
|
||||
if width <= 0 or height <= 0:
|
||||
continue
|
||||
# Unlike the recorded diagnostic filter, never discard a very large near obstacle.
|
||||
box = np.clip([x - width / 2, y - height / 2, x + width / 2, y + height / 2], 0, 1)
|
||||
boxes.append(tuple(float(value) for value in box))
|
||||
return boxes
|
||||
category = classes[int(selected[query])]
|
||||
observations.append(dict(box=[float(value) for value in box],
|
||||
coco_category_id=category,
|
||||
class_name=COCO_CLASSES[COCO_SPARSE_TO_CONTIGUOUS[category]],
|
||||
confidence=float(scores[query]), detector_query_index=int(query)))
|
||||
return observations
|
||||
|
||||
def infer(self, rgb: np.ndarray):
|
||||
return np.isin(self.segment(rgb), self.road_ids), self.detect(rgb)
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Mutable library labels/visibility, separate from immutable simulation evidence."""
|
||||
|
||||
import json
|
||||
import re
|
||||
|
||||
from k1link.simulation.ai_polygon.worlds import write_json
|
||||
|
||||
IDENTITY = re.compile(r"^(?:aiplan|airun)-[a-f0-9]{32}$")
|
||||
|
||||
|
||||
class LibraryMetadata:
|
||||
def __init__(self, root):
|
||||
self.root = root
|
||||
root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
|
||||
def path(self, identity):
|
||||
if not IDENTITY.fullmatch(identity):
|
||||
raise FileNotFoundError(identity)
|
||||
path = self.root / (identity + ".json")
|
||||
if path.is_symlink():
|
||||
raise ValueError("Library metadata must be a regular file")
|
||||
return path
|
||||
|
||||
def get(self, identity):
|
||||
path = self.path(identity)
|
||||
return json.loads(path.read_text()) if path.exists() else {}
|
||||
|
||||
def update(self, identity, changes):
|
||||
value = {**self.get(identity), **changes}
|
||||
write_json(self.path(identity), value)
|
||||
return value
|
||||
|
||||
def visible(self, rows, key):
|
||||
result = []
|
||||
for row in rows:
|
||||
metadata = self.get(row[key])
|
||||
if not metadata.get("removed", False):
|
||||
result.append({**row, **metadata})
|
||||
return result
|
||||
@@ -4,10 +4,18 @@ Operator waypoints specify the task. They are not a collision map or a motion
|
||||
trajectory. CMU retains authority to reject every requested local waypoint.
|
||||
"""
|
||||
|
||||
import copy
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .observed_recovery import ObservedRecovery
|
||||
|
||||
# An observed local goal may be offset from the declared task/corner centre.
|
||||
# Reserve CMU's 0.08 m stopping tolerance plus 0.02 m inside the unchanged
|
||||
# 0.4 m arrival radius. This retains intent only, never admits body support.
|
||||
OBSERVED_ARRIVAL_GOAL_RADIUS_M = 0.3
|
||||
|
||||
|
||||
def inclination(pose):
|
||||
x, y = pose[3:5]
|
||||
@@ -15,11 +23,15 @@ def inclination(pose):
|
||||
|
||||
|
||||
class WaypointMission:
|
||||
turn_budget_seconds = 24
|
||||
heading_progress_radians = 0.15
|
||||
|
||||
def __init__(self, route):
|
||||
self.route = [list(p) for p in route]
|
||||
self.index = self.attempts = 0
|
||||
self.anchor = self.anchor_time = None
|
||||
self.last_time = None
|
||||
self.last_pose = None
|
||||
self.state = "following"
|
||||
self.failed_goals = []
|
||||
self.goal = None
|
||||
@@ -27,6 +39,59 @@ class WaypointMission:
|
||||
self.best_distance = None
|
||||
self.recovery_goal = None
|
||||
self.recovery_started = None
|
||||
self.turn_started = self.turn_goal = self.turn_best_error = None
|
||||
self.recovery = ObservedRecovery()
|
||||
self.last_recovery_attempt = None
|
||||
|
||||
def heading_progress(self, pose, seconds):
|
||||
"""Credit new best alignment within the existing bounded turn budget.
|
||||
|
||||
A stationary turn does not reduce waypoint distance. Only a new best
|
||||
heading toward the same declared direction earns time; oscillation or
|
||||
changing goals alone cannot refresh the progress watchdog. A viewing
|
||||
direction can exist before the camera admits a translation goal.
|
||||
Recovery attempts are never replenished by turning alone.
|
||||
"""
|
||||
orientation = self.progress_orientation_target(seconds)
|
||||
target = orientation["xy"] if orientation is not None else self.goal
|
||||
if target is None:
|
||||
return False
|
||||
delta = np.asarray(target[:2]) - np.asarray(pose[:2])
|
||||
if np.linalg.norm(delta) < 0.1:
|
||||
return False
|
||||
x, y, z, w = pose[3:7]
|
||||
yaw = math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))
|
||||
bearing = math.atan2(delta[1], delta[0])
|
||||
error = abs(math.atan2(math.sin(bearing - yaw), math.cos(bearing - yaw)))
|
||||
if self.turn_started is None:
|
||||
self.turn_started = seconds
|
||||
goal = orientation["key"] if orientation is not None else tuple(target[:2])
|
||||
if self.turn_goal != goal:
|
||||
self.turn_goal, self.turn_best_error = goal, error
|
||||
return False
|
||||
if seconds - self.turn_started > self.turn_budget_seconds:
|
||||
return False
|
||||
if error <= 0.1 < self.turn_best_error:
|
||||
# A measured completed turn starts the translation phase once.
|
||||
# Contact slip may have increased remaining route distance during
|
||||
# the pivot. Measure subsequent translation from this actual pose,
|
||||
# without crediting arrival or replenishing recovery attempts.
|
||||
# The monotonically decreasing best heading prevents jitter from
|
||||
# repeating this transition.
|
||||
self.turn_best_error = error
|
||||
# A local body destination only earns bounded turning time. Its
|
||||
# completion cannot re-anchor global distance: alternating local
|
||||
# destinations must not turn backwards drift into route progress.
|
||||
if orientation == self.orientation_target() and self.recovery.sequence == 0:
|
||||
self.best_distance = self.distance_to_target(pose, target)
|
||||
return True
|
||||
if self.turn_best_error - error >= self.heading_progress_radians:
|
||||
self.turn_best_error = error
|
||||
return True
|
||||
return False
|
||||
|
||||
def progress_orientation_target(self, seconds):
|
||||
return self.orientation_target()
|
||||
|
||||
def resume(self):
|
||||
# Pause freezes the world clock. Preserve the mission cursor and any
|
||||
@@ -34,28 +99,111 @@ class WaypointMission:
|
||||
# goal entering the camera blind strip, but revalidate it before motion.
|
||||
self.anchor = self.anchor_time = None
|
||||
|
||||
def update(self, pose, seconds, choose_goal, choose_recovery=None):
|
||||
xy = np.asarray(pose[:2])
|
||||
if self.last_time is not None and seconds < self.last_time:
|
||||
raise ValueError("Mission observations must not rewind")
|
||||
self.last_time = seconds
|
||||
if inclination(pose) >= 30:
|
||||
self.fault = "unstable"
|
||||
if self.fault:
|
||||
return None, self.intent(self.fault)
|
||||
if self.route and np.linalg.norm(xy - self.route[self.index]) <= 0.4:
|
||||
if self.index == len(self.route) - 1:
|
||||
self.fault = "goal-reached"
|
||||
return None, self.intent(self.fault)
|
||||
def retire_local_goal(self, target, *, failed=False):
|
||||
# An observed arrival point is evidence for the task waypoint, not an
|
||||
# expendable intermediate manoeuvre. Keep it through a temporary block
|
||||
# or retreat so revalidation can finish the waypoint in the camera's
|
||||
# blind strip. choose_goal and live collision checks still veto motion;
|
||||
# the recovery budget still terminates a permanently blocked route.
|
||||
if self.goal is None or (
|
||||
target is not None
|
||||
and np.linalg.norm(np.asarray(self.goal[:2]) - target) <= OBSERVED_ARRIVAL_GOAL_RADIUS_M
|
||||
):
|
||||
return
|
||||
if failed:
|
||||
self.failed_goals.append(self.goal)
|
||||
self.goal = None
|
||||
|
||||
def arrival_candidate(self, pose):
|
||||
return bool(
|
||||
self.route
|
||||
and not self.fault
|
||||
and np.linalg.norm(np.asarray(pose[:2]) - self.route[self.index]) <= 0.4
|
||||
)
|
||||
|
||||
def can_query_arrival(self, pose):
|
||||
return True
|
||||
|
||||
def arrival_target(self):
|
||||
return self.route[self.index] if self.route else None
|
||||
|
||||
def retain_arrival_query(self, goal):
|
||||
return True
|
||||
|
||||
def orientation_target(self):
|
||||
if not self.route or self.fault:
|
||||
return None
|
||||
return {"key": self.orientation_key(f"waypoint-{self.index}"),
|
||||
"xy": list(self.route[self.index])}
|
||||
|
||||
def orientation_key(self, key):
|
||||
# A recovery may leave the robot facing away from the task. Completion
|
||||
# of the old alignment belongs to the old intent, not to the waypoint
|
||||
# forever. Re-enter stop-and-align once, without resetting route progress.
|
||||
return key + (f"-recovery-{self.recovery.sequence}" if self.recovery.sequence else "")
|
||||
|
||||
def distance_to_target(self, pose, target):
|
||||
return float(np.linalg.norm(np.asarray(pose[:2]) - target)) if target is not None else None
|
||||
|
||||
def confirm_arrival(self, pose, seconds, waypoint, *, admitted):
|
||||
"""Commit only the current observation's whole-body admission receipt.
|
||||
|
||||
Distance is a candidate, not completion. A missing, rejected or old
|
||||
receipt never changes the mission cursor or replenishes recovery.
|
||||
"""
|
||||
if (
|
||||
admitted is not True
|
||||
or seconds != self.last_time
|
||||
or tuple(pose) != self.last_pose
|
||||
or waypoint != self.index
|
||||
or inclination(pose) >= 30
|
||||
or not self.arrival_candidate(pose)
|
||||
):
|
||||
return False
|
||||
if self.index == len(self.route) - 1:
|
||||
self.fault = self.state = "goal-reached"
|
||||
else:
|
||||
self.index += 1
|
||||
self.anchor = self.goal = None
|
||||
self.best_distance = None
|
||||
self.recovery_goal = None
|
||||
self.attempts = 0
|
||||
self.turn_started = self.turn_goal = self.turn_best_error = None
|
||||
self.state = "replanning"
|
||||
return True
|
||||
|
||||
def update(self, pose, seconds, choose_goal, choose_recovery=None, *, choose_maneuver=None):
|
||||
xy = np.asarray(pose[:2])
|
||||
if self.last_time is not None and seconds < self.last_time:
|
||||
raise ValueError("Mission observations must not rewind")
|
||||
self.last_time = seconds
|
||||
self.last_pose = tuple(pose)
|
||||
if inclination(pose) >= 30:
|
||||
self.fault = "unstable"
|
||||
if self.fault:
|
||||
return None, self.intent(self.fault)
|
||||
if self.recovery.active:
|
||||
selected, state = self.recovery.tick(pose, seconds, choose_maneuver)
|
||||
self.state = state
|
||||
if not self.recovery.active:
|
||||
# Keep one completed attempt after begin() clears the live
|
||||
# recovery failure. This is diagnostic evidence, never intent
|
||||
# or motion authority, and must survive terminal stuck.
|
||||
self.last_recovery_attempt = dict(
|
||||
sequence=self.recovery.sequence,
|
||||
attempt=self.attempts,
|
||||
ended_seconds=seconds,
|
||||
failure=copy.deepcopy(self.recovery.failure),
|
||||
)
|
||||
self.failed_goals = list(self.recovery.excluded)
|
||||
self.anchor_time = seconds
|
||||
self.goal = None
|
||||
self.turn_started = self.turn_goal = self.turn_best_error = None
|
||||
return selected, self.intent(state)
|
||||
target = self.route[self.index] if self.route else None
|
||||
if self.anchor is None:
|
||||
self.anchor, self.anchor_time = xy.copy(), seconds
|
||||
distance = float(np.linalg.norm(xy - target)) if target is not None else None
|
||||
distance = self.distance_to_target(pose, target)
|
||||
if self.best_distance is None:
|
||||
self.best_distance = distance
|
||||
progress = self.best_distance - distance if target is not None else 0.0
|
||||
@@ -71,7 +219,8 @@ class WaypointMission:
|
||||
return self.recovery_goal, self.intent("reversing")
|
||||
# Recovery is an attempt to escape, never route progress. The next
|
||||
# forward attempt must beat the previous best distance to the task.
|
||||
self.recovery_goal = self.goal = None
|
||||
self.recovery_goal = None
|
||||
self.retire_local_goal(target)
|
||||
self.anchor_time = seconds
|
||||
return None, self.intent("replanning")
|
||||
if progress >= 0.1:
|
||||
@@ -80,17 +229,22 @@ class WaypointMission:
|
||||
self.best_distance = distance
|
||||
self.attempts = 0
|
||||
self.failed_goals.clear()
|
||||
self.turn_started = self.turn_goal = self.turn_best_error = None
|
||||
elif self.heading_progress(pose, seconds):
|
||||
self.anchor_time = seconds
|
||||
stalled = seconds - self.anchor_time >= 8
|
||||
if stalled:
|
||||
self.attempts += 1
|
||||
if self.goal is not None:
|
||||
self.failed_goals.append(self.goal)
|
||||
self.goal = None
|
||||
self.retire_local_goal(target, failed=True)
|
||||
self.anchor_time = seconds
|
||||
if self.attempts > 3:
|
||||
self.fault = "stuck"
|
||||
return None, self.intent("stuck")
|
||||
self.state = "replanning"
|
||||
if choose_maneuver is not None:
|
||||
self.recovery.begin(pose, seconds, self.failed_goals)
|
||||
self.state = "surveying"
|
||||
return None, self.intent(self.state)
|
||||
if choose_recovery is not None:
|
||||
self.recovery_goal = choose_recovery(None)
|
||||
if self.recovery_goal is not None:
|
||||
@@ -113,4 +267,7 @@ class WaypointMission:
|
||||
waypoint=self.index,
|
||||
waypoint_count=len(self.route),
|
||||
recovery_attempt=self.attempts,
|
||||
**({"recovery": self.recovery.evidence()} if self.recovery.active else {}),
|
||||
**({"last_recovery_attempt": copy.deepcopy(self.last_recovery_attempt)}
|
||||
if self.last_recovery_attempt is not None else {}),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
"""Observation-driven local manoeuvres, independent of scene and renderer.
|
||||
|
||||
Like a navigation recovery subtree, this owns intent and progress, never motor
|
||||
admission. A completed survey is not permission to move: the selected heading
|
||||
or destination still passes the normal live body/support/obstacle controller.
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
|
||||
def heading(pose):
|
||||
x, y, z, w = pose[3:7]
|
||||
return math.atan2(2 * (w*z + x*y), 1 - 2 * (y*y + z*z))
|
||||
|
||||
|
||||
def angle(value):
|
||||
return math.atan2(math.sin(value), math.cos(value))
|
||||
|
||||
|
||||
class ObservedRecovery:
|
||||
sectors = (0, 90, -90, 180)
|
||||
no_progress_seconds = 8.0
|
||||
|
||||
def __init__(self):
|
||||
self.phase = "idle"
|
||||
self.sequence = 0
|
||||
self.option = 0
|
||||
self.selected = None
|
||||
self.excluded = []
|
||||
self.views = {}
|
||||
self.request = None
|
||||
self.previous = None
|
||||
self._stationary_at_previous = False
|
||||
self.best_distance = self.best_heading = None
|
||||
self.blockage = None
|
||||
self.blocked_option = False
|
||||
self.failure = None
|
||||
|
||||
@property
|
||||
def active(self):
|
||||
return self.phase != "idle"
|
||||
|
||||
def begin(self, pose, seconds, excluded):
|
||||
self.sequence += 1
|
||||
self.phase = "stopping"
|
||||
self.selected = self.request = self.previous = None
|
||||
self._stationary_at_previous = False
|
||||
self.views = {}
|
||||
self.excluded = [list(p) for p in excluded]
|
||||
self.started = self.progress_at = seconds
|
||||
self.wait_progress_at = seconds
|
||||
self.survey_progress = 0
|
||||
self.option = 0
|
||||
self.blockage = None
|
||||
self.blocked_option = False
|
||||
self.failure = None
|
||||
|
||||
def observe_navigation(self, result, pose, seconds, option_key, execution_inputs_sha256):
|
||||
"""Retire a consistently vetoed intention, never grant motion.
|
||||
|
||||
Missing/old data and planner startup are not evidence of an obstacle.
|
||||
Bind both confirmations to this option, current sector, pose and run.
|
||||
"""
|
||||
if (self.phase != "executing" or option_key != (self.sequence, self.option)
|
||||
or not self.view_current(pose, seconds)):
|
||||
return
|
||||
observation = result.get("route_observation", {}).get("observation")
|
||||
expected = dict(pose=list(pose), simulation_time_seconds=seconds,
|
||||
execution_inputs_sha256=execution_inputs_sha256)
|
||||
if observation != expected:
|
||||
return
|
||||
failure = result.get("diagnostic", {}).get("failure")
|
||||
hard_veto = failure in {
|
||||
"no-path", "footprint", "observed-unsafe-support",
|
||||
"forbidden-surface-sweep", "detected-object-sweep",
|
||||
}
|
||||
if (result.get("status") != "blocked" or not hard_veto
|
||||
or abs(result.get("speed_mps", 0))+abs(result.get("yaw_rate_rps", 0)) > 1e-5):
|
||||
self.blockage = None
|
||||
return
|
||||
if self.blockage is not None:
|
||||
before, stamp = self.blockage
|
||||
if (math.dist(pose[:2], before[:2]) <= .05
|
||||
and abs(angle(heading(pose)-heading(before))) <= .05):
|
||||
if seconds-stamp >= .5:
|
||||
self.blocked_option = True
|
||||
return
|
||||
self.blockage = (list(pose), seconds)
|
||||
|
||||
def observe_view(self, request, pose, seconds):
|
||||
# The producer copies this exact request before capture processing.
|
||||
# Old/in-flight sectors cannot acknowledge a new recovery phase.
|
||||
if request is None or request != self.request or seconds < request["after_seconds"]:
|
||||
return
|
||||
self.views[request["yaw_degrees"]] = (seconds, list(pose), request["key"])
|
||||
# Credit a new best survey extent, never repeated frames or a cycle
|
||||
# which clears and reacquires the same incomplete set of sectors.
|
||||
if self.phase == "surveying" and len(self.views) > self.survey_progress:
|
||||
self.survey_progress = len(self.views)
|
||||
self.wait_progress_at = seconds
|
||||
|
||||
def view_request(self, pose, seconds):
|
||||
yaw = None
|
||||
if self.phase == "surveying":
|
||||
yaw = next((v for v in self.sectors if v not in self.views), None)
|
||||
elif self.phase == "executing" and self.selected:
|
||||
dx, dy = (self.selected["goal"][i] - pose[i] for i in range(2))
|
||||
bearing = math.degrees(angle(math.atan2(dy, dx) - heading(pose)))
|
||||
yaw = int(round(bearing / 90) * 90)
|
||||
yaw = 180 if yaw == -180 else yaw
|
||||
if yaw is None:
|
||||
self.request = None
|
||||
elif self.request is None or self.request["yaw_degrees"] != yaw:
|
||||
self.request = dict(key=f"recovery-{self.sequence}-{self.option}-{yaw}",
|
||||
yaw_degrees=yaw, after_seconds=seconds)
|
||||
return self.request.copy() if self.request else None
|
||||
|
||||
def view_current(self, pose, seconds):
|
||||
if self.request is None:
|
||||
return False
|
||||
observed = self.views.get(self.request["yaw_degrees"])
|
||||
return bool(observed and observed[2] == self.request["key"]
|
||||
and observed[0] >= self.request["after_seconds"]
|
||||
and 0 <= seconds - observed[0] <= 2
|
||||
and math.dist(pose[:2], observed[1][:2]) <= 0.5
|
||||
and abs(angle(heading(pose)-heading(observed[1]))) <= math.radians(40))
|
||||
|
||||
def orientation(self):
|
||||
if self.phase != "executing" or self.selected is None or self.selected["reverse"]:
|
||||
return None
|
||||
return {"key": f"recovery-{self.sequence}-{self.option}",
|
||||
"xy": list(self.selected["goal"][:2])}
|
||||
|
||||
def tick(self, pose, seconds, choose):
|
||||
stationary = False
|
||||
if self.previous is not None:
|
||||
before, stamp = self.previous
|
||||
dt = seconds-stamp
|
||||
if dt == 0 and list(pose) == before:
|
||||
# Independent neural completions can replan the same range
|
||||
# sample. Reuse its proof without inventing another pose pair
|
||||
# or moving any progress/deadline timestamp.
|
||||
stationary = self._stationary_at_previous
|
||||
elif dt <= 0:
|
||||
# Contradictory samples and time reversal cannot preserve a
|
||||
# stationary survey or rewind its time reference.
|
||||
self._stationary_at_previous = False
|
||||
self.views.clear()
|
||||
self.request = None
|
||||
return None, "surveying"
|
||||
else:
|
||||
stationary = (dt <= 1 and math.dist(pose[:2], before[:2]) <= .025*dt
|
||||
and abs(angle(heading(pose)-heading(before))) <= .04*dt)
|
||||
self.previous = (list(pose), seconds)
|
||||
self._stationary_at_previous = stationary
|
||||
# As in a pose progress checker, lack of measured progress retires an
|
||||
# option below. Do not abort a slow but progressing turn by total age.
|
||||
if self.phase == "stopping":
|
||||
if stationary:
|
||||
self.phase = "surveying"
|
||||
self.wait_progress_at = seconds
|
||||
elif seconds - self.wait_progress_at >= self.no_progress_seconds:
|
||||
return self.fail_wait("stop-unconfirmed", seconds)
|
||||
return None, "surveying"
|
||||
if self.phase == "surveying":
|
||||
if not stationary:
|
||||
self.views.clear()
|
||||
self.request = None
|
||||
if seconds - self.wait_progress_at >= self.no_progress_seconds:
|
||||
return self.fail_wait("survey-incomplete", seconds)
|
||||
if not stationary:
|
||||
return None, "surveying"
|
||||
if not all(sector in self.views for sector in self.sectors):
|
||||
return None, "surveying"
|
||||
self.phase = "selecting"
|
||||
if self.phase == "selecting":
|
||||
self.selected = choose(None, self.excluded)
|
||||
if self.selected is None:
|
||||
self.phase = "idle"
|
||||
return None, "replanning"
|
||||
self.option += 1
|
||||
self.phase = "executing"
|
||||
self.request = None
|
||||
self.progress_at = seconds
|
||||
self.best_distance = math.dist(pose[:2], self.selected["goal"][:2])
|
||||
self.best_heading = math.inf
|
||||
self.blockage = None
|
||||
self.blocked_option = False
|
||||
if self.phase == "executing":
|
||||
distance = math.dist(pose[:2], self.selected["goal"][:2])
|
||||
observed = choose(self.selected, self.excluded)
|
||||
dx, dy = (self.selected["goal"][i] - pose[i] for i in range(2))
|
||||
desired = math.atan2(dy, dx) + (math.pi if self.selected["reverse"] else 0)
|
||||
error = abs(angle(desired-heading(pose)))
|
||||
orienting = self.selected.get("kind") == "orient"
|
||||
if (error <= .1 if orienting else distance <= .3):
|
||||
self.phase = "idle"
|
||||
return None, "replanning"
|
||||
if self.best_distance-distance >= .1 or self.best_heading-error >= .05:
|
||||
self.progress_at = seconds
|
||||
self.best_distance = min(self.best_distance, distance)
|
||||
self.best_heading = min(self.best_heading, error)
|
||||
if (observed is None or self.blocked_option
|
||||
or seconds-self.progress_at >= self.no_progress_seconds):
|
||||
self.excluded.append(list(self.selected["goal"]))
|
||||
self.phase = "selecting"
|
||||
self.selected = self.request = None
|
||||
return None, "surveying"
|
||||
# Request the manoeuvre's current view BEFORE accepting translation
|
||||
# or a pivot. A sector switch is observation, never chassis rotation.
|
||||
self.view_request(pose, seconds)
|
||||
if not self.view_current(pose, seconds):
|
||||
return None, "surveying"
|
||||
if orienting:
|
||||
return None, "orienting"
|
||||
return self.selected["goal"], "reversing" if self.selected["reverse"] else "manoeuvring"
|
||||
return None, "surveying"
|
||||
|
||||
def fail_wait(self, reason, seconds):
|
||||
"""Finish this attempt without inventing geometry or resetting its budget."""
|
||||
self.failure = dict(reason=reason, phase=self.phase, seconds=seconds,
|
||||
last_progress_seconds=self.wait_progress_at,
|
||||
surveyed_sectors=sorted(self.views))
|
||||
self.phase = "idle"
|
||||
self.selected = self.request = None
|
||||
return None, "replanning"
|
||||
|
||||
def evidence(self):
|
||||
return dict(phase=self.phase, option=self.option, selected=self.selected,
|
||||
surveyed_sectors=sorted(self.views), request=self.request,
|
||||
rejected_goals=self.excluded, failure=self.failure)
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Immutable, operator-confirmed simulation tasks, independent of run history."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
from uuid import uuid4
|
||||
|
||||
from k1link.artifacts import utc_now_iso
|
||||
from k1link.simulation.ai_polygon.library import LibraryMetadata
|
||||
from k1link.simulation.ai_polygon.worlds import write_json
|
||||
|
||||
PLAN_ID = re.compile(r"^aiplan-[a-f0-9]{32}$")
|
||||
|
||||
|
||||
class PlanStore:
|
||||
def __init__(self, root):
|
||||
self.root = root
|
||||
root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
self.library = LibraryMetadata(root / "library")
|
||||
|
||||
def get(self, identity):
|
||||
if not PLAN_ID.fullmatch(identity):
|
||||
raise FileNotFoundError(identity)
|
||||
path = self.root / (identity + ".json")
|
||||
if path.is_symlink():
|
||||
raise ValueError("Plan must be a regular file")
|
||||
row = json.loads(path.read_text())
|
||||
content = {key: value for key, value in row.items() if key != "sha256"}
|
||||
if row["plan_id"] != identity or row["sha256"] != self.digest(content):
|
||||
raise ValueError("Сохранённое задание повреждено.")
|
||||
return row
|
||||
|
||||
def list(self):
|
||||
return sorted(
|
||||
[self.get(p.stem) for p in self.root.glob("aiplan-*.json")],
|
||||
key=lambda p: p["created_at"],
|
||||
reverse=True,
|
||||
)
|
||||
|
||||
def visible_list(self):
|
||||
return self.library.visible(self.list(), "plan_id")
|
||||
|
||||
@staticmethod
|
||||
def digest(value):
|
||||
return hashlib.sha256(
|
||||
json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
|
||||
).hexdigest()
|
||||
|
||||
def create(
|
||||
self,
|
||||
run,
|
||||
name,
|
||||
points,
|
||||
sequence,
|
||||
*,
|
||||
draft_id=None,
|
||||
cache_key=None,
|
||||
editor_collider_sha256=None,
|
||||
):
|
||||
if not 2 <= len(points) <= 33:
|
||||
raise ValueError("Нужны старт и финиш: от 2 до 33 точек.")
|
||||
if len({p["id"] for p in points}) != len(points):
|
||||
raise ValueError("Идентификаторы точек должны различаться.")
|
||||
for old in self.list():
|
||||
if self.library.get(old["plan_id"]).get("removed"):
|
||||
continue
|
||||
if (
|
||||
old.get("source_draft_id", old["source_run_id"]) == (draft_id or run["run_id"])
|
||||
and old["source_sequence"] == sequence
|
||||
and old.get("editor_cache_key") == cache_key
|
||||
and old["robot_sha256"] == run["robot"]["sha256"]
|
||||
and old["name"] == name
|
||||
and old["points"] == points
|
||||
):
|
||||
return old
|
||||
for point in points:
|
||||
xyz = point["position"]
|
||||
if len(xyz) != 3 or not all(math.isfinite(v) and abs(v) <= 10000 for v in xyz):
|
||||
raise ValueError("Некорректная точка поверхности.")
|
||||
positions = [p["position"] for p in points]
|
||||
if any(
|
||||
math.dist(a[:2], b[:2]) < 0.15 for a, b in zip(positions, positions[1:], strict=False)
|
||||
):
|
||||
raise ValueError("Соседние точки должны быть дальше 15 см друг от друга.")
|
||||
first, second = positions[:2]
|
||||
settings = {
|
||||
**run["world"]["settings"],
|
||||
"spawn_xy": first[:2],
|
||||
"ground_z": first[2],
|
||||
"heading_degrees": math.degrees(math.atan2(second[1] - first[1], second[0] - first[0])),
|
||||
"route_xy": [p[:2] for p in positions[1:]],
|
||||
"prepared": True,
|
||||
}
|
||||
value = {
|
||||
"schema_version": "missioncore.simulation-plan/v1",
|
||||
"plan_id": "aiplan-" + uuid4().hex,
|
||||
"name": name,
|
||||
"created_at": utc_now_iso(),
|
||||
"source": "operator-viewport",
|
||||
"source_run_id": run["run_id"],
|
||||
"source_sequence": sequence,
|
||||
"world_id": run["world"]["world_id"],
|
||||
"world_sha256": run["world"]["sha256"],
|
||||
"collider_sha256": run["world"].get("collider_sha256"),
|
||||
"robot_id": run["robot"]["robot_id"],
|
||||
"robot_sha256": run["robot"]["sha256"],
|
||||
"points": points,
|
||||
"settings": settings,
|
||||
"arrival_radius_m": 0.4,
|
||||
"length_m": sum(
|
||||
math.dist(a, b) for a, b in zip(positions, positions[1:], strict=False)
|
||||
),
|
||||
}
|
||||
if draft_id:
|
||||
value.update(
|
||||
source="operator-local-viewport",
|
||||
source_draft_id=draft_id,
|
||||
editor_cache_key=cache_key,
|
||||
editor_collider_sha256=editor_collider_sha256,
|
||||
)
|
||||
row = {**value, "sha256": self.digest(value)}
|
||||
write_json(self.root / (row["plan_id"] + ".json"), row)
|
||||
return row
|
||||
@@ -11,7 +11,7 @@ from k1link.simulation.ai_polygon.contracts import Decision
|
||||
|
||||
class RoadPolicy:
|
||||
def __init__(self, max_speed_mps: float):
|
||||
if not 0 < max_speed_mps <= 1:
|
||||
if not np.isfinite(max_speed_mps) or max_speed_mps <= 0:
|
||||
raise ValueError("invalid laboratory speed")
|
||||
self.max_speed = max_speed_mps
|
||||
self.clear_frames = 0
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Read-through projection of Gaussian Pipeline projects into the location library.
|
||||
|
||||
The project remains the sole owner of its artifacts and calibration. No source
|
||||
copy, second conversion job, or preview masquerading as the full scene.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from urllib.parse import unquote
|
||||
|
||||
from k1link.simulation.projects import SimulationProjectStore
|
||||
|
||||
from .contracts import WorldSettings
|
||||
|
||||
|
||||
class ProjectWorlds:
|
||||
def __init__(self, data_dir):
|
||||
self.projects = SimulationProjectStore(data_dir)
|
||||
|
||||
def list(self):
|
||||
return [self.world(p) for p in self.projects.list() if p.get("world_manifest")]
|
||||
|
||||
def get(self, world_id):
|
||||
try:
|
||||
return self.world(self.projects.get("sim-" + world_id.removeprefix("aiworld-")))
|
||||
except RuntimeError as exc:
|
||||
raise FileNotFoundError(world_id) from exc
|
||||
|
||||
def world(self, project):
|
||||
manifest = project["world_manifest"]
|
||||
settings = project["viewer_settings"]
|
||||
# The saved viewer transforms override (not multiply) the defaults in
|
||||
# world_manifest, exactly as in the existing local viewer.
|
||||
scene = {
|
||||
"visual_url": manifest["visual"]["streamed_sog_url"]
|
||||
or manifest["visual"]["preview_sog_url"],
|
||||
"collision_url": manifest["collision"]["mesh_url"],
|
||||
"visual_rotation": [settings["visual"]["rotation_degrees"][a] for a in ("x", "y", "z")],
|
||||
"collision_rotation": [
|
||||
settings["collision"]["rotation_degrees"][a] for a in ("x", "y", "z")
|
||||
],
|
||||
"project_id": project["project_id"],
|
||||
}
|
||||
identity = {
|
||||
"source": project["source"]["bundle_sha256"],
|
||||
"scene": scene,
|
||||
"artifacts": project["artifacts"],
|
||||
}
|
||||
digest = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest()
|
||||
return {
|
||||
"schema_version": "missioncore.ai-polygon-world/v1",
|
||||
"world_id": project["project_id"].replace("sim-", "aiworld-", 1),
|
||||
"name": project["name"],
|
||||
"author": "",
|
||||
"license": "",
|
||||
"source_url": None,
|
||||
"filename": "lod-meta.json",
|
||||
"byte_length": sum(a["byte_length"] for a in project["artifacts"]),
|
||||
"status": "available",
|
||||
"uploaded_bytes": 0,
|
||||
"sha256": digest,
|
||||
"splat_count": None,
|
||||
"created_at": project["created_at_utc"],
|
||||
"settings": WorldSettings(
|
||||
prepared=bool(scene["collision_url"]), rotation_degrees=(90, 0, 0)
|
||||
).model_dump(mode="json"),
|
||||
"storage": {"kind": "project", "project_id": project["project_id"]},
|
||||
"local_scene": scene,
|
||||
"collider_sha256": self.cache_files(
|
||||
{"storage": {"project_id": project["project_id"]}, "local_scene": scene}
|
||||
)["collision.glb"]["sha256"],
|
||||
"inference_ready": True,
|
||||
|
||||
}
|
||||
|
||||
def package(self, world):
|
||||
project = self.projects.get(world["storage"]["project_id"])
|
||||
prefix = f"/api/v1/simulation-worlds/projects/{project['project_id']}/artifacts/"
|
||||
paths = {
|
||||
k: unquote(world["local_scene"][k + "_url"].removeprefix(prefix))
|
||||
for k in ("visual", "collision")
|
||||
}
|
||||
artifacts = [
|
||||
a
|
||||
for a in project["artifacts"]
|
||||
if (
|
||||
a["logical_path"].startswith("streamed/0_")
|
||||
or a["logical_path"].startswith("streamed/env/")
|
||||
)
|
||||
or a["logical_path"] in paths.values()
|
||||
]
|
||||
return {
|
||||
"world_sha256": world["sha256"],
|
||||
"project_id": project["project_id"],
|
||||
"provider_job_id": project["provider"]["job_id"],
|
||||
"artifacts": artifacts,
|
||||
"visual_path": paths["visual"],
|
||||
"collision_path": paths["collision"],
|
||||
}
|
||||
|
||||
def cache_files(self, world):
|
||||
result = {}
|
||||
project_id = world["storage"]["project_id"]
|
||||
prefix = f"/api/v1/simulation-worlds/projects/{project_id}/artifacts/"
|
||||
for name, url in (
|
||||
("scene.sog", world["local_scene"]["visual_url"]),
|
||||
("collision.glb", world["local_scene"]["collision_url"]),
|
||||
):
|
||||
if not url or not url.startswith(prefix):
|
||||
raise ValueError("В локации отсутствует локальная сцена или поверхность.")
|
||||
path, descriptor = self.projects.artifact_path(project_id, unquote(url[len(prefix) :]))
|
||||
if path.stat().st_size != descriptor["byte_length"]:
|
||||
raise ValueError("Артефакт локации изменился.")
|
||||
result[name] = {
|
||||
"sha256": descriptor["sha256"],
|
||||
"byte_length": descriptor["byte_length"],
|
||||
"uploaded_bytes": descriptor["byte_length"],
|
||||
}
|
||||
return result
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Installed simulation robots. A selection identifies geometry, sensors and dynamics."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_ROBOT = "dcd006-v020"
|
||||
ADAPTERS = Path(__file__).resolve().parents[4] / "simulation/ai-polygon"
|
||||
|
||||
|
||||
def robot_catalog(adapters: Path = ADAPTERS) -> list[dict]:
|
||||
result = []
|
||||
for path in sorted((adapters / "robots").glob("*.json")):
|
||||
raw = path.read_bytes()
|
||||
robot = json.loads(raw)
|
||||
if robot["robot_id"] != path.stem:
|
||||
raise ValueError("Robot profile identity mismatch")
|
||||
result.append({**robot, "sha256": hashlib.sha256(raw).hexdigest()})
|
||||
return result
|
||||
|
||||
|
||||
def select_robot(robot_id: str, expected_sha256: str | None = None, adapters: Path = ADAPTERS):
|
||||
robot = next((r for r in robot_catalog(adapters) if r["robot_id"] == robot_id), None)
|
||||
if robot is None:
|
||||
raise ValueError("Этот ровер не установлен в симуляторе.")
|
||||
if expected_sha256 is not None and robot["sha256"] != expected_sha256:
|
||||
raise ValueError("Профиль ровера изменился. Обновите список перед запуском.")
|
||||
return robot
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Bounded session exclusions from stopped, fresh local obstacle observations.
|
||||
|
||||
An exclusion means this episode abandoned a locally blocked edge. It is not a
|
||||
claim that the whole corridor is impassable, and never supplies ground support.
|
||||
Unknown ground, network waits and a moving person detector are not map edits.
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
def yaw(pose):
|
||||
x, y, z, w = pose[3:7]
|
||||
return math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))
|
||||
|
||||
|
||||
class ObservedRouteBlockage:
|
||||
def __init__(self):
|
||||
self.pending = None
|
||||
|
||||
def observe(self, result, points, pose, seconds, inputs, segment, radius):
|
||||
diagnostic = result.get("diagnostic", {})
|
||||
observation = result.get("route_observation")
|
||||
if observation is not None:
|
||||
if observation.get("schema_version") != "missioncore.local-route-observation/v1":
|
||||
self.pending = None
|
||||
return None
|
||||
binding = observation.get("observation")
|
||||
hazards = observation.get("near_obstacles", [])
|
||||
else:
|
||||
# Older recorded transactions have the same exact binding in the
|
||||
# support receipt. Early goal-body returns had no such evidence.
|
||||
binding = diagnostic.get("motion_support", {}).get("observation")
|
||||
hazards = diagnostic.get("near_obstacles", [])
|
||||
blocked = diagnostic.get("failure") in {"no-path", "footprint", "observed-unsafe-support"}
|
||||
blocked |= observation is not None and diagnostic.get("failure") == "goal-body-support"
|
||||
# A local obstacle detour can ask for a pivot which the support policy
|
||||
# vetoes. That secondary veto must not hide a independently observed
|
||||
# blocked edge. Only the dedicated, exactly bound route observation can
|
||||
# establish this case; the current-return/persistence checks below
|
||||
# still reject a support gap without an actual obstacle ahead.
|
||||
blocked |= (
|
||||
observation is not None
|
||||
and diagnostic.get("failure") == "insufficient-fresh-ground"
|
||||
and diagnostic.get("arrival_approach", {}).get("phase") == "local-path"
|
||||
)
|
||||
corridor_detour = (
|
||||
result.get("route_guard") == "swept-body-outside-corridor"
|
||||
and diagnostic.get("failure") == "none"
|
||||
)
|
||||
expected = {
|
||||
"pose": list(pose),
|
||||
"simulation_time_seconds": seconds,
|
||||
"execution_inputs_sha256": inputs["sha256"],
|
||||
}
|
||||
# This is the same transaction already admitted by the adapter. A
|
||||
# latest/old terrain snapshot, timeout or support gap cannot close edges.
|
||||
if (
|
||||
result.get("status") != "blocked"
|
||||
or abs(result.get("speed_mps", 0)) + abs(result.get("yaw_rate_rps", 0)) > 1e-8
|
||||
or not (blocked or corridor_detour)
|
||||
or diagnostic.get("arrival_approach", {}).get("phase") in {"braking", "aligning"}
|
||||
or binding != expected
|
||||
):
|
||||
self.pending = None
|
||||
return None
|
||||
hazards = np.asarray(hazards, dtype=float)
|
||||
points = np.asarray(points, dtype=float)
|
||||
if (
|
||||
hazards.ndim != 2
|
||||
or hazards.shape[1] != 4
|
||||
or len(hazards) > 12
|
||||
or points.ndim != 2
|
||||
or points.shape[1] != 3
|
||||
or not 50 <= len(points) <= 30000
|
||||
or not np.isfinite(hazards).all()
|
||||
or not np.isfinite(points).all()
|
||||
):
|
||||
self.pending = None
|
||||
return None
|
||||
a, b = np.array(segment["start_xy"]), np.array(segment["end_xy"])
|
||||
direction = (b - a) / np.linalg.norm(b - a)
|
||||
lateral = np.array([-direction[1], direction[0]])
|
||||
matched = []
|
||||
for hazard in hazards:
|
||||
# Cost can represent geometry or an explicit semantic exclusion.
|
||||
# Require an actual current return at that location, ahead of the
|
||||
# body, on this edge, near its intended centre line. Memory alone
|
||||
# and an unrelated obstacle behind/alongside the rover cannot act.
|
||||
ahead = float(np.dot(hazard[:2] - pose[:2], direction))
|
||||
along = float(np.dot(hazard[:2] - a, direction))
|
||||
if (
|
||||
hazard[3] > inputs["robot"]["geometry"]["max_step_m"] + 1e-4
|
||||
and radius + 0.1 <= ahead <= 3.5
|
||||
and 0 <= along <= np.linalg.norm(b - a)
|
||||
and abs(float(np.dot(hazard[:2] - a, lateral))) <= radius
|
||||
and np.any(np.linalg.norm(points - hazard[:3], axis=1) <= 0.15)
|
||||
):
|
||||
matched.append(hazard[:3])
|
||||
matched = np.unique(np.asarray(matched).reshape(-1, 3), axis=0)
|
||||
if len(matched) < 3:
|
||||
self.pending = None
|
||||
return None
|
||||
centre = np.median(matched, axis=0).tolist()
|
||||
previous = self.pending
|
||||
continuous = False
|
||||
if previous is not None:
|
||||
dt = seconds - previous["seconds"]
|
||||
angle = yaw(pose) - yaw(previous["pose"])
|
||||
continuous = (
|
||||
previous["edge_id"] == segment["edge_id"]
|
||||
and 0 < dt <= 0.8
|
||||
and math.dist(pose[:2], previous["pose"][:2]) <= 0.025 * dt
|
||||
and abs(math.atan2(math.sin(angle), math.cos(angle))) <= 0.05 * dt
|
||||
and math.dist(centre, previous["centre"]) <= 0.3
|
||||
)
|
||||
self.pending = {
|
||||
"edge_id": segment["edge_id"],
|
||||
"seconds": seconds,
|
||||
"pose": list(pose),
|
||||
"centre": centre,
|
||||
"started": previous["started"] if continuous else seconds,
|
||||
"frames": previous["frames"] + 1 if continuous else 1,
|
||||
}
|
||||
if self.pending["frames"] < 3 or seconds - self.pending["started"] < 2:
|
||||
return None
|
||||
receipt = {
|
||||
"schema_version": "missioncore.route-blockage/v1",
|
||||
"observation": expected,
|
||||
"edge_id": segment["edge_id"],
|
||||
"reason": "persistent-observed-local-obstacle",
|
||||
"hazards_xyz": matched.tolist(),
|
||||
"stationary_seconds": seconds - self.pending["started"],
|
||||
"fresh_frames": self.pending["frames"],
|
||||
"scope": "episode exclusion; not proof of whole-corridor impassability",
|
||||
}
|
||||
self.pending = None
|
||||
return receipt
|
||||
@@ -0,0 +1,277 @@
|
||||
"""Declared metric corridors, separate from observed terrain and local control.
|
||||
|
||||
The graph grants route intent only. It supplies neither ground support nor
|
||||
obstacle clearance. All routes are pinned to the world and robot input identity.
|
||||
"""
|
||||
|
||||
import copy
|
||||
import heapq
|
||||
import math
|
||||
import re
|
||||
|
||||
from k1link.simulation.ai_polygon.run_inputs import digest, number
|
||||
|
||||
MAP_SCHEMA = "missioncore.route-map/v1"
|
||||
ROUTE_SCHEMA = "missioncore.global-route/v1"
|
||||
|
||||
|
||||
def fields(value, expected):
|
||||
if not isinstance(value, dict) or set(value) != set(expected.split()):
|
||||
raise ValueError("Invalid route contract fields")
|
||||
|
||||
|
||||
def identity(value):
|
||||
if not isinstance(value, str) or not re.fullmatch(r"[a-zA-Z0-9_-]{1,64}", value):
|
||||
raise ValueError("Invalid route identity")
|
||||
return value
|
||||
|
||||
|
||||
def xy(value):
|
||||
if not isinstance(value, list) or len(value) != 2:
|
||||
raise ValueError("Invalid route coordinate")
|
||||
return [number(v, -1e7, 1e7) for v in value]
|
||||
|
||||
|
||||
def validate_routing(routing, world_sha256, goals):
|
||||
fields(routing, "map start_node goal_nodes blocked_edges")
|
||||
graph = routing["map"]
|
||||
fields(graph, "schema_version frame world_sha256 nodes edges no_go sha256")
|
||||
if (
|
||||
graph["schema_version"] != MAP_SCHEMA
|
||||
or graph["frame"] != "world-xy-metres"
|
||||
or not re.fullmatch(r"[a-f0-9]{64}", str(world_sha256))
|
||||
or graph["world_sha256"] != world_sha256
|
||||
or graph["sha256"] != digest({k: v for k, v in graph.items() if k != "sha256"})
|
||||
):
|
||||
raise ValueError("Route map identity or world mismatch")
|
||||
if not isinstance(graph["nodes"], list) or not 1 <= len(graph["nodes"]) <= 2048:
|
||||
raise ValueError("Invalid route node budget")
|
||||
nodes = {}
|
||||
for node in graph["nodes"]:
|
||||
fields(node, "id xy")
|
||||
key = identity(node["id"])
|
||||
if key in nodes:
|
||||
raise ValueError("Duplicate route node")
|
||||
nodes[key] = xy(node["xy"])
|
||||
if not isinstance(graph["edges"], list) or len(graph["edges"]) > 8192:
|
||||
raise ValueError("Invalid route edge budget")
|
||||
edges = set()
|
||||
for edge in graph["edges"]:
|
||||
fields(edge, "id start end half_width_m bidirectional")
|
||||
key = identity(edge["id"])
|
||||
if (
|
||||
key in edges
|
||||
or identity(edge["start"]) not in nodes
|
||||
or identity(edge["end"]) not in nodes
|
||||
or edge["start"] == edge["end"]
|
||||
or type(edge["bidirectional"]) is not bool
|
||||
):
|
||||
raise ValueError("Invalid route edge")
|
||||
edges.add(key)
|
||||
number(edge["half_width_m"], 0.05, 20)
|
||||
if math.dist(nodes[edge["start"]], nodes[edge["end"]]) < 0.05:
|
||||
raise ValueError("Degenerate route edge")
|
||||
if not isinstance(graph["no_go"], list) or len(graph["no_go"]) > 256:
|
||||
raise ValueError("Invalid route no-go budget")
|
||||
for zone in graph["no_go"]:
|
||||
fields(zone, "lower_xy upper_xy")
|
||||
low, high = xy(zone["lower_xy"]), xy(zone["upper_xy"])
|
||||
if any(a >= b for a, b in zip(low, high, strict=True)):
|
||||
raise ValueError("Invalid route no-go rectangle")
|
||||
if identity(routing["start_node"]) not in nodes:
|
||||
raise ValueError("Unknown route start")
|
||||
if (
|
||||
not isinstance(routing["goal_nodes"], list)
|
||||
or not 1 <= len(routing["goal_nodes"]) <= 1000
|
||||
or len(routing["goal_nodes"]) != len(goals)
|
||||
):
|
||||
raise ValueError("Route goals must match mission")
|
||||
previous = routing["start_node"]
|
||||
for key, goal in zip(routing["goal_nodes"], goals, strict=True):
|
||||
if identity(key) not in nodes or nodes[key] != xy(goal):
|
||||
raise ValueError("Route goal does not match mission")
|
||||
if key == previous:
|
||||
raise ValueError("Route leg needs distinct start and goal")
|
||||
previous = key
|
||||
blocked = routing["blocked_edges"]
|
||||
if (
|
||||
not isinstance(blocked, list)
|
||||
or any(identity(key) not in edges for key in blocked)
|
||||
or len(set(blocked)) != len(blocked)
|
||||
):
|
||||
raise ValueError("Invalid blocked route edges")
|
||||
return copy.deepcopy(routing)
|
||||
|
||||
|
||||
def projection(point, start, end):
|
||||
delta = [b - a for a, b in zip(start, end, strict=True)]
|
||||
length = math.hypot(*delta)
|
||||
along = max(
|
||||
0.0,
|
||||
min(length, sum((p - a) * d for p, a, d in zip(point, start, delta, strict=True)) / length),
|
||||
)
|
||||
closest = [a + along * d / length for a, d in zip(start, delta, strict=True)]
|
||||
return along, math.dist(point, closest)
|
||||
|
||||
|
||||
def segment_intersects_box(start, end, low, high):
|
||||
enter, leave = 0.0, 1.0
|
||||
for a, b, lo, hi in zip(start, end, low, high, strict=True):
|
||||
delta = b - a
|
||||
if abs(delta) < 1e-12:
|
||||
if a < lo or a > hi:
|
||||
return False
|
||||
else:
|
||||
t0, t1 = sorted(((lo - a) / delta, (hi - a) / delta))
|
||||
enter, leave = max(enter, t0), min(leave, t1)
|
||||
if enter > leave:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def body_radius(geometry):
|
||||
return math.hypot(geometry["length_m"], geometry["width_m"]) / 2 + 0.05
|
||||
|
||||
|
||||
def build_route(inputs, *, unavailable_edges=(), start_node=None, goal_offset=0):
|
||||
"""Bounded deterministic reference router; not a Nav2 replacement decision."""
|
||||
routing = inputs.get("routing")
|
||||
if routing is None:
|
||||
return None # Existing waypoint episodes retain their declared semantics.
|
||||
graph = routing["map"]
|
||||
routing = validate_routing(routing, graph["world_sha256"], inputs["mission"]["route_xy"])
|
||||
nodes = {n["id"]: n["xy"] for n in graph["nodes"]}
|
||||
unavailable = set(unavailable_edges)
|
||||
if (
|
||||
unavailable - {edge["id"] for edge in graph["edges"]}
|
||||
or (start_node is not None and start_node not in nodes)
|
||||
or type(goal_offset) is not int
|
||||
or not 0 <= goal_offset < len(routing["goal_nodes"])
|
||||
):
|
||||
raise ValueError("Invalid session route exclusion or anchor")
|
||||
radius = body_radius(inputs["robot"]["geometry"])
|
||||
adjacency = {key: [] for key in nodes}
|
||||
rejected = {}
|
||||
for edge in sorted(graph["edges"], key=lambda row: row["id"]):
|
||||
start, end = nodes[edge["start"]], nodes[edge["end"]]
|
||||
reason = None
|
||||
if edge["id"] in routing["blocked_edges"]:
|
||||
reason = "declared-blocked"
|
||||
elif edge["id"] in unavailable:
|
||||
reason = "observed-unavailable"
|
||||
elif edge["half_width_m"] < radius:
|
||||
reason = "insufficient-corridor-width"
|
||||
elif any(
|
||||
segment_intersects_box(
|
||||
start,
|
||||
end,
|
||||
[v - radius for v in zone["lower_xy"]],
|
||||
[v + radius for v in zone["upper_xy"]],
|
||||
)
|
||||
for zone in graph["no_go"]
|
||||
):
|
||||
reason = "declared-no-go"
|
||||
if reason:
|
||||
rejected[edge["id"]] = reason
|
||||
continue
|
||||
adjacency[edge["start"]].append((edge["end"], edge, start, end))
|
||||
if edge["bidirectional"]:
|
||||
adjacency[edge["end"]].append((edge["start"], edge, end, start))
|
||||
legs, start = [], start_node or routing["start_node"]
|
||||
for goal in routing["goal_nodes"][goal_offset:]:
|
||||
distances, previous, heap = {start: 0.0}, {}, [(0.0, start)]
|
||||
while heap:
|
||||
cost, node = heapq.heappop(heap)
|
||||
if cost != distances[node]:
|
||||
continue
|
||||
if node == goal:
|
||||
break
|
||||
for target, edge, a, b in adjacency[node]:
|
||||
candidate = cost + math.dist(a, b)
|
||||
if candidate < distances.get(target, math.inf):
|
||||
distances[target] = candidate
|
||||
previous[target] = (node, edge, a, b)
|
||||
heapq.heappush(heap, (candidate, target))
|
||||
segments = []
|
||||
if goal in distances:
|
||||
cursor = goal
|
||||
while cursor != start:
|
||||
parent, edge, a, b = previous[cursor]
|
||||
segments.append(
|
||||
dict(
|
||||
edge_id=edge["id"], start_xy=a, end_xy=b, half_width_m=edge["half_width_m"]
|
||||
)
|
||||
)
|
||||
cursor = parent
|
||||
segments.reverse()
|
||||
legs.append(
|
||||
dict(
|
||||
start_node=start,
|
||||
goal_node=goal,
|
||||
start_xy=nodes[start],
|
||||
goal_xy=nodes[goal],
|
||||
status="ready" if goal in distances else "unreachable",
|
||||
length_m=distances.get(goal),
|
||||
segments=segments,
|
||||
)
|
||||
)
|
||||
start = goal
|
||||
result = dict(
|
||||
schema_version=ROUTE_SCHEMA,
|
||||
map_sha256=graph["sha256"],
|
||||
inputs_sha256=inputs["sha256"],
|
||||
provider="declared-graph-dijkstra/v1",
|
||||
body_radius_m=radius,
|
||||
no_go=graph["no_go"],
|
||||
legs=legs,
|
||||
rejected_edges=rejected,
|
||||
authority="route-intent-only",
|
||||
)
|
||||
result["sha256"] = digest(result)
|
||||
return result
|
||||
|
||||
|
||||
def disc_permitted(point, radius, segments, no_go):
|
||||
"""A whole enclosing disc must fit one convex corridor capsule.
|
||||
|
||||
Conservative at junctions: no claim that separately safe corners imply a
|
||||
safe body inside a non-convex union. No-go rectangles have independent veto.
|
||||
"""
|
||||
if not any(
|
||||
projection(point, s["start_xy"], s["end_xy"])[1] + radius <= s["half_width_m"]
|
||||
for s in segments
|
||||
):
|
||||
return False
|
||||
return not any(
|
||||
math.hypot(
|
||||
*[
|
||||
max(lo - p, 0, p - hi)
|
||||
for p, lo, hi in zip(point, z["lower_xy"], z["upper_xy"], strict=True)
|
||||
]
|
||||
)
|
||||
<= radius
|
||||
for z in no_go
|
||||
)
|
||||
|
||||
|
||||
def discs_permitted(points, radius, segments, no_go):
|
||||
"""Batch the same full-disc gate before ranking observed local goals."""
|
||||
import numpy as np
|
||||
|
||||
points = np.asarray(points, dtype=float).reshape(-1, 2)
|
||||
if not np.isfinite(points).all() or not math.isfinite(radius) or radius < 0:
|
||||
raise ValueError("Invalid corridor goal candidates")
|
||||
allowed = np.zeros(len(points), dtype=bool)
|
||||
for segment in segments:
|
||||
start, end = np.asarray(segment["start_xy"]), np.asarray(segment["end_xy"])
|
||||
delta = end - start
|
||||
fraction = np.clip((points - start) @ delta / float(delta @ delta), 0, 1)
|
||||
lateral = np.linalg.norm(points - (start + fraction[:, None] * delta), axis=1)
|
||||
allowed |= lateral + radius <= segment["half_width_m"]
|
||||
for zone in no_go:
|
||||
distance = np.maximum(
|
||||
np.maximum(np.asarray(zone["lower_xy"]) - points, 0),
|
||||
points - np.asarray(zone["upper_xy"]),
|
||||
)
|
||||
allowed &= np.linalg.norm(distance, axis=1) > radius
|
||||
return allowed
|
||||
@@ -0,0 +1,547 @@
|
||||
"""Follow a declared route without converting it into a motion permission."""
|
||||
|
||||
import copy
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
from k1link.simulation.ai_polygon.mission_policy import WaypointMission, inclination
|
||||
from k1link.simulation.ai_polygon.route_feedback import ObservedRouteBlockage
|
||||
from k1link.simulation.ai_polygon.route_graph import (
|
||||
build_route,
|
||||
disc_permitted,
|
||||
discs_permitted,
|
||||
projection,
|
||||
)
|
||||
from k1link.simulation.ai_polygon.run_inputs import digest
|
||||
|
||||
|
||||
class RoutedMission(WaypointMission):
|
||||
def __init__(self, inputs):
|
||||
super().__init__(inputs["mission"]["route_xy"])
|
||||
if inputs["sensors"]["schema_version"] in {
|
||||
"missioncore.simulation-sensor-rig/v2",
|
||||
"missioncore.simulation-sensor-rig/v3",
|
||||
"missioncore.simulation-sensor-rig/v4",
|
||||
}:
|
||||
# The mounted rig admits slow, stopped pivots up to 0.15 rad/s. Keep
|
||||
# finite monotonic-heading credit for a half-turn with intermittent
|
||||
# deadman stops; the independent 8 s no-progress checks still run.
|
||||
self.turn_budget_seconds = 90
|
||||
# A measured 0.05 rad improvement is progress for the guarded
|
||||
# guarded pivot mode even with deadman pauses. Count only a new best
|
||||
# heading; neither jitter nor progress extends the total budget.
|
||||
self.heading_progress_radians = 0.05
|
||||
self.global_route = build_route(inputs)
|
||||
# The preparation provider stays immutable across reconnects. Runtime
|
||||
# exclusions and revisions belong to this mission session only.
|
||||
self.inputs = copy.deepcopy(inputs)
|
||||
self.active_route = copy.deepcopy(self.global_route)
|
||||
self.route_revision = 0
|
||||
self.unavailable_edges = set()
|
||||
self.blockage = ObservedRouteBlockage()
|
||||
self.reroute_events = []
|
||||
self.leg_index = -1
|
||||
self.segment_index = 0
|
||||
self.completed_length = 0.0
|
||||
self.remaining = None
|
||||
self.route_target = None
|
||||
self.route_failure = None
|
||||
self.route_last_pose = self.route_last_time = None
|
||||
self.max_speed = inputs["behavior"]["max_speed_mps"]
|
||||
self.last_transition_time = None
|
||||
self.view_maneuver = None
|
||||
self.maneuver_progress = None
|
||||
self.body_approach = None
|
||||
|
||||
@property
|
||||
def leg(self):
|
||||
return self.active_route["legs"][self.index]
|
||||
|
||||
def observe_navigation(self, result, points, pose, seconds):
|
||||
if (
|
||||
self.fault
|
||||
or self.route_failure
|
||||
or self.recovery_goal is not None or self.recovery.active
|
||||
or seconds != self.last_time
|
||||
or tuple(pose) != self.last_pose
|
||||
or not self.leg["segments"]
|
||||
):
|
||||
self.blockage.pending = None
|
||||
return None
|
||||
segment = self.leg["segments"][self.segment_index]
|
||||
receipt = self.blockage.observe(
|
||||
result, points, pose, seconds, self.inputs, segment, self.global_route["body_radius_m"]
|
||||
)
|
||||
if receipt is None:
|
||||
return None
|
||||
self.unavailable_edges.add(segment["edge_id"])
|
||||
event = {
|
||||
"schema_version": "missioncore.route-revision/v1",
|
||||
"revision": self.route_revision + 1,
|
||||
"previous_route_sha256": self.active_route["sha256"],
|
||||
"blockage": receipt,
|
||||
"unavailable_edges": sorted(self.unavailable_edges),
|
||||
"authority": "route-intent-only",
|
||||
}
|
||||
edge = next(
|
||||
e for e in self.inputs["routing"]["map"]["edges"] if e["id"] == segment["edge_id"]
|
||||
)
|
||||
nodes = {n["id"]: n["xy"] for n in self.inputs["routing"]["map"]["nodes"]}
|
||||
anchor = edge["start"] if nodes[edge["start"]] == segment["start_xy"] else edge["end"]
|
||||
failure = (
|
||||
"route-reroute-budget"
|
||||
if self.route_revision >= 3
|
||||
else "route-return-blocked"
|
||||
if segment.get("return_to_anchor")
|
||||
else "route-return-forbidden"
|
||||
if not edge["bidirectional"]
|
||||
else None
|
||||
)
|
||||
candidate = None
|
||||
if failure is None:
|
||||
candidate = build_route(
|
||||
self.inputs,
|
||||
unavailable_edges=self.unavailable_edges,
|
||||
start_node=anchor,
|
||||
goal_offset=self.index,
|
||||
)
|
||||
if candidate["legs"][0]["status"] != "ready":
|
||||
failure = "route-observed-blocked-no-detour"
|
||||
if failure is not None:
|
||||
self.route_failure, self.fault, self.state = failure, "stuck", "stuck"
|
||||
event.update(status="unreachable", failure=failure)
|
||||
else:
|
||||
# Rejoin at the declared start of this edge; never teleport to a
|
||||
# nearby branch. Only this prefix can use the excluded edge, in the
|
||||
# opposite direction away from the measured obstacle. Its ground,
|
||||
# full-body sweep and anchor arrival still require sensor admission.
|
||||
prefix = {
|
||||
**segment,
|
||||
"start_xy": list(segment["end_xy"]),
|
||||
"end_xy": list(segment["start_xy"]),
|
||||
"return_to_anchor": True,
|
||||
}
|
||||
leg = candidate["legs"][0]
|
||||
leg["segments"].insert(0, prefix)
|
||||
leg["length_m"] += math.dist(prefix["start_xy"], prefix["end_xy"])
|
||||
leg["start_xy"] = list(pose[:2])
|
||||
candidate["legs"] = (
|
||||
copy.deepcopy(self.active_route["legs"][: self.index]) + candidate["legs"]
|
||||
)
|
||||
candidate.update(revision=event["revision"], cause_sha256=digest(event))
|
||||
candidate["sha256"] = digest({k: v for k, v in candidate.items() if k != "sha256"})
|
||||
self.active_route = candidate
|
||||
self.route_revision += 1
|
||||
self.segment_index, self.completed_length = 0, 0.0
|
||||
self.anchor = self.goal = self.best_distance = self.recovery_goal = None
|
||||
self.attempts = 0
|
||||
self.failed_goals.clear()
|
||||
self.turn_started = self.turn_goal = self.turn_best_error = None
|
||||
self.last_transition_time = seconds
|
||||
self.state = "replanning"
|
||||
self.route_observation(pose, seconds)
|
||||
event.update(status="ready", active_route=copy.deepcopy(candidate))
|
||||
event["sha256"] = digest(event)
|
||||
self.reroute_events.append(event)
|
||||
return event
|
||||
|
||||
def route_observation(self, pose, seconds):
|
||||
if not math.isfinite(seconds) or not np.isfinite(pose).all():
|
||||
raise ValueError("Invalid route observation")
|
||||
if self.route_last_time is not None:
|
||||
elapsed = seconds - self.route_last_time
|
||||
if elapsed < 0:
|
||||
raise ValueError("Route observations must not rewind")
|
||||
if math.dist(pose[:2], self.route_last_pose[:2]) > self.max_speed * elapsed + 0.2:
|
||||
self.route_failure = "localization-discontinuity"
|
||||
self.route_last_time, self.route_last_pose = seconds, list(pose)
|
||||
if self.index != self.leg_index:
|
||||
self.leg_index, self.segment_index, self.completed_length = self.index, 0, 0.0
|
||||
if math.dist(pose[:2], self.leg["start_xy"]) > 0.4:
|
||||
self.route_failure = "outside-declared-start"
|
||||
if self.leg["status"] != "ready":
|
||||
self.route_failure = "route-unreachable"
|
||||
if self.route_failure:
|
||||
self.fault = "stuck"
|
||||
return
|
||||
segments = self.leg["segments"]
|
||||
if not segments:
|
||||
# The sole goal is the declared start. Still require body admission.
|
||||
self.route_target = self.leg["goal_xy"]
|
||||
self.remaining = math.dist(pose[:2], self.route_target)
|
||||
return
|
||||
segment = segments[self.segment_index]
|
||||
if not disc_permitted(
|
||||
pose[:2],
|
||||
self.global_route["body_radius_m"],
|
||||
self.motion_corridors(),
|
||||
self.global_route["no_go"],
|
||||
):
|
||||
self.route_failure, self.fault = "outside-route-corridor", "stuck"
|
||||
return
|
||||
along, lateral = projection(pose[:2], segment["start_xy"], segment["end_xy"])
|
||||
self.remaining = max(0.0, self.leg["length_m"] - self.completed_length - along) + lateral
|
||||
# Supply a stable segment endpoint. The visual/local planner already
|
||||
# chooses observed intermediate goals within its own lookahead. A second
|
||||
# 0.8m target here sits in the camera blind strip and can make it choose
|
||||
# unrelated farther pixels instead of remembering a visible corner.
|
||||
self.route_target = list(segment["end_xy"])
|
||||
|
||||
def distance_to_target(self, pose, target):
|
||||
return self.remaining
|
||||
|
||||
def orientation_target(self):
|
||||
if self.route_target is None or self.route_failure or self.fault:
|
||||
return None
|
||||
return {
|
||||
"key": self.orientation_key(f"route-{self.index}-{self.segment_index}"
|
||||
+ (f"-revision-{self.route_revision}" if self.route_revision else "")),
|
||||
"xy": list(self.route_target),
|
||||
}
|
||||
|
||||
def observe_maneuver(self, maneuver, pose, seconds):
|
||||
"""A bound observed local placement earns time, never a route receipt."""
|
||||
if maneuver is None:
|
||||
self.view_maneuver = None
|
||||
return
|
||||
expected = {
|
||||
"pose": list(pose),
|
||||
"simulation_time_seconds": seconds,
|
||||
"execution_inputs_sha256": self.inputs["sha256"],
|
||||
}
|
||||
target = self.orientation_target()
|
||||
goal = maneuver.get("goal", [])
|
||||
if (
|
||||
maneuver.get("schema_version") != "missioncore.observed-turn-placement/v1"
|
||||
or maneuver.get("observation") != expected
|
||||
or seconds != self.last_time
|
||||
or tuple(pose) != self.last_pose
|
||||
or target is None
|
||||
or maneuver.get("target_key") != target["key"]
|
||||
or len(goal) != 3
|
||||
or not np.isfinite(goal).all()
|
||||
or not self.goal_permitted(goal)
|
||||
or not maneuver.get("body", {}).get("admitted")
|
||||
or not maneuver.get("initial_pivot", {}).get("admitted")
|
||||
or maneuver.get("phase") not in ("observing", "placing")
|
||||
or maneuver.get("positive_surface_admitted") is not (maneuver["phase"] == "placing")
|
||||
or (
|
||||
maneuver["phase"] == "placing"
|
||||
and not maneuver.get("surface_body", {}).get("admitted")
|
||||
)
|
||||
or not maneuver["started_seconds"] <= seconds <= maneuver["deadline_seconds"]
|
||||
or not math.isclose(
|
||||
maneuver["deadline_seconds"] - maneuver["started_seconds"],
|
||||
60,
|
||||
abs_tol=1e-9,
|
||||
rel_tol=0,
|
||||
)
|
||||
or maneuver.get("attempt") not in (1, 2)
|
||||
):
|
||||
raise ValueError("Invalid observed turn placement")
|
||||
key = (maneuver["target_key"], maneuver["attempt"])
|
||||
if self.maneuver_progress is None or self.maneuver_progress[0] != key:
|
||||
self.maneuver_progress = (key, tuple(goal), math.dist(pose[:2], goal[:2]))
|
||||
elif self.maneuver_progress[1] != tuple(goal):
|
||||
raise ValueError("Turn placement changed within an attempt")
|
||||
self.view_maneuver = copy.deepcopy(maneuver)
|
||||
|
||||
def perception_target(self):
|
||||
if self.view_maneuver is not None:
|
||||
return {
|
||||
"key": self.view_maneuver["target_key"] + "-stage",
|
||||
"xy": self.view_maneuver["goal"][:2],
|
||||
}
|
||||
return self.orientation_target()
|
||||
|
||||
def observe_body_approach(self, goal, pose, seconds, *, admitted, intermediate=False):
|
||||
"""Retain a bound local direction for progress, never motion or arrival.
|
||||
|
||||
The adapter supplies admission only after validating both destination
|
||||
and command sweep against the exact current sensor transaction.
|
||||
"""
|
||||
self.body_approach = None
|
||||
orientation = self.orientation_target()
|
||||
if not admitted:
|
||||
return
|
||||
geometry = self.inputs["robot"]["geometry"]
|
||||
in_region = (
|
||||
(
|
||||
len(goal) == 3
|
||||
and math.dist(goal[:2], pose[:2])
|
||||
<= max(geometry["length_m"], geometry["width_m"]) + 1e-6
|
||||
and 0.4
|
||||
< math.dist(goal[:2], self.arrival_target())
|
||||
< math.dist(pose[:2], self.arrival_target())
|
||||
)
|
||||
if intermediate
|
||||
else len(goal) == 3 and math.dist(goal[:2], self.arrival_target()) <= 0.4
|
||||
)
|
||||
if (
|
||||
orientation is None
|
||||
or seconds != self.last_time
|
||||
or tuple(pose) != self.last_pose
|
||||
or len(goal) != 3
|
||||
or not np.isfinite(goal).all()
|
||||
or not in_region
|
||||
or not disc_permitted(
|
||||
goal[:2],
|
||||
self.global_route["body_radius_m"],
|
||||
self.motion_corridors(),
|
||||
self.global_route["no_go"],
|
||||
)
|
||||
):
|
||||
raise ValueError("Invalid observed body approach")
|
||||
self.body_approach = (orientation["key"], tuple(goal[:2]), seconds)
|
||||
|
||||
def progress_orientation_target(self, seconds):
|
||||
orientation = self.orientation_target()
|
||||
if self.body_approach is not None and orientation is not None:
|
||||
key, goal, captured = self.body_approach
|
||||
if key == orientation["key"] and 0 <= seconds - captured <= 0.8:
|
||||
# Goal changes initialize a new best heading, but the existing
|
||||
# turn_started deadline and recovery count are never reset.
|
||||
return {"key": (key, goal), "xy": goal}
|
||||
return orientation
|
||||
|
||||
def heading_progress(self, pose, seconds):
|
||||
stage = self.view_maneuver
|
||||
if stage is not None and seconds <= stage["deadline_seconds"]:
|
||||
key, goal, best = self.maneuver_progress
|
||||
remaining = math.dist(pose[:2], goal[:2])
|
||||
if best - remaining >= 0.1:
|
||||
self.maneuver_progress = (key, goal, remaining)
|
||||
return True
|
||||
return super().heading_progress(pose, seconds)
|
||||
|
||||
def can_query_arrival(self, pose):
|
||||
return not self.route_failure and self.remaining is not None
|
||||
|
||||
def arrival_target(self):
|
||||
segments = self.leg["segments"]
|
||||
return segments[self.segment_index]["end_xy"] if segments else self.leg["goal_xy"]
|
||||
|
||||
def retain_arrival_query(self, goal):
|
||||
# View acquisition can find an observed path toward the corner before
|
||||
# its full destination footprint is visible. Resume guarded local
|
||||
# traversal even when that local goal is near the corner. The adapter
|
||||
# re-arms body admission whenever the actual pose enters the unchanged
|
||||
# arrival region; this cannot advance a segment without its receipt.
|
||||
return goal is None
|
||||
|
||||
def retire_local_goal(self, target, *, failed=False):
|
||||
# Recovery belongs to the current corner/return anchor. Comparing with
|
||||
# the final task goal discarded a valid corner goal on every retry.
|
||||
super().retire_local_goal(self.route_target, failed=failed)
|
||||
|
||||
def arrival_candidate(self, pose):
|
||||
return (
|
||||
self.can_query_arrival(pose)
|
||||
and not self.fault
|
||||
and math.dist(pose[:2], self.arrival_target()) <= 0.4
|
||||
)
|
||||
|
||||
def confirm_arrival(self, pose, seconds, waypoint, *, admitted):
|
||||
if seconds == self.last_transition_time:
|
||||
return False
|
||||
segments = self.leg["segments"]
|
||||
if self.segment_index == max(0, len(segments) - 1):
|
||||
return super().confirm_arrival(pose, seconds, waypoint, admitted=admitted)
|
||||
if (
|
||||
admitted is not True
|
||||
or seconds != self.last_time
|
||||
or tuple(pose) != self.last_pose
|
||||
or waypoint != self.index
|
||||
or inclination(pose) >= 30
|
||||
or not self.arrival_candidate(pose)
|
||||
or not disc_permitted(
|
||||
pose[:2],
|
||||
self.global_route["body_radius_m"],
|
||||
[segments[self.segment_index + 1]],
|
||||
self.global_route["no_go"],
|
||||
)
|
||||
):
|
||||
return False
|
||||
# A corner is a stopped, observed body placement, not task completion.
|
||||
# Advance one adjacent edge only after the same bound admission receipt
|
||||
# used for task goals; distance alone can never skip a route branch.
|
||||
self.advance_segment(pose, seconds)
|
||||
return True
|
||||
|
||||
def confirm_corridor_transition(self, pose, seconds, body):
|
||||
"""Join adjacent corridors without treating a graph vertex as a task goal.
|
||||
|
||||
A current positive whole-body assessment and containment in BOTH
|
||||
corridors are required. This changes intent only; the adapter fences
|
||||
the old command, and every subsequent turn still needs swept admission.
|
||||
Explicit mission goals and return-to-anchor obligations retain arrival.
|
||||
"""
|
||||
segments = self.leg["segments"]
|
||||
if (
|
||||
self.fault
|
||||
or self.route_failure
|
||||
or self.recovery_goal is not None or self.recovery.active
|
||||
or seconds != self.last_time
|
||||
or tuple(pose) != self.last_pose
|
||||
or seconds == self.last_transition_time
|
||||
or inclination(pose) >= 30
|
||||
or self.segment_index >= len(segments) - 1
|
||||
or segments[self.segment_index].get("return_to_anchor")
|
||||
or math.dist(pose[:2], self.arrival_target()) <= 0.4
|
||||
):
|
||||
return None
|
||||
expected = dict(
|
||||
pose=list(pose),
|
||||
target_xy=self.arrival_target(),
|
||||
simulation_time_seconds=seconds,
|
||||
execution_inputs_sha256=self.inputs["sha256"],
|
||||
)
|
||||
if (
|
||||
body.get("observation") != expected
|
||||
or not all(
|
||||
body.get(k) is True
|
||||
for k in (
|
||||
"admitted",
|
||||
"collision_free",
|
||||
"support_known",
|
||||
"positive_surface_required",
|
||||
)
|
||||
)
|
||||
or type(body.get("support_samples")) is not int
|
||||
or body["support_samples"] <= 0
|
||||
or body["support_samples"] != body.get("supported_samples")
|
||||
):
|
||||
return None
|
||||
adjacent = segments[self.segment_index : self.segment_index + 2]
|
||||
directions = [np.asarray(s["end_xy"]) - s["start_xy"] for s in adjacent]
|
||||
# A reversal is a visit and return, not a corner that can be cut.
|
||||
if np.dot(*directions) <= -0.95 * np.linalg.norm(directions[0]) * np.linalg.norm(
|
||||
directions[1]
|
||||
):
|
||||
return None
|
||||
if not all(
|
||||
disc_permitted(
|
||||
pose[:2], self.global_route["body_radius_m"], [segment], self.global_route["no_go"]
|
||||
)
|
||||
for segment in adjacent
|
||||
):
|
||||
return None
|
||||
receipt = dict(
|
||||
schema_version="missioncore.observed-corridor-transition/v1",
|
||||
authority="adjacent-route-intent-only; not-mission-arrival",
|
||||
active_route_sha256=self.active_route["sha256"],
|
||||
leg=self.index,
|
||||
from_segment=self.segment_index,
|
||||
to_segment=self.segment_index + 1,
|
||||
edge_ids=[s["edge_id"] for s in adjacent],
|
||||
body=copy.deepcopy(body),
|
||||
)
|
||||
receipt["sha256"] = digest(receipt)
|
||||
self.advance_segment(pose, seconds)
|
||||
return receipt
|
||||
|
||||
def advance_segment(self, pose, seconds):
|
||||
segment = self.leg["segments"][self.segment_index]
|
||||
self.completed_length += math.dist(segment["start_xy"], segment["end_xy"])
|
||||
self.segment_index += 1
|
||||
self.last_transition_time = seconds
|
||||
self.anchor = self.goal = self.best_distance = self.recovery_goal = None
|
||||
self.attempts = 0
|
||||
self.turn_started = self.turn_goal = self.turn_best_error = None
|
||||
self.state = "replanning"
|
||||
self.route_observation(pose, seconds)
|
||||
|
||||
def update(self, pose, seconds, choose_goal, choose_recovery=None, *, choose_maneuver=None):
|
||||
self.route_observation(pose, seconds)
|
||||
|
||||
def choose(_target, prior, excluded):
|
||||
candidate = choose_goal(self.route_target, prior, excluded)
|
||||
if candidate is None:
|
||||
return None
|
||||
# Goal intent is restricted to this edge; the local controller's
|
||||
# swept-body veto below independently constrains actual motion.
|
||||
if not self.goal_permitted(candidate):
|
||||
return None
|
||||
return candidate
|
||||
|
||||
result = super().update(pose, seconds, choose, choose_recovery,
|
||||
choose_maneuver=choose_maneuver)
|
||||
if self.fault == "stuck" and self.route_failure is None:
|
||||
self.route_failure = "route-progress-timeout"
|
||||
return None, self.intent("stuck")
|
||||
return result
|
||||
|
||||
def goal_permitted(self, candidate):
|
||||
segments = self.leg["segments"]
|
||||
return not segments or disc_permitted(
|
||||
candidate[:2],
|
||||
self.global_route["body_radius_m"],
|
||||
[segments[self.segment_index]],
|
||||
self.global_route["no_go"],
|
||||
)
|
||||
|
||||
def goals_permitted(self, candidates):
|
||||
points = np.asarray(candidates, dtype=float)
|
||||
segments = self.leg["segments"]
|
||||
return (
|
||||
np.ones(len(points), dtype=bool)
|
||||
if not segments
|
||||
else discs_permitted(
|
||||
points[:, :2],
|
||||
self.global_route["body_radius_m"],
|
||||
[segments[self.segment_index]],
|
||||
self.global_route["no_go"],
|
||||
)
|
||||
)
|
||||
|
||||
def motion_corridors(self):
|
||||
# The motion guard already permits neighbouring declared capsules at
|
||||
# a junction. Apply that same domain to measured body occupancy. A
|
||||
# stopped pivot may still occupy the previous corridor after a corner
|
||||
# receipt; this never advances a segment or admits an off-route goal.
|
||||
segments = self.leg["segments"]
|
||||
return segments[max(0, self.segment_index - 1) : self.segment_index + 2]
|
||||
|
||||
def command_permitted(self, pose, bounds):
|
||||
"""Enclose the existing P2 swept-body bounds; never shrink that envelope."""
|
||||
low = np.array(bounds["lower_xy_m"]) - bounds["discrepancy_xy_m"]
|
||||
high = np.array(bounds["upper_xy_m"]) + bounds["discrepancy_xy_m"]
|
||||
centre = (low + high) / 2
|
||||
radius = float(np.linalg.norm((high - low) / 2))
|
||||
x, y, z, w = pose[3:7]
|
||||
yaw = math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))
|
||||
world = (
|
||||
np.array(pose[:2])
|
||||
+ np.array([[math.cos(yaw), -math.sin(yaw)], [math.sin(yaw), math.cos(yaw)]]) @ centre
|
||||
)
|
||||
return disc_permitted(world, radius, self.motion_corridors(), self.global_route["no_go"])
|
||||
|
||||
def regulate_command(self, pose, monitor, speed, yaw_rate):
|
||||
# A command can be too wide at full rate while its slower counterpart
|
||||
# fits. Recompute the unchanged P2 envelope for each bounded proposal;
|
||||
# never reduce the envelope of a command we actually send. Scaling
|
||||
# both rates keeps curvature and stays inside the original swept bounds
|
||||
# already admitted by the obstacle and observed-support guards.
|
||||
for scale in (1.0, 0.75, 0.5, 0.25):
|
||||
velocity, angular = speed * scale, yaw_rate * scale
|
||||
if self.command_permitted(pose, monitor.command_bounds(velocity, angular)):
|
||||
return velocity, angular, scale
|
||||
return 0.0, 0.0, 0.0
|
||||
|
||||
def intent(self, state):
|
||||
return {
|
||||
**super().intent(state),
|
||||
"global_route_sha256": self.global_route["sha256"],
|
||||
"active_route_sha256": self.active_route["sha256"],
|
||||
"route_revision": self.route_revision,
|
||||
"route_segment": self.segment_index,
|
||||
"route_remaining_m": self.remaining,
|
||||
"route_failure": self.route_failure,
|
||||
}
|
||||
|
||||
|
||||
def mission_for_inputs(inputs):
|
||||
if inputs.get("routing") is not None:
|
||||
return RoutedMission(inputs)
|
||||
return WaypointMission(inputs["mission"]["route_xy"])
|
||||
@@ -0,0 +1,349 @@
|
||||
"""Versioned execution inputs and the explicit legacy world/plan adapter.
|
||||
|
||||
Only the standard library is required before Isaac starts. This is part of the
|
||||
existing run, not another registry or lifecycle. Legacy evidence is never edited.
|
||||
"""
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
|
||||
SCHEMA = "missioncore.simulation-inputs/v2"
|
||||
LEGACY_SCHEMA = "missioncore.simulation-inputs/v1"
|
||||
ROUTED_SCHEMA = "missioncore.simulation-inputs/v3"
|
||||
SENSOR_SCHEMA = "missioncore.simulation-sensor-rig/v1"
|
||||
SOURCE_ADAPTER = "pinhole-resize800x600-crop512/v1"
|
||||
LEGACY_MOUNTED_SENSOR_SCHEMA = "missioncore.simulation-sensor-rig/v2"
|
||||
LEGACY_MOUNTED_SOURCE_ADAPTER = "dual-origin-rectilinear800x600-crop512/v1"
|
||||
MOUNTED_SENSOR_SCHEMA = "missioncore.simulation-sensor-rig/v3"
|
||||
MOUNTED_SOURCE_ADAPTER = "single-lens-quadrants800x600-crop512/v1"
|
||||
CONTINUOUS_SENSOR_SCHEMA = "missioncore.simulation-sensor-rig/v4"
|
||||
CONTINUOUS_SOURCE_ADAPTER = "body-forward-dual-origin800x600-crop512/v1"
|
||||
|
||||
|
||||
def digest(value):
|
||||
return hashlib.sha256(
|
||||
json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
|
||||
).hexdigest()
|
||||
|
||||
|
||||
def number(value, low, high):
|
||||
if type(value) not in (int, float) or not math.isfinite(value) or not low <= value <= high:
|
||||
raise ValueError("Invalid simulation input number")
|
||||
return value
|
||||
|
||||
|
||||
def sensor_rig(robot, camera_height):
|
||||
"""Migrate the installed robot's mount and legacy camera into a named rig.
|
||||
|
||||
The pinned surface servers consume 800x600, crop [100,0,600,600], output 512².
|
||||
Other 4:3 source resolutions use a declared bilinear adapter, never guessed crop.
|
||||
"""
|
||||
physics = robot["physics"]
|
||||
size = robot.get("sensor_image_size", [800, 600])
|
||||
rig = {
|
||||
"schema_version": SENSOR_SCHEMA,
|
||||
"source_adapter": SOURCE_ADAPTER,
|
||||
"image_size": list(size),
|
||||
"provider_image_size": [800, 600],
|
||||
"provider_crop_xywh": [100, 0, 600, 600],
|
||||
"surface_size": [512, 512],
|
||||
"capture_hz": 10,
|
||||
"camera_forward_m": physics["camera_forward_m"],
|
||||
"camera_height_m": camera_height,
|
||||
"camera_pitch_degrees": physics["camera_pitch_degrees"],
|
||||
"focal_length_mm": physics["camera_focal_length_mm"],
|
||||
"horizontal_aperture_mm": physics["camera_horizontal_aperture_mm"],
|
||||
}
|
||||
validate_sensor_rig(rig)
|
||||
return rig
|
||||
|
||||
|
||||
def validate_sensor_rig(rig):
|
||||
if isinstance(rig, dict) and rig.get("schema_version") in {
|
||||
LEGACY_MOUNTED_SENSOR_SCHEMA,
|
||||
MOUNTED_SENSOR_SCHEMA,
|
||||
CONTINUOUS_SENSOR_SCHEMA,
|
||||
}:
|
||||
from .sensor_mounts import validate_mounts
|
||||
|
||||
mounts = validate_mounts(rig.get("mounts"))
|
||||
legacy = {k: v for k, v in rig.items() if k != "mounts"}
|
||||
legacy.update(schema_version=SENSOR_SCHEMA, source_adapter=SOURCE_ADAPTER)
|
||||
validate_sensor_rig(legacy)
|
||||
if (
|
||||
rig["source_adapter"]
|
||||
!= (
|
||||
CONTINUOUS_SOURCE_ADAPTER
|
||||
if rig["schema_version"] == CONTINUOUS_SENSOR_SCHEMA
|
||||
else MOUNTED_SOURCE_ADAPTER
|
||||
if rig["schema_version"] == MOUNTED_SENSOR_SCHEMA
|
||||
else LEGACY_MOUNTED_SOURCE_ADAPTER
|
||||
)
|
||||
or rig["image_size"] != [800, 600]
|
||||
or rig["camera_height_m"] != mounts["insta360"]["body_center_m"][2]
|
||||
):
|
||||
raise ValueError("Invalid mounted camera adapter")
|
||||
return
|
||||
expected = {
|
||||
"schema_version",
|
||||
"source_adapter",
|
||||
"image_size",
|
||||
"provider_image_size",
|
||||
"provider_crop_xywh",
|
||||
"surface_size",
|
||||
"capture_hz",
|
||||
"camera_forward_m",
|
||||
"camera_height_m",
|
||||
"camera_pitch_degrees",
|
||||
"focal_length_mm",
|
||||
"horizontal_aperture_mm",
|
||||
}
|
||||
if not isinstance(rig, dict) or set(rig) != expected:
|
||||
raise ValueError("Invalid sensor rig fields")
|
||||
if rig["schema_version"] != SENSOR_SCHEMA or rig["source_adapter"] != SOURCE_ADAPTER:
|
||||
raise ValueError("Unsupported sensor rig or source adapter")
|
||||
size = rig["image_size"]
|
||||
if (
|
||||
not isinstance(size, list)
|
||||
or len(size) != 2
|
||||
or any(type(v) is not int or not 64 <= v <= 2048 for v in size)
|
||||
):
|
||||
raise ValueError("Invalid source image size")
|
||||
if size[0] * 3 != size[1] * 4:
|
||||
raise ValueError("Installed source adapter requires a 4:3 pinhole camera")
|
||||
if (
|
||||
rig["provider_image_size"] != [800, 600]
|
||||
or rig["provider_crop_xywh"] != [100, 0, 600, 600]
|
||||
or rig["surface_size"] != [512, 512]
|
||||
):
|
||||
raise ValueError("Installed model projection contract changed")
|
||||
for key, bounds in {
|
||||
"capture_hz": (1, 30),
|
||||
"camera_forward_m": (-10, 10),
|
||||
"camera_height_m": (0.1, 10),
|
||||
"camera_pitch_degrees": (-89, 89),
|
||||
"focal_length_mm": (1, 200),
|
||||
"horizontal_aperture_mm": (1, 200),
|
||||
}.items():
|
||||
number(rig[key], *bounds)
|
||||
|
||||
|
||||
def robot_geometry(robot, *, contact=True):
|
||||
keys = (
|
||||
"length_m",
|
||||
"width_m",
|
||||
"height_m",
|
||||
"body_contact_height_m",
|
||||
"max_step_m",
|
||||
"max_slope_degrees",
|
||||
)
|
||||
geometry = {key: robot["physics"][key] for key in keys}
|
||||
for key, value in geometry.items():
|
||||
number(value, 0.001, 89 if key == "max_slope_degrees" else 20)
|
||||
# The installed CMU terrain normalizer still has a qualified 10 cm / 25°
|
||||
# envelope. Different dimensions are supported; different terrain limits
|
||||
# require a provider revision, not a silently ignored RobotProfile field.
|
||||
if geometry["max_step_m"] != 0.1 or geometry["max_slope_degrees"] != 25:
|
||||
raise ValueError("Unsupported CMU terrain envelope")
|
||||
if contact and robot["physics"].get("contact_model") == "tracks":
|
||||
mechanics = robot["mechanics"]
|
||||
shift = number(robot["visual"]["motion"]["shift_m"][0], -20, 20)
|
||||
rollers = mechanics["lower_roller_centres_source_xz_m"]
|
||||
xs = [number(point[0], -20, 20) + shift for point in rollers]
|
||||
width = number(mechanics["track_width_m"], 0.001, 20)
|
||||
separation = number(robot["physics"]["track_width_m"], width, 20)
|
||||
low, high = min(xs), max(xs)
|
||||
if (
|
||||
not low < high
|
||||
or max(abs(low), abs(high)) > geometry["length_m"] / 2
|
||||
or separation + width > geometry["width_m"] + 1e-6
|
||||
or abs(high - low - mechanics["contact_bottom_straight_m"]) > 1e-6
|
||||
or abs(separation - width - mechanics["inner_gap_m"]) > 1e-6
|
||||
):
|
||||
raise ValueError("Inconsistent tracked contact geometry")
|
||||
geometry["ground_contact"] = {
|
||||
"schema_version": "missioncore.ground-contact/v1",
|
||||
"model": "two-track-bottom-bands",
|
||||
"scope": "nominal-flat-ground; no bridging or load-bearing claim",
|
||||
"bands": [
|
||||
{
|
||||
"side": side,
|
||||
"lower_xy_m": [low, sign * separation / 2 - width / 2],
|
||||
"upper_xy_m": [high, sign * separation / 2 + width / 2],
|
||||
}
|
||||
for side, sign in (("left", 1), ("right", -1))
|
||||
],
|
||||
}
|
||||
return geometry
|
||||
|
||||
|
||||
def legacy_run_inputs(run, robot):
|
||||
"""One-way bridge from run/v1, world settings and composition parameters."""
|
||||
settings = run["world"]["settings"]
|
||||
environment = "park"
|
||||
for selected in (run["request"].get("composition") or {}).get("selections", []):
|
||||
if selected["module_id"] == "simulation-waypoint-mission":
|
||||
environment = selected.get("parameters", {}).get("environment", "park")
|
||||
plan = run.get("plan") or {}
|
||||
value = {
|
||||
"schema_version": SCHEMA,
|
||||
"migration": "world-plan-composition/v1",
|
||||
"robot": {
|
||||
"robot_id": robot["robot_id"],
|
||||
"sha256": robot["sha256"],
|
||||
"geometry": robot_geometry(robot),
|
||||
},
|
||||
"sensors": sensor_rig(robot, settings["camera_height_m"]),
|
||||
"mission": {
|
||||
"route_xy": copy.deepcopy(settings.get("route_xy", [])),
|
||||
"arrival_radius_m": 0.4,
|
||||
"plan_sha256": plan.get("sha256"),
|
||||
},
|
||||
"behavior": {"environment": environment, "max_speed_mps": settings["max_speed_mps"]},
|
||||
"localization": {"mode": "simulator-oracle"},
|
||||
}
|
||||
value["sha256"] = digest(value)
|
||||
return validate_run_inputs(value, robot)
|
||||
|
||||
|
||||
def validate_run_inputs(value, robot):
|
||||
expected = {
|
||||
"schema_version",
|
||||
"migration",
|
||||
"robot",
|
||||
"sensors",
|
||||
"mission",
|
||||
"behavior",
|
||||
"localization",
|
||||
"sha256",
|
||||
}
|
||||
if isinstance(value, dict) and value.get("schema_version") == ROUTED_SCHEMA:
|
||||
expected.add("routing")
|
||||
if (
|
||||
not isinstance(value, dict)
|
||||
or set(value) != expected
|
||||
or value["schema_version"] not in {SCHEMA, LEGACY_SCHEMA, ROUTED_SCHEMA}
|
||||
):
|
||||
raise ValueError("Unsupported execution input schema")
|
||||
if value["sha256"] != digest({k: v for k, v in value.items() if k != "sha256"}):
|
||||
raise ValueError("Execution input identity changed")
|
||||
if value["migration"] != "world-plan-composition/v1" or value["localization"] != {
|
||||
"mode": "simulator-oracle"
|
||||
}:
|
||||
raise ValueError("Unsupported input adapter or localization")
|
||||
expected_robot = {
|
||||
"robot_id": robot["robot_id"],
|
||||
"sha256": robot["sha256"],
|
||||
# Old evidence remains v1 with its original hash and full-body audit.
|
||||
# Only newly pinned v2 inputs carry the selected contact geometry.
|
||||
"geometry": robot_geometry(robot, contact=value["schema_version"] != LEGACY_SCHEMA),
|
||||
}
|
||||
if value["robot"] != expected_robot:
|
||||
raise ValueError("Execution robot geometry or identity mismatch")
|
||||
validate_sensor_rig(value["sensors"])
|
||||
version, height = value["sensors"]["schema_version"], value["sensors"]["camera_height_m"]
|
||||
expected_sensors = (
|
||||
mounted_sensor_rig(robot, height, legacy=version == LEGACY_MOUNTED_SENSOR_SCHEMA,
|
||||
continuous=version == CONTINUOUS_SENSOR_SCHEMA)
|
||||
if version in {LEGACY_MOUNTED_SENSOR_SCHEMA, MOUNTED_SENSOR_SCHEMA, CONTINUOUS_SENSOR_SCHEMA}
|
||||
else sensor_rig(robot, height)
|
||||
)
|
||||
if value["sensors"] != expected_sensors:
|
||||
raise ValueError("Sensor rig does not match selected robot")
|
||||
mission, behavior = value["mission"], value["behavior"]
|
||||
if not isinstance(mission, dict) or not isinstance(behavior, dict):
|
||||
raise ValueError("Invalid mission or behavior inputs")
|
||||
if (
|
||||
set(mission) != {"route_xy", "arrival_radius_m", "plan_sha256"}
|
||||
or mission["arrival_radius_m"] != 0.4
|
||||
):
|
||||
raise ValueError("Unsupported mission contract")
|
||||
if mission["plan_sha256"] is not None and not re.fullmatch(
|
||||
r"[a-f0-9]{64}", str(mission["plan_sha256"])
|
||||
):
|
||||
raise ValueError("Invalid mission identity")
|
||||
route = mission["route_xy"]
|
||||
if not isinstance(route, list) or len(route) > 1000:
|
||||
raise ValueError("Invalid mission route")
|
||||
for xy in route:
|
||||
if not isinstance(xy, list) or len(xy) != 2:
|
||||
raise ValueError("Invalid mission waypoint")
|
||||
for v in xy:
|
||||
number(v, -1e7, 1e7)
|
||||
if set(behavior) != {"environment", "max_speed_mps"} or behavior["environment"] not in {
|
||||
"park",
|
||||
"urban",
|
||||
"natural",
|
||||
}:
|
||||
raise ValueError("Unsupported behavior profile")
|
||||
number(behavior["max_speed_mps"], 0.05, robot["control"]["max_side_speed_mps"])
|
||||
if value["schema_version"] == ROUTED_SCHEMA:
|
||||
from k1link.simulation.ai_polygon.route_graph import validate_routing
|
||||
|
||||
validate_routing(value["routing"], value["routing"]["map"]["world_sha256"], route)
|
||||
return copy.deepcopy(value)
|
||||
|
||||
|
||||
def mounted_sensor_rig(robot, camera_height, *, legacy=False, continuous=False):
|
||||
from .sensor_mounts import rover_mounts
|
||||
|
||||
if robot["robot_id"] != "dcd006-v020":
|
||||
raise ValueError("Mounted sensors require the Rover 006 body")
|
||||
rig = sensor_rig(robot, camera_height)
|
||||
rig.update(
|
||||
schema_version=LEGACY_MOUNTED_SENSOR_SCHEMA if legacy else MOUNTED_SENSOR_SCHEMA,
|
||||
source_adapter=LEGACY_MOUNTED_SOURCE_ADAPTER if legacy else MOUNTED_SOURCE_ADAPTER,
|
||||
image_size=[800, 600],
|
||||
camera_forward_m=0.665,
|
||||
camera_pitch_degrees=-30.0,
|
||||
focal_length_mm=13.0,
|
||||
mounts=rover_mounts(camera_height),
|
||||
)
|
||||
if continuous:
|
||||
if legacy:
|
||||
raise ValueError("Conflicting camera generations")
|
||||
rig.update(schema_version=CONTINUOUS_SENSOR_SCHEMA,
|
||||
source_adapter=CONTINUOUS_SOURCE_ADAPTER)
|
||||
validate_sensor_rig(rig)
|
||||
return rig
|
||||
|
||||
|
||||
def mounted_run_inputs(value, robot, camera_height=0.8, *, legacy=False, continuous=False):
|
||||
"""Select the rover's mounting profile, independent of a world's old camera.
|
||||
|
||||
Legacy world camera settings describe its former virtual pinhole. They
|
||||
cannot position a physical sensor body below the rover's mounting panel.
|
||||
"""
|
||||
result = validate_run_inputs(value, robot)
|
||||
result["sensors"] = mounted_sensor_rig(robot, camera_height, legacy=legacy,
|
||||
continuous=continuous)
|
||||
result["sha256"] = digest({k: v for k, v in result.items() if k != "sha256"})
|
||||
return validate_run_inputs(result, robot)
|
||||
|
||||
|
||||
def resolve_run_inputs(run, robot):
|
||||
value = run.get("execution_inputs")
|
||||
if value is None:
|
||||
return legacy_run_inputs(run, robot)
|
||||
result = validate_run_inputs(value, robot)
|
||||
if result["mission"]["plan_sha256"] != (run.get("plan") or {}).get("sha256"):
|
||||
raise ValueError("Execution mission identity mismatch")
|
||||
if result.get("routing") is not None:
|
||||
from k1link.simulation.ai_polygon.route_graph import validate_routing
|
||||
|
||||
validate_routing(result["routing"], run["world"]["sha256"], result["mission"]["route_xy"])
|
||||
return result
|
||||
|
||||
|
||||
def declared_route_inputs(value, routing, robot, world_sha256):
|
||||
"""Explicit engineering opt-in; legacy episodes are never silently routed."""
|
||||
from k1link.simulation.ai_polygon.route_graph import validate_routing
|
||||
|
||||
result = validate_run_inputs(value, robot)
|
||||
result["routing"] = validate_routing(routing, world_sha256, result["mission"]["route_xy"])
|
||||
result["schema_version"] = ROUTED_SCHEMA
|
||||
result["sha256"] = digest({k: v for k, v in result.items() if k != "sha256"})
|
||||
return validate_run_inputs(result, robot)
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Resolve reproducible run variants without changing installed robot profiles."""
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
|
||||
from .robots import select_robot
|
||||
|
||||
|
||||
def digest(value):
|
||||
return hashlib.sha256(
|
||||
json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
|
||||
).hexdigest()
|
||||
|
||||
|
||||
def validated_settings(raw):
|
||||
"""Dependency-free boundary also used by Isaac's bundled Python."""
|
||||
fields = {
|
||||
"max_speed_mps": (0.05, 1 if raw.get("schema_version", "missioncore.rover-settings/v1") == "missioncore.rover-settings/v1" else math.inf),
|
||||
"base_mass_kg": (10, 1000),
|
||||
"payload_mass_kg": (0, 500),
|
||||
"payload_height_m": (0.1, 3),
|
||||
}
|
||||
value = {"schema_version": "missioncore.rover-settings/v1", "payload_mass_kg": 0, **raw}
|
||||
if (
|
||||
set(value) != {"schema_version", *fields}
|
||||
or value["schema_version"] not in {"missioncore.rover-settings/v1", "missioncore.rover-settings/v2"}
|
||||
):
|
||||
raise ValueError("Invalid rover settings schema")
|
||||
for key, (low, high) in fields.items():
|
||||
number = value[key]
|
||||
if (
|
||||
type(number) not in (int, float)
|
||||
or not math.isfinite(number)
|
||||
or not low <= number <= high
|
||||
):
|
||||
raise ValueError("Invalid rover setting: " + key)
|
||||
value[key] = float(number)
|
||||
return value
|
||||
|
||||
|
||||
def configure_robot(base, raw_settings):
|
||||
"""Centered point payload; base inertia scales at unchanged geometry.
|
||||
|
||||
Payload location changes COM and inertia by the parallel-axis theorem.
|
||||
This approximation does not invent payload dimensions or extra collisions.
|
||||
Motor torque, power, friction and controller gains retain their base values.
|
||||
"""
|
||||
settings = validated_settings(raw_settings)
|
||||
if settings["schema_version"].endswith("/v1") and settings["max_speed_mps"] > base["control"]["max_side_speed_mps"]:
|
||||
raise ValueError("Скорость превышает предел привода выбранного ровера.")
|
||||
if base["physics"].get("contact_model") != "tracks":
|
||||
raise ValueError("Этот профиль ещё не поддерживает настройку нагрузки.")
|
||||
robot = copy.deepcopy(base)
|
||||
robot.pop("sha256", None)
|
||||
if settings["schema_version"] == "missioncore.rover-settings/v2":
|
||||
# The base profile's .3 m/s was a laboratory command ceiling, not a
|
||||
# measured motor limit. Only this run's simulated drive envelope changes.
|
||||
# Keep v1 resolution byte-identical for archived evidence and its hashes.
|
||||
robot["control"]["max_side_speed_mps"] = max(
|
||||
base["control"]["max_side_speed_mps"], settings["max_speed_mps"]
|
||||
)
|
||||
physics, contact = robot["physics"], robot["tracked_contact"]
|
||||
mass, payload = settings["base_mass_kg"], settings["payload_mass_kg"]
|
||||
total = mass + payload
|
||||
base_height = contact["chassis_com_height_m"]
|
||||
height = (mass * base_height + payload * settings["payload_height_m"]) / total
|
||||
inertia = [v * mass / physics["mass_kg"] for v in contact["chassis_inertia_kg_m2"]]
|
||||
offset = (
|
||||
mass * (base_height - height) ** 2 + payload * (settings["payload_height_m"] - height) ** 2
|
||||
)
|
||||
inertia[0] += offset
|
||||
inertia[1] += offset
|
||||
physics["mass_kg"] = total
|
||||
contact["chassis_com_height_m"] = height
|
||||
contact["chassis_inertia_kg_m2"] = inertia
|
||||
configuration = {
|
||||
"schema_version": "missioncore.run-rover-configuration/v1",
|
||||
"base_robot_sha256": base["sha256"],
|
||||
"settings": settings,
|
||||
"load_model": "centered-point-payload; base-inertia-scaled-with-mass",
|
||||
"total_mass_kg": total,
|
||||
"effective_robot_sha256": digest(robot),
|
||||
}
|
||||
configuration["sha256"] = digest(configuration)
|
||||
return {**robot, "sha256": configuration["effective_robot_sha256"]}, configuration
|
||||
|
||||
|
||||
def resolve_run_robot(run, *, adapters=None):
|
||||
identity = run["robot"]
|
||||
kwargs = {} if adapters is None else {"adapters": adapters}
|
||||
base = select_robot(identity["robot_id"], identity["sha256"], **kwargs)
|
||||
raw = run["request"].get("rover_settings")
|
||||
pinned = run.get("rover_configuration")
|
||||
if raw is None:
|
||||
if pinned is not None:
|
||||
raise ValueError("Unexpected rover configuration")
|
||||
return base
|
||||
settings = validated_settings(raw)
|
||||
robot, expected = configure_robot(base, settings)
|
||||
if pinned != expected or run["world"]["settings"]["max_speed_mps"] != settings["max_speed_mps"]:
|
||||
raise ValueError("Run rover configuration mismatch")
|
||||
return robot
|
||||
@@ -23,8 +23,21 @@ from k1link.simulation.ai_polygon.contracts import (
|
||||
RunApplied,
|
||||
RunCreate,
|
||||
RunSample,
|
||||
SimulationReport,
|
||||
WorkerHello,
|
||||
)
|
||||
from k1link.simulation.ai_polygon.library import LibraryMetadata
|
||||
from k1link.simulation.ai_polygon.plans import PlanStore
|
||||
from k1link.simulation.ai_polygon.robots import select_robot
|
||||
from k1link.simulation.ai_polygon.run_inputs import (
|
||||
CONTINUOUS_SENSOR_SCHEMA,
|
||||
LEGACY_MOUNTED_SENSOR_SCHEMA,
|
||||
MOUNTED_SENSOR_SCHEMA,
|
||||
legacy_run_inputs,
|
||||
mounted_run_inputs,
|
||||
)
|
||||
from k1link.simulation.ai_polygon.run_inputs import SCHEMA as INPUTS_SCHEMA
|
||||
from k1link.simulation.ai_polygon.run_robot import configure_robot
|
||||
from k1link.simulation.ai_polygon.worlds import WorldStore, write_json
|
||||
|
||||
RUN_ID = re.compile(r"^airun-[a-f0-9]{32}$")
|
||||
@@ -38,10 +51,14 @@ class RunStore:
|
||||
self.queue = queue
|
||||
self.root = worlds.root.parent / "runs"
|
||||
self.root.mkdir(mode=0o700, exist_ok=True)
|
||||
self.library = LibraryMetadata(self.root / "library")
|
||||
self.plans = PlanStore(worlds.root.parent / "plans")
|
||||
self.lock = threading.RLock()
|
||||
self.preview = None
|
||||
self.worker: dict | None = None
|
||||
self.seen = 0.0
|
||||
self.active: str | None = None
|
||||
self.incomplete_run_ids: set[str] = set()
|
||||
self.token_path = self.root.parent / "worker.token"
|
||||
if not self.token_path.exists():
|
||||
try:
|
||||
@@ -82,12 +99,21 @@ class RunStore:
|
||||
return json.loads((self.directory(run_id) / "run.json").read_text())
|
||||
|
||||
def list(self) -> list[dict]:
|
||||
rows = []
|
||||
incomplete = set()
|
||||
for path in self.root.iterdir():
|
||||
if not RUN_ID.fullmatch(path.name) or not path.is_dir() or path.is_symlink():
|
||||
continue
|
||||
# Old admission could crash after mkdir but before run.json. Preserve
|
||||
# that directory and any reservation; an absent record is not release
|
||||
# evidence. New admissions publish only a complete directory.
|
||||
if not (path / "run.json").exists():
|
||||
incomplete.add(path.name)
|
||||
continue
|
||||
rows.append(self.get(path.name))
|
||||
self.incomplete_run_ids = incomplete
|
||||
return sorted(
|
||||
[
|
||||
self.get(p.name)
|
||||
for p in self.root.iterdir()
|
||||
if RUN_ID.fullmatch(p.name) and p.is_dir() and not p.is_symlink()
|
||||
],
|
||||
rows,
|
||||
key=lambda item: item["created_at"],
|
||||
reverse=True,
|
||||
)
|
||||
@@ -95,19 +121,62 @@ class RunStore:
|
||||
def _save(self, doc: dict) -> None:
|
||||
write_json(self.directory(doc["run_id"]) / "run.json", doc)
|
||||
|
||||
def _publish(self, doc: dict) -> None:
|
||||
"""Publish a fully validated admission in one same-filesystem rename."""
|
||||
staging = self.root / f".pending-{doc['run_id']}-{uuid4().hex}"
|
||||
staging.mkdir(mode=0o700)
|
||||
try:
|
||||
if doc["clock"] == "lockstep":
|
||||
(staging / "frames").mkdir(mode=0o700)
|
||||
write_json(staging / "run.json", doc)
|
||||
staging.rename(self.root / doc["run_id"])
|
||||
finally:
|
||||
if staging.exists():
|
||||
# Only this unpublished directory is owned by this attempt.
|
||||
shutil.rmtree(staging)
|
||||
|
||||
def _release_finished(self, row: dict) -> None:
|
||||
run_id = row["run_id"]
|
||||
# A delayed duplicate receipt must not release a subsequent owner's GPU.
|
||||
if self.active not in (None, run_id):
|
||||
return
|
||||
if not row.get("resources_released"):
|
||||
if self.queue is not None:
|
||||
self.queue.release_simulation(run_id)
|
||||
row["resources_released"] = True
|
||||
self._save(row)
|
||||
if self.active == run_id:
|
||||
self.active = None
|
||||
|
||||
def update_library(self, kind, identity, changes):
|
||||
with self.lock:
|
||||
store = self.plans if kind == "plans" else self
|
||||
row = store.get(identity)
|
||||
if (
|
||||
kind == "runs"
|
||||
and changes.get("removed")
|
||||
and (row["state"] not in TERMINAL or self.active == identity)
|
||||
):
|
||||
raise RuntimeError("Сначала завершите прогон и дождитесь освобождения симулятора.")
|
||||
return {**row, **store.library.update(identity, changes)}
|
||||
|
||||
def _expire(self) -> None:
|
||||
if self.worker is not None and time.monotonic() - self.seen > WORKER_LEASE_SECONDS:
|
||||
if self.active:
|
||||
row = self.get(self.active)
|
||||
if row.get("clock") == "realtime":
|
||||
row.update(
|
||||
state="disconnected",
|
||||
message="Связь с Worker потеряна. Состояние уточняется.",
|
||||
)
|
||||
else:
|
||||
row.update(state="failed", message="Worker потерял связь. Прогон остановлен.")
|
||||
self.active = None
|
||||
self._save(row)
|
||||
# A terminal outcome can still be waiting for a release retry.
|
||||
# Lease loss changes worker availability, not sealed run history;
|
||||
# reopening it would make poll issue the finished episode again.
|
||||
if row["state"] not in TERMINAL:
|
||||
if row.get("clock") == "realtime":
|
||||
row.update(
|
||||
state="disconnected",
|
||||
message="Связь с Worker потеряна. Состояние уточняется.",
|
||||
)
|
||||
else:
|
||||
row.update(state="failed", message="Worker потерял связь. Прогон остановлен.")
|
||||
self.active = None
|
||||
self._save(row)
|
||||
self.worker = None
|
||||
|
||||
def status(self) -> dict:
|
||||
@@ -141,7 +210,9 @@ class RunStore:
|
||||
if self.worker is None or self.worker["instance_id"] != instance_id:
|
||||
raise RuntimeError("Сессия Worker истекла; требуется переподключение.")
|
||||
|
||||
def start(self, request: RunCreate, request_id: str) -> dict:
|
||||
def start(
|
||||
self, request: RunCreate, request_id: str, *, composition_sha256: str | None = None
|
||||
) -> dict:
|
||||
if not re.fullmatch(r"[a-zA-Z0-9_-]{8,100}", request_id):
|
||||
raise ValueError("Требуется уникальный идентификатор запуска.")
|
||||
with self.lock:
|
||||
@@ -157,11 +228,23 @@ class RunStore:
|
||||
raise RuntimeError("Worker не поддерживает этот режим симуляции.")
|
||||
if request.clock == "realtime" and not self.worker.get("stream"):
|
||||
raise RuntimeError("Видеопоток Worker не настроен.")
|
||||
if request.purpose == "planning" and (
|
||||
request.clock != "realtime" or not request.start_paused
|
||||
):
|
||||
raise ValueError("Планирование требует остановленной realtime-сцены.")
|
||||
if self.queue is None:
|
||||
raise RuntimeError("Контроль занятости Worker недоступен.")
|
||||
if self.active is not None:
|
||||
raise RuntimeError("Сначала завершите текущий прогон.")
|
||||
world = self.worlds.get(request.world_id)
|
||||
if world.get("inference_ready") is False:
|
||||
raise RuntimeError(world["inference_message"])
|
||||
if world.get("local_scene") and "project-sog" not in self.worker.get(
|
||||
"scene_formats", []
|
||||
):
|
||||
raise RuntimeError(
|
||||
"Worker ещё не поддерживает SOG-проекты. Требуется обновление симулятора."
|
||||
)
|
||||
storage = world.get("storage", {})
|
||||
if storage.get("kind") == "worker" and (
|
||||
storage["worker_id"] != self.worker["worker_id"] or request.clock != "realtime"
|
||||
@@ -172,19 +255,76 @@ class RunStore:
|
||||
run_id = f"airun-{uuid4().hex}"
|
||||
if (
|
||||
request.clock == "lockstep"
|
||||
and shutil.disk_usage(self.root).free < request.max_steps * 1024**2 + 512 * 1024**2
|
||||
and shutil.disk_usage(self.root).free < 513 * 1024**2
|
||||
):
|
||||
raise ValueError("Недостаточно места для кадров прогона.")
|
||||
(self.root / run_id).mkdir(mode=0o700)
|
||||
if request.clock == "lockstep":
|
||||
(self.root / run_id / "frames").mkdir(mode=0o700)
|
||||
robot = (
|
||||
select_robot(request.robot_id, request.robot_sha256)
|
||||
if request.clock == "realtime"
|
||||
else None
|
||||
)
|
||||
if (
|
||||
robot
|
||||
and self.worker.get("robots")
|
||||
and (self.worker["robots"].get(robot["robot_id"]) != robot["sha256"])
|
||||
):
|
||||
raise RuntimeError(
|
||||
"Профиль ровера на Worker ещё обновляется. Повторите запуск позже."
|
||||
)
|
||||
plan = self.plans.get(request.plan_id) if request.plan_id else None
|
||||
if plan and self.plans.library.get(plan["plan_id"]).get("removed"):
|
||||
raise ValueError("Задание удалено из списка. Выберите другое задание.")
|
||||
if world.get("local_scene") and (not plan or request.clock != "realtime"):
|
||||
raise ValueError("Для SOG-локации сначала сохраните маршрут задания.")
|
||||
if plan:
|
||||
if not robot or any(
|
||||
[
|
||||
plan["world_id"] != world["world_id"],
|
||||
plan["world_sha256"] != world["sha256"],
|
||||
plan.get("collider_sha256") != world.get("collider_sha256"),
|
||||
plan["robot_id"] != robot["robot_id"],
|
||||
plan["robot_sha256"] != robot["sha256"],
|
||||
]
|
||||
):
|
||||
raise ValueError("Задание не соответствует локации или выбранному роверу.")
|
||||
world = {**world, "settings": plan["settings"]}
|
||||
effective_robot = robot
|
||||
rover_configuration = None
|
||||
if request.rover_settings is not None:
|
||||
if request.rover_settings.schema_version not in self.worker.get(
|
||||
"rover_settings_versions", []
|
||||
):
|
||||
raise RuntimeError(
|
||||
"Подключённый симулятор ещё не поддерживает настройки ровера."
|
||||
)
|
||||
effective_robot, rover_configuration = configure_robot(
|
||||
robot, request.rover_settings.model_dump(mode="json")
|
||||
)
|
||||
world = {
|
||||
**world,
|
||||
"settings": {
|
||||
**world["settings"],
|
||||
"max_speed_mps": request.rover_settings.max_speed_mps,
|
||||
},
|
||||
}
|
||||
row = {
|
||||
"schema_version": "missioncore.ai-polygon-run/v1",
|
||||
"run_id": run_id,
|
||||
"request_id": request_id,
|
||||
"request": request.model_dump(),
|
||||
"composition_sha256": composition_sha256,
|
||||
"created_at": utc_now_iso(),
|
||||
"world": world,
|
||||
"robot": robot,
|
||||
"rover_configuration": rover_configuration,
|
||||
"plan": plan,
|
||||
"plan_display_name": (
|
||||
self.plans.library.get(plan["plan_id"]).get("display_name", plan["name"])
|
||||
if plan
|
||||
else None
|
||||
),
|
||||
"planning_commands": [],
|
||||
"planning_sequence": 0,
|
||||
"worker": dict(self.worker),
|
||||
"state": "starting",
|
||||
"control": "pause" if request.start_paused else "play",
|
||||
@@ -202,7 +342,21 @@ class RunStore:
|
||||
"clock": request.clock,
|
||||
"step_ns": 100_000_000,
|
||||
}
|
||||
self._save(row)
|
||||
if robot and INPUTS_SCHEMA in self.worker.get("execution_inputs_versions", []):
|
||||
row["execution_inputs"] = legacy_run_inputs(row, effective_robot)
|
||||
versions = self.worker.get("sensor_rig_versions", [])
|
||||
if request.clock == "realtime" and any(
|
||||
v in versions for v in (CONTINUOUS_SENSOR_SCHEMA, MOUNTED_SENSOR_SCHEMA,
|
||||
LEGACY_MOUNTED_SENSOR_SCHEMA)
|
||||
):
|
||||
row["execution_inputs"] = mounted_run_inputs(
|
||||
row["execution_inputs"],
|
||||
effective_robot,
|
||||
legacy=not any(v in versions for v in (MOUNTED_SENSOR_SCHEMA,
|
||||
CONTINUOUS_SENSOR_SCHEMA)),
|
||||
continuous=CONTINUOUS_SENSOR_SCHEMA in versions,
|
||||
)
|
||||
self._publish(row)
|
||||
try:
|
||||
self.queue.reserve_simulation(run_id)
|
||||
except RuntimeError:
|
||||
@@ -220,6 +374,8 @@ class RunStore:
|
||||
return row
|
||||
if command not in {"pause", "play", "step", "stop"}:
|
||||
raise ValueError("Неизвестная команда симуляции.")
|
||||
if row["request"].get("purpose") == "planning" and command in {"play", "step"}:
|
||||
raise RuntimeError("Сохраните задание и завершите планирование перед запуском AI.")
|
||||
if command == "step" and row.get("clock") == "realtime":
|
||||
raise RuntimeError("Realtime не допускает пошаговое продвижение времени.")
|
||||
if command == "step" and row["state"] != "paused":
|
||||
@@ -244,6 +400,10 @@ class RunStore:
|
||||
if self.active is None:
|
||||
return {"run": None, "action": "idle"}
|
||||
row = self.get(self.active)
|
||||
if row["state"] in TERMINAL:
|
||||
# A release receipt may be awaiting retry. Never reload an
|
||||
# already finished episode and never infer resource release.
|
||||
return {"run": None, "action": "idle"}
|
||||
if run_id is None:
|
||||
return {"run": row, "action": "load"}
|
||||
if run_id != self.active:
|
||||
@@ -251,7 +411,21 @@ class RunStore:
|
||||
action = row["control"]
|
||||
if row.get("clock") == "realtime":
|
||||
# Only actual local snapshots can acknowledge pause/play.
|
||||
return {"run": row, "action": action}
|
||||
# The live camera channel carries controls, not repeated scene,
|
||||
# model descriptors, archived samples or rendered telemetry.
|
||||
control = {
|
||||
key: row.get(key)
|
||||
for key in (
|
||||
"run_id",
|
||||
"state",
|
||||
"control",
|
||||
"control_sequence",
|
||||
"camera",
|
||||
"observer_input",
|
||||
"planning_commands",
|
||||
)
|
||||
}
|
||||
return {"run": control, "action": action}
|
||||
if action == "pause":
|
||||
if row["step_budget"]:
|
||||
row["step_budget"] = 0
|
||||
@@ -274,17 +448,91 @@ class RunStore:
|
||||
self._save(row)
|
||||
return {"control": row["control"]}
|
||||
|
||||
def view(self, run_id: str, camera: str) -> dict:
|
||||
def inference_preview(self, run_id, instance_id=None, preview=None):
|
||||
with self.lock:
|
||||
row = self.get(run_id)
|
||||
if preview is not None:
|
||||
self._require_worker(instance_id)
|
||||
if self.active != run_id or row["state"] in TERMINAL:
|
||||
raise RuntimeError("Симуляция не запущена.")
|
||||
if (
|
||||
self.preview
|
||||
and self.preview[0] == run_id
|
||||
and self.preview[1]["frame_id"] >= preview.frame_id
|
||||
):
|
||||
return {"accepted": False}
|
||||
# Validate the bounded raster before forwarding data to browsers.
|
||||
for layer in preview.layers:
|
||||
if layer.kind != "image":
|
||||
continue
|
||||
raw = base64.b64decode(layer.jpeg, validate=True)
|
||||
with Image.open(io.BytesIO(raw)) as image:
|
||||
if image.format != "JPEG" or image.size != (layer.image_size or (400, 300)):
|
||||
raise ValueError("Invalid inference preview raster")
|
||||
image.verify()
|
||||
self.preview = (run_id, {**preview.model_dump(), "received_at": utc_now_iso()})
|
||||
return {"accepted": True}
|
||||
return self.preview[1] if self.preview and self.preview[0] == run_id else None
|
||||
|
||||
def view(self, run_id: str, camera: str, navigation=None) -> dict:
|
||||
with self.lock:
|
||||
row = self.get(run_id)
|
||||
if run_id != self.active or row.get("clock") != "realtime":
|
||||
raise RuntimeError("Симуляция не запущена.")
|
||||
if camera not in {"follow", "overview", "camera"}:
|
||||
raise ValueError("Неизвестная камера.")
|
||||
if navigation is not None:
|
||||
if row["camera"] != camera:
|
||||
raise RuntimeError("Режим камеры уже изменён.")
|
||||
previous = row.get("observer_input") or {}
|
||||
if (
|
||||
previous.get("session") == navigation.session
|
||||
and previous.get("sequence", -1) >= navigation.sequence
|
||||
):
|
||||
return row
|
||||
row["observer_input"] = navigation.model_dump()
|
||||
elif row["camera"] != camera:
|
||||
row["observer_input"] = None
|
||||
row["camera"] = camera
|
||||
self._save(row)
|
||||
return row
|
||||
|
||||
def planning_command(self, run_id, command):
|
||||
with self.lock:
|
||||
row = self.get(run_id)
|
||||
if self.active != run_id or row["request"].get("purpose") != "planning":
|
||||
raise RuntimeError("Редактирование доступно только в режиме планирования.")
|
||||
if row["control"] == "stop":
|
||||
raise RuntimeError("Планирование завершается.")
|
||||
commands = row["planning_commands"]
|
||||
if any(c["request_id"] == command.request_id for c in commands):
|
||||
return row
|
||||
ack = ((row.get("telemetry") or {}).get("planning") or {}).get("sequence", 0)
|
||||
if len([c for c in commands if c["sequence"] > ack]) >= 32:
|
||||
raise RuntimeError("Дождитесь обработки действий Worker.")
|
||||
row["planning_sequence"] += 1
|
||||
row["planning_commands"] = commands[-31:] + [
|
||||
{**command.model_dump(), "sequence": row["planning_sequence"]}
|
||||
]
|
||||
self._save(row)
|
||||
return row
|
||||
|
||||
def save_plan(self, run_id, request):
|
||||
with self.lock:
|
||||
row = self.get(run_id)
|
||||
if self.active != run_id or row["request"].get("purpose") != "planning":
|
||||
raise RuntimeError("Откройте планирование для сохранения задания.")
|
||||
if row["control"] == "stop":
|
||||
raise RuntimeError("Планирование завершается.")
|
||||
draft = (row.get("telemetry") or {}).get("planning")
|
||||
if (
|
||||
not draft
|
||||
or draft["sequence"] != request.sequence
|
||||
or (row["planning_sequence"] != request.sequence)
|
||||
):
|
||||
raise RuntimeError("Дождитесь подтверждения изменений Worker.")
|
||||
return self.plans.create(row, request.name, draft["points"], request.sequence)
|
||||
|
||||
def snapshot(self, run_id: str, instance_id: str, snapshot: RealtimeSnapshot) -> dict:
|
||||
with self.lock:
|
||||
self._require_worker(instance_id)
|
||||
@@ -327,7 +575,7 @@ class RunStore:
|
||||
raise RuntimeError("Realtime кадры хранятся только на Worker.")
|
||||
if row["control"] == "stop":
|
||||
raise RuntimeError("Получена команда остановки.")
|
||||
if sample.sequence != row["samples"] or sample.sequence >= row["request"]["max_steps"]:
|
||||
if sample.sequence != row["samples"]:
|
||||
raise RuntimeError("Нарушена последовательность кадров.")
|
||||
if row["samples"] != row["applied_steps"]:
|
||||
raise RuntimeError("Предыдущий шаг физики не подтверждён.")
|
||||
@@ -383,15 +631,47 @@ class RunStore:
|
||||
self._save(row)
|
||||
return {"applied": receipt.sequence}
|
||||
|
||||
def finish(self, run_id: str, instance_id: str, outcome: str, message: str) -> dict:
|
||||
def finish(
|
||||
self,
|
||||
run_id: str,
|
||||
instance_id: str,
|
||||
outcome: str,
|
||||
message: str,
|
||||
report: SimulationReport | None = None,
|
||||
) -> dict:
|
||||
with self.lock:
|
||||
self._require_worker(instance_id)
|
||||
row = self.get(run_id)
|
||||
if row["worker"]["instance_id"] != instance_id:
|
||||
raise RuntimeError("Прогон принадлежит другому Worker.")
|
||||
if report is not None:
|
||||
expected_composition = row.get("composition_sha256")
|
||||
if (
|
||||
report.run_id != run_id
|
||||
or report.world_sha256 != row["world"]["sha256"]
|
||||
or report.robot_sha256 != (row.get("robot") or {}).get("sha256")
|
||||
or report.execution_inputs_sha256
|
||||
!= (row.get("execution_inputs") or {}).get("sha256")
|
||||
or report.rover_configuration_sha256
|
||||
!= (row.get("rover_configuration") or {}).get("sha256")
|
||||
or report.effective_robot_sha256
|
||||
!= (row.get("rover_configuration") or {}).get("effective_robot_sha256")
|
||||
or report.runtime_sources != row["worker"].get("runtime_sources", {})
|
||||
or report.plan_id != (row.get("plan") or {}).get("plan_id")
|
||||
or report.plan_sha256 != (row.get("plan") or {}).get("sha256")
|
||||
or (
|
||||
expected_composition is not None
|
||||
and report.composition_sha256 != expected_composition
|
||||
and (report.composition_sha256 is not None or report.inference_count > 0)
|
||||
)
|
||||
):
|
||||
raise ValueError("Отчёт не соответствует выбранному прогону.")
|
||||
if report.mission_outcome == "goal-reached" and outcome != "completed":
|
||||
raise ValueError("Достижение цели не соответствует исходу прогона.")
|
||||
if row["state"] in TERMINAL:
|
||||
if self.queue is not None:
|
||||
self.queue.release_simulation(run_id)
|
||||
if report is not None and row.get("report") != report.model_dump(mode="json"):
|
||||
raise ValueError("Сохранённый отчёт нельзя заменить.")
|
||||
self._release_finished(row)
|
||||
return row
|
||||
if run_id != self.active:
|
||||
raise RuntimeError("Прогон уже завершён.")
|
||||
@@ -399,14 +679,14 @@ class RunStore:
|
||||
row.get("clock") == "lockstep"
|
||||
and outcome == "completed"
|
||||
and (
|
||||
row["samples"] != row["request"]["max_steps"]
|
||||
row["samples"] == 0
|
||||
or row["applied_steps"] != row["samples"]
|
||||
)
|
||||
):
|
||||
raise RuntimeError("Прогон не достиг заданного числа шагов.")
|
||||
raise RuntimeError("Последний шаг физики не подтверждён.")
|
||||
row.update(state=outcome, message=message or None)
|
||||
if report is not None:
|
||||
row["report"] = report.model_dump(mode="json")
|
||||
self._save(row)
|
||||
if self.queue is not None:
|
||||
self.queue.release_simulation(run_id)
|
||||
self.active = None
|
||||
self._release_finished(row)
|
||||
return row
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Portable simulated sensor layout, independent of the execution computer.
|
||||
|
||||
Body frame is X forward, Y left, Z up from nominal track contact. These are
|
||||
explicit engineering mounting/optics assumptions, not factory calibration.
|
||||
"""
|
||||
|
||||
import copy
|
||||
import math
|
||||
|
||||
SCHEMA = "missioncore.rover-sensor-mounts/v1"
|
||||
|
||||
|
||||
def rover_mounts(height=0.8):
|
||||
return {
|
||||
"schema_version": SCHEMA,
|
||||
"frame": "body-x-forward-y-left-z-up-from-ground-contact",
|
||||
"calibration_status": "engineering-approximation-not-device-calibration",
|
||||
"insta360": {
|
||||
"model": "X4-dual-fisheye-surrogate",
|
||||
"body_center_m": [0.62, 0.0, height],
|
||||
"body_size_m": [0.1236, 0.0376, 0.046],
|
||||
"body_orientation": "long-axis-forward-lenses-left-right",
|
||||
"lens_centres_m": [[0.665, 0.02, height], [0.665, -0.02, height]],
|
||||
"lens_yaw_degrees": [90.0, -90.0],
|
||||
"image_size": [640, 640],
|
||||
"full_fov_degrees": 200.0,
|
||||
"projection": "equidistant-kb4-zero-coefficients",
|
||||
"panorama_size": [1024, 512],
|
||||
"stitch": "directional-dual-origin; no-vendor-optical-flow-emulation",
|
||||
"navigation_seam_guard_degrees": 4.0,
|
||||
},
|
||||
"realsense": {
|
||||
"model": "D455-ideal-depth-surrogate",
|
||||
"origin_m": [0.602, 0.0, 0.55],
|
||||
"pitch_degrees": -40.0,
|
||||
"body_size_m": [0.026, 0.124, 0.029],
|
||||
"image_size": [640, 480],
|
||||
"depth_sample_size": [60, 40],
|
||||
"fov_degrees": [87.0, 58.0],
|
||||
"depth_z_range_m": [0.52, 6.0],
|
||||
"no_return": "unknown-not-free",
|
||||
"scope": "ideal-first-hit-depth; no-stereo-noise-or-small-crack-claim",
|
||||
},
|
||||
"k1": {
|
||||
"model": "K1-with-MID360-angular-envelope",
|
||||
"origin_m": [0.0, 0.0, height + 0.25],
|
||||
"tilt_forward_degrees": 15.0,
|
||||
"body_size_m": [0.11, 0.11, 0.20],
|
||||
"elevation_degrees": [-7.0, 52.0],
|
||||
"range_m": [0.3, 8.0],
|
||||
"scope": (
|
||||
"MID360-published-FOV; mount-assumed; "
|
||||
"bounded-uniform-sampling-not-vendor-scan-pattern; 8m-lab-horizon"
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def validate_mounts(value):
|
||||
# First version admits the owner's mounting topology with a configurable
|
||||
# X4 height. A different lens model or mounting topology needs a revision.
|
||||
try:
|
||||
height = value["insta360"]["body_center_m"][2]
|
||||
if type(height) not in (int, float) or not math.isfinite(height) or not 0.78 <= height <= 2:
|
||||
raise ValueError("Invalid sensor mounting height")
|
||||
if value != rover_mounts(height):
|
||||
raise ValueError("Unsupported or changed sensor mount calibration")
|
||||
except (KeyError, TypeError, IndexError) as exc:
|
||||
raise ValueError("Invalid sensor mounts") from exc
|
||||
return copy.deepcopy(value)
|
||||
@@ -0,0 +1,228 @@
|
||||
"""Declared pinhole source -> installed model raster coordinates."""
|
||||
|
||||
import copy
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
from .run_inputs import (LEGACY_MOUNTED_SENSOR_SCHEMA, MOUNTED_SENSOR_SCHEMA,
|
||||
CONTINUOUS_SENSOR_SCHEMA, validate_sensor_rig)
|
||||
|
||||
|
||||
class PinholeSource:
|
||||
def __init__(self, rig):
|
||||
validate_sensor_rig(rig)
|
||||
self.rig = copy.deepcopy(rig)
|
||||
self.width, self.height = rig["image_size"]
|
||||
self.output_width, self.output_height = rig["surface_size"]
|
||||
pw, ph = rig["provider_image_size"]
|
||||
x, y, w, h = rig["provider_crop_xywh"]
|
||||
self.crop = (
|
||||
x * self.width / pw,
|
||||
y * self.height / ph,
|
||||
w * self.width / pw,
|
||||
h * self.height / ph,
|
||||
)
|
||||
|
||||
def validate_rgb(self, rgb):
|
||||
if rgb.dtype != np.uint8 or rgb.shape != (self.height, self.width, 3):
|
||||
raise ValueError("RGB does not match declared source camera")
|
||||
|
||||
def model_rgb(self, rgb):
|
||||
self.validate_rgb(rgb)
|
||||
size = tuple(self.rig["provider_image_size"])
|
||||
if (self.width, self.height) == size:
|
||||
return rgb
|
||||
return np.asarray(Image.fromarray(rgb).resize(size, Image.Resampling.BILINEAR))
|
||||
|
||||
def visible(self, u, v):
|
||||
x, y, width, height = self.crop
|
||||
return (u >= x) & (u < x + width) & (v >= y) & (v < y + height)
|
||||
|
||||
def indices(self, u, v):
|
||||
x, y, width, height = self.crop
|
||||
return ((v - y) * self.output_height / height).astype(int), (
|
||||
(u - x) * self.output_width / width
|
||||
).astype(int)
|
||||
|
||||
def validate_surface(self, surface):
|
||||
if surface.shape != (self.output_height, self.output_width):
|
||||
raise ValueError("Surface does not match declared model raster")
|
||||
|
||||
|
||||
class DualOriginSource(PinholeSource):
|
||||
"""Rectified pixels keep the actual lens origin that supplied their colour."""
|
||||
|
||||
def semantic_visible(self, points, calibration):
|
||||
"""One fixed perspective sector owns each semantic bearing.
|
||||
|
||||
Overlapping crops remain available to the operator and object detector.
|
||||
Edge-of-view reclassifications must not overwrite the same ground cell
|
||||
observed in its central view. Unprocessed sectors remain unknown.
|
||||
"""
|
||||
from .camera_optics import axes
|
||||
|
||||
lens_world = np.asarray(calibration["lens_axes"])[0]
|
||||
lens_body = axes(self.rig["mounts"]["insta360"]["lens_yaw_degrees"][0])
|
||||
body = lens_world @ lens_body.T
|
||||
origins = np.asarray(calibration["lens_origins"])
|
||||
# Native poses carry float32 quaternion roundoff. Transposition is not
|
||||
# exactly inversion for that measured basis; it can turn a correctly
|
||||
# quantized digital view into a spurious contract error after a turn.
|
||||
# Solve in the same basis used to construct the calibrated world view.
|
||||
ray = np.linalg.solve(body, (np.asarray(points) - origins.mean(axis=0)).T).T
|
||||
view = np.linalg.solve(body, np.asarray(calibration["rotation"]).reshape(3, 3))
|
||||
bearing = np.arctan2(ray[:, 1], ray[:, 0])
|
||||
yaw = np.arctan2(view[1, 0], view[0, 0])
|
||||
stride = np.pi / 4
|
||||
sector = int(np.rint(yaw / stride)) % 8
|
||||
mismatch = yaw - sector * stride
|
||||
if abs(np.arctan2(np.sin(mismatch), np.cos(mismatch))) > 1e-8:
|
||||
raise ValueError("Semantic view is outside the fixed sector contract")
|
||||
# Compute ownership once from the body bearing. Independent floating
|
||||
# boundary comparisons in overlapping views can admit a ray twice.
|
||||
owner = np.floor((bearing + stride / 2) / stride).astype(int) % 8
|
||||
return owner == sector
|
||||
|
||||
def project(self, points, calibration):
|
||||
from .camera_optics import fisheye_project
|
||||
|
||||
if calibration.get("projection") != "dual-origin-rectilinear/v1":
|
||||
raise ValueError("A panorama cannot masquerade as a central pinhole")
|
||||
rotation = np.asarray(calibration["rotation"], dtype=float).reshape(3, 3)
|
||||
origins = np.asarray(calibration["lens_origins"], dtype=float)
|
||||
lens_axes = np.asarray(calibration["lens_axes"], dtype=float).reshape(2, 3, 3)
|
||||
local = (points - np.mean(origins, axis=0)) @ rotation
|
||||
u, v, visible = np.zeros(len(points)), np.zeros(len(points)), np.zeros(len(points), bool)
|
||||
fx, fy, cx, cy = calibration["intrinsics"]
|
||||
for i, origin in enumerate(origins):
|
||||
world = points - origin
|
||||
ray = world @ rotation
|
||||
depth = np.maximum(ray[:, 0], 1e-8)
|
||||
x, y = cx - fx * ray[:, 1] / depth, cy - fy * ray[:, 2] / depth
|
||||
# Rectification selects a lens by ray direction, not by point truth.
|
||||
fu, fv, covered = fisheye_project(world, lens_axes[i], self.rig["mounts"]["insta360"])
|
||||
ok = (ray[:, 0] > 0.05) & self.lens_contributes(world, lens_axes, i) & covered & self.visible(x, y)
|
||||
# This surrogate does not reproduce proprietary optical-flow
|
||||
# stitching. Its ownership seam is not reliable semantic evidence:
|
||||
# parallax/texture discontinuities can be labelled as a thin tree.
|
||||
# Keep that angular band unknown for projection, retaining all
|
||||
# independent range hazards. Operator panorama stays complete.
|
||||
seam_guard = np.sin(np.radians(self.seam_guard_degrees()))
|
||||
confidence = np.abs(world @ lens_axes[0, :, 0]) / np.maximum(
|
||||
np.linalg.norm(world, axis=1), 1e-12
|
||||
)
|
||||
ok &= confidence >= seam_guard
|
||||
depths = getattr(self, "lens_depths", None)
|
||||
if depths is not None:
|
||||
from .camera_optics import sample_nearest
|
||||
|
||||
observed = sample_nearest(depths[i], fu, fv)
|
||||
distance = np.linalg.norm(world, axis=1)
|
||||
ok &= np.isfinite(observed) & (observed > 0) & (distance <= observed + 0.08)
|
||||
take = ok & ~visible
|
||||
u[take], v[take], visible[take] = x[take], y[take], True
|
||||
return local, u, v, visible
|
||||
|
||||
def seam_guard_degrees(self):
|
||||
return self.rig["mounts"]["insta360"]["navigation_seam_guard_degrees"]
|
||||
|
||||
def lens_contributes(self, world, lens_axes, lens):
|
||||
return np.argmax(world @ lens_axes[:, :, 0].T, axis=1) == lens
|
||||
|
||||
|
||||
class BodyViewSource(DualOriginSource):
|
||||
"""One stable perspective can contain pixels from both physical lenses.
|
||||
|
||||
The v4 feather stitch removes the hard colour discontinuity. It grants no
|
||||
geometric visibility: the inherited per-origin first-hit checks still apply.
|
||||
Overlapping supplementary views update the same observed semantic map.
|
||||
"""
|
||||
|
||||
def semantic_visible(self, points, calibration):
|
||||
_, u, v, visible = self.project(points, calibration)
|
||||
return visible & self.semantic_pixels(u, v)
|
||||
|
||||
def semantic_pixels(self, u, v):
|
||||
# The model crop border has truncated image context. Keep the complete
|
||||
# operator view and range hazards, but do not let these edge labels
|
||||
# overwrite the persistent surface map as ground leaves the image.
|
||||
x, y, width, height = self.crop
|
||||
margin = .05
|
||||
return ((u >= x + margin*width) & (u < x + (1-margin)*width)
|
||||
& (v >= y + margin*height) & (v < y + (1-margin)*height))
|
||||
|
||||
def seam_guard_degrees(self):
|
||||
return 0.0
|
||||
|
||||
def lens_contributes(self, world, lens_axes, lens):
|
||||
affinity = world @ lens_axes[:, :, 0].T / np.maximum(
|
||||
np.linalg.norm(world, axis=1)[:, None], 1e-12)
|
||||
weight = np.clip(.5 + (affinity[:,0]-affinity[:,1]) /
|
||||
(4*np.sin(np.radians(4))), 0, 1)
|
||||
return (weight if lens == 0 else 1-weight) > 0
|
||||
|
||||
|
||||
class SingleLensSource(PinholeSource):
|
||||
"""One physical lens supplies every pixel of a rectified inference frame."""
|
||||
|
||||
def semantic_visible(self, points, calibration):
|
||||
from .camera_optics import axes
|
||||
|
||||
body = (
|
||||
np.asarray(calibration["lens_axes"])[0]
|
||||
@ axes(self.rig["mounts"]["insta360"]["lens_yaw_degrees"][0]).T
|
||||
)
|
||||
view = np.linalg.solve(body, np.asarray(calibration["rotation"]).reshape(3, 3))
|
||||
yaw = np.arctan2(view[1, 0], view[0, 0])
|
||||
stride = np.pi / 2
|
||||
sector = int(np.rint((yaw - stride / 2) / stride)) % 4
|
||||
mismatch = yaw - (sector + 0.5) * stride
|
||||
if abs(np.arctan2(np.sin(mismatch), np.cos(mismatch))) > 1e-8:
|
||||
raise ValueError("Semantic view is outside the single-lens sector contract")
|
||||
centre = np.asarray(calibration["lens_origins"]).mean(axis=0)
|
||||
ray = np.linalg.solve(body, (np.asarray(points) - centre).T).T
|
||||
owner = np.floor(np.arctan2(ray[:, 1], ray[:, 0]) / stride).astype(int) % 4
|
||||
return owner == sector
|
||||
|
||||
def project(self, points, calibration):
|
||||
from .camera_optics import fisheye_project, sample_nearest
|
||||
|
||||
lens = calibration.get("source_lens")
|
||||
if (
|
||||
calibration.get("projection") != "single-lens-rectilinear/v1"
|
||||
or type(lens) is not int
|
||||
or lens not in (0, 1)
|
||||
):
|
||||
raise ValueError("Expected one identified physical lens, not a central panorama")
|
||||
origin = np.asarray(calibration["lens_origins"])[lens]
|
||||
if not np.array_equal(origin, calibration["origin"]):
|
||||
raise ValueError("Rectified origin differs from its physical lens")
|
||||
world = np.asarray(points) - origin
|
||||
local = world @ np.asarray(calibration["rotation"]).reshape(3, 3)
|
||||
fx, fy, cx, cy = calibration["intrinsics"]
|
||||
depth = np.maximum(local[:, 0], 1e-8)
|
||||
u, v = cx - fx * local[:, 1] / depth, cy - fy * local[:, 2] / depth
|
||||
fu, fv, covered = fisheye_project(
|
||||
world, np.asarray(calibration["lens_axes"])[lens], self.rig["mounts"]["insta360"]
|
||||
)
|
||||
visible = (local[:, 0] > 0.05) & covered & self.visible(u, v)
|
||||
depths = getattr(self, "lens_depths", None)
|
||||
if depths is not None:
|
||||
observed = sample_nearest(depths[lens], fu, fv)
|
||||
visible &= (
|
||||
np.isfinite(observed)
|
||||
& (observed > 0)
|
||||
& (np.linalg.norm(world, axis=1) <= observed + 0.08)
|
||||
)
|
||||
return local, u, v, visible
|
||||
|
||||
|
||||
def source_for_rig(rig):
|
||||
if rig["schema_version"] == CONTINUOUS_SENSOR_SCHEMA:
|
||||
return BodyViewSource(rig)
|
||||
if rig["schema_version"] == MOUNTED_SENSOR_SCHEMA:
|
||||
return SingleLensSource(rig)
|
||||
if rig["schema_version"] == LEGACY_MOUNTED_SENSOR_SCHEMA:
|
||||
return DualOriginSource(rig)
|
||||
return PinholeSource(rig)
|
||||
@@ -13,9 +13,9 @@ def terrain_matches(manifest, world, generator_sha256=None):
|
||||
# A supplied full-scene collider is not the generated 30 m tile below.
|
||||
# Source/calibration and collider hashes still bind this asset; actual
|
||||
# support and full-body clearance are checked at the new start by Isaac.
|
||||
return manifest.get("collider_sha256") == world.get("collider_sha256") and bool(
|
||||
manifest.get("collider_sha256")
|
||||
)
|
||||
return manifest.get("source_collider_sha256", manifest.get("collider_sha256")) == world.get(
|
||||
"collider_sha256"
|
||||
) and bool(manifest.get("collider_sha256"))
|
||||
# The versioned preparer captures a 30x30 m tile and a 12 m vertical band.
|
||||
# Admit starts only within its interior; physical support is checked later.
|
||||
return (
|
||||
|
||||
@@ -13,6 +13,7 @@ import numpy as np
|
||||
|
||||
from k1link.artifacts import utc_now_iso
|
||||
from k1link.simulation.ai_polygon.contracts import WorkerWorldCreate, WorldCreate, WorldSettings
|
||||
from k1link.simulation.ai_polygon.project_worlds import ProjectWorlds
|
||||
|
||||
CHUNK_BYTES = 4 * 1024**2
|
||||
WORLD_ID = re.compile(r"^aiworld-[a-f0-9]{32}$")
|
||||
@@ -89,7 +90,7 @@ def inspect_gaussian_ply(path: Path) -> int:
|
||||
"rot_3",
|
||||
}
|
||||
if (
|
||||
not 1 <= count <= 20_000_000
|
||||
count < 1
|
||||
or not required.issubset(names)
|
||||
or len(names) != len(set(names))
|
||||
or not 14 <= len(properties) <= 128
|
||||
@@ -108,6 +109,7 @@ def inspect_gaussian_ply(path: Path) -> int:
|
||||
|
||||
class WorldStore:
|
||||
def __init__(self, root: Path):
|
||||
self.projects = ProjectWorlds(root)
|
||||
self.root = root / "ai-polygon" / "worlds"
|
||||
self.root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
self.lock = threading.RLock()
|
||||
@@ -122,6 +124,10 @@ class WorldStore:
|
||||
|
||||
def get(self, world_id: str) -> dict:
|
||||
with self.lock:
|
||||
if not (self.root / world_id / "world.json").exists():
|
||||
if not WORLD_ID.fullmatch(world_id):
|
||||
raise FileNotFoundError(world_id)
|
||||
return self.projects.get(world_id)
|
||||
path = self.directory(world_id)
|
||||
document = json.loads((path / "world.json").read_text())
|
||||
if document["status"] == "uploading":
|
||||
@@ -137,7 +143,7 @@ class WorldStore:
|
||||
self.get(p.name)
|
||||
for p in self.root.iterdir()
|
||||
if WORLD_ID.fullmatch(p.name) and p.is_dir() and not p.is_symlink()
|
||||
],
|
||||
] + self.projects.list(),
|
||||
key=lambda item: item["created_at"],
|
||||
reverse=True,
|
||||
)
|
||||
@@ -251,6 +257,8 @@ class WorldStore:
|
||||
doc = self.get(world_id)
|
||||
if doc["status"] != "available":
|
||||
raise RuntimeError("Сначала завершите импорт сцены.")
|
||||
if doc.get("storage", {}).get("kind") == "project":
|
||||
raise ValueError("Калибровка этой локации хранится в исходном проекте.")
|
||||
doc["settings"] = settings.model_dump(mode="json")
|
||||
write_json(self.directory(world_id) / "world.json", doc)
|
||||
return doc
|
||||
|
||||
@@ -10,9 +10,15 @@ from fastapi.responses import FileResponse
|
||||
from k1link.observatory.recorded_jobs import ObservatoryRecordedJobQueue
|
||||
from k1link.simulation.ai_polygon.composition import compose, registry
|
||||
from k1link.simulation.ai_polygon.contracts import (
|
||||
InferencePreview,
|
||||
LocalPlanCreate,
|
||||
PlanLibraryUpdate,
|
||||
PlanningCommand,
|
||||
PlanSave,
|
||||
RealtimeSnapshot,
|
||||
RunApplied,
|
||||
RunCreate,
|
||||
RunLibraryUpdate,
|
||||
RunProgress,
|
||||
RunSample,
|
||||
ViewControl,
|
||||
@@ -23,6 +29,8 @@ from k1link.simulation.ai_polygon.contracts import (
|
||||
WorldCreate,
|
||||
WorldSettings,
|
||||
)
|
||||
from k1link.simulation.ai_polygon.editor_cache import EditorCache
|
||||
from k1link.simulation.ai_polygon.robots import robot_catalog, select_robot
|
||||
from k1link.simulation.ai_polygon.runs import RunStore
|
||||
from k1link.simulation.ai_polygon.worlds import CHUNK_BYTES, SOURCES, WorldStore
|
||||
|
||||
@@ -32,8 +40,12 @@ def build_ai_polygon_router(
|
||||
) -> APIRouter:
|
||||
worlds = WorldStore(data_dir)
|
||||
runs = RunStore(worlds, queue)
|
||||
editor = EditorCache(data_dir, worlds)
|
||||
router = APIRouter(prefix="/api/v1/ai-polygon", tags=["ai-polygon"])
|
||||
adapters = Path(__file__).resolve().parents[3] / "simulation/ai-polygon"
|
||||
from k1link.web.ai_profile_api import build_ai_profile_router
|
||||
|
||||
router.include_router(build_ai_profile_router(data_dir / "ai-polygon/ai-profiles", adapters))
|
||||
|
||||
def invoke(fn, *args):
|
||||
try:
|
||||
@@ -52,14 +64,37 @@ def build_ai_polygon_router(
|
||||
|
||||
@router.get("/catalog")
|
||||
def catalog():
|
||||
runtime = runs.status()
|
||||
locations = worlds.list()
|
||||
if "project-sog" not in (runtime.get("worker") or {}).get("scene_formats", []):
|
||||
locations = [
|
||||
{
|
||||
**w,
|
||||
"inference_ready": False,
|
||||
"inference_message": "Для inference этой локации требуется обновление Worker.",
|
||||
}
|
||||
if w.get("local_scene")
|
||||
else w
|
||||
for w in locations
|
||||
]
|
||||
return {
|
||||
"schema_version": "missioncore.ai-polygon-catalog/v1",
|
||||
"sources": SOURCES,
|
||||
"worlds": worlds.list(),
|
||||
"runtime": runs.status(),
|
||||
"runs": runs.list()[:30],
|
||||
"robots": robot_catalog(adapters),
|
||||
"worlds": locations,
|
||||
"runtime": runtime,
|
||||
"runs": runs.library.visible(runs.list(), "run_id")[:30],
|
||||
"plans": runs.plans.visible_list(),
|
||||
}
|
||||
|
||||
@router.get("/worker/worlds/{world_id}/project-assets")
|
||||
def project_assets(world_id: str, authorization: str | None = Header(default=None)):
|
||||
authenticate(authorization)
|
||||
world = invoke(worlds.get, world_id)
|
||||
if not world.get("local_scene"):
|
||||
raise HTTPException(400, "Локация не является Gaussian-проектом.")
|
||||
return invoke(worlds.projects.package, world)
|
||||
|
||||
@router.post("/worlds", status_code=201)
|
||||
def create_world(body: WorldCreate):
|
||||
return invoke(worlds.create, body)
|
||||
@@ -107,12 +142,67 @@ def build_ai_polygon_router(
|
||||
},
|
||||
)
|
||||
|
||||
@router.post("/worlds/{world_id}/editor-cache")
|
||||
def prepare_editor(world_id: str):
|
||||
return invoke(editor.request, world_id)
|
||||
|
||||
@router.get("/editor-cache/{key}")
|
||||
def editor_status(key: str):
|
||||
return invoke(editor.get, key)
|
||||
|
||||
@router.get("/editor-cache/{key}/{name}")
|
||||
def editor_asset(key: str, name: str):
|
||||
path, digest = invoke(editor.asset, key, name)
|
||||
return FileResponse(
|
||||
path,
|
||||
headers={
|
||||
"ETag": f'"{digest}"',
|
||||
"Cache-Control": "private, max-age=31536000, immutable",
|
||||
},
|
||||
)
|
||||
|
||||
@router.post("/plans", status_code=201)
|
||||
def local_plan(body: LocalPlanCreate):
|
||||
with runs.lock:
|
||||
cached = invoke(editor.get, body.cache_key)
|
||||
world = invoke(worlds.get, cached["world"]["world_id"])
|
||||
if cached["status"] != "ready" or editor.identity(world) != cached["identity"]:
|
||||
raise HTTPException(409, "Локация изменилась. Откройте планирование заново.")
|
||||
robot = invoke(select_robot, body.robot_id, body.robot_sha256)
|
||||
context = {"world": world, "robot": robot, "run_id": None}
|
||||
return invoke(
|
||||
lambda: runs.plans.create(
|
||||
context,
|
||||
body.name,
|
||||
[p.model_dump() for p in body.points],
|
||||
body.sequence,
|
||||
draft_id=body.draft_id,
|
||||
cache_key=body.cache_key,
|
||||
editor_collider_sha256=cached["files"]["collision.glb"]["sha256"],
|
||||
)
|
||||
)
|
||||
|
||||
@router.patch("/plans/{plan_id}")
|
||||
def update_plan(plan_id: str, body: PlanLibraryUpdate):
|
||||
return invoke(runs.update_library, "plans", plan_id, body.model_dump(exclude_none=True))
|
||||
|
||||
@router.patch("/runs/{run_id}")
|
||||
def update_run(run_id: str, body: RunLibraryUpdate):
|
||||
return invoke(runs.update_library, "runs", run_id, body.model_dump())
|
||||
|
||||
@router.post("/runs", status_code=201)
|
||||
def start(body: RunCreate, idempotency_key: str = Header(alias="Idempotency-Key")):
|
||||
if editor.pending():
|
||||
raise HTTPException(409, "Дождитесь загрузки локальной сцены.")
|
||||
if body.clock == "realtime":
|
||||
graph = invoke(compose, adapters, body.composition)
|
||||
body = body.model_copy(update={"composition": graph.selection_document()})
|
||||
return invoke(runs.start, body, idempotency_key)
|
||||
return invoke(
|
||||
lambda: runs.start(
|
||||
body, idempotency_key,
|
||||
composition_sha256=graph.sha256 if body.clock == "realtime" else None,
|
||||
)
|
||||
)
|
||||
|
||||
@router.get("/ai-modules")
|
||||
def modules():
|
||||
@@ -129,10 +219,6 @@ def build_ai_polygon_router(
|
||||
runs.status()
|
||||
return invoke(runs.get, run_id)
|
||||
|
||||
@router.post("/runs/{run_id}/{command}")
|
||||
def control(run_id: str, command: Literal["pause", "play", "step", "stop"]):
|
||||
return invoke(runs.control, run_id, command)
|
||||
|
||||
@router.get("/runs/{run_id}/frames/{sequence}.jpg")
|
||||
def frame(run_id: str, sequence: int):
|
||||
row = invoke(runs.get, run_id)
|
||||
@@ -144,9 +230,37 @@ def build_ai_polygon_router(
|
||||
headers={"Cache-Control": "private, max-age=31536000, immutable"},
|
||||
)
|
||||
|
||||
@router.get("/runs/{run_id}/inference-preview")
|
||||
def inference_preview(run_id: str, response: Response):
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
return invoke(runs.inference_preview, run_id)
|
||||
|
||||
@router.post("/worker/runs/{run_id}/inference-preview")
|
||||
def publish_inference_preview(
|
||||
run_id: str,
|
||||
body: InferencePreview,
|
||||
instance_id: str = Header(alias="Worker-Instance"),
|
||||
authorization: str | None = Header(default=None),
|
||||
):
|
||||
authenticate(authorization)
|
||||
return invoke(runs.inference_preview, run_id, instance_id, body)
|
||||
|
||||
@router.put("/runs/{run_id}/view")
|
||||
def view(run_id: str, body: ViewControl):
|
||||
return invoke(runs.view, run_id, body.camera)
|
||||
row = invoke(runs.view, run_id, body.camera, body.navigation)
|
||||
return {"accepted": body.navigation.sequence} if body.navigation else row
|
||||
|
||||
@router.put("/runs/{run_id}/planning")
|
||||
def planning(run_id: str, body: PlanningCommand):
|
||||
return invoke(runs.planning_command, run_id, body)
|
||||
|
||||
@router.post("/runs/{run_id}/plan")
|
||||
def save_plan(run_id: str, body: PlanSave):
|
||||
return invoke(runs.save_plan, run_id, body)
|
||||
|
||||
@router.post("/runs/{run_id}/{command}")
|
||||
def control(run_id: str, command: Literal["pause", "play", "step", "stop"]):
|
||||
return invoke(runs.control, run_id, command)
|
||||
|
||||
@router.get("/runs/{run_id}/decisions")
|
||||
def decisions(run_id: str):
|
||||
@@ -181,7 +295,42 @@ def build_ai_polygon_router(
|
||||
@router.post("/worker/poll")
|
||||
def poll(body: WorkerPoll, authorization: str | None = Header(default=None)):
|
||||
authenticate(authorization)
|
||||
return invoke(runs.poll, body.instance_id, body.run_id)
|
||||
value = invoke(runs.poll, body.instance_id, body.run_id)
|
||||
if value["action"] == "idle":
|
||||
pending = editor.pending()
|
||||
if pending:
|
||||
if runs.queue is None:
|
||||
return value
|
||||
try:
|
||||
runs.queue.reserve_simulation("aicache-" + pending["key"])
|
||||
except RuntimeError:
|
||||
return value
|
||||
return {"action": "editor-cache", "cache": pending}
|
||||
return value
|
||||
|
||||
@router.post("/worker/editor-cache/{key}")
|
||||
async def upload_editor(
|
||||
key: str,
|
||||
request: Request,
|
||||
authorization: str | None = Header(default=None),
|
||||
instance_id: str = Header(alias="Worker-Instance"),
|
||||
):
|
||||
authenticate(authorization)
|
||||
invoke(runs.heartbeat, instance_id)
|
||||
raw = bytearray()
|
||||
async for block in request.stream():
|
||||
raw.extend(block)
|
||||
if len(raw) > 1024 * 1024:
|
||||
raise HTTPException(413, "Editor transfer chunk too large")
|
||||
import json
|
||||
|
||||
body = json.loads(raw)
|
||||
if body.get("action") == "release":
|
||||
invoke(editor.get, key)
|
||||
if runs.queue is not None:
|
||||
invoke(runs.queue.release_simulation, "aicache-" + key)
|
||||
return {"released": True}
|
||||
return invoke(editor.update, key, body)
|
||||
|
||||
@router.post("/worker/runs/{run_id}/progress")
|
||||
def progress(
|
||||
@@ -216,7 +365,9 @@ def build_ai_polygon_router(
|
||||
@router.post("/worker/runs/{run_id}/finish")
|
||||
def finish(run_id: str, body: WorkerResult, authorization: str | None = Header(default=None)):
|
||||
authenticate(authorization)
|
||||
return invoke(runs.finish, run_id, body.instance_id, body.outcome, body.message)
|
||||
return invoke(
|
||||
runs.finish, run_id, body.instance_id, body.outcome, body.message, body.report
|
||||
)
|
||||
|
||||
@router.post("/worker/runs/{run_id}/applied")
|
||||
def applied(
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
"""AI preset library; no authority to launch or modify a running simulation."""
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from pydantic import Field
|
||||
|
||||
from k1link.simulation.ai_polygon.ai_profiles import AiProfileStore
|
||||
from k1link.simulation.ai_polygon.contracts import Contract
|
||||
|
||||
|
||||
class ProfileCreate(Contract):
|
||||
name: str = Field(min_length=1, max_length=120)
|
||||
composition: dict
|
||||
|
||||
|
||||
class ProfileUpdate(Contract):
|
||||
expected_revision: int = Field(ge=1)
|
||||
name: str | None = Field(default=None, min_length=1, max_length=120)
|
||||
composition: dict | None = None
|
||||
removed: bool = False
|
||||
|
||||
|
||||
def build_ai_profile_router(root, adapters):
|
||||
store = AiProfileStore(root, adapters)
|
||||
router = APIRouter(prefix="/ai-profiles")
|
||||
|
||||
def invoke(fn, *args, **kwargs):
|
||||
try:
|
||||
return fn(*args, **kwargs)
|
||||
except FileNotFoundError as exc:
|
||||
raise HTTPException(404, "Профиль AI не найден.") from exc
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(409, str(exc)) from exc
|
||||
|
||||
@router.get("")
|
||||
def profiles():
|
||||
return invoke(store.list)
|
||||
|
||||
@router.post("", status_code=201)
|
||||
def create(body: ProfileCreate):
|
||||
return invoke(store.save, body.name, body.composition)
|
||||
|
||||
@router.patch("/{identity}")
|
||||
def update(identity: str, body: ProfileUpdate):
|
||||
return invoke(store.save, body.name, body.composition, identity=identity,
|
||||
expected_revision=body.expected_revision, removed=body.removed)
|
||||
|
||||
return router
|
||||
Reference in New Issue
Block a user