Bound urban route clearance preference and expose Nav2 costmap diagnostics

This commit is contained in:
DCCONSTRUCTIONS
2026-10-09 07:48:20 +03:00
parent a14158e483
commit 8c520ba32e
5 changed files with 89 additions and 7 deletions
@@ -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)
+7 -2
View File
@@ -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 [],
+15 -5
View File
@@ -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)