From 51406fc90c00edd7734a7caecc7f96ce602de246 Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Fri, 9 Oct 2026 12:22:26 +0300 Subject: [PATCH] Separate Nav2 body collision from ground search costs --- .../nav2/check_collision_domains.py | 128 ++++++++++++++++++ simulation/ai-polygon/nav2/configuration.py | 5 + .../ai-polygon/nav2/observed_collision.py | 12 +- simulation/ai-polygon/nav2/server.py | 12 +- .../ai_polygon/observed_recovery.py | 11 ++ tests/test_observed_recovery.py | 31 +++++ 6 files changed, 192 insertions(+), 7 deletions(-) create mode 100644 simulation/ai-polygon/nav2/check_collision_domains.py diff --git a/simulation/ai-polygon/nav2/check_collision_domains.py b/simulation/ai-polygon/nav2/check_collision_domains.py new file mode 100644 index 00000000..8fe7ad04 --- /dev/null +++ b/simulation/ai-polygon/nav2/check_collision_domains.py @@ -0,0 +1,128 @@ +"""Bounded native BackUp check on archived observations, without an actuator. + +Captured geometry receives an explicit synthetic ground restriction beneath +future body overhang, with stationary odometry/fresh times. This verifies +native collision plumbing, never route or physical acceptance. +""" +import argparse +import json +import math +import subprocess +import threading +import time +from pathlib import Path + +import numpy as np +import rclpy +import yaml +from action_msgs.msg import GoalStatus +from configuration import observed_configuration +from observed_collision import ObservedCollision +from ros_navigation import RosNavigation, yaw_of + + +def main(): + parser = argparse.ArgumentParser() + for name in ('inputs', 'robot', 'snapshot', 'output'): + parser.add_argument('--'+name, type=Path, required=True) + parser.add_argument('--mixed', action='store_true') + args = parser.parse_args() + args.output.mkdir(exist_ok=False, parents=True) + inputs = json.loads(args.inputs.read_text()) + snapshot = json.loads(args.snapshot.read_text()) + request = snapshot['latest_plan']['request'] + assert request['execution_inputs_sha256'] == inputs['sha256'] + assert not snapshot['current_detected'], 'This recorded fixture has no detections' + request['geometry_age_seconds'] = 0. + physical = np.array(snapshot['geometry']) + search = np.array(snapshot['search_terrain']) + pose = np.asarray(request['pose']); yaw = yaw_of(pose) + axes = np.array([[math.cos(yaw), -math.sin(yaw)], [math.sin(yaw), math.cos(yaw)]]) + local = (search[:, :2]-pose[:2]) @ axes + # A ground restriction 83 cm behind the origin intersects the mounted + # body's predicted reverse sweep, but not the shorter track sweep. + selected = int(np.argmin(np.linalg.norm(local-[-.83, 0.], axis=1))) + assert -.9 < local[selected, 0] < -.78 and abs(local[selected, 1]) < .07 + assert search[selected, 3] <= inputs['robot']['geometry']['max_step_m'] + search[selected, 3] = 1. + synthetic_ground_hint = search[selected].tolist() + config = observed_configuration(inputs, json.loads(args.robot.read_text()), 2) + parameters = args.output/'parameters.yaml' + parameters.write_text(yaml.safe_dump(config, sort_keys=False)) + rclpy.init() + node = RosNavigation() + collision = ObservedCollision(node, inputs['robot']['geometry']['max_step_m'], 2) + running = threading.Event(); running.set() + lock = threading.Lock() + state = dict(physical=search if args.mixed else physical) + errors, commands, processes, logs = [], [], [], [] + spinner = threading.Thread(target=rclpy.spin, args=(node,)) + + def publish(): + try: + while running.is_set(): + node.observe_pose(request['pose'], .01, [0., 0., 0.]) + with lock: + terrain = state['physical'] + assert collision.publish(request, terrain, 0., search_terrain=search) + commands.append(node.native_command()) + time.sleep(.08) + except BaseException as error: + errors.append(str(error)) + + source = threading.Thread(target=publish) + report = dict(passed=False, mixed=args.mixed, authority=None, + scope='Native collision-domain regression; synthetic ground hint on archived range, stationary odometry, no actuator', + synthetic_ground_hint=synthetic_ground_hint) + try: + spinner.start(); source.start() + for package, name in (('nav2_planner', 'planner_server'), + ('nav2_controller', 'controller_server'), + ('nav2_behaviors', 'behavior_server')): + log = (args.output/(name+'.log')).open('w'); logs.append(log) + processes.append(subprocess.Popen([ + '/opt/ndc_nav2/install/'+package+'/lib/'+package+'/'+name, + '--ros-args', '--params-file', str(parameters), '-r', '/cmd_vel:=/nav2/'+ + ('behavior' if package == 'nav2_behaviors' else 'controller')+'_cmd_vel'], + stdout=log, stderr=subprocess.STDOUT)) + node.activate() + time.sleep(.8) + node.backup(.8, .1, 0.) + started = time.monotonic() + while time.monotonic()-started < 6 and not node.terminal.done(): + time.sleep(.08) + report['held_seconds'] = time.monotonic()-started + report['terminal_status'] = node.terminal.result().status if node.terminal.done() else None + report['reverse_samples'] = sum(c is not None and c[1] < 0 for c in commands) + if args.mixed: + assert report['terminal_status'] == GoalStatus.STATUS_ABORTED, report + else: + assert report['terminal_status'] is None and report['reverse_samples'] > 30, report + # An explicit synthetic physical object must still abort native + # BackUp. It is not a semantic hint and cannot be waived by support. + pose = request['pose']; yaw = yaw_of(pose) + obstacle = [pose[0]-.8*math.cos(yaw), pose[1]-.8*math.sin(yaw), pose[2], 1.] + with lock: + state['physical'] = np.vstack((physical, obstacle)) + terminal = node.await_result(node.terminal, 3.) + report['physical_obstacle_status'] = terminal.status + assert terminal.status == GoalStatus.STATUS_ABORTED, report + assert not errors, errors + report['passed'] = True + finally: + running.clear() + if source.is_alive(): source.join(timeout=2) + for process in processes: process.terminate() + for process in processes: + try: process.wait(timeout=3) + except subprocess.TimeoutExpired: process.kill(); process.wait(timeout=3) + for log in logs: log.close() + rclpy.try_shutdown() + if spinner.is_alive(): spinner.join(timeout=2) + node.destroy_node() + (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 c618b2c9..54441299 100644 --- a/simulation/ai-polygon/nav2/configuration.py +++ b/simulation/ai-polygon/nav2/configuration.py @@ -167,4 +167,9 @@ def observed_configuration(inputs, robot, origin_count): costmap.update(rolling_window=True, width=16, height=16, plugins=['obstacle_layer', 'inflation_layer'], obstacle_layer=copy.deepcopy(layer)) + # Global path search retains forbidden/unsafe ground hints. Local DWB + # and native behaviors use the full-body physical collision domain; + # support and surface permission remain hard command-admission gates. + if name == 'global_costmap': + costmap['obstacle_layer']['hazards']['topic'] = '/observed_search_hazards' return config diff --git a/simulation/ai-polygon/nav2/observed_collision.py b/simulation/ai-polygon/nav2/observed_collision.py index e836772c..b0c645f1 100644 --- a/simulation/ai-polygon/nav2/observed_collision.py +++ b/simulation/ai-polygon/nav2/observed_collision.py @@ -32,8 +32,9 @@ class ObservedCollision: self.rays = [node.create_publisher(PointCloud2, '/observed_rays_'+str(i), 2) for i in range(origin_count)] self.hazards = node.create_publisher(PointCloud2, '/observed_hazards', 2) + self.search = node.create_publisher(PointCloud2, '/observed_search_hazards', 2) - def publish(self, request, terrain, elapsed, *, detected=()): + def publish(self, request, terrain, elapsed, *, search_terrain, detected=()): rays = request['range_rays'] age = float(request['geometry_age_seconds'])+elapsed if not math.isfinite(age) or age < 0 or len(rays['origins']) != len(self.rays): @@ -53,9 +54,14 @@ class ObservedCollision: points=[[end[0]-origin[0],end[1]-origin[1]] for end, owner in zip(rays['ends'], rays['origin_indices']) if owner==i] publisher.publish(cloud(stamp,'range'+str(i),points)) - # Both measured hazards and derived clearance costs belong to search. - # Never feed the reserve raster back into raw range or support evidence. + # The body collision map contains physical/detector obstacles. Ground + # permission and rejected support patches are search costs: treating + # them as solid objects blocks an overhanging camera during BackUp/Spin. + # Smac retains both; every native proposal still passes the separate + # full ground-contact/semantic gates before reaching the actuator. hazards = terrain[terrain[:,3]>self.max_step+1e-4,:2] + search = search_terrain[search_terrain[:,3]>self.max_step+1e-4,:2] reserve = self.detector_exclusion.points(detected, request['pose']) self.hazards.publish(cloud(stamp,'map',np.concatenate((hazards,reserve)))) + self.search.publish(cloud(stamp,'map',np.concatenate((search,reserve)))) return True diff --git a/simulation/ai-polygon/nav2/server.py b/simulation/ai-polygon/nav2/server.py index 9330534f..0e7d8ffb 100644 --- a/simulation/ai-polygon/nav2/server.py +++ b/simulation/ai-polygon/nav2/server.py @@ -91,12 +91,15 @@ class Navigation: terminal = self.node.terminal if (key == self.action_key and key[0] in {'path', 'backup'} and terminal is not None and terminal.done() - and terminal.result().status == GoalStatus.STATUS_SUCCEEDED): + and terminal.result().status in (GoalStatus.STATUS_SUCCEEDED, GoalStatus.STATUS_ABORTED)): # Preserve the native terminal result before a sensor refresh can # submit the same FollowPath again. This is local-action completion, # not whole-body arrival admission and never a motion proposal. - return self.reply('native-action-complete', route_observation=route, - action_result=dict(status='succeeded', kind=key[0], goal_xy=list(key[1]))) + succeeded = terminal.result().status == GoalStatus.STATUS_SUCCEEDED + return self.reply('native-action-complete' if succeeded else 'native-action-aborted', + status='waiting-for-plan' if succeeded else 'blocked', route_observation=route, + action_result=dict(status='succeeded' if succeeded else 'aborted', + kind=key[0], goal_xy=list(key[1]))) return None def plan(self, value): @@ -135,7 +138,8 @@ class Navigation: terrain = observed['terrain'] self.latest_terrain = observed observed['observation_id'] = value['observation_id'] - if not self.collision.publish(value, observed['search_terrain'], time.monotonic()-entered, + if not self.collision.publish(value, observed['collision_terrain'], time.monotonic()-entered, + search_terrain=observed['search_terrain'], detected=observed['detected']): return self.reply('stale-range') route = route_observation(terrain, pose, value, self.monitor.max_step) diff --git a/src/k1link/simulation/ai_polygon/observed_recovery.py b/src/k1link/simulation/ai_polygon/observed_recovery.py index 64c6f094..b840a2ec 100644 --- a/src/k1link/simulation/ai_polygon/observed_recovery.py +++ b/src/k1link/simulation/ai_polygon/observed_recovery.py @@ -83,6 +83,17 @@ class ObservedRecovery: # mission arrival. No camera permission is needed to stop an action. self.completion = completion return + if (self.selected is not None and self.selected.get("kind") != "orient" + and result.get("status") == "blocked" + and result.get("speed_mps") == result.get("yaw_rate_rps") == 0. + and completion == dict(status="aborted", + kind="backup" if self.selected["reverse"] else "path", + goal_xy=list(self.selected["goal"][:2]))): + # The bound native action has ended, so waiting cannot produce a + # new command. Retire this option; an abort does not invent an + # obstacle or authorize a replacement manoeuvre. + self.blocked_option = True + return if not self.view_current(pose, seconds): return failure = result.get("diagnostic", {}).get("failure") diff --git a/tests/test_observed_recovery.py b/tests/test_observed_recovery.py index 3c8f7732..505b2745 100644 --- a/tests/test_observed_recovery.py +++ b/tests/test_observed_recovery.py @@ -264,3 +264,34 @@ def test_unbound_or_unsuccessful_result_cannot_complete_local_recovery(mismatch) r.observe_navigation(receipt, position, now, key, run) r.tick(position, now+.1, choose) assert r.active and r.selected == selected + + +@pytest.mark.parametrize('reverse', [False, True]) +@pytest.mark.parametrize('mismatch', [None, 'run', 'time', 'pose', 'option', 'goal', 'kind', + 'missing', 'nonzero', 'status']) +def test_only_bound_native_abort_retires_the_local_option(reverse, mismatch): + r = ObservedRecovery() + r.begin(pose(), 0, []) + selected = dict(goal=[-2. if reverse else 2., 0., 0.], reverse=reverse) + choose = lambda *_: selected + survey(r, pose(), choose) + position, now = pose(), 2. + receipt = completed_path(position, now, selected['goal']) + receipt.update(status='blocked', diagnostic=dict(failure='native-action-aborted')) + receipt['action_result'].update(status='aborted', kind='backup' if reverse else 'path') + key, run = (r.sequence, r.option), 'run' + if mismatch == 'run': run = 'another-run' + elif mismatch == 'time': now += .1 + elif mismatch == 'pose': position = pose(.1) + elif mismatch == 'option': key = (r.sequence, r.option+1) + elif mismatch == 'goal': receipt['action_result']['goal_xy'] = [9., 0.] + elif mismatch == 'kind': receipt['action_result']['kind'] = 'spin' + elif mismatch == 'missing': receipt.pop('action_result') + elif mismatch == 'nonzero': receipt['speed_mps'] = .1 + elif mismatch == 'status': receipt['status'] = 'waiting-for-plan' + r.observe_navigation(receipt, position, now, key, run) + assert r.blocked_option is (mismatch is None) + assert r.completion is None + if mismatch is None: + assert r.tick(position, now+.1, choose)[0] is None + assert r.excluded == [selected['goal']]