Restore observed recovery through native Nav2

This commit is contained in:
DCCONSTRUCTIONS
2026-10-08 11:11:12 +03:00
parent 117e937906
commit 140b6002e0
12 changed files with 1351 additions and 24 deletions
@@ -63,12 +63,13 @@ def main():
def controls():
try:
while running.is_set():
with condition:current=dict(state)
packet=dict(execution_inputs_sha256=inputs['sha256'],pose=original['pose'],
measured_twist=[0.,0.,0.],speed_mps=0.,pose_age_seconds=.01,
perception_age_seconds=0.,**current)
result=request('/control',packet)
responses.append(result)
with condition:
current=dict(state)
packet=dict(execution_inputs_sha256=inputs['sha256'],pose=current.pop('pose',original['pose']),
measured_twist=[0.,0.,0.],speed_mps=0.,pose_age_seconds=.01,
perception_age_seconds=0.,**current)
result=request('/control',packet)
responses.append(result)
time.sleep(.05)
except BaseException as error:errors.append(error)
@@ -183,6 +184,72 @@ def main():
restored=request('/plan',value)
assert restored['status']=='path' and restored['controller_goal'][0]=='path',restored
with condition:state['observation_id']=value['observation_id']
# A separate synthetic, stationary floor checks the actual BackUp ->
# rover-gate integration. It does not qualify motion on the city scene.
with condition:
state.update(enabled=False,pose=[0.,0.,.37,0.,0.,0.,1.])
assert request('/reset',{})['reset']
ready()
floor=[[i*.05,j*.05,0.] for i in range(-40,41) for j in range(-40,41)]
front=[p for p in floor if p[0]>.75]
retreat=copy.deepcopy(original)
retreat.update(pose=[0.,0.,.37,0.,0.,0.,1.],goal=[1.,0.,0.],
max_speed_mps=.1,allow_reverse=False,translation_allowed=True,
recovery_orientation=False,orientation_target=None,arrival_target=None,
detection_point_indices=[],unlocalized_rear_detection=False,
geometry_age_seconds=0.,detection_age_seconds=0.,semantic_points=[])
retreat['range_rays']=dict(origins=[[0.,0.,.37],[0.,0.,.37]],
ends=floor,origin_indices=[0]*len(floor))
retreat['semantic_observations']=[dict(frame_id='retreat-floor',age_seconds=0.,
samples=[[*p,1.] for p in floor])]
retreat['points']=floor
deadline=time.monotonic()+15
while True:
retreat['observation_id']='retreat-bootstrap'
result=request('/plan',retreat)
if result['status']=='path':break
assert time.monotonic()<deadline,result
time.sleep(.1)
# Warm the costmaps through normal planning before invoking a behavior;
# lifecycle activation alone does not publish their first observation.
assert result['controller_goal'][0]=='path',result
retreat.update(goal=[-1.,0.,0.],allow_reverse=True,observation_id='retreat-full-ground')
result=request('/plan',retreat)
assert result['status']=='path' and result['controller_goal'][0]=='backup',result
with condition:state.update(enabled=True,observation_id=retreat['observation_id'])
time.sleep(.15)
retreat['points']=front
retreat['range_rays'].update(ends=front,origin_indices=[0]*len(front))
retreat['semantic_observations']=[]
retreat['observation_id']='retreat-retained-ground'
result=request('/plan',retreat)
assert result['status']=='path',result
with condition:state['observation_id']=retreat['observation_id']
time.sleep(.2)
backward=responses[-1]
report['retained_ground_backup']=dict(plan=result,command=backward)
assert backward['reason']=='none' and -.1<=backward['speed_mps']<0.,backward
assert backward['support_policy']=='observed-static-ground-retreat',backward
# Fresh rear returns still veto a previously observed, clear floor.
obstacle=[[-.65,j*.05,.3] for j in range(-10,11)]
retreat['points']=front+obstacle
retreat['range_rays'].update(ends=front+obstacle,origin_indices=[0]*(len(front)+len(obstacle)))
retreat['observation_id']='retreat-new-rear-obstacle'
request('/plan',retreat)
with condition:state['observation_id']=retreat['observation_id']
time.sleep(.15)
report['new_rear_obstacle_zero']=responses[-1]
assert responses[-1]['speed_mps']==responses[-1]['yaw_rate_rps']==0.,responses[-1]
# Restore the archived fixture before the existing lease/fault checks.
with condition:
state.update(enabled=False,pose=original['pose'])
assert request('/reset',{})['reset']
ready()
deadline=time.monotonic()+15
while request('/plan',value)['status']!='path':
assert time.monotonic()<deadline,'Archived fixture did not restore'
time.sleep(.1)
with condition:state['observation_id']=value['observation_id']
with condition:state['enabled']=False
time.sleep(.1)
assert responses[-1]['speed_mps']==responses[-1]['yaw_rate_rps']==0.
@@ -168,6 +168,7 @@ class ContinuousControl:
speed, angular, support_scale, support = self.support.regulate(
speed, angular, terrain, pose, request["body_contact_height_m"],
current_points=points,
observed_retreat=bool(reverse and request.get("continuous")),
)
evidence = dict(support_policy=support["policy"]["reason"],
support_reasons=support["support_reasons"],
@@ -13,12 +13,51 @@ from .semantic_surface import SemanticSurface
class ObservedGoals:
def __init__(self):
def __init__(self, *, reverse_heading_tolerance=math.pi/4):
self.reverse_heading_tolerance = reverse_heading_tolerance
self.surface = SemanticSurface(retain_near=True)
self.measured = {}
self.evidence = None
def observe(self, samples, captured_at, pose):
self.surface.observe(samples, captured_at, pose)
sample = np.asarray(samples, dtype=float).reshape(-1, 4)
for key, point in zip(self.surface.cell_keys(sample), sample, strict=True):
self.measured[tuple(key)] = point[:3].copy()
# Same lifetime and classification owner as the semantic cells. Keep
# actual range returns, never invented voxel centres or hidden geometry.
self.measured = {key: point for key, point in self.measured.items()
if key in self.surface.cells
and self.surface.retained(key, self.surface.cells[key][1], captured_at)}
def boundary_cost(self, candidates, geometry, now):
"""Soft clearance preference, like an inflation potential in a costmap.
A far waypoint is an objective, not a straight-line corridor. Prefer
space away from observed exclusions before reaching their hard veto.
Actual rectangular body/swept support admission remains independent.
"""
barriers = np.array([point for key, point in self.measured.items()
if self.surface.cells.get(key, (1, 0))[0] == 0
and self.surface.retained(key, self.surface.cells[key][1], now)],
dtype=float).reshape(-1, 3)
cost = np.zeros(len(candidates))
if not len(barriers):
return cost
width = geometry['width_m']
# Ignore remote returns before pairwise work; each batch is bounded.
low, high = candidates[:,:2].min(0)-4*width, candidates[:,:2].max(0)+4*width
barriers = barriers[np.all((barriers[:,:2]>=low)&(barriers[:,:2]<=high),axis=1)]
if not len(barriers):
return cost
for start in range(0,len(candidates),128):
batch = candidates[start:start+128]
distance = np.linalg.norm(batch[:,None,:2]-barriers[None,:,:2],axis=2)
dz = barriers[None,:,2]-batch[:,None,2]
relevant = (dz>=-geometry.get('max_step_m', .1)) & (dz<=geometry.get('height_m',width))
nearest = np.min(np.where(relevant,distance,np.inf),axis=1)
cost[start:start+len(batch)] = 2*width*np.exp(-nearest/width)
return cost
def maneuver(self, points, pose, target, prior, excluded, geometry, now, candidate_mask=None):
"""Measured local destinations may temporarily move away from the task.
@@ -30,6 +69,11 @@ class ObservedGoals:
points = np.asarray(points, dtype=float).reshape(-1, 3)
if not len(points) or target is None:
return None
retained = np.array([point for point in self.measured.values()
if np.linalg.norm(point[:2]-np.asarray(pose[:2]))
<= 2*geometry['length_m']], dtype=float).reshape(-1, 3)
if len(retained):
points = np.concatenate((points, retained))
if prior is not None and prior.get("kind") == "orient":
# The viewing intent survives its source leaving the crop. Current
# range and full swept-body support still govern the actual pivot.
@@ -82,16 +126,40 @@ class ObservedGoals:
bearings = np.arctan2(delta[:, 1], delta[:, 0]) - yaw
errors = np.arctan2(np.sin(bearings), np.cos(bearings))
distance = np.linalg.norm(delta, axis=1)
# A short straight back-out is one option, alongside forward arcs and
# A measured retreat is one option, alongside forward arcs and
# stopped pivots. It is never an obligatory first recovery action.
reverse = (np.abs(errors) > math.pi-.12) & (distance <= .8)
# This is a destination proposal, not a swept-clearance certificate.
# Distance is already bounded by the same robot-sized local horizon.
# The blind strip may hide nearby floor; a farther observed rear goal
# must not become a forced 180-degree turn merely because it exceeds
# a separate short-retreat cutoff. Live sweeps still admit every tick.
reverse = np.abs(errors) > math.pi-self.reverse_heading_tolerance
turning = np.where(reverse, math.pi-np.abs(errors), np.abs(errors))
score = np.linalg.norm(candidates[:, :2]-target, axis=1) + .2*turning + .15*distance
score += self.boundary_cost(candidates, geometry, now)
# Recovery actions need a fair turn, as in Nav2's RoundRobin recovery
# subtree. Distance-to-task alone can spend every retry on almost the
# same forward approach before ever considering a measured retreat.
# Balance failed local directions; the rear sector uses reverse.
# Retain the existing geometric score within each family.
# This schedules intentions only, never certifies a body trajectory.
def family(relative):
return np.floor((relative + math.pi/4) / (math.pi/2)).astype(int) % 4
families = family(errors)
failures = np.zeros(4, dtype=int)
if excluded:
failed_delta = np.asarray(excluded)[:, :2] - xy
failed_distance = np.linalg.norm(failed_delta, axis=1)
failed_angle = np.arctan2(failed_delta[:, 1], failed_delta[:, 0])-yaw
failed_angle = np.arctan2(np.sin(failed_angle), np.cos(failed_angle))
nearby = failed_distance <= 2*geometry['length_m']
np.add.at(failures, family(failed_angle[nearby]), 1)
order = np.lexsort((score, failures[families]))
offsets = np.linspace(-geometry["width_m"]/2, geometry["width_m"]/2,
math.ceil(geometry["width_m"]/.1)+1)
# Search once per 20 cm observed cell, not every duplicate ray return.
tried = set()
for i in np.argsort(score, kind="stable"):
for i in order:
point = candidates[i]
key = tuple(self.surface.cell_keys(point[None])[0])
if key in tried:
@@ -116,7 +184,7 @@ class ObservedGoals:
# translation destination while still being worth inspecting with the
# front depth sensors. This grants ONLY an orientation intent. Neither
# the point nor the camera survey certifies the ground under a pivot.
for i in np.argsort(score, kind="stable"):
for i in order:
if abs(errors[i]) >= math.radians(30):
return dict(goal=candidates[i].tolist(), reverse=False, kind="orient")
return inspect_heading()
@@ -192,7 +260,11 @@ class ObservedGoals:
return before.tolist()
distance_to_target = np.linalg.norm(candidates[:, :2] - target, axis=1)
# The declared task, not the selected lens, owns the preferred direction.
score = distance_to_target + 2 * np.abs((candidates[:, :2] - pose[:2]) @ lateral)
x,y,z,w = pose[3:7]
heading = math.atan2(2*(w*z+x*y),1-2*(y*y+z*z))
bearing = np.arctan2(candidates[:,1]-pose[1],candidates[:,0]-pose[0])-heading
score = (distance_to_target + .2*np.abs(np.arctan2(np.sin(bearing),np.cos(bearing)))
+ self.boundary_cost(candidates, geometry, now))
for index in np.argsort(score, kind="stable"):
if supported(candidates[index]):
return candidates[index].tolist()
@@ -103,7 +103,8 @@ class SupportPolicy:
patches=patches,
)
def regulate(self, speed, yaw_rate, terrain, pose, contact_height_m, *, current_points):
def regulate(self, speed, yaw_rate, terrain, pose, contact_height_m, *, current_points,
observed_retreat=False):
m = self.monitor
requested = [speed, yaw_rate]
pivot_scale = 1.0
@@ -262,15 +263,18 @@ class SupportPolicy:
self.partial_yaw_rps / max(abs(yaw_rate), 1e-12),
)
reason = "partial-observation-limit"
if (scale == 0 and self.observed_approaches and speed > 0
if (scale == 0 and self.observed_approaches
and (speed > 0 or (speed < 0 and observed_retreat))
and support["status"] == "observed-supported"):
# The fixed distant track-end probes are context, not the
# commanded sweep. A curb beyond that sweep must not prevent
# stopping on the fully observed ground before it. This branch
# never fills unknown ground, admits reverse, or shrinks away
# never fills unknown ground or shrinks away
# a hazard inside the ORIGINAL command's full stopping bounds.
# It uses causal range memory through the normal map owner;
# current raw returns independently veto changed ground.
# Reverse requires an explicit recovery intent and the same
# completely observed stopping sweep, at the existing crawl cap.
current = np.asarray(current_points, dtype=float).reshape(-1, 3)
fresh = m.assess_command_support(
speed, yaw_rate,
@@ -285,9 +289,10 @@ class SupportPolicy:
elif fresh["unsafe_samples"]:
reason = "observed-unsafe-support"
else:
scale = min(1.0, self.partial_speed_mps / speed,
scale = min(1.0, self.partial_speed_mps / abs(speed),
self.partial_yaw_rps / max(abs(yaw_rate), 1e-12))
reason = "observed-static-ground-approach"
reason = ("observed-static-ground-approach" if speed > 0
else "observed-static-ground-retreat")
if scale == 0 and requested_support is not None:
support = requested_support
fresh_sweep = requested_fresh
+7 -2
View File
@@ -394,8 +394,12 @@ class ComposedInference:
self.source = source_for_rig(self.inputs["sensors"])
self.optics = None
self.task_view_intent = TaskViewIntent()
# Native Nav2 BackUp follows the current body axis. The legacy CMU
# controller also supports rear arcs; keep their intent limits distinct.
self.observed_goals = (
ObservedGoals() if self.inputs["sensors"]["schema_version"] in
ObservedGoals(reverse_heading_tolerance=(.12 if any(
n.module.module_id == "simulation-nav2-navigation" for n in self.graph.nodes
) else math.pi/4)) if self.inputs["sensors"]["schema_version"] in
{MOUNTED_SENSOR_SCHEMA, CONTINUOUS_SENSOR_SCHEMA} else None
)
if "mounts" in self.inputs["sensors"]:
@@ -523,7 +527,8 @@ class ComposedInference:
self.body_goal_waypoint = self.body_goal_phase_key = None
self.task_view_intent = TaskViewIntent()
if self.observed_goals is not None:
self.observed_goals = ObservedGoals()
self.observed_goals = ObservedGoals(
reverse_heading_tolerance=self.observed_goals.reverse_heading_tolerance)
self.mission.resume()
self.navigation.request("/reset", {})
deadline = time.monotonic() + 8