Files
NODEDC_MISSION_CORE/simulation/ai-polygon/navigation/arrival_approach.py
T

271 lines
11 KiB
Python

"""One observed stop-and-orient phase per task goal or declared route segment.
A direction grants no translation, ground or arrival authority. Every pivot
must pass the existing swept-obstacle and support guards on the same sensor
transaction. Completed orientation never overrides a local obstacle detour.
"""
import math
import re
def separate_counter_rotation(speed, yaw_rate, track_centres_y, *, stationary):
"""Autonomy stops before a turn that would reverse one moving track.
A normal forward arc remains continuous. A pivot is only a proposal: the
caller must apply the complete sweep and live observation checks anew.
"""
side_speeds = [speed - yaw_rate * y for y in track_centres_y]
if speed > 0 and min(side_speeds) < 0 < max(side_speeds):
return (
0.0,
yaw_rate if stationary else 0.0,
{
"phase": "pivoting" if stationary else "braking",
"requested_command": [speed, yaw_rate],
"authority": "proposal-requires-swept-obstacle-and-support-admission",
},
)
return speed, yaw_rate, None
def path_alignment_command(path, *, lookahead_m, maximum_yaw_rps):
"""Propose a stationary turn toward the SAME selected local path.
A translation sweep may be blocked beside a front corner while a stationary
pivot is clear. This grants no motion: callers require a stopped body and
independently admit the full pivot with current obstacle and support data.
Do not rotate for a straight blocked path, invent a detour, or reverse.
"""
if len(path) < 2:
return None
point = next((p for p in path if math.hypot(*p[:2]) >= lookahead_m), path[-1])
if not all(math.isfinite(x) for x in point[:2]) or point[0] <= 0:
return None
heading = math.atan2(point[1], point[0])
if abs(heading) <= 0.02:
return None
return 0.0, max(-maximum_yaw_rps, min(maximum_yaw_rps, 2 * heading))
def admit_path_alignment(path, monitor, policy, terrain, pose, contact_height_m,
current_points, *, stationary, reverse, orienting, lookahead_m):
"""A blocked translation can turn first, with its own complete admission.
Ground rejection and body collision both require a different swept region;
neither may authorize the original arc. Reuse the selected path heading,
require a stopped body, and recheck obstacle and support independently.
"""
if not stationary or reverse or orienting:
return None
pivot = path_alignment_command(path, lookahead_m=lookahead_m,
maximum_yaw_rps=policy.partial_yaw_rps)
if pivot is None:
return None
v, w, body_scale = monitor.regulate_command(*pivot, terrain, pose)
if body_scale == 0:
return None
v, w, ground_scale, ground = policy.regulate(
v, w, terrain, pose, contact_height_m, current_points=current_points)
if ground_scale == 0 or ground["status"] != "observed-supported":
return None
return v, w, body_scale, ground_scale, ground, dict(
phase="path-alignment", proposed_command=list(pivot),
authority="stationary-selected-path; independently admitted pivot sweep and support")
def forward_path_command(path, track_centres_y, *, lookahead_m, maximum_speed,
maximum_yaw_rps):
"""Pure-pursuit proposal along the selected path with both tracks forward.
A local follower's rotate-first preference must not be the only proposal
for a driveable bend. Pursue a lookahead on that SAME prefix, limiting
curvature so the inner track keeps at least 10% of the outer track's speed.
This is a steering constraint, not proof the wider arc is clear; its actual
sweep still needs independent admission. Do not extend a short path,
aim directly at the mission goal or grant collision/support admission.
"""
if not track_centres_y or maximum_speed <= 0 or maximum_yaw_rps <= 0:
return None
if len(path) < 2:
return None
candidates = []
for point in path:
x, y = point[:2]
if not all(math.isfinite(n) for n in (x, y)):
return None
if math.hypot(x, y) >= lookahead_m:
candidates.append(point)
if not candidates:
candidates = [path[-1]] # Native paths may be cropped before lookahead.
for point in candidates:
x, y = point[:2]
distance = math.hypot(x, y)
if x <= 0 or distance < min(lookahead_m, max(map(abs, track_centres_y))):
continue
requested_curvature = 2*y/(distance*distance)
minimum_track_ratio = 0.1
radius = max(map(abs, track_centres_y))
if radius <= 0:
return None
limit = (1-minimum_track_ratio)/(1+minimum_track_ratio)/radius
curvature = max(-limit, min(limit, requested_curvature))
speed = min(maximum_speed, maximum_yaw_rps/max(abs(curvature), 1e-12))
yaw_rate = max(-maximum_yaw_rps, min(maximum_yaw_rps, speed*curvature))
return speed, yaw_rate, {
"phase": "forward-path", "lookahead_vehicle_xy": [x, y],
"curvature_per_m": curvature,
"requested_curvature_per_m": requested_curvature,
"minimum_track_ratio": minimum_track_ratio,
"authority": "selected-prefix-proposal; requires live sweep and support",
}
return None
def follower_stopped_short(pose, goal, command, *, arrival_complete, stop_distance):
"""Follower tolerance cannot stand in for measured mission arrival.
Even a fully supported current body can be outside the task region when
its selected destination lies near that region's edge.
"""
return bool(
not arrival_complete
and abs(command[0]) + abs(command[1]) < 1e-5
and math.dist(goal[:2], pose[:2]) <= stop_distance
)
def terminal_path_command(
pose, goal, path, command, *, stop_distance, maximum_speed, command_bounds
):
"""Finish a fresh local path whose follower tolerance precedes body arrival.
This proposes a short final approach only after the caller has admitted
the complete destination. It follows the existing CMU prefix; it never
extends that prefix, certifies support, or changes mission acceptance.
The caller must reassess the actual command through all live sweep gates.
"""
if (
len(path) < 2
or abs(command[0]) + abs(command[1]) > 1e-5
or math.dist(pose[:2], goal[:2]) > 2 * stop_distance
):
return None
x, y = path[-1][:2] # Same-transaction vehicle-yaw frame, not world XY.
distance = math.hypot(x, y)
if not 0 < distance <= 2 * stop_distance or x <= 0:
return None
heading = math.atan2(y, x)
if abs(heading) > 0.3:
return None
yaw = max(-0.15, min(0.15, 2 * heading))
limit = min(maximum_speed, 0.1)
# Use the owning monitor's horizon, not a second copy of its timing limits.
# The upper speed limit makes the bound conservative for the output.
horizon = command_bounds(limit, yaw)["horizon_seconds"]
speed = min(limit, distance / horizon)
return (
speed,
yaw,
{
"phase": "terminal-path",
"path_endpoint_vehicle_xy": [x, y],
"prefix_length_m": distance,
"held_translation_bound_m": speed * horizon,
"authority": "proposal-requires-destination-and-live-sweep-admission",
},
)
def validate_orientation(value):
if value is None:
return None
if (
not isinstance(value, dict)
or set(value) not in ({"key", "xy"}, {"key", "xy", "direction_xy"})
or not isinstance(value["key"], str)
or not re.fullmatch(r"[a-zA-Z0-9_-]{1,80}", value["key"])
or not isinstance(value["xy"], list)
or len(value["xy"]) != 2
or any(
isinstance(v, bool) or not isinstance(v, (float, int)) or not math.isfinite(v)
for v in value["xy"]
)
):
raise ValueError("Invalid orientation intent")
direction = value.get("direction_xy")
if "direction_xy" in value and (
not isinstance(direction, list) or len(direction) != 2
or any(isinstance(v, bool) or not isinstance(v, (float, int))
or not math.isfinite(v) for v in direction)
or not math.isclose(math.hypot(*direction), 1., abs_tol=1e-9)
):
raise ValueError("Invalid orientation direction")
return value
def orientation_identity(value):
"""A translated bearing endpoint is the same intent; a new bearing is not."""
direction = value.get("direction_xy")
return (value["key"], "direction", tuple(direction)) if direction is not None else (
value["key"], "point", tuple(value["xy"]))
class ArrivalApproach:
def __init__(self):
self.turning = self.completed = False
self.previous = self.target = None
def command(self, pose, target, seconds, speed, yaw_rate, *, enabled):
target = validate_orientation(target)
if not enabled or target is None:
self.previous = None
return speed, yaw_rate, {"phase": "local-path"}
if not all(math.isfinite(v) for v in (*pose, seconds, speed, yaw_rate)):
raise ValueError("Non-finite orientation observation")
if self.target != target["key"]:
self.target = target["key"]
self.turning = self.completed = False
self.previous = None
if self.completed:
return speed, yaw_rate, {"phase": "local-path", "target_key": self.target}
if math.dist(pose[:2], target["xy"]) <= 0.4:
self.completed = True
return speed, yaw_rate, {"phase": "body-placement", "target_key": self.target}
observed_speed = None
if self.previous is not None:
position, before = self.previous
dt = seconds - before
if dt < 0:
raise ValueError("Orientation observations must not rewind")
if 0 < dt <= 1:
observed_speed = math.dist(pose[:2], position) / dt
self.previous = (list(pose[:2]), seconds)
x, y, z, w = pose[3:7]
heading = math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))
bearing = math.atan2(target["xy"][1] - pose[1], target["xy"][0] - pose[0])
error = math.atan2(math.sin(bearing - heading), math.cos(bearing - heading))
self.turning = abs(error) > (0.1 if self.turning else 0.3)
phase = "local-path"
if self.turning:
speed = 0.0
if observed_speed is None or observed_speed > 0.025:
yaw_rate, phase = 0.0, "braking"
else:
yaw_rate = max(-math.radians(20), min(math.radians(20), 2 * error))
phase = "aligning"
else:
self.completed = True
return (
speed,
yaw_rate,
{
"phase": phase,
"target_key": self.target,
"heading_error_radians": error,
"observed_translation_mps": observed_speed,
"proposed_command": [speed, yaw_rate],
"authority": "proposal-requires-swept-obstacle-and-support-admission",
},
)