From d0f6c80ee2b4d380466777c764766f73b3eb095e Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Sat, 10 Oct 2026 01:19:52 +0300 Subject: [PATCH] Reconstruct crossing permission from observed approach geometry --- .../ai-polygon/continuous_composition.py | 15 +++- simulation/ai-polygon/urban_crossing.py | 76 +++++++++++++++---- tests/test_marked_crossing.py | 60 ++++++++++++++- 3 files changed, 133 insertions(+), 18 deletions(-) diff --git a/simulation/ai-polygon/continuous_composition.py b/simulation/ai-polygon/continuous_composition.py index 4c2289e9..b96e27cd 100644 --- a/simulation/ai-polygon/continuous_composition.py +++ b/simulation/ai-polygon/continuous_composition.py @@ -87,8 +87,21 @@ class ContinuousComposition(ComposedInference): allowed = permissions[indices] known = (values["segmentation.known"][indices] | crossing_mask[indices]) & (permitted[indices] | ~allowed) known &= self.camera_source.semantic_pixels(u[visible], v[visible]) + samples = np.column_stack((points[visible][known], allowed[known].astype(int))) + if crossing.get("admitted"): + # The observed crossing AREA owns this semantic exception, including + # current range in the camera's near blind strip. Waiting for that + # ground to reappear in the image leaves old road prohibitions under + # the rover. No new points/support or traffic permission are created. + crossing_ground = self.crossing.ground_mask(points) + visible_indices = np.flatnonzero(visible) + crossing_ground[visible_indices[known]] = False # already classified + classes = values["segmentation.labels"][indices] + crossing_ground[visible_indices[~np.isin(classes, (0, 1, 2, 3))]] = False + samples = np.concatenate((samples, np.column_stack(( + points[crossing_ground], np.ones(int(crossing_ground.sum())))))) sample = { - "samples": np.column_stack((points[visible][known], allowed[known].astype(int))).tolist(), + "samples": samples.tolist(), "captured_at": observation["captured_at"], "pose": observation["pose"], "frame_id": f"{frame_id}:{yaw}:{pitch}", "capture_id": str(frame_id), } diff --git a/simulation/ai-polygon/urban_crossing.py b/simulation/ai-polygon/urban_crossing.py index 2eec6a2b..7bab7bf7 100644 --- a/simulation/ai-polygon/urban_crossing.py +++ b/simulation/ai-polygon/urban_crossing.py @@ -7,6 +7,7 @@ This is not traffic right-of-way: range, body, freshness and object vetoes remai independent. Moving traffic needs a separately qualified gap/occlusion policy. """ import math +from collections import OrderedDict import numpy as np from scipy import ndimage @@ -22,6 +23,46 @@ class MarkedCrossing: def __init__(self, geometry): self.geometry = geometry self.previous = self.stopped_since = self.active = None + self.measured = OrderedDict() + + def _remember(self, points, sampled, ground, pose): + """Join actual approach views before committing one crossing footprint. + + A close camera crop cannot replace the wider marking seen on approach. + This bounded static-scene semantic evidence supplies no ground/support + certificate. Current range and objects still veto every commanded sweep. + """ + near = np.linalg.norm(points[:, :2]-pose[:2], axis=1) < 12 + for point, label in zip(points[near & ground], sampled[near & ground]): + key = tuple(np.floor(point / [.2, .2, .06]).astype(int)) + if label in (1, 3): + self.measured[key] = (point.copy(), int(label)) + self.measured.move_to_end(key) + elif label in (4, 5): + self.measured.pop(key, None) + for key, (point, _) in list(self.measured.items()): + if np.linalg.norm(point[:2]-pose[:2]) >= 12: + del self.measured[key] + while len(self.measured) > 6000: + self.measured.popitem(last=False) + + def ground_mask(self, points): + """Crossing permission for current measured ground, including blind strips. + + The camera established the bounded area; range establishes which actual + returns are still on its measured plane. This neither fills missing + range nor turns elevated objects into permitted ground. + """ + points = np.asarray(points, dtype=float).reshape(-1, 3) + if self.active is None: + return np.zeros(len(points), dtype=bool) + a = self.active + relative = points-a['origin'] + coords = relative[:, :2] @ a['axes'] + inside = np.all(coords @ a['equations'][:, :2].T + a['equations'][:, 2] <= 1e-7, axis=1) + planar = np.abs(np.column_stack((relative[:, :2], np.ones(len(points)))) @ a['plane'] + - relative[:, 2]) <= self.ground_tolerance_m + return inside & planar & np.isfinite(points).all(axis=1) def _groups(self, local, candidate): """Join neighbouring paint islands in metres, never the entire raster.""" @@ -61,14 +102,16 @@ class MarkedCrossing: if (rank < 3 or np.linalg.norm(plane[:2]) > math.tan(math.radians(self.geometry['max_slope_degrees'])) or np.max(np.abs(design @ plane - xyz[:, 2])) > self.ground_tolerance_m): continue - planar = np.abs(np.column_stack((points[:, :2]-pose[:2], np.ones(len(points)))) @ plane - - (points[:, 2]-pose[2])) <= self.ground_tolerance_m - exit_mask = ((sampled == 1) & ground & planar + # A sidewalk exit can be higher than the painted asphalt. Its + # semantic identity anchors the crossing area, not a coplanarity + # assertion. Native contact/slope/step checks still own passage. + exit_mask = ((sampled == 1) & ground & (local[:, 0] >= high[0]-.3) & (local[:, 0] <= high[0]+4) & (local[:, 1] >= low[1]) & (local[:, 1] <= high[1])) exit_points = local[exit_mask] exit_seen = (len(exit_points) >= 3 - and np.linalg.eigvalsh(np.cov(exit_points.T))[0] > 1e-4) + and np.linalg.eigvalsh(np.cov(exit_points.T))[0] > 1e-4 + and np.ptp(exit_points[:, 1]) >= self.geometry['width_m']) state.update(marked_points=len(ids), exit_points=int(exit_mask.sum()), observed_exit=bool(exit_seen), marked_width_m=float(high[1]-low[1])) if not exit_seen: @@ -80,7 +123,7 @@ class MarkedCrossing: return {**state, 'state': 'waiting-for-stop'} # Connect marking to observed pedestrian entry/exit within the same # lateral span; no permission is extrapolated into unobserved road. - entry = ((sampled == 1) & ground & planar + entry = ((sampled == 1) & ground & (local[:, 0] >= low[0]-1.5) & (local[:, 0] < low[0]) & (local[:, 1] >= low[1]) & (local[:, 1] <= high[1])) footprint = np.vstack((patch, local[entry | exit_mask])) @@ -112,7 +155,6 @@ class MarkedCrossing: height = (points-pose[:3]) @ up + self.geometry['body_contact_height_m'] distance = np.linalg.norm(local, axis=1) ground = np.abs(height) <= .1+distance*math.tan(math.radians(self.geometry['max_slope_degrees'])) - candidate = (sampled == 3) & ground & (local[:, 0] > 0) & (distance < 12) now = captured_at if advance and (self.previous is None or now > self.previous[0]): if self.previous is not None: @@ -134,20 +176,28 @@ class MarkedCrossing: or np.linalg.norm(relative) > 16): self.active = None self.stopped_since = None + self.measured.clear() state = {'scope': 'static-simulation; observed crossing ground only; no traffic-priority certification', 'admitted': False, 'active': False, 'speed_limit_mps': None, 'speed_policy': 'mission-profile-with-independent-collision-limits'} if self.active is None: - state.update(self._admit(points, local, sampled, ground, candidate, pose, axes, now)) + self._remember(points, sampled, ground, pose) + if self.measured: + remembered = np.array([v[0] for v in self.measured.values()]) + classes = np.array([v[1] for v in self.measured.values()]) + relative = (remembered[:, :2]-pose[:2]) @ axes + distance = np.linalg.norm(relative, axis=1) + height = (remembered-pose[:3]) @ up + self.geometry['body_contact_height_m'] + on_ground = np.abs(height) <= .1+distance*math.tan(math.radians(self.geometry['max_slope_degrees'])) + paint = (classes == 3) & on_ground & (relative[:, 0] > 0) & (distance < 12) + state.update(self._admit(remembered, relative, classes, on_ground, + paint, pose, axes, now)) + else: + state['state'] = 'sidewalk' if self.active is None: return denied, state a = self.active - relative = points-a['origin'] - coords = relative[:, :2] @ a['axes'] - inside = np.all(coords @ a['equations'][:, :2].T + a['equations'][:, 2] <= 1e-7, axis=1) - planar = np.abs(np.column_stack((relative[:, :2], np.ones(len(points)))) @ a['plane'] - - relative[:, 2]) <= self.ground_tolerance_m - admitted = inside & planar & np.isin(sampled, (0, 1, 2, 3)) + admitted = self.ground_mask(points) & np.isin(sampled, (0, 1, 2, 3)) # Sparse raster permissions correspond to actual visible ground returns. # Never fill a 2D hull over an occluding object; duplicate projected # pixels with a non-ground return are conservatively denied. diff --git a/tests/test_marked_crossing.py b/tests/test_marked_crossing.py index cb0151bf..1f06ad67 100644 --- a/tests/test_marked_crossing.py +++ b/tests/test_marked_crossing.py @@ -89,7 +89,8 @@ def test_grouping_does_not_join_distant_markings(module): assert sorted(map(len, groups)) == [2, 4] -def test_unknown_crossing_ground_reaches_semantic_memory(monkeypatch, module): +@pytest.mark.parametrize("half_hidden", [False, True]) +def test_unknown_crossing_ground_reaches_semantic_memory(monkeypatch, module, half_hidden): composition = importlib.import_module('continuous_composition') labels, points, pixels, pose = scene(); g = gate(module) enter(g, (labels, points, pixels, pose)) @@ -100,10 +101,12 @@ def test_unknown_crossing_ground_reaches_semantic_memory(monkeypatch, module): obj.crossing = g obj.optics = SimpleNamespace(lens_axes=np.array([np.eye(3)]), rectify_forward=lambda *a: (np.zeros((600,800,3),np.uint8), None)) - obj.camera_source = SimpleNamespace(indices=lambda *a:pixels, - semantic_pixels=lambda *a:np.ones(len(points),bool)) + visible = points[:, 1] >= 0 if half_hidden else np.ones(len(points), bool) + observed_pixels = tuple(p[visible] for p in pixels) + obj.camera_source = SimpleNamespace(indices=lambda *a:observed_pixels, + semantic_pixels=lambda *a:np.ones(int(visible.sum()),bool)) monkeypatch.setattr(composition, 'project', lambda *a:(None, np.zeros(len(points)), - np.zeros(len(points)), np.ones(len(points),bool))) + np.zeros(len(points)), visible)) obj.models = SimpleNamespace(labels={}, surface=lambda rgb:{'segmentation.labels':labels, 'segmentation.surface':np.isin(labels, (1,2,3)), 'segmentation.known':labels != 0}) observation = dict(calibration={'lens_axes':[np.eye(3)], 'intrinsics':[1,1,1,1]}, @@ -118,3 +121,52 @@ def test_unknown_crossing_ground_reaches_semantic_memory(monkeypatch, module): permitted_points = set(map(tuple, samples[samples[:,3] == 1, :3])) assert all(tuple(p) in permitted_points for p in points[expected_unknown]) assert not any(tuple(p) in permitted_points for p in points[np.abs(points[:,1]) > 1.1]) + if half_hidden: + hidden_ground = g.ground_mask(points) & ~visible + assert hidden_ground.any() + assert all(tuple(p) in permitted_points for p in points[hidden_ground]) + + +def test_approach_measurements_survive_a_narrow_near_camera_view(module): + labels, points, pixels, pose = scene(); g = gate(module) + # See the complete marking from farther away, without granting admission. + far = pose.copy(); far[0] = -3 + assert not g.observe(labels, points, pixels, far, 10.)[1]['admitted'] + # At the entry, the crop sees only a narrow strip, not the crossing width. + seen = np.abs(points[:, 1]) < .3 + narrow = (labels, points[seen], tuple(p[seen] for p in pixels), pose) + g.observe(*narrow, 11.) + g.observe(*narrow, 11.4) + _, status = g.observe(*narrow, 11.8) + assert status['admitted'] + intended = (points[:, 0] > 1.1) & (points[:, 0] < 6) & (np.abs(points[:, 1]) < .9) + assert g.ground_mask(points)[intended].all() + # A memory-free crop does not have enough width to invent a crossing. + assert not enter(gate(module), narrow)[1]['admitted'] + + +def test_exit_sidewalk_need_not_be_coplanar_with_road(module): + data = scene(); labels, points, pixels, _ = data + sidewalk = labels[pixels] == 1 + points[sidewalk, 2] = .15 + mask, status = enter(gate(module), data) + assert status['admitted'] + assert mask[pixels][labels[pixels] == 3].all() + # Permission is not a certificate that this physical step can be crossed. + # Raised exit ground still relies on its own sidewalk and support evidence. + assert not mask[pixels][sidewalk].any() + + +def test_small_exit_fragment_is_not_a_rover_width_exit(module): + data = scene(); labels, points, pixels, _ = data + bad = (points[:, 0] >= 6.5) & (np.abs(points[:, 1]) >= .3) + labels[pixels[0][bad], pixels[1][bad]] = 0 + _, state = enter(gate(module), data) + assert state['exit_points'] > 3 + assert not state['admitted'] and not state['observed_exit'] + + +def test_retained_crossing_does_not_admit_new_ground_above_or_outside_it(module): + g = gate(module); assert enter(g, scene())[1]['admitted'] + points = np.array([[3, 0, 0], [3, 0, .4], [3, 2, 0], [3, 0, -1.]]) + assert g.ground_mask(points).tolist() == [True, False, False, False]