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
+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