From 8c520ba32e4f770fce69ee36c87b32afd7693900 Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Fri, 9 Oct 2026 07:48:20 +0300 Subject: [PATCH] Bound urban route clearance preference and expose Nav2 costmap diagnostics --- docs/AI_POLYGON_ROUTE_PLANNING.md | 17 +++++++++++++ simulation/ai-polygon/nav2/ros_navigation.py | 26 ++++++++++++++++++++ simulation/ai-polygon/nav2/server.py | 9 +++++-- simulation/ai-polygon/scene_route_field.py | 20 +++++++++++---- tests/test_scene_route_field.py | 24 ++++++++++++++++++ 5 files changed, 89 insertions(+), 7 deletions(-) diff --git a/docs/AI_POLYGON_ROUTE_PLANNING.md b/docs/AI_POLYGON_ROUTE_PLANNING.md index 31990d94..3c24b10e 100644 --- a/docs/AI_POLYGON_ROUTE_PLANNING.md +++ b/docs/AI_POLYGON_ROUTE_PLANNING.md @@ -93,6 +93,12 @@ SOG-кэш используется редактором и локальным глобальной гипотезы; открытые разрывы не соединяются. Это не распознавание автомобилей: небольшой постоянный объект тоже может попасть в такую область. Сенсоры обязаны независимо подтвердить опору и свободный объём при движении. +Стоимость графа предпочитает достаточный зазор: штраф действует только ниже +половины наибольшего размера корпуса плюс одна ячейка подготовки (0,5 м). +Более широкая поверхность после этой границы не получает дополнительного +преимущества. Прежняя обратная зависимость от ширины притягивала линию +от тротуара к середине улицы; это геометрическое смещение устранено, но +семантическая пешеходная карта от этого не появляется. Геометрический источник не знает правил движения, тротуаров, переходов или временного характера каждого объекта. Его центральная линия улицы не является пешеходной картой и не доказывает пригодность полного городского маршрута. @@ -129,3 +135,14 @@ decimation, обрезки SH и повторного квантования з Полный граф может содержать ветви вне этой визуальной области. Дальний перемаршрут за её пределы ещё требует пространственной подгрузки сцены; наличие ветви графа не считается доказательством готовности такого объезда. + + +Read-only Nav2 `/diagnostic-snapshot` сохраняет последний запрос планирования, +включая отказ, отдельно от последнего допущенного control-плана. Снимок содержит +текущие физический/поисковый terrain, опубликованные raw costmap глобального и +локального Nav2 и карту у последнего завершившегося ComputePathToPose. Карты +ограничены 320×320; записи заменяются в RAM и не становятся входами управления. +Метки получения/публикации позволяют проверить возраст карты. При более новом +terrain необходимо сверять observation ID: одинаковость разных транзакций +не предполагается. Такой снимок — диагностическое свидетельство, не replay- +или native-приёмка проезда. diff --git a/simulation/ai-polygon/nav2/ros_navigation.py b/simulation/ai-polygon/nav2/ros_navigation.py index 15ebb125..8f2f5796 100644 --- a/simulation/ai-polygon/nav2/ros_navigation.py +++ b/simulation/ai-polygon/nav2/ros_navigation.py @@ -15,6 +15,7 @@ from geometry_msgs.msg import TransformStamped, Twist from lifecycle_msgs.msg import Transition from lifecycle_msgs.srv import ChangeState from nav2_msgs.action import BackUp, ComputePathToPose, FollowPath, Spin +from nav2_msgs.msg import Costmap from nav_msgs.msg import Odometry from rclpy.action import ActionClient from rclpy.node import Node @@ -33,6 +34,11 @@ class RosNavigation(Node): self.condition = threading.Condition() self.action_lock = threading.Lock() self.pose = None + self.costmaps = {} + self.last_planner_diagnostic = None + for name in ("global_costmap", "local_costmap"): + self.create_subscription(Costmap, "/"+name+"/costmap_raw", + lambda value, owner=name: self.receive_costmap(owner, value), 1) self.action_handle = self.terminal = self.latest_command = None self.command_sequence = 0 self.action_sequence = 0 @@ -52,6 +58,22 @@ class RosNavigation(Node): self.spin_client = ActionClient(self, Spin, '/spin') self.backup_client = ActionClient(self, BackUp, '/backup') + def receive_costmap(self, name, message): + metadata = message.metadata + if metadata.size_x * metadata.size_y != len(message.data) or len(message.data) > 320*320: + return # Bounded read-only diagnostics; never a planning input. + receipt = dict(received_at=time.monotonic(), frame_id=message.header.frame_id, + stamp_ns=message.header.stamp.sec*1_000_000_000+message.header.stamp.nanosec, + resolution=metadata.resolution, width=metadata.size_x, height=metadata.size_y, + origin=[metadata.origin.position.x, metadata.origin.position.y], + data=list(message.data)) + with self.condition: + self.costmaps[name] = receipt + + def diagnostic(self): + with self.condition: + return dict(costmaps=dict(self.costmaps), last_planner=self.last_planner_diagnostic) + @staticmethod def await_result(future, timeout): done = threading.Event() @@ -144,6 +166,10 @@ class RosNavigation(Node): # Do not leave work from a timed-out HTTP transaction as authority. self.await_result(handle.cancel_goal_async(), .2) raise + with self.condition: + self.last_planner_diagnostic = dict(completed_at=time.monotonic(), + start=list(pose), goal=list(goal), goal_yaw=yaw, status=result.status, + costmaps=dict(self.costmaps)) return (result.result.path if result.status == GoalStatus.STATUS_SUCCEEDED else None, result.status) diff --git a/simulation/ai-polygon/nav2/server.py b/simulation/ai-polygon/nav2/server.py index 1545e841..9c19df4e 100644 --- a/simulation/ai-polygon/nav2/server.py +++ b/simulation/ai-polygon/nav2/server.py @@ -52,6 +52,7 @@ class Navigation: self.active, self.failure = False, None self.activating = False self.latest_terrain = None + self.latest_exchange = None self.control = ContinuousControl(self.monitor, self.support, lambda _:None, lambda *_:None, self.native_command, body_top_m=self.geometry['collision_top_m'], native_only=True) @@ -101,8 +102,9 @@ class Navigation: def plan(self, value): # Transaction-local metadata cannot survive a stale/failed observation. receipts = {} - result = self._plan(value, receipts) - return {**result, **receipts} + result = {**self._plan(value, receipts), **receipts} + self.latest_exchange = dict(request=value, result=result) + return result def _plan(self, value, receipts): entered = time.monotonic() @@ -300,6 +302,9 @@ def main(): self.reply(200,dict(schema_version='missioncore.navigation-diagnostic/v1', authority='none',execution_inputs_sha256=inputs['sha256'], exchange=navigation.control.snapshot(), + latest_plan=navigation.latest_exchange, + native=navigation.node.diagnostic(), + search_terrain=observed['search_terrain'].tolist() if observed else [], current_observation_id=observed['observation_id'] if observed else None, current_metrics=observed['metrics'] if observed else None, current_detected=observed['detected'].tolist() if observed else [], diff --git a/simulation/ai-polygon/scene_route_field.py b/simulation/ai-polygon/scene_route_field.py index 4bd05f43..c2d9407b 100644 --- a/simulation/ai-polygon/scene_route_field.py +++ b/simulation/ai-polygon/scene_route_field.py @@ -92,7 +92,15 @@ def ground_envelope(vertices, faces, seed): return origin,height,envelope,unknown -def route_graph(origin, height, envelope, unknown, positions, source, world_sha256): +def route_graph(origin, height, envelope, unknown, positions, source, world_sha256, + *, body_extent_m=1.): + if not math.isfinite(body_extent_m) or body_extent_m <= 0: + raise ValueError("Invalid route body extent") + # Once half the body plus one preparation cell fits, additional open area + # earns no discount. Otherwise every narrow sidewalk is attracted toward + # the centre of a wider carriageway, despite having enough usable space. + # This is a geometric preference, never pedestrian or live permission. + preferred_clearance = body_extent_m/2 + CELL clearance = ndimage.distance_transform_edt(envelope)*CELL ids = np.full(envelope.shape,-1,dtype=np.int32) cells = np.argwhere(envelope & (clearance >= .75)) @@ -112,8 +120,8 @@ def route_graph(origin, height, envelope, unknown, positions, source, world_sha2 return None if not envelope[ij[:,0],ij[:,1]].all(): return None - # Keep boundaries expensive. The route follows broad ground structure, - # with a bounded preference that cannot outweigh a long useful detour. + # Preserve measured envelope width; only insufficient comfort clearance + # contributes a soft penalty below. width=float(np.min(clearance[ij[:,0],ij[:,1]])) z=height[ij[:,0],ij[:,1]] if np.any(np.abs(np.diff(z))>.5): @@ -132,7 +140,7 @@ def route_graph(origin, height, envelope, unknown, positions, source, world_sha2 if length < .05: return edges.append(dict(id=str(len(edges)),start=str(i),end=str(j),half_width_m=min(20,width), - bidirectional=True,cost_m=length*(1+2/max(.5,width)))) + bidirectional=True,cost_m=length*(1+2*max(0.,1-width/preferred_clearance)**2))) for i,a in enumerate(cells): for dx,dy in ((STRIDE,0),(0,STRIDE),(STRIDE,STRIDE),(STRIDE,-STRIDE)): @@ -192,7 +200,9 @@ def prepare(request, collider, output, field_cache): with cache.open("rb") as stream: receipt.write_text(json.dumps({"sha256":hashlib.file_digest(stream,"sha256").hexdigest(),"identity":field_identity})) source={k:identity[k] for k in ('provider','provider_sha256','collider_sha256')} - routing=route_graph(origin,height,envelope,unknown,positions,source,world['sha256']) + geometry=robot_geometry(request['robot']) + routing=route_graph(origin,height,envelope,unknown,positions,source,world['sha256'], + body_extent_m=max(geometry['length_m'],geometry['width_m'])) inputs=dict(routing=routing,mission={"route_xy":[p[:2] for p in positions[1:]]}, robot={"geometry":robot_geometry(request['robot'])},sha256=request['key']) route=build_route(inputs) diff --git a/tests/test_scene_route_field.py b/tests/test_scene_route_field.py index 959e927d..49a04565 100644 --- a/tests/test_scene_route_field.py +++ b/tests/test_scene_route_field.py @@ -64,3 +64,27 @@ def test_goal_on_another_height_layer_does_not_attach_to_street(): with pytest.raises(ValueError,match='Endpoint'): route_graph(*field,[[1.,0.,0.],[22.,0.,2.]], dict(provider='synthetic',provider_sha256='a'*64,collider_sha256='b'*64),'c'*64) + + +def test_sufficient_clearance_does_not_attract_route_to_widest_surface(): + # A long open street with A/B on the same side. Geometry has no lane labels; + # extra width farther away must not bend this otherwise direct intention. + origin=np.array([0.,0.]);height=np.zeros((125,65)) + envelope=np.ones_like(height,dtype=bool);envelope[[0,-1],:]=False;envelope[:,[0,-1]]=False + positions=[[2.25,2.25,0.],[58.25,2.25,0.]] + graph=route_graph(origin,height,envelope,np.zeros_like(envelope),positions, + dict(provider='synthetic',provider_sha256='a'*64,collider_sha256='b'*64),'c'*64, + body_extent_m=1.2) + route=build_route(dict(routing=graph,mission={'route_xy':[positions[-1][:2]]}, + robot={'geometry':{'length_m':1.2,'width_m':.9}},sha256='d'*64))['legs'][0] + assert route['status']=='ready' + assert route['length_m']==pytest.approx(56.) + assert all(segment['end_xy'][1]==2.25 for segment in route['segments']) + # There is still a real penalty near an envelope boundary; equal straight + # edge lengths in already generous space have the same price. + nodes={n['id']:n for n in graph['map']['nodes']} + for edge in graph['map']['edges']: + length=np.linalg.norm(np.array(nodes[edge['start']]['xy'])-nodes[edge['end']]['xy']) + assert edge['cost_m'] >= length + if edge['half_width_m']>=1.1: + assert edge['cost_m']==pytest.approx(length)