From 16865574d01d3026c8022afad4d013d01e494650 Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Fri, 9 Oct 2026 22:15:20 +0300 Subject: [PATCH] Align Nav2 with physics time and preserve complete simulation scenes --- simulation/ai-polygon/continuous_pipeline.py | 8 +- simulation/ai-polygon/loop_profile.py | 28 +++++++ .../ai-polygon/nav2/check_http_integration.py | 10 +++ .../ai-polygon/nav2/check_native_adapter.py | 13 ++- .../ai-polygon/nav2/check_simulation_clock.py | 81 +++++++++++++++++++ simulation/ai-polygon/nav2/configuration.py | 14 ++-- .../ai-polygon/nav2/observed_collision.py | 3 +- simulation/ai-polygon/nav2/ros_navigation.py | 34 ++++++-- simulation/ai-polygon/nav2/server.py | 10 ++- simulation/ai-polygon/process_pipeline.py | 5 +- simulation/ai-polygon/project_assets.py | 38 ++------- simulation/ai-polygon/run_realtime.py | 21 ++++- simulation/ai-polygon/scheduling_policy.py | 18 +++-- tests/test_nav2_configuration.py | 9 +++ tests/test_progressive_perception.py | 35 ++++++++ 15 files changed, 262 insertions(+), 65 deletions(-) create mode 100644 simulation/ai-polygon/loop_profile.py create mode 100644 simulation/ai-polygon/nav2/check_simulation_clock.py diff --git a/simulation/ai-polygon/continuous_pipeline.py b/simulation/ai-polygon/continuous_pipeline.py index 108bc5f2..ec848d87 100644 --- a/simulation/ai-polygon/continuous_pipeline.py +++ b/simulation/ai-polygon/continuous_pipeline.py @@ -92,12 +92,15 @@ class ContinuousPipeline: "simulation_time_ns": simulation_time_ns}) self.condition.notify_all() - def observe_pose(self, pose, speed, captured_at, *, measured_twist=None): + def observe_pose(self, pose, speed, captured_at, *, measured_twist=None, simulation_time_ns=None): # Called from the physics callback: only an in-memory bounded publish. if measured_twist is not None and (len(measured_twist) != 3 or not all(math.isfinite(value) for value in measured_twist)): raise ValueError('Invalid measured planar twist') + if simulation_time_ns is not None and (type(simulation_time_ns) is not int or simulation_time_ns < 0): + raise ValueError('Invalid measured simulation time') with self.condition: + self.pose_simulation_time = (simulation_time_ns, captured_at) self.pose = (list(pose), float(speed), captured_at) self.pose_twist = None if measured_twist is None else (tuple(measured_twist), captured_at) @@ -275,6 +278,7 @@ class ContinuousPipeline: guard = self.route_guard sensor = self.sensor measured_twist = getattr(self, 'pose_twist', None) + pose_simulation_time = getattr(self, 'pose_simulation_time', None) enabled = self.enabled and self.ready intent_revision = self.intent_revision if connection_epoch != epoch: @@ -288,6 +292,8 @@ class ContinuousPipeline: perception_age_seconds=max(0, started-perception[1]["observation"]["captured_at"]), observation_id=result["observation_id"], enabled=result["decision"]["reason"] in {"road", "replanning"}) + if pose_simulation_time is not None and pose_simulation_time[1] == pose[2]: + payload['pose_simulation_time_ns'] = pose_simulation_time[0] if measured_twist is not None and measured_twist[1] == pose[2]: payload['measured_twist'] = list(measured_twist[0]) range_identity = sensor[:2] if sensor is not None else None diff --git a/simulation/ai-polygon/loop_profile.py b/simulation/ai-polygon/loop_profile.py new file mode 100644 index 00000000..7300c1be --- /dev/null +++ b/simulation/ai-polygon/loop_profile.py @@ -0,0 +1,28 @@ +"""Bounded stage-cost evidence; no scheduling or motion authority.""" +from collections import defaultdict, deque +import math + + +class LoopProfile: + def __init__(self): + self.samples = defaultdict(lambda: deque(maxlen=600)) + self.last_report = None + + def add(self, stage, seconds): + if math.isfinite(seconds) and seconds >= 0: + self.samples[stage].append(seconds*1000) + + def due(self, now): + return self.last_report is None or now-self.last_report >= 5 + + def report(self, now): + self.last_report = now + result = {} + for stage, values in self.samples.items(): + values = sorted(values) + if values: + result[stage] = dict(samples=len(values), mean_ms=sum(values)/len(values), + p50_ms=values[len(values)//2], p95_ms=values[math.ceil(.95*len(values))-1], + max_ms=values[-1]) + return dict(schema_version='missioncore.loop-profile/v1', monotonic=now, + scope='rolling stage costs; app update includes physics callbacks', stages=result) diff --git a/simulation/ai-polygon/nav2/check_http_integration.py b/simulation/ai-polygon/nav2/check_http_integration.py index 9bc59d78..79e94902 100644 --- a/simulation/ai-polygon/nav2/check_http_integration.py +++ b/simulation/ai-polygon/nav2/check_http_integration.py @@ -38,7 +38,17 @@ def main(): state=dict(enabled=False,observation_id='bootstrap') responses=[];errors=[];running=threading.Event();running.set() + clock_started = time.monotonic() + def request(path,value=None): + # Explicit synthetic clock for this isolated, stationary-odometry check. + # Production obtains these fields only from completed physics steps. + seconds = 10 + time.monotonic()-clock_started + if path == '/control': + value = {**value, 'pose_simulation_time_ns': round(seconds*1e9)} + elif path == '/plan': + value = {**value, 'simulation_time_seconds': seconds} + client=http.client.HTTPConnection('127.0.0.1',args.port,timeout=2) try: client.request('GET' if value is None else 'POST',path, diff --git a/simulation/ai-polygon/nav2/check_native_adapter.py b/simulation/ai-polygon/nav2/check_native_adapter.py index 575bace6..fad27c1a 100644 --- a/simulation/ai-polygon/nav2/check_native_adapter.py +++ b/simulation/ai-polygon/nav2/check_native_adapter.py @@ -23,12 +23,14 @@ def main(): parser = argparse.ArgumentParser() for name in ('inputs', 'robot', 'output'): parser.add_argument('--' + name, type=Path, required=True) + parser.add_argument('--simulation-clock', action='store_true') args = parser.parse_args() args.output.mkdir(exist_ok=False, parents=True) - config = configuration(json.loads(args.inputs.read_text()), json.loads(args.robot.read_text())) + config = configuration(json.loads(args.inputs.read_text()), json.loads(args.robot.read_text()), + use_sim_time=args.simulation_clock) path = args.output/'parameters.yaml'; path.write_text(yaml.safe_dump(config, sort_keys=False)) rclpy.init() - fixture, bridge = Check(), RosNavigation() + fixture, bridge = Check(), RosNavigation(simulation_clock=args.simulation_clock) measured = [] fixture.create_subscription(Odometry, '/odom', lambda value: measured.append([ value.twist.twist.linear.x, value.twist.twist.linear.y, @@ -42,10 +44,13 @@ def main(): continuous_updates = threading.Event() continuity_samples = [] + clock_started = time.monotonic() + def measurements(): try: while running.is_set(): - bridge.observe_pose(pose, .01, [.03, -.005, .012]) + bridge.observe_pose(pose, .01, [.03, -.005, .012], + round((10 + time.monotonic()-clock_started)*1e9) if args.simulation_clock else None) if continuous_updates.is_set(): continuity_samples.append(bridge.native_command()) time.sleep(.04) @@ -54,7 +59,7 @@ def main(): source = threading.Thread(target=measurements) processes, logs = [], [] - report = dict(qualified=False, scope='native ROS action/odometry integration', passed=False) + report = dict(simulation_clock=args.simulation_clock, qualified=False, scope='native ROS action/odometry integration', passed=False) try: fixture.map_case('free') # map_case uses spin_once for initial map publication; that helper diff --git a/simulation/ai-polygon/nav2/check_simulation_clock.py b/simulation/ai-polygon/nav2/check_simulation_clock.py new file mode 100644 index 00000000..e6de8451 --- /dev/null +++ b/simulation/ai-polygon/nav2/check_simulation_clock.py @@ -0,0 +1,81 @@ +"""Real ROS clock/odometry check; synthetic measurements, no actuator authority.""" +import argparse +import json +import math +import threading +import time +from pathlib import Path + +import rclpy +from nav_msgs.msg import Odometry +from rclpy.executors import MultiThreadedExecutor +from rclpy.node import Node +from rclpy.parameter import Parameter +from ros_navigation import RosNavigation + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--output', type=Path, required=True) + args = parser.parse_args() + args.output.mkdir(parents=True, exist_ok=False) + rclpy.init() + bridge = RosNavigation(simulation_clock=True) + observer = Node('clock_check', parameter_overrides=[Parameter('use_sim_time', value=True)]) + rows = [] + observer.create_subscription(Odometry, '/odom', lambda m: rows.append(dict( + stamp=m.header.stamp.sec*10**9+m.header.stamp.nanosec, + x=m.pose.pose.position.x, vx=m.twist.twist.linear.x)), 20) + executor = MultiThreadedExecutor(num_threads=2) + executor.add_node(bridge); executor.add_node(observer) + spinner = threading.Thread(target=executor.spin); spinner.start() + report = dict(passed=False, qualified=False, scope='ROS timestamps at variable pacing and pause') + stamp = 10_000_000_000 + try: + time.sleep(.3) + for rate in (.4, 1., 2.): + for _ in range(12): + stamp += 50_000_000 + bridge.observe_pose([.4*stamp/1e9, 0., .37, 0., 0., 0., 1.], .013, + [.4, 0., 0.], stamp) + time.sleep(.05/rate) + time.sleep(.1) + assert observer.get_clock().now().nanoseconds == stamp + # Late delivery must not rewind the source clock or renew old odometry. + before = bridge.pose + bridge.observe_pose([0.,0.,.37,0.,0.,0.,1.], 0., [.4,0.,0.], stamp-1) + assert bridge.pose == before + paused = observer.get_clock().now().nanoseconds + time.sleep(.65) + assert observer.get_clock().now().nanoseconds == paused + count = len(rows); bridge.publish_pose(); time.sleep(.1) + assert len(rows) == count, 'Wall-stale measurement was republished at frozen sim time' + unique = {r['stamp']: r for r in rows} + ordered = [unique[k] for k in sorted(unique)] + assert len(ordered) >= 30 + residuals = [abs((b['x']-a['x'])/((b['stamp']-a['stamp'])/1e9)-a['vx']) + for a,b in zip(ordered, ordered[1:])] + assert max(residuals) < 1e-10 + assert all(math.isfinite(r['x']) for r in ordered) + sample = bridge.observation_stamp(10.5, .9) + assert sample.sec*10**9+sample.nanosec == 10_500_000_000 + try: + bridge.observe_pose([0.,0.,.37,0.,0.,0.,1.], 0., [0.,0.,0.]) + raise AssertionError('Missing physics time was accepted') + except ValueError: + pass + report.update(passed=True, unique_measurements=len(ordered), pacing_factors=[.4,1.,2.], + maximum_velocity_stamp_residual=max(residuals), pause_preserved=True, + stale_pose_expired_by_wall_time=True, source_stamp_preserved=True) + except BaseException as error: + report['error'] = type(error).__name__+': '+str(error) + raise + finally: + executor.shutdown(timeout_sec=2); spinner.join(timeout=2) + bridge.destroy_node(); observer.destroy_node(); rclpy.shutdown() + (args.output/'result.json').write_text(json.dumps(report,indent=2)+'\n') + print(json.dumps(report)) + + +if __name__ == '__main__': + main() diff --git a/simulation/ai-polygon/nav2/configuration.py b/simulation/ai-polygon/nav2/configuration.py index 0dce2c4e..7c6029df 100644 --- a/simulation/ai-polygon/nav2/configuration.py +++ b/simulation/ai-polygon/nav2/configuration.py @@ -15,7 +15,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from rig_collision import collision_geometry # noqa: E402 -def configuration(inputs, robot): +def configuration(inputs, robot, *, use_sim_time=False): body = {key: value for key, value in inputs.items() if key != 'sha256'} actual = hashlib.sha256(json.dumps(body, sort_keys=True, separators=(',', ':'), allow_nan=False).encode()).hexdigest() @@ -36,7 +36,7 @@ def configuration(inputs, robot): raise ValueError('Invalid rover envelope') footprint = json.dumps([[x, y], [-x, y], [-x, -y], [x, -y]]) costmap = dict( - use_sim_time=False, global_frame='map', robot_base_frame='base_link', + use_sim_time=use_sim_time, global_frame='map', robot_base_frame='base_link', update_frequency=10.0, publish_frequency=5.0, resolution=0.05, rolling_window=False, track_unknown_space=True, footprint=footprint, footprint_padding=0.05, transform_tolerance=0.2, @@ -61,7 +61,7 @@ def configuration(inputs, robot): heading_bins = max(8, 4 * math.ceil((2 * math.pi / angle_step) / 4)) return { 'behavior_server': {'ros__parameters': dict( - use_sim_time=False, global_frame='map', robot_base_frame='base_link', + use_sim_time=use_sim_time, global_frame='map', robot_base_frame='base_link', costmap_topic='local_costmap/costmap_raw', footprint_topic='local_costmap/published_footprint', cycle_frequency=20.0, transform_tolerance=0.2, @@ -73,7 +73,7 @@ def configuration(inputs, robot): rotational_acc_lim=2*acceleration/track_width, )}, 'planner_server': {'ros__parameters': dict( - use_sim_time=False, expected_planner_frequency=5.0, planner_plugins=['GridBased'], + use_sim_time=use_sim_time, expected_planner_frequency=5.0, planner_plugins=['GridBased'], GridBased=dict(plugin='nav2_smac_planner/SmacPlannerHybrid', motion_model_for_search='DUBIN', # Retain the former differential lattice's 0.5 m @@ -85,7 +85,7 @@ def configuration(inputs, robot): cache_obstacle_heuristic=False, smooth_path=False), )}, 'controller_server': {'ros__parameters': dict( - use_sim_time=False, controller_frequency=20.0, odom_topic='/odom', + use_sim_time=use_sim_time, controller_frequency=20.0, odom_topic='/odom', min_x_velocity_threshold=0.001, min_y_velocity_threshold=0.001, min_theta_velocity_threshold=0.001, failure_tolerance=0.0, progress_checker_plugin='progress_checker', goal_checker_plugins=['goal_checker'], @@ -143,7 +143,7 @@ def configuration(inputs, robot): } -def observed_configuration(inputs, robot, origin_count): +def observed_configuration(inputs, robot, origin_count, *, use_sim_time=False): """Use upstream ray clearing/obstacle marking for a rolling collision map. Ground support and surface permission are separate inputs/gates. In @@ -151,7 +151,7 @@ def observed_configuration(inputs, robot, origin_count): """ if type(origin_count) is not int or not 1 <= origin_count <= 16: raise ValueError('Invalid observed sensor origin count') - config = configuration(inputs, robot) + config = configuration(inputs, robot, use_sim_time=use_sim_time) sources = { 'hazards': dict(topic='/observed_hazards', data_type='PointCloud2', sensor_frame='base_link', marking=True, clearing=False, diff --git a/simulation/ai-polygon/nav2/observed_collision.py b/simulation/ai-polygon/nav2/observed_collision.py index b0c645f1..5bfb27de 100644 --- a/simulation/ai-polygon/nav2/observed_collision.py +++ b/simulation/ai-polygon/nav2/observed_collision.py @@ -9,7 +9,6 @@ import struct import numpy as np from detector_exclusion import DetectorExclusion from geometry_msgs.msg import TransformStamped -from rclpy.time import Time from sensor_msgs.msg import PointCloud2, PointField @@ -41,7 +40,7 @@ class ObservedCollision: raise ValueError('Invalid observed collision age/origins') if age > .8: return False - stamp = Time(nanoseconds=self.node.get_clock().now().nanoseconds-int(age*1e9)).to_msg() + stamp = self.node.observation_stamp(request['simulation_time_seconds'], age) transforms=[] for i, origin in enumerate(rays['origins']): tf = TransformStamped() diff --git a/simulation/ai-polygon/nav2/ros_navigation.py b/simulation/ai-polygon/nav2/ros_navigation.py index b75f246c..923ea466 100644 --- a/simulation/ai-polygon/nav2/ros_navigation.py +++ b/simulation/ai-polygon/nav2/ros_navigation.py @@ -20,6 +20,8 @@ from nav2_msgs.msg import Costmap from nav_msgs.msg import Odometry from rclpy.action import ActionClient from rclpy.node import Node +from rclpy.parameter import Parameter +from rosgraph_msgs.msg import Clock from rclpy.time import Time from tf2_ros import TransformBroadcaster @@ -30,8 +32,11 @@ def yaw_of(pose): class RosNavigation(Node): - def __init__(self): - super().__init__('missioncore_nav2_adapter') + def __init__(self, *, simulation_clock=False): + super().__init__('missioncore_nav2_adapter', parameter_overrides=[ + Parameter('use_sim_time', value=simulation_clock)]) + self.simulation_clock = simulation_clock + self.clock_publisher = self.create_publisher(Clock, '/clock', 1) if simulation_clock else None self.condition = threading.Condition() self.action_lock = threading.Lock() self.pose = None @@ -100,21 +105,38 @@ class RosNavigation(Node): if not client.wait_for_server(timeout_sec=2): raise TimeoutError('Nav2 action unavailable') - def observe_pose(self, pose, age, twist=None): + def observe_pose(self, pose, age, twist=None, simulation_time_ns=None): if (len(pose) != 7 or (twist is not None and len(twist) != 3) or not all(math.isfinite(float(v)) for v in (*pose, *(twist or []), age)) or age < 0 or abs(sum(v*v for v in pose[3:])-1) > .02): raise ValueError('Invalid measured odometry') now = time.monotonic() - stamp = self.get_clock().now().nanoseconds-int(age*1e9) + if self.simulation_clock: + if type(simulation_time_ns) is not int or not 0 <= simulation_time_ns < 2**63: + raise ValueError('Measured simulation time is required for odometry') + stamp = simulation_time_ns + else: + stamp = self.get_clock().now().nanoseconds-int(age*1e9) if stamp < 0: raise ValueError('Invalid odometry stamp') with self.condition: captured = now-age - if self.pose is None or captured >= self.pose[0]: - self.pose = (captured, tuple(pose), tuple(twist) if twist is not None else None, stamp) + if self.pose is not None and (captured < self.pose[0] or stamp < self.pose[3]): + return # Delayed delivery cannot rewind TF or the episode clock. + self.pose = (captured, tuple(pose), tuple(twist) if twist is not None else None, stamp) + if self.clock_publisher is not None: + # Physics owns time. Repeated measurements at pause never advance + # it; HTTP age and all transport/action waits remain wall time. + self.clock_publisher.publish(Clock(clock=Time(nanoseconds=stamp).to_msg())) self.publish_pose() + def observation_stamp(self, seconds, wall_age): + if self.simulation_clock: + if not math.isfinite(seconds) or seconds < 0: + raise ValueError('Invalid observed simulation time') + return Time(nanoseconds=round(seconds*1e9)).to_msg() + return Time(nanoseconds=self.get_clock().now().nanoseconds-int(wall_age*1e9)).to_msg() + def publish_pose(self): with self.condition: measured = self.pose diff --git a/simulation/ai-polygon/nav2/server.py b/simulation/ai-polygon/nav2/server.py index d8109f4b..16ede6d2 100644 --- a/simulation/ai-polygon/nav2/server.py +++ b/simulation/ai-polygon/nav2/server.py @@ -75,7 +75,8 @@ class Navigation: return self.node.native_command() def tick(self, value): - self.node.observe_pose(value['pose'], float(value['pose_age_seconds']), value['measured_twist']) + self.node.observe_pose(value['pose'], float(value['pose_age_seconds']), value['measured_twist'], + value.get('pose_simulation_time_ns')) with self.owner_lock: owner = self.command_generation result = self.control.tick(value) @@ -149,7 +150,8 @@ class Navigation: return self.reply('stale-observation') self.control.observe(value) if self.node.pose is None: - self.node.observe_pose(value['pose'], age) # TF only; no invented velocity. + self.node.observe_pose(value['pose'], age, None, + round(value['simulation_time_seconds']*1e9)) # TF only. if not self.activating: self.activating = True threading.Thread(target=self.activate, daemon=True).start() @@ -321,11 +323,11 @@ def main(): inputs = json.loads(Path(os.environ['MISSIONCORE_RUN_INPUTS']).read_text()) root = Path(__file__).resolve().parents[1] robot = json.loads((root/'robots'/ (inputs['robot']['robot_id']+'.json')).read_text()) - config = observed_configuration(inputs, robot, 2) # Mounted K1 and depth origins. + config = observed_configuration(inputs, robot, 2, use_sim_time=True) # Mounted K1 and depth origins. parameters = Path('/tmp/missioncore-nav2.yaml') parameters.write_text(yaml.safe_dump(config, sort_keys=False)) rclpy.init() - node = RosNavigation() + node = RosNavigation(simulation_clock=True) navigation = Navigation(node, inputs, robot) thread = threading.Thread(target=rclpy.spin, args=(node,), daemon=True); thread.start() terrain_reset = node.create_client(Trigger, '/terrain/reset') diff --git a/simulation/ai-polygon/process_pipeline.py b/simulation/ai-polygon/process_pipeline.py index b02f699e..6894bbd6 100644 --- a/simulation/ai-polygon/process_pipeline.py +++ b/simulation/ai-polygon/process_pipeline.py @@ -67,8 +67,10 @@ def run_pipeline(factory, arguments, directory, incoming, outgoing, stop): if message['pose'] is not None: pose, speed, stamp = message['pose'] twist = message['twist'] + simulated = message['pose_simulation_time'] pipeline.observe_pose(pose, speed, stamp, measured_twist=( - twist[0] if twist is not None and twist[1] == stamp else None)) + twist[0] if twist is not None and twist[1] == stamp else None), + simulation_time_ns=simulated[0] if simulated is not None and simulated[1] == stamp else None) packet = message['sensor'] if packet is not None and packet[0] == pipeline.epoch: _, frame, observation = packet @@ -137,6 +139,7 @@ class ProcessPipeline(ContinuousPipeline): identity = self.sensor[:2] if self.sensor is not None else None message = dict(epoch=self.epoch, enabled=self.enabled, pose=self.pose, twist=getattr(self, 'pose_twist', None), + pose_simulation_time=getattr(self, 'pose_simulation_time', None), sensor=self.sensor if identity != sent_sensor else None) try: self.incoming.put(message, timeout=.05) diff --git a/simulation/ai-polygon/project_assets.py b/simulation/ai-polygon/project_assets.py index 8d5e90be..b3403352 100644 --- a/simulation/ai-polygon/project_assets.py +++ b/simulation/ai-polygon/project_assets.py @@ -1,4 +1,4 @@ -"""Prepare a bounded mission region from an existing Gaussian Pipeline package. +"""Prepare the complete visual scene from an existing Gaussian Pipeline package. Uses the installed SplatTransform, preserves LOD0 and SH, and reuses verified Worker artifacts. The local editor and Isaac share the same collider bytes and @@ -83,23 +83,11 @@ def prepare_project(client, run, state, episode, job, pulse, isaac): collider = root / package["collision_path"] if not visual.is_file() or not collider.is_file(): raise ValueError("Incomplete project scene") - # Keep 12 m of surrounding visual context in every direction. A saved route - # bounds the adaptation. Retain LOD0 and all SH bands without a count ceiling. - points = run["plan"]["points"] - prior = run["plan"].get("prepared_route") - if prior: - # A curved A/B route needs its entire preview, not just its endpoints. - # Unselected graph branches must not force the whole city into RTX. - # Long detours outside this visual region require spatial streaming; - # the graph never substitutes for live support in such an area. - points = points + [{"position": p} for p in prior["preview_xyz"]] - xyz = [[p["position"][0], p["position"][2], -p["position"][1]] for p in points] - bounds = [min(p[i] for p in xyz) - 12 for i in range(3)] + [ - max(p[i] for p in xyz) + 12 for i in range(3) - ] + # The route is guidance, not permission to remove the rest of the world. + # Adapt the complete selected source LOD and preserve every SH coefficient. key = hashlib.sha256( json.dumps( - {"world": world["sha256"], "bounds": bounds, "adapter": digest(Path(__file__)), "region_adapter": digest(Path(__file__).with_name("route_region.py"))}, + {"world": world["sha256"], "coverage": "complete-source-lod0", "adapter": digest(Path(__file__))}, sort_keys=True, ).encode() ).hexdigest() @@ -119,7 +107,7 @@ def prepare_project(client, run, state, episode, job, pulse, isaac): raise RuntimeError("Installed SOG converter is unavailable") temporary = root / (key + ".part.ply") # SplatTransform uses Rz(180) for PLY/SOG input/output conventions. - # Work and crop in the calibrated PlayCanvas Y-up frame, then retain + # Work in the calibrated PlayCanvas Y-up frame, then retain # that frame in the output PLY. Isaac applies the declared Rx(90). command = [ node, @@ -137,20 +125,11 @@ def prepare_project(client, run, state, episode, job, pulse, isaac): "0,0,180", "-r", ",".join(map(str, scene["visual_rotation"])), - "-B", - ",".join(map(str, bounds)), "-r", "0,0,180", str(temporary), ] commands = [command] - filtered = temporary.with_suffix(".region.ply") - if prior: - region = episode / "visual-region.json" - write_json(region, {"route_xz": [[p[0],-p[1]] for p in prior["preview_xyz"]], - "radius_m": 12, "authority": "visual-context-only"}) - commands.append([str(isaac / "python.bat"), str(Path(__file__).with_name("route_region.py")), - "--source",str(temporary),"--output",str(filtered),"--region",str(region)]) with (episode / "project-preparation.log").open("wb") as log: for command in commands: process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT) @@ -168,13 +147,11 @@ def prepare_project(client, run, state, episode, job, pulse, isaac): if process.poll() is None: from worker import terminate_episode terminate_episode(process) - if prior: - filtered.replace(temporary) with temporary.open("rb") as f: header = f.read(65536).split(b"end_header", 1)[0].decode("ascii") count = int(re.search(r"element vertex (\d+)", header)[1]) if count <= 0: - raise ValueError("Prepared mission region is empty") + raise ValueError("Prepared visual scene is empty") temporary.replace(output) write_json( receipt, @@ -182,7 +159,8 @@ def prepare_project(client, run, state, episode, job, pulse, isaac): "sha256": digest(output), "gaussian_count": count, "lod": 0, - "bounds_y_up": bounds, + "coverage": "complete-source-lod0", + "spatially_cropped": False, "source_sha256": world["sha256"], "converter": "splat-transform-3.4.0", "decimated": False, diff --git a/simulation/ai-polygon/run_realtime.py b/simulation/ai-polygon/run_realtime.py index 0534ee30..1bc08232 100644 --- a/simulation/ai-polygon/run_realtime.py +++ b/simulation/ai-polygon/run_realtime.py @@ -26,6 +26,8 @@ def main(): parser.add_argument("--source", type=Path, required=True) parser.add_argument("--stream-address", required=True) parser.add_argument("--no-stream", action="store_true", help="Qualify sensors without WebRTC") + parser.add_argument('--catch-up-mode', choices=['sensor-period-catchup', 'render-period-catchup'], + default='sensor-period-catchup', help='Native scheduling qualification') args, _ = parser.parse_known_args() root = Path(__file__).resolve().parents[2] sys.path.insert(0, str(root / "src")) @@ -324,7 +326,8 @@ def main(): mission = mission_for_inputs(execution_inputs) continuous = rig["schema_version"] == "missioncore.simulation-sensor-rig/v4" scheduling = build_scheduling_policy(continuous=continuous, physics_dt=1/60, - capture_hz=SENSOR_HZ, main_loop_hz=30) + capture_hz=SENSOR_HZ, main_loop_hz=30, + catch_up_mode=args.catch_up_mode) config.set("/persistent/simulation/minFrameRate", scheduling["min_simulation_frame_rate_hz"]) if config.get("/persistent/simulation/minFrameRate") != scheduling["min_simulation_frame_rate_hz"]: @@ -358,6 +361,8 @@ def main(): envelope, chassis_feedback = motion_control.envelope, motion_control.feedback state = {"velocity": 0.0, "yaw_rate": 0.0, "stop_reason": "paused", "decision": None} physics_rows = [] + from loop_profile import LoopProfile + loop_profile = LoopProfile() physics_seconds = 0.0 from motion_metrics import PlanarDistance, planar_twist travelled = PlanarDistance() @@ -478,7 +483,8 @@ def main(): if continuous: heading = state['transform'].TransformDir(Gf.Vec3d(1, 0, 0)) ai.observe_pose(state["pose"], state["speed"], time.monotonic(), measured_twist= - planar_twist(state['body_velocity'], state['body_angular_velocity'], heading)) + planar_twist(state['body_velocity'], state['body_angular_velocity'], heading), + simulation_time_ns=round(physics_seconds * 1e9)) if track_motion: track_motion.advance(dt, *drive.side_speeds()) unstable |= inclination(state["pose"]) >= PROFILE["stop_tilt_degrees"] @@ -517,6 +523,7 @@ def main(): def guarded(callback): def invoke(dt, context): + began = time.perf_counter() try: callback(dt, context) except Exception: @@ -525,6 +532,8 @@ def main(): callback_errors.append(traceback.format_exc()) ai.enable(False) drive.command(0.0, 0.0) + finally: + loop_profile.add(callback.__name__, time.perf_counter()-began) return invoke @@ -606,7 +615,9 @@ def main(): # Apply fixtures before rendering so RGB and range observe the # same environment. Never mutate the rover or its controller. challenge.tick(time.monotonic(), obstacle) + began_update = time.perf_counter() app.update() # Never waits for inference, a network request, or an operator ACK. + loop_profile.add('app_update_inclusive', time.perf_counter()-began_update) if track_motion: track_motion.publish() if callback_errors: @@ -621,11 +632,13 @@ def main(): velocity, yaw_rate = state["velocity"], state["yaw_rate"] stop_reason, decision = state["stop_reason"], state["decision"] if physics_rows: + began_journal = time.perf_counter() physics_motion.writelines( json.dumps(row, allow_nan=False) + "\n" for row in physics_rows ) physics_rows.clear() physics_motion.flush() + loop_profile.add('physics_journal', time.perf_counter()-began_journal) physics = SimulationManager.get_num_physics_steps() sim_ns = round((physics - baseline) * 1e9 / 60) if playing and capture_cadence.due(captured_at): @@ -654,6 +667,8 @@ def main(): else range_sensor.capture(eye, transform, rear_eye) ) range_ready_at = time.monotonic() + loop_profile.add('range_capture', range_ready_at-rgb_ready_at) + loop_profile.add('rgb_read', rgb_ready_at-captured_at) if obstacle and challenge.started is not None: challenge.record( "obstacle-observation", @@ -711,6 +726,8 @@ def main(): json.dumps(e, allow_nan=False) + "\n" for e in challenge.drain_events() ) challenge_events.flush() + if loop_profile.due(captured_at): + write_json(directory / 'loop-profile.json', loop_profile.report(captured_at)) if captured_at - last_report >= 0.25: prior_at, prior_render, prior_sensor, prior_ai, prior_physics = prior_metrics elapsed = captured_at - prior_at diff --git a/simulation/ai-polygon/scheduling_policy.py b/simulation/ai-polygon/scheduling_policy.py index 4158d5b3..2a1f3006 100644 --- a/simulation/ai-polygon/scheduling_policy.py +++ b/simulation/ai-polygon/scheduling_policy.py @@ -19,20 +19,21 @@ def _positive(value, name): def build_scheduling_policy(*, continuous, physics_dt, capture_hz, main_loop_hz, - catch_up_mode="render-period-catchup"): - """Derive a native integer clamp from the declared main-loop cadence. + catch_up_mode="sensor-period-catchup"): + """Bound native catch-up by one sensor acquisition period, not display FPS. - For fractional main-loop rates, round only the native setting upward; + For fractional acquisition/display rates, round only the native setting upward; the requested loop and sensor cadences are unchanged. The ceil step bound is a conservative runtime guard, not a promise that every update executes that - many steps. 60Hz physics/30Hz main loop gives an exact two-step cap. + many steps. 60Hz physics/10Hz sensing gives a six-step cap. Display-rate catch-up + remains available for qualification against the previous two-step clamp. Explicit legacy-wall-catchup permits a same-build continuous A/B comparison; noncontinuous execution always retains the legacy one-Hz clamp. Existing execution-input validation owns the supported capture-rate range. """ if type(continuous) is not bool: raise ValueError("Invalid scheduling continuous mode") - if catch_up_mode not in ("render-period-catchup", "legacy-wall-catchup"): + if catch_up_mode not in ("sensor-period-catchup", "render-period-catchup", "legacy-wall-catchup"): raise ValueError("Invalid scheduling catch-up mode") physics_dt = _positive(physics_dt, "physics dt") capture_hz = _positive(capture_hz, "capture rate") @@ -40,7 +41,8 @@ def build_scheduling_policy(*, continuous, physics_dt, capture_hz, main_loop_hz, physics_hz = _positive(1 / physics_dt, "physics rate") effective_mode = catch_up_mode if continuous else "legacy-wall-catchup" render_period = effective_mode == "render-period-catchup" - minimum = math.ceil(main_loop_hz) if render_period else 1 + sensor_period = effective_mode == "sensor-period-catchup" + minimum = math.ceil(capture_hz) if sensor_period else math.ceil(main_loop_hz) if render_period else 1 maximum_steps = math.ceil(physics_hz / minimum) return dict( schema_version=SCHEMA, @@ -58,8 +60,8 @@ def build_scheduling_policy(*, continuous, physics_dt, capture_hz, main_loop_hz, max_physics_steps_per_update=maximum_steps, max_requested_physics_interval_seconds=1 / minimum, max_integrated_seconds_per_update=maximum_steps * physics_dt, - derivation=("ceil-main-loop-rate" if render_period else "legacy-one-hz-clamp"), - native_rate_rounding=("up-to-integer" if render_period else "none"), + derivation=("ceil-sensor-rate" if sensor_period else "ceil-main-loop-rate" if render_period else "legacy-one-hz-clamp"), + native_rate_rounding=("up-to-integer" if sensor_period or render_period else "none"), step_bound_rounding="ceil-conservative-verify-native-counts", overload_policy="discard-excess-wall-time-demand-and-report-lower-rtf", simulation_clock="sum-completed-physics-dt", diff --git a/tests/test_nav2_configuration.py b/tests/test_nav2_configuration.py index 81fed4e4..223d2ec3 100644 --- a/tests/test_nav2_configuration.py +++ b/tests/test_nav2_configuration.py @@ -72,3 +72,12 @@ def test_clearance_potential_spans_the_local_intent_horizon(configured): cost = lambda d: 252*math.exp(-layer['cost_scaling_factor']*d) assert cost(1.) > cost(2.) > cost(3.) > 1. assert grid['footprint_padding'] == .05 and grid['track_unknown_space'] + + +def test_simulation_clock_reaches_every_native_node_and_costmap(configured): + configure, inputs, robot = configured + config = configure(inputs, robot, use_sim_time=True) + for name in ('planner_server', 'controller_server', 'behavior_server'): + assert config[name]['ros__parameters']['use_sim_time'] is True + for name in ('global_costmap', 'local_costmap'): + assert config[name][name]['ros__parameters']['use_sim_time'] is True diff --git a/tests/test_progressive_perception.py b/tests/test_progressive_perception.py index 1396d15c..b1630ddf 100644 --- a/tests/test_progressive_perception.py +++ b/tests/test_progressive_perception.py @@ -118,3 +118,38 @@ def test_recovery_acknowledges_the_side_capture_pose_and_time(modules): assert submitted[0]["source.pose"] == live["pose"] assert submitted[0]["source.camera.lens-depths"] == front["lens_depths"] assert [v["lens_depths"] for v in submitted[0]["source.detection-views"]] == [[1.], [2.]] + + +def test_controller_uses_physics_stamp_but_wall_time_freshness(modules, monkeypatch, tmp_path): + _, module = modules + import numpy as np + pipeline = module.ContinuousPipeline(None, tmp_path, clock=lambda: 100.) + pipeline.enable(True) + pipeline.ready = True + pipeline.model = SimpleNamespace(inputs={"sha256": "inputs"}) + pipeline.await_model = lambda: True + pipeline.observe_pose([1, 0, 0, 0, 0, 0, 1], .4, 99.95, + measured_twist=(.4, 0, 0), simulation_time_ns=25_000_000_000) + pipeline.perception = (pipeline.epoch, {"observation": {"captured_at": 99.6}}) + pipeline.sensor = (pipeline.epoch, 1, {"captured_at": 99.9, "points": np.zeros((0, 3))}) + pipeline.result = {"observation_id": "live", "captured_at": 99.8, + "decision": {"reason": "road"}} + sent = [] + class Connection: + def close(self): pass + def request(self, path, payload): + sent.append((path, payload)) + pipeline.closed = True + return dict(reason="none", observation_id="live", speed_mps=.4, yaw_rate_rps=0) + monkeypatch.setattr(module, "NavigationClient", Connection) + pipeline.control_loop() + path, payload = sent[0] + assert path == "/control" + assert payload["pose_simulation_time_ns"] == 25_000_000_000 + assert payload["pose_age_seconds"] == pytest.approx(.05) + assert payload["perception_age_seconds"] == pytest.approx(.4) + assert payload["measured_twist"] == [.4, 0, 0] + import json + record = json.loads((tmp_path / "controller.jsonl").read_text()) + assert record["expires_at"] == pytest.approx(100.25) + assert record["freshness_deadlines"]["range"] == pytest.approx(100.7)