diff --git a/src/k1link/simulation/ai_polygon/route_feedback.py b/src/k1link/simulation/ai_polygon/route_feedback.py index 57c07ae1..687bf57a 100644 --- a/src/k1link/simulation/ai_polygon/route_feedback.py +++ b/src/k1link/simulation/ai_polygon/route_feedback.py @@ -137,3 +137,38 @@ class ObservedRouteBlockage: } self.pending = None return receipt + + +def blocked_route_piece(routing, segment, hazards, pose): + """Resolve simplified guidance back to its original graph components. + + RDP is presentation/direction compression. It must not turn a local + exclusion into closure of every source edge or a long return to the + beginning of the compressed chain. This returns intent metadata only. + """ + from k1link.simulation.ai_polygon.route_graph import projection + + nodes = {n['id']: n['xy'] for n in routing['map']['nodes']} + edges = {e['id']: e for e in routing['map']['edges']} + cursor = segment['start_xy'] + chain = [] + for identity in segment.get('edge_ids', [segment['edge_id']]): + edge = edges[identity] + if nodes[edge['start']] == cursor: + start, end = edge['start'], edge['end'] + elif edge['bidirectional'] and nodes[edge['end']] == cursor: + start, end = edge['end'], edge['start'] + else: + raise ValueError('Route components are not an oriented graph chain') + chain.append((edge, start, end)) + cursor = nodes[end] + def nearest(point): + return min(range(len(chain)), key=lambda i: (projection( + point, nodes[chain[i][1]], nodes[chain[i][2]])[1], -i)) + blocked = {nearest(point[:2]) for point in hazards} + # Rejoin at an original node on our side of the first blocked component. + # If the blockage is farther ahead, do not jump across unseen components + # to reach that node. Every actual approach still needs native admission. + index = min(nearest(pose[:2]), min(blocked)) + edge, anchor, _ = chain[index] + return edge, anchor, sorted(chain[i][0]['id'] for i in blocked) diff --git a/src/k1link/simulation/ai_polygon/route_mission.py b/src/k1link/simulation/ai_polygon/route_mission.py index 19bb5874..35ed3f1c 100644 --- a/src/k1link/simulation/ai_polygon/route_mission.py +++ b/src/k1link/simulation/ai_polygon/route_mission.py @@ -6,7 +6,7 @@ import math import numpy as np from k1link.simulation.ai_polygon.mission_policy import WaypointMission, inclination -from k1link.simulation.ai_polygon.route_feedback import ObservedRouteBlockage +from k1link.simulation.ai_polygon.route_feedback import ObservedRouteBlockage, blocked_route_piece from k1link.simulation.ai_polygon.route_graph import ( build_route, disc_permitted, @@ -75,20 +75,25 @@ class RoutedMission(WaypointMission): ) if receipt is None: return None - self.unavailable_edges.update(segment.get("edge_ids", [segment["edge_id"]])) + nodes = {n["id"]: n["xy"] for n in self.inputs["routing"]["map"]["nodes"]} + if segment.get("guidance_only") and not segment.get("return_to_anchor"): + edge, anchor, blocked_edges = blocked_route_piece( + self.inputs["routing"], segment, receipt["hazards_xyz"], pose) + else: + edge = next(e for e in self.inputs["routing"]["map"]["edges"] + if e["id"] == segment["edge_id"]) + anchor = edge["start"] if nodes[edge["start"]] == segment["start_xy"] else edge["end"] + blocked_edges = segment.get("edge_ids", [segment["edge_id"]]) + self.unavailable_edges.update(blocked_edges) event = { "schema_version": "missioncore.route-revision/v1", "revision": self.route_revision + 1, "previous_route_sha256": self.active_route["sha256"], "blockage": receipt, "unavailable_edges": sorted(self.unavailable_edges), + "anchor_node": anchor, "authority": "route-intent-only", } - edge = next( - e for e in self.inputs["routing"]["map"]["edges"] if e["id"] == segment["edge_id"] - ) - nodes = {n["id"]: n["xy"] for n in self.inputs["routing"]["map"]["nodes"]} - anchor = edge["start"] if nodes[edge["start"]] == segment["start_xy"] else edge["end"] failure = ( "route-reroute-budget" if self.route_revision >= 3 @@ -112,19 +117,23 @@ class RoutedMission(WaypointMission): self.route_failure, self.fault, self.state = failure, "stuck", "stuck" event.update(status="unreachable", failure=failure) else: - # Rejoin at the declared start of this edge; never teleport to a - # nearby branch. Only this prefix can use the excluded edge, in the - # opposite direction away from the measured obstacle. Its ground, - # full-body sweep and anchor arrival still require sensor admission. + # Rejoin a real graph node; never teleport to another branch. + # Simplified advisory segments retain their source edge identities: + # the nearby component owns this return, not the complete chord. + # Hard corridors keep their original enclosing return capsule. prefix = { **segment, - "start_xy": list(segment["end_xy"]), - "end_xy": list(segment["start_xy"]), + "start_xy": list(pose[:2]) if segment.get("guidance_only") else list(segment["end_xy"]), + "end_xy": list(nodes[anchor]), + "edge_id": edge["id"], + "edge_ids": [edge["id"]], "return_to_anchor": True, } leg = candidate["legs"][0] - leg["segments"].insert(0, prefix) - leg["length_m"] += math.dist(prefix["start_xy"], prefix["end_xy"]) + return_length = math.dist(prefix["start_xy"], prefix["end_xy"]) + if return_length > 1e-8: + leg["segments"].insert(0, prefix) + leg["length_m"] += return_length leg["start_xy"] = list(pose[:2]) candidate["legs"] = ( copy.deepcopy(self.active_route["legs"][: self.index]) + candidate["legs"] diff --git a/tests/test_prepared_urban_route.py b/tests/test_prepared_urban_route.py index 46cd15b4..c970ba82 100644 --- a/tests/test_prepared_urban_route.py +++ b/tests/test_prepared_urban_route.py @@ -224,3 +224,61 @@ def test_observed_detour_can_pass_advisory_joint_without_returning_to_line(condi assert result["authority"] == "adjacent-route-intent-only; not-mission-arrival" assert result["body"] == body assert mission.confirm_corridor_transition(pose, 10., body) is None + + +@pytest.mark.parametrize('direction', ['forward', 'reverse', 'at-node']) +def test_local_blockage_keeps_original_graph_edge_and_nearby_return_node(direction): + from k1link.simulation.ai_polygon.route_feedback import blocked_route_piece + *_, inputs, _ = fixture() + if direction == 'reverse': + inputs['routing'].update(start_node='3', goal_nodes=['0']) + inputs['mission']['route_xy'] = [[0., 0.]] + segment = build_route(inputs)['legs'][0]['segments'][0] + pose = [2.8, .2] if direction == 'reverse' else ([8., 0.] if direction == 'at-node' else [9.2, .2]) + hazard = [1.8, .1, 0.] if direction == 'reverse' else [10.2, .1, 0.] + edge, anchor, closed = blocked_route_piece(inputs['routing'], segment, [hazard], pose) + assert (edge['id'], anchor, closed) == (('0', '1', ['0']) if direction == 'reverse' else ('2', '2', ['2'])) + + +def test_compressed_advisory_reroute_uses_nearby_branch_without_closing_the_passed_chain(monkeypatch): + from k1link.simulation.ai_polygon.route_mission import RoutedMission + *_, inputs, _ = fixture() + graph = inputs['routing']['map'] + graph['nodes'].append(dict(id='6', xy=[8., 5.], z=0.)) + graph['edges'].extend([ + dict(id='6', start='2', end='6', half_width_m=1., bidirectional=True, cost_m=5.), + dict(id='7', start='6', end='5', half_width_m=1., bidirectional=True, cost_m=4.)]) + graph['sha256'] = digest({k:v for k,v in graph.items() if k!='sha256'}) + inputs.update(sensors={'schema_version':'missioncore.simulation-sensor-rig/v4'}, + behavior={'max_speed_mps':1.}) + mission = RoutedMission(inputs) + mission.route_observation([0.,0.,0.,0.,0.,0.,1.],0.) + pose = [9.2,.2,0.,0.,0.,0.,1.] + mission.route_observation(pose,10.) + mission.last_time, mission.last_pose = 10., tuple(pose) + receipt = dict(hazards_xyz=[[10.2,.1,0.],[10.2,.2,0.],[10.2,.3,0.]]) + monkeypatch.setattr(mission.blockage, 'observe', lambda *args: receipt) + original = copy.deepcopy(mission.global_route) + event = mission.observe_navigation({},np.empty((0,3)),pose,10.) + assert event['status'] == 'ready' and event['anchor_node'] == '2' + assert mission.unavailable_edges == {'2'} + segments = mission.leg['segments'] + assert segments[0]['start_xy'] == pose[:2] + assert segments[0]['end_xy'] == [8.,0.] and segments[0]['edge_ids'] == ['2'] + assert segments[0]['return_to_anchor'] is True + assert segments[1]['end_xy'] == [8.,5.] + assert math.dist(pose[:2], mission.arrival_target()) < 1.3 + assert mission.global_route == original # Preparation remains immutable. + assert mission.index == 0 and mission.segment_index == 0 + assert not mission.confirm_arrival(pose,10.,0,admitted=False) + + +def test_component_chain_cannot_reverse_a_one_way_edge(): + from k1link.simulation.ai_polygon.route_feedback import blocked_route_piece + *_, inputs, _ = fixture() + segment = build_route(inputs)['legs'][0]['segments'][0] + inputs['routing']['map']['edges'][1]['bidirectional'] = False + broken = {**segment,'start_xy':segment['end_xy'],'end_xy':segment['start_xy'], + 'edge_ids':list(reversed(segment['edge_ids']))} + with pytest.raises(ValueError,match='oriented graph chain'): + blocked_route_piece(inputs['routing'],broken,[[1.,0.,0.]],[3.,0.])