Compare commits

..
3 Commits
21 changed files with 762 additions and 38 deletions
@@ -21,6 +21,17 @@ PHASES = (
("resume", 3, 1, 0), ("resume", 3, 1, 0),
("final-hold", 3, 0, 0), ("final-hold", 3, 0, 0),
) )
# Direct transitions intentionally omit an intervening safety-zero command.
# This isolates recovery from opposed tracks into straight translation.
TRANSITION_PHASES = (
("hold", 3, 0, 0),
("pivot-left", 8, 0, 0.35),
("exit-left", 6, 1, 0),
("hold-left", 3, 0, 0),
("pivot-right", 8, 0, -0.35),
("exit-right", 6, 1, 0),
("final-hold", 3, 0, 0),
)
CRITERIA = { CRITERIA = {
"translation_fraction_min": 0.5, "translation_fraction_min": 0.5,
"turn_fraction_min": 0.45, "turn_fraction_min": 0.45,
+15 -15
View File
@@ -96,23 +96,23 @@ class ChassisSpeedFeedback:
# requested yaw differential is retained. Safety zero stays zero. # requested yaw differential is retained. Safety zero stays zero.
pivot_room = abs(yaw_rate) * self.track_centres / 2 pivot_room = abs(yaw_rate) * self.track_centres / 2
correction = max(-pivot_room, min(pivot_room, correction)) correction = max(-pivot_room, min(pivot_room, correction))
corrected = velocity + correction
# Feedback may reduce translation to zero, but cannot request an
# unplanned reversal. A pivot retains its opposed side directions.
if velocity * corrected < 0:
corrected = 0.0
nominal = SideSpeeds.from_twist(velocity, yaw_rate, self.track_centres) nominal = SideSpeeds.from_twist(velocity, yaw_rate, self.track_centres)
proposed = SideSpeeds.from_twist(corrected, yaw_rate, self.track_centres) # Limit the common correction before applying it to either belt.
# The nominal envelope owns each side's reversal through zero. A # Clipping each side independently changes their difference and can
# common correction must also respect a stationary/turning inner belt. # amplify yaw when one nominal belt is near zero after a pivot.
target = SideSpeeds( for intent in vars(nominal).values():
*( if intent > 0:
value if intent * value > 0 else 0.0 correction = max(correction, -intent)
for intent, value in zip( elif intent < 0:
vars(nominal).values(), vars(proposed).values(), strict=True correction = min(correction, -intent)
else:
correction = 0.0
corrected = velocity + correction
if velocity * corrected < 0:
corrected, correction = 0.0, -velocity
target = SideSpeeds.from_twist(corrected, yaw_rate, self.track_centres).bounded(
self.max_side
) )
)
).bounded(self.max_side)
applied = target.twist(self.track_centres) applied = target.twist(self.track_centres)
self.metrics = dict( self.metrics = dict(
nominal_twist=[velocity, yaw_rate], nominal_twist=[velocity, yaw_rate],
@@ -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 math
import struct import struct
import numpy as np
from detector_exclusion import DetectorExclusion
from geometry_msgs.msg import TransformStamped from geometry_msgs.msg import TransformStamped
from rclpy.time import Time from rclpy.time import Time
from sensor_msgs.msg import PointCloud2, PointField from sensor_msgs.msg import PointCloud2, PointField
@@ -26,11 +28,12 @@ def cloud(stamp, frame, points):
class ObservedCollision: class ObservedCollision:
def __init__(self, node, max_step, origin_count): def __init__(self, node, max_step, origin_count):
self.node, self.max_step = node, max_step self.node, self.max_step = node, max_step
self.detector_exclusion = DetectorExclusion()
self.rays = [node.create_publisher(PointCloud2, '/observed_rays_'+str(i), 2) self.rays = [node.create_publisher(PointCloud2, '/observed_rays_'+str(i), 2)
for i in range(origin_count)] for i in range(origin_count)]
self.hazards = node.create_publisher(PointCloud2, '/observed_hazards', 2) 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'] rays = request['range_rays']
age = float(request['geometry_age_seconds'])+elapsed age = float(request['geometry_age_seconds'])+elapsed
if not math.isfinite(age) or age < 0 or len(rays['origins']) != len(self.rays): 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]] points=[[end[0]-origin[0],end[1]-origin[1]]
for end, owner in zip(rays['ends'], rays['origin_indices']) if owner==i] for end, owner in zip(rays['ends'], rays['origin_indices']) if owner==i]
publisher.publish(cloud(stamp,'range'+str(i),points)) 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 return True
+25 -9
View File
@@ -19,6 +19,7 @@ import rclpy
import yaml import yaml
from action_msgs.msg import GoalStatus from action_msgs.msg import GoalStatus
from configuration import observed_configuration from configuration import observed_configuration
from differential_motion import alignment_angle
from navigation.arrival_approach import validate_orientation from navigation.arrival_approach import validate_orientation
from navigation.continuous_control import ContinuousControl from navigation.continuous_control import ContinuousControl
from navigation.footprint import Footprint from navigation.footprint import Footprint
@@ -44,6 +45,7 @@ class Navigation:
self.plan_lock, self.owner_lock = threading.Lock(), threading.Lock() self.plan_lock, self.owner_lock = threading.Lock(), threading.Lock()
self.action_key = None self.action_key = None
self.completed_orientation = None self.completed_orientation = None
self.attempted_alignment = None
self.path = None self.path = None
self.path_planned_at = float('-inf') self.path_planned_at = float('-inf')
self.active, self.failure = False, None self.active, self.failure = False, None
@@ -124,7 +126,8 @@ class Navigation:
terrain = observed['terrain'] terrain = observed['terrain']
self.latest_terrain = observed self.latest_terrain = observed
observed['observation_id'] = value['observation_id'] 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') return self.reply('stale-range')
route = route_observation(terrain, pose, value, self.monitor.max_step) route = route_observation(terrain, pose, value, self.monitor.max_step)
orientation = validate_orientation(value.get('orientation_target')) 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 is not None and self.node.terminal.done()
and self.node.terminal.result().status == GoalStatus.STATUS_SUCCEEDED): and self.node.terminal.result().status == GoalStatus.STATUS_SUCCEEDED):
self.completed_orientation = orientation_key self.completed_orientation = orientation_key
# Smac/DWB owns the approach to a permitted translation destination, # The tracked rover can change heading without translating. Consider
# including recovery goals. Forcing a bearing-alignment Spin first can # a native Spin before a large direction change, only if the complete
# sweep the rear into an obstacle when a forward arc is available. # rectangular body turn fits the obstacle/detector reserve and its
# Spin belongs only to explicit orientation-only intent; its completion # complete newly entered track sweep has measured support.
# cannot authorize translation. BackUp keeps the existing body heading. # Unsafe turns leave Smac/DWB free to find an arc. Support and all live
orienting = (not reverse and orientation is not None # 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 orientation_key != self.completed_orientation
and not value['translation_allowed']) and not value['translation_allowed'])
if not value['translation_allowed'] and not orienting: if not value['translation_allowed'] and not orienting:
self.node.stop() self.node.stop()
return self.reply('no-permitted-goal', status='blocked', route_observation=route) return self.reply('no-permitted-goal', status='blocked', route_observation=route)
if orienting: 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]) heading = math.atan2(delta[1], delta[0])
angle = math.atan2(math.sin(heading-yaw_of(pose)), math.cos(heading-yaw_of(pose))) 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: if key != self.action_key:
with self.owner_lock: with self.owner_lock:
self.action_key = None self.action_key = None
@@ -173,6 +187,8 @@ class Navigation:
# a second wall-clock maneuver budget in a slower simulation. # a second wall-clock maneuver budget in a slower simulation.
# The unchanged command/data leases still gate every output. # The unchanged command/data leases still gate every output.
self.node.spin(angle, 0.) self.node.spin(angle, 0.)
if automatic:
self.attempted_alignment = alignment_key
local_path = [[0.,0.,0.],[0.,0.,0.]] local_path = [[0.,0.,0.],[0.,0.,0.]]
elif reverse: elif reverse:
delta = goal[:2]-pose[:2] delta = goal[:2]-pose[:2]
@@ -81,6 +81,21 @@ class Footprint:
# cannot authorize moving toward it, reversing into it or corner penetration. # cannot authorize moving toward it, reversing into it or corner penetration.
return bool(np.all(clearance + 1e-6 >= np.minimum(initial, self.clearance_m))) 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): def assess_pose(self, terrain, pose, contact_height_m, *, support_terrain=None):
"""Certify a stationary body using observed support, never empty space. """Certify a stationary body using observed support, never empty space.
@@ -258,7 +258,18 @@ class ObservedGoals:
and (candidate_mask is None or candidate_mask(before[None])[0]) and (candidate_mask is None or candidate_mask(before[None])[0])
and supported(before)): and supported(before)):
return before.tolist() return before.tolist()
distance_to_target = np.linalg.norm(candidates[:, :2] - target, axis=1) # Score the task direction at the existing 3.5 m observation horizon.
# Distance to a remote endpoint mostly rewards longitudinal advance:
# slightly farther side returns can beat a clear straight destination
# and make successive measured goals oscillate across the corridor.
# This reference only ranks actual permitted returns. It is never a
# generated drive goal, a straight-line route or a clearance receipt.
horizon = min(remaining, 3.5)
reference = pose[:2] + forward * horizon
# A smooth local attraction, normalized to metres like boundary_cost.
# Its gradient diminishes near the reference so centimetres of extra
# advance cannot outweigh clearance from an observed corridor edge.
distance_to_target = np.sum((candidates[:, :2] - reference)**2, axis=1) / horizon
# The declared task, not the selected lens, owns the preferred direction. # The declared task, not the selected lens, owns the preferred direction.
x,y,z,w = pose[3:7] x,y,z,w = pose[3:7]
heading = math.atan2(2*(w*z+x*y),1-2*(y*y+z*z)) heading = math.atan2(2*(w*z+x*y),1-2*(y*y+z*z))
@@ -10,7 +10,6 @@ import itertools
import numpy as np import numpy as np
VIEW_FIELDS = ("view_models", "view_sizes", "view_axes", "view_parameters", "view_ranges") VIEW_FIELDS = ("view_models", "view_sizes", "view_axes", "view_parameters", "view_ranges")
@@ -60,7 +59,35 @@ class RangeImages:
self.models, self.sizes, self.origins, self.axes, self.parameters, strict=True): self.models, self.sizes, self.origins, self.axes, self.parameters, strict=True):
image = self.ranges[offset:offset+w*h].reshape(h, w) image = self.ranges[offset:offset+w*h].reshape(h, w)
offset += w*h offset += w*h
local = (corners-origin) @ axes # Clearing requires EVERY corner and EVERY pixel in its footprint.
# A single corner/pixel that fails is therefore a sufficient veto.
# Most retained returns are still occluded: reject those cheaply
# before projecting the other seven corners. Survivors still take
# the complete original test below; this grants no new free space.
first = (corners[:, :1, :]-origin) @ axes
first_distance = np.linalg.norm(first, axis=2)[:, 0]
if model == 0:
first_u = (np.degrees(np.arctan2(first[..., 1], first[..., 0]))-p[0])/p[1]
first_u = (first_u + (first_u-first_u+w/2) % w-w/2)[:, 0]
first_v = ((np.degrees(np.arctan2(first[..., 2],
np.linalg.norm(first[..., :2], axis=2)))-p[2])/p[3])[:, 0]
eligible = np.ones(len(points), dtype=bool)
else:
front = first[:, 0, 0]
eligible = front > 1e-6
denominator = np.maximum(front, 1e-6)
first_u = p[2]-p[0]*first[:, 0, 1]/denominator-0.5
first_v = p[3]-p[1]*first[:, 0, 2]/denominator-0.5
eligible &= (np.floor(first_u) >= 0) & (np.ceil(first_u) < w)
eligible &= ((first_distance > margin_m) & (np.floor(first_v) >= 0)
& (np.ceil(first_v) < h) & ~result)
candidates = np.flatnonzero(eligible)
measured = image[np.floor(first_v[candidates]).astype(int),
np.floor(first_u[candidates]).astype(int) % w]
candidates = candidates[measured > first_distance[candidates]+margin_m]
if not len(candidates):
continue
local = (corners[candidates]-origin) @ axes
distance = np.linalg.norm(local, axis=2) distance = np.linalg.norm(local, axis=2)
if model == 0: if model == 0:
u = (np.degrees(np.arctan2(local[..., 1], local[..., 0]))-p[0])/p[1] u = (np.degrees(np.arctan2(local[..., 1], local[..., 0]))-p[0])/p[1]
@@ -68,7 +95,7 @@ class RangeImages:
u = u[:, :1] + (u-u[:, :1]+w/2) % w-w/2 u = u[:, :1] + (u-u[:, :1]+w/2) % w-w/2
v = (np.degrees(np.arctan2(local[..., 2], v = (np.degrees(np.arctan2(local[..., 2],
np.linalg.norm(local[..., :2], axis=2)))-p[2])/p[3] np.linalg.norm(local[..., :2], axis=2)))-p[2])/p[3]
visible = np.ones(len(points), dtype=bool) visible = np.ones(len(candidates), dtype=bool)
else: else:
front = local[..., 0] front = local[..., 0]
visible = (front > 1e-6).all(axis=1) visible = (front > 1e-6).all(axis=1)
@@ -82,7 +109,7 @@ class RangeImages:
visible &= (low_u >= 0) & (high_u < w) visible &= (low_u >= 0) & (high_u < w)
# A near-sensor voxel spanning a large portion of the image stays # A near-sensor voxel spanning a large portion of the image stays
# unknown. Bound work, without subsampling its clearing footprint. # unknown. Bound work, without subsampling its clearing footprint.
visible &= (high_u-low_u <= 8) & (high_v-low_v <= 8) & ~result visible &= (high_u-low_u <= 8) & (high_v-low_v <= 8)
indices = np.flatnonzero(visible) indices = np.flatnonzero(visible)
if not len(indices): if not len(indices):
continue continue
@@ -96,5 +123,5 @@ class RangeImages:
rows = np.flatnonzero(inside) rows = np.flatnonzero(inside)
measured = image[lv[rows]+dv, (lu[rows]+du) % w] measured = image[lv[rows]+dv, (lu[rows]+du) % w]
free[rows] &= measured > required[rows] free[rows] &= measured > required[rows]
result[indices[free]] = True result[candidates[indices[free]]] = True
return result return result
@@ -960,6 +960,8 @@ class ComposedInference:
reason = "waiting" reason = "waiting"
elif reason == "road" and intent["state"] in {"replanning", "reversing"}: elif reason == "road" and intent["state"] in {"replanning", "reversing"}:
reason = "replanning" 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( body_direction_current = body_goal_query and current_body_destination(
result, result,
pose, pose,
@@ -15,7 +15,7 @@ parser = argparse.ArgumentParser()
parser.add_argument("--output", type=Path, required=True) parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--reservation", type=Path, required=True) parser.add_argument("--reservation", type=Path, required=True)
parser.add_argument("--case", action="append", dest="case_ids") parser.add_argument("--case", action="append", dest="case_ids")
parser.add_argument("--profile", choices=("control", "sweep"), default="control") parser.add_argument("--profile", choices=("control", "sweep", "transition"), default="control")
parser.add_argument("--contact-sample-hz", type=int, default=0, choices=(0, 1, 5, 10, 60)) parser.add_argument("--contact-sample-hz", type=int, default=0, choices=(0, 1, 5, 10, 60))
args = parser.parse_args() args = parser.parse_args()
receipt = json.loads(args.reservation.read_text(encoding="utf-8-sig")) receipt = json.loads(args.reservation.read_text(encoding="utf-8-sig"))
@@ -40,6 +40,9 @@ from k1link.simulation.ai_polygon.robots import select_robot # noqa: E402
from k1link.simulation.ai_polygon.run_inputs import legacy_run_inputs # noqa: E402 from k1link.simulation.ai_polygon.run_inputs import legacy_run_inputs # noqa: E402
from k1link.simulation.ai_polygon.run_robot import configure_robot # noqa: E402 from k1link.simulation.ai_polygon.run_robot import configure_robot # noqa: E402
if args.profile == "transition":
from control_qualification import TRANSITION_PHASES as PHASES
if args.profile == "sweep": if args.profile == "sweep":
from sweep_qualification import CRITERIA, PHASES, SCHEMA from sweep_qualification import CRITERIA, PHASES, SCHEMA
from sweep_qualification import phase_metrics as sweep_metrics from sweep_qualification import phase_metrics as sweep_metrics
+12 -2
View File
@@ -102,13 +102,23 @@ class TwoSideDrive:
dt = min(dt, self.limits.max_step_seconds) dt = min(dt, self.limits.max_step_seconds)
old = (self.applied.left_mps, self.applied.right_mps) old = (self.applied.left_mps, self.applied.right_mps)
goal = (target.left_mps, target.right_mps) goal = (target.left_mps, target.right_mps)
goal = tuple(0.0 if a * b < 0 else b for a, b in zip(old, goal, strict=True))
fraction = 1.0 fraction = 1.0
for a, b in zip(old, goal, strict=True): for a, b in zip(old, goal, strict=True):
if a * b < 0:
continue
rate = ( rate = (
self.limits.acceleration_mps2 if abs(b) > abs(a) else self.limits.deceleration_mps2 self.limits.acceleration_mps2 if abs(b) > abs(a) else self.limits.deceleration_mps2
) )
if a != b: if a != b:
fraction = min(fraction, rate * dt / abs(b - a)) fraction = min(fraction, rate * dt / abs(b - a))
self.applied = SideSpeeds(*(a + (b - a) * fraction for a, b in zip(old, goal, strict=True))) # A reversing side owns its braking phase. Coupling its zero target to
# the other side's acceleration fraction can approach zero forever and
# leave one belt held while the other accelerates into an unwanted arc.
# Reach zero at the declared braking rate; accelerate in the opposite
# direction only on a later tick. Ordinary arcs keep the common fraction.
self.applied = SideSpeeds(*(
math.copysign(max(0.0, abs(a) - self.limits.deceleration_mps2 * dt), a)
if a * b < 0 else a + (b - a) * fraction
for a, b in zip(old, goal, strict=True)
))
return self.applied return self.applied
@@ -342,7 +342,8 @@ def registry(adapter_root: Path) -> ModuleRegistry:
"support_obstacles.py", "semantic_surface.py", "observed_space.py", "range_image.py", "support_obstacles.py", "semantic_surface.py", "observed_space.py", "range_image.py",
"detection_obstacles.py", "route_observation.py", "arrival_approach.py", "pcl_ground.py") "detection_obstacles.py", "route_observation.py", "arrival_approach.py", "pcl_ground.py")
runtime = ("configuration.py", "nodes.py", "observed_collision.py", "ros_navigation.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/"nav2"/name for name in runtime]
files += [adapter_root/"navigation"/name for name in shared] 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")] 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.turn_started = self.turn_goal = self.turn_best_error = None
self.recovery = ObservedRecovery() self.recovery = ObservedRecovery()
self.last_recovery_attempt = None self.last_recovery_attempt = None
self.local_alignment = None
def heading_progress(self, pose, seconds): def heading_progress(self, pose, seconds):
"""Credit new best alignment within the existing bounded turn budget. """Credit new best alignment within the existing bounded turn budget.
@@ -90,7 +91,28 @@ class WaypointMission:
return True return True
return False 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): 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() return self.orientation_target()
def resume(self): def resume(self):
@@ -296,7 +296,7 @@ class RoutedMission(WaypointMission):
self.body_approach = (orientation["key"], tuple(goal[:2]), seconds) self.body_approach = (orientation["key"], tuple(goal[:2]), seconds)
def progress_orientation_target(self, 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: if self.body_approach is not None and orientation is not None:
key, goal, captured = self.body_approach key, goal, captured = self.body_approach
if key == orientation["key"] and 0 <= seconds - captured <= 0.8: if key == orientation["key"] and 0 <= seconds - captured <= 0.8:
+46
View File
@@ -218,3 +218,49 @@ def test_explicit_control_profile_is_used_by_command_adapter(module):
robot["control"]["chassis_speed_feedback"]["enabled"] = False robot["control"]["chassis_speed_feedback"]["enabled"] = False
control = module.RoverMotionControl(robot, 0.2) control = module.RoverMotionControl(robot, 0.2)
assert control.step(0.2, 0, 1 / 60, 0, 0) == pytest.approx((0.1 / 60, 0)) assert control.step(0.2, 0, 1 / 60, 0, 0) == pytest.approx((0.1 / 60, 0))
@pytest.mark.parametrize('side',[0,1])
def test_small_reversing_side_reaches_zero_while_other_side_accelerates(side):
limits=DriveLimits(.685,1.,.2,.4,.1)
drive=TwoSideDrive(limits)
initial=[-.0025,.193]
if side:
initial.reverse()
drive.applied=SideSpeeds(*initial)
value=drive.step(SideSpeeds(.331,.331),1/60)
actual=list(vars(value).values())
assert actual[side]==0.
assert actual[1-side]==pytest.approx(.193+.2/60)
next_value=list(vars(drive.step(SideSpeeds(.331,.331),1/60)).values())
assert 0.<next_value[side]<=.2/60+1e-12
@pytest.mark.parametrize('side',[0,1])
def test_reversing_side_brakes_within_its_own_bound_despite_other_target_changes(side):
drive=TwoSideDrive(DriveLimits(.685,1.,.2,.4,.1))
initial=[-.1,.2]
if side:
initial.reverse()
drive.applied=SideSpeeds(*initial)
for step in range(16):
target=[.3,.5 if step%2 else .8]
if side:
target.reverse()
prior=list(vars(drive.applied).values())
value=list(vars(drive.step(SideSpeeds(*target),1/60)).values())
assert value[side]>=prior[side]
assert max(abs(a-b) for a,b in zip(prior,value,strict=True))<=.4/60+1e-12
assert value[side]>=0.
@pytest.mark.parametrize('yaw',[.2854,-.2854])
def test_common_speed_feedback_cannot_amplify_yaw_when_a_side_is_near_zero(module,yaw):
feedback=module.ChassisSpeedFeedback(
{'proportional_gain':.75,'max_correction_mps':.15},.37,.685,1.)
v,w=feedback.step(.0952,yaw,.069,-.09)
assert w==pytest.approx(yaw)
before=SideSpeeds.from_twist(.0952,yaw,.685)
after=SideSpeeds.from_twist(v,w,.685)
for a,b in zip(vars(before).values(),vars(after).values(),strict=True):
assert a*b>=-1e-12
+19
View File
@@ -246,3 +246,22 @@ def test_native_backup_only_uses_straight_rear_destinations(selector,yaw,shift,s
assert selected is not None and selected.get('kind')!='orient' assert selected is not None and selected.get('kind')!='orient'
assert selected['reverse'] is reverse assert selected['reverse'] is reverse
assert any(np.array_equal(selected['goal'],p) for p in rear) assert any(np.array_equal(selected['goal'],p) for p in rear)
@pytest.mark.parametrize('yaw,shift',[(0,(0,0)),(73,(42,-17)),(-138,(-250,52))])
@pytest.mark.parametrize('side',[-1,1])
def test_uneven_range_horizon_does_not_pull_straight_intent_sideways(selector,yaw,shift,side):
_,pose,_,_,rotation=road(yaw,shift)
# The road is straight and wide. One side merely has farther measured
# returns; maximizing advance toward a far endpoint preferred its edge.
xy=np.array([[x,y] for x in np.arange(.4,3.51,.05)
for y in np.arange(-1.2,1.21,.05) if x<=3.1+.35*side*y])
points=np.c_[xy@rotation.T+shift,np.zeros(len(xy))]
selector.observe(np.c_[points,np.ones(len(points))],1,pose)
target=np.array(shift)+rotation@[675.,0.]
goal=selector.choose(points,pose,target,None,(),GEOMETRY,1)
local=(np.array(goal[:2])-shift)@rotation
assert local[0]>2.5 and abs(local[1])<.2
assert np.min(np.linalg.norm(points-goal,axis=1))<1e-9
# A local reference grants no synthetic ground or permission.
assert selector.choose(np.empty((0,3)),pose,target,goal,(),GEOMETRY,1) is None
+92
View File
@@ -0,0 +1,92 @@
"""Independent full-footprint oracle for conservative range-memory clearing."""
import importlib
import itertools
from pathlib import Path
import numpy as np
import pytest
@pytest.fixture
def range_images(monkeypatch):
monkeypatch.syspath_prepend(str(Path(__file__).parents[1] / "simulation/ai-polygon"))
return importlib.import_module("navigation.range_image").RangeImages
def full_footprint_oracle(images, points, voxel=0.06, margin=0.12):
"""Enumerate every corner and covered pixel, without a candidate prefilter."""
result = []
offsets = np.array(list(itertools.product((0, 1), repeat=3))) * voxel
for point in points:
cleared, offset = False, 0
for model, (w, h), origin, axes, p in zip(
images.models, images.sizes, images.origins, images.axes, images.parameters,
strict=True,
):
image = images.ranges[offset : offset + w * h].reshape(h, w)
offset += w * h
local = (np.floor(point / voxel) * voxel + offsets - origin) @ axes
distances = np.linalg.norm(local, axis=1)
if model == 0:
u = (np.degrees(np.arctan2(local[:, 1], local[:, 0])) - p[0]) / p[1]
u = u[0] + (u - u[0] + w / 2) % w - w / 2
elevation = np.degrees(np.arctan2(local[:, 2],
np.linalg.norm(local[:, :2], axis=1)))
v = (elevation - p[2]) / p[3]
else:
if np.any(local[:, 0] <= 1e-6):
continue
u = p[2] - p[0] * local[:, 1] / local[:, 0] - 0.5
v = p[3] - p[1] * local[:, 2] / local[:, 0] - 0.5
lu, lv = int(np.floor(u.min())), int(np.floor(v.min()))
hu, hv = int(np.ceil(u.max())), int(np.ceil(v.max()))
if (distances.min() <= margin or lv < 0 or hv >= h
or hu - lu > 8 or hv - lv > 8
or (model == 1 and (lu < 0 or hu >= w))):
continue
if all(image[y, x % w] > distances.max() + margin
for y in range(lv, hv + 1) for x in range(lu, hu + 1)):
cleared = True
result.append(cleared)
return np.array(result, dtype=bool)
@pytest.mark.parametrize("model", [0, 1])
@pytest.mark.parametrize("depth", ["open", "occluded", "discontinuities"])
def test_early_veto_matches_every_corner_and_pixel(range_images, model, depth):
rng = np.random.default_rng(20261008)
w, h = 80, 30
ranges = np.full((h, w), 8.0 if depth == "open" else 2.0)
if depth == "discontinuities":
ranges = rng.choice([0.0, 0.12, 1.5, 3.0, 8.0], (h, w))
angle = 0.47
rotation = np.array([[np.cos(angle), -np.sin(angle), 0],
[np.sin(angle), np.cos(angle), 0], [0, 0, 1]])
origin = np.array([12.11, -3.17, 0.91])
packet = dict(view_models=[model], view_sizes=[[w, h]], view_axes=[rotation],
view_parameters=[[-180, 360 / w, -40, 2.5] if model == 0
else [40, 40, w / 2, h / 2]],
view_ranges=ranges.ravel())
images = range_images([origin], packet)
local = np.vstack((rng.uniform([-5, -4, -3], [6, 4, 3], (400, 3)),
[[-2, 0, 0], [-2, -1e-10, 0], [-2, 1e-10, 0],
[0, 0, 0], [0.06, 0, 0], [2, 0, 0]]))
points = local @ rotation.T + origin
np.testing.assert_array_equal(images.cleared(points, 0.06, 0.12),
full_footprint_oracle(images, points))
def test_one_visible_corner_cannot_clear_a_voxel_with_hidden_corners(range_images):
packet = dict(view_models=[1], view_sizes=[[80, 30]], view_axes=[np.eye(3)],
view_parameters=[[40, 40, 40, 15]], view_ranges=np.full(2400, 8.0))
points = np.array([[2, 0, 0], [2, 0.06, 0.06], [2, -0.06, -0.06]])
images = range_images([[0, 0, 0]], packet)
assert images.cleared(points, 0.06, 0.12).all()
# Every individual unknown pixel must veto exactly the same full footprints.
for y, x in itertools.product(range(11, 18), range(36, 44)):
changed = {**packet, "view_ranges": packet["view_ranges"].copy()}
changed["view_ranges"][y * 80 + x] = 0
images = range_images([[0, 0, 0]], changed)
np.testing.assert_array_equal(images.cleared(points, 0.06, 0.12),
full_footprint_oracle(images, points))
+77
View File
@@ -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.))
+120
View File
@@ -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']