Restore observed recovery through native Nav2

This commit is contained in:
DCCONSTRUCTIONS
2026-10-08 11:11:12 +03:00
parent 117e937906
commit 140b6002e0
12 changed files with 1351 additions and 24 deletions
@@ -0,0 +1,74 @@
param(
[Parameter(Mandatory=$true)][ValidatePattern('^[a-f0-9]{16}$')][string]$Release,
[Parameter(Mandatory=$true)][ValidatePattern('^[a-f0-9]{16}$')][string]$ExpectedCurrentRelease,
[string]$EvidenceRoot,
[switch]$Apply
)
# Runtime-only update of an already installed service. Installation, firewall,
# principal, task settings, credentials and tunnel configuration are preserved.
$ErrorActionPreference='Stop'
$root='D:\NDC_MISSIONCORE\runtime\simulation'
$name='ndc-ai-polygon-worker'
if(Test-Path "$root\state\active.json") { throw 'Active episode prevents update' }
$task=Get-ScheduledTask -TaskName $name
if(@($task.Actions).Count -ne 1) { throw 'Expected one installed worker action' }
$old=$task.Actions[0]
$releaseMatches=[regex]::Matches($old.Arguments,'ai-polygon-([a-f0-9]{16})[\\/]+simulation[\\/]+ai-polygon[\\/]+realtime_worker\.py')
if($releaseMatches.Count -ne 1 -or $releaseMatches[0].Groups[1].Value -ne $ExpectedCurrentRelease) {
throw 'Installed worker identity changed'
}
$source="$root\releases\ai-polygon-$Release"
$manifestPath="$root\releases\ai-polygon-$Release.manifest.json"
$digest=(Get-FileHash $manifestPath -Algorithm SHA256).Hash.ToLower()
if(!$digest.StartsWith($Release)) { throw 'Manifest identity mismatch' }
$manifest=Get-Content $manifestPath -Raw | ConvertFrom-Json
$count=0
foreach($entry in $manifest.PSObject.Properties) {
$path=[IO.Path]::GetFullPath((Join-Path $source $entry.Name))
if(!$path.StartsWith($source+'\',[StringComparison]::OrdinalIgnoreCase) -or
(Get-FileHash $path -Algorithm SHA256).Hash.ToLower() -ne $entry.Value) {
throw "Source identity mismatch: $($entry.Name)"
}
$count++
}
if($count -eq 0) { throw 'Empty release' }
$arguments=$old.Arguments.Replace('ai-polygon-'+$ExpectedCurrentRelease,'ai-polygon-'+$Release)
if($EvidenceRoot) {
$EvidenceRoot=[IO.Path]::GetFullPath($EvidenceRoot)
if($EvidenceRoot -notmatch '^[A-Za-z]:\\' -or $EvidenceRoot -match '[&|<>^%!"\r\n]') {
throw 'Evidence storage must be an explicit local Windows directory'
}
if($arguments -match '--evidence-root') { throw 'Review existing evidence storage before replacing it' }
$arguments+=' --evidence-root "'+$EvidenceRoot+'"'
}
$action=New-ScheduledTaskAction -Execute $old.Execute -Argument $arguments -WorkingDirectory $old.WorkingDirectory
$report=[ordered]@{utc=[DateTime]::UtcNow.ToString('o'); task=$name; previous=$ExpectedCurrentRelease;
release=$Release; manifest_sha256=$digest; verified_files=$count; applied=$false;
network_changed=$false; credentials_changed=$false; principal_changed=$false}
if($EvidenceRoot) { $report['evidence_root']=$EvidenceRoot }
if($Apply) {
if($EvidenceRoot) { New-Item -ItemType Directory -Force -Path $EvidenceRoot | Out-Null }
$backup="$root\preparations\worker-activation-$Release"
New-Item -ItemType Directory -Path $backup -ErrorAction Stop | Out-Null
Export-ScheduledTask -TaskName $name | Set-Content -Encoding UTF8 "$backup\previous-task.xml"
$oldPattern="ai-polygon-$ExpectedCurrentRelease[\\/]+simulation[\\/]+ai-polygon[\\/]+realtime_worker\.py"
try {
Stop-ScheduledTask -TaskName $name
$deadline=[DateTime]::UtcNow.AddSeconds(10)
while(@(Get-CimInstance Win32_Process | Where-Object {$_.CommandLine -match $oldPattern}).Count) {
if([DateTime]::UtcNow -ge $deadline) { throw 'Old worker did not stop' }
Start-Sleep -Milliseconds 200
}
Set-ScheduledTask -TaskName $name -Action $action | Out-Null
Start-ScheduledTask -TaskName $name
$report.applied=$true
} catch {
Set-ScheduledTask -TaskName $name -Action $old | Out-Null
Start-ScheduledTask -TaskName $name
$report['error']=$_.Exception.Message
$report | ConvertTo-Json | Set-Content -Encoding UTF8 "$backup\activation.json"
throw
}
$report | ConvertTo-Json | Set-Content -Encoding UTF8 "$backup\activation.json"
}
$report | ConvertTo-Json
@@ -63,12 +63,13 @@ def main():
def controls():
try:
while running.is_set():
with condition:current=dict(state)
packet=dict(execution_inputs_sha256=inputs['sha256'],pose=original['pose'],
measured_twist=[0.,0.,0.],speed_mps=0.,pose_age_seconds=.01,
perception_age_seconds=0.,**current)
result=request('/control',packet)
responses.append(result)
with condition:
current=dict(state)
packet=dict(execution_inputs_sha256=inputs['sha256'],pose=current.pop('pose',original['pose']),
measured_twist=[0.,0.,0.],speed_mps=0.,pose_age_seconds=.01,
perception_age_seconds=0.,**current)
result=request('/control',packet)
responses.append(result)
time.sleep(.05)
except BaseException as error:errors.append(error)
@@ -183,6 +184,72 @@ def main():
restored=request('/plan',value)
assert restored['status']=='path' and restored['controller_goal'][0]=='path',restored
with condition:state['observation_id']=value['observation_id']
# A separate synthetic, stationary floor checks the actual BackUp ->
# rover-gate integration. It does not qualify motion on the city scene.
with condition:
state.update(enabled=False,pose=[0.,0.,.37,0.,0.,0.,1.])
assert request('/reset',{})['reset']
ready()
floor=[[i*.05,j*.05,0.] for i in range(-40,41) for j in range(-40,41)]
front=[p for p in floor if p[0]>.75]
retreat=copy.deepcopy(original)
retreat.update(pose=[0.,0.,.37,0.,0.,0.,1.],goal=[1.,0.,0.],
max_speed_mps=.1,allow_reverse=False,translation_allowed=True,
recovery_orientation=False,orientation_target=None,arrival_target=None,
detection_point_indices=[],unlocalized_rear_detection=False,
geometry_age_seconds=0.,detection_age_seconds=0.,semantic_points=[])
retreat['range_rays']=dict(origins=[[0.,0.,.37],[0.,0.,.37]],
ends=floor,origin_indices=[0]*len(floor))
retreat['semantic_observations']=[dict(frame_id='retreat-floor',age_seconds=0.,
samples=[[*p,1.] for p in floor])]
retreat['points']=floor
deadline=time.monotonic()+15
while True:
retreat['observation_id']='retreat-bootstrap'
result=request('/plan',retreat)
if result['status']=='path':break
assert time.monotonic()<deadline,result
time.sleep(.1)
# Warm the costmaps through normal planning before invoking a behavior;
# lifecycle activation alone does not publish their first observation.
assert result['controller_goal'][0]=='path',result
retreat.update(goal=[-1.,0.,0.],allow_reverse=True,observation_id='retreat-full-ground')
result=request('/plan',retreat)
assert result['status']=='path' and result['controller_goal'][0]=='backup',result
with condition:state.update(enabled=True,observation_id=retreat['observation_id'])
time.sleep(.15)
retreat['points']=front
retreat['range_rays'].update(ends=front,origin_indices=[0]*len(front))
retreat['semantic_observations']=[]
retreat['observation_id']='retreat-retained-ground'
result=request('/plan',retreat)
assert result['status']=='path',result
with condition:state['observation_id']=retreat['observation_id']
time.sleep(.2)
backward=responses[-1]
report['retained_ground_backup']=dict(plan=result,command=backward)
assert backward['reason']=='none' and -.1<=backward['speed_mps']<0.,backward
assert backward['support_policy']=='observed-static-ground-retreat',backward
# Fresh rear returns still veto a previously observed, clear floor.
obstacle=[[-.65,j*.05,.3] for j in range(-10,11)]
retreat['points']=front+obstacle
retreat['range_rays'].update(ends=front+obstacle,origin_indices=[0]*(len(front)+len(obstacle)))
retreat['observation_id']='retreat-new-rear-obstacle'
request('/plan',retreat)
with condition:state['observation_id']=retreat['observation_id']
time.sleep(.15)
report['new_rear_obstacle_zero']=responses[-1]
assert responses[-1]['speed_mps']==responses[-1]['yaw_rate_rps']==0.,responses[-1]
# Restore the archived fixture before the existing lease/fault checks.
with condition:
state.update(enabled=False,pose=original['pose'])
assert request('/reset',{})['reset']
ready()
deadline=time.monotonic()+15
while request('/plan',value)['status']!='path':
assert time.monotonic()<deadline,'Archived fixture did not restore'
time.sleep(.1)
with condition:state['observation_id']=value['observation_id']
with condition:state['enabled']=False
time.sleep(.1)
assert responses[-1]['speed_mps']==responses[-1]['yaw_rate_rps']==0.
@@ -168,6 +168,7 @@ class ContinuousControl:
speed, angular, support_scale, support = self.support.regulate(
speed, angular, terrain, pose, request["body_contact_height_m"],
current_points=points,
observed_retreat=bool(reverse and request.get("continuous")),
)
evidence = dict(support_policy=support["policy"]["reason"],
support_reasons=support["support_reasons"],
@@ -13,12 +13,51 @@ from .semantic_surface import SemanticSurface
class ObservedGoals:
def __init__(self):
def __init__(self, *, reverse_heading_tolerance=math.pi/4):
self.reverse_heading_tolerance = reverse_heading_tolerance
self.surface = SemanticSurface(retain_near=True)
self.measured = {}
self.evidence = None
def observe(self, samples, captured_at, pose):
self.surface.observe(samples, captured_at, pose)
sample = np.asarray(samples, dtype=float).reshape(-1, 4)
for key, point in zip(self.surface.cell_keys(sample), sample, strict=True):
self.measured[tuple(key)] = point[:3].copy()
# Same lifetime and classification owner as the semantic cells. Keep
# actual range returns, never invented voxel centres or hidden geometry.
self.measured = {key: point for key, point in self.measured.items()
if key in self.surface.cells
and self.surface.retained(key, self.surface.cells[key][1], captured_at)}
def boundary_cost(self, candidates, geometry, now):
"""Soft clearance preference, like an inflation potential in a costmap.
A far waypoint is an objective, not a straight-line corridor. Prefer
space away from observed exclusions before reaching their hard veto.
Actual rectangular body/swept support admission remains independent.
"""
barriers = np.array([point for key, point in self.measured.items()
if self.surface.cells.get(key, (1, 0))[0] == 0
and self.surface.retained(key, self.surface.cells[key][1], now)],
dtype=float).reshape(-1, 3)
cost = np.zeros(len(candidates))
if not len(barriers):
return cost
width = geometry['width_m']
# Ignore remote returns before pairwise work; each batch is bounded.
low, high = candidates[:,:2].min(0)-4*width, candidates[:,:2].max(0)+4*width
barriers = barriers[np.all((barriers[:,:2]>=low)&(barriers[:,:2]<=high),axis=1)]
if not len(barriers):
return cost
for start in range(0,len(candidates),128):
batch = candidates[start:start+128]
distance = np.linalg.norm(batch[:,None,:2]-barriers[None,:,:2],axis=2)
dz = barriers[None,:,2]-batch[:,None,2]
relevant = (dz>=-geometry.get('max_step_m', .1)) & (dz<=geometry.get('height_m',width))
nearest = np.min(np.where(relevant,distance,np.inf),axis=1)
cost[start:start+len(batch)] = 2*width*np.exp(-nearest/width)
return cost
def maneuver(self, points, pose, target, prior, excluded, geometry, now, candidate_mask=None):
"""Measured local destinations may temporarily move away from the task.
@@ -30,6 +69,11 @@ class ObservedGoals:
points = np.asarray(points, dtype=float).reshape(-1, 3)
if not len(points) or target is None:
return None
retained = np.array([point for point in self.measured.values()
if np.linalg.norm(point[:2]-np.asarray(pose[:2]))
<= 2*geometry['length_m']], dtype=float).reshape(-1, 3)
if len(retained):
points = np.concatenate((points, retained))
if prior is not None and prior.get("kind") == "orient":
# The viewing intent survives its source leaving the crop. Current
# range and full swept-body support still govern the actual pivot.
@@ -82,16 +126,40 @@ class ObservedGoals:
bearings = np.arctan2(delta[:, 1], delta[:, 0]) - yaw
errors = np.arctan2(np.sin(bearings), np.cos(bearings))
distance = np.linalg.norm(delta, axis=1)
# A short straight back-out is one option, alongside forward arcs and
# A measured retreat is one option, alongside forward arcs and
# stopped pivots. It is never an obligatory first recovery action.
reverse = (np.abs(errors) > math.pi-.12) & (distance <= .8)
# This is a destination proposal, not a swept-clearance certificate.
# Distance is already bounded by the same robot-sized local horizon.
# The blind strip may hide nearby floor; a farther observed rear goal
# must not become a forced 180-degree turn merely because it exceeds
# a separate short-retreat cutoff. Live sweeps still admit every tick.
reverse = np.abs(errors) > math.pi-self.reverse_heading_tolerance
turning = np.where(reverse, math.pi-np.abs(errors), np.abs(errors))
score = np.linalg.norm(candidates[:, :2]-target, axis=1) + .2*turning + .15*distance
score += self.boundary_cost(candidates, geometry, now)
# Recovery actions need a fair turn, as in Nav2's RoundRobin recovery
# subtree. Distance-to-task alone can spend every retry on almost the
# same forward approach before ever considering a measured retreat.
# Balance failed local directions; the rear sector uses reverse.
# Retain the existing geometric score within each family.
# This schedules intentions only, never certifies a body trajectory.
def family(relative):
return np.floor((relative + math.pi/4) / (math.pi/2)).astype(int) % 4
families = family(errors)
failures = np.zeros(4, dtype=int)
if excluded:
failed_delta = np.asarray(excluded)[:, :2] - xy
failed_distance = np.linalg.norm(failed_delta, axis=1)
failed_angle = np.arctan2(failed_delta[:, 1], failed_delta[:, 0])-yaw
failed_angle = np.arctan2(np.sin(failed_angle), np.cos(failed_angle))
nearby = failed_distance <= 2*geometry['length_m']
np.add.at(failures, family(failed_angle[nearby]), 1)
order = np.lexsort((score, failures[families]))
offsets = np.linspace(-geometry["width_m"]/2, geometry["width_m"]/2,
math.ceil(geometry["width_m"]/.1)+1)
# Search once per 20 cm observed cell, not every duplicate ray return.
tried = set()
for i in np.argsort(score, kind="stable"):
for i in order:
point = candidates[i]
key = tuple(self.surface.cell_keys(point[None])[0])
if key in tried:
@@ -116,7 +184,7 @@ class ObservedGoals:
# translation destination while still being worth inspecting with the
# front depth sensors. This grants ONLY an orientation intent. Neither
# the point nor the camera survey certifies the ground under a pivot.
for i in np.argsort(score, kind="stable"):
for i in order:
if abs(errors[i]) >= math.radians(30):
return dict(goal=candidates[i].tolist(), reverse=False, kind="orient")
return inspect_heading()
@@ -192,7 +260,11 @@ class ObservedGoals:
return before.tolist()
distance_to_target = np.linalg.norm(candidates[:, :2] - target, axis=1)
# The declared task, not the selected lens, owns the preferred direction.
score = distance_to_target + 2 * np.abs((candidates[:, :2] - pose[:2]) @ lateral)
x,y,z,w = pose[3:7]
heading = math.atan2(2*(w*z+x*y),1-2*(y*y+z*z))
bearing = np.arctan2(candidates[:,1]-pose[1],candidates[:,0]-pose[0])-heading
score = (distance_to_target + .2*np.abs(np.arctan2(np.sin(bearing),np.cos(bearing)))
+ self.boundary_cost(candidates, geometry, now))
for index in np.argsort(score, kind="stable"):
if supported(candidates[index]):
return candidates[index].tolist()
@@ -103,7 +103,8 @@ class SupportPolicy:
patches=patches,
)
def regulate(self, speed, yaw_rate, terrain, pose, contact_height_m, *, current_points):
def regulate(self, speed, yaw_rate, terrain, pose, contact_height_m, *, current_points,
observed_retreat=False):
m = self.monitor
requested = [speed, yaw_rate]
pivot_scale = 1.0
@@ -262,15 +263,18 @@ class SupportPolicy:
self.partial_yaw_rps / max(abs(yaw_rate), 1e-12),
)
reason = "partial-observation-limit"
if (scale == 0 and self.observed_approaches and speed > 0
if (scale == 0 and self.observed_approaches
and (speed > 0 or (speed < 0 and observed_retreat))
and support["status"] == "observed-supported"):
# The fixed distant track-end probes are context, not the
# commanded sweep. A curb beyond that sweep must not prevent
# stopping on the fully observed ground before it. This branch
# never fills unknown ground, admits reverse, or shrinks away
# never fills unknown ground or shrinks away
# a hazard inside the ORIGINAL command's full stopping bounds.
# It uses causal range memory through the normal map owner;
# current raw returns independently veto changed ground.
# Reverse requires an explicit recovery intent and the same
# completely observed stopping sweep, at the existing crawl cap.
current = np.asarray(current_points, dtype=float).reshape(-1, 3)
fresh = m.assess_command_support(
speed, yaw_rate,
@@ -285,9 +289,10 @@ class SupportPolicy:
elif fresh["unsafe_samples"]:
reason = "observed-unsafe-support"
else:
scale = min(1.0, self.partial_speed_mps / speed,
scale = min(1.0, self.partial_speed_mps / abs(speed),
self.partial_yaw_rps / max(abs(yaw_rate), 1e-12))
reason = "observed-static-ground-approach"
reason = ("observed-static-ground-approach" if speed > 0
else "observed-static-ground-retreat")
if scale == 0 and requested_support is not None:
support = requested_support
fresh_sweep = requested_fresh
+7 -2
View File
@@ -394,8 +394,12 @@ class ComposedInference:
self.source = source_for_rig(self.inputs["sensors"])
self.optics = None
self.task_view_intent = TaskViewIntent()
# Native Nav2 BackUp follows the current body axis. The legacy CMU
# controller also supports rear arcs; keep their intent limits distinct.
self.observed_goals = (
ObservedGoals() if self.inputs["sensors"]["schema_version"] in
ObservedGoals(reverse_heading_tolerance=(.12 if any(
n.module.module_id == "simulation-nav2-navigation" for n in self.graph.nodes
) else math.pi/4)) if self.inputs["sensors"]["schema_version"] in
{MOUNTED_SENSOR_SCHEMA, CONTINUOUS_SENSOR_SCHEMA} else None
)
if "mounts" in self.inputs["sensors"]:
@@ -523,7 +527,8 @@ class ComposedInference:
self.body_goal_waypoint = self.body_goal_phase_key = None
self.task_view_intent = TaskViewIntent()
if self.observed_goals is not None:
self.observed_goals = ObservedGoals()
self.observed_goals = ObservedGoals(
reverse_heading_tolerance=self.observed_goals.reverse_heading_tolerance)
self.mission.resume()
self.navigation.request("/reset", {})
deadline = time.monotonic() + 8
+200 -5
View File
@@ -42,6 +42,9 @@ def module(name):
"project": partial(result.project, source=source),
"visual_goal": partial(result.visual_goal, source=source, geometry=geometry),
"recovery_goal": partial(result.recovery_goal, geometry=geometry),
"corner_approach": partial(
result.corner_approach, source=source, geometry=geometry
),
}
)
if name == "navigation/terrain_costs":
@@ -56,6 +59,18 @@ def module(name):
return result
def test_local_route_receipt_is_bounded_and_binds_the_exact_observation():
receipt = module("navigation/route_observation").route_observation
terrain = np.array([[x, 0, 0, 1] for x in range(25)] + [[0.5, 0, 0, 0]])
pose = np.array([0, 0, 0.37, 0, 0, 0, 1])
value = {"simulation_time_seconds": 4, "execution_inputs_sha256": "a" * 64}
result = receipt(terrain, pose, value, 0.15)
assert len(result["near_obstacles"]) == 12
assert [p[0] for p in result["near_obstacles"]] == list(range(12))
assert result["observation"] == {"pose": pose.tolist(), **value}
assert receipt(np.array([[0, 0, 0, 0]]), pose, value, 0.15)["near_obstacles"] == []
def test_grouped_semantic_barriers_preserve_per_return_expiry_and_boundaries():
memory = module("navigation/semantic_surface").SemanticSurface()
samples = np.array([[0, 0, 0, 0], [-0.001, 0, 0, 1], [0.201, 0, 0, 1], [0.202, 0, 1, 0]])
@@ -67,7 +82,7 @@ def test_grouped_semantic_barriers_preserve_per_return_expiry_and_boundaries():
expected = terrain.copy()
blocked = []
for point in terrain:
cell = tuple(np.floor(point[:2] / 0.2).astype(int))
cell = tuple(memory.cell_keys(point[None])[0])
permission, observed = memory.cells.get(cell, (1, now))
blocked.append(permission == 0 and observed >= now - 30)
expected[blocked, 3] = np.maximum(expected[blocked, 3], 1)
@@ -76,6 +91,42 @@ def test_grouped_semantic_barriers_preserve_per_return_expiry_and_boundaries():
assert np.array_equal(original, terrain)
def test_semantic_snapshot_serializes_numpy_cells_without_refreshing_ttl():
import json
memory = module("navigation/semantic_surface").SemanticSurface()
memory.observe([[-1.01, 0.21, 0, 1]], 10)
assert json.loads(json.dumps(memory.snapshot(42))) == [[-6, 1, 0, 1, 32.0]]
terrain = np.array([[-1.01, 0.21, 0, 0]])
assert len(memory.permitted_terrain(terrain, 42)) == 0
@pytest.mark.parametrize('shift', [[0,0,0], [83.11,-24.03,2.17]])
def test_wall_labels_do_not_project_onto_observed_sidewalk_below(shift):
memory = module('navigation/semantic_surface').SemanticSurface(fuse_observations=True)
xyz = np.array([[1.01,.01,1.278], [1.01,.01,1.55], [1.01,.01,2.8]])+shift
terrain = np.c_[xyz, [0.,.3,1.5]]
# Many wall returns in the same XY column used to outvote the sidewalk.
samples = np.r_[np.c_[xyz[:1], [1.]], np.tile(np.c_[xyz[1:], [0.,0.]], (20,1))]
for frame in range(8):
memory.observe(samples, frame, evidence_id=str(frame))
output, count = memory.apply(terrain, 8)
assert output[:,3].tolist() == [0.,1.,1.5] and count == 2
np.testing.assert_array_equal(memory.permitted_terrain(terrain,8),terrain[:1])
# A new excluded measurement on that same floor still blocks it.
for frame in range(8,11):
memory.observe(np.c_[xyz[:1], [0.]], frame, evidence_id=str(frame))
assert memory.apply(terrain,11)[0][0,3] == 1
def test_allowed_upper_surface_cannot_permit_excluded_or_unseen_lower_floor():
memory = module('navigation/semantic_surface').SemanticSurface()
memory.observe([[1,0,1,1],[1,0,0,0]],0)
terrain=np.array([[1,0,1,0],[1,0,0,0],[1,0,-.5,0]],float)
assert memory.apply(terrain,0)[0][:,3].tolist() == [0,1,0]
assert memory.permitted_terrain(terrain,0).tolist() == [[1,0,1,0]]
def test_simulation_composition_has_causal_dependencies_and_separate_authority():
graph = compose(ROOT)
assert graph.as_dict()["execution"]["mode"] == "worker-local-simulation"
@@ -86,7 +137,7 @@ def test_simulation_composition_has_causal_dependencies_and_separate_authority()
assert motion.module.state_policy == "causal-reset-at-source-start"
selection = graph.selection_document()
selection["selections"] = [r for r in selection["selections"] if r["group"] != "segmentation"]
with pytest.raises(CompositionError, match="segmentation.labels"):
with pytest.raises(CompositionError, match="segmentation.known"):
compose(ROOT, selection)
@@ -165,6 +216,45 @@ def test_ground_placement_uses_actual_triangle_intersection():
assert len(terrain.ground_intersections(vertices, faces, 0.9, 0.9)) == 0
def test_local_goal_ranks_permitted_candidates_instead_of_rejecting_best_outside():
nav = module("navigation_client")
points = np.array(
[[x, y, 0] for x in np.linspace(1.5, 3.3, 40) for y in np.linspace(-0.3, 0.3, 9)]
)
pose = [0, 0, 0.37, 0, 0, 0, 1]
calibration = {
"origin": [0.38, 0, 0.8],
"rotation": np.eye(3).reshape(-1).tolist(),
"intrinsics": [800 * 24 / 36, 800 * 24 / 36, 400, 300],
}
surface = np.ones((512, 512), bool)
baseline = nav.visual_goal(surface, points, pose, calibration, target=[6, 0])
assert baseline[0] > 2.6
def allowed(candidates):
return candidates[:, 0] <= 2.6
selected = nav.visual_goal(
surface, points, pose, calibration, prior=baseline, target=[6, 0], candidate_mask=allowed
)
assert selected is not None and selected[0] <= 2.6
assert (
nav.visual_goal(
np.zeros_like(surface), points, pose, calibration, target=[6, 0], candidate_mask=allowed
)
is None
)
assert (
nav.visual_goal(
surface,
points,
pose,
calibration,
target=[6, 0],
candidate_mask=lambda candidates: np.zeros(len(candidates), bool),
)
is None
)
def test_observed_route_goal_keeps_task_position_and_cannot_run_away_from_it():
choose = module("navigation_client").visual_goal
points = np.array(
@@ -210,6 +300,42 @@ def test_observed_route_goal_keeps_task_position_and_cannot_run_away_from_it():
assert far is not None and 1.2 <= far[0] <= 3.1
def test_offset_arrival_goal_survives_blind_strip_with_stopping_reserve():
nav = module("navigation_client")
points = np.array(
[[x, y, 0] for x in np.arange(1.5, 3.1, 0.05) for y in np.arange(-0.3, 0.31, 0.05)]
)
pose = [0, 0, 0.37, 0, 0, 0, 1]
calibration = {
"origin": [0.62, 0, 0.8],
"rotation": np.eye(3).reshape(-1).tolist(),
"intrinsics": [800 * 24 / 36, 800 * 24 / 36, 400, 300],
}
surface = np.ones((512, 512), dtype=bool)
target = [0.8, 0]
# A measured local goal 27 cm beyond the corner still fits the 40 cm
# arrival disc, including the follower's 8 cm stopping tolerance.
prior = [1.07, 0, 0]
assert nav.visual_goal(surface, points, pose, calibration, prior, target) == prior
# Missing current road observations cannot be replaced by remembered intent.
assert nav.visual_goal(np.zeros_like(surface), points, pose, calibration, prior, target) is None
# A farther goal leaves too little stopping reserve and must not be retained.
assert nav.visual_goal(surface, points, pose, calibration, [1.13, 0, 0], target) is None
# A goal with a visible, explicitly forbidden side is rejected even if its
# other contact projections have entered the camera blind strip.
camera = {**calibration, "origin": [0.62, 0, 0.25]}
_, u, v, visible = nav.project(np.array([[1.07, -0.4525, 0], prior, [1.07, 0.4525, 0]]), camera)
assert visible.any() and not visible.all()
denied = surface.copy()
from k1link.simulation.ai_polygon.robots import select_robot
from k1link.simulation.ai_polygon.run_inputs import sensor_rig
from k1link.simulation.ai_polygon.source_projection import PinholeSource
source = PinholeSource(sensor_rig(select_robot("dcd006-v020"), 0.8))
denied[source.indices(u[visible], v[visible])] = False
assert nav.visual_goal(denied, points, pose, camera, prior, target) is None
def test_collision_identity_follows_geometry_and_tile_coverage_not_camera_or_start():
settings = dict(
meters_per_unit=1,
@@ -349,7 +475,7 @@ def test_underbody_support_does_not_clear_future_terrain_walls_or_drops():
terrain = np.array(
[
[-0.375, -0.28, 0.066, 0.103], # Low return already under the chassis.
[0.55, 0, 0.066, 0.103], # DCD-006 inset excludes the leading edge.
[0.55, 0, 0.066, 0.103], # Low return beneath the real leading edge.
[0.75, 0, 0.066, 0.103], # Never change future terrain from body pose.
[0, 0, 0.12, 0.12], # A real step within the footprint remains blocked.
[0, 0, 0.5, 0.5],
@@ -358,8 +484,8 @@ def test_underbody_support_does_not_clear_future_terrain_walls_or_drops():
)
original = terrain.copy()
result, count = correct(terrain, [0, 0, 0.37, 0, 0, 0, 1])
assert count == 1 and result[0, 3] == pytest.approx(0.066)
assert np.array_equal(result[1:], original[1:])
assert count == 2 and result[:2, 3] == pytest.approx([0.066, 0.066])
assert np.array_equal(result[2:], original[2:])
assert np.array_equal(terrain, original) # Never erase the causal raw map.
# Rotate both observations and the measured chassis; the result must agree.
yaw = np.pi / 2
@@ -561,3 +687,72 @@ def test_range_fan_rotation_preserves_both_mounts_and_first_hit_occlusion():
sensor.query = SimpleNamespace(raycast_closest=lambda *a, **k: {"hit": False})
assert len(sensor.capture([1, 0, 0.8], transform)) == 0
assert sensor.hit_paths == {}
def test_snapshot_patch_requires_exact_upstream_anchors():
patch = module("navigation/patch_snapshot").patch
source = "\n".join(
[
"bool clearingCloud = false;",
' nh->declare_parameter<double>("scanVoxelSize", scanVoxelSize);',
' nh->get_parameter("scanVoxelSize", scanVoxelSize);',
" // stack registered laser scans",
]
)
result = patch(source)
assert "bool inputIsMapSnapshot = false;" in result
assert result.index("terrainVoxelCloud[ind]->clear()") < result.index(
"// stack registered laser scans"
)
with pytest.raises(ValueError, match="already present"):
patch(result)
with pytest.raises(ValueError, match="anchor"):
patch(source.replace("bool clearingCloud = false;", ""))
def test_blind_corner_approach_uses_fresh_measured_direction_not_ground_permission():
nav = module("navigation_client")
points = np.array([[x, y, 0] for x in np.arange(1.5, 2.01, 0.05) for y in (-0.1, 0, 0.1)])
pose = [0, 0, 0.37, 0, 0, 0, 1]
calibration = {
"origin": [0.62, 0, 0.8],
"rotation": np.eye(3).reshape(-1).tolist(),
"intrinsics": [800 * 14 / 36, 800 * 14 / 36, 400, 300],
}
surface = np.ones((512, 512), dtype=bool)
original = points.copy()
result = nav.corner_approach(surface, points, pose, calibration, [0.8, 0])
assert result["goal"] == [0.8, 0, 0] and result["max_speed_mps"] == 0.1
assert any(np.array_equal(point, result["observed_direction_point"]) for point in points)
assert np.array_equal(points, original) and result["authority"].startswith(
"declared-corner-intent-only"
)
# The front-mounted camera may already be past the target while the body
# centre still approaches it. Current forward observations remain required.
assert nav.corner_approach(surface, points, pose, calibration, [0.45, 0]) is not None
for target in (None, [-0.8, 0], [0, 0.8], [1.3, 0], [0.4, 0]):
assert nav.corner_approach(surface, points, pose, calibration, target) is None
assert nav.corner_approach(surface, points[:2], pose, calibration, [0.8, 0]) is None
assert nav.corner_approach(np.zeros_like(surface), points, pose, calibration, [0.8, 0]) is None
assert nav.corner_approach(surface, points + [0, 1, 0], pose, calibration, [0.8, 0]) is None
# A currently visible corner uses ordinary semantic/range admission. This
# fallback cannot replace a visible rejection with an inferred road label.
assert (
nav.corner_approach(surface, points, pose, {**calibration, "origin": [0, 0, 0.1]}, [0.8, 0])
is None
)
def test_mounted_semantics_retains_occluded_near_ground_and_barriers_until_observed_again():
memory = module("navigation/semantic_surface").SemanticSurface(retain_near=True)
pose = [0, 0, 0.37, 0, 0, 0, 1]
memory.observe([[0, 0, 0, 1], [1, 0, 0, 0], [8, 0, 0, 1]], 0, pose)
terrain = np.array([[0, 0, 0, 0], [1, 0, 0, 0], [8, 0, 0, 0]], float)
assert len(memory.permitted_terrain(terrain, 60)) == 1
assert memory.apply(terrain, 60)[0][1, 3] == 1
assert memory.cells[(0, 0, 0)][1] == 0 # Retention never rewrites capture time.
memory.observe([[0, 0, 0, 0], [1, 0, 0, 1]], 61, pose)
assert memory.apply(terrain, 61)[0][0, 3] == 1
assert memory.permitted_terrain(terrain, 61)[0, 0] == 1
memory.observe([], 100, [10, 0, 0.37, 0, 0, 0, 1])
assert len(memory.permitted_terrain(terrain, 100)) == 0
+248
View File
@@ -0,0 +1,248 @@
import importlib
import math
from pathlib import Path
import numpy as np
import pytest
@pytest.fixture
def selector(monkeypatch):
monkeypatch.syspath_prepend(str(Path(__file__).parents[1] / 'simulation/ai-polygon'))
return importlib.import_module('navigation.observed_goals').ObservedGoals()
def road(yaw=0, shift=(0, 0)):
a = math.radians(yaw)
rotation = np.array([[math.cos(a), -math.sin(a)], [math.sin(a), math.cos(a)]])
xy = np.array([[x, y] for x in np.arange(.4, 3.51, .08) for y in np.arange(-1.1, 1.11, .08)])
points = np.column_stack((xy @ rotation.T + shift, np.zeros(len(xy))))
pose = [*shift, .37, 0, 0, math.sin(a / 2), math.cos(a / 2)]
target = np.array(shift) + rotation @ [8, 0]
return points, pose, target, xy[:, 1], rotation
GEOMETRY = dict(width_m=.905, body_contact_height_m=.37, max_slope_degrees=25)
@pytest.mark.parametrize('yaw,shift', [(0, (0, 0)), (73, (42, -17)), (-138, (-250, 52))])
def test_surveyed_maneuver_can_leave_greedy_route_without_leaving_permitted_ground(selector, yaw, shift):
_, pose, target, _, rotation = road(yaw, shift)
# Only a wide side passage behind the current task-distance contour exists.
xy = np.array([[x, y] for x in np.arange(-1.1, .01, .07)
for y in np.arange(.7, 2.1, .07)])
points = np.column_stack((xy@rotation.T+shift, np.zeros(len(xy))))
geometry = {**GEOMETRY, 'length_m': 1.163, 'max_step_m': .1}
assert selector.maneuver(points, pose, target, None, (), geometry, 0)['kind'] == 'orient'
selector.observe(np.column_stack((points, np.ones(len(points)))), 1, pose)
assert selector.choose(points, pose, target, None, (), geometry, 1) is None
selected = selector.maneuver(points, pose, target, None, (), geometry, 1)
assert selected is not None and not selected['reverse']
assert math.dist(selected['goal'][:2], target) > math.dist(pose[:2], target)
assert selector.maneuver(points, pose, target, selected, (), geometry, 1) == selected
# A real new prohibition revokes even a latched recovery destination.
selector.observe(np.column_stack((points, np.zeros(len(points)))), 2, pose)
assert selector.maneuver(points, pose, target, selected, (), geometry, 2) is None
def test_recovery_respects_route_corridor_and_missing_bottom(selector):
points, pose, target, _, _ = road()
geometry = {**GEOMETRY, 'length_m': 1.163, 'max_step_m': .1}
selector.observe(np.column_stack((points, np.ones(len(points)))), 0, pose)
assert selector.maneuver(points, pose, target, None, (), geometry, 0,
lambda p: np.zeros(len(p), bool))['kind'] == 'orient'
# Old positive labels cannot create ground returns at an unobserved bottom.
assert selector.maneuver(np.empty((0, 3)), pose, target, None, (), geometry, 0) is None
def test_narrow_visible_sector_can_request_a_pivot_but_not_translation(selector):
pose = [0, 0, .37, 0, 0, 0, 1]
points = np.array([[x, y, 0] for x in np.arange(-.1, .11, .05)
for y in np.arange(.8, 1.21, .05)])
geometry = {**GEOMETRY, 'length_m': 1.163, 'max_step_m': .1}
selector.observe(np.column_stack((points, np.ones(len(points)))), 1, pose)
selected = selector.maneuver(points, pose, [10, 0], None, (), geometry, 1)
assert selected['kind'] == 'orient' and selected['reverse'] is False
@pytest.mark.parametrize('yaw,shift', [(0, (0, 0)), (73, (42, -17)), (-138, (-250, 52))])
def test_alternating_lenses_cannot_move_a_measured_goal_between_sides(selector, yaw, shift):
points, pose, target, side, rotation = road(yaw, shift)
for time, sign in [(0, 1), (.3, -1)]:
subset = points[side * sign >= -.05]
selector.observe(np.column_stack((subset, np.ones(len(subset)))), time, pose)
goal = selector.choose(points, pose, target, None, (), GEOMETRY, .4)
assert goal is not None
assert abs(((np.array(goal[:2]) - pose[:2]) @ rotation)[1]) < .13
for time, sign in [(.6, 1), (.9, -1), (1.2, 1)]:
subset = points[side * sign >= -.05]
selector.observe(np.column_stack((subset, np.ones(len(subset)))), time, pose)
assert selector.choose(points, pose, target, goal, (), GEOMETRY, time) == goal
assert selector.evidence['oldest_surface_age_seconds'] > 0
def test_no_geometry_or_unknown_surface_never_creates_a_goal(selector):
points, pose, target, _, _ = road()
assert selector.choose(points, pose, target, None, (), GEOMETRY, 0) is None
selector.observe(np.column_stack((points, np.ones(len(points)))), 0, pose)
assert selector.choose(np.empty((0, 3)), pose, target, None, (), GEOMETRY, .1) is None
assert selector.choose(points + [0, 0, 4], pose, target, None, (), GEOMETRY, .1) is None
def test_new_prohibition_revokes_goal_and_cannot_be_refreshed_by_read(selector):
points, pose, target, _, _ = road()
selector.observe(np.column_stack((points, np.ones(len(points)))), 0, pose)
goal = selector.choose(points, pose, target, None, (), GEOMETRY, 1)
assert goal is not None
blocked = points[np.linalg.norm(points[:, :2] - goal[:2], axis=1) < .5]
selector.observe(np.column_stack((blocked, np.zeros(len(blocked)))), 1, pose)
assert selector.choose(points, pose, target, goal, (), GEOMETRY, 2) != goal
stamps = list(selector.surface.cells.values())
selector.choose(points, pose, target, None, (), GEOMETRY, 3)
assert list(selector.surface.cells.values()) == stamps
selector.surface.position = np.array([100, 100])
assert selector.choose(points, pose, target, goal, (), GEOMETRY, 40) is None
def test_current_range_corridor_and_exclusions_revoke_retained_goal(selector):
points, pose, target, _, _ = road()
selector.observe(np.column_stack((points, np.ones(len(points)))), 0, pose)
goal = selector.choose(points, pose, target, None, (), GEOMETRY, .1)
allowed = lambda values: values[:, 0] < goal[0] - .5
result = selector.choose(points, pose, target, goal, (), GEOMETRY, .2, allowed)
assert result is not None and allowed(np.array([result]))[0]
assert selector.choose(points, pose, target, goal, [goal], GEOMETRY, .2) != goal
absent = points[np.linalg.norm(points - goal, axis=1) > .5]
assert selector.choose(absent, pose, target, goal, (), GEOMETRY, .2) != goal
def test_chassis_width_is_enforced_across_accumulated_views(selector):
points, pose, target, side, _ = road()
strip = points[abs(side) < .15]
selector.observe(np.column_stack((strip, np.ones(len(strip)))), 0, pose)
assert selector.choose(points, pose, target, None, (), GEOMETRY, .1) is None
@pytest.mark.parametrize('yaw,shift', [(0,(0,0)),(73,(42,-17))])
def test_cross_slope_uses_measured_height_across_the_corridor(selector,yaw,shift):
points,pose,target,side,_=road(yaw,shift)
points[:,2]=side*.2
selector.observe(np.c_[points,np.ones(len(points))],0,pose)
# A different surface directly above the path must not poison its labels.
upper=points+[0,0,.7]
selector.observe(np.c_[upper,np.zeros(len(upper))],.1,pose)
goal=selector.choose(points,pose,target,None,(),GEOMETRY,.2)
assert goal is not None and np.min(np.linalg.norm(points-goal,axis=1))<1e-9
assert selector.choose(upper,pose,target,None,(),GEOMETRY,.2) is None
def test_recovery_can_select_measured_retreat_after_ground_leaves_current_view(selector):
points, pose, target, _, _ = road()
rear = np.array([[x,y,0.] for x in (-.75,-.65) for y in np.arange(-.6,.61,.05)])
geometry = {**GEOMETRY,'length_m':1.163,'max_step_m':.1}
selector.observe(np.c_[rear,np.ones(len(rear))],1,pose)
selected = selector.maneuver(points,pose,target,None,(),geometry,2)
assert selected['reverse'] and selected.get('kind') != 'orient'
assert any(np.array_equal(selected['goal'],p) for p in rear)
assert selector.maneuver(points,pose,target,selected,(),geometry,2) == selected
# A new exclusion revokes the retained intention, not just its live sweep.
selector.observe(np.c_[rear,np.zeros(len(rear))],3,pose)
assert selector.maneuver(points,pose,target,selected,(),geometry,3) is None
@pytest.mark.parametrize('yaw,shift', [(0,(0,0)), (73,(42,-17)), (-138,(-250,52))])
def test_rear_destination_beyond_near_blind_strip_keeps_reverse_intent(selector,yaw,shift):
points,pose,target,_,rotation = road(yaw,shift)
rear = np.array([[x,y,0.] for x in np.arange(-2.1,-1.19,.07)
for y in np.arange(-.8,.81,.07)])
rear[:,:2] = rear[:,:2]@rotation.T+shift
geometry = {**GEOMETRY,'length_m':1.163,'max_step_m':.1}
selector.observe(np.c_[rear,np.ones(len(rear))],1,pose)
selected = selector.maneuver(points,pose,target,None,(),geometry,2)
assert selected['reverse'] and selected.get('kind') != 'orient'
assert .8 < math.dist(selected['goal'][:2],pose[:2]) <= 2*geometry['length_m']
assert np.min(np.linalg.norm(rear-selected['goal'],axis=1)) < 1e-9
# Observed destination intent retains both corridor and permission vetoes.
assert selector.maneuver(points,pose,target,selected,(),geometry,2,
lambda p: np.zeros(len(p),bool)) is None
selector.observe(np.c_[rear,np.zeros(len(rear))],3,pose)
assert selector.maneuver(points,pose,target,selected,(),geometry,3) is None
@pytest.mark.parametrize('angle,shift',[(0,(0,0)),(73,(42,-17)),(-138,(-250,52))])
def test_far_goal_does_not_pull_local_intent_to_the_corridor_edge(selector,angle,shift):
points,pose,target,_,rotation = road(angle,shift)
border = np.array([[x,y,0] for x in np.arange(.4,3.6,.08) for y in (-1.18,1.18)])
border[:,:2] = border[:,:2]@rotation.T+shift
selector.observe(np.r_[np.c_[points,np.ones(len(points))],np.c_[border,np.zeros(len(border))]],1,pose)
# The endpoint is far to the right of the currently observed corridor.
target = np.array(shift)+rotation@[8,-5]
chosen = selector.choose(points,pose,target,None,(),GEOMETRY,1)
assert chosen is not None
local = (np.array(chosen[:2])-shift)@rotation
assert abs(local[1]) < .45
# Permission still owns admission: the preference creates no destination
# when the corridor itself is excluded.
selector.observe(np.c_[points,np.zeros(len(points))],2,pose)
assert selector.choose(points,pose,target,None,(),GEOMETRY,2) is None
@pytest.mark.parametrize('yaw,shift',[(0,(0,0)),(73,(42,-17)),(-138,(-250,52))])
def test_measured_rear_arc_is_translation_intent_not_a_forced_body_spin(selector,yaw,shift):
points,pose,target,_,rotation = road(yaw,shift)
rear = np.array([[x,y,0.] for x in np.arange(-1.2,-.29,.05)
for y in np.arange(-.8,.81,.05)])
rear[:,:2] = rear[:,:2]@rotation.T+shift
destination = np.array(shift)+rotation@[-.65,.25]
geometry = {**GEOMETRY,'length_m':1.163,'max_step_m':.1}
selector.observe(np.c_[rear,np.ones(len(rear))],1,pose)
selected = selector.maneuver(np.r_[points,rear],pose,target,None,(),geometry,2,
lambda p: np.linalg.norm(p[:,:2]-destination,axis=1)<.04)
assert selected['reverse'] and selected.get('kind') != 'orient'
assert math.dist(selected['goal'][:2],pose[:2]) <= .8
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))])
def test_failed_forward_options_cannot_starve_other_observed_manoeuvres(selector,yaw,shift):
_,pose,target,_,rotation = road(yaw,shift)
xy = np.array([[x,y] for x in np.arange(-2.8,2.81,.08)
for y in np.arange(-2.8,2.81,.08)])
points = np.c_[xy@rotation.T+shift,np.zeros(len(xy))]
geometry = {**GEOMETRY,'length_m':1.163,'max_step_m':.1}
selector.observe(np.c_[points,np.ones(len(points))],1,pose)
excluded=[]; selected=[]
# The live controller may reject every proposed forward/side manoeuvre.
# A clear, observed reverse exit must still get a turn within this cycle,
# independently of map translation/rotation and the far task direction.
for _ in range(5):
candidate=selector.maneuver(points,pose,target,None,excluded,geometry,1)
assert candidate is not None and candidate.get('kind') != 'orient'
selected.append(candidate)
if candidate['reverse']:
break
excluded.append(candidate['goal'])
assert selected[-1]['reverse']
assert len(selected) <= 4
for candidate in selected:
assert np.min(np.linalg.norm(points-candidate['goal'],axis=1)) < 1e-9
@pytest.mark.parametrize('yaw,shift', [(0,(0,0)), (73,(42,-17)), (-138,(-250,52))])
@pytest.mark.parametrize('side,reverse', [(0.,True), (.5,False)])
def test_native_backup_only_uses_straight_rear_destinations(selector,yaw,shift,side,reverse):
# Nav2 BackUp follows the body axis; the retained CMU selector may use rear
# arcs. Keep that capability distinction after recovering measured memory.
selector.reverse_heading_tolerance=.12
front,pose,target,_,rotation=road(yaw,shift)
rear=np.array([[x,y,0.] for x in np.arange(-2.,-.8,.05)
for y in np.arange(-1.,1.01,.05)])
rear[:,:2]=rear[:,:2]@rotation.T+shift
destination=np.array(shift)+rotation@[-1.5,side]
selector.observe(np.c_[rear,np.ones(len(rear))],1,pose)
selected=selector.maneuver(np.r_[front,rear],pose,target,None,(),
{**GEOMETRY,'length_m':1.163,'max_step_m':.1},2,
lambda p: np.linalg.norm(p[:,:2]-destination,axis=1)<.04)
assert selected is not None and selected.get('kind')!='orient'
assert selected['reverse'] is reverse
assert any(np.array_equal(selected['goal'],p) for p in rear)
+300
View File
@@ -0,0 +1,300 @@
"""Support response, without turning missing ground into a safety certificate."""
import importlib
import math
from pathlib import Path
import numpy as np
import pytest
from k1link.simulation.ai_polygon.robots import select_robot
from k1link.simulation.ai_polygon.run_inputs import robot_geometry
POSE = [0, 0, 0.37, 0, 0, 0, 1]
@pytest.fixture
def policy(monkeypatch):
monkeypatch.syspath_prepend(str(Path(__file__).parents[1] / "simulation/ai-polygon"))
monitor = importlib.import_module("navigation.footprint").Footprint(
robot_geometry(select_robot("dcd006-v020"))
)
return importlib.import_module("navigation.support_policy").SupportPolicy(monitor)
@pytest.fixture
def terrain():
return np.array(
[[x, y, 0, 0] for x in np.arange(-2, 2.01, 0.05) for y in np.arange(-2, 2.01, 0.05)]
)
def test_clear_observed_motion_and_explicit_hold(policy, terrain):
v, w, scale, audit = policy.regulate(0.2, 0, terrain, POSE, 0.37, current_points=terrain[:, :3])
assert (v, w, scale) == (0.2, 0, 1)
assert audit["admitted"] and audit["enforced"]
assert audit["policy"]["reason"] == "observed-support"
v, w, scale, audit = policy.regulate(0, 0, [], POSE, 0.37, current_points=[])
assert (v, w, scale) == (0, 0, 1)
assert audit["policy"]["reason"] == "hold"
@pytest.mark.parametrize("reverse", [False, True])
def test_one_track_drop_vetoes_both_motors_without_shrinking_hazard_away(policy, terrain, reverse):
terrain[(terrain[:, 0] > 0.6) & (terrain[:, 1] > 0.12), 2] = -0.4
if reverse:
terrain[:, 0] *= -1
v, w, scale, audit = policy.regulate(
-0.3 if reverse else 0.3, 0, terrain, POSE, 0.37, current_points=terrain[:, :3]
)
assert (v, w, scale) == (0, 0, 0)
assert audit["policy"]["reason"] == "observed-unsafe-support"
assert audit["unsafe_samples"] > 0 and not audit["admitted"]
@pytest.mark.parametrize("command", [(0.2, 0.25), (0, 0.8), (-0.2, -0.25)])
def test_partial_ground_reduces_same_arc_without_relabeling_unknown(policy, terrain, command):
# Fresh remote patches provide context. The swept margin is still unseen.
context = terrain[np.abs(terrain[:, 0]) > 0.75]
v, w, scale, audit = policy.regulate(
*command, context, POSE, 0.37, current_points=context[:, :3]
)
assert 0 < scale < 1
assert v == pytest.approx(command[0] * scale) and w == pytest.approx(command[1] * scale)
assert abs(v) <= 0.1 and abs(w) <= 0.15
assert audit["unknown_samples"] > 0 and not audit["admitted"]
assert audit["policy"]["reason"] == "partial-observation-limit"
@pytest.mark.parametrize("fresh", ["empty", "walls", "one-track", "front-only"])
def test_memory_cannot_mask_lost_ground_view_or_missing_turn_side(policy, terrain, fresh):
current = terrain[:, :3].copy()
if fresh == "empty":
current = []
elif fresh == "walls":
current[:, 2] = 1.5
elif fresh == "one-track":
current = current[current[:, 1] < 0]
else:
current = current[current[:, 0] > 0]
# A pivot requires rear evidence on the left and front on the right.
v, w, scale, audit = policy.regulate(0, 0.3, terrain, POSE, 0.37, current_points=current)
assert (v, w, scale) == (0, 0, 0)
assert audit["policy"]["reason"] == (
"observed-unsafe-support" if fresh == "walls" else "insufficient-fresh-ground"
)
def test_observation_restore_releases_stop_and_inputs_remain_immutable(policy, terrain):
before = terrain.copy()
assert policy.regulate(0.2, 0, terrain, POSE, 0.37, current_points=[])[2] == 0
assert policy.regulate(0.2, 0, terrain, POSE, 0.37, current_points=terrain[:, :3])[2] == 1
assert np.array_equal(terrain, before)
with pytest.raises(ValueError, match="Invalid support observation"):
policy.regulate(0.2, 0, terrain, POSE, 0.37, current_points=[[0, 0, float("nan")]])
@pytest.mark.parametrize("rate", [0.1, 0.15])
def test_mounted_pivot_requires_full_measured_sweep_and_retains_other_vetoes(policy, terrain, rate):
policy.observed_pivots = True
front = terrain[terrain[:, 0] > 0.75, :3]
# A distant unseen rear patch is outside the fully measured pivot sweep.
v, w, scale, audit = policy.regulate(0, rate, terrain, POSE, 0.37, current_points=front)
assert (v, w, scale) == (0, rate, 1)
assert audit["admitted"] and audit["policy"]["reason"] == "observed-static-ground-pivot"
# No extrapolation into an unmeasured part of that same sweep.
incomplete = terrain[terrain[:, 0] > 0]
assert policy.regulate(0, rate, incomplete, POSE, 0.37, current_points=front)[2] == 0
assert policy.regulate(0, rate, terrain, POSE, 0.37, current_points=[])[2] == 0
assert policy.regulate(-0.1, 0, terrain, POSE, 0.37, current_points=front)[2] == 0
assert policy.regulate(0, 0.3, terrain, POSE, 0.37, current_points=front)[2] == 0
unsafe = terrain.copy()
unsafe[(unsafe[:, 0] < -0.5) & (unsafe[:, 1] > 0.15), 2] = -0.4
assert policy.regulate(0, rate, unsafe, POSE, 0.37, current_points=front)[2] == 0
def test_pivot_slows_for_unknown_sweep_and_retains_near_hazard_veto(policy, terrain):
policy.observed_pivots = True
narrow = terrain[np.abs(terrain[:, 1]) <= 0.600001]
front = terrain[terrain[:, 0] > 0.75, :3]
v, w, scale, audit = policy.regulate(0, 0.15, narrow, POSE, 0.37, current_points=front)
# The retained profile has unknown support in the requested stopping sweep.
# Only the independently checked slower sweep can retain motion authority.
assert (v, w) == (0, 0.1) and scale == pytest.approx(2 / 3)
assert audit['requested_pivot_support']['unknown_samples'] > 0
assert audit["admitted"] and audit["unknown_samples"] == 0
assert audit["policy"]["requested_command"] == [0, 0.15]
assert audit["bounds"] == policy.monitor.command_bounds(v, w)
# A nearby measured drop intersects even the slower sweep and still vetoes.
hazard = terrain.copy()
hazard[(hazard[:, 1] > .55) & (hazard[:, 0] < -.3), 2] = -.4
assert policy.regulate(0,.15,hazard,POSE,.37,current_points=front)[2]==0
# A fresh raised obstacle intersects only the faster uncertain stop envelope.
# It remains a physical obstacle while the independently checked slow pivot
# is allowed; repeated ticks still have to stop before reaching it.
fresh = np.vstack((terrain[:,:3], [.4,.6,.3]))
v,w,scale,audit = policy.regulate(0,.15,terrain,POSE,.37,current_points=fresh)
assert (v,w)==(0,.1) and scale==pytest.approx(2/3)
assert audit['admitted'] and audit['fresh_sweep']['body_clear']
fresh[-1,1]=.5
assert policy.regulate(0,.15,terrain,POSE,.37,current_points=fresh)[2]==0
def test_observed_short_approach_can_stop_before_distant_unsafe_context(policy, terrain):
policy.observed_approaches = True
distant = terrain[:, :3].copy()
distant[(distant[:, 0] > .9) & (distant[:, 1] > .12), 2] = -.4
remembered = np.c_[distant, np.zeros(len(distant))]
# A supported short stop does not reach the distant left-track drop.
v, w, scale, audit = policy.regulate(.04, 0, remembered, POSE, .37,
current_points=distant)
assert (v, w, scale) == (.04, 0, 1)
assert audit['admitted']
assert audit['policy']['reason'] == 'observed-static-ground-approach'
assert audit['policy']['fresh_context']['patches'][0]['observed_unsafe'] > 0
# The requested high-speed sweep is unsafe. A separately assessed slower
# stop may end before the SAME drop; the measured hazard is never erased.
before = remembered.copy()
v, w, scale, audit = policy.regulate(.3, 0, remembered, POSE, .37, current_points=distant)
assert 0 < v <= .1 and w == 0 and 0 < scale < 1
assert audit["admitted"] and audit["requested_support"]["unsafe_samples"] > 0
assert policy.monitor.assess_command_support(v, w, remembered, POSE, .37)["admitted"]
np.testing.assert_array_equal(remembered, before)
# A newly seen near drop revokes remembered support before map rebuilding.
near = distant.copy()
near[near[:, 1] > .45, 2] = -.4 # Newly entered lateral margin of the left track.
assert policy.regulate(.04, 0, remembered, POSE, .37, current_points=near)[2] == 0
# No memory shortcut into unknown ground, reverse, or loss of sensor data.
assert policy.regulate(.04, 0, [], POSE, .37, current_points=distant)[2] == 0
assert policy.regulate(.04, 0, remembered, POSE, .37, current_points=[])[2] == 0
front = distant[distant[:, 0] > .75]
assert policy.regulate(-.04, 0, remembered, POSE, .37, current_points=front)[2] == 0
@pytest.mark.parametrize('heading,offset', [(0, [0, 0]), (1.2, [81, -23]), (-2.4, [-210, 47])])
def test_observed_approach_has_no_map_frame_or_world_position_dependency(policy, terrain, heading, offset):
policy.observed_approaches = True
terrain[(terrain[:, 0] > .9) & (terrain[:, 1] > .12), 2] = -.4
axes = np.array([[math.cos(heading), -math.sin(heading)],
[math.sin(heading), math.cos(heading)]])
terrain[:, :2] = terrain[:, :2] @ axes.T + offset
pose = [*offset, .37, 0, 0, math.sin(heading/2), math.cos(heading/2)]
v, w, scale, audit = policy.regulate(.04, 0, terrain, pose, .37,
current_points=terrain[:, :3])
assert (v, w, scale) == (.04, 0, 1)
assert audit['policy']['reason'] == 'observed-static-ground-approach'
v, w, scale, audit = policy.regulate(.3, 0, terrain, pose, .37, current_points=terrain[:, :3])
assert 0 < v <= .1 and w == 0 and 0 < scale < 1
assert audit["admitted"] and audit["requested_support"]["unsafe_samples"] > 0
assert policy.monitor.assess_command_support(v, w, terrain, pose, .37)["admitted"]
@pytest.mark.parametrize("heading,offset", [(0, [0, 0]), (1.1, [45, -81])])
def test_speed_uses_fully_observed_stopping_distance_instead_of_fixed_creep(policy, heading, offset):
terrain = np.array([[x, y, 0, 0] for x in np.arange(-1.5, 2.01, .05)
for y in np.arange(-1.5, 1.51, .05)])
axes = np.array([[math.cos(heading), -math.sin(heading)],
[math.sin(heading), math.cos(heading)]])
terrain[:, :2] = terrain[:, :2] @ axes.T + offset
pose = [*offset, .37, 0, 0, math.sin(heading/2), math.cos(heading/2)]
v, w, scale, audit = policy.regulate(.8, 0, terrain, pose, .37, current_points=terrain[:, :3])
assert .4 < v < .8 and w == 0 and 0 < scale < 1
assert audit["admitted"] and audit["unsafe_samples"] == audit["unknown_samples"] == 0
assert audit["requested_support"]["unknown_samples"] > 0
assert audit["policy"]["reason"] == "observed-support-speed-limit"
assert policy.monitor.assess_command_support(v, w, terrain, pose, .37)["admitted"]
# The higher proposal cannot pass by reducing only its reported number.
assert not policy.monitor.assess_command_support(.8, 0, terrain, pose, .37)["admitted"]
@pytest.mark.parametrize('heading,offset', [(0, [0, 0]), (1.1, [45, -81])])
def test_distant_hazard_does_not_deadlock_partial_observation_crawl(policy, heading, offset):
# The near under-body strip is occluded; both fresh track-end patches exist.
# A drop is visible further along the fast stopping horizon.
terrain = np.array([[x, y, -.4 if x > 1.7 else 0, 0]
for x in np.arange(.78, 4.01, .05)
for y in np.arange(-1.5, 1.51, .05)])
axes = np.array([[math.cos(heading), -math.sin(heading)],
[math.sin(heading), math.cos(heading)]])
terrain[:, :2] = terrain[:, :2] @ axes.T + offset
pose = [*offset, .37, 0, 0, math.sin(heading/2), math.cos(heading/2)]
before = terrain.copy()
v, w, scale, audit = policy.regulate(1, 0, terrain, pose, .37, current_points=terrain[:, :3])
assert (v, w) == (.1, 0) and scale == pytest.approx(.1)
assert audit['unknown_samples'] > 0 and not audit['admitted']
assert audit['unsafe_samples'] == 0 and audit['requested_support']['unsafe_samples'] > 0
assert audit['policy']['reason'] == 'partial-observation-limit'
assert policy.regulate(1, 0, terrain, pose, .37, current_points=[])[2] == 0
# Move the rover towards the SAME observed drop: the short stopping sweep
# now reaches it, so both tracks must stop even with fresh ground visible.
closer = pose.copy();closer[:2] = np.array(offset) + np.array([1.15,0]) @ axes.T
assert policy.regulate(1, 0, terrain, closer, .37, current_points=terrain[:, :3])[2] == 0
np.testing.assert_array_equal(terrain,before)
@pytest.mark.parametrize("heading,offset", [(0, [0, 0]), (1.1, [45, -81])])
def test_speed_search_rechecks_fresh_drop_before_map_has_changed(policy, terrain, heading, offset):
policy.observed_approaches = True
fresh = terrain[:, :3].copy()
fresh[(fresh[:, 0] > .9) & (fresh[:, 1] > .12), 2] = -.4
axes = np.array([[math.cos(heading), -math.sin(heading)],
[math.sin(heading), math.cos(heading)]])
terrain[:, :2] = terrain[:, :2] @ axes.T + offset
fresh[:, :2] = fresh[:, :2] @ axes.T + offset
pose = [*offset, .37, 0, 0, math.sin(heading/2), math.cos(heading/2)]
before = terrain.copy()
v, w, scale, audit = policy.regulate(1, 0, terrain, pose, .37, current_points=fresh)
assert 0 < v <= .1 and w == 0 and 0 < scale < 1
assert audit["admitted"] and audit["fresh_sweep"]["unsafe_samples"] == 0
# The map has not acquired the drop; the current range veto owns it.
np.testing.assert_array_equal(terrain, before)
near = fresh.copy()
local = (near[:, :2] - offset) @ axes
near[local[:, 1] > .45, 2] = -.4
assert policy.regulate(1, 0, terrain, pose, .37, current_points=near)[2] == 0
def test_raised_wall_is_body_obstacle_not_neighbouring_track_ground(policy, terrain):
points = np.vstack((terrain[:, :3], [.5, policy.monitor.half_width + .06, .3]))
v, w, scale, audit = policy.regulate(.2, 0, terrain, POSE, .37, current_points=points)
assert (v, w, scale) == (.2, 0, 1)
assert audit["fresh_sweep"]["body_clear"]
# Move that SAME raised return into the body. Retained flat ground cannot
# excuse the new physical obstruction, including during a pivot.
points[-1, 1] = 0
assert policy.regulate(.2, 0, terrain, POSE, .37, current_points=points)[2] == 0
assert policy.regulate(0, .1, terrain, POSE, .37, current_points=points)[2] == 0
@pytest.mark.parametrize('heading,offset', [(0,[0,0]),(1.2,[23,-19])])
def test_support_search_keeps_shorter_observed_stop_below_partial_speed(policy, heading, offset):
policy.observed_approaches = True
terrain = np.array([[x,y,0.,0.] for x in np.arange(-2,2.01,.03)
for y in np.arange(-1,1.01,.03)])
terrain[(terrain[:,0]>.51)&(terrain[:,1]>.12),2] = -.4
axes = np.array([[math.cos(heading),-math.sin(heading)],
[math.sin(heading),math.cos(heading)]])
terrain[:,:2] = terrain[:,:2] @ axes.T + offset
pose = np.array([*offset,.37,0,0,math.sin(heading/2),math.cos(heading/2)])
before = terrain.copy()
v,w,scale,audit = policy.regulate(.1,0,terrain,pose,.37,current_points=terrain[:,:3])
assert .02 <= v < .1 and w == 0 and scale > 0
assert audit['admitted'] and audit['unsafe_samples'] == 0
assert audit['requested_support']['unsafe_samples'] > 0
# The hazard remains. A later pose entering it cannot inherit permission.
pose[:2] += np.array([.2,0]) @ axes.T
assert policy.regulate(.1,0,terrain,pose,.37,current_points=terrain[:,:3])[2] == 0
np.testing.assert_array_equal(terrain,before)
def test_explicit_recovery_retreat_requires_complete_retained_ground_and_live_veto(policy, terrain):
policy.observed_approaches = True
front = terrain[terrain[:,0] > .75, :3]
v,w,s,d = policy.regulate(-.1,0,terrain,POSE,.37,current_points=front,observed_retreat=True)
assert (v,w,s) == (-.1,0,1)
assert d['admitted'] and d['policy']['reason'] == 'observed-static-ground-retreat'
# Unknown rear, stale/lost range and new measured holes retain their veto.
unknown = terrain[terrain[:,0] > -.35]
assert policy.regulate(-.1,0,unknown,POSE,.37,current_points=front,observed_retreat=True)[2] == 0
assert policy.regulate(-.1,0,terrain,POSE,.37,current_points=[],observed_retreat=True)[2] == 0
current = terrain[:,:3].copy()
current[(current[:,0] < -.6) & (current[:,1] > .12),2] = -.4
assert policy.regulate(-.1,0,terrain,POSE,.37,current_points=current,observed_retreat=True)[2] == 0
+99
View File
@@ -0,0 +1,99 @@
"""Nav2 commands keep geometric vetoes without former proposal fallbacks."""
import importlib
from pathlib import Path
import numpy as np
import pytest
@pytest.fixture
def admission(monkeypatch):
monkeypatch.syspath_prepend(str(Path(__file__).parents[1]/'simulation/ai-polygon'))
control = importlib.import_module('navigation.continuous_control')
footprint = importlib.import_module('navigation.footprint')
policy = importlib.import_module('navigation.support_policy')
geometry = dict(length_m=1., width_m=.6, max_step_m=.1, max_slope_degrees=25.)
monitor = footprint.Footprint(geometry)
now, command = [10.], [.08, 0.]
gate = control.ContinuousControl(monitor, policy.SupportPolicy(monitor),
lambda _: None, lambda *_: None, lambda: (now[0], *command), clock=lambda: now[0],
native_only=True, body_top_m=1.)
points = np.array([[x,y,0.] for x in np.arange(-2,2.01,.075)
for y in np.arange(-2,2.01,.075)])
terrain = np.column_stack((points, np.zeros(len(points))))
pose = [0.,0.,.37,0.,0.,0.,1.]
request = dict(geometry_age_seconds=0., points=points, pose=pose, observation_id='sample-1',
body_contact_height_m=.37, max_speed_mps=.1)
result = dict(status='path', speed_mps=.1, yaw_rate_rps=.04, path=[[0.,0.,0.],[1.,0.,0.]],
diagnostic={'terminal_approach':True})
gate.observe(request); gate.accept(request, result, terrain)
tick = dict(pose=pose, pose_age_seconds=0., perception_age_seconds=0., enabled=True,
observation_id='sample-1', speed_mps=0.)
return gate, now, command, tick
def test_native_zero_cannot_use_previous_terminal_override(admission):
gate, _, command, tick = admission
assert gate.tick(tick)['speed_mps'] > 0
command[:] = [0., 0.]
result = gate.tick(tick)
assert result['speed_mps'] == result['yaw_rate_rps'] == 0.
assert result['command_source'] == 'nav2'
def test_native_command_still_stops_for_new_obstacle(admission):
gate, _, _, tick = admission
gate.observe(dict(geometry_age_seconds=0., range_sequence=[1,2],
points=np.vstack((gate.geometry[1], [[.525,0.,.5]]))))
result = gate.tick(tick)
assert result['speed_mps'] == result['yaw_rate_rps'] == 0.
assert result['reason'] == 'obstacle'
def test_native_command_still_loses_range_lease(admission):
gate, now, _, tick = admission
now[0] += .801
result = gate.tick(tick)
assert result['speed_mps'] == result['yaw_rate_rps'] == 0.
assert result['reason'] == 'stale-range'
@pytest.mark.parametrize('condition', ['clear','unknown-rear','lost-range','drop','obstacle','no-recovery'])
def test_native_backup_requires_retained_support_and_live_hazard_veto(admission,condition):
gate, _, command, tick = admission
gate.support.observed_approaches=True
record=gate.plans['sample-1']
floor=record['terrain'].copy()
current=floor[floor[:,0]>.75,:3]
if condition=='unknown-rear':floor=floor[floor[:,0]>-.2]
elif condition=='lost-range':current=np.empty((0,3))
elif condition=='drop':
rear=record['terrain'][record['terrain'][:,0]<-.45,:3].copy()
rear[:,2]=-.4
current=np.r_[current,rear]
elif condition=='obstacle':current=np.r_[current,[[-.525,0.,.5]]]
request={**record['value'],'points':current,'allow_reverse':True,
'continuous':condition!='no-recovery'}
gate.observe(request)
gate.accept(request,record['result'],floor)
command[:]=[-.1,0.]
result=gate.tick(tick)
if condition=='clear':
assert result['speed_mps']==-.1 and result['yaw_rate_rps']==0.
assert result['support_policy']=='observed-static-ground-retreat'
else:
assert result['speed_mps']==result['yaw_rate_rps']==0.,result
def test_refined_detection_subset_is_shared_with_control_without_removing_raw_range(admission):
gate, _, _, tick = admission
record=gate.plans['sample-1']
request={**record['value'],'detection_point_indices':[0,1]}
gate.accept(request,record['result'],record['terrain'],detections=request['points'][[1]])
np.testing.assert_array_equal(gate.plans['sample-1']['detections'],request['points'][[1]])
assert len(gate.geometry[1])==len(request['points'])
with pytest.raises(ValueError,match='original associated range'):
gate.accept(request,record['result'],record['terrain'],detections=[[99,99,99]])
gate.observe(dict(geometry_age_seconds=0.,range_sequence=[1,2],
points=np.vstack((gate.geometry[1],[[.525,0.,.5]]))))
assert gate.tick(tick)['reason']=='obstacle'
+196
View File
@@ -0,0 +1,196 @@
import math
import pytest
from k1link.simulation.ai_polygon.mission_policy import WaypointMission
from k1link.simulation.ai_polygon.observed_recovery import ObservedRecovery
def pose(x=0, y=0, yaw=0):
return [x, y, .37, 0, 0, math.sin(yaw/2), math.cos(yaw/2)]
def survey(recovery, position, choose, start=0):
recovery.tick(position, start, choose)
recovery.tick(position, start+.2, choose)
for index, sector in enumerate(recovery.sectors):
now = start+.4+index*.2
request = recovery.view_request(position, now)
assert request["yaw_degrees"] == sector
recovery.observe_view(request, position, now)
goal, state = recovery.tick(position, now, choose)
assert goal is None
return now
@pytest.mark.parametrize("destination,reverse", [([0, 1.5, 0], False),
([0, -1.5, 0], False),
([-.65, 0, 0], True)])
def test_survey_precedes_any_manoeuvre_and_is_not_a_body_turn(destination, reverse):
r = ObservedRecovery()
r.begin(pose(), 0, [])
selected = dict(goal=destination, reverse=reverse)
calls = []
def choose(prior, excluded):
calls.append(prior)
return selected
assert r.tick(pose(), 0, choose)[0] is None
assert not calls and r.orientation() is None
now = survey(r, pose(), choose, .2)
request = r.view_request(pose(), now+.2)
assert request is not None
assert r.tick(pose(), now+.2, choose)[0] is None
r.observe_view(request, pose(), now+.2)
assert r.tick(pose(), now+.3, choose) == (
destination, "reversing" if reverse else "manoeuvring")
if not reverse:
assert r.orientation()["xy"] == destination[:2]
# No old camera result can keep authorising this sector indefinitely.
assert r.tick(pose(), now+2.5, choose)[0] is None
def test_old_request_and_pre_request_capture_cannot_acknowledge_survey():
r = ObservedRecovery()
r.begin(pose(), 0, [])
r.tick(pose(), 0, lambda *_: None)
r.tick(pose(), .2, lambda *_: None)
first = r.view_request(pose(), .2)
r.observe_view(first, pose(), .1)
assert not r.views
r.begin(pose(), 1, [])
r.tick(pose(), 1, lambda *_: None)
r.tick(pose(), 1.2, lambda *_: None)
second = r.view_request(pose(), 1.2)
assert first != second
r.observe_view(first, pose(), 1.2)
assert not r.views
def test_blocked_manoeuvre_is_retired_before_trying_another_direction():
r = ObservedRecovery()
r.begin(pose(), 0, [])
first = dict(goal=[0, 1.5, 0], reverse=False)
choose = lambda prior, excluded: first if not excluded else dict(goal=[0, -1.5, 0], reverse=False)
now = survey(r, pose(), choose)
r.observe_view(r.view_request(pose(), now+.1), pose(), now+.1)
r.tick(pose(), now+.2, choose)
assert r.tick(pose(), now+9, choose)[0] is None
assert r.excluded == [first["goal"]]
r.tick(pose(), now+9.2, choose)
assert r.selected["goal"] == [0, -1.5, 0]
def test_survey_does_not_assume_rear_ground_or_create_a_destination():
r = ObservedRecovery()
r.begin(pose(), 0, [])
survey(r, pose(), lambda *_: None)
assert not r.active and r.selected is None
def test_orientation_only_recovery_never_creates_a_translation_goal():
r = ObservedRecovery()
r.begin(pose(), 0, [])
choose = lambda *_: dict(goal=[0, 2, 0], reverse=False, kind="orient")
now = survey(r, pose(), choose)
r.observe_view(r.view_request(pose(), now+.1), pose(), now+.1)
assert r.tick(pose(), now+.2, choose) == (None, 'orienting')
assert r.orientation()['xy'] == [0, 2]
# Rotation alone completes this observation manoeuvre, with zero travel.
assert r.tick(pose(yaw=math.pi/2), now+4, choose) == (None, 'replanning')
assert not r.active
def test_progressing_turn_is_not_abandoned_at_an_absolute_duration_limit():
r = ObservedRecovery()
r.begin(pose(), 0, [])
selected = dict(goal=[0, 2, 0], reverse=False, kind='orient')
choose = lambda *_: selected
start = survey(r, pose(), choose)
option = r.option
for step in range(1, 146):
now, position = start+step, pose(yaw=.01*step)
r.observe_view(r.view_request(position, now), position, now)
assert r.tick(position, now, choose) == (None, 'orienting')
assert r.active and r.option == option and not r.excluded
assert r.tick(pose(yaw=math.pi/2), start+146, choose) == (None, 'replanning')
assert not r.active
def test_recovery_distance_and_rotation_do_not_replenish_task_progress():
mission = WaypointMission([[10, 0]])
normal = lambda *_: [2, 0, 0]
maneuver = lambda *_: dict(goal=[0, 1.5, 0], reverse=False)
mission.update(pose(), 0, normal, choose_maneuver=maneuver)
assert mission.update(pose(), 8, normal, choose_maneuver=maneuver)[1]["state"] == "surveying"
survey(mission.recovery, pose(), maneuver, 8)
mission.recovery.observe_view(mission.recovery.view_request(pose(), 10), pose(), 10)
goal, intent = mission.update(pose(), 10.1, normal, choose_maneuver=maneuver)
assert goal == [0, 1.5, 0] and intent["state"] == "manoeuvring"
mission.update(pose(0, 1.4, math.pi/2), 13, normal, choose_maneuver=maneuver)
assert not mission.recovery.active and mission.attempts == 1
mission.update(pose(), 14, normal, choose_maneuver=maneuver)
assert mission.attempts == 1 and mission.best_distance == 10
def test_completed_recovery_invalidates_old_alignment_and_preserves_retry_budget(monkeypatch):
import importlib
from pathlib import Path
monkeypatch.syspath_prepend(str(Path(__file__).parents[1]/'simulation/ai-polygon'))
approach = importlib.import_module('navigation.arrival_approach').ArrivalApproach()
mission = WaypointMission([[10, 0]])
normal = lambda *_: [2, 0, 0]
mission.update(pose(), 0, normal)
target = mission.orientation_target()
assert approach.command(pose(), target, 0, .2, 0, enabled=True)[2]['phase'] == 'local-path'
assert approach.completed
mission.recovery.begin(pose(), 8, [])
mission.attempts = 1
mission.recovery.phase = 'executing'
mission.recovery.selected = dict(goal=[-2, 0, 0], reverse=False, kind='orient')
# The physical manoeuvre finishes facing backward, farther from the task.
position = pose(-1, yaw=math.pi)
mission.update(position, 100, normal, choose_maneuver=lambda prior, _: prior)
assert not mission.recovery.active
new_target = mission.orientation_target()
assert new_target['xy'] == target['xy'] and new_target['key'] != target['key']
assert mission.turn_started is None
assert approach.command(position, new_target, 100, .2, 0, enabled=True)[2]['phase'] == 'braking'
v, w, evidence = approach.command(position, new_target, 100.2, .2, 0, enabled=True)
assert v == 0 and abs(w) > 0 and evidence['phase'] == 'aligning'
# Re-alignment alone must not credit retreat as route progress.
mission.heading_progress(position, 100)
mission.heading_progress(pose(-1), 120)
assert mission.attempts == 1 and mission.best_distance == 10 and mission.index == 0
@pytest.mark.parametrize('failure', ['footprint', 'no-path'])
def test_repeated_fresh_body_veto_retires_option_without_waiting_progress_timeout(failure):
r = ObservedRecovery(); p = pose(); r.begin(p,0,[])
selected = dict(goal=[0,1.5,0],reverse=False)
choose = lambda *_: selected
now = survey(r,p,choose)
r.observe_view(r.view_request(p,now+.1),p,now+.1)
r.tick(p,now+.2,choose)
key = (r.sequence,r.option)
def reply(t,failure=failure):
return dict(status='blocked',speed_mps=0,yaw_rate_rps=0,
diagnostic=dict(failure=failure),route_observation=dict(observation=dict(
pose=p,simulation_time_seconds=t,execution_inputs_sha256='run')))
# Wrong option, stale receipts, and missing observations cannot reject it.
r.observe_navigation(reply(now+.2),p,now+.2,(0,0),'run')
r.observe_navigation(reply(now+.2),p,now+.8,key,'run')
r.observe_navigation(reply(now+.8),p,now+.8,key,'different-run')
assert r.blockage is None
r.observe_navigation(reply(now+.8),p,now+.8,key,'run')
r.observe_navigation(reply(now+1),p,now+1,key,'run')
assert not r.blocked_option
# Planner/data waiting breaks confirmation; it is not an obstacle.
r.observe_navigation(reply(now+1.1,'stale-range'),p,now+1.1,key,'run')
assert r.blockage is None
r.observe_navigation(reply(now+1.2),p,now+1.2,key,'run')
r.observe_navigation(reply(now+1.8),p,now+1.8,key,'run')
assert r.blocked_option
assert r.tick(p,now+1.9,choose) == (None,'surveying')
assert r.excluded == [selected['goal']]
r.tick(p,now+2,choose)
assert not r.blocked_option and r.blockage is None
@@ -0,0 +1,65 @@
"""Native planner vetoes must reach the already existing recovery policy."""
import importlib
from pathlib import Path
from types import SimpleNamespace
import numpy as np
from k1link.simulation.ai_polygon.mission_policy import WaypointMission
from test_observed_recovery import pose, survey
def test_navigation_delivers_current_option_veto_and_stale_data_does_not_retire_it(monkeypatch):
monkeypatch.syspath_prepend(str(Path(__file__).parents[1]/'simulation/ai-polygon'))
module=importlib.import_module('navigation_client')
model=object.__new__(module.ComposedInference)
model.mission=WaypointMission([[10,0]])
r=model.mission.recovery;p=pose();r.begin(p,0,[])
selected=dict(goal=[2,0,0],reverse=False)
choose=lambda *_:selected
now=survey(r,p,choose)
r.observe_view(r.view_request(p,now+.1),p,now+.1)
r.tick(p,now+.2,choose)
model.goal=selected['goal']
model.body_goal_waypoint=model.body_goal_phase_key=None
model.geometry=dict(length_m=1.163,width_m=.905)
model.inputs=dict(sha256='run',behavior=dict(max_speed_mps=1.))
model.environment='urban'
model.max_speed=1.
model.source=SimpleNamespace(indices=lambda u,v:(np.zeros(len(u),int),np.zeros(len(v),int)),
semantic_visible=lambda points,calibration:np.ones(len(points),bool))
monkeypatch.setattr(module,'project',lambda points,*args:(points,np.zeros(len(points)),
np.zeros(len(points)),np.ones(len(points),bool)))
failure=['no-path']
def response(path,request):
assert path=='/plan'
return dict(status='blocked',path=[],speed_mps=0.,yaw_rate_rps=0.,
diagnostic=dict(failure=failure[0]),route_observation=dict(observation=dict(
pose=list(request['pose']),simulation_time_seconds=request['simulation_time_seconds'],
execution_inputs_sha256=request['execution_inputs_sha256'])))
model.navigation=SimpleNamespace(request=response)
surface=np.ones((512,512),bool)
inputs={'navigation.surface':surface,'navigation.permissions':surface,'navigation.semantic-known':surface,
'detection.boxes':[],'source.lidar':np.array([[1+i*.01,0,0] for i in range(60)]),
'source.pose':p,'source.camera.calibration':dict(body_contact_height_m=.37),
'navigation.intent':model.mission.intent('manoeuvring'),'source.range-rays':{},
'source.semantic-observation':[],'source.range-captured-at':module.time.monotonic(),
'source.observation-id':'sample'}
for seconds,reason in [(now+.3,'no-path'),(now+.7,'stale-range'),(now+.8,'no-path')]:
failure[0]=reason;inputs['source.simulation-time']=seconds
assert model.navigate(inputs)['motion.command']['speed_mps']==0
assert not r.blocked_option
inputs['source.simulation-time']=now+1.4
model.navigate(inputs)
assert r.blocked_option
assert r.tick(p,now+1.5,choose)==(None,'surveying')
assert r.excluded==[selected['goal']] and model.mission.route==[[10,0]]
# A normal first navigation transaction precedes begin(): its recovery
# identity must exist without requiring a prior recovery manoeuvre.
model.mission=WaypointMission([[10,0]])
inputs['navigation.intent']=model.mission.intent('following')
inputs['source.simulation-time']=0.
assert model.navigate(inputs)['motion.command']['speed_mps']==0
assert not model.mission.recovery.active
assert model.mission.recovery.sequence==model.mission.recovery.option==0