153 lines
8.6 KiB
Python
153 lines
8.6 KiB
Python
"""Reuse the existing ground observation stage, without CMU motion planning.
|
|
|
|
Only first-hit sensor data and calibrated semantic observations enter here.
|
|
Output is measured terrain cost; it is not a command or a route permission.
|
|
"""
|
|
import math
|
|
import threading
|
|
import time
|
|
from collections import OrderedDict
|
|
|
|
import numpy as np
|
|
from nav_msgs.msg import Odometry
|
|
from sensor_msgs.msg import PointCloud2, PointField
|
|
from sensor_msgs_py import point_cloud2
|
|
from std_msgs.msg import Header
|
|
|
|
from navigation.detection_obstacles import DetectionObstacles
|
|
from navigation.observed_ground import observed_ground_costs
|
|
from navigation.observed_space import ObservedSpace
|
|
from navigation.semantic_surface import SemanticSurface
|
|
from navigation.support_obstacles import SupportObstacles
|
|
from navigation.terrain_costs import TerrainCostNormalizer, underbody_support_costs
|
|
|
|
|
|
PARAMETERS = dict(scanVoxelSize=0.06, inputIsMapSnapshot=True, decayTime=0.5,
|
|
noDecayDis=0.0, useSorting=True, quantileZ=0.25, considerDrop=True,
|
|
clearDyObs=False, noDataObstacle=False, vehicleHeight=0.9,
|
|
minRelZ=-2.0, maxRelZ=1.0, voxelPointUpdateThre=1, voxelTimeUpdateThre=0.0)
|
|
|
|
|
|
class TerrainObservation:
|
|
def __init__(self, node, monitor, geometry, *, range_limits_m=None):
|
|
self.node, self.monitor, self.geometry = node, monitor, geometry
|
|
self.observed = ObservedSpace(range_limits_m=range_limits_m)
|
|
self.normalize = TerrainCostNormalizer()
|
|
self.semantics = SemanticSurface(retain_near=True, fuse_observations=True)
|
|
self.detections = DetectionObstacles(monitor)
|
|
self.support_obstacles = SupportObstacles(1.0)
|
|
self.condition = threading.Condition()
|
|
self.reply = None
|
|
self.ground_reply = None
|
|
self.seen_semantics = OrderedDict()
|
|
self.scan = node.create_publisher(PointCloud2, '/registered_scan', 2)
|
|
self.current_scan = node.create_publisher(PointCloud2, '/terrain/current_scan', 2)
|
|
self.odom = node.create_publisher(Odometry, '/state_estimation', 2)
|
|
node.create_subscription(PointCloud2, '/terrain_map', self.receive, 2)
|
|
node.create_subscription(PointCloud2, '/terrain/current_ground', self.receive_ground, 2)
|
|
|
|
def receive_ground(self, message):
|
|
points = point_cloud2.read_points_numpy(
|
|
message, field_names=['x','y','z','intensity']).copy()
|
|
stamp = message.header.stamp.sec * 1_000_000_000 + message.header.stamp.nanosec
|
|
with self.condition:
|
|
self.ground_reply = stamp, points
|
|
self.condition.notify_all()
|
|
|
|
def receive(self, message):
|
|
points = point_cloud2.read_points_numpy(
|
|
message, field_names=['x', 'y', 'z', 'intensity'], skip_nans=True).copy()
|
|
stamp = message.header.stamp.sec * 1_000_000_000 + message.header.stamp.nanosec
|
|
with self.condition:
|
|
self.reply = stamp, points
|
|
self.condition.notify_all()
|
|
|
|
def observe(self, request):
|
|
started = time.monotonic()
|
|
pose = np.asarray(request['pose'], dtype=float)
|
|
current = np.asarray(request['points'], dtype=np.float32)
|
|
if (current.ndim != 2 or current.shape[1] != 3 or not 50 <= len(current) <= 30000
|
|
or pose.shape != (7,) or not np.isfinite(current).all()
|
|
or not np.isfinite(pose).all() or abs(np.linalg.norm(pose[3:])-1) > .01):
|
|
raise ValueError('Invalid range/pose observation')
|
|
rays = request['range_rays']
|
|
points = self.observed.observe(current, pose, started,
|
|
rays['origins'], rays['ends'], rays['origin_indices'], range_views=rays)
|
|
remembered_at, remembered_count = time.monotonic(), len(points)
|
|
for sample in request['semantic_observations']:
|
|
age = float(sample['age_seconds'])
|
|
if not math.isfinite(age) or age < 0:
|
|
raise ValueError('Invalid semantic capture age')
|
|
identity = sample['frame_id']
|
|
if identity not in self.seen_semantics:
|
|
self.semantics.observe(sample['samples'], started-age, pose,
|
|
evidence_id=sample.get('capture_id', identity))
|
|
self.seen_semantics[identity] = True
|
|
while len(self.seen_semantics) > 128:
|
|
self.seen_semantics.popitem(last=False)
|
|
semantics_at = time.monotonic()
|
|
header = Header(stamp=self.node.get_clock().now().to_msg(), frame_id='map')
|
|
identity = header.stamp.sec * 1_000_000_000 + header.stamp.nanosec
|
|
odom = Odometry(header=header, child_frame_id='vehicle')
|
|
odom.pose.pose.position.x, odom.pose.pose.position.y, odom.pose.pose.position.z = map(float, pose[:3])
|
|
q = odom.pose.pose.orientation
|
|
q.x, q.y, q.z, q.w = map(float, pose[3:])
|
|
fields = [PointField(name=name, offset=i*4, datatype=PointField.FLOAT32, count=1)
|
|
for i, name in enumerate(('x', 'y', 'z', 'intensity'))]
|
|
self.odom.publish(odom)
|
|
self.current_scan.publish(point_cloud2.create_cloud(header, fields,
|
|
np.column_stack((current, np.zeros(len(current), np.float32)))))
|
|
self.scan.publish(point_cloud2.create_cloud(header, fields,
|
|
np.column_stack((points, np.zeros(len(points), np.float32)))))
|
|
with self.condition:
|
|
ready = self.condition.wait_for(
|
|
lambda: (self.reply is not None and abs(self.reply[0]-identity) <= 1000
|
|
and self.ground_reply is not None and self.ground_reply[0] == identity),
|
|
timeout=0.6)
|
|
if not ready:
|
|
raise TimeoutError('Terrain observation did not match the submitted sensor frame')
|
|
points = self.reply[1].copy()
|
|
ground = self.ground_reply[1].copy()
|
|
if (ground.shape != (len(current), 4) or not np.array_equal(ground[:,:3], current)
|
|
or not np.isin(ground[:,3], [0,1]).all()):
|
|
raise ValueError('Ground segmentation changed the source range returns')
|
|
terrain_at = time.monotonic()
|
|
points, slope_count = self.normalize(points)
|
|
points, body_count = underbody_support_costs(points, pose,
|
|
request['body_contact_height_m'], geometry=self.geometry)
|
|
points, patch_count = observed_ground_costs(points, pose,
|
|
request['body_contact_height_m'], monitor=self.monitor)
|
|
physical = points.copy()
|
|
ground_at = time.monotonic()
|
|
# Both checks use the same immutable terrain and pose in this transaction.
|
|
surface = self.support_obstacles.revalidate(points, pose, request['body_contact_height_m'],
|
|
monitor=self.monitor)
|
|
self.support_obstacles.observe_ahead(points, pose, request['body_contact_height_m'],
|
|
monitor=self.monitor, speed_mps=float(request['max_speed_mps']), surface=surface)
|
|
support_at = time.monotonic()
|
|
candidates = self.detections.observed(request)
|
|
ground = current[ground[:,3] == 1]
|
|
detected = self.detections.without_ground(candidates,
|
|
self.semantics.permitted_terrain(ground, time.monotonic()))
|
|
points = self.detections.overlay(points, detected)
|
|
collision = points.copy()
|
|
points, forbidden = self.semantics.apply(points, time.monotonic())
|
|
search, _ = self.support_obstacles.apply(points, pose=pose, monitor=self.monitor)
|
|
return dict(terrain=points, collision_terrain=collision, search_terrain=search,
|
|
physical_terrain=physical, detected=detected,
|
|
permitted_terrain=(self.semantics.permitted_terrain(points, time.monotonic())
|
|
if request.get("route_transition_target") is not None else None),
|
|
current_points=current,
|
|
metrics=dict(detection_candidates=len(candidates),
|
|
detection_ground_returns=len(candidates)-len(detected),
|
|
slope_corrected=slope_count, observed_patches=patch_count,
|
|
underbody_points=body_count, forbidden_points=forbidden,
|
|
remembered_points=remembered_count, terrain_points=len(points),
|
|
stage_ms=dict(memory=(remembered_at-started)*1000,
|
|
semantics=(semantics_at-remembered_at)*1000,
|
|
terrain=(terrain_at-semantics_at)*1000,
|
|
ground=(ground_at-terrain_at)*1000,
|
|
support=(support_at-ground_at)*1000,
|
|
overlays=(time.monotonic()-support_at)*1000),
|
|
processing_ms=(time.monotonic()-started)*1000))
|