diff --git a/simulation/ai-polygon/nav2/server.py b/simulation/ai-polygon/nav2/server.py index 9c19df4e..9330534f 100644 --- a/simulation/ai-polygon/nav2/server.py +++ b/simulation/ai-polygon/nav2/server.py @@ -265,7 +265,8 @@ class Navigation: route_observation=route, diagnostic=dict(terrain=observed['metrics'], controller='nav2')) # This is a proposal returned to the mission layer; /control supplies # the separately admitted command bound to current pose/range/intent. - self.control.accept(value, result, terrain, detections=observed['detected']) + self.control.accept(value, result, terrain, detections=observed['detected'], + collision_terrain=observed['collision_terrain']) return result diff --git a/simulation/ai-polygon/nav2/terrain_observation.py b/simulation/ai-polygon/nav2/terrain_observation.py index e3a7945f..0e129ed9 100644 --- a/simulation/ai-polygon/nav2/terrain_observation.py +++ b/simulation/ai-polygon/nav2/terrain_observation.py @@ -130,9 +130,11 @@ class TerrainObservation: detected = self.detections.without_ground(candidates, self.semantics.permitted_terrain(ground, time.monotonic())) points = self.detections.overlay(points, detected) + collision = points.copy() points, forbidden = self.semantics.apply(points, time.monotonic()) search, _ = self.support_obstacles.apply(points, pose=pose, monitor=self.monitor) - return dict(terrain=points, search_terrain=search, physical_terrain=physical, detected=detected, + return dict(terrain=points, collision_terrain=collision, search_terrain=search, + physical_terrain=physical, detected=detected, permitted_terrain=(self.semantics.permitted_terrain(points, time.monotonic()) if request.get("route_transition_target") is not None else None), current_points=current, diff --git a/simulation/ai-polygon/navigation/continuous_control.py b/simulation/ai-polygon/navigation/continuous_control.py index 2bcdc570..eae62c79 100644 --- a/simulation/ai-polygon/navigation/continuous_control.py +++ b/simulation/ai-polygon/navigation/continuous_control.py @@ -30,6 +30,7 @@ class ContinuousControl: clock=time.monotonic, body_top_m=math.inf, native_only=False): self.monitor, self.support = monitor, support_policy self.detections = DetectionObstacles(monitor) + self.ground_monitor = monitor.ground_envelope() self.publish_pose, self.publish_path, self.native_command = ( publish_pose, publish_path, native_command) self.clock, self.lock = clock, threading.Lock() @@ -61,7 +62,7 @@ class ContinuousControl: self.geometry = (self.clock() - age, points) self.range_sequence = sequence - def accept(self, value, result, terrain, *, detections=None): + def accept(self, value, result, terrain, *, detections=None, collision_terrain=None): candidates = self.detections.observed(value) if detections is None: detections = candidates @@ -69,8 +70,18 @@ class ContinuousControl: detections = np.asarray(detections, dtype=float).reshape(-1, 3).copy() if not set(map(tuple, detections)) <= set(map(tuple, candidates)): raise ValueError("Refined detection is not an original associated range return") + terrain = np.asarray(terrain, dtype=float).reshape(-1, 4).copy() + collision = (terrain.copy() if collision_terrain is None else + np.asarray(collision_terrain, dtype=float).reshape(-1, 4).copy()) + if (collision.shape != terrain.shape or not np.isfinite([terrain, collision]).all() + or not np.array_equal(collision[:, :3], terrain[:, :3]) + or np.any(collision[:, 3] > terrain[:, 3])): + raise ValueError("Collision and surface layers must share the measured terrain") + # Only costs added by the semantic overlay belong to ground exclusion. + # Physical terrain and detected solids retain the complete body envelope. + floor = terrain[terrain[:, 3] > collision[:, 3]].copy() record = dict(value=value, result=result, detections=detections, - terrain=np.asarray(terrain, dtype=float).reshape(-1, 4).copy(), + terrain=terrain, collision_terrain=collision, forbidden_ground=floor, received_at=self.clock()) with self.lock: self.plans[value["observation_id"]] = record @@ -84,7 +95,9 @@ class ContinuousControl: return None identity, plan = next(reversed(self.plans.items())) return dict(observation_id=identity, request=copy.deepcopy(plan["value"]), - result=copy.deepcopy(plan["result"]), terrain=plan["terrain"].tolist()) + result=copy.deepcopy(plan["result"]), terrain=plan["terrain"].tolist(), + collision_terrain=plan["collision_terrain"].tolist(), + forbidden_ground=plan["forbidden_ground"].tolist()) def tick(self, value): started = self.clock() @@ -147,6 +160,7 @@ class ContinuousControl: raised = (height > self.monitor.max_step + 1e-4) & (height <= self.body_top_m) hazards = np.column_stack((points[raised], np.ones(int(raised.sum())))) terrain = np.concatenate((plan["terrain"], hazards)) + collision = np.concatenate((plan["collision_terrain"], hazards)) def admit(command): speed, angular = map(float, command) if not all(math.isfinite(x) for x in (speed, angular)): @@ -162,12 +176,16 @@ class ContinuousControl: min(self.support.partial_yaw_rps, angular)) if stationary else 0.0 if (reverse and (speed > 0 or abs(angular) > 0.15)) or (not reverse and speed < 0): return output(reason="direction") - speed, angular, obstacle_scale = self.monitor.regulate_command(speed, angular, terrain, pose) + speed, angular, obstacle_scale = self.monitor.regulate_command(speed, angular, collision, pose) if obstacle_scale == 0: return output(reason="obstacle") + speed, angular, ground_scale = self.ground_monitor.regulate_command( + speed, angular, plan["forbidden_ground"], pose) + if ground_scale == 0: + return output(reason="forbidden-ground-sweep") speed, angular, support_scale, support = self.support.regulate( speed, angular, terrain, pose, request["body_contact_height_m"], - current_points=points, + current_points=points, collision_terrain=collision, observed_retreat=bool(reverse and request.get("continuous")), ) evidence = dict(support_policy=support["policy"]["reason"], diff --git a/simulation/ai-polygon/navigation/footprint.py b/simulation/ai-polygon/navigation/footprint.py index f5e2d217..40365631 100644 --- a/simulation/ai-polygon/navigation/footprint.py +++ b/simulation/ai-polygon/navigation/footprint.py @@ -45,6 +45,22 @@ class Footprint: else None ) + def ground_envelope(self): + """Conservative origin-centred enclosure of all validated contact bands. + + Surface exclusions constrain ground contacts, not mounted overhangs. + Keep the gap between tracks and the same reserve, braking and motion + discrepancy bounds. Legacy geometry retains the full collision body. + """ + if self.contacts is None: + return self + extent = np.max([np.maximum(np.abs(low), np.abs(high)) + for low, high in self.contacts.bands], axis=0) + return Footprint(dict(length_m=float(2*extent[0]), width_m=float(2*extent[1]), + max_step_m=self.max_step, + max_slope_degrees=math.degrees(math.atan(self.max_slope))), + deceleration=self.deceleration, clearance_m=self.clearance_m) + def classify_contacts(self, surface, offsets): if self.contacts is None: return surface.classify(offsets) diff --git a/simulation/ai-polygon/navigation/support_policy.py b/simulation/ai-polygon/navigation/support_policy.py index eee485b6..3d91702c 100644 --- a/simulation/ai-polygon/navigation/support_policy.py +++ b/simulation/ai-polygon/navigation/support_policy.py @@ -110,8 +110,9 @@ class SupportPolicy: ) def regulate(self, speed, yaw_rate, terrain, pose, contact_height_m, *, current_points, - observed_retreat=False): + observed_retreat=False, collision_terrain=None): m = self.monitor + collision = terrain if collision_terrain is None else collision_terrain requested = [speed, yaw_rate] pivot_scale = 1.0 requested_support = None @@ -151,7 +152,7 @@ class SupportPolicy: narrow_fresh = live_sweep(speed * lower, yaw_rate * lower) if (narrow["admitted"] and fresh_clear(narrow_fresh) and m.command_footprint_clear( - speed * lower, yaw_rate * lower, terrain, pose)): + speed * lower, yaw_rate * lower, collision, pose)): upper = 1.0 original = requested_support = support for _ in range(7): @@ -161,7 +162,7 @@ class SupportPolicy: candidate_fresh = live_sweep(speed * middle, yaw_rate * middle) if (candidate["admitted"] and fresh_clear(candidate_fresh) and m.command_footprint_clear( - speed * middle, yaw_rate * middle, terrain, pose)): + speed * middle, yaw_rate * middle, collision, pose)): lower, narrow, narrow_fresh = middle, candidate, candidate_fresh else: upper = middle @@ -180,7 +181,7 @@ class SupportPolicy: narrow_fresh = live_sweep(speed * lower, yaw_rate * lower) if ((support["unsafe_samples"] or not fresh_clear(fresh_sweep)) and not narrow["unsafe_samples"] and fresh_clear(narrow_fresh) - and m.command_footprint_clear(speed * lower, yaw_rate * lower, terrain, pose)): + and m.command_footprint_clear(speed * lower, yaw_rate * lower, collision, pose)): # Apply the existing partial-observation policy to the actual # shorter stopping sweep, not to the discarded fast proposal. # This grants at most crawl speed and still requires both fresh @@ -208,7 +209,7 @@ class SupportPolicy: narrow = m.assess_command_support(0, slower, terrain, pose, contact_height_m) narrow_fresh = live_sweep(0, slower) if (narrow["admitted"] and fresh_clear(narrow_fresh) - and m.command_footprint_clear(0, slower, terrain, pose)): + and m.command_footprint_clear(0, slower, collision, pose)): narrow["requested_pivot_support"] = { key: support[key] for key in ("status", "unknown_samples", "unsafe_samples", "bounds") diff --git a/simulation/ai-polygon/realtime_worker.py b/simulation/ai-polygon/realtime_worker.py index 62a2cb3f..7998ba5f 100644 --- a/simulation/ai-polygon/realtime_worker.py +++ b/simulation/ai-polygon/realtime_worker.py @@ -172,6 +172,7 @@ def main(): for n in ( "run_realtime.py", "native_experience.py", + "scheduling_policy.py", "motion_control.py", "rover_profile.py", "tracked_rover.py", diff --git a/simulation/ai-polygon/run_realtime.py b/simulation/ai-polygon/run_realtime.py index 17cda54f..0534ee30 100644 --- a/simulation/ai-polygon/run_realtime.py +++ b/simulation/ai-polygon/run_realtime.py @@ -12,7 +12,7 @@ from datetime import UTC, datetime from pathlib import Path from episode_failure import consume_pipeline_failure -from scheduling_policy import build_scheduling_policy +from scheduling_policy import CaptureCadence, build_scheduling_policy from local_state import StateChannel, read_json, write_json from motion_control import RoverMotionControl from observer_camera import ObserverCamera, SmoothView @@ -187,6 +187,7 @@ def main(): directory / "sensor-clock.json", { "requested_hz": SENSOR_HZ, + "capture_cadence": "monotonic-deadline-latest-frame-no-catchup", "maximum_pending_inference_frames": 1, "frame_deadline_seconds": FRAME_DEADLINE_SECONDS, "ray_packet": "world-mounts-indexed-endpoints-organized-ranges-v2", @@ -345,7 +346,8 @@ def main(): operator_camera = ObserverCamera() smooth_view = SmoothView() control = {"control": "pause", "control_sequence": 0, "camera": "follow"} - start = last_report = last_sensor = last_control = time.monotonic() + start = last_report = last_control = time.monotonic() + capture_cadence = CaptureCadence(SENSOR_HZ, start) render_frames = sensor_frames = sequence = 0 prior_metrics = (start, 0, 0, 0, baseline) speed = 0.0 @@ -626,7 +628,7 @@ def main(): physics_motion.flush() physics = SimulationManager.get_num_physics_steps() sim_ns = round((physics - baseline) * 1e9 / 60) - if playing and captured_at - last_sensor >= 1 / SENSOR_HZ: + if playing and capture_cadence.due(captured_at): mounted_observation = None if mounted: intent = getattr(mission, "perception_target", mission.orientation_target)() @@ -704,7 +706,6 @@ def main(): challenge.submit(packet, time.monotonic(), ai.submit) else: ai.submit(*packet) - last_sensor = captured_at if challenge: challenge_events.writelines( json.dumps(e, allow_nan=False) + "\n" for e in challenge.drain_events() diff --git a/simulation/ai-polygon/scheduling_policy.py b/simulation/ai-polygon/scheduling_policy.py index ed072c72..4158d5b3 100644 --- a/simulation/ai-polygon/scheduling_policy.py +++ b/simulation/ai-polygon/scheduling_policy.py @@ -9,7 +9,6 @@ physical simulation time. Acquisition timestamps and freshness stay on wall time import math - SCHEMA = "missioncore.simulation-scheduling/v1" @@ -67,3 +66,30 @@ def build_scheduling_policy(*, continuous, physics_dt, capture_hz, main_loop_hz, freshness_clock="monotonic-wall-time-with-original-capture-timestamps", step_obligations="retain-every-executed-pre-post-and-native-audit", ) + + +class CaptureCadence: + """Admit only the current rendered frame, retaining the requested phase. + + Render jitter may skip deadlines but must not round the capture period up + to an integer number of render frames. Missed slots are discarded; neither + acquisition timestamps nor physics clocks are synthesized or advanced. + """ + + def __init__(self, hz, started_at): + self.period = 1 / _positive(hz, "capture rate") + self.next_at = float(started_at) + self.period + if not math.isfinite(self.next_at): + raise ValueError("Invalid capture start") + + def due(self, captured_at): + if not math.isfinite(captured_at): + raise ValueError("Invalid capture timestamp") + if captured_at < self.next_at: + return False + missed = math.floor((captured_at - self.next_at) / self.period) + self.next_at += (missed + 1) * self.period + # Retain a strict future deadline even at floating-point boundaries. + if self.next_at <= captured_at: + self.next_at += self.period + return True diff --git a/tests/test_capture_cadence.py b/tests/test_capture_cadence.py new file mode 100644 index 00000000..29824b9b --- /dev/null +++ b/tests/test_capture_cadence.py @@ -0,0 +1,44 @@ +"""Render jitter must not silently lower the requested capture rate.""" +import importlib +from pathlib import Path + +import pytest + + +@pytest.fixture +def cadence(monkeypatch): + monkeypatch.syspath_prepend(str(Path(__file__).parents[1] / "simulation/ai-polygon")) + return importlib.import_module("scheduling_policy").CaptureCadence + + +def test_ten_hz_capture_survives_sixteen_hz_render_quantization(cadence): + clock = cadence(10, 0.) + admitted = [i/16 for i in range(1, 161) if clock.due(i/16)] + assert len(admitted) == 100 + assert all(0 <= actual - (i+1)/10 < 1/16 + 1e-9 + for i, actual in enumerate(admitted)) + assert set(round(b-a, 8) for a, b in zip(admitted, admitted[1:], strict=False)) == {.0625, .125} + + +def test_overload_and_pause_discard_missed_slots_without_a_burst(cadence): + clock = cadence(10, 100.) + assert not clock.due(100.05) + assert clock.due(102.035) + assert not clock.due(102.035) + assert not clock.due(102.05) + assert clock.due(102.1) + assert not clock.due(102.1) + # A long operator pause creates no queued frames or catch-up workload. + assert clock.due(500.07) + assert not clock.due(500.08) + assert clock.due(500.11) + + +def test_invalid_clocks_and_rates_are_rejected(cadence): + for rate in (0, -1, float("nan"), float("inf"), True): + with pytest.raises(ValueError): + cadence(rate, 0.) + with pytest.raises(ValueError): + cadence(10, float("nan")) + with pytest.raises(ValueError): + cadence(10, 0.).due(float("nan")) diff --git a/tests/test_nav2_native_admission.py b/tests/test_nav2_native_admission.py index 824f77bd..6034cd15 100644 --- a/tests/test_nav2_native_admission.py +++ b/tests/test_nav2_native_admission.py @@ -97,3 +97,103 @@ def test_refined_detection_subset_is_shared_with_control_without_removing_raw_ra gate.observe(dict(geometry_age_seconds=0.,range_sequence=[1,2], points=np.vstack((gate.geometry[1],[[.525,0.,.5]])))) assert gate.tick(tick)['reason']=='obstacle' + + +@pytest.fixture +def tracked_admission(admission): + gate, now, command, tick = admission + footprint = importlib.import_module('navigation.footprint') + geometry = dict(length_m=1.2, width_m=.6, collision_length_m=1.8, + max_step_m=.1, max_slope_degrees=25., ground_contact=dict( + schema_version='missioncore.ground-contact/v1', model='two-track-bottom-bands', + bands=[dict(side='left', lower_xy_m=[-.4,.2], upper_xy_m=[.3,.3]), + dict(side='right', lower_xy_m=[-.4,-.3], upper_xy_m=[.3,-.2])])) + monitor = footprint.Footprint(geometry) + gate.monitor = gate.support.monitor = monitor + gate.ground_monitor = monitor.ground_envelope() + gate.support.observed_pivots = gate.support.observed_approaches = True + return gate, now, command, tick + + +@pytest.mark.parametrize('command', [(0.,.15),(0.,-.15),(-.1,0.)]) +def test_forbidden_floor_under_overhang_does_not_block_supported_native_escape( + tracked_admission, command): + gate, _, proposal, tick = tracked_admission + record = gate.plans['sample-1'] + physical = np.r_[record['terrain'], [[.75,0.,0.,0.]]] + terrain = physical.copy() + terrain[-1,3] = 1. + request = {**record['value'], 'allow_reverse':command[0]<0, 'continuous':True} + proposal[:] = command + gate.accept(request,record['result'],terrain) + assert gate.tick(tick)['reason'] == 'obstacle' # Reproduces the previous conflation. + gate.accept(request,record['result'],terrain,collision_terrain=physical) + result = gate.tick(tick) + assert result['reason']=='none', result + assert (result['speed_mps'],result['yaw_rate_rps']) == command + assert result['command_source']=='nav2' + + +@pytest.mark.parametrize('source', [ + 'retained-solid','fresh-solid','track-exclusion','unknown-support']) +def test_separated_floor_never_waives_solid_collision_or_ground_safety(tracked_admission,source): + gate, _, command, tick = tracked_admission + record = gate.plans['sample-1'] + physical = np.r_[record['terrain'], [[.75,0.,0.,0.]]] + terrain = physical.copy() + terrain[-1,3] = 1. + command[:] = [0.,.15] + if source=='retained-solid': + physical[-1] = terrain[-1] = [.75,0.,.5,1.] + elif source=='fresh-solid': + gate.observe(dict(geometry_age_seconds=0.,range_sequence=[1,2], + points=np.r_[gate.geometry[1], [[.75,0.,.5]]])) + elif source=='track-exclusion': + physical[-1,:2] = terrain[-1,:2] = [.2,.25] + else: + physical = physical[physical[:,0]>.9] + terrain = terrain[terrain[:,0]>.9] + gate.observe(dict(geometry_age_seconds=0.,range_sequence=[1,2], + points=physical[:,:3])) + gate.accept(record['value'],record['result'],terrain,collision_terrain=physical) + result = gate.tick(tick) + assert result['speed_mps']==result['yaw_rate_rps']==0.,result + if source.endswith('solid'): + assert result['reason']=='obstacle' + if source=='track-exclusion': + assert result['reason']=='forbidden-ground-sweep' + + +def test_new_floor_exclusion_reduces_forward_command(tracked_admission): + gate, _, command, tick = tracked_admission + record = gate.plans['sample-1'] + physical = np.r_[record['terrain'], [[.6,0.,0.,0.]]] + terrain = physical.copy() + terrain[-1,3] = 1. + command[:] = [.1,0.] + gate.accept(record['value'],record['result'],terrain,collision_terrain=physical) + result = gate.tick(tick) + assert 0 <= result['speed_mps'] < .1 and result['yaw_rate_rps']==0.,result + + +def test_legacy_contact_geometry_retains_full_body_surface_veto(admission): + gate, _, command, tick = admission + assert gate.ground_monitor is gate.monitor + record = gate.plans['sample-1'] + physical = np.r_[record['terrain'], [[.4,0.,0.,0.]]] + terrain = physical.copy() + terrain[-1,3] = 1. + command[:] = [0.,.15] + gate.accept(record['value'],record['result'],terrain,collision_terrain=physical) + assert gate.tick(tick)['reason']=='forbidden-ground-sweep' + + +def test_surface_separation_rejects_misaligned_or_lowered_observations(admission): + gate, _, _, _ = admission + record = gate.plans['sample-1'] + terrain = record['terrain'] + for field in (0,3): + altered=terrain.copy() + altered[0,field]+=1 + with pytest.raises(ValueError,match='share the measured terrain'): + gate.accept(record['value'],record['result'],terrain,collision_terrain=altered)