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