From e61aa6da5fca2def08a710be98f2b97032fd0d54 Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Fri, 9 Oct 2026 23:01:29 +0300 Subject: [PATCH] Admit observed crossing ground between zebra markings --- .../ai-polygon/continuous_composition.py | 4 +- simulation/ai-polygon/navigation_client.py | 10 +- simulation/ai-polygon/urban_crossing.py | 223 +++++++++++------- tests/test_marked_crossing.py | 120 ++++++++++ 4 files changed, 261 insertions(+), 96 deletions(-) create mode 100644 tests/test_marked_crossing.py diff --git a/simulation/ai-polygon/continuous_composition.py b/simulation/ai-polygon/continuous_composition.py index 4d789fa5..4c2289e9 100644 --- a/simulation/ai-polygon/continuous_composition.py +++ b/simulation/ai-polygon/continuous_composition.py @@ -82,10 +82,10 @@ class ContinuousComposition(ComposedInference): np.ones_like(permitted, dtype=bool), self.environment, self.segmenter_id, self.models.labels) permissions |= crossing_mask - permitted |= crossing_mask & values["segmentation.surface"] + permitted |= crossing_mask values["navigation.surface"] = permitted allowed = permissions[indices] - known = values["segmentation.known"][indices] & (permitted[indices] | ~allowed) + known = (values["segmentation.known"][indices] | crossing_mask[indices]) & (permitted[indices] | ~allowed) known &= self.camera_source.semantic_pixels(u[visible], v[visible]) sample = { "samples": np.column_stack((points[visible][known], allowed[known].astype(int))).tolist(), diff --git a/simulation/ai-polygon/navigation_client.py b/simulation/ai-polygon/navigation_client.py index e91f0861..4b41fe3c 100644 --- a/simulation/ai-polygon/navigation_client.py +++ b/simulation/ai-polygon/navigation_client.py @@ -559,10 +559,12 @@ class ComposedInference: crossing = inputs.get("source.crossing-mask") if crossing is not None and self.environment == "urban" and self.segmenter_id == "simulation-sam3-surfaces": crossing = np.asarray(crossing, dtype=bool) - if crossing.shape != surface.shape or np.any(crossing & (inputs["segmentation.labels"] != 3)): - raise ValueError("Crossing admission exceeds observed marking") + if crossing.shape != surface.shape or np.any(crossing & ~np.isin(inputs["segmentation.labels"], (0, 1, 2, 3))): + raise ValueError("Crossing admission exceeds ground surface classes") + if crossing.any() and not inputs.get("source.crossing-admission", {}).get("admitted"): + raise ValueError("Crossing ground requires manoeuvre admission") permissions |= crossing - surface |= crossing & inputs["segmentation.surface"] + surface |= crossing observed_goals = getattr(self, "observed_goals", None) semantic_observation = inputs.get("source.semantic-observation") if observed_goals is not None and semantic_observation is not None: @@ -678,7 +680,7 @@ class ComposedInference: "navigation.goal": self.goal, "navigation.intent": intent, "navigation.surface": surface, - "navigation.semantic-known": inputs["segmentation.known"], + "navigation.semantic-known": inputs["segmentation.known"] | (crossing if crossing is not None else False), # Low confidence is not a semantic obstacle. Keep that gate in # visual_goal, but persist only explicit profile exclusions in CMU. "navigation.permissions": permissions, diff --git a/simulation/ai-polygon/urban_crossing.py b/simulation/ai-polygon/urban_crossing.py index d72ca714..2eec6a2b 100644 --- a/simulation/ai-polygon/urban_crossing.py +++ b/simulation/ai-polygon/urban_crossing.py @@ -1,116 +1,159 @@ -"""Marked-crossing admission for the static RGB/range simulation contour. +"""Observed crossing-area permission for the static simulation contour. -This admits only the observed crosswalk component after a measured stop and -an observed sidewalk exit. It is not a traffic-light/right-of-way estimator; -physical deployment and moving-traffic qualification need that separate owner. -Range, body, semantic freshness and road-user collision vetoes remain active. +A zebra is an area, not a set of paint islands. Admission retains a bounded +metric footprint after a measured entry stop and observed sidewalk exit. Only +current ground returns inside it can override unknown/carriageway semantics. +This is not traffic right-of-way: range, body, freshness and object vetoes remain +independent. Moving traffic needs a separately qualified gap/occlusion policy. """ import math import numpy as np -from PIL import Image, ImageDraw +from scipy import ndimage +from scipy.spatial import ConvexHull, QhullError class MarkedCrossing: - speed_limit_mps = .3 stop_seconds = .6 + # Geometric reconstruction tolerances, not traffic clearance margins. + grid_m = .2 + ground_tolerance_m = .1 def __init__(self, geometry): self.geometry = geometry self.previous = self.stopped_since = self.active = None + def _groups(self, local, candidate): + """Join neighbouring paint islands in metres, never the entire raster.""" + indices = np.flatnonzero(candidate) + if not len(indices): + return [] + cells = np.floor(local[indices] / self.grid_m).astype(int) + low = cells.min(axis=0) + cells -= low + occupied = np.zeros(tuple(cells.max(axis=0) + 7), dtype=bool) + cells += 3 + occupied[tuple(cells.T)] = True + y, x = np.mgrid[-3:4, -3:4] + # Two 0.6m neighbourhoods bridge ordinary stripe gaps; distant + # crossings stay separate. A hull is built per connected group. + grown = ndimage.binary_dilation(occupied, structure=x*x+y*y <= 9) + components, _ = ndimage.label(grown) + owners = components[tuple(cells.T)] + return [indices[owners == key] for key in np.unique(owners)] + + def _admit(self, points, local, sampled, ground, candidate, pose, axes, now): + state = {'state': 'approach' if candidate.any() else 'sidewalk'} + groups = sorted(self._groups(local, candidate), + key=lambda ids: float(np.linalg.norm(local[ids], axis=1).min())) + for ids in groups: + if len(ids) < 12: + continue + patch = local[ids] + low, high = patch.min(axis=0), patch.max(axis=0) + if high[1]-low[1] < self.geometry['width_m']+.1 or high[0]-low[0] < 1: + continue + # Keep a measured ground plane as well as XY bounds: an unknown + # bus, wall or person above the crossing is never permitted ground. + xyz = points[ids] - pose[:3] + design = np.column_stack((xyz[:, :2], np.ones(len(xyz)))) + plane, _, rank, _ = np.linalg.lstsq(design, xyz[:, 2], rcond=None) + 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 + & (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) + 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: + state['state'] = 'incomplete-crossing' + continue + if np.linalg.norm(patch, axis=1).min() > self.geometry['length_m']/2+1.25: + continue + if self.stopped_since is None or now-self.stopped_since < self.stop_seconds: + 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 + & (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])) + try: + hull = ConvexHull(footprint) + except QhullError: + continue + self.active = dict(origin=pose[:3].copy(), axes=axes.copy(), plane=plane, + polygon=footprint[hull.vertices], equations=hull.equations, + exit_forward=float(np.max(exit_points[:, 0]))) + return state + return state + def observe(self, labels, points, pixels, pose, captured_at, *, advance=True): labels = np.asarray(labels) points = np.asarray(points, dtype=float).reshape(-1, 3) pose = np.asarray(pose, dtype=float) - if (labels.shape != (512,512) or not np.isfinite(points).all() + if (labels.shape != (512, 512) or not np.isfinite(points).all() or pose.shape != (7,) or not np.isfinite(pose).all() or not math.isfinite(captured_at) or len(points) != len(pixels[0])): raise ValueError('Invalid crossing observation') denied = np.zeros(labels.shape, dtype=bool) - x,y,z,w=pose[3:]; yaw=math.atan2(2*(w*z+x*y),1-2*(y*y+z*z)) - axes=np.array([[math.cos(yaw),-math.sin(yaw)],[math.sin(yaw),math.cos(yaw)]]) - local=(points[:,:2]-pose[:2])@axes - sampled=labels[pixels] - up=np.array([2*(x*z+w*y),2*(y*z-w*x),1-2*(x*x+y*y)]) - height=(points-pose[:3])@up+self.geometry['body_contact_height_m'] - distance=np.linalg.norm(local,axis=1) - # This selects semantic ground candidates; it does not certify their - # physical support. The existing 3D surface/body guards own that check. - 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]): + x, y, z, w = pose[3:] + yaw = math.atan2(2*(w*z+x*y), 1-2*(y*y+z*z)) + axes = np.array([[math.cos(yaw), -math.sin(yaw)], [math.sin(yaw), math.cos(yaw)]]) + local = (points[:, :2]-pose[:2]) @ axes + sampled = labels[pixels] + up = np.array([2*(x*z+w*y), 2*(y*z-w*x), 1-2*(x*x+y*y)]) + 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: - before, previous_pose=self.previous; dt=now-before - stable=(0=math.cos(.01/2)) - self.stopped_since=(before if self.stopped_since is None else self.stopped_since) if stable else None - self.previous=(now,pose.copy()) + before, previous_pose = self.previous + dt = now-before + stable = (0 < dt <= 2 and np.linalg.norm(pose[:2]-previous_pose[:2])/dt <= .02 + and abs(float(pose[3:] @ previous_pose[3:])) >= math.cos(.01/2)) + self.stopped_since = ((before if self.stopped_since is None else self.stopped_since) + if stable else None) + self.previous = (now, pose.copy()) elif self.previous is not None and now < self.previous[0]: - return denied, {'state':'stale-observation','admitted':False} + return denied, {'state': 'stale-observation', 'admitted': False} if self.active is not None: - a=self.active; relative=(pose[:2]-a['origin'])@a['axes'] - if relative[0]>a['upper'][0]+self.geometry['length_m']/2: - self.active=None;self.stopped_since=None - state={'state':'approach' if candidate.any() else 'sidewalk','admitted':False, - 'active':self.active is not None, - 'speed_limit_mps':self.speed_limit_mps if self.active is not None else None, - 'scope':'static-simulation; marked area only; no traffic-priority certification'} - if not candidate.any(): - return denied,{**state,'active':self.active is not None, - 'speed_limit_mps':self.speed_limit_mps if self.active is not None else None} - indices=np.flatnonzero(candidate) - if self.active is not None: - a=self.active; coords=(points[indices,:2]-a['origin'])@a['axes'] - matching=np.all((coords>=a['lower']-.4)&(coords<=a['upper']+.4),axis=1) - indices=indices[matching] - if not len(indices):return denied,{**state,'state':'different-crossing','active':True, - 'speed_limit_mps':self.speed_limit_mps} - image=Image.fromarray((labels==3).astype(np.uint8)).copy() - seen=np.zeros(labels.shape,dtype=bool); component=None; attempts=0; chosen=None - for seed in indices[np.argsort(distance[indices])]: - if seen[pixels[0][seed],pixels[1][seed]]:continue - attempts+=1 - if attempts>16:break - ImageDraw.floodfill(image,(int(pixels[1][seed]),int(pixels[0][seed])),2) - region=(np.asarray(image)==2)&~seen; seen|=region - measured=candidate & region[pixels] - patch=local[measured] - if len(patch)<(3 if self.active is not None else 12):continue - low,high=np.min(patch,axis=0),np.max(patch,axis=0) - # A spatial area wider than the vehicle, not an isolated stripe. - # Entry proves the complete marked area and its exit. Near that - # exit the same component becomes a short visible strip: retain - # its observed permission without demanding another full crossing. - # Seeds still have to match the active area's measured bounds. - if (self.active is not None or - (high[1]-low[1]>=self.geometry['width_m']+.1 and high[0]-low[0]>=1.)): - evidence=int(np.count_nonzero(region[pixels][indices])) - if chosen is None or evidence>chosen[0]: - chosen=(evidence,region,measured,low,high,seed) - if self.active is None:break - if chosen is None:return denied,{**state,'state':'insufficient-marked-area'} - # A tiny near-camera fragment must not replace the main marked area - # merely because one of its rays is closer. Track the component with - # the most current range evidence inside this already admitted area. - _,component,measured,low,high,seed=chosen - exit_mask=(sampled==1)&ground&(local[:,0]>=high[0]-.3)&(local[:,0]<=high[0]+4) - exit_mask &= (local[:,1]>=low[1]-.5)&(local[:,1]<=high[1]+.5) - exit_points=local[exit_mask] - exit_seen=(len(exit_points)>=3 and np.linalg.eigvalsh(np.cov(exit_points.T))[0]>1e-4) - state.update(marked_points=int(measured.sum()),exit_points=int(exit_mask.sum()), - observed_exit=bool(exit_seen),marked_width_m=float(high[1]-low[1])) + a = self.active + relative = (pose[:2]-a['origin'][:2]) @ a['axes'] + # Completion and abandonment revoke this manoeuvre. It cannot + # expand indefinitely by following unrelated new yellow pixels. + if (relative[0] > a['exit_forward']+self.geometry['length_m']/2 + or np.linalg.norm(relative) > 16): + self.active = None + self.stopped_since = None + 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: - if not exit_seen:return denied,{**state,'state':'incomplete-crossing'} - if distance[seed]>self.geometry['length_m']/2+1.25: - return denied,state - if self.stopped_since is None or now-self.stopped_since= 1) & (points[:, 0] <= 6.1) & (np.mod(points[:, 0]+.01, 1) < .45) + sidewalk = near & ((points[:, 0] < 1) | (points[:, 0] >= 6.5)) + labels[pixels[0][paint], pixels[1][paint]] = 3 + labels[pixels[0][sidewalk], pixels[1][sidewalk]] = 1 + return labels, points, pixels, np.array([0, 0, .37, 0, 0, 0, 1.]) + + +def gate(module): + return module.MarkedCrossing(dict(length_m=1.16, width_m=.905, + body_contact_height_m=.37, max_slope_degrees=25)) + + +def enter(g, data): + g.observe(*data, 10.) + g.observe(*data, 10.4) + return g.observe(*data, 10.8) + + +def test_stripes_admit_connected_ground_gaps_only_after_entry_stop(module): + data = scene(); labels, points, pixels, _ = data; g = gate(module) + mask, status = g.observe(*data, 10.) + assert not mask.any() and status['state'] == 'waiting-for-stop' + g.observe(*data, 10.4) + mask, status = g.observe(*data, 10.8) + assert status['admitted'] and status['speed_limit_mps'] is None + inside = (points[:, 0] > 1.1) & (points[:, 0] < 6.1) & (np.abs(points[:, 1]) < .9) + assert mask[pixels][inside].all() + assert mask[pixels][inside & (labels[pixels] == 0)].any() + assert not mask[pixels][np.abs(points[:, 1]) > 1.1].any() + + +def test_exit_evidence_and_ground_area_are_required(module): + data = scene(); labels, _, pixels, _ = data + labels[labels == 1] = 0 + mask, status = enter(gate(module), data) + assert not mask.any() and not status['admitted'] + labels[:] = 0 + labels[pixels[0][:8], pixels[1][:8]] = 3 + assert not enter(gate(module), data)[0].any() + + +def test_active_crossing_survives_paint_flicker_but_not_obstacles_or_new_road(module): + data = scene(); labels, points, pixels, pose = data; g = gate(module) + original, status = enter(g, data) + assert status['admitted'] + labels[labels == 3] = 0 + mask, _ = g.observe(*data, 11.) + np.testing.assert_array_equal(mask, original) + ix = np.flatnonzero(mask[pixels])[:3] + # Unknown raised object, explicit wall, and explicit conflict each veto. + points[ix[0], 2] = 1. + labels[pixels[0][ix[1]], pixels[1][ix[1]]] = 4 + labels[pixels[0][ix[2]], pixels[1][ix[2]]] = 5 + mask, _ = g.observe(*data, 11.2) + assert not mask[pixels][ix].any() + assert not mask[pixels][np.abs(points[:, 1]) > 1.1].any() + assert not g.observe(*data, 9.)[0].any() # out-of-order input + pose[0] = 10. + mask, status = g.observe(*data, 12.) + assert not mask.any() and not status['active'] + + +def test_grouping_does_not_join_distant_markings(module): + g = gate(module) + local = np.array([[1, 0], [1, .2], [2, 0], [2, .2], [8, 0], [8, .2]]) + groups = g._groups(local, np.ones(len(local), bool)) + assert sorted(map(len, groups)) == [2, 4] + + +def test_unknown_crossing_ground_reaches_semantic_memory(monkeypatch, module): + composition = importlib.import_module('continuous_composition') + labels, points, pixels, pose = scene(); g = gate(module) + enter(g, (labels, points, pixels, pose)) + # Isolate the integration boundary: calibrated point projection/model input + # stay fixed while original unknown confidence remains false. + obj = object.__new__(composition.ContinuousComposition) + obj.environment, obj.segmenter_id = 'urban', 'simulation-sam3-surfaces' + 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)) + monkeypatch.setattr(composition, 'project', lambda *a:(None, np.zeros(len(points)), + np.zeros(len(points)), np.ones(len(points),bool))) + 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]}, + captured_at=11., points=points, pose=pose, + camera_sources={'insta360_left':None,'insta360_right':None}, lens_depths=[]) + with ThreadPoolExecutor(max_workers=1) as pool: + obj.pool = pool + result = obj.perceive_view(observation, 1, 0, detect=False) + samples = np.asarray(result['samples']['samples']) + expected_unknown = result['values']['source.crossing-mask'][pixels] & (labels[pixels] == 0) + assert expected_unknown.any() + 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])