Align native planning clearance and admit observed tracked pivots
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -342,7 +342,8 @@ def registry(adapter_root: Path) -> ModuleRegistry:
|
||||
"support_obstacles.py", "semantic_surface.py", "observed_space.py", "range_image.py",
|
||||
"detection_obstacles.py", "route_observation.py", "arrival_approach.py", "pcl_ground.py")
|
||||
runtime = ("configuration.py", "nodes.py", "observed_collision.py", "ros_navigation.py",
|
||||
"server.py", "terrain_node.py", "terrain_observation.py", "terrain_process.py")
|
||||
"server.py", "terrain_node.py", "terrain_observation.py", "terrain_process.py",
|
||||
"detector_exclusion.py", "differential_motion.py")
|
||||
files = [adapter_root/"nav2"/name for name in runtime]
|
||||
files += [adapter_root/"navigation"/name for name in shared]
|
||||
files += [adapter_root/name for name in ("model_stack.py", "navigation_client.py", "rig_collision.py")]
|
||||
|
||||
@@ -42,6 +42,7 @@ class WaypointMission:
|
||||
self.turn_started = self.turn_goal = self.turn_best_error = None
|
||||
self.recovery = ObservedRecovery()
|
||||
self.last_recovery_attempt = None
|
||||
self.local_alignment = None
|
||||
|
||||
def heading_progress(self, pose, seconds):
|
||||
"""Credit new best alignment within the existing bounded turn budget.
|
||||
@@ -90,7 +91,28 @@ class WaypointMission:
|
||||
return True
|
||||
return False
|
||||
|
||||
def observe_alignment(self, result, pose, seconds, execution_inputs_sha256):
|
||||
"""Bind heading progress to the native local Spin, without crediting travel."""
|
||||
self.local_alignment = None
|
||||
if (self.recovery.active or self.goal is None or self.last_time != seconds
|
||||
or self.last_pose != tuple(pose)):
|
||||
return
|
||||
expected = dict(pose=list(pose), simulation_time_seconds=seconds,
|
||||
execution_inputs_sha256=execution_inputs_sha256)
|
||||
owner = result.get("controller_goal") or []
|
||||
if (result.get("route_observation", {}).get("observation") == expected
|
||||
and result.get("status") == "path" and result.get("speed_mps") == 0.
|
||||
and len(owner) == 3 and owner[0] == "align"
|
||||
and list(owner[1]) == list(self.goal[:2])):
|
||||
self.local_alignment = dict(key=("native-align", tuple(owner[1])),
|
||||
xy=list(owner[1]), seconds=seconds)
|
||||
|
||||
def progress_orientation_target(self, seconds):
|
||||
local = self.local_alignment
|
||||
if (local is not None and self.goal is not None
|
||||
and local["xy"] == list(self.goal[:2])
|
||||
and 0 <= seconds-local["seconds"] <= 1.):
|
||||
return {"key": local["key"], "xy": local["xy"]}
|
||||
return self.orientation_target()
|
||||
|
||||
def resume(self):
|
||||
|
||||
@@ -296,7 +296,7 @@ class RoutedMission(WaypointMission):
|
||||
self.body_approach = (orientation["key"], tuple(goal[:2]), seconds)
|
||||
|
||||
def progress_orientation_target(self, seconds):
|
||||
orientation = self.orientation_target()
|
||||
orientation = super().progress_orientation_target(seconds)
|
||||
if self.body_approach is not None and orientation is not None:
|
||||
key, goal, captured = self.body_approach
|
||||
if key == orientation["key"] and 0 <= seconds - captured <= 0.8:
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Real heading improvement toward a native detour is progress, not task arrival."""
|
||||
import math
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.simulation.ai_polygon.mission_policy import WaypointMission
|
||||
|
||||
|
||||
def pose(yaw=0.):
|
||||
return [0.,0.,.37,0.,0.,math.sin(yaw/2),math.cos(yaw/2)]
|
||||
|
||||
|
||||
def receipt(position, seconds, goal):
|
||||
return dict(status='path',speed_mps=0.,yaw_rate_rps=.35,
|
||||
controller_goal=['align',goal[:2],1.],route_observation=dict(observation=dict(
|
||||
pose=position,simulation_time_seconds=seconds,execution_inputs_sha256='run')))
|
||||
|
||||
|
||||
def test_local_turn_away_from_global_bearing_keeps_existing_progress_watchdog_alive():
|
||||
mission = WaypointMission([[10.,0.]])
|
||||
goal = [0.,2.,0.]
|
||||
for second in range(16):
|
||||
position = pose(.04*second)
|
||||
mission.update(position,float(second),lambda *_:goal,
|
||||
choose_maneuver=lambda *_:None)
|
||||
mission.observe_alignment(receipt(position,float(second),goal),position,float(second),'run')
|
||||
assert not mission.recovery.active and mission.attempts==0
|
||||
assert mission.best_distance==10. and mission.index==0
|
||||
|
||||
|
||||
@pytest.mark.parametrize('invalid',['old','other-goal','moving','unbound'])
|
||||
def test_only_the_bound_current_local_spin_can_supply_a_progress_direction(invalid):
|
||||
mission = WaypointMission([[10.,0.]])
|
||||
goal = [0.,2.,0.]
|
||||
position = pose()
|
||||
mission.update(position,2.,lambda *_:goal)
|
||||
result = receipt(position,2.,goal)
|
||||
if invalid=='old':
|
||||
result['route_observation']['observation']['simulation_time_seconds']=1.
|
||||
elif invalid=='other-goal':
|
||||
result['controller_goal'][1]=[0.,3.]
|
||||
elif invalid=='moving':
|
||||
result['speed_mps']=.1
|
||||
else:
|
||||
result['route_observation']['observation']['execution_inputs_sha256']='other'
|
||||
mission.observe_alignment(result,position,2.,'run')
|
||||
assert mission.progress_orientation_target(2.)==mission.orientation_target()
|
||||
|
||||
|
||||
def test_alignment_receipt_expires_and_repeated_yaw_cannot_extend_a_stall():
|
||||
mission = WaypointMission([[10.,0.]])
|
||||
goal = [0.,2.,0.]
|
||||
for second in range(12):
|
||||
position = pose(.2 if second%2 else 0.)
|
||||
mission.update(position,float(second),lambda *_:goal,
|
||||
choose_maneuver=lambda *_:None)
|
||||
mission.observe_alignment(receipt(position,float(second),goal),position,float(second),'run')
|
||||
assert mission.attempts==1
|
||||
assert mission.best_distance==10. and mission.index==0
|
||||
assert mission.progress_orientation_target(14.)==mission.orientation_target()
|
||||
|
||||
|
||||
def test_routed_mission_retains_bound_native_turn_progress_over_route_body_approach():
|
||||
from k1link.simulation.ai_polygon.route_mission import RoutedMission
|
||||
|
||||
# Isolate the routed progress adapter from graph construction and travel.
|
||||
mission = RoutedMission.__new__(RoutedMission)
|
||||
WaypointMission.__init__(mission, [[10.,0.]])
|
||||
position = pose()
|
||||
goal = [0.,2.,0.]
|
||||
mission.goal = goal
|
||||
mission.last_pose, mission.last_time = tuple(position), 2.
|
||||
mission.body_approach = (('route',0), (3.,0.), 2.)
|
||||
mission.observe_alignment(receipt(position,2.,goal),position,2.,'run')
|
||||
direction = mission.progress_orientation_target(2.2)
|
||||
assert direction['xy'] == [0.,2.]
|
||||
assert direction['key'] == ('native-align',(0.,2.))
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Tracked turns and object clearance must agree before motor admission."""
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def motion(monkeypatch):
|
||||
root = Path(__file__).parents[1] / 'simulation/ai-polygon'
|
||||
monkeypatch.syspath_prepend(str(root))
|
||||
monkeypatch.syspath_prepend(str(root / 'nav2'))
|
||||
from detector_exclusion import DetectorExclusion
|
||||
from differential_motion import alignment_angle
|
||||
from navigation.footprint import Footprint
|
||||
monitor = Footprint(dict(length_m=1., width_m=.8, max_step_m=.1, max_slope_degrees=20))
|
||||
def alignment(pose, goal, terrain, detected, monitor):
|
||||
floor = np.array([[i*.05,j*.05,0.,0.] for i in range(-40,41) for j in range(-40,41)])
|
||||
return alignment_angle(pose, goal, np.concatenate((floor,terrain)), detected, monitor,.37)
|
||||
return alignment, DetectorExclusion(), monitor
|
||||
|
||||
|
||||
def pose(yaw=0):
|
||||
return np.array([0., 0., .37, 0., 0., math.sin(yaw/2), math.cos(yaw/2)])
|
||||
|
||||
|
||||
@pytest.mark.parametrize('yaw', [0., .31, -1.3])
|
||||
@pytest.mark.parametrize('angle', [math.pi/4, -math.pi/2, math.pi])
|
||||
def test_large_local_direction_change_can_use_zero_translation_turn(motion, yaw, angle):
|
||||
alignment, _, monitor = motion
|
||||
goal = [2*math.cos(yaw+angle), 2*math.sin(yaw+angle), 0.]
|
||||
result = alignment(pose(yaw), goal, np.empty((0,4)), np.empty((0,3)), monitor)
|
||||
assert abs(math.atan2(math.sin(result-angle), math.cos(result-angle))) < 1e-10
|
||||
assert alignment(pose(yaw+angle), goal, np.empty((0,4)), np.empty((0,3)), monitor) is None
|
||||
|
||||
|
||||
def test_turn_checks_intermediate_corner_sweep_and_detector_reserve(motion):
|
||||
alignment, _, monitor = motion
|
||||
# Initially outside the chassis; an intermediate corner hits it during a turn.
|
||||
hazard = np.array([[0., -.59, .3, 1.1]])
|
||||
assert monitor._clear(monitor._obstacles(hazard, pose()), np.zeros(2), 0.)
|
||||
assert alignment(pose(), [0.,2.,0.], hazard, np.empty((0,3)), monitor) is None
|
||||
# Ordinary body padding fits this turn; the detector's larger reserve does not.
|
||||
point = np.array([[0., -.86, .3]])
|
||||
assert alignment(pose(), [0.,2.,0.], np.empty((0,4)), np.empty((0,3)), monitor) is not None
|
||||
assert alignment(pose(), [0.,2.,0.], np.empty((0,4)), point, monitor) is None
|
||||
|
||||
|
||||
def test_small_course_correction_stays_with_native_path_controller(motion):
|
||||
alignment, _, monitor = motion
|
||||
assert alignment(pose(), [2.,.5,0.], np.empty((0,4)), np.empty((0,3)), monitor) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('offset', [[0.,0.], [.023,-.017], [13.193,-24.208]])
|
||||
def test_search_reserve_covers_guard_at_every_heading_without_inventing_ground(motion, offset):
|
||||
_, exclusion, monitor = motion
|
||||
centre = np.asarray(offset)
|
||||
observed = np.array([[*centre, .7]])
|
||||
original = observed.copy()
|
||||
rover = pose()
|
||||
rover[:2] = centre
|
||||
costs = exclusion.points(observed, rover)
|
||||
assert len(costs) and len(costs) < 400
|
||||
# Any point of the added square margin, rotated at any heading, is covered
|
||||
# by a lethal published cell. Test the contour and its interior separately.
|
||||
for angle in np.linspace(-math.pi, math.pi, 97):
|
||||
c, s = math.cos(angle), math.sin(angle)
|
||||
axes = np.array([[c,-s],[s,c]])
|
||||
local = np.array([[x,y] for x in np.linspace(-.3,.3,9)
|
||||
for y in np.linspace(-.3,.3,9)])
|
||||
samples = local@axes.T+centre
|
||||
nearest = np.min(np.max(np.abs(samples[:,None]-costs[None]),axis=2),axis=1)
|
||||
assert np.all(nearest <= .05/2+1e-9)
|
||||
np.testing.assert_array_equal(observed, original)
|
||||
assert exclusion.points([], rover).shape == (0,2)
|
||||
|
||||
|
||||
def test_retreat_creates_turning_room_without_relaxing_object_clearance(motion):
|
||||
alignment, _, monitor = motion
|
||||
obstacle = np.array([[.8,0.,.3]])
|
||||
terrain = np.column_stack((obstacle,[1.1]))
|
||||
destination = [1.5,1.5,0.]
|
||||
# Too close for the corners to sweep around this object at the start.
|
||||
assert alignment(pose(), destination, terrain, obstacle, monitor) is None
|
||||
# A real measured retreat gives the same requested destination room for a
|
||||
# native in-place turn. No fixed short reverse distance is an admission rule.
|
||||
after_retreat = pose()
|
||||
after_retreat[0] = -.8
|
||||
turn = alignment(after_retreat, destination, terrain, obstacle, monitor)
|
||||
assert turn is not None and turn > math.pi/6
|
||||
|
||||
|
||||
def test_unknown_future_track_ground_does_not_select_an_incomplete_turn(motion):
|
||||
from differential_motion import alignment_angle
|
||||
_, _, monitor = motion
|
||||
floor = np.array([[i*.05,j*.05,0.,0.] for i in range(-25,26) for j in range(-25,26)])
|
||||
assert alignment_angle(pose(),[0.,2.,0.],floor,[],monitor,.37) is not None
|
||||
# The current footprint and front are observed; rear-side future contact
|
||||
# ground is unknown. A short initial pivot can fit but the whole turn cannot.
|
||||
hole = floor[~((floor[:,0]<-.2)&(floor[:,1]>.45))]
|
||||
assert alignment_angle(pose(),[0.,2.,0.],hole,[],monitor,.37) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('helper',['detector_exclusion.py','differential_motion.py'])
|
||||
def test_native_module_identity_includes_behavior_helpers(monkeypatch,helper):
|
||||
from k1link.simulation.ai_polygon.composition import registry
|
||||
|
||||
root=Path(__file__).parents[1]/'simulation/ai-polygon'
|
||||
def identities():
|
||||
return {m.module_id:m.implementation_sha256 for m in registry(root).modules}
|
||||
before=identities()
|
||||
original=Path.read_bytes
|
||||
def changed(path):
|
||||
data=original(path)
|
||||
return data+b'\n# distinct implementation\n' if path==root/'nav2'/helper else data
|
||||
monkeypatch.setattr(Path,'read_bytes',changed)
|
||||
after=identities()
|
||||
assert before['simulation-nav2-navigation']!=after['simulation-nav2-navigation']
|
||||
assert before['simulation-waypoint-mission']==after['simulation-waypoint-mission']
|
||||
Reference in New Issue
Block a user