From ac980912e0c8936deeda813d8bf2af96bd5ca5f1 Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Sat, 10 Oct 2026 08:29:26 +0300 Subject: [PATCH] Plan translation before choosing motion toward a local goal --- .../ai-polygon/nav2/differential_motion.py | 66 --------- simulation/ai-polygon/nav2/server.py | 38 +---- .../simulation/ai_polygon/composition.py | 2 +- tests/test_nav2_detector_reserve.py | 58 ++++++++ tests/test_nav2_differential_motion.py | 140 ------------------ tests/test_nav2_route_support.py | 43 ++++-- 6 files changed, 98 insertions(+), 249 deletions(-) delete mode 100644 simulation/ai-polygon/nav2/differential_motion.py create mode 100644 tests/test_nav2_detector_reserve.py delete mode 100644 tests/test_nav2_differential_motion.py diff --git a/simulation/ai-polygon/nav2/differential_motion.py b/simulation/ai-polygon/nav2/differential_motion.py deleted file mode 100644 index d7b9fcb6..00000000 --- a/simulation/ai-polygon/nav2/differential_motion.py +++ /dev/null @@ -1,66 +0,0 @@ -"""Choose a native in-place turn before translation when the body sweep fits. - -This is action selection, not a path or velocity controller. Nav2 Spin owns -rotation; the live range, support, detector and freshness gates admit each tick. -""" -import math - -import numpy as np -from navigation.detection_obstacles import DetectionObstacles -from navigation.support_surface import SupportSurface - - -def observed_turn_support(angle, terrain, pose, monitor, contact_height): - """Test the complete newly entered contact area before choosing Spin. - - Use the existing contact-cell geometry and support classifier. Retain the - per-command discrepancy envelope at every orientation; no floor is filled - under the current body and no positive motor permission is returned. - """ - bounds = monitor.command_bounds(0., math.copysign(.15, angle)) - bounds['horizon_seconds'] = abs(angle)/.15 - if monitor.contacts is not None: - local, _ = monitor.contacts.cells(bounds, math.copysign(.15, angle)) - else: - # Legacy geometry has no contact bands: conservatively inspect the - # whole rotational disk on the existing fixed support-cell lattice. - radius = math.hypot(monitor.half_length, monitor.half_width) - radius += max(bounds['discrepancy_xy_m']) - cells = math.ceil(radius/.1) - local = np.array([[i*.1,j*.1] for i in range(-cells,cells+1) - for j in range(-cells,cells+1) if math.hypot(i*.1,j*.1)<=radius+.1]) - required = (np.abs(local[:,0])>monitor.half_length) | (np.abs(local[:,1])>monitor.half_width) - x, y, z, w = pose[3:] - yaw = math.atan2(2*(w*z+x*y), 1-2*(y*y+z*z)) - axes = np.array([[math.cos(yaw),-math.sin(yaw)],[math.sin(yaw),math.cos(yaw)]]) - surface = SupportSurface(terrain, pose, contact_height, monitor.max_step, monitor.max_slope, - anchor_radius_m=math.hypot(monitor.half_length,monitor.half_width)) - states, _ = monitor.classify_contacts(surface,local[required]@axes.T) - return bool(np.all(states=='observed-supported')) - - -def alignment_angle(pose, goal, terrain, detected, monitor, contact_height, *, - collision_terrain=None): - delta = np.asarray(goal[:2]) - np.asarray(pose[:2]) - if np.linalg.norm(delta) <= .4: - return None - x, y, z, w = pose[3:] - yaw = math.atan2(2*(w*z+x*y), 1-2*(y*y+z*z)) - bearing = math.atan2(delta[1], delta[0]) - yaw - angle = math.atan2(math.sin(bearing), math.cos(bearing)) - if abs(angle) < math.pi/6: - return None - collision = terrain if collision_terrain is None else collision_terrain - if not monitor.rotation_clear(angle, collision, pose): - return None - if collision_terrain is not None: - forbidden = terrain[terrain[:, 3] > collision[:, 3]] - if not monitor.ground_envelope().rotation_clear(angle, forbidden, pose): - return None - objects = DetectionObstacles(monitor) - hazards = np.column_stack((detected, np.full(len(detected), objects.cost))) - if not objects.monitor.rotation_clear(angle, hazards, pose): - return None - if not observed_turn_support(angle, terrain, pose, monitor, contact_height): - return None - return angle diff --git a/simulation/ai-polygon/nav2/server.py b/simulation/ai-polygon/nav2/server.py index 2ce580ff..b59e71d8 100644 --- a/simulation/ai-polygon/nav2/server.py +++ b/simulation/ai-polygon/nav2/server.py @@ -19,7 +19,6 @@ import rclpy import yaml from action_msgs.msg import GoalStatus from configuration import observed_configuration -from differential_motion import alignment_angle from navigation.arrival_approach import validate_orientation, orientation_identity from navigation.continuous_control import ContinuousControl from navigation.footprint import Footprint @@ -49,7 +48,6 @@ class Navigation: self.command_generation = 0 self.path_context = None self.completed_orientation = None - self.attempted_alignment = None self.path = None self.path_planned_at = float('-inf') self.active, self.failure = False, None @@ -205,50 +203,30 @@ class Navigation: and self.node.terminal is not None and self.node.terminal.done() and self.node.terminal.result().status == GoalStatus.STATUS_SUCCEEDED): self.completed_orientation = orientation_key - # The tracked rover can change heading without translating. Consider - # a native Spin before a large direction change, only if the complete - # rectangular body turn fits the obstacle/detector reserve and its - # complete newly entered track sweep has measured support. - # Unsafe turns leave Smac/DWB free to find an arc. Support and all live - # command gates still apply during Spin; completion grants no motion. - alignment_key = ('align', tuple(goal[:2]), limit) - aligning = (not reverse and value['translation_allowed'] - and self.action_key == alignment_key and self.node.terminal is not None - and not self.node.terminal.done()) - # A changing local endpoint is still a FollowPath task. Let Smac/DWB - # choose its curve; facing the endpoint directly is not a prerequisite - # for following that curve. Preempting a live path with Spin on every - # >30 degree bearing change creates stop/turn/advance oscillations. - # A completed/aborted path and explicit mission recovery may still - # select a fully observed in-place turn before starting translation. + # Smac plans from the measured heading. A destination bearing is not + # a path tangent or evidence of reachability, including after a failed + # action. Never turn toward an unplanned translation goal. DWB retains + # differential steering/pivots while following a feasible native path; + # separate Spin is reserved for an explicit non-translating survey. following = (self.action_key is not None and self.action_key[0] == 'path' and self.node.terminal is not None and not self.node.terminal.done()) - turn = None - if (not reverse and value['translation_allowed'] and not aligning and not following - and alignment_key != self.attempted_alignment): - turn = alignment_angle(pose, goal, terrain, observed['detected'], self.monitor, - value['body_contact_height_m'], - collision_terrain=observed['collision_terrain']) - orienting = aligning or turn is not None or (not reverse and orientation is not None + orienting = (not reverse and orientation is not None and orientation_key != self.completed_orientation and not value['translation_allowed']) if not value['translation_allowed'] and not orienting: self.stop() return self.reply('no-permitted-goal', status='blocked', route_observation=route) if orienting: - automatic = aligning or turn is not None - delta = (goal[:2] if automatic else np.asarray(orientation['xy']))-pose[:2] + delta = np.asarray(orientation['xy'])-pose[:2] heading = math.atan2(delta[1], delta[0]) angle = math.atan2(math.sin(heading-yaw_of(pose)), math.cos(heading-yaw_of(pose))) - key = alignment_key if automatic else orientation_key + key = orientation_key if key != self.action_key: self.revoke_command() # Existing mission budgets use simulation time. Do not invent # a second wall-clock maneuver budget in a slower simulation. # The unchanged command/data leases still gate every output. self.node.spin(angle, 0.) - if automatic: - self.attempted_alignment = alignment_key local_path = [[0.,0.,0.],[0.,0.,0.]] elif reverse: key = ('backup', tuple(goal[:2]), limit) diff --git a/src/k1link/simulation/ai_polygon/composition.py b/src/k1link/simulation/ai_polygon/composition.py index d35879f9..3bb33a9e 100644 --- a/src/k1link/simulation/ai_polygon/composition.py +++ b/src/k1link/simulation/ai_polygon/composition.py @@ -344,7 +344,7 @@ def registry(adapter_root: Path) -> ModuleRegistry: "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", - "detector_exclusion.py", "differential_motion.py", "route_support.py") + "detector_exclusion.py", "route_support.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")] diff --git a/tests/test_nav2_detector_reserve.py b/tests/test_nav2_detector_reserve.py new file mode 100644 index 00000000..5893a716 --- /dev/null +++ b/tests/test_nav2_detector_reserve.py @@ -0,0 +1,58 @@ +"""Native detector reserve covers the command guard without adding ground.""" +import math +from pathlib import Path + +import numpy as np +import pytest + + +@pytest.fixture +def exclusion(monkeypatch): + root = Path(__file__).parents[1] / 'simulation/ai-polygon' + monkeypatch.syspath_prepend(str(root / 'nav2')) + from detector_exclusion import DetectorExclusion + return DetectorExclusion() + + +def pose(yaw=0): + return np.array([0., 0., .37, 0., 0., math.sin(yaw/2), math.cos(yaw/2)]) + + +@pytest.mark.parametrize('offset', [[0.,0.], [.023,-.017], [13.193,-24.208]]) +def test_search_reserve_covers_guard_at_every_heading_without_inventing_ground(exclusion, offset): + centre = np.asarray(offset) + observed = np.array([[*centre, .7]]) + original = observed.copy() + rover = pose() + rover[:2] = centre + costs = exclusion.points(observed, rover) + assert len(costs) and len(costs) < 400 + # Any point of the added square margin, rotated at any heading, is covered + # by a lethal published cell. Test the contour and its interior separately. + for angle in np.linspace(-math.pi, math.pi, 97): + c, s = math.cos(angle), math.sin(angle) + axes = np.array([[c,-s],[s,c]]) + local = np.array([[x,y] for x in np.linspace(-.3,.3,9) + for y in np.linspace(-.3,.3,9)]) + samples = local@axes.T+centre + nearest = np.min(np.max(np.abs(samples[:,None]-costs[None]),axis=2),axis=1) + assert np.all(nearest <= .05/2+1e-9) + np.testing.assert_array_equal(observed, original) + assert exclusion.points([], rover).shape == (0,2) + +@pytest.mark.parametrize('helper',['detector_exclusion.py','route_support.py']) +def test_native_module_identity_includes_behavior_helpers(monkeypatch,helper): + from k1link.simulation.ai_polygon.composition import registry + + root=Path(__file__).parents[1]/'simulation/ai-polygon' + def identities(): + return {m.module_id:m.implementation_sha256 for m in registry(root).modules} + before=identities() + original=Path.read_bytes + def changed(path): + data=original(path) + return data+b'\n# distinct implementation\n' if path==root/'nav2'/helper else data + monkeypatch.setattr(Path,'read_bytes',changed) + after=identities() + assert before['simulation-nav2-navigation']!=after['simulation-nav2-navigation'] + assert before['simulation-waypoint-mission']==after['simulation-waypoint-mission'] diff --git a/tests/test_nav2_differential_motion.py b/tests/test_nav2_differential_motion.py deleted file mode 100644 index 5ead8eac..00000000 --- a/tests/test_nav2_differential_motion.py +++ /dev/null @@ -1,140 +0,0 @@ -"""Tracked turns and object clearance must agree before motor admission.""" -import math -from pathlib import Path - -import numpy as np -import pytest - - -@pytest.fixture -def motion(monkeypatch): - root = Path(__file__).parents[1] / 'simulation/ai-polygon' - monkeypatch.syspath_prepend(str(root)) - monkeypatch.syspath_prepend(str(root / 'nav2')) - from detector_exclusion import DetectorExclusion - from differential_motion import alignment_angle - from navigation.footprint import Footprint - monitor = Footprint(dict(length_m=1., width_m=.8, max_step_m=.1, max_slope_degrees=20)) - def alignment(pose, goal, terrain, detected, monitor): - floor = np.array([[i*.05,j*.05,0.,0.] for i in range(-40,41) for j in range(-40,41)]) - return alignment_angle(pose, goal, np.concatenate((floor,terrain)), detected, monitor,.37) - return alignment, DetectorExclusion(), monitor - - -def pose(yaw=0): - return np.array([0., 0., .37, 0., 0., math.sin(yaw/2), math.cos(yaw/2)]) - - -@pytest.mark.parametrize('yaw', [0., .31, -1.3]) -@pytest.mark.parametrize('angle', [math.pi/4, -math.pi/2, math.pi]) -def test_large_local_direction_change_can_use_zero_translation_turn(motion, yaw, angle): - alignment, _, monitor = motion - goal = [2*math.cos(yaw+angle), 2*math.sin(yaw+angle), 0.] - result = alignment(pose(yaw), goal, np.empty((0,4)), np.empty((0,3)), monitor) - assert abs(math.atan2(math.sin(result-angle), math.cos(result-angle))) < 1e-10 - assert alignment(pose(yaw+angle), goal, np.empty((0,4)), np.empty((0,3)), monitor) is None - - -def test_turn_checks_intermediate_corner_sweep_and_detector_reserve(motion): - alignment, _, monitor = motion - # Initially outside the chassis; an intermediate corner hits it during a turn. - hazard = np.array([[0., -.59, .3, 1.1]]) - assert monitor._clear(monitor._obstacles(hazard, pose()), np.zeros(2), 0.) - assert alignment(pose(), [0.,2.,0.], hazard, np.empty((0,3)), monitor) is None - # Ordinary body padding fits this turn; the detector's larger reserve does not. - point = np.array([[0., -.86, .3]]) - assert alignment(pose(), [0.,2.,0.], np.empty((0,4)), np.empty((0,3)), monitor) is not None - assert alignment(pose(), [0.,2.,0.], np.empty((0,4)), point, monitor) is None - - -def test_small_course_correction_stays_with_native_path_controller(motion): - alignment, _, monitor = motion - assert alignment(pose(), [2.,.5,0.], np.empty((0,4)), np.empty((0,3)), monitor) is None - - -@pytest.mark.parametrize('offset', [[0.,0.], [.023,-.017], [13.193,-24.208]]) -def test_search_reserve_covers_guard_at_every_heading_without_inventing_ground(motion, offset): - _, exclusion, monitor = motion - centre = np.asarray(offset) - observed = np.array([[*centre, .7]]) - original = observed.copy() - rover = pose() - rover[:2] = centre - costs = exclusion.points(observed, rover) - assert len(costs) and len(costs) < 400 - # Any point of the added square margin, rotated at any heading, is covered - # by a lethal published cell. Test the contour and its interior separately. - for angle in np.linspace(-math.pi, math.pi, 97): - c, s = math.cos(angle), math.sin(angle) - axes = np.array([[c,-s],[s,c]]) - local = np.array([[x,y] for x in np.linspace(-.3,.3,9) - for y in np.linspace(-.3,.3,9)]) - samples = local@axes.T+centre - nearest = np.min(np.max(np.abs(samples[:,None]-costs[None]),axis=2),axis=1) - assert np.all(nearest <= .05/2+1e-9) - np.testing.assert_array_equal(observed, original) - assert exclusion.points([], rover).shape == (0,2) - - -def test_retreat_creates_turning_room_without_relaxing_object_clearance(motion): - alignment, _, monitor = motion - obstacle = np.array([[.8,0.,.3]]) - terrain = np.column_stack((obstacle,[1.1])) - destination = [1.5,1.5,0.] - # Too close for the corners to sweep around this object at the start. - assert alignment(pose(), destination, terrain, obstacle, monitor) is None - # A real measured retreat gives the same requested destination room for a - # native in-place turn. No fixed short reverse distance is an admission rule. - after_retreat = pose() - after_retreat[0] = -.8 - turn = alignment(after_retreat, destination, terrain, obstacle, monitor) - assert turn is not None and turn > math.pi/6 - - -def test_unknown_future_track_ground_does_not_select_an_incomplete_turn(motion): - from differential_motion import alignment_angle - _, _, monitor = motion - floor = np.array([[i*.05,j*.05,0.,0.] for i in range(-25,26) for j in range(-25,26)]) - assert alignment_angle(pose(),[0.,2.,0.],floor,[],monitor,.37) is not None - # The current footprint and front are observed; rear-side future contact - # ground is unknown. A short initial pivot can fit but the whole turn cannot. - hole = floor[~((floor[:,0]<-.2)&(floor[:,1]>.45))] - assert alignment_angle(pose(),[0.,2.,0.],hole,[],monitor,.37) is None - - -@pytest.mark.parametrize('helper',['detector_exclusion.py','differential_motion.py','route_support.py']) -def test_native_module_identity_includes_behavior_helpers(monkeypatch,helper): - from k1link.simulation.ai_polygon.composition import registry - - root=Path(__file__).parents[1]/'simulation/ai-polygon' - def identities(): - return {m.module_id:m.implementation_sha256 for m in registry(root).modules} - before=identities() - original=Path.read_bytes - def changed(path): - data=original(path) - return data+b'\n# distinct implementation\n' if path==root/'nav2'/helper else data - monkeypatch.setattr(Path,'read_bytes',changed) - after=identities() - assert before['simulation-nav2-navigation']!=after['simulation-nav2-navigation'] - assert before['simulation-waypoint-mission']==after['simulation-waypoint-mission'] - - -@pytest.mark.parametrize('kind', ['overhang-ground','physical-object','track-ground']) -def test_spin_selection_keeps_body_and_track_surface_domains_separate(motion,kind): - from differential_motion import alignment_angle - from navigation.footprint import 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(geometry) - floor=np.array([[i*.05,j*.05,0.,0.] for i in range(-30,31) for j in range(-30,31)]) - point=np.array([[0.,-.45 if kind=='track-ground' else -.82,0.,1.]]) - terrain=np.r_[floor,point] - collision=terrain.copy() - if kind!='physical-object':collision[-1,3]=0. - angle=alignment_angle(pose(),[0.,2.,0.],terrain,[],monitor,.37, - collision_terrain=collision) - assert (angle is not None) == (kind=='overhang-ground') diff --git a/tests/test_nav2_route_support.py b/tests/test_nav2_route_support.py index db2b9e36..472008c6 100644 --- a/tests/test_nav2_route_support.py +++ b/tests/test_nav2_route_support.py @@ -26,13 +26,12 @@ def bridge(monkeypatch): cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'Navigation') scope = dict(np=np, math=math, time=time, route_support=route_support, route_observation=route_observation, validate_orientation=validate_orientation, - orientation_identity=orientation_identity, - alignment_angle=lambda *args, **kwargs: None) + orientation_identity=orientation_identity) exec(compile(ast.Module(body=[cls], type_ignores=[]), str(root / 'nav2/server.py'), 'exec'), scope) navigation = scope['Navigation'].__new__(scope['Navigation']) navigation.failure = None navigation.active = navigation.activating = True - navigation.action_key = navigation.attempted_alignment = None + navigation.action_key = None navigation.command_generation = 0 navigation.path_context = None navigation.owner_lock = threading.Lock() @@ -101,7 +100,7 @@ def test_route_support_rejects_invalid_or_wrongly_bound_target(bridge): @pytest.mark.parametrize('terminal_status', [None, 4, 6]) -def test_endpoint_change_keeps_live_path_but_terminal_path_can_align(bridge, terminal_status): +def test_endpoint_change_plans_before_motion_even_after_terminal_path(bridge, terminal_status): navigation, observed, value = bridge future = Future() if terminal_status is not None: @@ -117,24 +116,44 @@ def test_endpoint_change_keeps_live_path_but_terminal_path_can_align(bridge, ter SimpleNamespace(pose=SimpleNamespace(position=SimpleNamespace(x=x, y=y))) for x, y in [(0.,0.), (1.,.3), (2.,2.)]]), 4) calls = [] - navigation.node.follow = lambda *args, **kwargs: calls.append('follow') + def follow(*args, **kwargs): + calls.append('follow') + navigation.node.terminal = Future() + navigation.node.follow = follow navigation.node.spin = lambda *args: calls.append('spin') navigation.control.accept = lambda *args, **kwargs: None observed['metrics'] = {} globals_ = navigation._plan.__globals__ - globals_['alignment_angle'] = lambda *args, **kwargs: math.pi/4 globals_['yaw_of'] = lambda _: 0. globals_['GoalStatus'] = SimpleNamespace(STATUS_SUCCEEDED=4, STATUS_ABORTED=6) result = navigation.plan({**value, 'translation_allowed': True, 'goal': [2.,2.,0.]}) - if terminal_status is None: - assert calls == ['follow'] - assert result['controller_goal'][0] == 'path' - else: - assert calls == ['spin'] - assert result['controller_goal'][0] == 'align' + assert calls == ['follow'] + assert result['controller_goal'][0] == 'path' assert result['status'] == 'path' +def test_unreachable_lateral_goal_cannot_command_a_preplanning_spin(moving_bridge): + navigation, value, _, seen = moving_bridge + navigation.node.terminal.set_result(SimpleNamespace(status=6)) + navigation.node.plan = lambda *args: (None, 6) + navigation.node.spin = lambda *args: seen.append('unplanned-spin') + result = navigation.plan({**value, 'goal': [0., 3., 0.]}) + assert result['status'] == 'blocked' + assert result['planning_result']['status'] == 'aborted' + assert result['speed_mps'] == result['yaw_rate_rps'] == 0. + assert seen == [] + + +def test_explicit_stationary_survey_keeps_native_spin(moving_bridge): + navigation, value, planned, seen = moving_bridge + navigation.node.spin = lambda angle, budget: seen.append((angle, budget)) + result = navigation.plan({**value, 'translation_allowed': False, + 'recovery_orientation': True, 'orientation_target': dict(key='survey-1', xy=[0., 3.])}) + assert planned == [] + assert seen == [(math.pi/2, 0.)] + assert result['controller_goal'][0] == 'spin' + + @pytest.mark.parametrize('layer', ['search', 'surface', 'physical']) def test_goal_clearance_uses_solids_without_waiving_search_or_surface_costs(bridge, layer): navigation, observed, value = bridge