Files
NODEDC_MISSION_CORE/simulation/ai-polygon/urban_crossing.py
T

218 lines
12 KiB
Python

"""Observed crossing-area permission for the static simulation contour.
A zebra is an area, not a set of paint islands. Admission retains a bounded
metric footprint after a measured approach 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
from collections import OrderedDict
import numpy as np
from scipy import ndimage
from scipy.spatial import ConvexHull, QhullError
class MarkedCrossing:
stop_seconds = .6
# Geometric reconstruction tolerances, not traffic clearance margins.
grid_m = .2
ground_tolerance_m = .1
def __init__(self, geometry, *, observation_range_m=12.):
if not math.isfinite(observation_range_m) or not 12 <= observation_range_m <= 40:
raise ValueError("Invalid crossing observation range")
self.observation_range_m = observation_range_m
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) < self.observation_range_m
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]) >= self.observation_range_m:
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."""
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
# 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.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:
state['state'] = 'incomplete-crossing'
continue
# Semantic permission must be established before native planning
# can approach across the road's unknown-cell inflation boundary.
# Requiring proximity to paint creates a circular precondition:
# motion needs permission, permission needs the forbidden motion.
# The measured footprint, exit and stopped observation bound this
# static-scene exception; it never grants the intervening road or
# replaces current swept-body/support/object admission.
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
& (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()
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)
ground = np.abs(height) <= .1+distance*math.tan(math.radians(self.geometry['max_slope_degrees']))
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 < 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}
if self.active is not None:
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) > max(16., self.observation_range_m+self.geometry["length_m"])):
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:
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 < self.observation_range_m)
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
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.
mask = denied.copy()
mask[pixels[0][admitted], pixels[1][admitted]] = True
mask[pixels[0][~admitted], pixels[1][~admitted]] = False
return mask, {**state, 'state': 'crossing', 'admitted': True, 'active': True,
'entry_stop_confirmed': True, 'permitted_ground_points': int(admitted.sum()),
'footprint_world_xy': (a['polygon'] @ a['axes'].T + a['origin'][:2]).tolist()}