Plan translation before choosing motion toward a local goal

This commit is contained in:
DCCONSTRUCTIONS
2026-10-10 08:29:26 +03:00
parent fe495fa302
commit ac980912e0
6 changed files with 98 additions and 249 deletions
+58
View File
@@ -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']
-140
View File
@@ -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')
+31 -12
View File
@@ -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