diff --git a/simulation/ai-polygon/nav2/configuration.py b/simulation/ai-polygon/nav2/configuration.py index 54441299..856eb184 100644 --- a/simulation/ai-polygon/nav2/configuration.py +++ b/simulation/ai-polygon/nav2/configuration.py @@ -44,7 +44,11 @@ def configuration(inputs, robot): static_layer=dict(plugin='nav2_costmap_2d::StaticLayer', map_topic='/observed_map', map_subscribe_transient_local=True, subscribe_to_updates=False), inflation_layer=dict(plugin='nav2_costmap_2d::InflationLayer', - cost_scaling_factor=3.0, inflation_radius=math.hypot(x, y) + 0.15), + # A gentle field over the local goal horizon makes observed + # obstacles influence the path before the body is beside them. + # Full footprint, lethal cells and support gates are unchanged. + cost_scaling_factor=1.0 / geometry['width_m'], + inflation_radius=max(3.5, math.hypot(x, y) + 0.15)), ) # Bound the corner displacement from a full angular bin to half a map # cell. Humble floors the start heading; a coarse primitive lattice can diff --git a/simulation/ai-polygon/nav2/differential_motion.py b/simulation/ai-polygon/nav2/differential_motion.py index b9355ed6..d7b9fcb6 100644 --- a/simulation/ai-polygon/nav2/differential_motion.py +++ b/simulation/ai-polygon/nav2/differential_motion.py @@ -39,7 +39,8 @@ def observed_turn_support(angle, terrain, pose, monitor, contact_height): return bool(np.all(states=='observed-supported')) -def alignment_angle(pose, goal, terrain, detected, monitor, contact_height): +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 @@ -49,8 +50,13 @@ def alignment_angle(pose, goal, terrain, detected, monitor, contact_height): angle = math.atan2(math.sin(bearing), math.cos(bearing)) if abs(angle) < math.pi/6: return None - if not monitor.rotation_clear(angle, terrain, pose): + 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): diff --git a/simulation/ai-polygon/nav2/server.py b/simulation/ai-polygon/nav2/server.py index 0e7d8ffb..c487f161 100644 --- a/simulation/ai-polygon/nav2/server.py +++ b/simulation/ai-polygon/nav2/server.py @@ -143,6 +143,15 @@ class Navigation: detected=observed['detected']): return self.reply('stale-range') route = route_observation(terrain, pose, value, self.monitor.max_step) + # Return the same observed search obstacles used by Smac, as bounded + # intent guidance only. Goal selection must see unlabelled solids too. + hazards = observed['search_terrain'] + hazards = hazards[hazards[:, 3] > self.monitor.max_step + 1e-4, :2] + if len(hazards): + _, indices = np.unique(np.floor(hazards / .05), axis=0, return_index=True) + hazards = hazards[np.sort(indices)] + receipts['clearance_observation'] = dict( + observation=route['observation'], obstacles_xy=hazards.tolist()) support = route_support(self.monitor, observed, value, self.inputs) if support is not None: receipts["route_support"] = support @@ -183,7 +192,8 @@ class Navigation: if (not reverse and value['translation_allowed'] and not aligning and alignment_key != self.attempted_alignment): turn = alignment_angle(pose, goal, terrain, observed['detected'], self.monitor, - value['body_contact_height_m']) + 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 and orientation_key != self.completed_orientation and not value['translation_allowed']) @@ -207,16 +217,16 @@ class Navigation: self.attempted_alignment = alignment_key local_path = [[0.,0.,0.],[0.,0.,0.]] elif reverse: + key = ('backup', tuple(goal[:2]), limit) + completed = self.completed_action(key, route) + if completed is not None: + return completed delta = goal[:2]-pose[:2] heading = yaw_of(pose) rear = -float(delta @ [math.cos(heading), math.sin(heading)]) if rear <= 0: self.node.stop() return self.reply('reverse-goal-is-not-behind', status='blocked') - key = ('backup', tuple(goal[:2]), limit) - completed = self.completed_action(key, route) - if completed is not None: - return completed if key != self.action_key: with self.owner_lock: self.action_key = None diff --git a/simulation/ai-polygon/navigation/observed_goals.py b/simulation/ai-polygon/navigation/observed_goals.py index 33f60631..c890e64b 100644 --- a/simulation/ai-polygon/navigation/observed_goals.py +++ b/simulation/ai-polygon/navigation/observed_goals.py @@ -18,6 +18,7 @@ class ObservedGoals: self.surface = SemanticSurface(retain_near=True) self.measured = {} self.evidence = None + self.clearance_observation = None def observe(self, samples, captured_at, pose): self.surface.observe(samples, captured_at, pose) @@ -30,6 +31,59 @@ class ObservedGoals: if key in self.surface.cells and self.surface.retained(key, self.surface.cells[key][1], captured_at)} + def observe_navigation(self, result, pose, seconds, execution_inputs_sha256, captured_at): + """Use native observed geometry for intent, never as motion admission.""" + receipt = result.get("clearance_observation") + expected = dict(pose=list(pose), simulation_time_seconds=seconds, + execution_inputs_sha256=execution_inputs_sha256) + if not isinstance(receipt, dict) or receipt.get("observation") != expected: + return + points = np.asarray(receipt.get("obstacles_xy"), dtype=float) + if not points.size: + points = np.empty((0, 2)) + if (points.ndim != 2 or points.shape[1] != 2 or len(points) > 30000 + or not np.isfinite(points).all() or not math.isfinite(captured_at)): + raise ValueError("Invalid observed clearance guidance") + self.clearance_observation = (captured_at, points.copy()) + + def approach_clearance(self, candidates, pose, geometry, now): + """Minimum obstacle distance along candidate approaches, in metres. + + These straight segments rank spatial intentions; they are not paths. + Smac still chooses the actual path and every commanded sweep must pass + live body, support, semantic and freshness admission. No new free cells + or positive surface labels are created here. + """ + distances = np.full(len(candidates), np.inf) + observed = self.clearance_observation + if observed is None or not 0 <= now-observed[0] <= .8 or not len(observed[1]): + return distances + obstacles = observed[1] + xy = np.asarray(pose[:2]) + delta = candidates[:, :2]-xy + length = np.linalg.norm(delta, axis=1) + # The currently occupied body is shared by every approach. Compare the + # corridor ahead of it, preserving the same full-body live veto below. + start = np.minimum(length, geometry.get("length_m", geometry["width_m"])/2) + direction = delta / np.maximum(length[:, None], 1e-9) + low = np.minimum(xy, candidates[:, :2].min(0))-4*geometry['width_m'] + high = np.maximum(xy, candidates[:, :2].max(0))+4*geometry['width_m'] + obstacles = obstacles[np.all((obstacles >= low) & (obstacles <= high), axis=1)] + if not len(obstacles): + return distances + offsets = obstacles-xy + for first in range(0, len(candidates), 128): + last = min(first+128, len(candidates)) + along = np.clip(direction[first:last] @ offsets.T, + start[first:last, None], length[first:last, None]) + difference = (offsets[None]-along[:, :, None]*direction[first:last, None]) + distances[first:last] = np.sqrt(np.min(np.sum(difference*difference, axis=2), axis=1)) + return distances + + def clearance_cost(self, candidates, pose, geometry, now): + clearance = self.approach_clearance(candidates, pose, geometry, now) + return 4*geometry['width_m']*np.exp(-clearance/geometry['width_m']), clearance + def boundary_cost(self, candidates, geometry, now): """Soft clearance preference, like an inflation potential in a costmap. @@ -137,6 +191,7 @@ class ObservedGoals: turning = np.where(reverse, math.pi-np.abs(errors), np.abs(errors)) score = np.linalg.norm(candidates[:, :2]-target, axis=1) + .2*turning + .15*distance score += self.boundary_cost(candidates, geometry, now) + score += self.clearance_cost(candidates, pose, geometry, now)[0] # Recovery actions need a fair turn, as in Nav2's RoundRobin recovery # subtree. Distance-to-task alone can spend every retry on almost the # same forward approach before ever considering a measured retreat. @@ -250,6 +305,7 @@ class ObservedGoals: # A lens switch cannot replace a currently measured, permitted goal. # A new prohibition, missing current range or changed corridor can. + retain = None if prior is not None: before = np.asarray(prior, dtype=float) matched = np.linalg.norm(candidates - before, axis=1) <= 0.15 @@ -257,7 +313,7 @@ class ObservedGoals: and all(math.dist(before[:2], failed[:2]) > 0.6 for failed in excluded) and (candidate_mask is None or candidate_mask(before[None])[0]) and supported(before)): - return before.tolist() + retain = before # Score the task direction at the existing 3.5 m observation horizon. # Distance to a remote endpoint mostly rewards longitudinal advance: # slightly farther side returns can beat a clear straight destination @@ -276,7 +332,27 @@ class ObservedGoals: bearing = np.arctan2(candidates[:,1]-pose[1],candidates[:,0]-pose[0])-heading score = (distance_to_target + .2*np.abs(np.arctan2(np.sin(bearing),np.cos(bearing))) + self.boundary_cost(candidates, geometry, now)) + clearance_cost, clearances = self.clearance_cost(candidates, pose, geometry, now) + score += clearance_cost + retained_clearance = (self.approach_clearance(retain[None], pose, geometry, now)[0] + if retain is not None else None) for index in np.argsort(score, kind="stable"): if supported(candidates[index]): - return candidates[index].tolist() + selected = candidates[index] + if retain is not None and not ( + retained_clearance < geometry['width_m'] + and clearances[index] > retained_clearance + .1 + ): + selected = retain + supported(retain) + if self.evidence is not None: + self.evidence['approach_clearance_m'] = ( + float(self.approach_clearance(selected[None], pose, geometry, now)[0]) + if self.clearance_observation is not None + and 0 <= now-self.clearance_observation[0] <= .8 + and len(self.clearance_observation[1]) else None) + if self.evidence is not None and not math.isfinite( + self.evidence.get('approach_clearance_m') or 0.): + self.evidence['approach_clearance_m'] = None + return selected.tolist() return None diff --git a/simulation/ai-polygon/navigation_client.py b/simulation/ai-polygon/navigation_client.py index 593d7888..b816251e 100644 --- a/simulation/ai-polygon/navigation_client.py +++ b/simulation/ai-polygon/navigation_client.py @@ -844,6 +844,10 @@ class ComposedInference: "allow_reverse": intent["state"] == "reversing", }, ) + if getattr(self, "observed_goals", None) is not None: + self.observed_goals.observe_navigation( + result, pose, inputs["source.simulation-time"], self.inputs["sha256"], + inputs.get("source.range-captured-at", calibration.get("captured_at", -math.inf))) self.mission.reject_local_plan( result, pose, inputs["source.simulation-time"], self.inputs["sha256"]) self.mission.recovery.observe_navigation( diff --git a/src/k1link/simulation/ai_polygon/observed_recovery.py b/src/k1link/simulation/ai_polygon/observed_recovery.py index b840a2ec..99ea1875 100644 --- a/src/k1link/simulation/ai_polygon/observed_recovery.py +++ b/src/k1link/simulation/ai_polygon/observed_recovery.py @@ -36,6 +36,7 @@ class ObservedRecovery: self.blocked_option = False self.failure = None self.completion = None + self.native_action = None @property def active(self): @@ -56,6 +57,7 @@ class ObservedRecovery: self.blocked_option = False self.failure = None self.completion = None + self.native_action = None def observe_navigation(self, result, pose, seconds, option_key, execution_inputs_sha256): """Consume bound completion or retire a consistently vetoed intention. @@ -70,6 +72,16 @@ class ObservedRecovery: execution_inputs_sha256=execution_inputs_sha256) if observation != expected: return + owner = result.get("controller_goal") or [] + if (self.selected is not None and self.selected.get("kind") != "orient" + and result.get("status") == "path" and len(owner) == 3 + and owner[0] == ("backup" if self.selected["reverse"] else "path") + and list(owner[1]) == list(self.selected["goal"][:2])): + # The bound native action owns its stopping tolerance. A second + # 30 cm arrival test used to cancel short retreats halfway through. + # Ownership never grants motion: current views, ground, obstacles + # and measured progress still govern every subsequent command. + self.native_action = dict(kind=owner[0], goal_xy=list(owner[1])) completion = result.get("action_result") if (self.selected is not None and self.selected.get("kind") != "orient" and result.get("status") == "waiting-for-plan" @@ -216,6 +228,7 @@ class ObservedRecovery: self.best_heading = math.inf self.blockage = None self.blocked_option = False + self.native_action = None if self.phase == "executing": distance = math.dist(pose[:2], self.selected["goal"][:2]) observed = choose(self.selected, self.excluded) @@ -223,7 +236,7 @@ class ObservedRecovery: desired = math.atan2(dy, dx) + (math.pi if self.selected["reverse"] else 0) error = abs(angle(desired-heading(pose))) orienting = self.selected.get("kind") == "orient" - if (error <= .1 if orienting else distance <= .3): + if (error <= .1 if orienting else self.native_action is None and distance <= .3): self.phase = "idle" return None, "replanning" if self.best_distance-distance >= .1 or self.best_heading-error >= .05: @@ -258,4 +271,5 @@ class ObservedRecovery: def evidence(self): return dict(phase=self.phase, option=self.option, selected=self.selected, surveyed_sectors=sorted(self.views), request=self.request, - rejected_goals=self.excluded, failure=self.failure) + rejected_goals=self.excluded, failure=self.failure, + native_action=self.native_action) diff --git a/tests/test_ai_polygon_observed_goals.py b/tests/test_ai_polygon_observed_goals.py index a9f6ec14..f9d4bf1f 100644 --- a/tests/test_ai_polygon_observed_goals.py +++ b/tests/test_ai_polygon_observed_goals.py @@ -265,3 +265,54 @@ def test_uneven_range_horizon_does_not_pull_straight_intent_sideways(selector,ya assert np.min(np.linalg.norm(points-goal,axis=1))<1e-9 # A local reference grants no synthetic ground or permission. assert selector.choose(np.empty((0,3)),pose,target,goal,(),GEOMETRY,1) is None + + +def clearance_receipt(position, obstacles, seconds=1): + return dict(clearance_observation=dict(obstacles_xy=obstacles, + observation=dict(pose=position, simulation_time_seconds=seconds, + execution_inputs_sha256='run'))) + + +@pytest.mark.parametrize('yaw,shift', [(0, (0, 0)), (73, (42, -17)), (-138, (-250, 52))]) +def test_unlabelled_pole_changes_approach_before_body_gets_close(selector, yaw, shift): + points, position, target, _, rotation = road(yaw, shift) + geometry = {**GEOMETRY, 'length_m': 1.163, 'max_step_m': .1} + selector.observe(np.c_[points, np.ones(len(points))], 1., position) + old_goal = selector.choose(points, position, target, None, (), geometry, 1.) + # No semantic object name is required: native physical geometry supplies it. + pole = np.array([[1.9, -.25]]) @ rotation.T + shift + selector.observe_navigation(clearance_receipt(position, pole.tolist()), + position, 1, 'run', 1.) + goal = selector.choose(points, position, target, old_goal, (), geometry, 1.1) + lateral = ((np.array(goal[:2])-shift) @ rotation)[1] + assert lateral > .3 + assert selector.approach_clearance(np.array([goal]), position, geometry, 1.1)[0] > ( + selector.approach_clearance(np.array([old_goal]), position, geometry, 1.1)[0]+.1) + assert np.min(np.linalg.norm(points-goal, axis=1)) < 1e-9 + # Ranking is not new ground permission and expired geometry is not refreshed. + assert selector.choose(points, position, target, None, (), geometry, 1.1, + lambda p: np.zeros(len(p), bool)) is None + assert np.isinf(selector.approach_clearance(np.array([goal]),position,geometry,1.81)[0]) + + +def test_obstacle_beyond_goal_has_less_effect_than_one_on_approach(selector): + points, position, target, _, _ = road() + selector.observe(np.c_[points,np.ones(len(points))],1.,position) + candidates=np.array([[3.,0.,0.],[3.,.6,0.]]) + selector.observe_navigation(clearance_receipt(position, [[1.6,0.]]),position,1,'run',1.) + scores, clearances=selector.clearance_cost(candidates,position,GEOMETRY,1.1) + assert clearances[0] == 0. and scores[0] > scores[1] + # Looking only at the final point misses this mid-approach obstruction. + assert np.linalg.norm(candidates[0,:2]-[1.6,0.]) > 1. + + +@pytest.mark.parametrize('mismatch', ['run','pose','time']) +def test_clearance_receipt_is_bound_and_does_not_invent_semantics(selector,mismatch): + _,position,_,_,_=road() + receipt=clearance_receipt(position,[[1.5,0.]]) + run,seconds='run',1 + if mismatch=='run':run='different' + elif mismatch=='time':seconds=2 + elif mismatch=='pose':position=[1.,*position[1:]] + selector.observe_navigation(receipt,position,seconds,run,1.) + assert selector.clearance_observation is None and not selector.surface.cells diff --git a/tests/test_nav2_configuration.py b/tests/test_nav2_configuration.py index f5ae4230..81fed4e4 100644 --- a/tests/test_nav2_configuration.py +++ b/tests/test_nav2_configuration.py @@ -58,3 +58,17 @@ def test_mission_translation_rotation_and_endpoint_do_not_change_navigation_conf changed["mission"]["route_xy"] = [[-500., 700.], [-503., 702.]] changed["sha256"] = digest({k: v for k, v in changed.items() if k != "sha256"}) assert configure(changed, robot) == original + + +def test_clearance_potential_spans_the_local_intent_horizon(configured): + configure, inputs, robot = configured + config = configure(inputs, robot) + for name in ('global_costmap', 'local_costmap'): + grid = config[name][name]['ros__parameters'] + layer = grid['inflation_layer'] + assert layer['inflation_radius'] >= 3.5 + # The native exponential must still distinguish the middle of a + # passage from its edge well outside the hard collision reserve. + 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'] diff --git a/tests/test_nav2_differential_motion.py b/tests/test_nav2_differential_motion.py index b9655a09..5ead8eac 100644 --- a/tests/test_nav2_differential_motion.py +++ b/tests/test_nav2_differential_motion.py @@ -118,3 +118,23 @@ def test_native_module_identity_includes_behavior_helpers(monkeypatch,helper): 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_observed_recovery.py b/tests/test_observed_recovery.py index 505b2745..79732b7d 100644 --- a/tests/test_observed_recovery.py +++ b/tests/test_observed_recovery.py @@ -295,3 +295,73 @@ def test_only_bound_native_abort_retires_the_local_option(reverse, mismatch): if mismatch is None: assert r.tick(position, now+.1, choose)[0] is None assert r.excluded == [selected['goal']] + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_native_action_finishes_its_own_distance_before_returning_to_route(reverse): + r = ObservedRecovery() + r.begin(pose(), 0, []) + sign = -1 if reverse else 1 + selected = dict(goal=[sign*.7, 0., 0.], reverse=reverse) + choose = lambda *_: selected + now = survey(r, pose(), choose) + receipt = completed_path(pose(), now, selected['goal']) + receipt.update(status='path', speed_mps=sign*.1, + controller_goal=['backup' if reverse else 'path', selected['goal'][:2], .1]) + receipt.pop('action_result') + r.observe_navigation(receipt, pose(), now, (r.sequence, r.option), 'run') + position = pose(sign*.45) + r.observe_view(r.view_request(position, now+1), position, now+1) + assert r.tick(position, now+1, choose) == ( + selected['goal'], 'reversing' if reverse else 'manoeuvring') + assert r.active and r.completion is None + # A completed native action stops intent even slightly past its goal. + position = pose(sign*.71) + receipt = completed_path(position, now+2, selected['goal']) + receipt['action_result']['kind'] = 'backup' if reverse else 'path' + r.observe_navigation(receipt, position, now+2, (r.sequence, r.option), 'run') + assert r.tick(position, now+2, choose) == (None, 'replanning') + assert not r.active + + +@pytest.mark.parametrize('mismatch', ['run', 'time', 'pose', 'option', 'goal', 'kind']) +def test_unbound_owner_cannot_suppress_legacy_completion(mismatch): + r = ObservedRecovery() + r.begin(pose(), 0, []) + selected = dict(goal=[-.7, 0., 0.], reverse=True) + choose = lambda *_: selected + now = survey(r, pose(), choose) + receipt = completed_path(pose(), now, selected['goal']) + receipt.update(status='path', speed_mps=-.1, + controller_goal=['backup', [-.7, 0.], .1]) + receipt.pop('action_result') + position, key, run = pose(), (r.sequence, r.option), 'run' + if mismatch == 'run': run = 'other' + elif mismatch == 'time': now += .1 + elif mismatch == 'pose': position = pose(.1) + elif mismatch == 'option': key = (r.sequence, r.option+1) + elif mismatch == 'goal': receipt['controller_goal'][1] = [-1., 0.] + elif mismatch == 'kind': receipt['controller_goal'][0] = 'spin' + r.observe_navigation(receipt, position, now, key, run) + assert r.native_action is None + assert r.tick(pose(-.45), now+1, choose) == (None, 'replanning') + + +def test_native_owner_does_not_bypass_unknown_view_or_progress_budget(): + r = ObservedRecovery() + r.begin(pose(), 0, []) + selected = dict(goal=[-.7, 0., 0.], reverse=True) + choose = lambda *_: selected + now = survey(r, pose(), choose) + receipt = completed_path(pose(), now, selected['goal']) + receipt.update(status='path', speed_mps=-.1, + controller_goal=['backup', [-.7, 0.], .1]) + receipt.pop('action_result') + r.observe_navigation(receipt, pose(), now, (r.sequence, r.option), 'run') + # Close enough for the former distance threshold, but no current rear view. + assert r.tick(pose(-.45), now+3, choose) == (None, 'surveying') + assert r.active + assert r.tick(pose(-.45), now+12, choose) == (None, 'surveying') + assert r.excluded == [selected['goal']] + r.tick(pose(-.45), now+12.1, choose) + assert r.native_action is None