243 lines
13 KiB
Python
243 lines
13 KiB
Python
"""Fast control admission, independent of camera inference and map construction.
|
|
|
|
The native CMU follower supplies proposals from live odometry. Every delivered
|
|
proposal is checked against the current observed geometry and contact policy.
|
|
Wall-clock observation leases are never renewed by a controller poll.
|
|
"""
|
|
|
|
import math
|
|
import copy
|
|
import threading
|
|
import time
|
|
from collections import OrderedDict
|
|
|
|
import numpy as np
|
|
|
|
if __package__:
|
|
from .arrival_approach import separate_counter_rotation
|
|
from .detection_obstacles import DetectionObstacles
|
|
else:
|
|
from arrival_approach import separate_counter_rotation
|
|
from detection_obstacles import DetectionObstacles
|
|
|
|
|
|
class ContinuousControl:
|
|
range_deadline = 0.8
|
|
pose_deadline = 0.5
|
|
semantic_deadline = 2.0
|
|
|
|
def __init__(self, monitor, support_policy, publish_pose, publish_path, native_command,
|
|
clock=time.monotonic, body_top_m=math.inf, native_only=False):
|
|
self.monitor, self.support = monitor, support_policy
|
|
self.detections = DetectionObstacles(monitor)
|
|
self.ground_monitor = monitor.ground_envelope()
|
|
self.publish_pose, self.publish_path, self.native_command = (
|
|
publish_pose, publish_path, native_command)
|
|
self.clock, self.lock = clock, threading.Lock()
|
|
self.geometry = None
|
|
self.plans = OrderedDict()
|
|
self.path_id = None
|
|
self.body_top_m = body_top_m
|
|
self.range_sequence = None
|
|
self.native_only = native_only
|
|
|
|
def observe(self, value):
|
|
age = float(value["geometry_age_seconds"])
|
|
if not math.isfinite(age) or age < 0:
|
|
raise ValueError("Invalid range capture age")
|
|
points = np.asarray(value["points"], dtype=float).reshape(-1, 3).copy()
|
|
if not np.isfinite(points).all():
|
|
raise ValueError("Non-finite live range")
|
|
sequence = value.get("range_sequence")
|
|
if sequence is not None:
|
|
if (not isinstance(sequence, list) or len(sequence) != 2
|
|
or any(type(n) is not int or n < 0 for n in sequence)):
|
|
raise ValueError("Invalid range sequence")
|
|
sequence = tuple(sequence)
|
|
with self.lock:
|
|
# Once the direct sensor channel is active, planner transactions
|
|
# cannot replace its newer packet or renew its capture lease.
|
|
if self.range_sequence is not None and (sequence is None or sequence <= self.range_sequence):
|
|
return
|
|
self.geometry = (self.clock() - age, points)
|
|
self.range_sequence = sequence
|
|
|
|
def accept(self, value, result, terrain, *, detections=None, collision_terrain=None):
|
|
candidates = self.detections.observed(value)
|
|
if detections is None:
|
|
detections = candidates
|
|
else:
|
|
detections = np.asarray(detections, dtype=float).reshape(-1, 3).copy()
|
|
if not set(map(tuple, detections)) <= set(map(tuple, candidates)):
|
|
raise ValueError("Refined detection is not an original associated range return")
|
|
terrain = np.asarray(terrain, dtype=float).reshape(-1, 4).copy()
|
|
collision = (terrain.copy() if collision_terrain is None else
|
|
np.asarray(collision_terrain, dtype=float).reshape(-1, 4).copy())
|
|
if (collision.shape != terrain.shape or not np.isfinite([terrain, collision]).all()
|
|
or not np.array_equal(collision[:, :3], terrain[:, :3])
|
|
or np.any(collision[:, 3] > terrain[:, 3])):
|
|
raise ValueError("Collision and surface layers must share the measured terrain")
|
|
# Only costs added by the semantic overlay belong to ground exclusion.
|
|
# Physical terrain and detected solids retain the complete body envelope.
|
|
floor = terrain[terrain[:, 3] > collision[:, 3]].copy()
|
|
record = dict(value=value, result=result, detections=detections,
|
|
terrain=terrain, collision_terrain=collision, forbidden_ground=floor,
|
|
received_at=self.clock())
|
|
with self.lock:
|
|
self.plans[value["observation_id"]] = record
|
|
while len(self.plans) > 4:
|
|
self.plans.popitem(last=False)
|
|
|
|
def snapshot(self):
|
|
"""One immutable planning transaction for offline diagnosis, no authority."""
|
|
with self.lock:
|
|
if not self.plans:
|
|
return None
|
|
identity, plan = next(reversed(self.plans.items()))
|
|
return dict(observation_id=identity, request=copy.deepcopy(plan["value"]),
|
|
result=copy.deepcopy(plan["result"]), terrain=plan["terrain"].tolist(),
|
|
collision_terrain=plan["collision_terrain"].tolist(),
|
|
forbidden_ground=plan["forbidden_ground"].tolist())
|
|
|
|
def tick(self, value):
|
|
started = self.clock()
|
|
pose = np.asarray(value["pose"], dtype=float)
|
|
age = float(value["pose_age_seconds"])
|
|
perception_age = float(value["perception_age_seconds"])
|
|
if (pose.shape != (7,) or not np.isfinite(pose).all()
|
|
or abs(np.linalg.norm(pose[3:]) - 1) > 0.01
|
|
or not all(math.isfinite(x) and x >= 0 for x in (age, perception_age))
|
|
or type(value["enabled"]) is not bool):
|
|
raise ValueError("Invalid continuous state")
|
|
if "range_observation" in value:
|
|
self.observe(value["range_observation"])
|
|
# Always feed current state, including while stopped, without waiting
|
|
# for terrain_analysis or a model. This publisher is follower-only.
|
|
self.publish_pose(pose)
|
|
with self.lock:
|
|
geometry = self.geometry
|
|
plan = self.plans.get(value.get("observation_id"))
|
|
|
|
def output(v=0.0, w=0.0, reason="waiting", **evidence):
|
|
return dict(speed_mps=float(v), yaw_rate_rps=float(w), reason=reason,
|
|
processing_ms=(self.clock() - started) * 1000, **evidence)
|
|
|
|
if not value["enabled"]:
|
|
return output(reason="paused")
|
|
if age > self.pose_deadline:
|
|
return output(reason="stale-pose")
|
|
if perception_age > self.semantic_deadline:
|
|
return output(reason="stale-perception")
|
|
if geometry is None or started - geometry[0] > self.range_deadline:
|
|
return output(reason="stale-range")
|
|
if len(geometry[1]) < 50:
|
|
return output(reason="insufficient-range")
|
|
if plan is None or plan["result"].get("status") != "path":
|
|
return output(reason="waiting-for-plan")
|
|
if started - plan["received_at"] > self.range_deadline:
|
|
return output(reason="stale-plan")
|
|
request, result = plan["value"], plan["result"]
|
|
if (started - plan["received_at"] + request.get("detection_age_seconds", 0)
|
|
> self.detections.deadline_seconds):
|
|
return output(reason="stale-detection")
|
|
if self.path_id != value["observation_id"]:
|
|
self.publish_path(result["path"], request["pose"])
|
|
self.path_id = value["observation_id"]
|
|
native = self.native_command()
|
|
if native is None or started - native[0] > 0.25:
|
|
return output(reason="waiting-for-controller")
|
|
limit = float(request["max_speed_mps"])
|
|
reverse = request.get("allow_reverse", False)
|
|
stationary = abs(float(value.get("speed_mps", 0))) < 0.02
|
|
qx, qy, qz, qw = pose[3:]
|
|
if 1 - 2 * (qx*qx + qy*qy) <= math.cos(math.radians(30)):
|
|
return output(reason="inclination")
|
|
# Newly arrived raw returns can veto a map that has not finished its
|
|
# next terrain pass yet. Ground support uses independent first-hit data.
|
|
points = geometry[1]
|
|
up = np.array([2*(qx*qz + qw*qy), 2*(qy*qz - qw*qx), 1-2*(qx*qx+qy*qy)])
|
|
height = (points - pose[:3]) @ up + request["body_contact_height_m"]
|
|
raised = (height > self.monitor.max_step + 1e-4) & (height <= self.body_top_m)
|
|
hazards = np.column_stack((points[raised], np.ones(int(raised.sum()))))
|
|
terrain = np.concatenate((plan["terrain"], hazards))
|
|
collision = np.concatenate((plan["collision_terrain"], hazards))
|
|
def admit(command):
|
|
speed, angular = map(float, command)
|
|
if not all(math.isfinite(x) for x in (speed, angular)):
|
|
return output(reason="invalid-proposal")
|
|
speed = max(-limit, min(limit, speed))
|
|
angular = max(-0.8, min(0.8, angular))
|
|
if not self.native_only and not reverse and self.monitor.contacts is not None:
|
|
speed, angular, _ = separate_counter_rotation(speed, angular,
|
|
[(low[1]+high[1])/2 for low, high in self.monitor.contacts.bands],
|
|
stationary=stationary)
|
|
if abs(speed) < 1e-8 and abs(angular) > 1e-8:
|
|
angular = max(-self.support.partial_yaw_rps,
|
|
min(self.support.partial_yaw_rps, angular)) if stationary else 0.0
|
|
if (reverse and (speed > 0 or abs(angular) > 0.15)) or (not reverse and speed < 0):
|
|
return output(reason="direction")
|
|
speed, angular, obstacle_scale = self.monitor.regulate_command(speed, angular, collision, pose)
|
|
if obstacle_scale == 0:
|
|
return output(reason="obstacle")
|
|
speed, angular, ground_scale = self.ground_monitor.regulate_command(
|
|
speed, angular, plan["forbidden_ground"], pose)
|
|
if ground_scale == 0:
|
|
return output(reason="forbidden-ground-sweep")
|
|
speed, angular, support_scale, support = self.support.regulate(
|
|
speed, angular, terrain, pose, request["body_contact_height_m"],
|
|
current_points=points, collision_terrain=collision,
|
|
observed_retreat=bool(reverse and request.get("continuous")),
|
|
)
|
|
evidence = dict(support_policy=support["policy"]["reason"],
|
|
support_reasons=support["support_reasons"],
|
|
fresh_context=support["policy"]["fresh_context"])
|
|
if support_scale == 0:
|
|
return output(reason=support["policy"]["reason"], **evidence)
|
|
speed, angular, detection_scale = self.detections.regulate(
|
|
speed, angular, plan["detections"], pose)
|
|
evidence["detection_command_scale"] = detection_scale
|
|
if detection_scale == 0:
|
|
return output(reason="detected-object-sweep", **evidence)
|
|
return output(speed, angular, "none", **evidence)
|
|
|
|
if self.native_only:
|
|
# Nav2 owns the proposal. No CMU fallback, arrival override or
|
|
# alternative local pursuit may become a competing controller.
|
|
response = admit(native[1:])
|
|
response.update(command_source="nav2", observation_id=value["observation_id"],
|
|
native_command=list(native[1:]),
|
|
processing_ms=(self.clock()-started)*1000)
|
|
return response
|
|
|
|
planned = [result["speed_mps"], result["yaw_rate_rps"]]
|
|
approach = result.get("diagnostic", {}).get("arrival_approach", {})
|
|
phase = approach.get("phase")
|
|
terminal = result.get("diagnostic", {}).get("terminal_approach")
|
|
local_turn = result.get("diagnostic", {}).get("local_turn") or {}
|
|
if phase == "path-alignment" and not stationary:
|
|
return output(reason="path-alignment-braking")
|
|
# A short, destination-admitted terminal prefix may lie inside the
|
|
# native follower's stop tolerance. Its valid zero command must not
|
|
# suppress the terminal proposal. It retains the plan's bounded lease
|
|
# and traverses exactly the same current-pose/range guards below.
|
|
proposal = planned if (terminal or local_turn.get("phase") == "forward-path"
|
|
or phase in {"braking", "aligning", "path-alignment"}) else native[1:]
|
|
response = admit(proposal)
|
|
source = ("local-path" if local_turn.get("phase") == "forward-path" else "arrival") \
|
|
if proposal is planned else "follower"
|
|
if response["reason"] != "none" and tuple(proposal) != tuple(planned):
|
|
# A fresh path proposal and the live follower can disagree on
|
|
# curvature. Test the planner's original command at the CURRENT
|
|
# pose and ranges before declaring deadlock. This is no admission
|
|
# shortcut: both candidates traverse exactly the same guards.
|
|
fallback = admit(planned)
|
|
if fallback["reason"] == "none":
|
|
fallback["rejected_follower"] = response
|
|
response, source = fallback, "guarded-plan"
|
|
response.update(range_age_ms=(started-geometry[0])*1000,
|
|
pose_age_ms=age*1000, perception_age_ms=perception_age*1000,
|
|
native_command=list(native[1:]), command_source=source,
|
|
observation_id=value["observation_id"],
|
|
processing_ms=(self.clock()-started)*1000)
|
|
return response
|