"""Selected robot swept-body check on CMU's observed terrain and chosen path. CMU's circular path table proposes paths. This final adapter check preserves the actual rectangular chassis, including the initial turn, without widening it to its circumscribed circle for straight travel. No scene geometry enters here. """ import math import numpy as np if __package__: from .contact_support import ContactSupport from .support_surface import SupportSurface else: from contact_support import ContactSupport from support_surface import SupportSurface FRAME_DEADLINE_SECONDS = 0.8 class Footprint: def __init__(self, geometry, deceleration=0.4, *, clearance_m=0.05): self.half_length = geometry["length_m"] / 2 self.half_width = geometry["width_m"] / 2 # Mounted bodies affect collision clearance; tracks still define support. self.collision_half_length = geometry.get("collision_length_m", geometry["length_m"]) / 2 self.collision_half_width = geometry.get("collision_width_m", geometry["width_m"]) / 2 if (not all(math.isfinite(v) for v in (self.collision_half_length, self.collision_half_width)) or self.collision_half_length < self.half_length or self.collision_half_width < self.half_width): raise ValueError("Collision projection cannot shrink the chassis") self.max_step = geometry["max_step_m"] self.max_slope = math.tan(math.radians(geometry["max_slope_degrees"])) self.deceleration = deceleration self.clearance_m = float(clearance_m) if not math.isfinite(self.clearance_m) or self.clearance_m < 0.05: raise ValueError("Invalid obstacle clearance") if min(self.half_length, self.half_width, self.max_step, deceleration) <= 0: raise ValueError("Invalid footprint geometry") self.contacts = ( ContactSupport(geometry["ground_contact"], geometry["length_m"], geometry["width_m"]) if "ground_contact" in geometry else None ) def classify_contacts(self, surface, offsets): if self.contacts is None: return surface.classify(offsets) width = min(high[1]-low[1] for low, high in self.contacts.bands) return surface.classify_contacts(offsets, width) def _obstacles(self, terrain, pose): terrain = np.asarray(terrain, dtype=float) obstacles = terrain[terrain[:, 3] > self.max_step + 1e-4, :2] - np.asarray(pose[:2]) x, y, z, w = pose[3:] yaw = math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)) return obstacles @ np.array( [[math.cos(yaw), -math.sin(yaw)], [math.sin(yaw), math.cos(yaw)]] ) def _clearances(self, obstacles): return np.maximum( np.abs(obstacles[:, 0]) - self.collision_half_length, np.abs(obstacles[:, 1]) - self.collision_half_width ) def _clear(self, obstacles, position, angle): delta = obstacles - position c, s = math.cos(angle), math.sin(angle) along = delta[:, 0] * c + delta[:, 1] * s across = -delta[:, 0] * s + delta[:, 1] * c initial = self._clearances(obstacles) if np.any(initial <= 0): return False # Never excuse an overlap of the actual robot body. clearance = np.maximum(np.abs(along) - self.collision_half_length, np.abs(across) - self.collision_half_width) # An observed point may already be inside the 5 cm reserve behind the body. # Permit only motion that never decreases that initial clearance. This # cannot authorize moving toward it, reversing into it or corner penetration. return bool(np.all(clearance + 1e-6 >= np.minimum(initial, self.clearance_m))) def assess_pose(self, terrain, pose, contact_height_m, *, support_terrain=None): """Certify a stationary body using observed support, never empty space. The 10 cm lattice includes every contact edge and corner for v2, or every body edge and corner for legacy v1. Each point must lie inside a local observed ground patch (15 cm radius), with a bounded plane slope/residual. Nearest returns alone cannot extrapolate support past a ledge. This is sampled geometric support, not load or soil-bearing-capacity estimation, and does not authorize a path to it. """ terrain = np.asarray(terrain, dtype=float).reshape(-1, 4) pose = np.asarray(pose, dtype=float) if not np.isfinite(terrain).all() or pose.shape != (7,) or not np.isfinite(pose).all(): raise ValueError("Invalid body assessment observation") qx, qy, qz, qw = pose[3:] yaw = math.atan2(2 * (qw * qz + qx * qy), 1 - 2 * (qy * qy + qz * qz)) axes = np.array([[math.cos(yaw), -math.sin(yaw)], [math.sin(yaw), math.cos(yaw)]]) spacing, radius = 0.1, 0.15 grid = ( self.contacts.stationary_samples(spacing) if self.contacts is not None else np.array( [ [x, y] for x in np.linspace( -self.half_length, self.half_length, math.ceil(2 * self.half_length / spacing) + 1, ) for y in np.linspace( -self.half_width, self.half_width, math.ceil(2 * self.half_width / spacing) + 1, ) ] ) ) @ axes.T support = ( terrain if support_terrain is None else np.asarray(support_terrain, dtype=float).reshape(-1, 4) ) if not np.isfinite(support).all(): raise ValueError("Invalid support observation") surface = SupportSurface( support, pose, contact_height_m, self.max_step, self.max_slope, anchor_radius_m=math.hypot(self.half_length, self.half_width) ) states, reasons = self.classify_contacts(surface, grid) supported = int(np.count_nonzero(states == "observed-supported")) collision_free = self._clear(self._obstacles(terrain, pose), np.zeros(2), 0) return dict( schema_version="missioncore.body-clearance/v2" if self.contacts is not None else "missioncore.body-clearance/v1", collision_free=collision_free, support_known=supported == len(grid), admitted=collision_free and supported == len(grid), support_samples=len(grid), supported_samples=supported, support_spacing_m=spacing, support_radius_m=radius, support_reasons=reasons, **({"ground_contact": self.contacts.value} if self.contacts is not None else {}), ) def find_arrival_pose( self, terrain, pose, target_xy, contact_height_m, *, support_terrain=None, minimum_translation_m=0.0, refinement=None, ): """Find an observed pose inside the existing 0.4 m task region. Keep the measured heading; do not assume room for a turn. The bounded search proposes a destination only. CMU must plan it on a new sensor transaction, and the command sweep retains its independent veto. """ if not math.isfinite(minimum_translation_m) or minimum_translation_m < 0: raise ValueError("Invalid arrival translation minimum") terrain = np.asarray(terrain, dtype=float).reshape(-1, 4) pose = np.asarray(pose, dtype=float) qx, qy, qz, qw = pose[3:] up = np.array( [2 * (qx * qz + qw * qy), 2 * (qy * qz - qw * qx), 1 - 2 * (qx * qx + qy * qy)] ) if up[2] <= 0: return None yaw = math.atan2(2 * (qw * qz + qx * qy), 1 - 2 * (qy * qy + qz * qz)) # Sample centre, then forward and lateral options. The 1 cm inset # belongs to the proposal; the mission's admission radius stays 0.4 m. offsets = [(0, 0)] + [ (radius * math.cos(yaw + angle), radius * math.sin(yaw + angle)) for radius in (0.1, 0.2, 0.3, 0.39) for angle in (0, math.pi / 4, -math.pi / 4, math.pi / 2, -math.pi / 2, math.pi) ] if refinement is not None: # The radial coarse search can miss a narrow but fully supported # placement. Refine at the existing 2.5 cm sweep resolution without # monopolizing a planning transaction. Never retain body receipts. axes = np.array([[math.cos(yaw), -math.sin(yaw)], [math.sin(yaw), math.cos(yaw)]]) offsets = [axes @ offset for offset in refinement.batch( pose, target_xy, minimum_translation_m)] for offset in offsets: candidate = pose.copy() candidate[:2] = np.asarray(target_xy) + offset if np.linalg.norm(candidate[:2] - pose[:2]) <= minimum_translation_m: continue candidate[2] -= np.dot(up[:2], candidate[:2] - pose[:2]) / up[2] # Cheap identical collision veto before fitting contact support. if not self._clear(self._obstacles(terrain, candidate), np.zeros(2), 0): continue if self.assess_pose( terrain, candidate, contact_height_m, support_terrain=support_terrain )["admitted"]: return candidate.tolist() return None def find_observed_approach( self, terrain, pose, target_xy, contact_height_m, *, support_terrain, minimum_translation_m ): """Propose a full supported body placement before an unseen destination. Only measured, positively classified support may supply this bounded receding horizon. This is not an arrival, a path, or motion permission; the local planner and swept command gates remain mandatory. """ pose = np.asarray(pose, dtype=float) delta = np.asarray(target_xy, dtype=float) - pose[:2] distance = np.linalg.norm(delta) if distance <= 0.4 or support_terrain is None or len(support_terrain) == 0: return None if not math.isfinite(minimum_translation_m) or minimum_translation_m <= 0: raise ValueError("Invalid approach translation minimum") qx, qy, qz, qw = pose[3:] up = np.array( [2 * (qx * qz + qw * qy), 2 * (qy * qz - qw * qx), 1 - 2 * (qx * qx + qy * qy)] ) if up[2] <= 0: return None limit = min(distance - 0.41, 2 * max(self.half_length, self.half_width)) # Stop before the unchanged task region. A candidate is never accepted # merely because the current body is supported; assess its whole body. for travel in np.arange(limit, minimum_translation_m, -0.1): candidate = pose.copy() offset = delta * travel / distance candidate[:2] += offset candidate[2] -= np.dot(up[:2], offset) / up[2] if self.assess_pose( terrain, candidate, contact_height_m, support_terrain=support_terrain )["admitted"]: return candidate.tolist() return None def command_bounds(self, speed, yaw_rate): """Bound a held command, allowing incomplete translation and turning. The body need not follow an ideal differential-drive arc: each response can range from zero to the requested rate. Bound its centre by integrating component extrema over that heading sector, then add the rotating body's rectangular projections. Straight travel retains rectangular dimensions. The additional directional discrepancy is an empirical simulation margin, calibrated on the DCD-006 flat-ground matrix (100/130 kg, 0.1–0.3 m/s, friction 0.35/0.8). It is not a physical guarantee, a ground-support proof, or qualification of every speed/load accepted by the settings editor. """ if not math.isfinite(speed) or not math.isfinite(yaw_rate): raise ValueError("Non-finite motion command") horizon = ( FRAME_DEADLINE_SECONDS + 0.5 + abs(speed) / self.deceleration + abs(yaw_rate) / 1.6 ) angle = abs(yaw_rate) * horizon def extent(along, across): if angle >= math.atan2(across, along): return math.hypot(along, across) return along * math.cos(angle) + across * math.sin(angle) cosine_min = math.cos(min(angle, math.pi)) sine_max = math.sin(min(angle, math.pi / 2)) sine_min = 0 if angle <= math.pi else math.sin(min(angle, 1.5 * math.pi)) if yaw_rate < 0: sine_min, sine_max = -sine_max, -sine_min travel = speed * horizon x_range = sorted((travel * min(0, cosine_min), travel)) y_range = sorted((travel * min(0, sine_min), travel * max(0, sine_max))) half = np.array( [extent(self.collision_half_length, self.collision_half_width), extent(self.collision_half_width, self.collision_half_length)] ) lower = np.array([x_range[0], y_range[0]]) - half upper = np.array([x_range[1], y_range[1]]) + half discrepancy = horizon * (np.array([0.01, 0.03]) + 0.15 * abs(yaw_rate)) return dict( horizon_seconds=horizon, centre_lower_xy_m=[x_range[0], y_range[0]], centre_upper_xy_m=[x_range[1], y_range[1]], lower_xy_m=lower.tolist(), upper_xy_m=upper.tolist(), discrepancy_xy_m=discrepancy.tolist(), ) def command_footprint_clear(self, speed, yaw_rate, terrain, pose): """Veto observed obstacles in the command's bounded swept body. Empty observations do not certify terrain support. The independent planner, unknown-space policy and stationary arrival checks retain that responsibility. A zero return from regulation always means stop; it is never a certificate that an already unsafe pose has become safe. """ bounds = self.command_bounds(speed, yaw_rate) terrain = np.asarray(terrain, dtype=float).reshape(-1, 4) pose = np.asarray(pose, dtype=float) if pose.shape != (7,) or not np.isfinite(pose).all() or not np.isfinite(terrain).all(): raise ValueError("Invalid swept-body observation") obstacles = self._obstacles(terrain, pose) initial = self._clearances(obstacles) if np.any(initial <= 0): return False lower, upper = np.array(bounds["lower_xy_m"]), np.array(bounds["upper_xy_m"]) error = np.array(bounds["discrepancy_xy_m"]) clearance = np.maximum(lower - obstacles, obstacles - upper).max(axis=1) hard_clearance = np.maximum(lower - error - obstacles, obstacles - upper - error).max( axis=1 ) # Keep the pre-existing reserve exception, but never excuse penetration # of the body discrepancy envelope, even when departing an obstacle. suspects = (clearance + 1e-6 < np.minimum(initial, self.clearance_m)) | (hard_clearance <= 0) if not np.any(suspects): return True return self._rotating_envelope_clear( obstacles[suspects], initial[suspects], bounds, yaw_rate) def _rotating_envelope_clear(self, obstacles, initial, bounds, yaw_rate): """Refine the broad AABB without shrinking any motion uncertainty. AABB corners combine body extrema attained at different headings and can falsely forbid a pivot AWAY from an obstacle beside the front. Retain the entire uncertain translation rectangle at every orientation. Test its Minkowski sum with the oriented body on all four separating axes. Each angular interval is enclosed by a corner-displacement disk; this is an outer bound between samples, not a collision sampling gap. The same reserve, latency, braking and discrepancy remain mandatory. """ angle = max(-2 * math.pi, min(2 * math.pi, yaw_rate * bounds["horizon_seconds"])) if abs(angle) < 1e-12: return False # Straight AABB is already exact. low, high = np.array(bounds["centre_lower_xy_m"]), np.array(bounds["centre_upper_xy_m"]) centre, half = (low + high) / 2, (high - low) / 2 error = np.array(bounds["discrepancy_xy_m"]) count = max(1, math.ceil(abs(angle) / 0.025)) step = angle / count radius = math.hypot(self.collision_half_length, self.collision_half_width) delta = obstacles - centre reserve = np.minimum(initial, self.clearance_m) intervals = [(index * step, (index + 1) * step, 0) for index in range(count)] while intervals: start, end, depth = intervals.pop() theta = (start + end) / 2 angular_error = 2 * radius * math.sin(abs(end - start) / 4) c, s = math.cos(theta), math.sin(theta) abs_c, abs_s = abs(c), abs(s) # Axes of the axis-aligned centre box and of the rotated chassis # are all edge normals of their Minkowski sum (a zonotope). projections = np.column_stack((np.abs(delta), np.abs(delta[:,0]*c + delta[:,1]*s), np.abs(-delta[:,0]*s + delta[:,1]*c))) extent = np.array([ half[0] + self.collision_half_length*abs_c + self.collision_half_width*abs_s, half[1] + self.collision_half_length*abs_s + self.collision_half_width*abs_c, self.collision_half_length + half[0]*abs_c + half[1]*abs_s, self.collision_half_width + half[0]*abs_s + half[1]*abs_c, ]) separation = projections - extent uncertainty = np.array([error[0], error[1], error[0]*abs_c + error[1]*abs_s, error[0]*abs_s + error[1]*abs_c]) # A midpoint collision is an actual counterexample. Otherwise an # inconclusive outer bound needs refinement, not a permanent veto: # a coarse angular disk can consume a genuinely clear few mm at a # corner and strand the same nominal path on every observation. if np.any(separation.max(axis=1) + 1e-6 < reserve): return False if np.any((separation - uncertainty).max(axis=1) <= 0): return False bounded = separation - angular_error if (np.any(bounded.max(axis=1) + 1e-6 < reserve) or np.any((bounded - uncertainty).max(axis=1) <= 0)): if depth >= 10: return False # Unresolved intervals never grant motion. intervals.extend(((start, theta, depth + 1), (theta, end, depth + 1))) return True def assess_command_support( self, speed, yaw_rate, terrain, pose, contact_height_m, *, surface=None ): """Check newly entered area, without demanding sight through the body. Legacy inputs use the full-body lattice; v2 uses selected contact bands. Each fixed lattice rounds outward from its envelope. Its samples are nested when command scale decreases; reducing speed cannot skip a failed sample by shifting a grid. The currently occupied body is excluded from this future-ground test, not painted as observed terrain. Known obstacles retain their independent full-body veto. A stop is always available and does not certify that the existing pose is safe. """ bounds = self.command_bounds(speed, yaw_rate) lower = np.array(bounds["lower_xy_m"]) - bounds["discrepancy_xy_m"] upper = np.array(bounds["upper_xy_m"]) + bounds["discrepancy_xy_m"] if self.contacts is not None: spacing = self.contacts.spacing_m local, sides = self.contacts.cells(bounds, yaw_rate) else: spacing = 0.1 low, high = np.floor(lower / spacing).astype(int), np.ceil(upper / spacing).astype(int) if np.prod(high - low + 1) > 20000: raise ValueError("Support envelope exceeds bounded sample budget") local = ( np.array( [[x, y] for x in range(low[0], high[0] + 1) for y in range(low[1], high[1] + 1)] ) * spacing ) pose = np.asarray(pose, dtype=float) if pose.shape != (7,) or not np.isfinite(pose).all(): raise ValueError("Invalid support pose") 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)]]) offsets = local @ axes.T current = (np.abs(local[:, 0]) <= self.half_length) & ( np.abs(local[:, 1]) <= self.half_width ) moving = abs(speed) + abs(yaw_rate) > 1e-8 required = ~current if moving else np.zeros(len(local), bool) if surface is None: surface = SupportSurface(terrain, pose, contact_height_m, self.max_step, self.max_slope, anchor_radius_m=math.hypot(self.half_length, self.half_width)) states, reasons = self.classify_contacts(surface, offsets[required]) supported = int(np.count_nonzero(states == "observed-supported")) unknown = int(np.count_nonzero(states == "unknown")) unsafe = int(np.count_nonzero(states == "observed-unsafe")) missing = offsets[required][states != "observed-supported"] + pose[:2] return dict( schema_version="missioncore.swept-support/v2" if self.contacts is not None else "missioncore.swept-support/v1", admitted=supported == len(states), status="hold" if not moving else "current-footprint-only" if not len(states) else "observed-unsafe" if unsafe else "unknown" if unknown else "observed-supported", support_samples=len(states), supported_samples=supported, unknown_samples=unknown, unsafe_samples=unsafe, current_body_excluded_samples=int(current.sum()), scope="newly-entered-area; current body occupancy is not a ground observation", support_spacing_m=spacing, support_radius_m=SupportSurface.radius_m, support_reasons=reasons, bounds=bounds, roughness_obstacles_xyz=list(surface.raised_obstacles.values()), support_obstacle_samples=surface.hazard_samples( offsets[required][states == "observed-unsafe"]), unsupported_xy=missing[:12].tolist(), **( { "ground_contact": self.contacts.value, "per_side": { name: { "support_samples": int(sides[required, side].sum()), "unknown_samples": int( np.count_nonzero((states == "unknown") & sides[required, side]) ), "unsafe_samples": int( np.count_nonzero( (states == "observed-unsafe") & sides[required, side] ) ), } for side, name in enumerate(("left", "right")) }, } if self.contacts is not None else {} ), ) def regulate_supported_command(self, speed, yaw_rate, terrain, pose, contact_height_m): """The same requested arc must pass obstacle and new-ground checks.""" surface = SupportSurface(terrain, pose, contact_height_m, self.max_step, self.max_slope, anchor_radius_m=math.hypot(self.half_length, self.half_width)) def assess(scale): v, w = speed * scale, yaw_rate * scale ground = self.assess_command_support( v, w, terrain, pose, contact_height_m, surface=surface ) return self.command_footprint_clear(v, w, terrain, pose) and ground["admitted"], ground clear, support = assess(1.0) if clear: return speed, yaw_rate, 1.0, support low, high = self.minimum_command_scale(speed, yaw_rate), 1.0 clear, support = assess(low) if not clear: return 0.0, 0.0, 0.0, support for _ in range(7): middle = (low + high) / 2 clear, candidate = assess(middle) if clear: low, support = middle, candidate else: high = middle return speed * low, yaw_rate * low, low, support def regulate_command(self, speed, yaw_rate, terrain, pose): """Reduce speed along CMU's same arc when its full-speed stop is unsafe. Scaling both components preserves requested curvature. The sector bounds and discrepancy shrink monotonically, so find the largest admitted scale. Never choose another turn/direction, ignore a hazard or creep arbitrarily. """ if self.command_footprint_clear(speed, yaw_rate, terrain, pose): return speed, yaw_rate, 1.0 low, high = self.minimum_command_scale(speed, yaw_rate), 1.0 if not self.command_footprint_clear(speed * low, yaw_rate * low, terrain, pose): return 0.0, 0.0, 0.0 for _ in range(7): middle = (low + high) / 2 if self.command_footprint_clear(speed * middle, yaw_rate * middle, terrain, pose): low = middle else: high = middle return speed * low, yaw_rate * low, low @staticmethod def minimum_command_scale(speed, yaw_rate): """Bound arbitrarily slow creep in physical units, not a setpoint ratio. The existing 0.1 commands admitted regulation down to 0.02 m/s or rad/s. Keep that simulation floor for larger setpoints too: raising the operator's maximum must not remove an already feasible slow arc. Smaller original proposals (e.g. acceleration ramps) stay unchanged. This is an operational floor, not a motor/traction qualification. """ magnitude = abs(speed) if abs(speed) > 1e-8 else abs(yaw_rate) return min(1.0, 0.02 / max(magnitude, 1e-12)) def swept_footprint_clear(self, path, terrain, pose): path = np.asarray(path, dtype=float)[:, :2] terrain = np.asarray(terrain, dtype=float) if len(path) < 2 or terrain.ndim != 2 or terrain.shape[1] != 4: return False obstacles = self._obstacles(terrain, pose) previous_angle = 0.0 for start, end in zip(path[:-1], path[1:], strict=True): delta = end - start length = np.linalg.norm(delta) if length < 1e-6: continue angle = math.atan2(delta[1], delta[0]) turn = math.atan2(math.sin(angle - previous_angle), math.cos(angle - previous_angle)) for fraction in np.linspace(0, 1, max(2, math.ceil(abs(turn) / 0.035) + 1)): if not self._clear(obstacles, start, previous_angle + fraction * turn): return False for fraction in np.linspace(0, 1, max(2, math.ceil(length / 0.025) + 1)): if not self._clear(obstacles, start + fraction * delta, angle): return False previous_angle = angle return True