feat(obstacle_cloud): 新包——从配对点云提取障碍并发布感知就绪

输入:laserMapping 发布的成对点云(世界 xyz + 同一批点的原始光心 xyz),
以及 /aft_mapped_to_init 里程计。
输出:/cloud_obstacles_for_scan(供栅格地图消费)、/planning/perception_ready、
/planning/perception_diagnostics。

- core.py 只做几何、不依赖 ROS,离线也可复算;地面模型明确限定为平整行驶面
  加已知 IMU 安装高度,不是可通过性/爬楼分类器。
- 自身回波在光心坐标上判别,不靠位姿反变换。
- 配对断裂必须 fail-closed(test_pairing 断言),不允许回退到别的数据来源。
This commit is contained in:
walunt5
2026-11-05 11:58:57 +08:00
parent f6bbae78bd
commit 5bc7fa74a5
10 changed files with 1112 additions and 0 deletions
@@ -0,0 +1,20 @@
cmake_minimum_required(VERSION 3.8)
project(obstacle_cloud)
find_package(ament_cmake REQUIRED)
find_package(ament_cmake_python REQUIRED)
ament_python_install_package(${PROJECT_NAME})
install(PROGRAMS obstacle_cloud/node.py DESTINATION lib/${PROJECT_NAME} RENAME obstacle_cloud)
install(DIRECTORY config DESTINATION share/${PROJECT_NAME})
if(BUILD_TESTING)
find_package(ament_cmake_pytest REQUIRED)
find_package(launch_testing_ament_cmake REQUIRED)
ament_add_pytest_test(test_obstacle_cloud test/test_core.py
PYTHON_EXECUTABLE /usr/bin/python3
ENV PYTEST_DISABLE_PLUGIN_AUTOLOAD=1)
ament_add_pytest_test(test_obstacle_cloud_pairing test/test_pairing.py
PYTHON_EXECUTABLE /usr/bin/python3
ENV PYTEST_DISABLE_PLUGIN_AUTOLOAD=1)
add_launch_test(test/test_node.py TIMEOUT 20)
add_launch_test(test/test_self_node.py TIMEOUT 20)
endif()
ament_package()
@@ -0,0 +1,44 @@
# Experimental; enabled only by use_obstacle_cloud:=true.
# Height prior is IMU -> floor (not body_odom offset or body_height).
# 0.44 = approximately 0.48 m lidar height minus 0.04412 m lidar->IMU z.
# Re-measure the mount before using this on another robot. Not for ramps.
obstacle_cloud:
ros__parameters:
voxel: 0.05
roi_xy: 5.5
imu_ground_height: 0.44
height_tolerance: 0.08
ground_band: 0.025
max_slope_deg: 5.0
window: 0.7
fit_period: 0.2
min_ground_points: 40
min_ground_fraction: 0.45
column_height: 0.50
# Avoid promoting centimetric floor-fit residuals into tall obstacles.
# Raw returns below this height are still retained, not deleted.
column_min_height: 0.08
# Optical-lidar measurements (front/rear sum to 81 cm, width 80 cm).
# Keep disabled unless explicitly requested by use_self_filter:=true.
self_filter_enable: false
self_front: 0.385
self_rear: 0.425
self_left: 0.40
self_right: 0.40
self_z_min: -0.48
self_z_max: 0.0
# Exterior points pause perception; they are never cropped as self.
self_boundary_guard: 0.02
# p_IMU = R_L_I * p_lidar + T_L_I, active Point-LIO R_L_I is identity.
lidar_to_imu_translation: [-0.011, -0.02329, 0.04412]
# Local tolerance box around ONE confirmed body-part echo: the rear-right
# corner return at optical-lidar (-0.435, -0.386, -0.034) m, which sits 10 mm
# outside self_rear and was producing an obstacle column at its own XY.
# This is a local tolerance around a measured echo, not a change to the
# vehicle dimensions; the general box and the boundary guard are unchanged.
# Only effective together with self_filter_enable above.
self_local_box_enable: true
self_local_box_min: [-0.445, -0.396, -0.044]
self_local_box_max: [-0.425, -0.376, -0.024]
@@ -0,0 +1 @@
"""Experimental obstacle perception for the flat corridor."""
@@ -0,0 +1,301 @@
"""Geometry only; independent of ROS so recorded points can be checked offline.
Use full-resolution, world-frame returns, never localization voxel centroids.
The ground model is intentionally limited to a flat driving surface and a known
IMU mounting height. It is not a traversability or stair-climbing classifier.
"""
from collections import deque
from dataclasses import dataclass
import numpy as np
@dataclass(frozen=True)
class Config:
voxel: float = 0.05
roi_xy: float = 5.5
imu_ground_height: float = 0.44
height_tolerance: float = 0.08
ground_band: float = 0.025
max_slope_deg: float = 5.0
window: float = 0.7
fit_period: float = 0.2
min_ground_points: int = 40
min_ground_fraction: float = 0.45
# Fill the driving-height interval at measured obstacle XY. Solid steps
# also occupy the space below an upper-face return, which may be the only
# visible surface. This is a conservative flat-ground solid-object model.
column_height: float = 0.50
column_min_height: float = 0.08
# Measured physical box in the optical lidar frame; no deletion padding.
self_filter_enable: bool = False
self_front: float = 0.385
self_rear: float = 0.425
self_left: float = 0.40
self_right: float = 0.40
self_z_min: float = -0.48
self_z_max: float = 0.0
# Points just outside the box are NOT removed: they inhibit readiness.
self_boundary_guard: float = 0.02
# Local tolerance box around a CONFIRMED body-part return, in the raw optical
# frame. It is not a change to the vehicle dimensions: it only removes the
# measured echo that sits just outside the general box. Disabled by default;
# a vehicle profile opts in explicitly. Takes effect only when the self filter
# is on, and removed points never count as boundary points.
self_local_box_enable: bool = False
self_local_box_min: tuple = (-0.445, -0.396, -0.044)
self_local_box_max: tuple = (-0.425, -0.376, -0.024)
lidar_to_imu_translation: tuple = (-0.011, -0.02329, 0.04412)
def rotation_from_quaternion(quaternion):
q = np.asarray(quaternion, dtype=np.float64)
if q.shape != (4,) or not np.isfinite(q).all() or np.linalg.norm(q) < 1e-6:
raise ValueError('invalid IMU orientation for self filter')
x, y, z, w = q / np.linalg.norm(q)
return np.array([[1-2*(y*y+z*z), 2*(x*y-z*w), 2*(x*z+y*w)],
[2*(x*y+z*w), 1-2*(x*x+z*z), 2*(y*z-x*w)],
[2*(x*z-y*w), 2*(y*z+x*w), 1-2*(x*x+y*y)]])
def classify_self_returns(points, pose, quaternion, cfg):
"""World -> IMU -> optical lidar, using the active fixed identity R_L_I.
Only the measured closed box is deleted. An exterior uncertainty shell
inhibits motion readiness and preserves potentially real close obstacles.
"""
rotation = rotation_from_quaternion(quaternion)
local = (points - pose) @ rotation - np.asarray(cfg.lidar_to_imu_translation)
lo = np.array([-cfg.self_rear, -cfg.self_right, cfg.self_z_min])
hi = np.array([cfg.self_front, cfg.self_left, cfg.self_z_max])
inside = ((local >= lo) & (local <= hi)).all(axis=1)
# The ambiguity guard is lateral only. Extending below the measured floor
# would incorrectly classify ordinary ground returns as uncertain bodywork.
guard = np.array([cfg.self_boundary_guard, cfg.self_boundary_guard, 0.0])
near = ((local >= lo-guard) & (local <= hi+guard)).all(axis=1) & ~inside
return inside, near
def classify_self_returns_lidar(lidar_xyz, cfg):
"""Classify raw optical-centre coordinates directly: no pose, no inverse transform.
Same measured closed box and the same lateral boundary guard as
classify_self_returns(); the difference is that the caller supplies the
original lidar coordinates of each world point, so no odometry inverse is
applied a second time. Returns (inside_mask, boundary_mask) over N points.
"""
lidar = np.asarray(lidar_xyz, dtype=np.float64)
if lidar.ndim != 2 or lidar.shape[1] != 3:
raise ValueError('expected N x 3 optical-centre coordinates')
lo = np.array([-cfg.self_rear, -cfg.self_right, cfg.self_z_min])
hi = np.array([cfg.self_front, cfg.self_left, cfg.self_z_max])
inside = ((lidar >= lo) & (lidar <= hi)).all(axis=1)
if cfg.self_filter_enable and cfg.self_local_box_enable:
# Confirmed part echo just outside the general box. Folded into
# inside_mask BEFORE the guard is computed, so a removed point can never
# reappear as a boundary hazard.
local_lo = np.asarray(cfg.self_local_box_min, dtype=np.float64)
local_hi = np.asarray(cfg.self_local_box_max, dtype=np.float64)
inside |= ((lidar >= local_lo) & (lidar <= local_hi)).all(axis=1)
guard = np.array([cfg.self_boundary_guard, cfg.self_boundary_guard, 0.0])
near = ((lidar >= lo-guard) & (lidar <= hi+guard)).all(axis=1) & ~inside
return inside, near
def actual_voxel_points(points, voxel):
"""Highest *measured* point per voxel; no averaging across surfaces."""
if len(points) == 0:
return np.empty((0, 3), dtype=np.float64)
cells = np.floor(points / voxel).astype(np.int64)
# Sorting z descending makes np.unique select the highest actual return.
order = np.argsort(-points[:, 2], kind='stable')
_, first = np.unique(cells[order], axis=0, return_index=True)
return points[order[first]]
def fit_ground(points, pose, cfg):
"""Constrained RANSAC z=a*x+b*y+c, followed by a checked least-squares fit."""
if len(points) < cfg.min_ground_points:
return None
# Center coordinates for numerical stability after long odometry travel.
design = np.column_stack((points[:, :2] - pose[:2], np.ones(len(points))))
z = points[:, 2]
limit = np.tan(np.deg2rad(cfg.max_slope_deg))
rng = np.random.default_rng(7)
best = None
best_count = 0
# Bound work independently of sensor density.
for _ in range(64):
idx = rng.choice(len(points), 3, replace=False)
if abs(np.linalg.det(design[idx])) < 0.05:
continue
model = np.linalg.solve(design[idx], z[idx])
if np.linalg.norm(model[:2]) > limit:
continue
if abs(model[2] - (pose[2] - cfg.imu_ground_height)) > cfg.height_tolerance:
continue
mask = np.abs(design @ model - z) <= cfg.ground_band
count = int(mask.sum())
if count > best_count:
best, best_count = mask, count
if best is None or best_count < cfg.min_ground_points:
return None
if best_count / len(points) < cfg.min_ground_fraction:
return None
xy = design[best, :2]
if np.ptp(xy[:, 0]) < 1.0 or np.ptp(xy[:, 1]) < 0.5:
return None
# A single wall/line must not qualify as a ground plane.
if np.linalg.eigvalsh(np.cov(xy.T))[0] < 0.02:
return None
model, _, rank, _ = np.linalg.lstsq(design[best], z[best], rcond=None)
if rank < 3 or np.linalg.norm(model[:2]) > limit:
return None
if abs(model[2] - (pose[2] - cfg.imu_ground_height)) > cfg.height_tolerance:
return None
model[2] -= model[:2] @ pose[:2]
return model
class ObstacleFilter:
def __init__(self, cfg=Config()):
if cfg.self_filter_enable:
bounds = np.array([cfg.self_front, cfg.self_rear, cfg.self_left, cfg.self_right,
cfg.self_z_min, cfg.self_z_max, cfg.self_boundary_guard], dtype=float)
translation = np.asarray(cfg.lidar_to_imu_translation, dtype=float)
if (not np.isfinite(bounds).all() or np.any(bounds[:4] <= 0) or
cfg.self_z_min >= cfg.self_z_max or not 0 <= cfg.self_boundary_guard <= .03 or
translation.shape != (3,) or not np.isfinite(translation).all()):
raise ValueError('invalid measured self-filter box or lidar/IMU translation')
if cfg.self_local_box_enable:
local_min = np.asarray(cfg.self_local_box_min, dtype=np.float64)
local_max = np.asarray(cfg.self_local_box_max, dtype=np.float64)
if (local_min.shape != (3,) or local_max.shape != (3,) or
not np.isfinite(local_min).all() or not np.isfinite(local_max).all() or
not np.all(local_min < local_max)):
raise ValueError('invalid local self-filter box: needs 3 finite bounds '
'with min < max on every axis')
self.cfg = cfg
self.samples = deque()
self.model = None
self.last_time = None
self.last_fit = -np.inf
self.last_good_fit = -np.inf
def process(self, xyz, pose, stamp, orientation=None):
cfg = self.cfg
if self.last_time is not None and stamp <= self.last_time:
self.samples.clear()
self.model = None
self.last_fit = self.last_good_fit = -np.inf
self.last_time = stamp
pts = np.asarray(xyz, dtype=np.float64).reshape((-1, 3))
pose = np.asarray(pose, dtype=np.float64)
if not np.isfinite(pose).all() or not np.isfinite(stamp):
return np.empty((0, 3)), False, {'reason': 'invalid_pose_or_stamp'}
keep = np.isfinite(pts).all(axis=1)
keep &= np.max(np.abs(pts[:, :2] - pose[:2]), axis=1) <= cfg.roi_xy
# Only the driving-height band is useful to this wheeled robot.
keep &= (pts[:, 2] >= pose[2] - 0.8) & (pts[:, 2] <= pose[2] + 1.0)
pts = pts[keep]
if len(pts) == 0:
return pts, False, {'reason': 'empty_cloud_in_roi'}
input_count = len(pts)
self_removed = 0
boundary_points = 0
if cfg.self_filter_enable:
try:
inside, near = classify_self_returns(pts, pose, orientation, cfg)
except (TypeError, ValueError):
return np.empty((0, 3)), False, {'reason': 'self_pose_unconfirmed'}
self_removed = int(inside.sum())
boundary_points = int(near.sum())
# Before ground estimation and all voxelization/extrusion; synthetic
# columns must never be made from the robot's own measured returns.
pts = pts[~inside]
return self._finish(pts, pose, stamp, input_count, self_removed, boundary_points)
def process_with_lidar(self, world_xyz, lidar_xyz, pose, stamp):
"""Delete self returns using per-point ORIGINAL lidar coordinates.
The obstacle branch receives world points that carry their own optical
centre coordinates, so the classification needs no pose inverse. A
mismatch between the two arrays is a hard error: no unfiltered cloud may
be published and the old inverse-transform path is not used as a
fallback.
"""
cfg = self.cfg
if self.last_time is not None and stamp <= self.last_time:
self.samples.clear()
self.model = None
self.last_fit = self.last_good_fit = -np.inf
self.last_time = stamp
pts = np.asarray(world_xyz, dtype=np.float64).reshape((-1, 3))
lid = np.asarray(lidar_xyz, dtype=np.float64).reshape((-1, 3))
pose = np.asarray(pose, dtype=np.float64)
if len(pts) != len(lid):
return np.empty((0, 3)), False, {'reason': 'self_point_correspondence_mismatch',
'world_points': int(len(pts)),
'lidar_points': int(len(lid))}
if not np.isfinite(pose).all() or not np.isfinite(stamp):
return np.empty((0, 3)), False, {'reason': 'invalid_pose_or_stamp'}
keep = np.isfinite(pts).all(axis=1) & np.isfinite(lid).all(axis=1)
keep &= np.max(np.abs(pts[:, :2] - pose[:2]), axis=1) <= cfg.roi_xy
keep &= (pts[:, 2] >= pose[2] - 0.8) & (pts[:, 2] <= pose[2] + 1.0)
# Apply the SAME keep mask to both arrays so the one-to-one
# correspondence survives the ROI and height crop.
pts, lid = pts[keep], lid[keep]
if len(pts) == 0:
return pts, False, {'reason': 'empty_cloud_in_roi'}
input_count = len(pts)
inside, near = classify_self_returns_lidar(lid, cfg)
self_removed = int(inside.sum())
boundary_points = int(near.sum())
pts = pts[~inside]
return self._finish(pts, pose, stamp, input_count, self_removed,
boundary_points)
def _finish(self, pts, pose, stamp, input_count, self_removed, boundary_points):
cfg = self.cfg
seed = pts[np.abs(pts[:, 2] - (pose[2] - cfg.imu_ground_height)) <= cfg.height_tolerance]
self.samples.append((stamp, seed))
while self.samples and stamp - self.samples[0][0] > cfg.window:
self.samples.popleft()
if stamp - self.last_fit >= cfg.fit_period:
self.last_fit = stamp
candidates = actual_voxel_points(np.concatenate([p for _, p in self.samples]), cfg.voxel)
model = fit_ground(candidates, pose, cfg)
if model is not None:
self.model = model
self.last_good_fit = stamp
ready = self.model is not None and 0 <= stamp - self.last_good_fit <= cfg.window
if not ready:
# Do not remove anything using an untrusted ground estimate.
return actual_voxel_points(pts, cfg.voxel), False, {'reason': 'ground_unconfirmed', 'self_removed': self_removed}
heights = pts[:, 2] - (pts[:, :2] @ self.model[:2] + self.model[2])
ground = np.abs(heights) <= cfg.ground_band
measured = actual_voxel_points(pts[~ground], cfg.voxel)
obstacle_height = measured[:, 2] - (measured[:, :2] @ self.model[:2] + self.model[2])
# A small positive ground-fit residual is not sufficient evidence for
# a tall obstacle. Preserve such returns, but do not extrude them.
low = measured[(obstacle_height >= cfg.column_min_height) & (obstacle_height < cfg.column_height)]
columns = []
# Preserve measured XYZ as well; column points share a measured XY.
# Do not clamp to the return's Z: doing so leaves a hollow volume below
# a tall step and can miss it at the lower body_odom query height.
for height in np.arange(cfg.voxel, cfg.column_height + cfg.voxel / 2, cfg.voxel):
p = low.copy()
ground_z = p[:, :2] @ self.model[:2] + self.model[2]
p[:, 2] = ground_z + height
columns.append(p)
output = actual_voxel_points(np.concatenate([measured] + columns), cfg.voxel)
# Exterior shell points remain measured obstacles and receive columns.
# A trusted conservative cloud is still supplied to the map while its
# readiness is false, so a later clean frame cannot erase this evidence.
return output, boundary_points == 0, {
'reason': 'self_boundary_unconfirmed' if boundary_points else 'ready',
'publish_blocked_cloud': boundary_points > 0,
'input': input_count, 'self_removed': self_removed,
'self_boundary_points': boundary_points, 'ground_removed': int(ground.sum()),
'measured_obstacles': len(measured), 'output': len(output),
'ground_plane': self.model.tolist()}
@@ -0,0 +1,204 @@
#!/usr/bin/python3
"""Full-resolution obstacle cloud with fail-closed readiness for the planner."""
import json
import time
from collections import deque
import numpy as np
import rclpy
from nav_msgs.msg import Odometry
from rclpy.node import Node
from rclpy.executors import ExternalShutdownException
from rclpy.qos import DurabilityPolicy, QoSProfile, ReliabilityPolicy, qos_profile_sensor_data
from sensor_msgs.msg import PointCloud2
from sensor_msgs_py import point_cloud2
from std_msgs.msg import Bool, String
from obstacle_cloud.core import Config, ObstacleFilter
def seconds(stamp):
return stamp.sec + stamp.nanosec * 1e-9
def xyz_array(msg):
# Respect field offsets, point_step, row padding and endianness.
fields = {f.name: f for f in msg.fields}
if any(n not in fields or fields[n].datatype != 7 or fields[n].count != 1 for n in ('x', 'y', 'z')):
raise ValueError('expected scalar FLOAT32 x/y/z')
dtype = np.dtype({'names': ['x', 'y', 'z'], 'formats': [('>' if msg.is_bigendian else '<') + 'f4'] * 3,
'offsets': [fields[n].offset for n in ('x', 'y', 'z')], 'itemsize': msg.point_step})
data = np.ndarray((msg.height, msg.width), dtype=dtype, buffer=msg.data,
strides=(msg.row_step, msg.point_step))
return np.column_stack([data[n].ravel() for n in ('x', 'y', 'z')])
SELF_TOPIC = '/cloud_registered_full_lidar'
PAIRED_FIELDS = ('x', 'y', 'z', 'lidar_x', 'lidar_y', 'lidar_z')
def paired_array(msg):
"""World xyz plus the ORIGINAL optical-centre xyz of the very same points.
The two groups must come from one message and one point order; nothing here
reconstructs the lidar coordinate from the world coordinate.
"""
fields = {f.name: f for f in msg.fields}
missing = [n for n in PAIRED_FIELDS if n not in fields]
if missing:
raise ValueError('missing original lidar coordinate fields: ' + ','.join(missing))
if any(fields[n].datatype != 7 or fields[n].count != 1 for n in PAIRED_FIELDS):
raise ValueError('expected scalar FLOAT32 x/y/z/lidar_x/lidar_y/lidar_z')
prefix = '>' if msg.is_bigendian else '<'
dtype = np.dtype({'names': list(PAIRED_FIELDS),
'formats': [prefix + 'f4'] * len(PAIRED_FIELDS),
'offsets': [fields[n].offset for n in PAIRED_FIELDS],
'itemsize': msg.point_step})
data = np.ndarray((msg.height, msg.width), dtype=dtype, buffer=msg.data,
strides=(msg.row_step, msg.point_step))
world = np.column_stack([data[n].ravel() for n in ('x', 'y', 'z')])
lidar = np.column_stack([data[n].ravel() for n in ('lidar_x', 'lidar_y', 'lidar_z')])
if len(world) != len(lidar):
raise ValueError('world and lidar coordinate counts differ')
if not np.isfinite(world).all() or not np.isfinite(lidar).all():
raise ValueError('non-finite coordinate in paired cloud')
return world, lidar
class ObstacleCloudNode(Node):
def __init__(self):
super().__init__('obstacle_cloud')
defaults = Config()
cfg = Config(**{name: self.declare_parameter(name, list(getattr(defaults, name)) if isinstance(getattr(defaults, name), tuple)
else getattr(defaults, name)).value
for name in defaults.__dataclass_fields__})
if not (0 < cfg.voxel <= 0.05 and 0 < cfg.ground_band < cfg.height_tolerance < 0.1
and cfg.imu_ground_height > 0 and cfg.roi_xy > 0 and cfg.window > 0
and cfg.fit_period > 0 and cfg.min_ground_points >= 3
and 0 < cfg.min_ground_fraction <= 1 and 0 < cfg.max_slope_deg <= 5
and 0 < cfg.column_height <= 0.6
and cfg.ground_band < cfg.column_min_height < cfg.column_height):
raise ValueError('invalid flat-ground perception configuration')
self.filter = ObstacleFilter(cfg)
self.pose = None
self.pose_history = deque(maxlen=256)
self.pending_clouds = deque()
self.pose_stamp = 0.0
self.frame = ''
self.last_cloud = -np.inf
self.pose_receipt = -np.inf
self.last_receipt = -np.inf
qos = QoSProfile(depth=1, reliability=ReliabilityPolicy.RELIABLE,
durability=DurabilityPolicy.TRANSIENT_LOCAL)
self.cloud_pub = self.create_publisher(PointCloud2, '/cloud_obstacles_for_scan', qos_profile_sensor_data)
self.ready_pub = self.create_publisher(Bool, '/planning/perception_ready', qos)
self.detail_pub = self.create_publisher(String, '/planning/perception_diagnostics', qos)
self.create_subscription(Odometry, '/aft_mapped_to_init', self.odom, qos_profile_sensor_data)
# With the self filter on, only the paired cloud is accepted: the
# obstacle branch must never fall back to the odometry inverse path.
self.cloud_topic = SELF_TOPIC if cfg.self_filter_enable else '/cloud_registered_full'
self.create_subscription(PointCloud2, self.cloud_topic, self.cloud, qos_profile_sensor_data)
self.create_timer(0.05, self.watchdog)
self.set_ready(False, {'reason': 'waiting_for_full_cloud_and_pose',
'cloud_topic': self.cloud_topic})
def set_ready(self, ready, detail):
self.ready_pub.publish(Bool(data=ready))
self.detail_pub.publish(String(data=json.dumps(detail)))
def odom(self, msg):
p = msg.pose.pose.position
self.pose = np.array([p.x, p.y, p.z])
self.pose_stamp = seconds(msg.header.stamp)
self.frame = msg.header.frame_id
self.pose_receipt = time.monotonic()
q = msg.pose.pose.orientation
if self.pose_history and self.pose_stamp <= self.pose_history[-1][0]:
self.pose_history.clear()
self.pose_history.append((self.pose_stamp, self.pose.copy(),
np.array([q.x, q.y, q.z, q.w]), self.frame))
while self.pending_clouds and seconds(self.pending_clouds[0].header.stamp) <= self.pose_stamp:
pending = self.pending_clouds.popleft()
self.process_cloud(pending)
def watchdog(self):
if time.monotonic() - min(self.last_receipt, self.pose_receipt) > 0.25:
self.set_ready(False, {'reason': 'cloud_or_pose_timeout'})
def cloud(self, msg):
stamp = seconds(msg.header.stamp)
# The full cloud can arrive before its scan-end odometry. Waiting for
# that pose avoids cropping moving world points using an older origin.
# The existing absolute 250 ms age limit still applies when processed.
if (self.filter.cfg.self_filter_enable and self.pose is not None and
msg.header.frame_id == self.frame and 0 < stamp-self.pose_stamp <= .15):
if len(self.pending_clouds) >= 3:
self.pending_clouds.popleft()
self.set_ready(False, {'reason': 'self_pose_queue_overflow'})
self.pending_clouds.append(msg)
return
self.process_cloud(msg)
def process_cloud(self, msg):
stamp = seconds(msg.header.stamp)
age = self.get_clock().now().nanoseconds * 1e-9 - stamp
if (self.pose is None or msg.header.frame_id != self.frame or not msg.header.frame_id
or not 0 <= age <= 0.25 or abs(stamp - self.pose_stamp) > 0.15
or time.monotonic() - self.pose_receipt > 0.25):
self.set_ready(False, {'reason': 'stale_or_mismatched_cloud_pose'})
return
pose, orientation, pose_stamp = self.pose, None, self.pose_stamp
if self.filter.cfg.self_filter_enable:
candidates = [p for p in self.pose_history if p[3] == msg.header.frame_id]
match = min(candidates, key=lambda p: abs(p[0]-stamp)) if candidates else None
if match is None or abs(match[0]-stamp) > .03:
self.set_ready(False, {'reason': 'self_pose_time_mismatch', 'cloud_stamp': stamp})
return
pose_stamp, pose, orientation, _ = match
start = time.monotonic()
try:
if self.filter.cfg.self_filter_enable:
world, lidar = paired_array(msg)
filtered, ready, detail = self.filter.process_with_lidar(
world, lidar, pose, stamp)
else:
points = xyz_array(msg)
filtered, ready, detail = self.filter.process(points, pose, stamp, orientation)
except (ValueError, TypeError, BufferError, np.linalg.LinAlgError) as exc:
self.set_ready(False, {'reason': str(exc)})
return
# Warm-up/invalid ground must not seed the persistent occupancy map
# with floor points that later filtering cannot necessarily ray-clear.
publish_blocked = detail.get('publish_blocked_cloud', False)
cloud = point_cloud2.create_cloud_xyz32(msg.header, filtered.tolist()) if ready or publish_blocked else None
elapsed = time.monotonic() - start
self.last_cloud = stamp
self.last_receipt = time.monotonic()
# A slow frame must not authorize navigation on delayed data.
timely = elapsed < 0.15 and age + elapsed <= 0.25
ready = ready and timely
if timely and (ready or publish_blocked):
self.cloud_pub.publish(cloud)
detail['processing_ms'] = elapsed * 1000
detail['cloud_stamp'] = stamp
detail['pose_stamp'] = pose_stamp
detail['self_filter_enabled'] = self.filter.cfg.self_filter_enable
detail['cloud_topic'] = self.cloud_topic
self.set_ready(ready, detail)
def main():
rclpy.init()
node = ObstacleCloudNode()
try:
rclpy.spin(node)
except (KeyboardInterrupt, ExternalShutdownException):
pass
finally:
node.destroy_node()
if rclpy.ok():
rclpy.shutdown()
if __name__ == '__main__':
main()
@@ -0,0 +1,21 @@
<?xml version="1.0"?>
<package format="3">
<name>obstacle_cloud</name>
<version>0.1.0</version>
<description>Experimental full-resolution obstacle perception for a flat driving corridor.</description>
<maintainer email="[email protected]">kevin</maintainer>
<license>Apache-2.0</license>
<buildtool_depend>ament_cmake</buildtool_depend>
<buildtool_depend>ament_cmake_python</buildtool_depend>
<exec_depend>rclpy</exec_depend>
<exec_depend>nav_msgs</exec_depend>
<exec_depend>sensor_msgs</exec_depend>
<exec_depend>sensor_msgs_py</exec_depend>
<exec_depend>std_msgs</exec_depend>
<exec_depend>python3-numpy</exec_depend>
<test_depend>ament_cmake_pytest</test_depend>
<test_depend>python3-pytest</test_depend>
<test_depend>launch_testing_ament_cmake</test_depend>
<test_depend>launch_ros</test_depend>
<export><build_type>ament_cmake</build_type></export>
</package>
@@ -0,0 +1,294 @@
import numpy as np
import pytest
from obstacle_cloud.core import Config, ObstacleFilter, actual_voxel_points
def flat_scene():
x, y = np.meshgrid(np.linspace(-4, 4, 50), np.linspace(-2, 2, 25))
floor = np.column_stack((x.ravel(), y.ravel(), np.full(x.size, -0.44)))
x, y = np.meshgrid(np.linspace(1, 2.2, 15), np.linspace(0.8, 2, 15))
step20 = np.column_stack((x.ravel(), y.ravel(), np.full(x.size, -0.24)))
step40 = step20 + [2.0, 0, 0.2]
return floor, step20, step40
def test_mixed_surfaces_are_never_averaged():
points = np.array([[4.063, .498, -.146], [4.279, .092, -.456],
[4.242, .194, -.454], [4.208, .293, -.452],
[4.205, .394, -.454], [4.407, .481, -.318],
[4.131, .487, -.448], [4.010, .499, -.152]])
output = actual_voxel_points(points, .05)
assert len(output) == len(points)
assert all(np.any(np.all(points == p, axis=1)) for p in output)
assert not np.any(np.all(np.isclose(output, points.mean(axis=0)), axis=1))
def test_floor_removed_both_step_heights_retained_and_columned():
floor, s20, s40 = flat_scene()
output, ready, detail = ObstacleFilter().process(np.concatenate([floor, s20, s40]), [0, 0, 0], 1.)
assert ready
assert detail['ground_removed'] == len(floor)
# Solid steps must cover both the low body reference and higher path
# reference, even when the lidar only sees their upper face.
for steps in (s20, s40):
for p in steps[::20]:
assert np.min(np.linalg.norm(output - p, axis=1)) < 1e-9
col = output[np.linalg.norm(output[:, :2] - p[:2], axis=1) < 1e-9]
for height in (.1, .2, .4):
assert np.min(abs(col[:, 2] - (-.44 + height))) < 1e-9
assert set(map(tuple, output[:, :2])) <= set(map(tuple, np.concatenate([s20, s40])[:, :2]))
def test_step_top_alone_cannot_become_ground():
_, s20, s40 = flat_scene()
output, ready, _ = ObstacleFilter().process(np.concatenate([s20, s40]), [0, 0, 0], 1.)
assert not ready
assert len(output) > 0
def test_wall_and_slope_are_not_accepted_as_floor():
floor, _, _ = flat_scene()
slope = floor.copy()
slope[:, 2] += .2 * slope[:, 0]
wall = floor.copy()
wall[:, 2] = np.linspace(-.52, -.36, len(wall))
wall[:, 0] = 1
for pts in (slope, wall):
_, ready, _ = ObstacleFilter().process(pts, [0, 0, 0], 1.)
assert not ready
def test_model_expires_when_ground_disappears_and_time_rewind_clears_it():
floor, s20, _ = flat_scene()
f = ObstacleFilter()
assert f.process(floor, [0, 0, 0], 1.)[1]
assert f.process(s20, [0, 0, 0], 1.1)[1]
assert not f.process(s20, [0, 0, 0], 3.)[1]
assert f.process(floor, [0, 0, 0], 4.)[1]
assert not f.process(s20, [0, 0, 0], .5)[1]
def test_nonfinite_and_far_points_do_not_affect_ground():
floor, _, _ = flat_scene()
extra = np.array([[np.nan, 1, 0], [1, np.inf, 0], [20, 20, -.44]])
output, ready, detail = ObstacleFilter().process(np.concatenate([floor, extra]), [0, 0, 0], 1.)
assert ready and len(output) == 0
assert detail['ground_removed'] == len(floor)
def test_small_ground_residual_is_retained_without_tall_extrusion():
floor, _, _ = flat_scene()
low = np.array([[2.025, .025, -.41]]) # 3 cm above the floor plane.
output, ready, _ = ObstacleFilter().process(np.concatenate([floor, low]), [0, 0, 0], 1.)
assert ready
np.testing.assert_allclose(output, low)
def test_ten_cm_fence_covers_both_body_and_path_query_heights():
floor, _, _ = flat_scene()
fence = np.column_stack((np.linspace(3.2, 4.4, 13), np.full(13, -.72), np.full(13, -.34)))
output, ready, _ = ObstacleFilter().process(np.concatenate([floor, fence]), [0, 0, 0], 1.)
assert ready
for p in fence:
column = output[np.linalg.norm(output[:, :2] - p[:2], axis=1) < 1e-9]
for height in (.1, .2, .4):
assert np.min(abs(column[:, 2] - (-.44 + height))) < 1e-9
def test_self_filter_removes_measured_body_before_any_column_is_created():
from dataclasses import replace
cfg = replace(Config(), self_filter_enable=True)
floor, s20, s40 = flat_scene()
# Raw optical point -> IMU/world at identity pose, inside the rear corner.
own = np.array([[-.415, -.37, -.04]]) + cfg.lidar_to_imu_translation
scene = np.concatenate([floor, s20, s40, own])
output, ready, detail = ObstacleFilter(cfg).process(scene, [0, 0, 0], 1., [0, 0, 0, 1])
assert ready and detail['self_removed'] == 1
assert not np.any(np.linalg.norm(output[:, :2]-own[0, :2], axis=1) < 1e-8)
# All external surfaces keep exactly the same measured XYZ and solid columns.
expected = ObstacleFilter().process(np.concatenate([floor, s20, s40]), [0, 0, 0], 1.)[0]
np.testing.assert_array_equal(output, expected)
def test_self_filter_full_rotation_translation_and_closed_physical_bounds():
from obstacle_cloud.core import classify_self_returns, rotation_from_quaternion
cfg = Config()
q = [.08, -.04, .66, .74] # nonzero roll, pitch, yaw; normalization tested too
rot = rotation_from_quaternion(q)
pose = np.array([12., -5., 2.])
local = np.array([[.385, 0, -.04], [-.425, 0, -.04],
[0, .4, -.04], [0, -.4, -.04],
[.42, 0, -.04], [0, -.72, -.38], [1.2, .6, -.08]])
world = (local+cfg.lidar_to_imu_translation) @ rot.T + pose
# Roundoff at a closed mathematical boundary is avoided for the transformed
# points by a tiny inward displacement; exact boundary tested at identity.
local[:4, :2] *= 1-1e-10
world[:4] = (local[:4]+cfg.lidar_to_imu_translation) @ rot.T+pose
inside, near = classify_self_returns(world, pose, q, cfg)
np.testing.assert_array_equal(inside, [True]*4+[False]*3)
assert not near.any()
exact = np.array([[.385, 0, -.04], [-.425, 0, -.04]])+cfg.lidar_to_imu_translation
assert classify_self_returns(exact, np.zeros(3), [0, 0, 0, 1], cfg)[0].all()
def test_exterior_self_boundary_points_pause_instead_of_being_deleted_as_free():
from dataclasses import replace
cfg = replace(Config(), self_filter_enable=True)
floor, _, _ = flat_scene()
exterior = np.array([[-.432, -.37, -.04]])+cfg.lidar_to_imu_translation
out, ready, detail = ObstacleFilter(cfg).process(np.concatenate([floor, exterior]),
[0, 0, 0], 1., [0, 0, 0, 1])
assert not ready and len(out) > 0
assert detail['publish_blocked_cloud']
assert np.any(np.all(np.floor(out/.05) == np.floor(exterior[0]/.05), axis=1))
column = out[np.linalg.norm(out[:, :2]-exterior[0, :2], axis=1) < 1e-9]
assert np.min(abs(column[:, 2]-(-.44+.2))) < 1e-6
assert detail['reason'] == 'self_boundary_unconfirmed'
assert detail['self_boundary_points'] == 1
def test_self_filter_requires_valid_pose_and_keeps_ten_cm_fence():
from dataclasses import replace
cfg = replace(Config(), self_filter_enable=True)
floor, _, _ = flat_scene()
fence = np.column_stack((np.linspace(3.2, 4.4, 13), np.full(13, -.72), np.full(13, -.34)))
scene = np.concatenate([floor, fence])
for orientation in (None, [0, 0, 0, 0], [0, np.nan, 0, 1]):
_, ready, detail = ObstacleFilter(cfg).process(scene, [0, 0, 0], 1., orientation)
assert not ready and detail['reason'] == 'self_pose_unconfirmed'
got, ready, _ = ObstacleFilter(cfg).process(scene, [0, 0, 0], 1., [0, 0, 0, 1])
assert ready
expected = ObstacleFilter().process(scene, [0, 0, 0], 1.)[0]
np.testing.assert_array_equal(got, expected)
def test_classify_self_returns_lidar_uses_optical_frame_only():
from obstacle_cloud.core import classify_self_returns_lidar
cfg = Config()
lidar = np.array([[.385, 0, -.04], [-.425, 0, -.04], [0, .4, -.04], [0, -.4, -.04],
[.42, 0, -.04], [0, -.72, -.38], [1.2, .6, -.08], [0, 0, .02]])
inside, near = classify_self_returns_lidar(lidar, cfg)
np.testing.assert_array_equal(inside, [True]*4+[False]*4)
# Lateral guard only: the point above the box is not "near".
assert not near.any()
assert classify_self_returns_lidar(np.array([[.405, 0, -.04]]), cfg)[1].all()
def test_process_with_lidar_removes_body_and_keeps_external_surfaces():
from dataclasses import replace
cfg = replace(Config(), self_filter_enable=True)
floor, s20, s40 = flat_scene()
# The body occludes the floor beneath it; keep that region out of the scene so
# "self_removed" counts only the deliberate body return.
floor = floor[np.max(np.abs(floor[:, :2]), axis=1) > .8]
own_lidar = np.array([[-.415, -.37, -.04]])
fence_lidar = np.array([[3.5, -.72, -.38]])
lidar = np.concatenate([floor, s20, s40, own_lidar, fence_lidar])
# Identity pose at the origin: world = lidar + lidar->IMU translation.
world = lidar + cfg.lidar_to_imu_translation
output, ready, detail = ObstacleFilter(cfg).process_with_lidar(world, lidar, [0, 0, 0], 1.)
assert ready and detail['self_removed'] == 1
assert detail['self_boundary_points'] == 0
own_world = own_lidar[0] + cfg.lidar_to_imu_translation
# The body return must not survive, and must not have produced a column.
assert not np.any(np.linalg.norm(output[:, :2]-own_world[:2], axis=1) < 1e-8)
# External surfaces are untouched: same measured XYZ as the unfiltered path,
# and the 10 cm fence still reaches both body and path query heights.
expected = ObstacleFilter().process(np.concatenate([floor, s20, s40, fence_lidar])
+ cfg.lidar_to_imu_translation, [0, 0, 0], 1.)[0]
np.testing.assert_array_equal(output, expected)
def test_process_with_lidar_rejects_mismatched_point_counts():
from dataclasses import replace
cfg = replace(Config(), self_filter_enable=True)
floor, _, _ = flat_scene()
world = floor + cfg.lidar_to_imu_translation
output, ready, detail = ObstacleFilter(cfg).process_with_lidar(
world, floor[:-3], [0, 0, 0], 1.)
assert not ready and len(output) == 0
assert detail['reason'] == 'self_point_correspondence_mismatch'
def test_local_box_removes_confirmed_echo_without_boundary_alarm():
from dataclasses import replace
cfg = replace(Config(), self_filter_enable=True, self_local_box_enable=True)
floor, s20, s40 = flat_scene()
floor = floor[np.max(np.abs(floor[:, :2]), axis=1) > .8]
confirmed = np.array([[-0.435, -0.386, -0.034]]) # measured, just outside self_rear
lidar = np.concatenate([floor, s20, s40, confirmed])
world = lidar + cfg.lidar_to_imu_translation
out, ready, detail = ObstacleFilter(cfg).process_with_lidar(world, lidar, [0, 0, 0], 1.)
assert ready, detail['reason']
assert detail['self_removed'] == 1
# Removed as self, so it must not also raise the boundary guard.
assert detail['self_boundary_points'] == 0
echo_world = confirmed[0] + cfg.lidar_to_imu_translation
assert not np.any(np.linalg.norm(out[:, :2]-echo_world[:2], axis=1) < 1e-8)
# Nothing was invented at that XY either: no column from the removed point.
col = out[np.linalg.norm(out[:, :2]-echo_world[:2], axis=1) < 1e-8]
assert len(col) == 0
# External surfaces are byte-identical to the unfiltered path.
expected = ObstacleFilter().process(np.concatenate([floor, s20, s40])
+ cfg.lidar_to_imu_translation, [0, 0, 0], 1.)[0]
np.testing.assert_array_equal(out, expected)
def test_local_box_leaves_points_outside_it_untouched():
from dataclasses import replace
cfg = replace(Config(), self_filter_enable=True, self_local_box_enable=True)
floor, s20, s40 = flat_scene()
floor = floor[np.max(np.abs(floor[:, :2]), axis=1) > .8]
# Outside the local box on y (its range is -0.396..-0.376) but still inside
# the general guard band, so it must be kept AND raise the boundary flag.
outside = np.array([[-0.435, -0.400, -0.034]])
lidar = np.concatenate([floor, s20, s40, outside])
world = lidar + cfg.lidar_to_imu_translation
out, ready, detail = ObstacleFilter(cfg).process_with_lidar(world, lidar, [0, 0, 0], 1.)
assert detail['self_removed'] == 0
# Kept, and it still trips the boundary guard.
assert detail['self_boundary_points'] == 1
kept_world = outside[0] + cfg.lidar_to_imu_translation
assert np.any(np.linalg.norm(out[:, :2]-kept_world[:2], axis=1) < 1e-8)
def test_local_box_disabled_by_default_and_honours_self_filter_switch():
from dataclasses import replace
echo = np.array([[-0.435, -0.386, -0.034]])
# Default config: the local box is off, so the echo stays a boundary point.
from obstacle_cloud.core import classify_self_returns_lidar
inside, near = classify_self_returns_lidar(echo, Config())
assert not inside.any() and near.all()
# Enabled but the self filter is off: the local box must not act.
from obstacle_cloud.core import Config as C
cfg = replace(C(), self_filter_enable=False, self_local_box_enable=True)
inside, near = classify_self_returns_lidar(echo, cfg)
assert not inside.any() and near.all()
def test_invalid_local_box_is_rejected():
from dataclasses import replace
for bad in ((0.0, 0.0, 0.0), (float('nan'), 0.0, 0.0)):
cfg = replace(Config(), self_filter_enable=True, self_local_box_enable=True,
self_local_box_min=bad)
with pytest.raises(ValueError):
ObstacleFilter(cfg)
cfg = replace(Config(), self_filter_enable=True, self_local_box_enable=True,
self_local_box_min=(-0.445, -0.396, -0.044),
self_local_box_max=(-0.445, -0.376, -0.024))
with pytest.raises(ValueError):
ObstacleFilter(cfg)
def test_local_box_keeps_x_and_z_neighbours():
"""The existing outside-test only checks y; check the other two axes."""
from dataclasses import replace
from obstacle_cloud.core import classify_self_returns_lidar
cfg = replace(Config(), self_filter_enable=True, self_local_box_enable=True)
pts = np.array([
[-0.455, -0.386, -0.034], # 10 mm beyond the local box in x
[-0.435, -0.386, -0.014], # 10 mm above the local box in z
])
inside, _ = classify_self_returns_lidar(pts, cfg)
assert not inside.any(), 'only the confirmed echo may be removed'
@@ -0,0 +1,80 @@
"""Synthetic full clouds check live I/O and timeout behavior; no hardware."""
import time
import unittest
import launch
import launch_ros.actions
import launch_testing
import launch_testing.actions
import launch_testing.asserts
import numpy as np
import pytest
import rclpy
from nav_msgs.msg import Odometry
from rclpy.qos import DurabilityPolicy, QoSProfile, qos_profile_sensor_data
from sensor_msgs.msg import PointCloud2
from sensor_msgs_py.point_cloud2 import create_cloud_xyz32
from std_msgs.msg import Bool, Header
@pytest.mark.launch_test
def generate_test_description():
node = launch_ros.actions.Node(package='obstacle_cloud', executable='obstacle_cloud',
additional_env={'OPENBLAS_NUM_THREADS': '1'}, output='screen')
return launch.LaunchDescription([node, launch_testing.actions.ReadyToTest()])
class TestObstacleCloudNode(unittest.TestCase):
def test_ground_steps_and_timeout(self):
rclpy.init()
node = rclpy.create_node('obstacle_cloud_test_driver')
qos = QoSProfile(depth=1, durability=DurabilityPolicy.TRANSIENT_LOCAL)
ready, output = [], []
node.create_subscription(Bool, '/planning/perception_ready', lambda m: ready.append(m.data), qos)
node.create_subscription(PointCloud2, '/cloud_obstacles_for_scan', output.append, qos_profile_sensor_data)
odom_pub = node.create_publisher(Odometry, '/aft_mapped_to_init', 10)
cloud_pub = node.create_publisher(PointCloud2, '/cloud_registered_full', 10)
x, y = np.meshgrid(np.linspace(-4, 4, 30), np.linspace(-2, 2, 20))
floor = np.column_stack((x.ravel(), y.ravel(), np.full(x.size, -.44)))
pts = np.concatenate([floor, [[2., 1., -.24], [3., 1., -.04]]])
cloud_points = pts[-2:]
odom = Odometry()
odom.header.frame_id = 'camera_init'
odom.pose.pose.orientation.w = 1.
def spin(duration, clouds=True, frame='camera_init'):
end = time.monotonic() + duration
next_publish = 0
while time.monotonic() < end:
if time.monotonic() >= next_publish:
next_publish = time.monotonic() + .05
odom.header.stamp = node.get_clock().now().to_msg()
odom_pub.publish(odom)
if clouds:
cloud_pub.publish(create_cloud_xyz32(
Header(frame_id=frame, stamp=odom.header.stamp), cloud_points.tolist()))
rclpy.spin_once(node, timeout_sec=.01)
try:
spin(.7)
assert ready and not ready[-1] and not output
cloud_points = pts
spin(.8)
assert ready and ready[-1]
assert output and output[-1].width > 2 # Includes obstacle columns.
assert output[-1].width < 30 # The 600 floor returns have been removed.
spin(.6, clouds=False)
assert not ready[-1]
spin(.3, frame='wrong_frame')
assert not ready[-1]
spin(.4)
assert ready[-1]
finally:
node.destroy_node()
rclpy.shutdown()
@launch_testing.post_shutdown_test()
class TestShutdown(unittest.TestCase):
def test_clean_exit(self, proc_info):
launch_testing.asserts.assertExitCodes(proc_info)
@@ -0,0 +1,41 @@
"""The obstacle branch must receive world points paired with their own optical
coordinates; a broken pairing has to fail closed instead of falling back."""
import numpy as np
import pytest
from sensor_msgs.msg import PointField
from sensor_msgs_py import point_cloud2
from std_msgs.msg import Header
from obstacle_cloud.node import paired_array
NAMES = ('x', 'y', 'z', 'lidar_x', 'lidar_y', 'lidar_z')
FIELDS = [PointField(name=n, offset=4 * i, datatype=PointField.FLOAT32, count=1)
for i, n in enumerate(NAMES)]
def make_cloud(points, fields=FIELDS):
return point_cloud2.create_cloud(Header(frame_id='camera_init'), fields, points)
def test_world_and_optical_coordinates_keep_their_pairing():
rows = [(1.0, 2.0, 3.0, 0.1, 0.2, 0.3),
(4.0, 5.0, 6.0, 0.4, 0.5, 0.6)]
world, lidar = paired_array(make_cloud(rows))
np.testing.assert_allclose(world, [[1, 2, 3], [4, 5, 6]])
np.testing.assert_allclose(lidar, [[.1, .2, .3], [.4, .5, .6]])
def test_missing_optical_fields_are_rejected():
with pytest.raises(ValueError, match='missing original lidar coordinate'):
paired_array(make_cloud([(1.0, 2.0, 3.0)], FIELDS[:3]))
def test_only_one_optical_field_is_still_rejected():
fields = FIELDS[:4]
with pytest.raises(ValueError, match='missing original lidar coordinate'):
paired_array(make_cloud([(1.0, 2.0, 3.0, 0.1)], fields))
def test_non_finite_coordinates_are_rejected():
with pytest.raises(ValueError, match='non-finite'):
paired_array(make_cloud([(1.0, 2.0, 3.0, float('nan'), 0.0, 0.0)]))
@@ -0,0 +1,106 @@
"""Measured self box precedes columns; ambiguous data inhibits readiness, unsynced input is withheld."""
import json
import time
import unittest
import launch
import launch_ros.actions
import launch_testing.actions
import numpy as np
import pytest
import rclpy
from nav_msgs.msg import Odometry
from rclpy.qos import DurabilityPolicy, QoSProfile, qos_profile_sensor_data
from sensor_msgs.msg import PointCloud2, PointField
from sensor_msgs_py.point_cloud2 import create_cloud
from std_msgs.msg import Bool, Header, String
from obstacle_cloud.node import xyz_array
PAIRED_FIELDS = [PointField(name=n, offset=4*i, datatype=PointField.FLOAT32, count=1)
for i, n in enumerate(('x', 'y', 'z', 'lidar_x', 'lidar_y', 'lidar_z'))]
def paired_cloud(header, world, lidar):
"""One message: world xyz plus the original optical coordinates of the same points."""
rows = [tuple(w) + tuple(l) for w, l in zip(world.tolist(), lidar.tolist())]
return create_cloud(header, PAIRED_FIELDS, rows)
@pytest.mark.launch_test
def generate_test_description():
node = launch_ros.actions.Node(package='obstacle_cloud', executable='obstacle_cloud',
parameters=[{'self_filter_enable': True}],
additional_env={'OPENBLAS_NUM_THREADS': '1'}, output='screen')
return launch.LaunchDescription([node, launch_testing.actions.ReadyToTest()])
class TestSelfFilterNode(unittest.TestCase):
def test_body_fence_boundary_and_pose_alignment(self):
rclpy.init()
node = rclpy.create_node('self_filter_node_driver')
qos = QoSProfile(depth=1, durability=DurabilityPolicy.TRANSIENT_LOCAL)
ready, output, details = [], [], []
node.create_subscription(Bool, '/planning/perception_ready', lambda m: ready.append(m.data), qos)
node.create_subscription(String, '/planning/perception_diagnostics', lambda m: details.append(json.loads(m.data)), qos)
node.create_subscription(PointCloud2, '/cloud_obstacles_for_scan', output.append, qos_profile_sensor_data)
odom_pub = node.create_publisher(Odometry, '/aft_mapped_to_init', 10)
cloud_pub = node.create_publisher(PointCloud2, '/cloud_registered_full_lidar', 10)
x, y = np.meshgrid(np.linspace(-4, 4, 30), np.linspace(-2, 2, 20))
floor = np.column_stack((x.ravel(), y.ravel(), np.full(x.size, -.48)))
floor = floor[np.max(abs(floor[:, :2]), axis=1) > .8] # ground near body is occluded
trans = np.array([-.011, -.02329, .04412])
own = np.array([[-.415, -.37, -.04]])
fence = np.array([[3.5, -.72, -.38]])
pts = np.concatenate([floor, own, fence])+trans
odom = Odometry()
odom.header.frame_id = 'camera_init'
odom.pose.pose.orientation.w = 1.
pose_skew = 0.
def spin(duration):
end = time.monotonic()+duration
next_pub = 0.
while time.monotonic() < end:
if time.monotonic() >= next_pub:
next_pub = time.monotonic()+.05
stamp = node.get_clock().now()
odom.header.stamp = rclpy.time.Time(nanoseconds=stamp.nanoseconds-int(pose_skew*1e9)).to_msg()
odom_pub.publish(odom)
# pts are world coordinates; the same points' optical coordinates
# are pts - trans because the pose is identity at the origin.
cloud_pub.publish(paired_cloud(
Header(frame_id='camera_init', stamp=stamp.to_msg()), pts, pts-trans))
rclpy.spin_once(node, timeout_sec=.01)
try:
spin(1.)
assert ready[-1] and output
cloud = xyz_array(output[-1])
assert not np.any(np.linalg.norm(cloud[:, :2]-(own[0]+trans)[:2], axis=1)<1e-5)
col = cloud[np.linalg.norm(cloud[:, :2]-(fence[0]+trans)[:2], axis=1)<1e-5]
assert np.min(abs(col[:, 2]-(-.43588+.2))) < .01
assert details[-1]['self_removed'] == 1 and details[-1]['self_filter_enabled']
assert abs(details[-1]['cloud_stamp']-details[-1]['pose_stamp']) < .03
pts = np.concatenate([floor, own, fence, [[-.432, -.37, -.04]]])+trans
spin(.3)
assert not ready[-1] and details[-1]['reason'] == 'self_boundary_unconfirmed'
cloud = xyz_array(output[-1])
ext_xy = np.array([-.432, -.37])+trans[:2]
assert np.any(np.linalg.norm(cloud[:, :2]-ext_xy, axis=1) < 1e-5)
assert details[-1]['publish_blocked_cloud']
pts = np.concatenate([floor, own, fence])+trans
pose_skew = .08
spin(.5)
# Delayed odometry is buffered, then matched by sensor time instead
# of using a pose 80 ms older than the full cloud.
assert ready[-1]
assert abs(details[-1]['cloud_stamp']-details[-1]['pose_stamp']) <= .03
pose_skew = 1.
spin(.4)
assert not ready[-1]
pose_skew = 0.
spin(.5)
assert ready[-1]
finally:
node.destroy_node()
rclpy.shutdown()