diff --git a/simulation/ai-polygon/navigation/observed_goals.py b/simulation/ai-polygon/navigation/observed_goals.py index 3d7f8a73..f207a736 100644 --- a/simulation/ai-polygon/navigation/observed_goals.py +++ b/simulation/ai-polygon/navigation/observed_goals.py @@ -6,8 +6,10 @@ the native planner still admits the complete commanded body sweep. """ import math +from collections import OrderedDict import numpy as np +from scipy.spatial import cKDTree from .semantic_surface import SemanticSurface @@ -15,13 +17,25 @@ from .semantic_surface import SemanticSurface class ObservedGoals: def __init__(self, *, reverse_heading_tolerance=math.pi/4): self.reverse_heading_tolerance = reverse_heading_tolerance - self.surface = SemanticSurface(retain_near=True) + # Intent and native terrain use the same bounded, capture-deduplicated + # evidence rule. A single conflicting segmentation must not cancel a + # progressing path that repeated observations still support. Geometry + # and live swept-body guards remain immediate and independent. + self.surface = SemanticSurface(retain_near=True, fuse_observations=True) self.measured = {} + self.seen_semantics = OrderedDict() self.evidence = None self.clearance_observation = None + self.clearance_index = None - def observe(self, samples, captured_at, pose): - self.surface.observe(samples, captured_at, pose) + def observe(self, samples, captured_at, pose, *, frame_id=None, capture_id=None): + if frame_id is not None and frame_id in self.seen_semantics: + return + self.surface.observe(samples, captured_at, pose, evidence_id=capture_id) + if frame_id is not None: + self.seen_semantics[frame_id] = True + while len(self.seen_semantics) > 128: + self.seen_semantics.popitem(last=False) sample = np.asarray(samples, dtype=float).reshape(-1, 4) for key, point in zip(self.surface.cell_keys(sample), sample, strict=True): self.measured[tuple(key)] = point[:3].copy() @@ -46,7 +60,7 @@ class ObservedGoals: raise ValueError("Invalid observed clearance guidance") self.clearance_observation = (captured_at, points.copy()) - def approach_clearance(self, candidates, pose, geometry, now): + def approach_clearance(self, candidates, pose, geometry, now, *, lookahead_m=None): """Minimum obstacle distance along candidate approaches, in metres. These straight segments rank spatial intentions; they are not paths. @@ -58,34 +72,40 @@ class ObservedGoals: 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] + if not len(candidates): + return distances + if self.clearance_index is None or self.clearance_index[0] is not observed: + self.clearance_index = (observed, cKDTree(observed[1])) + tree = self.clearance_index[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 - squared = np.sum(offsets*offsets, axis=1) + 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) + 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)) - # Exact point-to-segment distance without an N*M*2 temporary or - # a threaded BLAS call for a two-coordinate product. - projection = (direction[first:last, 0, None]*offsets[None, :, 0] - + direction[first:last, 1, None]*offsets[None, :, 1]) - along = np.clip(projection, start[first:last, None], length[first:last, None]) - square_distance = squared[None] + along*(along-2*projection) - distances[first:last] = np.sqrt(np.maximum(0., np.min(square_distance, axis=1))) + 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] + + np.minimum(np.arange(int(steps.max())+1)[None], steps[:, None]) + * spacing[:, None]) + 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) return distances - def clearance_cost(self, candidates, pose, geometry, now): - clearance = self.approach_clearance(candidates, pose, geometry, now) + def clearance_cost(self, candidates, pose, geometry, now, *, lookahead_m=None): + clearance = self.approach_clearance(candidates, pose, geometry, now, + lookahead_m=lookahead_m) return 4*geometry['width_m']*np.exp(-clearance/geometry['width_m']), clearance def boundary_cost(self, candidates, geometry, now): @@ -318,7 +338,9 @@ class ObservedGoals: and (candidate_mask is None or candidate_mask(before[None])[0]) and supported(before)): retain = before - retained_clearance = (self.approach_clearance(retain[None], pose, geometry, now)[0] + horizon = min(remaining, 3.5) + retained_clearance = (self.approach_clearance( + retain[None], pose, geometry, now, lookahead_m=horizon)[0] if retain is not None else None) if retain is not None and retained_clearance >= geometry['width_m']: # The selection rule below cannot replace this still supported @@ -333,7 +355,6 @@ class ObservedGoals: # and make successive measured goals oscillate across the corridor. # This reference only ranks actual permitted returns. It is never a # generated drive goal, a straight-line route or a clearance receipt. - horizon = min(remaining, 3.5) reference = pose[:2] + forward * horizon # A smooth local attraction, normalized to metres like boundary_cost. # Its gradient diminishes near the reference so centimetres of extra @@ -345,7 +366,8 @@ 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) + clearance_cost, clearances = self.clearance_cost( + candidates, pose, geometry, now, lookahead_m=horizon) score += clearance_cost for index in np.argsort(score, kind="stable"): if supported(candidates[index]): diff --git a/simulation/ai-polygon/navigation_client.py b/simulation/ai-polygon/navigation_client.py index b816251e..e91f0861 100644 --- a/simulation/ai-polygon/navigation_client.py +++ b/simulation/ai-polygon/navigation_client.py @@ -567,7 +567,8 @@ class ComposedInference: semantic_observation = inputs.get("source.semantic-observation") if observed_goals is not None and semantic_observation is not None: for sample in semantic_observation: - observed_goals.observe(sample["samples"], sample["captured_at"], sample["pose"]) + observed_goals.observe(sample["samples"], sample["captured_at"], sample["pose"], + frame_id=sample.get("frame_id"), capture_id=sample.get("capture_id")) elif observed_goals is not None: calibration = inputs["source.camera.calibration"] points = inputs["source.lidar"] diff --git a/tests/test_ai_polygon_observed_goals.py b/tests/test_ai_polygon_observed_goals.py index 5652a08c..5e42c2ac 100644 --- a/tests/test_ai_polygon_observed_goals.py +++ b/tests/test_ai_polygon_observed_goals.py @@ -325,9 +325,9 @@ def test_clear_retained_intent_does_not_recompute_alternative_approaches(selecto selector.observe_navigation(clearance_receipt(position, [[1.6, 1.5]]), position, 1, 'run', 1.) evaluate = selector.approach_clearance sizes = [] - def measured(candidates, *args): + def measured(candidates, *args, **kwargs): sizes.append(len(candidates)) - return evaluate(candidates, *args) + return evaluate(candidates, *args, **kwargs) monkeypatch.setattr(selector, 'approach_clearance', measured) assert selector.choose(points, position, target, goal, (), GEOMETRY, 1.1) == goal assert sizes == [1] @@ -337,7 +337,7 @@ def test_clear_retained_intent_does_not_recompute_alternative_approaches(selecto assert max(sizes) > 1 -def test_clearance_matches_exact_continuous_segments(selector): +def test_clearance_is_bounded_below_exact_continuous_segments(selector): rng = np.random.default_rng(122) position = [17., -31., .37, 0., 0., 0., 1.] candidates = np.c_[rng.uniform(-3., 3., (259, 2))+position[:2], np.zeros(259)] @@ -353,4 +353,60 @@ def test_clearance_matches_exact_continuous_segments(selector): b = goal[:2] projection = np.clip((obstacles-a) @ (b-a) / max(np.sum((b-a)**2), 1e-20), 0, 1) expected.append(np.min(np.linalg.norm(obstacles-(a+projection[:, None]*(b-a)), axis=1))) - np.testing.assert_allclose(actual, expected, atol=1e-7, rtol=1e-7) + assert np.all(actual <= np.asarray(expected)+1e-10) + assert np.max(np.asarray(expected)-actual) <= .025+1e-10 + + +@pytest.mark.parametrize('yaw,shift', [(0, (0, 0)), (73, (42, -17)), (-138, (-250, 52))]) +def test_short_goal_cannot_hide_an_obstacle_beyond_its_endpoint(selector, yaw, shift): + points, position, target, _, rotation = road(yaw, shift) + selector.observe(np.c_[points, np.ones(len(points))], 1., position) + short = np.array([*[1.36, -.06] @ rotation.T + shift, 0.]) + pole = np.array([[3., -.25]]) @ rotation.T + shift + selector.observe_navigation(clearance_receipt(position, pole.tolist()), position, 1, 'run', 1.) + # Its endpoint is far from the pole, but its continuing bearing is not. + assert selector.approach_clearance(short[None], position, GEOMETRY, 1.1)[0] > 1.5 + assert selector.approach_clearance(short[None], position, GEOMETRY, 1.1, + lookahead_m=3.5)[0] < .3 + goal = selector.choose(points, position, target, short, (), GEOMETRY, 1.1) + assert ((np.array(goal[:2])-shift) @ rotation)[1] > .3 + assert np.min(np.linalg.norm(points-goal, axis=1)) < 1e-9 + + +def test_repeated_surface_evidence_survives_one_conflicting_frame_not_a_persistent_prohibition(selector): + points, position, target, _, _ = road() + geometry = {**GEOMETRY, 'length_m': 1.163, 'max_step_m': .1} + for stamp in [1., 2., 3.]: + selector.observe(np.c_[points, np.ones(len(points))], stamp, position) + prior = selector.maneuver(points, position, target, None, (), geometry, 3.) + forbidden = np.c_[points, np.zeros(len(points))] + selector.observe(forbidden, 4., position) + assert selector.maneuver(points, position, target, prior, (), geometry, 4.) == prior + # Reusing the same neural frame on many range ticks is one vote only. + for _ in range(5): + selector.observe(forbidden, 4., position) + assert selector.maneuver(points, position, target, prior, (), geometry, 4.5) == prior + selector.observe(forbidden, 5., position) + selector.observe(forbidden, 6., position) + assert selector.maneuver(points, position, target, prior, (), geometry, 6.) is None + fresh = type(selector)() + fresh.observe(forbidden, 1., position) + assert fresh.choose(points, position, target, None, (), geometry, 1.) is None + + +def test_alternating_cached_views_do_not_multiply_semantic_votes(selector): + points, position, target, _, _ = road() + positive = np.c_[points, np.ones(len(points))] + negative = np.c_[points, np.zeros(len(points))] + selector.observe(positive, 1., position, frame_id='a:front', capture_id='a') + selector.observe(positive, 2., position, frame_id='b:front', capture_id='b') + selector.observe(negative, 3., position, frame_id='c:front', capture_id='c') + selector.observe(negative, 3., position, frame_id='c:side', capture_id='c') + assert selector.choose(points, position, target, None, (), GEOMETRY, 3.) is not None + before = dict(selector.surface.cells) + for _ in range(5): + selector.observe(positive, 2., position, frame_id='b:front', capture_id='b') + selector.observe(negative, 3., position, frame_id='c:front', capture_id='c') + 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