Align native planning clearance and admit observed tracked pivots

This commit is contained in:
DCCONSTRUCTIONS
2026-10-08 21:14:12 +03:00
parent 7f87b5aa4d
commit 012286e972
12 changed files with 518 additions and 13 deletions
@@ -0,0 +1,144 @@
"""Bounded native Nav2 action integration with synthetic measured odometry.
No actuator, scene geometry or simulation acceptance is implied by this test.
"""
import argparse
import http.client
import json
import math
import os
import signal
import subprocess
import threading
import time
from pathlib import Path
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--inputs', type=Path, required=True)
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
args.output.mkdir(parents=True, exist_ok=False)
inputs = json.loads(args.inputs.read_text())
report = dict(authority=None, scope='synthetic native-action integration', passed=False)
log = (args.output/'server.log').open('w')
process = subprocess.Popen(['python3', str(Path(__file__).with_name('server.py'))],
env={**os.environ, 'MISSIONCORE_RUN_INPUTS':str(args.inputs)},
stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
lock = threading.Lock()
state = dict(pose=[0.,0.,.37,0.,0.,0.,1.], enabled=False, observation_id='bootstrap')
running = threading.Event()
running.set()
responses, errors = [], []
def request(path, value=None):
client = http.client.HTTPConnection('127.0.0.1',8010,timeout=3)
try:
client.request('GET' if value is None else 'POST',path,
body=None if value is None else json.dumps(value),
headers={} if value is None else {'Content-Type':'application/json'})
response = client.getresponse()
body = json.loads(response.read())
if response.status != 200:
raise RuntimeError((response.status, body))
return body
finally:
client.close()
def controls():
try:
while running.is_set():
with lock:
packet = dict(state)
packet.update(execution_inputs_sha256=inputs['sha256'],
measured_twist=[0.,0.,0.],speed_mps=0.,pose_age_seconds=0.,perception_age_seconds=0.)
responses.append(request('/control',packet))
time.sleep(.04)
except BaseException as error:
errors.append(str(error))
thread = None
try:
deadline = time.monotonic()+20
while True:
try:
request('/ready')
break
except (OSError,RuntimeError):
assert time.monotonic()<deadline and process.poll() is None
time.sleep(.1)
thread = threading.Thread(target=controls)
thread.start()
floor = [[i*.075,j*.075,0.] for i in range(-40,41) for j in range(-40,41)]
value = dict(execution_inputs_sha256=inputs['sha256'],pose=list(state['pose']),
observation_id='bootstrap',body_contact_height_m=.37,max_speed_mps=.1,
points=floor,goal=[2.,0.,0.],allow_reverse=False,translation_allowed=True,
geometry_age_seconds=0.,detection_age_seconds=0.,detection_point_indices=[],
semantic_observations=[dict(frame_id='floor',age_seconds=0.,
samples=[[*p,1.] for p in floor])],simulation_time_seconds=0.,
range_rays=dict(origins=[[0.,0.,.37],[0.,0.,.37]],ends=floor,
origin_indices=[0]*len(floor)),continuous=True)
plans = []
def plan_until(predicate, timeout=8.):
deadline = time.monotonic()+timeout
while True:
value['observation_id'] = 'test-'+str(len(plans))
with lock:
value['pose'] = list(state['pose'])
result = request('/plan',value)
plans.append(result)
with lock:
state.update(observation_id=value['observation_id'],enabled=result['status']=='path')
if predicate(result):
return result
assert time.monotonic()<deadline,result
time.sleep(.08)
plan_until(lambda r:r.get('controller_goal',[None])[0]=='path',15.)
value['goal'] = [1.5,1.5,0.]
turn = plan_until(lambda r:r.get('controller_goal',[None])[0]=='align')
assert turn['speed_mps']==0. and turn['yaw_rate_rps']>0.,turn
time.sleep(.15)
assert any(r['speed_mps']==0. and r['yaw_rate_rps']>0. and r['reason']=='none'
for r in responses),responses[-5:]
report['native_spin'] = turn
# Keep refreshing the same goal while synthetic measured yaw changes.
# The action must survive crossing the 30-degree entry threshold.
with lock:
state['pose'][5:] = [math.sin(.35/2),math.cos(.35/2)]
continued = plan_until(lambda r:r.get('controller_goal',[None])[0]=='align')
assert continued['speed_mps']==0.,continued
report['continued_spin'] = continued
# Nav2 observes completion, then the very same translation goal starts
# its own FollowPath. No alignment receipt is reused as motor authority.
with lock:
state['pose'][5:] = [math.sin((math.pi/4+.01)/2),math.cos((math.pi/4+.01)/2)]
translated = plan_until(lambda r:r.get('controller_goal',[None])[0]=='path')
report['after_spin_path'] = translated
old = request('/control',dict(execution_inputs_sha256=inputs['sha256'],
pose=state['pose'],measured_twist=[0.,0.,0.],speed_mps=0.,pose_age_seconds=0.,
perception_age_seconds=0.,enabled=True,observation_id='unknown-observation'))
assert old['speed_mps']==old['yaw_rate_rps']==0.,old
report['unbound_command_rejected'] = old
assert not errors,errors
report['passed'] = True
finally:
running.clear()
if thread:
thread.join(timeout=4)
os.killpg(process.pid,signal.SIGTERM)
try:
process.wait(timeout=8)
except subprocess.TimeoutExpired:
os.killpg(process.pid,signal.SIGKILL)
process.wait(timeout=3)
log.close()
report.update(plans=locals().get('plans',[]),controls=responses,errors=errors)
(args.output/'result.json').write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps({k:v for k,v in report.items() if k not in ('plans','controls')}))
if __name__ == '__main__':
main()
@@ -0,0 +1,41 @@
"""Rasterise detector reserve as collision costs, never as sensor measurements.
A rectangle enlarged on both axes by d lies inside its Minkowski sum with a
radius sqrt(2)*d disk. This covers the command guard's 35 cm reserve at every
heading while retaining Nav2's ordinary 5 cm footprint padding. The extra
raster allowance covers source-cell and published-cell quantisation. Raw rays,
terrain, support and independent exact-return command checks remain unchanged.
"""
import math
import numpy as np
from navigation.detection_obstacles import DetectionObstacles
class DetectorExclusion:
def __init__(self, resolution=.05, footprint_padding=.05, half_extent=8.):
self.resolution, self.half_extent = resolution, half_extent
self.radius = math.sqrt(2) * max(0., DetectionObstacles.clearance_m-footprint_padding)
cells = math.ceil(self.radius/resolution + math.sqrt(2))
self.offsets = np.array([(x,y) for x in range(-cells,cells+1)
for y in range(-cells,cells+1)
if math.hypot(x,y)*resolution <= self.radius+math.sqrt(2)*resolution])
def points(self, detected, pose):
detected = np.asarray(detected, dtype=float).reshape(-1,3)
if not np.isfinite(detected).all():
raise ValueError('Invalid detector exclusion observations')
if not len(detected):
return np.empty((0,2))
r = self.resolution
origin = np.floor(np.asarray(pose[:2])/r)*r-self.half_extent
size = math.ceil(2*self.half_extent/r)
seeds = np.unique(np.floor((detected[:,:2]-origin)/r).astype(np.int64), axis=0)
pad = int(np.max(np.abs(self.offsets)))
seeds = seeds[np.all((seeds>=-pad)&(seeds<size+pad),axis=1)]
occupied = np.zeros((size,size),dtype=bool)
for offset in self.offsets:
cells = seeds+offset
cells = cells[np.all((cells>=0)&(cells<size),axis=1)]
occupied[cells[:,0],cells[:,1]] = True
return origin+(np.argwhere(occupied)+.5)*r
@@ -0,0 +1,60 @@
"""Choose a native in-place turn before translation when the body sweep fits.
This is action selection, not a path or velocity controller. Nav2 Spin owns
rotation; the live range, support, detector and freshness gates admit each tick.
"""
import math
import numpy as np
from navigation.detection_obstacles import DetectionObstacles
from navigation.support_surface import SupportSurface
def observed_turn_support(angle, terrain, pose, monitor, contact_height):
"""Test the complete newly entered contact area before choosing Spin.
Use the existing contact-cell geometry and support classifier. Retain the
per-command discrepancy envelope at every orientation; no floor is filled
under the current body and no positive motor permission is returned.
"""
bounds = monitor.command_bounds(0., math.copysign(.15, angle))
bounds['horizon_seconds'] = abs(angle)/.15
if monitor.contacts is not None:
local, _ = monitor.contacts.cells(bounds, math.copysign(.15, angle))
else:
# Legacy geometry has no contact bands: conservatively inspect the
# whole rotational disk on the existing fixed support-cell lattice.
radius = math.hypot(monitor.half_length, monitor.half_width)
radius += max(bounds['discrepancy_xy_m'])
cells = math.ceil(radius/.1)
local = np.array([[i*.1,j*.1] for i in range(-cells,cells+1)
for j in range(-cells,cells+1) if math.hypot(i*.1,j*.1)<=radius+.1])
required = (np.abs(local[:,0])>monitor.half_length) | (np.abs(local[:,1])>monitor.half_width)
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)]])
surface = SupportSurface(terrain, pose, contact_height, monitor.max_step, monitor.max_slope,
anchor_radius_m=math.hypot(monitor.half_length,monitor.half_width))
states, _ = monitor.classify_contacts(surface,local[required]@axes.T)
return bool(np.all(states=='observed-supported'))
def alignment_angle(pose, goal, terrain, detected, monitor, contact_height):
delta = np.asarray(goal[:2]) - np.asarray(pose[:2])
if np.linalg.norm(delta) <= .4:
return None
x, y, z, w = pose[3:]
yaw = math.atan2(2*(w*z+x*y), 1-2*(y*y+z*z))
bearing = math.atan2(delta[1], delta[0]) - yaw
angle = math.atan2(math.sin(bearing), math.cos(bearing))
if abs(angle) < math.pi/6:
return None
if not monitor.rotation_clear(angle, terrain, pose):
return None
objects = DetectionObstacles(monitor)
hazards = np.column_stack((detected, np.full(len(detected), objects.cost)))
if not objects.monitor.rotation_clear(angle, hazards, pose):
return None
if not observed_turn_support(angle, terrain, pose, monitor, contact_height):
return None
return angle
@@ -6,6 +6,8 @@ independent gates keep the existing observed terrain and semantic evidence.
import math
import struct
import numpy as np
from detector_exclusion import DetectorExclusion
from geometry_msgs.msg import TransformStamped
from rclpy.time import Time
from sensor_msgs.msg import PointCloud2, PointField
@@ -26,11 +28,12 @@ def cloud(stamp, frame, points):
class ObservedCollision:
def __init__(self, node, max_step, origin_count):
self.node, self.max_step = node, max_step
self.detector_exclusion = DetectorExclusion()
self.rays = [node.create_publisher(PointCloud2, '/observed_rays_'+str(i), 2)
for i in range(origin_count)]
self.hazards = node.create_publisher(PointCloud2, '/observed_hazards', 2)
def publish(self, request, terrain, elapsed):
def publish(self, request, terrain, elapsed, *, detected=()):
rays = request['range_rays']
age = float(request['geometry_age_seconds'])+elapsed
if not math.isfinite(age) or age < 0 or len(rays['origins']) != len(self.rays):
@@ -50,5 +53,9 @@ class ObservedCollision:
points=[[end[0]-origin[0],end[1]-origin[1]]
for end, owner in zip(rays['ends'], rays['origin_indices']) if owner==i]
publisher.publish(cloud(stamp,'range'+str(i),points))
self.hazards.publish(cloud(stamp,'map',terrain[terrain[:,3]>self.max_step+1e-4]))
# Both measured hazards and derived clearance costs belong to search.
# Never feed the reserve raster back into raw range or support evidence.
hazards = terrain[terrain[:,3]>self.max_step+1e-4,:2]
reserve = self.detector_exclusion.points(detected, request['pose'])
self.hazards.publish(cloud(stamp,'map',np.concatenate((hazards,reserve))))
return True
+25 -9
View File
@@ -19,6 +19,7 @@ import rclpy
import yaml
from action_msgs.msg import GoalStatus
from configuration import observed_configuration
from differential_motion import alignment_angle
from navigation.arrival_approach import validate_orientation
from navigation.continuous_control import ContinuousControl
from navigation.footprint import Footprint
@@ -44,6 +45,7 @@ class Navigation:
self.plan_lock, self.owner_lock = threading.Lock(), threading.Lock()
self.action_key = None
self.completed_orientation = None
self.attempted_alignment = None
self.path = None
self.path_planned_at = float('-inf')
self.active, self.failure = False, None
@@ -124,7 +126,8 @@ class Navigation:
terrain = observed['terrain']
self.latest_terrain = observed
observed['observation_id'] = value['observation_id']
if not self.collision.publish(value, observed['search_terrain'], time.monotonic()-entered):
if not self.collision.publish(value, observed['search_terrain'], time.monotonic()-entered,
detected=observed['detected']):
return self.reply('stale-range')
route = route_observation(terrain, pose, value, self.monitor.max_step)
orientation = validate_orientation(value.get('orientation_target'))
@@ -150,22 +153,33 @@ class Navigation:
and self.node.terminal is not None and self.node.terminal.done()
and self.node.terminal.result().status == GoalStatus.STATUS_SUCCEEDED):
self.completed_orientation = orientation_key
# Smac/DWB owns the approach to a permitted translation destination,
# including recovery goals. Forcing a bearing-alignment Spin first can
# sweep the rear into an obstacle when a forward arc is available.
# Spin belongs only to explicit orientation-only intent; its completion
# cannot authorize translation. BackUp keeps the existing body heading.
orienting = (not reverse and orientation is not None
# The tracked rover can change heading without translating. Consider
# a native Spin before a large direction change, only if the complete
# rectangular body turn fits the obstacle/detector reserve and its
# complete newly entered track sweep has measured support.
# Unsafe turns leave Smac/DWB free to find an arc. Support and all live
# command gates still apply during Spin; completion grants no motion.
alignment_key = ('align', tuple(goal[:2]), limit)
aligning = (not reverse and value['translation_allowed']
and self.action_key == alignment_key and self.node.terminal is not None
and not self.node.terminal.done())
turn = None
if (not reverse and value['translation_allowed'] and not aligning
and alignment_key != self.attempted_alignment):
turn = alignment_angle(pose, goal, terrain, observed['detected'], self.monitor,
value['body_contact_height_m'])
orienting = aligning or turn is not None or (not reverse and orientation is not None
and orientation_key != self.completed_orientation
and not value['translation_allowed'])
if not value['translation_allowed'] and not orienting:
self.node.stop()
return self.reply('no-permitted-goal', status='blocked', route_observation=route)
if orienting:
delta = np.asarray(orientation['xy'])-pose[:2]
automatic = aligning or turn is not None
delta = (goal[:2] if automatic else np.asarray(orientation['xy']))-pose[:2]
heading = math.atan2(delta[1], delta[0])
angle = math.atan2(math.sin(heading-yaw_of(pose)), math.cos(heading-yaw_of(pose)))
key = orientation_key
key = alignment_key if automatic else orientation_key
if key != self.action_key:
with self.owner_lock:
self.action_key = None
@@ -173,6 +187,8 @@ class Navigation:
# a second wall-clock maneuver budget in a slower simulation.
# The unchanged command/data leases still gate every output.
self.node.spin(angle, 0.)
if automatic:
self.attempted_alignment = alignment_key
local_path = [[0.,0.,0.],[0.,0.,0.]]
elif reverse:
delta = goal[:2]-pose[:2]
@@ -81,6 +81,21 @@ class Footprint:
# 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 rotation_clear(self, angle, terrain, pose):
"""Collision-only proposal check for a complete turn about the body centre.
Sample corner travel at the same 2.5 cm scale as command admission.
This never certifies ground support or supplies a motor command.
"""
if not math.isfinite(angle) or abs(angle) > math.pi:
raise ValueError("Invalid proposed rotation")
obstacles = self._obstacles(np.asarray(terrain).reshape(-1, 4), pose)
radius = math.hypot(self.collision_half_length + self.clearance_m,
self.collision_half_width + self.clearance_m)
steps = max(1, math.ceil(abs(angle) * radius / .025))
return all(self._clear(obstacles, np.zeros(2), heading)
for heading in np.linspace(0., angle, steps + 1))
def assess_pose(self, terrain, pose, contact_height_m, *, support_terrain=None):
"""Certify a stationary body using observed support, never empty space.
@@ -960,6 +960,8 @@ class ComposedInference:
reason = "waiting"
elif reason == "road" and intent["state"] in {"replanning", "reversing"}:
reason = "replanning"
self.mission.observe_alignment(
result, pose, inputs["source.simulation-time"], self.inputs["sha256"])
body_direction_current = body_goal_query and current_body_destination(
result,
pose,