"""Conservative projective clearing at the declared range-image resolution. All corners of a voxel must project inside one sensor's measured image. Every sample covering that footprint must report free range beyond its farthest corner. Invalid/self-occluded samples, image edges and depth discontinuities cannot clear it. This removes surfaces, never creates ground observations. """ import itertools import numpy as np VIEW_FIELDS = ("view_models", "view_sizes", "view_axes", "view_parameters", "view_ranges") def sensor_range_limits(value, count): """Limits come from captured run configuration, never from a sensor packet.""" limits = np.full(count, 8.) if value is None else np.asarray(value, dtype=float) if (limits.shape != (count,) or not np.isfinite(limits).all() or np.any(limits <= 0) or np.any(limits > 40.)): raise ValueError("Invalid sensor range limits") return limits class RangeImages: def __init__(self, origins, packet, *, range_limits_m=None): self.origins = np.asarray(origins, dtype=float) self.models = np.asarray(packet["view_models"]) self.sizes = np.asarray(packet["view_sizes"]) self.axes = np.asarray(packet["view_axes"], dtype=float) self.parameters = np.asarray(packet["view_parameters"], dtype=float) self.ranges = np.asarray(packet["view_ranges"], dtype=float) n = len(self.models) if (not 1 <= n <= 8 or self.models.shape != (n,) or self.origins.shape != (n, 3) or self.sizes.shape != (n, 2) or self.axes.shape != (n, 3, 3) or self.parameters.shape != (n, 4) or not np.issubdtype(self.models.dtype, np.integer) or not np.issubdtype(self.sizes.dtype, np.integer) or not np.isin(self.models, [0, 1]).all() or np.any(self.sizes < 2) or np.any(self.sizes > 4096) or not all(np.isfinite(a).all() for a in (self.origins, self.axes, self.parameters, self.ranges)) or not np.allclose(self.axes.transpose(0, 2, 1) @ self.axes, np.eye(3), atol=1e-5) or not np.allclose(np.linalg.det(self.axes), 1, atol=1e-5)): raise ValueError("Invalid organized range calibration") counts = np.prod(self.sizes, axis=1) limits = sensor_range_limits(range_limits_m, n) count = int(counts.sum()) if (count > 8000 or self.ranges.shape != (count,) or np.any(self.ranges < 0) or np.any(self.ranges > np.repeat(limits, counts) + .01)): raise ValueError("Invalid organized range samples") for model, (w, h), p in zip(self.models, self.sizes, self.parameters, strict=True): if model == 0: if (p[1] <= 0 or p[3] <= 0 or abs(w*p[1]-360) > 1e-6 or p[2] <= -90 or p[2]+(h-1)*p[3] >= 90): raise ValueError("Invalid spherical range calibration") elif p[0] <= 0 or p[1] <= 0: raise ValueError("Invalid pinhole range calibration") def cleared(self, points, voxel_m, margin_m): points = np.asarray(points, dtype=float).reshape(-1, 3) result = np.zeros(len(points), dtype=bool) if not len(points): return result offsets = np.asarray(list(itertools.product((0, 1), repeat=3))) * voxel_m corners = np.floor(points[:, None, :] / voxel_m)*voxel_m + offsets offset = 0 for model, (w, h), origin, axes, p in zip( self.models, self.sizes, self.origins, self.axes, self.parameters, strict=True): image = self.ranges[offset:offset+w*h].reshape(h, w) offset += w*h # Clearing requires EVERY corner and EVERY pixel in its footprint. # A single corner/pixel that fails is therefore a sufficient veto. # Most retained returns are still occluded: reject those cheaply # before projecting the other seven corners. Survivors still take # the complete original test below; this grants no new free space. first = (corners[:, :1, :]-origin) @ axes first_distance = np.linalg.norm(first, axis=2)[:, 0] if model == 0: first_u = (np.degrees(np.arctan2(first[..., 1], first[..., 0]))-p[0])/p[1] first_u = (first_u + (first_u-first_u+w/2) % w-w/2)[:, 0] first_v = ((np.degrees(np.arctan2(first[..., 2], np.linalg.norm(first[..., :2], axis=2)))-p[2])/p[3])[:, 0] eligible = np.ones(len(points), dtype=bool) else: front = first[:, 0, 0] eligible = front > 1e-6 denominator = np.maximum(front, 1e-6) first_u = p[2]-p[0]*first[:, 0, 1]/denominator-0.5 first_v = p[3]-p[1]*first[:, 0, 2]/denominator-0.5 eligible &= (np.floor(first_u) >= 0) & (np.ceil(first_u) < w) eligible &= ((first_distance > margin_m) & (np.floor(first_v) >= 0) & (np.ceil(first_v) < h) & ~result) candidates = np.flatnonzero(eligible) measured = image[np.floor(first_v[candidates]).astype(int), np.floor(first_u[candidates]).astype(int) % w] candidates = candidates[measured > first_distance[candidates]+margin_m] if not len(candidates): continue local = (corners[candidates]-origin) @ axes distance = np.linalg.norm(local, axis=2) if model == 0: u = (np.degrees(np.arctan2(local[..., 1], local[..., 0]))-p[0])/p[1] # Unwrap each voxel locally across the azimuth image seam. u = u[:, :1] + (u-u[:, :1]+w/2) % w-w/2 v = (np.degrees(np.arctan2(local[..., 2], np.linalg.norm(local[..., :2], axis=2)))-p[2])/p[3] visible = np.ones(len(candidates), dtype=bool) else: front = local[..., 0] visible = (front > 1e-6).all(axis=1) denominator = np.maximum(front, 1e-6) u = p[2]-p[0]*local[..., 1]/denominator-0.5 v = p[3]-p[1]*local[..., 2]/denominator-0.5 low_u, high_u = np.floor(u.min(axis=1)), np.ceil(u.max(axis=1)) low_v, high_v = np.floor(v.min(axis=1)), np.ceil(v.max(axis=1)) visible &= (distance.min(axis=1) > margin_m) & (low_v >= 0) & (high_v < h) if model == 1: visible &= (low_u >= 0) & (high_u < w) # A near-sensor voxel spanning a large portion of the image stays # unknown. Bound work, without subsampling its clearing footprint. visible &= (high_u-low_u <= 8) & (high_v-low_v <= 8) indices = np.flatnonzero(visible) if not len(indices): continue lu, hu = low_u[indices].astype(int), high_u[indices].astype(int) lv, hv = low_v[indices].astype(int), high_v[indices].astype(int) free = np.ones(len(indices), dtype=bool) required = distance[indices].max(axis=1)+margin_m for dv in range(int((hv-lv).max())+1): for du in range(int((hu-lu).max())+1): inside = (dv <= hv-lv) & (du <= hu-lu) rows = np.flatnonzero(inside) measured = image[lv[rows]+dv, (lu[rows]+du) % w] free[rows] &= measured > required[rows] result[candidates[indices[free]]] = True return result