From c43b097a3a5c3f50c390ab1dea62e7bd5bf05c66 Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Fri, 9 Oct 2026 14:36:52 +0300 Subject: [PATCH] Bound corridor ranking work and retire aborted local actions --- .../ai-polygon/navigation/observed_goals.py | 55 +++++++++++++++---- .../simulation/ai_polygon/mission_policy.py | 11 +++- tests/test_ai_polygon_mission.py | 40 ++++++++++++++ tests/test_ai_polygon_observed_goals.py | 45 +++++++++++++++ 4 files changed, 138 insertions(+), 13 deletions(-) diff --git a/simulation/ai-polygon/navigation/observed_goals.py b/simulation/ai-polygon/navigation/observed_goals.py index f207a736..d35b23a3 100644 --- a/simulation/ai-polygon/navigation/observed_goals.py +++ b/simulation/ai-polygon/navigation/observed_goals.py @@ -81,18 +81,30 @@ class ObservedGoals: delta = candidates[:, :2]-xy length = np.linalg.norm(delta, axis=1) direction = delta / np.maximum(length[:, None], 1e-9) + inverse = angular_error = None if lookahead_m is not None: # Compare bearings over one common horizon. A short destination # before an obstacle must not hide that obstacle from intent cost. # This extends a scoring query, never the measured drive goal. - length = np.full(len(candidates), lookahead_m) + # Dense range samples often describe almost the same bearing. + # Share radial queries in quarter-degree bins; subtract the exact + # maximum displacement caused by that rotation from each result. + # This is still a lower bound, with <= 4.1 cm total error at 3.5 m. + bearing = np.arctan2(direction[:, 1], direction[:, 0]) + bins = np.rint(bearing/math.radians(.25)).astype(int) + unique, inverse = np.unique(bins, return_inverse=True) + quantized = unique*math.radians(.25) + angular_error = 2*lookahead_m*np.abs(np.sin((bearing-quantized[inverse])/2)) + direction = np.column_stack((np.cos(quantized), np.sin(quantized))) + length = np.full(len(unique), lookahead_m) + distances = np.full(len(unique), np.inf) start = np.minimum(length, geometry.get("length_m", geometry["width_m"])/2) # Nearest-obstacle distance is 1-Lipschitz. Sampling at <= 5 cm and # subtracting half the actual spacing gives a conservative continuous # segment lower bound (error <= 2.5 cm), without an N*M hazard matrix. # This is a soft ranking cost only, never a swept-body safety receipt. - for first in range(0, len(candidates), 128): - last = min(first+128, len(candidates)) + for first in range(0, len(length), 128): + last = min(first+128, len(length)) steps = np.maximum(1, np.ceil((length[first:last]-start[first:last])/.05).astype(int)) spacing = (length[first:last]-start[first:last])/steps along = (start[first:last, None] @@ -101,6 +113,8 @@ class ObservedGoals: queries = xy + along[:, :, None]*direction[first:last, None] nearest = tree.query(queries.reshape(-1, 2), workers=1)[0].reshape(along.shape) distances[first:last] = np.maximum(0., nearest.min(axis=1)-spacing/2) + if inverse is not None: + return np.maximum(0., distances[inverse]-angular_error) return distances def clearance_cost(self, candidates, pose, geometry, now, *, lookahead_m=None): @@ -128,13 +142,34 @@ class ObservedGoals: barriers = barriers[np.all((barriers[:,:2]>=low)&(barriers[:,:2]<=high),axis=1)] if not len(barriers): return cost - for start in range(0,len(candidates),128): - batch = candidates[start:start+128] - distance = np.linalg.norm(batch[:,None,:2]-barriers[None,:,:2],axis=2) - dz = barriers[None,:,2]-batch[:,None,2] - relevant = (dz>=-geometry.get('max_step_m', .1)) & (dz<=geometry.get('height_m',width)) - nearest = np.min(np.where(relevant,distance,np.inf),axis=1) - cost[start:start+len(batch)] = 2*width*np.exp(-nearest/width) + # Query nearest XY neighbours until one also lies in the candidate's + # exact height interval. Usually the first return qualifies. Unlike a + # dense candidate-by-barrier matrix this does no work for distant + # obstacles once a nearer relevant boundary has been found. + tree = cKDTree(barriers[:, :2]) + heights = np.sort(barriers[:, 2]) + lower = candidates[:, 2]-geometry.get('max_step_m', .1) + upper = candidates[:, 2]+geometry.get('height_m', width) + has_relevant = (np.searchsorted(heights, np.nextafter(upper, np.inf), side='right') + > np.searchsorted(heights, np.nextafter(lower, -np.inf), side='left')) + for start in range(0, len(candidates), 128): + pending = np.arange(start, min(start+128, len(candidates))) + pending = pending[has_relevant[pending]] + count = 1 + while len(pending): + distance, indices = tree.query(candidates[pending, :2], k=count, workers=1) + distance = np.asarray(distance).reshape(len(pending), count) + indices = np.asarray(indices).reshape(len(pending), count) + dz = barriers[indices, 2]-candidates[pending, None, 2] + relevant = ((dz >= -geometry.get('max_step_m', .1)) + & (dz <= geometry.get('height_m', width))) + nearest = np.min(np.where(relevant, distance, np.inf), axis=1) + found = np.isfinite(nearest) + cost[pending[found]] = 2*width*np.exp(-nearest[found]/width) + pending = pending[~found] + if count == len(barriers): + break + count = min(2*count, len(barriers)) return cost def maneuver(self, points, pose, target, prior, excluded, geometry, now, candidate_mask=None): diff --git a/src/k1link/simulation/ai_polygon/mission_policy.py b/src/k1link/simulation/ai_polygon/mission_policy.py index 56beb363..c9c8f89b 100644 --- a/src/k1link/simulation/ai_polygon/mission_policy.py +++ b/src/k1link/simulation/ai_polygon/mission_policy.py @@ -140,7 +140,7 @@ class WaypointMission: self.goal = None def reject_local_plan(self, result, pose, seconds, execution_inputs_sha256): - """Retire an intermediate intent after its bound native planner abort. + """Retire an intermediate intent after its bound native planner/action abort. This is not an obstacle label or motion permission. The next observed candidate must obtain its own native path and current command admission. @@ -154,8 +154,13 @@ class WaypointMission: if (result.get("route_observation", {}).get("observation") == expected and result.get("status") == "blocked" and result.get("speed_mps") == result.get("yaw_rate_rps") == 0. - and result.get("planning_result") == dict( - status="aborted", goal_xy=list(self.goal[:2]))): + and (result.get("planning_result") == dict( + status="aborted", goal_xy=list(self.goal[:2])) + or result.get("action_result") == dict( + status="aborted", kind="path", goal_xy=list(self.goal[:2])))): + # A terminated FollowPath cannot recover by waiting on the same + # handle. Try another currently observed goal, under the existing + # retry/progress budgets, before entering a full survey/retreat. rejected = list(self.goal) self.retire_local_goal(self.arrival_target(), failed=True) if self.goal is None: diff --git a/tests/test_ai_polygon_mission.py b/tests/test_ai_polygon_mission.py index ed9c7a8e..60bbb472 100644 --- a/tests/test_ai_polygon_mission.py +++ b/tests/test_ai_polygon_mission.py @@ -347,3 +347,43 @@ def test_native_backoff_does_not_clear_current_recovery_round_or_motion_failures mission.retry_native_goals(3.) assert mission.failed_goals == [other] assert mission.attempts == 0 and mission.anchor_time == 0 + + +def aborted_follow(goal, p, seconds): + result = aborted_plan(goal, p, seconds) + result['action_result'] = {**result.pop('planning_result'), 'kind': 'path'} + return result + + +def test_followpath_abort_does_not_wait_for_stall_or_force_recovery(): + mission = WaypointMission([[8, 0]]) + first, _ = mission.update(pose(), 0, goal) + mission.reject_local_plan(aborted_follow(first, pose(), 0), pose(), 0, 'run') + assert mission.goal is None and mission.failed_goals == [first] + second, intent = mission.update(pose(), .1, goal) + assert second != first and not mission.recovery.active + assert mission.anchor_time == 0 and mission.attempts == 0 + # Native aborts and replacement goals still earn no task progress. + for t in range(1, 34): + current, _ = mission.update(pose(), t, goal) + if current is not None: + mission.reject_local_plan(aborted_follow(current, pose(), t), pose(), t, 'run') + assert mission.fault == 'stuck' + + +@pytest.mark.parametrize('mismatch', ['kind', 'goal', 'status', 'run', 'pose', 'time', 'moving']) +def test_followpath_abort_must_belong_to_current_goal_and_observation(mismatch): + mission = WaypointMission([[8, 0]]) + first, _ = mission.update(pose(), 1, goal) + result = aborted_follow(first, pose(), 1) + receipt = result['action_result'] + observation = result['route_observation']['observation'] + if mismatch == 'kind': receipt['kind'] = 'backup' + elif mismatch == 'goal': receipt['goal_xy'] = [100., 100.] + elif mismatch == 'status': receipt['status'] = 'canceled' + elif mismatch == 'run': observation['execution_inputs_sha256'] = 'other' + elif mismatch == 'pose': observation['pose'] = pose(.1) + elif mismatch == 'time': observation['simulation_time_seconds'] = .9 + elif mismatch == 'moving': result['speed_mps'] = .1 + mission.reject_local_plan(result, pose(), 1, 'run') + assert mission.goal == first and mission.failed_goals == [] diff --git a/tests/test_ai_polygon_observed_goals.py b/tests/test_ai_polygon_observed_goals.py index 5e42c2ac..4fee01c9 100644 --- a/tests/test_ai_polygon_observed_goals.py +++ b/tests/test_ai_polygon_observed_goals.py @@ -410,3 +410,48 @@ def test_alternating_cached_views_do_not_multiply_semantic_votes(selector): assert dict(selector.surface.cells) == before selector.observe(negative, 4., position, frame_id='d:front', capture_id='d') assert selector.choose(points, position, target, None, (), GEOMETRY, 4.) is None + + +@pytest.mark.parametrize('seed', [19, 37, 44]) +def test_indexed_boundary_cost_preserves_exact_height_filtered_distance(selector, seed): + rng = np.random.default_rng(seed) + barriers = np.c_[rng.uniform(-3, 3, (415, 2)), rng.uniform(-2, 2, 415)] + candidates = np.c_[rng.uniform(-2, 2, (261, 2)), rng.uniform(-.3, .3, 261)] + geometry = {**GEOMETRY, 'height_m': .734, 'max_step_m': .1} + selector.observe(np.c_[barriers, np.zeros(len(barriers))], 1., [0, 0, .37, 0, 0, 0, 1]) + # Use the same actual retained return in each semantic voxel; no invented + # cell centres or relaxed height intervals enter either calculation. + measured = np.array(list(selector.measured.values())) + distance = np.linalg.norm(candidates[:, None, :2]-measured[None, :, :2], axis=2) + dz = measured[None, :, 2]-candidates[:, None, 2] + expected = 2*geometry['width_m']*np.exp(-np.min(np.where( + (dz>=-.1)&(dz<=.734), distance, np.inf),axis=1)/geometry['width_m']) + np.testing.assert_allclose(selector.boundary_cost(candidates, geometry, 1.), expected, + rtol=1e-12, atol=1e-12) + + +def test_boundary_index_skips_closer_returns_above_the_body(selector): + candidates = np.array([[1., 0., 0.], [1., 0., 8.]]) + barriers = np.array([[1., 0., 3.], [1.1, 0., 3.], [1.2, 0., 3.], [2., 0., 0.]]) + selector.observe(np.c_[barriers, np.zeros(len(barriers))], 1., [0, 0, .37, 0, 0, 0, 1]) + cost = selector.boundary_cost(candidates, GEOMETRY, 1.) + np.testing.assert_allclose(cost, [2*.905*np.exp(-1/.905), 0.]) + + +def test_shared_bearing_queries_conservatively_bound_common_horizon(selector): + rng = np.random.default_rng(126) + position = [17., -31., .37, 0., 0., 0., 1.] + candidates = np.c_[rng.uniform(-3., 3., (1259, 2))+position[:2], np.zeros(1259)] + obstacles = rng.uniform(-4., 4., (237, 2))+position[:2] + selector.observe_navigation(clearance_receipt(position, obstacles.tolist()), position, 1, 'run', 1.) + actual = selector.approach_clearance(candidates, position, GEOMETRY, 1.1, lookahead_m=3.5) + expected = [] + for goal in candidates: + delta = goal[:2]-position[:2] + direction = delta/np.linalg.norm(delta) + a = np.asarray(position[:2])+GEOMETRY['width_m']/2*direction + b = np.asarray(position[:2])+3.5*direction + projection = np.clip((obstacles-a) @ (b-a)/np.sum((b-a)**2), 0, 1) + expected.append(np.min(np.linalg.norm(obstacles-(a+projection[:, None]*(b-a)), axis=1))) + assert np.all(actual <= np.asarray(expected)+1e-10) + assert np.max(np.asarray(expected)-actual) < .041