feat(tracker): add tracker and RViz packages
This commit is contained in:
28
README.md
Normal file
28
README.md
Normal file
@@ -0,0 +1,28 @@
|
||||
# Robot dynamic obstacle tracker
|
||||
|
||||
This repository contains two ROS/catkin packages:
|
||||
|
||||
- `robot_dynamic_obstacle_tracker`: C++17 LiDAR clustering, multi-object
|
||||
tracking, and the native SensorReader/tf3 adapter.
|
||||
- `robot_dynamic_obstacle_tracker_rviz`: isolated simulated-LiDAR scene for
|
||||
visually reviewing tracker output, including ground-truth obstacle markers.
|
||||
|
||||
Clone this repository into a catkin workspace `src` directory. The packages
|
||||
also depend on T800 native packages `robot_sensor_ports`, `robot_sensor_msgs`,
|
||||
`robot_time`, and `tf3`, plus Eigen3, yaml-cpp, ROS Noetic, and RViz.
|
||||
|
||||
Build the core package:
|
||||
|
||||
```bash
|
||||
catkin_make --pkg robot_dynamic_obstacle_tracker -j2
|
||||
```
|
||||
|
||||
Build and launch the RViz simulation:
|
||||
|
||||
```bash
|
||||
catkin_make --pkg robot_dynamic_obstacle_tracker_rviz -j2
|
||||
source devel/setup.bash
|
||||
export ROS_MASTER_URI=http://127.0.0.1:11321
|
||||
export ROS_IP=127.0.0.1
|
||||
roslaunch robot_dynamic_obstacle_tracker_rviz tracker_rviz_sim.launch
|
||||
```
|
||||
139
robot_dynamic_obstacle_tracker/CMakeLists.txt
Normal file
139
robot_dynamic_obstacle_tracker/CMakeLists.txt
Normal file
@@ -0,0 +1,139 @@
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
project(robot_dynamic_obstacle_tracker VERSION 0.1.0 LANGUAGES CXX)
|
||||
|
||||
if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL)
|
||||
set(TRACKER_CATKIN ON)
|
||||
else()
|
||||
set(TRACKER_CATKIN OFF)
|
||||
endif()
|
||||
option(TRACKER_WITH_SENSOR_PORTS "Build the native SensorReader/tf3 adapter" ${TRACKER_CATKIN})
|
||||
option(TRACKER_BUILD_TESTS "Build deterministic tracker tests" ON)
|
||||
set(TRACKER_SANITIZER "" CACHE STRING "Optional address,undefined or thread sanitizer")
|
||||
find_package(Eigen3 REQUIRED)
|
||||
find_package(Threads REQUIRED)
|
||||
find_package(yaml-cpp REQUIRED)
|
||||
|
||||
if(TRACKER_CATKIN)
|
||||
if(NOT TRACKER_WITH_SENSOR_PORTS)
|
||||
message(FATAL_ERROR "Catkin package requires TRACKER_WITH_SENSOR_PORTS=ON")
|
||||
endif()
|
||||
find_package(catkin REQUIRED COMPONENTS robot_sensor_ports robot_sensor_msgs robot_time)
|
||||
catkin_package(
|
||||
INCLUDE_DIRS include
|
||||
LIBRARIES robot_dynamic_obstacle_tracker robot_dynamic_obstacle_tracker_core
|
||||
CATKIN_DEPENDS robot_sensor_ports robot_sensor_msgs robot_time
|
||||
DEPENDS EIGEN3
|
||||
)
|
||||
endif()
|
||||
|
||||
add_library(robot_dynamic_obstacle_tracker_core STATIC
|
||||
src/tracker_config.cpp src/scan_clusterer.cpp src/detection_fusion.cpp
|
||||
src/data_association.cpp src/kalman_track.cpp src/tracker_core.cpp)
|
||||
set_target_properties(robot_dynamic_obstacle_tracker_core PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
||||
target_link_libraries(robot_dynamic_obstacle_tracker_core PUBLIC Eigen3::Eigen)
|
||||
add_library(robot_dynamic_obstacle_tracker SHARED src/tracker_service.cpp src/tracker_config_yaml.cpp)
|
||||
target_link_libraries(robot_dynamic_obstacle_tracker
|
||||
PUBLIC robot_dynamic_obstacle_tracker_core
|
||||
PRIVATE yaml-cpp Threads::Threads)
|
||||
|
||||
foreach(target robot_dynamic_obstacle_tracker_core robot_dynamic_obstacle_tracker)
|
||||
target_compile_features(${target} PUBLIC cxx_std_17)
|
||||
set_target_properties(${target} PROPERTIES CXX_EXTENSIONS OFF)
|
||||
target_include_directories(${target} PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include> $<INSTALL_INTERFACE:include>)
|
||||
target_compile_options(${target} PRIVATE -Wall -Wextra -Wpedantic)
|
||||
if(TRACKER_SANITIZER)
|
||||
target_compile_options(${target} PUBLIC -fsanitize=${TRACKER_SANITIZER} -fno-omit-frame-pointer)
|
||||
target_link_options(${target} PUBLIC -fsanitize=${TRACKER_SANITIZER})
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
if(TRACKER_WITH_SENSOR_PORTS)
|
||||
find_path(TRACKER_TF3_INCLUDE_DIR tf3/buffer_core.h REQUIRED)
|
||||
find_library(TRACKER_TF3_LIBRARY NAMES tf3 REQUIRED)
|
||||
if(TRACKER_CATKIN)
|
||||
set(tracker_native_includes ${catkin_INCLUDE_DIRS} ${TRACKER_TF3_INCLUDE_DIR})
|
||||
set(tracker_native_libraries ${catkin_LIBRARIES} ${TRACKER_TF3_LIBRARY})
|
||||
if(catkin_EXPORTED_TARGETS)
|
||||
add_dependencies(robot_dynamic_obstacle_tracker ${catkin_EXPORTED_TARGETS})
|
||||
endif()
|
||||
elseif(TARGET robot_sensor_ports)
|
||||
set(tracker_native_includes ${TRACKER_TF3_INCLUDE_DIR})
|
||||
set(tracker_native_libraries robot_sensor_ports robot_time ${TRACKER_TF3_LIBRARY})
|
||||
else()
|
||||
# Standalone adapter requires explicitly installed native dependencies.
|
||||
find_package(robot_sensor_ports CONFIG REQUIRED)
|
||||
find_package(robot_sensor_msgs CONFIG REQUIRED)
|
||||
find_package(robot_time CONFIG REQUIRED)
|
||||
set(tracker_native_includes ${robot_sensor_ports_INCLUDE_DIRS}
|
||||
${robot_sensor_msgs_INCLUDE_DIRS} ${robot_time_INCLUDE_DIRS} ${TRACKER_TF3_INCLUDE_DIR})
|
||||
set(tracker_native_libraries ${robot_sensor_ports_LIBRARIES}
|
||||
${robot_time_LIBRARIES} ${TRACKER_TF3_LIBRARY})
|
||||
endif()
|
||||
target_sources(robot_dynamic_obstacle_tracker PRIVATE src/sensor_ports_input.cpp)
|
||||
target_include_directories(robot_dynamic_obstacle_tracker SYSTEM PRIVATE ${tracker_native_includes})
|
||||
target_link_libraries(robot_dynamic_obstacle_tracker PRIVATE ${tracker_native_libraries})
|
||||
endif()
|
||||
|
||||
if(TRACKER_BUILD_TESTS AND (NOT TRACKER_CATKIN OR CATKIN_ENABLE_TESTING))
|
||||
enable_testing()
|
||||
if(NOT TRACKER_CATKIN)
|
||||
find_package(GTest REQUIRED)
|
||||
endif()
|
||||
set(tracker_tests core service config)
|
||||
if(TRACKER_WITH_SENSOR_PORTS)
|
||||
list(APPEND tracker_tests sensor_ports simulated_lidar)
|
||||
endif()
|
||||
foreach(suite IN LISTS tracker_tests)
|
||||
set(test_target dynamic_tracker_${suite}_test)
|
||||
if(TRACKER_CATKIN)
|
||||
catkin_add_gtest(${test_target} test/${suite}_test.cpp test/test_main.cpp)
|
||||
if(NOT TARGET ${test_target})
|
||||
message(FATAL_ERROR "GoogleTest target unavailable: ${test_target}")
|
||||
endif()
|
||||
set_target_properties(${test_target} PROPERTIES EXCLUDE_FROM_ALL FALSE)
|
||||
else()
|
||||
add_executable(${test_target} test/${suite}_test.cpp test/test_main.cpp)
|
||||
target_link_libraries(${test_target} GTest::GTest)
|
||||
add_test(NAME ${test_target} COMMAND ${test_target})
|
||||
endif()
|
||||
if(suite STREQUAL "core")
|
||||
target_link_libraries(${test_target} robot_dynamic_obstacle_tracker_core)
|
||||
else()
|
||||
target_link_libraries(${test_target} robot_dynamic_obstacle_tracker Threads::Threads)
|
||||
endif()
|
||||
target_compile_options(${test_target} PRIVATE -Wall -Wextra -Wpedantic)
|
||||
target_compile_definitions(${test_target} PRIVATE
|
||||
TRACKER_SOURCE_DIR="${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
if(suite STREQUAL "sensor_ports" OR suite STREQUAL "simulated_lidar")
|
||||
target_include_directories(${test_target} SYSTEM PRIVATE ${tracker_native_includes})
|
||||
target_link_libraries(${test_target} ${tracker_native_libraries})
|
||||
endif()
|
||||
endforeach()
|
||||
endif()
|
||||
|
||||
include(GNUInstallDirs)
|
||||
install(TARGETS robot_dynamic_obstacle_tracker_core robot_dynamic_obstacle_tracker
|
||||
EXPORT robot_dynamic_obstacle_trackerTargets
|
||||
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
|
||||
install(DIRECTORY include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
|
||||
install(DIRECTORY config docs DESTINATION ${CMAKE_INSTALL_DATADIR}/${PROJECT_NAME})
|
||||
install(FILES README.md LICENSE DESTINATION ${CMAKE_INSTALL_DATADIR}/${PROJECT_NAME})
|
||||
if(NOT TRACKER_CATKIN)
|
||||
include(CMakePackageConfigHelpers)
|
||||
configure_package_config_file(cmake/robot_dynamic_obstacle_trackerConfig.cmake.in
|
||||
${CMAKE_CURRENT_BINARY_DIR}/robot_dynamic_obstacle_trackerConfig.cmake
|
||||
INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME})
|
||||
write_basic_package_version_file(
|
||||
${CMAKE_CURRENT_BINARY_DIR}/robot_dynamic_obstacle_trackerConfigVersion.cmake
|
||||
VERSION ${PROJECT_VERSION} COMPATIBILITY SameMajorVersion)
|
||||
install(EXPORT robot_dynamic_obstacle_trackerTargets
|
||||
NAMESPACE robot_dynamic_obstacle_tracker::
|
||||
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME})
|
||||
install(FILES
|
||||
${CMAKE_CURRENT_BINARY_DIR}/robot_dynamic_obstacle_trackerConfig.cmake
|
||||
${CMAKE_CURRENT_BINARY_DIR}/robot_dynamic_obstacle_trackerConfigVersion.cmake
|
||||
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME})
|
||||
endif()
|
||||
26
robot_dynamic_obstacle_tracker/LICENSE
Normal file
26
robot_dynamic_obstacle_tracker/LICENSE
Normal file
@@ -0,0 +1,26 @@
|
||||
BSD 3-Clause License
|
||||
|
||||
Copyright (c) 2026, DuongTD
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
1. Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
3. Neither the name of the copyright holder nor the names of its contributors
|
||||
may be used to endorse or promote products derived from this software
|
||||
without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
107
robot_dynamic_obstacle_tracker/README.md
Normal file
107
robot_dynamic_obstacle_tracker/README.md
Normal file
@@ -0,0 +1,107 @@
|
||||
# robot_dynamic_obstacle_tracker
|
||||
|
||||
Thư viện C++17 detection/tracking LiDAR và service quản lý worker thread, dùng được qua
|
||||
SensorReader/tf3 hoặc input adapter riêng. Không cần node ROS hoặc ROS master.
|
||||
|
||||
## Thành phần
|
||||
|
||||
- **robot_dynamic_obstacle_tracker_core**: clustering, fusion hai/nhiều nguồn, Hungarian
|
||||
association, Kalman constant velocity, lifecycle và covariance. Chỉ phụ thuộc Eigen/STL.
|
||||
- **robot_dynamic_obstacle_tracker**: service, snapshot bất biến, YAML loader; adapter
|
||||
SensorReader/tf3 được build khi TRACKER_WITH_SENSOR_PORTS=ON.
|
||||
|
||||
Header chính: **tracker_service.h**, **sensor_ports_input.h**, **tracker_types.h**.
|
||||
MpccLocalPlanner sẽ sở hữu TrackerService; hiện package này chưa được bật trong move_base2.
|
||||
|
||||
## Tích hợp
|
||||
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_service.h>
|
||||
#include <robot_dynamic_obstacle_tracker/sensor_ports_input.h>
|
||||
|
||||
namespace tracking = robot_dynamic_obstacle_tracker;
|
||||
tracking::TrackerConfig config;
|
||||
std::string error;
|
||||
if (!tracking::loadTrackerConfig(config_path, config, error))
|
||||
throw std::runtime_error(error);
|
||||
|
||||
tracking::TrackerDependencies dependencies;
|
||||
dependencies.input = tracking::makeSensorPortsInput(
|
||||
*sensor_reader, tf_buffer, measurement_clock, config.max_scan_points);
|
||||
|
||||
// Keep service as a planner member, not a local variable in compute().
|
||||
if (!tracker_service.configure(config, dependencies, error) ||
|
||||
!tracker_service.start(error))
|
||||
throw std::runtime_error(error);
|
||||
|
||||
auto snapshot = tracker_service.latestSnapshot();
|
||||
// Consume only with an explicit policy for health, source coverage and track lifecycle.
|
||||
// Check published_at using steady time; extrapolate from each track.state_stamp.
|
||||
// Caller must not equate an empty unhealthy snapshot with free space.
|
||||
|
||||
tracker_service.stop(); // Join before destroying SensorReader or unloading the plugin.
|
||||
|
||||
measurement_clock trả Stamp (int64 nanosecond) cùng clock với scan/TF.
|
||||
Có thể bỏ callback để dùng robot::Time::now() khi host đã cấu hình clock này đúng.
|
||||
SensorReader được mượn; TF được giữ bằng shared_ptr. Rebind yêu cầu stop rồi configure lại.
|
||||
Không gọi stop/configure từ callback input đang chạy trong worker.
|
||||
|
||||
Mọi callback input phải nonblocking hoặc có thời gian chờ giới hạn. Service đánh thức được
|
||||
condition_variable khi stop, nhưng không thể hủy cưỡng bức một callback bị treo.
|
||||
Sử dụng pollOnce thay start khi cần replay đồng bộ; hai cách này dùng cùng pipeline.
|
||||
|
||||
## Dữ liệu và giới hạn
|
||||
|
||||
- Scan thô có sequence, timestamp, frame, góc/range. Kiểm freshness cả measurement clock và
|
||||
steady clock; giới hạn source là min(config.max_age, SensorStore.max_age).
|
||||
- TF được tra bằng sec/nsec chính xác tại stamp đo; scan chờ TF tối đa tf_wait, không dùng latest.
|
||||
- Fusion giữ tối đa một frame mỗi nguồn, chờ tối đa fusion_wait; ghép nguồn khác nhau trong
|
||||
fusion_window và bù uncertainty theo fusion_max_speed.
|
||||
- Snapshot chứa source health, session/track ID, x/y/vx/vy, covariance 4x4, radius,
|
||||
timestamp quan sát thật, tentative/confirmed/coasting và moving/stationary/unknown.
|
||||
- Mất một nguồn required làm snapshot không valid. Không tự chuyển sang degraded mode.
|
||||
- Chưa deskew từng tia; scan_time/time_increment được giữ để chẩn đoán. Chưa có semantic
|
||||
classifier, xử lý chân người chuyên biệt hoặc loại self-return bằng footprint.
|
||||
- V1 dùng disc bao cụm; padding chỉ là giả định cho phần bề mặt không quan sát được.
|
||||
Cụm tường lớn vẫn được giữ. Merge/split và geometry bias cần đánh giá bằng scan thật.
|
||||
- Không giới hạn tốc độ vật cản bằng moving_speed; đây chỉ là ngưỡng phân loại có hysteresis.
|
||||
- Nhảy clock làm đổi epoch/session; track mất dấu không được làm mới last_observed_stamp.
|
||||
- Đầu ra chưa bao gồm trajectory tương lai theo horizon MPCC; consumer dự đoán từ state/covariance.
|
||||
- Vượt capacity báo overflow, không coi tập track bị cắt là đầy đủ.
|
||||
Trạng thái overflow của batch được giữ tới khi có batch mới hợp lệ; lỗi riêng của nguồn vẫn
|
||||
có trong sources, kể cả khi status tổng đang giữ lỗi có mức ưu tiên cao hơn.
|
||||
- Dữ liệu latest-only của SensorStore có thể mất các scan trung gian khi xử lý chậm; dropped_count
|
||||
phản ánh gap sequence. Chưa có cam kết hard realtime.
|
||||
|
||||
## Build và test
|
||||
|
||||
Standalone thuật toán + service, không dùng header/library ROS hoặc robot_*:
|
||||
|
||||
cmake -S src/AMR_T800/Test/robot_dynamic_obstacle_tracker -B /tmp/dynamic_tracker_build \
|
||||
-DCMAKE_BUILD_TYPE=Debug -DTRACKER_WITH_SENSOR_PORTS=OFF -DTRACKER_BUILD_TESTS=ON
|
||||
cmake --build /tmp/dynamic_tracker_build -j2
|
||||
cd /tmp/dynamic_tracker_build
|
||||
ctest --output-on-failure
|
||||
|
||||
Catkin cùng adapter native, từ workspace root:
|
||||
|
||||
catkin_make --pkg robot_dynamic_obstacle_tracker -j2
|
||||
catkin_make run_tests_robot_dynamic_obstacle_tracker -j2
|
||||
catkin_test_results build/test_results/robot_dynamic_obstacle_tracker
|
||||
|
||||
Chạy riêng ca LiDAR ray-cast mô phỏng sau khi build:
|
||||
|
||||
cd /home/duongtd/T800_ws
|
||||
./devel/lib/robot_dynamic_obstacle_tracker/dynamic_tracker_simulated_lidar_test
|
||||
|
||||
Hoặc chạy cùng toàn bộ test catkin bằng lệnh run_tests ở trên. Ca mô phỏng phát 101 frame cho hai
|
||||
LiDAR, 241 tia mỗi frame, clock 10 Hz; ray-cast ba hình tròn trong odom (hai tĩnh, một chạy ngang
|
||||
0.25 m/s), đồng thời robot chạy 0.04 m/s và quay 0.01 rad/s. Scan đi qua SensorStore và adapter
|
||||
tf3 thật, sau đó qua TrackerService. Đây là lidar mô phỏng tổng hợp trong test process; không phải
|
||||
node publish /f_scan-/b_scan và không khởi chạy Gazebo.
|
||||
|
||||
Standalone adapter yêu cầu dependency robot_sensor_ports/robot_sensor_msgs/robot_time đã được
|
||||
cài kèm CMake config, hoặc các target native đã có trong superbuild. Không tự tìm source/include
|
||||
từ /opt/ros hoặc devel để che thiếu dependency.
|
||||
|
||||
Bật sanitizer qua -DTRACKER_SANITIZER=address,undefined hoặc thread trong một build directory riêng.
|
||||
Kết quả và ranh giới bằng chứng được ghi ở [docs/verification.md](docs/verification.md).
|
||||
@@ -0,0 +1,7 @@
|
||||
@PACKAGE_INIT@
|
||||
include(CMakeFindDependencyMacro)
|
||||
find_dependency(Eigen3)
|
||||
find_dependency(Threads)
|
||||
include("${CMAKE_CURRENT_LIST_DIR}/robot_dynamic_obstacle_trackerTargets.cmake")
|
||||
set(robot_dynamic_obstacle_tracker_WITH_SENSOR_PORTS @TRACKER_WITH_SENSOR_PORTS@)
|
||||
check_required_components(robot_dynamic_obstacle_tracker)
|
||||
37
robot_dynamic_obstacle_tracker/config/tracker_params.yaml
Normal file
37
robot_dynamic_obstacle_tracker/config/tracker_params.yaml
Normal file
@@ -0,0 +1,37 @@
|
||||
# Cấu hình mẫu đóng gói; chưa thay đổi overlay runtime đang chạy.
|
||||
# Frame liên tục dùng cho vị trí/vận tốc tracking; TF phải có đúng stamp scan.
|
||||
tracking_frame: odom
|
||||
sources:
|
||||
- {topic: /f_scan, required: true, max_age: 0.3}
|
||||
- {topic: /b_scan, required: true, max_age: 0.3}
|
||||
# Giây; watchdog dùng steady clock, cửa sổ ghép dùng timestamp cảm biến.
|
||||
poll_period: 0.01
|
||||
tf_wait: 0.10
|
||||
fusion_window: 0.04
|
||||
fusion_wait: 0.03
|
||||
fusion_distance: 0.25 # m; ngưỡng ghép tâm từ hai LiDAR khác nhau.
|
||||
fusion_max_speed: 3.0 # m/s; biên bù chuyển động giữa các stamp.
|
||||
future_tolerance: 0.02
|
||||
clock_jump_reset: 1.0
|
||||
# Giới hạn tài nguyên; vượt giới hạn báo lỗi, không xuất healthy giả.
|
||||
max_scan_points: 32768
|
||||
max_detections: 128
|
||||
max_tracks: 128
|
||||
min_cluster_points: 3
|
||||
cluster_gap: 0.08 # m; khoảng nối cơ sở giữa hai tia liên tiếp.
|
||||
cluster_angle_scale: 1.5
|
||||
min_radius: 0.10 # m; disc bảo thủ tối thiểu.
|
||||
extent_padding: 0.10 # m; phần bề mặt không nhìn thấy, cần tune theo dữ liệu thật.
|
||||
measurement_sigma: 0.05 # m; độ lệch chuẩn vị trí detection.
|
||||
initial_velocity_sigma: 1.0 # m/s.
|
||||
acceleration_noise: 1.0 # Mật độ nhiễu gia tốc trắng liên tục, m²/s³.
|
||||
gate_chi2: 9.21 # Ngưỡng bình phương khoảng cách Mahalanobis.
|
||||
association_distance: 1.0 # m; gate khoảng cách Euclid bổ sung.
|
||||
confirmation_hits: 3
|
||||
motion_hysteresis_hits: 2
|
||||
tentative_timeout: 0.3 # s từ quan sát thật cuối.
|
||||
track_timeout: 0.8
|
||||
max_prediction: 0.5
|
||||
moving_speed: 0.15 # m/s; ngưỡng chuyển sang moving.
|
||||
stationary_speed: 0.08 # m/s; ngưỡng chuyển sang stationary.
|
||||
motion_velocity_sigma: 0.7 # m/s; chỉ phân loại khi vận tốc đủ chắc.
|
||||
115
robot_dynamic_obstacle_tracker/docs/verification.md
Normal file
115
robot_dynamic_obstacle_tracker/docs/verification.md
Normal file
@@ -0,0 +1,115 @@
|
||||
# Kiểm chứng tracker
|
||||
|
||||
Ngày triển khai: 2026-10-06.
|
||||
|
||||
Trạng thái: **đã build và kiểm chứng ở mức thuật toán, service, adapter native với scan tổng hợp,
|
||||
sanitizer và consumer sau install**. Chưa nối vào local planner/runtime đang chạy.
|
||||
|
||||
## 1. Kết quả
|
||||
|
||||
| Hạng mục | Kết quả | Bằng chứng |
|
||||
|---|---|---|
|
||||
| Standalone Debug, adapter OFF | Build thành công; 3/3 executable test, 40 test case pass | standalone_build.log, standalone_ctest.log |
|
||||
| Catkin Release, adapter ON | Build thành công; 49/49 test case pass | build.log, tests.log, simulated_lidar.xml |
|
||||
| Core | 22 case: scan/geometry/fusion/Hungarian/Kalman/track lifecycle/stop-start/timing | gtest-dynamic_tracker_core_test.xml |
|
||||
| Service | 15 case: sources, freshness, TF retry, clock reset, overflow, thread/snapshot/rebind guard | gtest-dynamic_tracker_service_test.xml |
|
||||
| YAML config | 3 case: mẫu đóng gói, validation, unknown/duplicate/malformed keys | gtest-dynamic_tracker_config_test.xml |
|
||||
| Adapter native | 8 case dùng SensorStore và BufferCore thật | gtest-dynamic_tracker_sensor_ports_test.xml |
|
||||
| LiDAR mô phỏng end-to-end | 1 case; 101 frame x 2 scanner, ba vật tròn, robot chạy/quay | simulated_lidar.log, simulated_lidar.xml |
|
||||
| Service lặp | 100 lượt x 15 case = 1.500 lần thực thi case, không failure | service_repeat_100.log |
|
||||
| ASan + UBSan + LeakSanitizer | 3/3 executable, 40 case pass; không có báo cáo lỗi sanitizer | asan_build.log, asan_ctest_unrestricted.log |
|
||||
| Install/export CMake | Install vào prefix riêng; consumer độc lập configure/build/run, exit 0 | install.log, consumer_configure.log, consumer_build.log, consumer_run.log |
|
||||
|
||||
Thư mục artifact của lượt này:
|
||||
|
||||
/home/duongtd/T800_ws/artifacts/dynamic_tracker_20261006_01/
|
||||
|
||||
**Cách đếm test:** 49 là số phần tử testcase trong XML, không cộng lại các case đã chạy ở
|
||||
standalone/sanitizer. Hãy đếm testcase trong từng XML; catkin_test_results có thể in tổng cao hơn
|
||||
khi tính cả suites. Ca mô phỏng được thêm sau đợt ASan/UBSan standalone.
|
||||
|
||||
ASan/UBSan/LSan áp dụng cho core và service standalone cùng các test của chúng. Dependency hệ thống
|
||||
và adapter native không được instrument trong lượt sanitizer này. Chưa chạy ThreadSanitizer.
|
||||
|
||||
## 2. Hành vi được kiểm chứng
|
||||
|
||||
- Giữ đúng gap giữa tia LiDAR; NaN không nối hai cụm; +Inf toàn scan là quan sát rỗng hợp lệ;
|
||||
scan rỗng hoặc toàn dữ liệu lỗi bị từ chối; không cắt cụm chỉ vì số điểm lớn.
|
||||
- Disc chứa mọi return của fixture, kể cả sau transform; hỗ trợ LiDAR lắp ngược trong mặt phẳng.
|
||||
- Hợp nhất hai nguồn khác extrinsic, chỉ một hit cho một object trong batch; không gộp hai
|
||||
detection từ cùng nguồn; alignment không sửa timestamp quan sát thật.
|
||||
- Hungarian vượt ca greedy bị kẹt; gate khoảng cách/Mahalanobis loại outlier; prediction trước
|
||||
association; Joseph covariance giữ đối xứng và dương trong các chuỗi đã thử.
|
||||
- Vận tốc 0.5 m/s được ước lượng trong sai số 0.02 m/s ở fixture; ID giữ qua crossing có khoảng
|
||||
cách bên hông, stop/start; coasting dự đoán và tăng covariance; track timeout/xóa đúng hạn.
|
||||
- Lookup TF tại stamp scan thay vì TF mới nhất; retry khi TF tới muộn; kiểm header/store stamp.
|
||||
- Cảnh tường tĩnh khi sensor tịnh tiến và cylinder tĩnh khi sensor quay không bị phân loại moving
|
||||
trong các fixture tương ứng.
|
||||
- Mất rear source required không được healthy dù front còn tốt; watchdog steady hoạt động khi
|
||||
measurement clock đứng; stale/future/duplicate/regressing scan có trạng thái lỗi riêng.
|
||||
- Clock nhảy lùi đổi epoch/session và xóa track cũ; snapshot đã cấp vẫn bất biến.
|
||||
- Capacity overflow không thành valid+rỗng; batch lỗi được giữ tới batch hợp lệ mới.
|
||||
- start/stop lặp, exception trong worker, đọc snapshot đồng thời, start lại và destructor join.
|
||||
- LiDAR ray-cast end-to-end: mỗi frame dựng scan trước/sau với TF riêng, vật tĩnh hai phía,
|
||||
vật chạy ngang 0.25 m/s và robot đang tiến/quay; vật tĩnh không thành moving và không tạo
|
||||
detection duplicate trong fixture.
|
||||
|
||||
Chạy riêng ca LiDAR mô phỏng:
|
||||
|
||||
cd /home/duongtd/T800_ws
|
||||
./devel/lib/robot_dynamic_obstacle_tracker/dynamic_tracker_simulated_lidar_test
|
||||
|
||||
Đây là tia ray-cast tổng hợp trong test process. Không có Gazebo world, ROS scan publisher,
|
||||
move_base2 host hoặc nhiễu vật lý trong kết quả này.
|
||||
|
||||
## 3. Số đo thời gian giới hạn phạm vi
|
||||
|
||||
Fixture CorePerformance dùng **32 track, 300 lần update**, input detection lý tưởng; đo update
|
||||
và lấy predictedTracks trên máy phát triển **Intel Core i5-13400F**, GCC 9.4, catkin Release.
|
||||
Lượt ghi trong catkin_tests.log: **p99 = 0.030937 ms, max = 0.071746 ms**.
|
||||
|
||||
Đây không phải độ trễ scan -> detection -> tracking đầy đủ, không gồm TF/store/worker scheduling,
|
||||
không phải tải worst-case 128 track dày đặc và không phải bằng chứng 20 Hz trên máy robot.
|
||||
Gate thời gian stop của test là 200 ms; 100 lượt service đều qua gate ở môi trường đã chạy.
|
||||
|
||||
## 4. Lệnh tái lập
|
||||
|
||||
Từ workspace root, tạo thư mục log theo timestamp:
|
||||
|
||||
set -o pipefail
|
||||
tracker_run_dir="$PWD/artifacts/dynamic_tracker_$(date +%Y%m%d_%H%M%S)"
|
||||
mkdir -p "$tracker_run_dir"
|
||||
catkin_make --pkg robot_dynamic_obstacle_tracker -j2 2>&1 | tee "$tracker_run_dir/build.log"
|
||||
catkin_make run_tests_robot_dynamic_obstacle_tracker -j2 2>&1 | tee "$tracker_run_dir/tests.log"
|
||||
catkin_test_results build/test_results/robot_dynamic_obstacle_tracker 2>&1 | tee "$tracker_run_dir/results.log"
|
||||
|
||||
Standalone/sanitizer theo README, dùng build directory riêng. Với CMake/CTest 3.16 của môi trường
|
||||
này, phải cd vào build directory trước ctest; --test-dir không được hỗ trợ.
|
||||
|
||||
Lệnh sanitizer đã chạy sau khi build với TRACKER_SANITIZER=address,undefined:
|
||||
|
||||
cd /tmp/dynamic_tracker_20261006_asan
|
||||
ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 UBSAN_OPTIONS=halt_on_error=1 ctest --output-on-failure
|
||||
|
||||
Lần chạy trong sandbox bị LeakSanitizer từ chối vì ptrace, sau khi các assertions đã chạy.
|
||||
Đã chạy lại ngoài sandbox với quyền được cho phép và đạt exit 0; không tắt detect_leaks để ghi pass.
|
||||
|
||||
Consumer sau install:
|
||||
|
||||
cd /home/duongtd/T800_ws
|
||||
cmake --install /tmp/dynamic_tracker_20261006_debug --prefix /tmp/dynamic_tracker_20261006_install
|
||||
cmake -S src/AMR_T800/Test/robot_dynamic_obstacle_tracker/test/install_consumer \
|
||||
-B /tmp/dynamic_tracker_20261006_consumer -DCMAKE_PREFIX_PATH=/tmp/dynamic_tracker_20261006_install
|
||||
cmake --build /tmp/dynamic_tracker_20261006_consumer -j2
|
||||
/tmp/dynamic_tracker_20261006_consumer/tracker_install_consumer
|
||||
|
||||
## 5. Chưa được nghiệm thu
|
||||
|
||||
- Replay scan/TF từ robot, noise/range/extrinsic thật, độ trễ lệch hai LiDAR và occlusion thật.
|
||||
- Deskew, footprint self-filter, merge/split chân người/xe đẩy và shape hoàn chỉnh của vật thể.
|
||||
- Gazebo chạy cùng host, costmap, MPCC, guard/arbiter; lifecycle callback khi move_base2 stop/refresh.
|
||||
- Tải CPU đầy đủ trên máy đích; timing worst-case; soak 1 giờ/8 giờ; ThreadSanitizer và robot thật.
|
||||
- Standalone adapter với bộ native dependencies được install hoàn chỉnh: lượt này chứng minh
|
||||
standalone core/service và catkin native adapter, chưa khẳng định native superbuild đã nghiệm thu.
|
||||
|
||||
Những phần trên là hạng mục tiếp theo; 49 test pass không thay thế các mức bằng chứng này.
|
||||
@@ -0,0 +1,12 @@
|
||||
#ifndef ROBOT_DYNAMIC_OBSTACLE_TRACKER_DATA_ASSOCIATION_H_
|
||||
#define ROBOT_DYNAMIC_OBSTACLE_TRACKER_DATA_ASSOCIATION_H_
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_config.h>
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_types.h>
|
||||
namespace robot_dynamic_obstacle_tracker
|
||||
{
|
||||
// Returns one detection index per track, or -1. Tracks must already be predicted to batch time.
|
||||
std::vector<int> associateDetections(const std::vector<Track>& predicted,
|
||||
const std::vector<Detection>& detections,
|
||||
const TrackerConfig&);
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,11 @@
|
||||
#ifndef ROBOT_DYNAMIC_OBSTACLE_TRACKER_DETECTION_FUSION_H_
|
||||
#define ROBOT_DYNAMIC_OBSTACLE_TRACKER_DETECTION_FUSION_H_
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_config.h>
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_types.h>
|
||||
namespace robot_dynamic_obstacle_tracker
|
||||
{
|
||||
// One detection per source per fused object. Never reduces covariance for correlated sensors.
|
||||
ProcessingResult fuseDetections(const std::vector<DetectionFrame>& frames, Stamp batch_stamp,
|
||||
const TrackerConfig&, std::vector<Detection>& out);
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,10 @@
|
||||
#ifndef ROBOT_DYNAMIC_OBSTACLE_TRACKER_KALMAN_TRACK_H_
|
||||
#define ROBOT_DYNAMIC_OBSTACLE_TRACKER_KALMAN_TRACK_H_
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_types.h>
|
||||
namespace robot_dynamic_obstacle_tracker
|
||||
{
|
||||
bool validDetection(const Detection&);
|
||||
bool predictTrack(Track&, Stamp, double acceleration_noise);
|
||||
bool correctTrack(Track&, const Detection&);
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,17 @@
|
||||
#ifndef ROBOT_DYNAMIC_OBSTACLE_TRACKER_SCAN_CLUSTERER_H_
|
||||
#define ROBOT_DYNAMIC_OBSTACLE_TRACKER_SCAN_CLUSTERER_H_
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_config.h>
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_types.h>
|
||||
namespace robot_dynamic_obstacle_tracker
|
||||
{
|
||||
class ScanClusterer
|
||||
{
|
||||
public:
|
||||
explicit ScanClusterer(const TrackerConfig& config);
|
||||
ProcessingResult detect(const RawScan&, const PlanarTransform&, std::size_t source,
|
||||
std::vector<Detection>& out) const;
|
||||
private:
|
||||
TrackerConfig config_;
|
||||
};
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,15 @@
|
||||
#ifndef ROBOT_DYNAMIC_OBSTACLE_TRACKER_SENSOR_PORTS_INPUT_H_
|
||||
#define ROBOT_DYNAMIC_OBSTACLE_TRACKER_SENSOR_PORTS_INPUT_H_
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_service.h>
|
||||
namespace robot_sensor_ports { class SensorReader; }
|
||||
namespace tf3 { class BufferCore; }
|
||||
|
||||
namespace robot_dynamic_obstacle_tracker
|
||||
{
|
||||
// Borrowed SensorReader must outlive service.stop()/destruction. TF uses shared ownership.
|
||||
// now() must be the same measurement clock as scan/TF; defaults to robot::Time::now().
|
||||
std::shared_ptr<TrackerInput> makeSensorPortsInput(
|
||||
const robot_sensor_ports::SensorReader& reader, std::shared_ptr<const tf3::BufferCore> tf,
|
||||
std::function<Stamp()> now = {}, std::size_t max_scan_points = 32768);
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,43 @@
|
||||
#ifndef ROBOT_DYNAMIC_OBSTACLE_TRACKER_TRACKER_CONFIG_H_
|
||||
#define ROBOT_DYNAMIC_OBSTACLE_TRACKER_TRACKER_CONFIG_H_
|
||||
#include <cstddef>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace robot_dynamic_obstacle_tracker
|
||||
{
|
||||
struct SourceConfig
|
||||
{
|
||||
std::string topic;
|
||||
bool required = true;
|
||||
double max_age = 0.3; // [s], capped by SensorStore policy.
|
||||
};
|
||||
|
||||
struct TrackerConfig
|
||||
{
|
||||
std::string tracking_frame = "odom";
|
||||
std::vector<SourceConfig> sources{{"/f_scan", true, 0.3}, {"/b_scan", true, 0.3}};
|
||||
double poll_period = 0.01, tf_wait = 0.1; // [s], steady clock.
|
||||
double fusion_window = 0.04, fusion_wait = 0.03; // Measurement / steady clock [s].
|
||||
double fusion_distance = 0.25, fusion_max_speed = 3.0; // [m], [m/s].
|
||||
double future_tolerance = 0.02, clock_jump_reset = 1.0; // [s].
|
||||
std::size_t max_scan_points = 32768, max_detections = 128, max_tracks = 128;
|
||||
std::size_t min_cluster_points = 3;
|
||||
double cluster_gap = 0.08, cluster_angle_scale = 1.5; // [m], dimensionless.
|
||||
double min_radius = 0.1, extent_padding = 0.1; // [m].
|
||||
double measurement_sigma = 0.05, initial_velocity_sigma = 1.0;
|
||||
double acceleration_noise = 1.0; // Continuous white acceleration spectral density.
|
||||
double gate_chi2 = 9.21, association_distance = 1.0; // Squared Mahalanobis, [m].
|
||||
std::size_t confirmation_hits = 3, motion_hysteresis_hits = 2;
|
||||
double tentative_timeout = 0.3, track_timeout = 0.8, max_prediction = 0.5; // [s].
|
||||
double moving_speed = 0.15, stationary_speed = 0.08; // [m/s].
|
||||
double motion_velocity_sigma = 0.7; // Maximum velocity stddev for classification [m/s].
|
||||
|
||||
bool validate(std::string& error) const;
|
||||
};
|
||||
|
||||
// Strict YAML parser: accepts a root mapping of TrackerConfig fields, rejects unknown keys.
|
||||
// YAML lives in the service library; the algorithm core does not depend on yaml-cpp.
|
||||
bool loadTrackerConfig(const std::string& path, TrackerConfig& out, std::string& error);
|
||||
} // namespace robot_dynamic_obstacle_tracker
|
||||
#endif
|
||||
@@ -0,0 +1,27 @@
|
||||
#ifndef ROBOT_DYNAMIC_OBSTACLE_TRACKER_TRACKER_CORE_H_
|
||||
#define ROBOT_DYNAMIC_OBSTACLE_TRACKER_TRACKER_CORE_H_
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_config.h>
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_types.h>
|
||||
namespace robot_dynamic_obstacle_tracker
|
||||
{
|
||||
// Single-owner, single-thread algorithm. No sensor, clock, thread, TF or ROS dependencies.
|
||||
class TrackerCore
|
||||
{
|
||||
public:
|
||||
explicit TrackerCore(const TrackerConfig& config);
|
||||
void reset(std::uint64_t session_id);
|
||||
ProcessingResult update(Stamp, const std::vector<Detection>&,
|
||||
const std::vector<std::size_t>& observed_sources);
|
||||
void expire(Stamp now);
|
||||
std::vector<Track> predictedTracks(Stamp now) const;
|
||||
Stamp lastUpdateStamp() const { return last_update_; }
|
||||
private:
|
||||
struct Record { Track track; std::size_t moving_hits = 0, stationary_hits = 0; };
|
||||
void classify(Record&);
|
||||
TrackerConfig config_;
|
||||
std::vector<Record> tracks_;
|
||||
std::uint64_t session_id_ = 0, next_id_ = 1;
|
||||
Stamp last_update_ = 0;
|
||||
};
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,52 @@
|
||||
#ifndef ROBOT_DYNAMIC_OBSTACLE_TRACKER_TRACKER_SERVICE_H_
|
||||
#define ROBOT_DYNAMIC_OBSTACLE_TRACKER_TRACKER_SERVICE_H_
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_config.h>
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_types.h>
|
||||
|
||||
namespace robot_dynamic_obstacle_tracker
|
||||
{
|
||||
enum class ReadStatus { kNoData, kScan, kError };
|
||||
|
||||
// All methods must be bounded/nonblocking; called only by the service's worker or pollOnce.
|
||||
// Adapter owns no host resources unless its concrete implementation says otherwise.
|
||||
class TrackerInput
|
||||
{
|
||||
public:
|
||||
virtual ~TrackerInput() = default;
|
||||
virtual bool describeSource(const std::string& topic, double& max_age, std::string& error) const = 0;
|
||||
virtual ReadStatus readLatest(const std::string& topic, std::uint64_t& cursor,
|
||||
RawScan& out, std::string& error) = 0;
|
||||
virtual bool lookupTransform(const std::string& target, const std::string& source, Stamp stamp,
|
||||
PlanarTransform& out, std::string& error) = 0;
|
||||
virtual Stamp measurementNow() const = 0;
|
||||
};
|
||||
struct TrackerDependencies
|
||||
{
|
||||
std::shared_ptr<TrackerInput> input;
|
||||
std::function<SteadyTime()> steady_now = [] { return std::chrono::steady_clock::now(); };
|
||||
};
|
||||
|
||||
class TrackerService
|
||||
{
|
||||
public:
|
||||
TrackerService();
|
||||
~TrackerService(); // stop + join; owner must outlive the worker's callbacks.
|
||||
TrackerService(const TrackerService&) = delete;
|
||||
TrackerService& operator=(const TrackerService&) = delete;
|
||||
bool configure(const TrackerConfig&, const TrackerDependencies&, std::string& error);
|
||||
bool start(std::string& error); // Idempotent while running; fresh session after stop.
|
||||
void stop() noexcept; // Idempotent. Call from the owning thread, never a callback.
|
||||
bool running() const noexcept;
|
||||
std::shared_ptr<const TrackSnapshot> latestSnapshot() const;
|
||||
|
||||
// Deterministic/synchronous embedding using the same pipeline as the worker.
|
||||
// Refused while start() owns the pipeline. No sleeps; caller controls injected clocks.
|
||||
bool pollOnce(std::string& error);
|
||||
private:
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,102 @@
|
||||
#ifndef ROBOT_DYNAMIC_OBSTACLE_TRACKER_TRACKER_TYPES_H_
|
||||
#define ROBOT_DYNAMIC_OBSTACLE_TRACKER_TRACKER_TYPES_H_
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <Eigen/Core>
|
||||
|
||||
namespace robot_dynamic_obstacle_tracker
|
||||
{
|
||||
using Stamp = std::int64_t; // Nanoseconds in the host measurement clock; never steady time.
|
||||
using SteadyTime = std::chrono::steady_clock::time_point;
|
||||
inline double secondsBetween(Stamp a, Stamp b) { return static_cast<double>(a - b) * 1e-9; }
|
||||
|
||||
enum class Health { kWarmingUp, kValid, kStale, kTfError, kInvalidInput, kOutOfOrder,
|
||||
kOverflow, kFault, kStopped };
|
||||
enum class TrackLifecycle { kTentative, kConfirmed, kCoasting };
|
||||
enum class MotionClass { kUnknown, kStationary, kMoving };
|
||||
|
||||
struct RawScan
|
||||
{
|
||||
Stamp stamp = 0;
|
||||
std::uint64_t sequence = 0;
|
||||
std::string frame;
|
||||
double angle_min = 0.0, angle_increment = 0.0;
|
||||
double range_min = 0.0, range_max = 0.0;
|
||||
double time_increment = 0.0, scan_time = 0.0; // Seconds; v1 does not deskew.
|
||||
std::vector<float> ranges;
|
||||
};
|
||||
|
||||
// Orthogonal XY map, including reflection for an upside-down planar laser.
|
||||
struct PlanarTransform
|
||||
{
|
||||
Eigen::Matrix2d linear = Eigen::Matrix2d::Identity();
|
||||
Eigen::Vector2d translation = Eigen::Vector2d::Zero();
|
||||
bool valid() const;
|
||||
Eigen::Vector2d apply(const Eigen::Vector2d& p) const { return linear * p + translation; }
|
||||
};
|
||||
|
||||
struct Detection
|
||||
{
|
||||
Eigen::Vector2d position = Eigen::Vector2d::Zero();
|
||||
Eigen::Matrix2d covariance = Eigen::Matrix2d::Identity() * 0.0025;
|
||||
double radius = 0.1; // Bounding disc of visible returns plus configured padding [m].
|
||||
Stamp stamp = 0;
|
||||
Stamp observed_stamp = 0; // Actual last return time; 0 means stamp for unfused detections.
|
||||
std::vector<std::size_t> sources;
|
||||
};
|
||||
|
||||
struct DetectionFrame
|
||||
{
|
||||
Stamp stamp = 0;
|
||||
std::size_t source = 0;
|
||||
std::vector<Detection> detections;
|
||||
};
|
||||
|
||||
struct Track
|
||||
{
|
||||
std::uint64_t session_id = 0, track_id = 0;
|
||||
Stamp state_stamp = 0, last_observed_stamp = 0;
|
||||
Eigen::Vector4d state = Eigen::Vector4d::Zero(); // x, y, vx, vy in snapshot frame.
|
||||
Eigen::Matrix4d covariance = Eigen::Matrix4d::Identity();
|
||||
double radius = 0.1;
|
||||
TrackLifecycle lifecycle = TrackLifecycle::kTentative;
|
||||
MotionClass motion = MotionClass::kUnknown;
|
||||
std::vector<std::size_t> observed_sources;
|
||||
std::uint64_t hit_count = 0, miss_count = 0;
|
||||
};
|
||||
|
||||
struct SourceHealth
|
||||
{
|
||||
std::string topic;
|
||||
bool required = true;
|
||||
Health status = Health::kWarmingUp;
|
||||
std::uint64_t last_sequence = 0, processed_count = 0, dropped_count = 0;
|
||||
Stamp last_measurement_stamp = 0, last_success_stamp = 0;
|
||||
SteadyTime last_receive_steady_time{}, last_success_steady_time{};
|
||||
std::string reason;
|
||||
};
|
||||
|
||||
struct TrackSnapshot
|
||||
{
|
||||
std::string frame;
|
||||
std::uint64_t session_id = 0, generation = 0, measurement_epoch = 0;
|
||||
Stamp state_stamp = 0;
|
||||
SteadyTime published_at{}, last_success_steady_time{};
|
||||
Health status = Health::kWarmingUp;
|
||||
std::string reason;
|
||||
std::vector<SourceHealth> sources;
|
||||
std::vector<Track> tracks;
|
||||
};
|
||||
|
||||
struct ProcessingResult
|
||||
{
|
||||
Health status = Health::kValid;
|
||||
std::string reason;
|
||||
std::size_t rejected_points = 0, small_clusters = 0;
|
||||
};
|
||||
const char* healthName(Health status) noexcept;
|
||||
} // namespace robot_dynamic_obstacle_tracker
|
||||
#endif
|
||||
21
robot_dynamic_obstacle_tracker/package.xml
Normal file
21
robot_dynamic_obstacle_tracker/package.xml
Normal file
@@ -0,0 +1,21 @@
|
||||
<package>
|
||||
<name>robot_dynamic_obstacle_tracker</name>
|
||||
<version>0.1.0</version>
|
||||
<description>Native C++ LiDAR clustering, multi-object tracking and a managed SensorReader service.</description>
|
||||
<maintainer email="tdd@gmail.com">DuongTD</maintainer>
|
||||
<license>BSD-3-Clause</license>
|
||||
<buildtool_depend version_gte="0.5.68">catkin</buildtool_depend>
|
||||
<build_depend>eigen</build_depend>
|
||||
<run_depend>eigen</run_depend>
|
||||
<build_depend>yaml-cpp</build_depend>
|
||||
<run_depend>yaml-cpp</run_depend>
|
||||
<build_depend>robot_sensor_ports</build_depend>
|
||||
<run_depend>robot_sensor_ports</run_depend>
|
||||
<build_depend>robot_sensor_msgs</build_depend>
|
||||
<run_depend>robot_sensor_msgs</run_depend>
|
||||
<build_depend>robot_time</build_depend>
|
||||
<run_depend>robot_time</run_depend>
|
||||
<build_depend>tf3</build_depend>
|
||||
<run_depend>tf3</run_depend>
|
||||
<test_depend>gtest</test_depend>
|
||||
</package>
|
||||
63
robot_dynamic_obstacle_tracker/src/data_association.cpp
Normal file
63
robot_dynamic_obstacle_tracker/src/data_association.cpp
Normal file
@@ -0,0 +1,63 @@
|
||||
#include <robot_dynamic_obstacle_tracker/data_association.h>
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
#include <Eigen/Cholesky>
|
||||
|
||||
namespace robot_dynamic_obstacle_tracker
|
||||
{
|
||||
std::vector<int> associateDetections(const std::vector<Track>& tracks,
|
||||
const std::vector<Detection>& detections,
|
||||
const TrackerConfig& config)
|
||||
{
|
||||
const std::size_t rows = tracks.size(), real_columns = detections.size();
|
||||
const std::size_t columns = real_columns + rows; // Private unmatched alternatives.
|
||||
std::vector<int> result(rows, -1);
|
||||
if (rows == 0 || real_columns == 0) return result;
|
||||
const double rejected = 1e12, unmatched = config.gate_chi2 + 1.0;
|
||||
std::vector<std::vector<double>> cost(rows, std::vector<double>(columns, unmatched));
|
||||
for (std::size_t i = 0; i < rows; ++i)
|
||||
for (std::size_t j = 0; j < real_columns; ++j)
|
||||
{
|
||||
cost[i][j] = rejected;
|
||||
const Eigen::Vector2d delta = detections[j].position - tracks[i].state.head<2>();
|
||||
if (delta.norm() > config.association_distance) continue;
|
||||
const Eigen::Matrix2d s = tracks[i].covariance.topLeftCorner<2,2>() + detections[j].covariance;
|
||||
Eigen::LDLT<Eigen::Matrix2d> ldlt(s);
|
||||
if (ldlt.info() != Eigen::Success || !ldlt.isPositive()) continue;
|
||||
const double d2 = delta.dot(ldlt.solve(delta));
|
||||
if (std::isfinite(d2) && d2 >= 0 && d2 <= config.gate_chi2) cost[i][j] = d2;
|
||||
}
|
||||
// Rectangular Hungarian assignment with deterministic row/column tie-breaking.
|
||||
std::vector<double> u(rows + 1), v(columns + 1);
|
||||
std::vector<std::size_t> p(columns + 1), way(columns + 1);
|
||||
for (std::size_t i = 1; i <= rows; ++i)
|
||||
{
|
||||
p[0] = i;
|
||||
std::size_t j0 = 0;
|
||||
std::vector<double> minimum(columns + 1, std::numeric_limits<double>::infinity());
|
||||
std::vector<bool> used(columns + 1, false);
|
||||
do
|
||||
{
|
||||
used[j0] = true;
|
||||
const std::size_t i0 = p[j0];
|
||||
std::size_t j1 = 0;
|
||||
double delta = std::numeric_limits<double>::infinity();
|
||||
for (std::size_t j = 1; j <= columns; ++j)
|
||||
{
|
||||
if (used[j]) continue;
|
||||
const double current = cost[i0-1][j-1] - u[i0] - v[j];
|
||||
if (current < minimum[j]) { minimum[j] = current; way[j] = j0; }
|
||||
if (minimum[j] < delta) { delta = minimum[j]; j1 = j; }
|
||||
}
|
||||
for (std::size_t j = 0; j <= columns; ++j)
|
||||
if (used[j]) { u[p[j]] += delta; v[j] -= delta; }
|
||||
else minimum[j] -= delta;
|
||||
j0 = j1;
|
||||
} while (p[j0] != 0);
|
||||
do { const auto j1 = way[j0]; p[j0] = p[j1]; j0 = j1; } while (j0 != 0);
|
||||
}
|
||||
for (std::size_t j = 1; j <= real_columns; ++j)
|
||||
if (p[j] && cost[p[j]-1][j-1] < unmatched) result[p[j]-1] = static_cast<int>(j-1);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
67
robot_dynamic_obstacle_tracker/src/detection_fusion.cpp
Normal file
67
robot_dynamic_obstacle_tracker/src/detection_fusion.cpp
Normal file
@@ -0,0 +1,67 @@
|
||||
#include <robot_dynamic_obstacle_tracker/detection_fusion.h>
|
||||
#include <robot_dynamic_obstacle_tracker/kalman_track.h>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <set>
|
||||
|
||||
namespace robot_dynamic_obstacle_tracker
|
||||
{
|
||||
ProcessingResult fuseDetections(const std::vector<DetectionFrame>& frames, Stamp stamp,
|
||||
const TrackerConfig& config, std::vector<Detection>& out)
|
||||
{
|
||||
out.clear();
|
||||
ProcessingResult result;
|
||||
std::set<std::size_t> source_ids;
|
||||
for (const auto& frame : frames)
|
||||
if (frame.source >= config.sources.size() || !source_ids.insert(frame.source).second ||
|
||||
!std::all_of(frame.detections.begin(), frame.detections.end(), [&](const Detection& d) {
|
||||
return d.sources.size() == 1 && d.sources.front() == frame.source;
|
||||
}))
|
||||
return {Health::kInvalidInput, "fusion requires one frame per known source"};
|
||||
for (const auto& frame : frames)
|
||||
{
|
||||
const double dt = secondsBetween(stamp, frame.stamp);
|
||||
if (dt < 0 || dt > config.fusion_window + 1e-9)
|
||||
return {Health::kOutOfOrder, "fusion batch exceeds timestamp window"};
|
||||
for (const auto& original : frame.detections)
|
||||
{
|
||||
if (!validDetection(original) || original.stamp != frame.stamp)
|
||||
return {Health::kInvalidInput, "invalid detection in fusion"};
|
||||
Detection d = original;
|
||||
d.observed_stamp = original.observed_stamp ? original.observed_stamp : original.stamp;
|
||||
// No velocity is available yet: bound inter-sensor motion rather than pretend simultaneous.
|
||||
const double motion_bound = config.fusion_max_speed * dt;
|
||||
d.radius += motion_bound;
|
||||
d.covariance += Eigen::Matrix2d::Identity() * motion_bound * motion_bound;
|
||||
d.stamp = stamp;
|
||||
int best = -1;
|
||||
double distance = config.fusion_distance;
|
||||
for (std::size_t j = 0; j < out.size(); ++j)
|
||||
{
|
||||
bool shared_source = false;
|
||||
for (auto source : d.sources)
|
||||
shared_source |= std::find(out[j].sources.begin(), out[j].sources.end(), source) != out[j].sources.end();
|
||||
const double candidate = (d.position - out[j].position).norm();
|
||||
if (!shared_source && candidate < distance) { distance = candidate; best = static_cast<int>(j); }
|
||||
}
|
||||
if (best >= 0)
|
||||
{
|
||||
auto& merged = out[static_cast<std::size_t>(best)];
|
||||
const Eigen::Vector2d center = 0.5 * (merged.position + d.position);
|
||||
merged.radius = std::max(merged.radius + (merged.position - center).norm(),
|
||||
d.radius + (d.position - center).norm());
|
||||
// Keep the larger isotropic uncertainty: the two scans can have correlated pose error.
|
||||
const double variance = std::max(merged.covariance.trace(), d.covariance.trace()) +
|
||||
(merged.position - d.position).squaredNorm();
|
||||
merged.covariance = Eigen::Matrix2d::Identity() * variance;
|
||||
merged.position = center;
|
||||
merged.observed_stamp = std::max(merged.observed_stamp, d.observed_stamp);
|
||||
merged.sources.insert(merged.sources.end(), d.sources.begin(), d.sources.end());
|
||||
}
|
||||
else if (out.size() < config.max_detections) out.push_back(std::move(d));
|
||||
else { result.status = Health::kOverflow; result.reason = "fused detections exceed capacity"; }
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
52
robot_dynamic_obstacle_tracker/src/kalman_track.cpp
Normal file
52
robot_dynamic_obstacle_tracker/src/kalman_track.cpp
Normal file
@@ -0,0 +1,52 @@
|
||||
#include <robot_dynamic_obstacle_tracker/kalman_track.h>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <Eigen/Cholesky>
|
||||
|
||||
namespace robot_dynamic_obstacle_tracker
|
||||
{
|
||||
bool validDetection(const Detection& d)
|
||||
{
|
||||
if (!d.position.allFinite() || !d.covariance.allFinite() || d.stamp <= 0 ||
|
||||
!std::isfinite(d.radius) || d.radius <= 0 || d.sources.empty() ||
|
||||
d.observed_stamp < 0 || d.observed_stamp > d.stamp ||
|
||||
!d.covariance.isApprox(d.covariance.transpose(), 1e-9)) return false;
|
||||
return Eigen::LLT<Eigen::Matrix2d>(d.covariance).info() == Eigen::Success;
|
||||
}
|
||||
bool predictTrack(Track& t, Stamp stamp, double noise)
|
||||
{
|
||||
const double dt = secondsBetween(stamp, t.state_stamp);
|
||||
if (dt < 0 || !std::isfinite(dt) || noise <= 0 || !std::isfinite(noise)) return false;
|
||||
Eigen::Matrix4d f = Eigen::Matrix4d::Identity();
|
||||
f(0,2) = dt; f(1,3) = dt;
|
||||
Eigen::Matrix4d q = Eigen::Matrix4d::Zero();
|
||||
for (int i = 0; i < 2; ++i)
|
||||
{
|
||||
q(i,i) = noise * dt * dt * dt / 3.0;
|
||||
q(i,i+2) = q(i+2,i) = noise * dt * dt / 2.0;
|
||||
q(i+2,i+2) = noise * dt;
|
||||
}
|
||||
t.state = f * t.state;
|
||||
t.covariance = f * t.covariance * f.transpose() + q;
|
||||
t.covariance = (0.5 * (t.covariance + t.covariance.transpose())).eval();
|
||||
t.state_stamp = stamp;
|
||||
return t.state.allFinite() && t.covariance.allFinite();
|
||||
}
|
||||
bool correctTrack(Track& t, const Detection& d)
|
||||
{
|
||||
if (!validDetection(d) || d.stamp != t.state_stamp) return false;
|
||||
const Eigen::Matrix2d s = t.covariance.topLeftCorner<2,2>() + d.covariance;
|
||||
Eigen::LDLT<Eigen::Matrix2d> ldlt(s);
|
||||
if (ldlt.info() != Eigen::Success || !ldlt.isPositive()) return false;
|
||||
const Eigen::Matrix<double,4,2> k =
|
||||
ldlt.solve(t.covariance.leftCols<2>().transpose()).transpose();
|
||||
t.state += k * (d.position - t.state.head<2>());
|
||||
Eigen::Matrix4d residual = Eigen::Matrix4d::Identity();
|
||||
residual.leftCols<2>() -= k;
|
||||
t.covariance = residual * t.covariance * residual.transpose() + k * d.covariance * k.transpose();
|
||||
t.covariance = (0.5 * (t.covariance + t.covariance.transpose())).eval();
|
||||
// Cover the actual observation even when the filter center differs from the measured center.
|
||||
t.radius = std::max(t.radius, d.radius + (d.position - t.state.head<2>()).norm());
|
||||
return t.state.allFinite() && t.covariance.allFinite();
|
||||
}
|
||||
}
|
||||
74
robot_dynamic_obstacle_tracker/src/scan_clusterer.cpp
Normal file
74
robot_dynamic_obstacle_tracker/src/scan_clusterer.cpp
Normal file
@@ -0,0 +1,74 @@
|
||||
#include <robot_dynamic_obstacle_tracker/scan_clusterer.h>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace robot_dynamic_obstacle_tracker
|
||||
{
|
||||
ScanClusterer::ScanClusterer(const TrackerConfig& config) : config_(config)
|
||||
{
|
||||
std::string error;
|
||||
if (!config_.validate(error)) throw std::invalid_argument(error);
|
||||
}
|
||||
ProcessingResult ScanClusterer::detect(const RawScan& scan, const PlanarTransform& transform,
|
||||
std::size_t source, std::vector<Detection>& out) const
|
||||
{
|
||||
out.clear();
|
||||
ProcessingResult result;
|
||||
if (scan.ranges.size() > config_.max_scan_points)
|
||||
return {Health::kOverflow, "scan exceeds max_scan_points"};
|
||||
if (scan.stamp <= 0 || scan.frame.empty() || scan.ranges.empty() ||
|
||||
!std::isfinite(scan.angle_min) || !std::isfinite(scan.angle_increment) ||
|
||||
std::abs(scan.angle_increment) < 1e-9 || std::abs(scan.angle_increment) > 3.141593 ||
|
||||
!std::isfinite(scan.range_min) || !std::isfinite(scan.range_max) ||
|
||||
scan.range_min < 0 || scan.range_max <= scan.range_min ||
|
||||
!std::isfinite(scan.time_increment) || scan.time_increment < 0 ||
|
||||
!std::isfinite(scan.scan_time) || scan.scan_time < 0 || !transform.valid())
|
||||
return {Health::kInvalidInput, "invalid scan geometry, stamp, frame or transform"};
|
||||
|
||||
std::vector<Eigen::Vector2d> cluster;
|
||||
cluster.reserve(scan.ranges.size());
|
||||
auto flush = [&]() {
|
||||
if (cluster.empty()) return;
|
||||
if (cluster.size() < config_.min_cluster_points) { ++result.small_clusters; cluster.clear(); return; }
|
||||
Detection detection;
|
||||
for (const auto& p : cluster) detection.position += p;
|
||||
detection.position /= static_cast<double>(cluster.size());
|
||||
double visible_radius = 0;
|
||||
for (const auto& p : cluster) visible_radius = std::max(visible_radius, (p - detection.position).norm());
|
||||
detection.radius = std::max(config_.min_radius, visible_radius + config_.extent_padding);
|
||||
detection.covariance = Eigen::Matrix2d::Identity() * config_.measurement_sigma * config_.measurement_sigma;
|
||||
detection.stamp = scan.stamp;
|
||||
detection.sources = {source};
|
||||
if (out.size() < config_.max_detections) out.push_back(std::move(detection));
|
||||
else { result.status = Health::kOverflow; result.reason = "clusters exceed max_detections"; }
|
||||
cluster.clear();
|
||||
};
|
||||
double previous_range = 0;
|
||||
std::size_t valid_returns = 0, no_returns = 0;
|
||||
for (std::size_t i = 0; i < scan.ranges.size(); ++i)
|
||||
{
|
||||
const double r = scan.ranges[i];
|
||||
if (!std::isfinite(r) || r < scan.range_min || r > scan.range_max)
|
||||
{
|
||||
if ((std::isinf(r) && r > 0) || (std::isfinite(r) && r > scan.range_max)) ++no_returns;
|
||||
else ++result.rejected_points;
|
||||
flush(); // A missing beam is a real break, not a point to skip before joining neighbours.
|
||||
continue;
|
||||
}
|
||||
++valid_returns;
|
||||
const double angle = scan.angle_min + static_cast<double>(i) * scan.angle_increment;
|
||||
const Eigen::Vector2d point = transform.apply({r * std::cos(angle), r * std::sin(angle)});
|
||||
const double gap = config_.cluster_gap + config_.cluster_angle_scale *
|
||||
std::min(r, previous_range) * std::abs(scan.angle_increment);
|
||||
if (!cluster.empty() && (point - cluster.back()).norm() > gap) flush();
|
||||
cluster.push_back(point);
|
||||
previous_range = r;
|
||||
}
|
||||
flush();
|
||||
// All +Inf is a valid empty observation; all NaN/zero/negative is a broken scan.
|
||||
if (valid_returns == 0 && no_returns == 0)
|
||||
return {Health::kInvalidInput, "scan contains no valid returns or no-return rays", result.rejected_points};
|
||||
return result;
|
||||
}
|
||||
}
|
||||
92
robot_dynamic_obstacle_tracker/src/sensor_ports_input.cpp
Normal file
92
robot_dynamic_obstacle_tracker/src/sensor_ports_input.cpp
Normal file
@@ -0,0 +1,92 @@
|
||||
#include <robot_dynamic_obstacle_tracker/sensor_ports_input.h>
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
#include <Eigen/Geometry>
|
||||
#include <boost/pointer_cast.hpp>
|
||||
#include <robot/time.h>
|
||||
#include <robot_sensor_msgs/LaserScan.h>
|
||||
#include <robot_sensor_ports/sensor_reader.h>
|
||||
#include <tf3/buffer_core.h>
|
||||
|
||||
namespace robot_dynamic_obstacle_tracker
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr const char* kLaserType = "robot_sensor_msgs/LaserScan";
|
||||
Stamp stampOf(const robot::Time& time)
|
||||
{ return static_cast<Stamp>(time.sec) * 1000000000LL + time.nsec; }
|
||||
|
||||
class SensorPortsInput final : public TrackerInput
|
||||
{
|
||||
public:
|
||||
SensorPortsInput(const robot_sensor_ports::SensorReader& reader,
|
||||
std::shared_ptr<const tf3::BufferCore> tf, std::function<Stamp()> now,
|
||||
std::size_t max_points)
|
||||
: reader_(reader), tf_(std::move(tf)), now_(std::move(now)), max_points_(max_points) {}
|
||||
|
||||
bool describeSource(const std::string& topic, double& age, std::string& error) const override
|
||||
{
|
||||
robot_sensor_ports::SensorInfo info;
|
||||
if (!reader_.has(kLaserType, topic) || !reader_.describe(topic, info) || info.data_type != kLaserType)
|
||||
{ error = "source is not configured as robot_sensor_msgs/LaserScan"; return false; }
|
||||
age = info.max_age; error.clear(); return true;
|
||||
}
|
||||
ReadStatus readLatest(const std::string& topic, std::uint64_t& cursor,
|
||||
RawScan& out, std::string& error) override
|
||||
{
|
||||
robot_sensor_ports::SensorSample sample;
|
||||
if (!reader_.latestErased(kLaserType, topic, cursor, sample)) return ReadStatus::kNoData;
|
||||
if (!sample.data) { error = "null sensor payload"; return ReadStatus::kError; }
|
||||
const auto scan = boost::static_pointer_cast<const robot_sensor_msgs::LaserScan>(sample.data);
|
||||
if (stampOf(scan->header.stamp) != stampOf(sample.stamp))
|
||||
{ error = "scan header stamp differs from SensorStore stamp"; return ReadStatus::kError; }
|
||||
if (scan->ranges.size() > max_points_)
|
||||
{ error = "scan exceeds adapter max_scan_points"; return ReadStatus::kError; }
|
||||
out.stamp = stampOf(sample.stamp); out.sequence = sample.sequence; out.frame = scan->header.frame_id;
|
||||
out.angle_min = scan->angle_min; out.angle_increment = scan->angle_increment;
|
||||
out.range_min = scan->range_min; out.range_max = scan->range_max;
|
||||
out.time_increment = scan->time_increment; out.scan_time = scan->scan_time;
|
||||
out.ranges = scan->ranges;
|
||||
error.clear(); return ReadStatus::kScan;
|
||||
}
|
||||
bool lookupTransform(const std::string& target, const std::string& source, Stamp stamp,
|
||||
PlanarTransform& out, std::string& error) override
|
||||
{
|
||||
if (stamp <= 0) { error = "TF requires a nonzero measurement stamp"; return false; }
|
||||
try
|
||||
{
|
||||
// Split integer nanoseconds directly: double round trips can cause extrapolation at a boundary.
|
||||
const auto transform = tf_->lookupTransform(target, source,
|
||||
tf3::Time(static_cast<std::uint32_t>(stamp / 1000000000LL),
|
||||
static_cast<std::uint32_t>(stamp % 1000000000LL)));
|
||||
const auto& rotation = transform.transform.rotation;
|
||||
Eigen::Quaterniond q(rotation.w, rotation.x, rotation.y, rotation.z);
|
||||
if (!q.coeffs().allFinite() || std::abs(q.norm() - 1.0) > 1e-3)
|
||||
{ error = "TF quaternion is not normalized"; return false; }
|
||||
const Eigen::Matrix3d r = q.normalized().toRotationMatrix();
|
||||
if (std::abs(std::abs(r(2,2)) - 1.0) > 1e-6)
|
||||
{ error = "laser plane is tilted; planar tracker cannot project this TF"; return false; }
|
||||
out.linear = r.topLeftCorner<2,2>();
|
||||
out.translation = {transform.transform.translation.x, transform.transform.translation.y};
|
||||
if (!out.valid()) { error = "nonfinite/invalid planar TF"; return false; }
|
||||
error.clear(); return true;
|
||||
}
|
||||
catch (const std::exception& ex) { error = ex.what(); return false; }
|
||||
}
|
||||
Stamp measurementNow() const override { return now_(); }
|
||||
private:
|
||||
const robot_sensor_ports::SensorReader& reader_;
|
||||
std::shared_ptr<const tf3::BufferCore> tf_;
|
||||
std::function<Stamp()> now_;
|
||||
std::size_t max_points_;
|
||||
};
|
||||
}
|
||||
std::shared_ptr<TrackerInput> makeSensorPortsInput(
|
||||
const robot_sensor_ports::SensorReader& reader, std::shared_ptr<const tf3::BufferCore> tf,
|
||||
std::function<Stamp()> now, std::size_t max_scan_points)
|
||||
{
|
||||
if (!tf || max_scan_points == 0) throw std::invalid_argument("TF and max_scan_points are required");
|
||||
if (!now) now = [] { return stampOf(robot::Time::now()); };
|
||||
return std::make_shared<SensorPortsInput>(reader, std::move(tf), std::move(now), max_scan_points);
|
||||
}
|
||||
}
|
||||
74
robot_dynamic_obstacle_tracker/src/tracker_config.cpp
Normal file
74
robot_dynamic_obstacle_tracker/src/tracker_config.cpp
Normal file
@@ -0,0 +1,74 @@
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_config.h>
|
||||
#include <cmath>
|
||||
#include <set>
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_types.h>
|
||||
|
||||
namespace robot_dynamic_obstacle_tracker
|
||||
{
|
||||
bool TrackerConfig::validate(std::string& error) const
|
||||
{
|
||||
error.clear();
|
||||
const auto positive = [&](double v, const char* name) {
|
||||
if (!std::isfinite(v) || v <= 0.0) { error = std::string(name) + " must be finite and > 0"; return false; }
|
||||
return true;
|
||||
};
|
||||
if (tracking_frame.empty() || sources.empty() || sources.size() > 8)
|
||||
{ error = "tracking_frame and 1..8 sources are required"; return false; }
|
||||
std::set<std::string> names;
|
||||
bool required = false;
|
||||
for (const auto& source : sources)
|
||||
{
|
||||
if (source.topic.empty() || !names.insert(source.topic).second)
|
||||
{ error = "source topics must be nonempty and unique"; return false; }
|
||||
if (!positive(source.max_age, "source.max_age")) return false;
|
||||
required |= source.required;
|
||||
}
|
||||
if (!required) { error = "at least one source must be required"; return false; }
|
||||
#define CHECK_POSITIVE(field) if (!positive(field, #field)) return false
|
||||
CHECK_POSITIVE(poll_period); CHECK_POSITIVE(tf_wait); CHECK_POSITIVE(fusion_window);
|
||||
CHECK_POSITIVE(fusion_wait); CHECK_POSITIVE(fusion_distance); CHECK_POSITIVE(fusion_max_speed);
|
||||
CHECK_POSITIVE(future_tolerance); CHECK_POSITIVE(clock_jump_reset);
|
||||
CHECK_POSITIVE(cluster_gap); CHECK_POSITIVE(cluster_angle_scale);
|
||||
CHECK_POSITIVE(min_radius); CHECK_POSITIVE(measurement_sigma);
|
||||
CHECK_POSITIVE(initial_velocity_sigma); CHECK_POSITIVE(acceleration_noise);
|
||||
CHECK_POSITIVE(gate_chi2); CHECK_POSITIVE(association_distance);
|
||||
CHECK_POSITIVE(tentative_timeout); CHECK_POSITIVE(track_timeout); CHECK_POSITIVE(max_prediction);
|
||||
CHECK_POSITIVE(moving_speed); CHECK_POSITIVE(stationary_speed); CHECK_POSITIVE(motion_velocity_sigma);
|
||||
#undef CHECK_POSITIVE
|
||||
if (!std::isfinite(extent_padding) || extent_padding < 0.0)
|
||||
{ error = "extent_padding must be finite and >= 0"; return false; }
|
||||
if (max_scan_points < 3 || max_scan_points > 1000000 || min_cluster_points < 1 ||
|
||||
min_cluster_points > max_scan_points || max_detections < 1 || max_detections > 512 ||
|
||||
max_tracks < 1 || max_tracks > 512 || confirmation_hits < 1 || motion_hysteresis_hits < 1)
|
||||
{ error = "invalid count/capacity (detections/tracks must be 1..512)"; return false; }
|
||||
if (stationary_speed >= moving_speed || tentative_timeout > track_timeout ||
|
||||
max_prediction > track_timeout || fusion_wait > tf_wait || poll_period > tf_wait)
|
||||
{ error = "inconsistent motion thresholds, retention, prediction or wait periods"; return false; }
|
||||
for (const auto& source : sources)
|
||||
if (tf_wait >= source.max_age || fusion_wait >= source.max_age)
|
||||
{ error = "tf_wait/fusion_wait must be shorter than source.max_age"; return false; }
|
||||
return true;
|
||||
}
|
||||
|
||||
bool PlanarTransform::valid() const
|
||||
{
|
||||
return linear.allFinite() && translation.allFinite() &&
|
||||
(linear.transpose() * linear - Eigen::Matrix2d::Identity()).norm() < 1e-5;
|
||||
}
|
||||
const char* healthName(Health h) noexcept
|
||||
{
|
||||
switch (h)
|
||||
{
|
||||
case Health::kWarmingUp: return "warming_up";
|
||||
case Health::kValid: return "valid";
|
||||
case Health::kStale: return "stale";
|
||||
case Health::kTfError: return "tf_error";
|
||||
case Health::kInvalidInput: return "invalid_input";
|
||||
case Health::kOutOfOrder: return "out_of_order";
|
||||
case Health::kOverflow: return "overflow";
|
||||
case Health::kFault: return "fault";
|
||||
case Health::kStopped: return "stopped";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
58
robot_dynamic_obstacle_tracker/src/tracker_config_yaml.cpp
Normal file
58
robot_dynamic_obstacle_tracker/src/tracker_config_yaml.cpp
Normal file
@@ -0,0 +1,58 @@
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_config.h>
|
||||
#include <set>
|
||||
#include <stdexcept>
|
||||
#include <yaml-cpp/yaml.h>
|
||||
|
||||
namespace robot_dynamic_obstacle_tracker
|
||||
{
|
||||
bool loadTrackerConfig(const std::string& path, TrackerConfig& out, std::string& error)
|
||||
{
|
||||
try
|
||||
{
|
||||
const YAML::Node root = YAML::LoadFile(path);
|
||||
if (!root.IsMap()) throw std::runtime_error("tracker config must be a mapping");
|
||||
TrackerConfig next;
|
||||
std::set<std::string> seen;
|
||||
for (const auto& entry : root)
|
||||
{
|
||||
const auto key = entry.first.as<std::string>();
|
||||
if (!seen.insert(key).second) throw std::runtime_error("duplicate key: " + key);
|
||||
const auto& value = entry.second;
|
||||
#define LOAD_FIELD(field) if (key == #field) { next.field = value.as<decltype(next.field)>(); continue; }
|
||||
LOAD_FIELD(tracking_frame)
|
||||
LOAD_FIELD(poll_period) LOAD_FIELD(tf_wait) LOAD_FIELD(fusion_window) LOAD_FIELD(fusion_wait)
|
||||
LOAD_FIELD(fusion_distance) LOAD_FIELD(fusion_max_speed) LOAD_FIELD(future_tolerance)
|
||||
LOAD_FIELD(clock_jump_reset) LOAD_FIELD(max_scan_points) LOAD_FIELD(max_detections) LOAD_FIELD(max_tracks)
|
||||
LOAD_FIELD(min_cluster_points) LOAD_FIELD(cluster_gap) LOAD_FIELD(cluster_angle_scale)
|
||||
LOAD_FIELD(min_radius) LOAD_FIELD(extent_padding) LOAD_FIELD(measurement_sigma)
|
||||
LOAD_FIELD(initial_velocity_sigma) LOAD_FIELD(acceleration_noise) LOAD_FIELD(gate_chi2)
|
||||
LOAD_FIELD(association_distance) LOAD_FIELD(confirmation_hits) LOAD_FIELD(motion_hysteresis_hits)
|
||||
LOAD_FIELD(tentative_timeout) LOAD_FIELD(track_timeout) LOAD_FIELD(max_prediction)
|
||||
LOAD_FIELD(moving_speed) LOAD_FIELD(stationary_speed) LOAD_FIELD(motion_velocity_sigma)
|
||||
#undef LOAD_FIELD
|
||||
if (key != "sources") throw std::runtime_error("unknown key: " + key);
|
||||
if (!value.IsSequence()) throw std::runtime_error("sources must be a sequence");
|
||||
next.sources.clear();
|
||||
for (const auto& source : value)
|
||||
{
|
||||
if (!source.IsMap()) throw std::runtime_error("source must be a mapping");
|
||||
std::set<std::string> source_keys;
|
||||
SourceConfig config;
|
||||
for (const auto& field : source)
|
||||
{
|
||||
const auto name = field.first.as<std::string>();
|
||||
if (!source_keys.insert(name).second) throw std::runtime_error("duplicate source key: " + name);
|
||||
if (name == "topic") config.topic = field.second.as<std::string>();
|
||||
else if (name == "required") config.required = field.second.as<bool>();
|
||||
else if (name == "max_age") config.max_age = field.second.as<double>();
|
||||
else throw std::runtime_error("unknown source key: " + name);
|
||||
}
|
||||
next.sources.push_back(std::move(config));
|
||||
}
|
||||
}
|
||||
if (!next.validate(error)) return false;
|
||||
out = std::move(next); error.clear(); return true;
|
||||
}
|
||||
catch (const std::exception& ex) { error = ex.what(); return false; }
|
||||
}
|
||||
}
|
||||
143
robot_dynamic_obstacle_tracker/src/tracker_core.cpp
Normal file
143
robot_dynamic_obstacle_tracker/src/tracker_core.cpp
Normal file
@@ -0,0 +1,143 @@
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_core.h>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
#include <set>
|
||||
#include <robot_dynamic_obstacle_tracker/data_association.h>
|
||||
#include <robot_dynamic_obstacle_tracker/kalman_track.h>
|
||||
|
||||
namespace robot_dynamic_obstacle_tracker
|
||||
{
|
||||
TrackerCore::TrackerCore(const TrackerConfig& config) : config_(config)
|
||||
{
|
||||
std::string error;
|
||||
if (!config.validate(error)) throw std::invalid_argument(error);
|
||||
tracks_.reserve(config.max_tracks);
|
||||
}
|
||||
void TrackerCore::reset(std::uint64_t session)
|
||||
{
|
||||
tracks_.clear(); session_id_ = session; next_id_ = 1; last_update_ = 0;
|
||||
}
|
||||
void TrackerCore::expire(Stamp now)
|
||||
{
|
||||
tracks_.erase(std::remove_if(tracks_.begin(), tracks_.end(), [&](const Record& r) {
|
||||
const double timeout = r.track.hit_count < config_.confirmation_hits ?
|
||||
config_.tentative_timeout : config_.track_timeout;
|
||||
return secondsBetween(now, r.track.last_observed_stamp) > timeout;
|
||||
}), tracks_.end());
|
||||
}
|
||||
void TrackerCore::classify(Record& r)
|
||||
{
|
||||
if (r.track.hit_count < config_.confirmation_hits ||
|
||||
r.track.covariance.bottomRightCorner<2,2>().diagonal().maxCoeff() >
|
||||
config_.motion_velocity_sigma * config_.motion_velocity_sigma)
|
||||
{ r.moving_hits = r.stationary_hits = 0; r.track.motion = MotionClass::kUnknown; return; }
|
||||
const double speed = r.track.state.tail<2>().norm();
|
||||
if (speed >= config_.moving_speed) { ++r.moving_hits; r.stationary_hits = 0; }
|
||||
else if (speed <= config_.stationary_speed) { ++r.stationary_hits; r.moving_hits = 0; }
|
||||
else { r.stationary_hits = r.moving_hits = 0; }
|
||||
if (r.moving_hits >= config_.motion_hysteresis_hits) r.track.motion = MotionClass::kMoving;
|
||||
if (r.stationary_hits >= config_.motion_hysteresis_hits) r.track.motion = MotionClass::kStationary;
|
||||
}
|
||||
ProcessingResult TrackerCore::update(Stamp stamp, const std::vector<Detection>& detections,
|
||||
const std::vector<std::size_t>& sources)
|
||||
{
|
||||
if (stamp <= 0 || sources.empty()) return {Health::kInvalidInput, "invalid batch stamp/sources"};
|
||||
if (last_update_ && stamp <= last_update_) return {Health::kOutOfOrder, "batch is not newer than core state"};
|
||||
if (detections.size() > config_.max_detections) return {Health::kOverflow, "too many detections"};
|
||||
const std::set<std::size_t> source_set(sources.begin(), sources.end());
|
||||
if (source_set.size() != sources.size() || *source_set.rbegin() >= config_.sources.size())
|
||||
return {Health::kInvalidInput, "unknown or duplicate batch source"};
|
||||
for (const auto& d : detections)
|
||||
{
|
||||
const std::set<std::size_t> detection_sources(d.sources.begin(), d.sources.end());
|
||||
if (!validDetection(d) || d.stamp != stamp || detection_sources.size() != d.sources.size() ||
|
||||
!std::all_of(d.sources.begin(), d.sources.end(), [&](std::size_t source) {
|
||||
return source_set.count(source) != 0;
|
||||
}))
|
||||
return {Health::kInvalidInput, "invalid detection, covariance or batch stamp"};
|
||||
}
|
||||
expire(stamp);
|
||||
// Work on a copy so numerical failure cannot partially advance the live state.
|
||||
auto next = tracks_;
|
||||
std::vector<Track> predicted;
|
||||
predicted.reserve(next.size());
|
||||
for (auto& record : next)
|
||||
{
|
||||
if (!predictTrack(record.track, stamp, config_.acceleration_noise))
|
||||
return {Health::kFault, "Kalman prediction failed"};
|
||||
predicted.push_back(record.track);
|
||||
}
|
||||
const auto assignment = associateDetections(predicted, detections, config_);
|
||||
std::vector<bool> used(detections.size(), false);
|
||||
for (std::size_t i = 0; i < next.size(); ++i)
|
||||
{
|
||||
auto& r = next[i];
|
||||
if (assignment[i] >= 0)
|
||||
{
|
||||
const auto index = static_cast<std::size_t>(assignment[i]);
|
||||
if (!correctTrack(r.track, detections[index])) return {Health::kFault, "Kalman correction failed"};
|
||||
used[index] = true;
|
||||
r.track.last_observed_stamp = std::max(r.track.last_observed_stamp,
|
||||
detections[index].observed_stamp ? detections[index].observed_stamp : stamp);
|
||||
r.track.observed_sources = detections[index].sources;
|
||||
++r.track.hit_count;
|
||||
r.track.miss_count = 0;
|
||||
r.track.lifecycle = r.track.hit_count >= config_.confirmation_hits ?
|
||||
TrackLifecycle::kConfirmed : TrackLifecycle::kTentative;
|
||||
classify(r);
|
||||
}
|
||||
else
|
||||
{
|
||||
const bool covered = std::any_of(sources.begin(), sources.end(), [&](std::size_t source) {
|
||||
return std::find(r.track.observed_sources.begin(), r.track.observed_sources.end(), source) !=
|
||||
r.track.observed_sources.end();
|
||||
});
|
||||
if (covered) { ++r.track.miss_count; r.moving_hits = r.stationary_hits = 0; }
|
||||
if (r.track.hit_count >= config_.confirmation_hits) r.track.lifecycle = TrackLifecycle::kCoasting;
|
||||
}
|
||||
}
|
||||
ProcessingResult result;
|
||||
for (std::size_t j = 0; j < detections.size(); ++j)
|
||||
{
|
||||
if (used[j]) continue;
|
||||
if (next.size() >= config_.max_tracks)
|
||||
{ result = {Health::kOverflow, "track capacity exceeded; unrepresented detections remain"}; continue; }
|
||||
Record r;
|
||||
const auto& d = detections[j];
|
||||
r.track.session_id = session_id_; r.track.track_id = next_id_++;
|
||||
r.track.state.head<2>() = d.position;
|
||||
r.track.covariance.setZero();
|
||||
r.track.covariance.topLeftCorner<2,2>() = d.covariance;
|
||||
r.track.covariance.bottomRightCorner<2,2>() =
|
||||
Eigen::Matrix2d::Identity() * config_.initial_velocity_sigma * config_.initial_velocity_sigma;
|
||||
r.track.radius = d.radius; r.track.state_stamp = stamp;
|
||||
r.track.last_observed_stamp = d.observed_stamp ? d.observed_stamp : stamp;
|
||||
r.track.observed_sources = d.sources; r.track.hit_count = 1;
|
||||
if (config_.confirmation_hits == 1) r.track.lifecycle = TrackLifecycle::kConfirmed;
|
||||
next.push_back(std::move(r));
|
||||
}
|
||||
tracks_ = std::move(next);
|
||||
last_update_ = stamp;
|
||||
return result;
|
||||
}
|
||||
std::vector<Track> TrackerCore::predictedTracks(Stamp now) const
|
||||
{
|
||||
std::vector<Track> out;
|
||||
out.reserve(tracks_.size());
|
||||
for (const auto& record : tracks_)
|
||||
{
|
||||
auto track = record.track;
|
||||
const double age = secondsBetween(now, track.last_observed_stamp);
|
||||
const double timeout = track.hit_count < config_.confirmation_hits ? config_.tentative_timeout : config_.track_timeout;
|
||||
if (age > timeout) continue;
|
||||
const Stamp limit = track.state_stamp + static_cast<Stamp>(config_.max_prediction * 1e9);
|
||||
const Stamp at = std::max(track.state_stamp, std::min(now, limit));
|
||||
if (!predictTrack(track, at, config_.acceleration_noise)) continue;
|
||||
if (now > track.last_observed_stamp && track.hit_count >= config_.confirmation_hits)
|
||||
track.lifecycle = TrackLifecycle::kCoasting;
|
||||
out.push_back(std::move(track));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
350
robot_dynamic_obstacle_tracker/src/tracker_service.cpp
Normal file
350
robot_dynamic_obstacle_tracker/src/tracker_service.cpp
Normal file
@@ -0,0 +1,350 @@
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_service.h>
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cmath>
|
||||
#include <condition_variable>
|
||||
#include <exception>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
#include <robot_dynamic_obstacle_tracker/detection_fusion.h>
|
||||
#include <robot_dynamic_obstacle_tracker/scan_clusterer.h>
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_core.h>
|
||||
|
||||
namespace robot_dynamic_obstacle_tracker
|
||||
{
|
||||
namespace
|
||||
{
|
||||
std::atomic<std::uint64_t> next_session{1}; // Identity only, never algorithm state.
|
||||
double elapsed(SteadyTime now, SteadyTime before)
|
||||
{ return std::chrono::duration<double>(now - before).count(); }
|
||||
int priority(Health status)
|
||||
{
|
||||
switch (status)
|
||||
{
|
||||
case Health::kFault: return 9;
|
||||
case Health::kOverflow: return 8;
|
||||
case Health::kInvalidInput: return 7;
|
||||
case Health::kOutOfOrder: return 6;
|
||||
case Health::kTfError: return 5;
|
||||
case Health::kStale: return 4;
|
||||
case Health::kWarmingUp: return 3;
|
||||
case Health::kStopped: return 2;
|
||||
case Health::kValid: return 0;
|
||||
}
|
||||
return 9;
|
||||
}
|
||||
}
|
||||
struct TrackerService::Impl
|
||||
{
|
||||
struct Source
|
||||
{
|
||||
SourceHealth health;
|
||||
double max_age = 0;
|
||||
std::uint64_t cursor = 0;
|
||||
Stamp last_seen_stamp = 0;
|
||||
std::optional<RawScan> pending;
|
||||
std::optional<DetectionFrame> ready;
|
||||
SteadyTime pending_since{}, ready_since{};
|
||||
};
|
||||
mutable std::mutex lifecycle_mutex;
|
||||
std::mutex wait_mutex;
|
||||
std::condition_variable wake;
|
||||
std::thread worker;
|
||||
std::atomic<bool> is_running{false}, stopping{false};
|
||||
bool configured = false;
|
||||
TrackerConfig config;
|
||||
TrackerDependencies dependencies;
|
||||
std::unique_ptr<ScanClusterer> clusterer;
|
||||
std::unique_ptr<TrackerCore> core;
|
||||
std::vector<Source> sources;
|
||||
std::shared_ptr<const TrackSnapshot> snapshot = std::make_shared<TrackSnapshot>();
|
||||
std::uint64_t session = 0, generation = 0, epoch = 0;
|
||||
Stamp last_now = 0;
|
||||
SteadyTime last_steady{}, started_at{}, last_success{};
|
||||
ProcessingResult batch_result;
|
||||
|
||||
void publish(Stamp now, SteadyTime steady, Health forced = Health::kValid, const std::string& reason = "")
|
||||
{
|
||||
auto next = std::make_shared<TrackSnapshot>();
|
||||
next->frame = config.tracking_frame;
|
||||
next->session_id = session; next->generation = ++generation; next->measurement_epoch = epoch;
|
||||
next->state_stamp = now; next->published_at = steady; next->last_success_steady_time = last_success;
|
||||
next->status = forced; next->reason = reason;
|
||||
if (forced == Health::kValid && priority(batch_result.status) > priority(next->status))
|
||||
{ next->status = batch_result.status; next->reason = batch_result.reason; }
|
||||
for (const auto& source : sources)
|
||||
{
|
||||
auto health = source.health;
|
||||
if (health.processed_count > 0 &&
|
||||
(secondsBetween(now, health.last_success_stamp) > source.max_age ||
|
||||
elapsed(steady, health.last_success_steady_time) > source.max_age))
|
||||
{ health.status = Health::kStale; health.reason = "last usable scan expired"; }
|
||||
else if (health.processed_count == 0 && elapsed(steady, started_at) > source.max_age &&
|
||||
health.status == Health::kWarmingUp)
|
||||
{ health.status = Health::kStale; health.reason = "no usable scan since start"; }
|
||||
if (forced == Health::kValid && health.required && priority(health.status) > priority(next->status))
|
||||
{ next->status = health.status; next->reason = health.topic + ": " + health.reason; }
|
||||
next->sources.push_back(std::move(health));
|
||||
}
|
||||
if (core) next->tracks = core->predictedTracks(now);
|
||||
std::atomic_store_explicit(&snapshot, std::shared_ptr<const TrackSnapshot>(next), std::memory_order_release);
|
||||
}
|
||||
|
||||
void reset(bool clear_cursors, Stamp now, SteadyTime steady)
|
||||
{
|
||||
session = next_session.fetch_add(1);
|
||||
core->reset(session);
|
||||
batch_result = {};
|
||||
started_at = steady; last_success = {}; last_now = now; last_steady = steady;
|
||||
for (std::size_t i = 0; i < sources.size(); ++i)
|
||||
{
|
||||
const auto cursor = clear_cursors ? 0 : sources[i].cursor;
|
||||
const double max_age = sources[i].max_age;
|
||||
sources[i] = Source{};
|
||||
sources[i].cursor = cursor; sources[i].max_age = max_age;
|
||||
sources[i].health.topic = config.sources[i].topic;
|
||||
sources[i].health.required = config.sources[i].required;
|
||||
}
|
||||
publish(now, steady, Health::kWarmingUp, "awaiting fresh observations");
|
||||
}
|
||||
|
||||
void collect(std::size_t index, Stamp now, SteadyTime steady)
|
||||
{
|
||||
auto& source = sources[index];
|
||||
if (source.ready) return; // Bounded one-frame queue; consume before requesting the next scan.
|
||||
auto& health = source.health;
|
||||
if (!source.pending)
|
||||
{
|
||||
RawScan scan;
|
||||
std::string error;
|
||||
const auto old_cursor = source.cursor;
|
||||
const auto status = dependencies.input->readLatest(health.topic, source.cursor, scan, error);
|
||||
if (status == ReadStatus::kError)
|
||||
{ health.status = Health::kInvalidInput; health.reason = error; return; }
|
||||
if (status == ReadStatus::kNoData) return;
|
||||
health.last_sequence = source.cursor;
|
||||
health.last_receive_steady_time = steady;
|
||||
health.last_measurement_stamp = scan.stamp;
|
||||
if (source.cursor <= old_cursor || scan.sequence != source.cursor)
|
||||
{ health.status = Health::kInvalidInput; health.reason = "nonadvancing or inconsistent scan sequence"; return; }
|
||||
if (old_cursor && source.cursor > old_cursor + 1) health.dropped_count += source.cursor - old_cursor - 1;
|
||||
if (scan.stamp <= 0 || secondsBetween(scan.stamp, now) > config.future_tolerance)
|
||||
{ health.status = Health::kInvalidInput; health.reason = "zero/negative/future scan stamp"; return; }
|
||||
if (secondsBetween(now, scan.stamp) > source.max_age)
|
||||
{ health.status = Health::kStale; health.reason = "received old measurement"; return; }
|
||||
if (source.last_seen_stamp && scan.stamp <= source.last_seen_stamp)
|
||||
{ health.status = Health::kOutOfOrder; health.reason = "duplicate or regressing measurement stamp"; return; }
|
||||
source.last_seen_stamp = scan.stamp;
|
||||
source.pending = std::move(scan);
|
||||
source.pending_since = steady;
|
||||
}
|
||||
if (secondsBetween(now, source.pending->stamp) > source.max_age)
|
||||
{
|
||||
source.pending.reset(); ++health.dropped_count;
|
||||
health.status = Health::kStale; health.reason = "pending scan expired"; return;
|
||||
}
|
||||
PlanarTransform transform;
|
||||
std::string error;
|
||||
if (!dependencies.input->lookupTransform(config.tracking_frame, source.pending->frame,
|
||||
source.pending->stamp, transform, error))
|
||||
{
|
||||
health.status = Health::kTfError; health.reason = error;
|
||||
if (elapsed(steady, source.pending_since) >= config.tf_wait)
|
||||
{ source.pending.reset(); ++health.dropped_count; }
|
||||
return;
|
||||
}
|
||||
DetectionFrame frame;
|
||||
frame.stamp = source.pending->stamp; frame.source = index;
|
||||
const auto result = clusterer->detect(*source.pending, transform, index, frame.detections);
|
||||
source.pending.reset();
|
||||
if (result.status != Health::kValid)
|
||||
{ health.status = result.status; health.reason = result.reason; ++health.dropped_count; return; }
|
||||
source.ready = std::move(frame); source.ready_since = steady;
|
||||
}
|
||||
|
||||
void consume(Stamp now, SteadyTime steady)
|
||||
{
|
||||
// Flush all possible batches in time order, at most one frame per configured source.
|
||||
for (std::size_t iteration = 0; iteration < sources.size(); ++iteration)
|
||||
{
|
||||
Stamp earliest = 0;
|
||||
SteadyTime first_ready{};
|
||||
for (const auto& source : sources)
|
||||
if (source.ready && (!earliest || source.ready->stamp < earliest))
|
||||
{ earliest = source.ready->stamp; first_ready = source.ready_since; }
|
||||
if (!earliest) break;
|
||||
bool wait_for_source = false;
|
||||
for (const auto& source : sources)
|
||||
if (source.health.required && !source.ready) wait_for_source = true;
|
||||
if (wait_for_source && elapsed(steady, first_ready) < config.fusion_wait) break;
|
||||
std::vector<DetectionFrame> frames;
|
||||
std::vector<std::size_t> observed;
|
||||
Stamp batch_stamp = earliest;
|
||||
for (std::size_t i = 0; i < sources.size(); ++i)
|
||||
{
|
||||
auto& source = sources[i];
|
||||
if (!source.ready || secondsBetween(source.ready->stamp, earliest) > config.fusion_window) continue;
|
||||
if (secondsBetween(now, source.ready->stamp) > source.max_age)
|
||||
{
|
||||
source.ready.reset(); source.health.status = Health::kStale;
|
||||
source.health.reason = "fusion frame expired"; ++source.health.dropped_count; continue;
|
||||
}
|
||||
batch_stamp = std::max(batch_stamp, source.ready->stamp);
|
||||
observed.push_back(i);
|
||||
frames.push_back(std::move(*source.ready)); source.ready.reset();
|
||||
}
|
||||
if (frames.empty()) continue;
|
||||
std::vector<Detection> fused;
|
||||
batch_result = fuseDetections(frames, batch_stamp, config, fused);
|
||||
if (batch_result.status == Health::kValid) batch_result = core->update(batch_stamp, fused, observed);
|
||||
for (const auto& frame : frames)
|
||||
{
|
||||
auto& health = sources[frame.source].health;
|
||||
health.status = batch_result.status; health.reason = batch_result.reason;
|
||||
if (batch_result.status == Health::kValid)
|
||||
{
|
||||
++health.processed_count; health.last_success_stamp = frame.stamp;
|
||||
health.last_success_steady_time = steady;
|
||||
}
|
||||
else ++health.dropped_count;
|
||||
}
|
||||
if (batch_result.status == Health::kValid) last_success = steady;
|
||||
}
|
||||
}
|
||||
|
||||
void tick()
|
||||
{
|
||||
const Stamp now = dependencies.input->measurementNow();
|
||||
const SteadyTime steady = dependencies.steady_now();
|
||||
if (now <= 0)
|
||||
{ publish(now, steady, Health::kInvalidInput, "measurement clock is not initialized"); return; }
|
||||
const double measurement_dt = secondsBetween(now, last_now);
|
||||
const double steady_dt = elapsed(steady, last_steady);
|
||||
if (last_now && (measurement_dt < -config.future_tolerance ||
|
||||
measurement_dt > std::max(0.0, steady_dt) + config.clock_jump_reset))
|
||||
{ ++epoch; reset(false, now, steady); }
|
||||
if (steady_dt < 0)
|
||||
{ publish(now, steady, Health::kFault, "steady clock regressed"); return; }
|
||||
last_now = now; last_steady = steady;
|
||||
for (std::size_t i = 0; i < sources.size(); ++i)
|
||||
{
|
||||
if (stopping.load()) return;
|
||||
collect(i, now, steady);
|
||||
}
|
||||
consume(now, steady);
|
||||
core->expire(now);
|
||||
publish(now, steady);
|
||||
}
|
||||
|
||||
void run() noexcept
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!stopping.load())
|
||||
{
|
||||
tick();
|
||||
std::unique_lock<std::mutex> lock(wait_mutex);
|
||||
wake.wait_for(lock, std::chrono::duration<double>(config.poll_period), [&] { return stopping.load(); });
|
||||
}
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
{ try { publish(last_now, std::chrono::steady_clock::now(), Health::kFault, ex.what()); } catch (...) {} }
|
||||
catch (...)
|
||||
{ try { publish(last_now, std::chrono::steady_clock::now(), Health::kFault, "unknown worker exception"); } catch (...) {} }
|
||||
is_running.store(false);
|
||||
}
|
||||
};
|
||||
|
||||
TrackerService::TrackerService() : impl_(std::make_unique<Impl>()) {}
|
||||
TrackerService::~TrackerService() { stop(); }
|
||||
|
||||
bool TrackerService::configure(const TrackerConfig& config, const TrackerDependencies& dependencies,
|
||||
std::string& error)
|
||||
{
|
||||
auto& p = *impl_;
|
||||
std::lock_guard<std::mutex> lock(p.lifecycle_mutex);
|
||||
error.clear();
|
||||
if (p.is_running.load()) { error = "stop tracker before configuring/rebinding"; return false; }
|
||||
if (!config.validate(error)) return false;
|
||||
if (!dependencies.input || !dependencies.steady_now)
|
||||
{ error = "input and steady clock are required"; return false; }
|
||||
try
|
||||
{
|
||||
std::vector<Impl::Source> sources(config.sources.size());
|
||||
for (std::size_t i = 0; i < config.sources.size(); ++i)
|
||||
{
|
||||
double store_age = 0;
|
||||
std::string source_error;
|
||||
const bool found = dependencies.input->describeSource(config.sources[i].topic, store_age, source_error);
|
||||
if ((!found || !std::isfinite(store_age) || store_age <= 0) && config.sources[i].required)
|
||||
{ error = config.sources[i].topic + ": " + source_error + " (invalid/unavailable source policy)"; return false; }
|
||||
sources[i].max_age = found && store_age > 0 ? std::min(store_age, config.sources[i].max_age) :
|
||||
config.sources[i].max_age;
|
||||
if (config.tf_wait >= sources[i].max_age)
|
||||
{ error = "tf_wait must be shorter than effective SensorStore max_age"; return false; }
|
||||
}
|
||||
const auto now = dependencies.input->measurementNow();
|
||||
const auto steady = dependencies.steady_now();
|
||||
auto core = std::make_unique<TrackerCore>(config);
|
||||
auto clusterer = std::make_unique<ScanClusterer>(config);
|
||||
if (p.worker.joinable()) p.worker.join();
|
||||
p.config = config; p.dependencies = dependencies; p.sources = std::move(sources);
|
||||
p.core = std::move(core); p.clusterer = std::move(clusterer);
|
||||
p.epoch = 0; p.stopping.store(false); p.configured = true; p.reset(true, now, steady);
|
||||
return true;
|
||||
}
|
||||
catch (const std::exception& ex) { error = ex.what(); return false; }
|
||||
}
|
||||
bool TrackerService::start(std::string& error)
|
||||
{
|
||||
auto& p = *impl_;
|
||||
std::lock_guard<std::mutex> lock(p.lifecycle_mutex);
|
||||
error.clear();
|
||||
if (!p.configured) { error = "tracker is not configured"; return false; }
|
||||
if (p.is_running.load()) return true;
|
||||
try
|
||||
{
|
||||
if (p.worker.joinable()) p.worker.join();
|
||||
p.stopping.store(false);
|
||||
p.reset(true, p.dependencies.input->measurementNow(), p.dependencies.steady_now());
|
||||
p.is_running.store(true);
|
||||
p.worker = std::thread([&p] { p.run(); });
|
||||
return true;
|
||||
}
|
||||
catch (const std::exception& ex) { p.is_running.store(false); error = ex.what(); return false; }
|
||||
}
|
||||
void TrackerService::stop() noexcept
|
||||
{
|
||||
auto& p = *impl_;
|
||||
std::lock_guard<std::mutex> lock(p.lifecycle_mutex);
|
||||
p.stopping.store(true); p.wake.notify_all();
|
||||
if (p.worker.joinable()) p.worker.join();
|
||||
p.is_running.store(false);
|
||||
try
|
||||
{
|
||||
const auto current = latestSnapshot();
|
||||
auto stopped = std::make_shared<TrackSnapshot>(*current);
|
||||
stopped->status = Health::kStopped; stopped->reason = "service stopped";
|
||||
stopped->generation = ++p.generation;
|
||||
stopped->tracks.clear();
|
||||
std::atomic_store(&p.snapshot, std::shared_ptr<const TrackSnapshot>(stopped));
|
||||
}
|
||||
catch (...) {} // Destruction must still finish if diagnostic allocation fails.
|
||||
}
|
||||
bool TrackerService::running() const noexcept { return impl_->is_running.load(); }
|
||||
std::shared_ptr<const TrackSnapshot> TrackerService::latestSnapshot() const
|
||||
{ return std::atomic_load_explicit(&impl_->snapshot, std::memory_order_acquire); }
|
||||
bool TrackerService::pollOnce(std::string& error)
|
||||
{
|
||||
auto& p = *impl_;
|
||||
std::lock_guard<std::mutex> lock(p.lifecycle_mutex);
|
||||
error.clear();
|
||||
if (!p.configured || p.is_running.load() || p.stopping.load())
|
||||
{ error = "pollOnce requires configured, stopped worker and no stop request; configure/start to reset"; return false; }
|
||||
try { p.tick(); return true; }
|
||||
catch (const std::exception& ex)
|
||||
{ error = ex.what(); p.publish(p.last_now, p.last_steady, Health::kFault, error); return false; }
|
||||
}
|
||||
}
|
||||
49
robot_dynamic_obstacle_tracker/test/config_test.cpp
Normal file
49
robot_dynamic_obstacle_tracker/test/config_test.cpp
Normal file
@@ -0,0 +1,49 @@
|
||||
#include <gtest/gtest.h>
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
#include <limits>
|
||||
#include <unistd.h>
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_config.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace robot_dynamic_obstacle_tracker;
|
||||
struct TemporaryYaml
|
||||
{
|
||||
std::string path;
|
||||
explicit TemporaryYaml(const std::string& text)
|
||||
{
|
||||
char name[]="/tmp/dynamic_tracker_config_XXXXXX";
|
||||
const int fd=mkstemp(name);
|
||||
if(fd<0) throw std::runtime_error("mkstemp failed");
|
||||
close(fd);path=name;std::ofstream out(path);out<<text;
|
||||
}
|
||||
~TemporaryYaml(){std::remove(path.c_str());}
|
||||
};
|
||||
TEST(Config, PackagedYamlLoadsAndMatchesDefaults)
|
||||
{
|
||||
TrackerConfig c;std::string error;
|
||||
ASSERT_TRUE(loadTrackerConfig(std::string(TRACKER_SOURCE_DIR)+"/config/tracker_params.yaml",c,error))<<error;
|
||||
EXPECT_EQ(c.sources.size(),2u);EXPECT_EQ(c.tracking_frame,"odom");
|
||||
EXPECT_EQ(c.max_tracks,TrackerConfig{}.max_tracks);
|
||||
EXPECT_DOUBLE_EQ(c.acceleration_noise,TrackerConfig{}.acceleration_noise);
|
||||
}
|
||||
TEST(Config, RejectsInvalidThresholdsCapacityAndSources)
|
||||
{
|
||||
TrackerConfig c;std::string error;
|
||||
c.stationary_speed=c.moving_speed;EXPECT_FALSE(c.validate(error));
|
||||
c=TrackerConfig{};c.max_tracks=513;EXPECT_FALSE(c.validate(error));
|
||||
c=TrackerConfig{};c.sources[1].topic=c.sources[0].topic;EXPECT_FALSE(c.validate(error));
|
||||
c=TrackerConfig{};c.measurement_sigma=std::numeric_limits<double>::quiet_NaN();EXPECT_FALSE(c.validate(error));
|
||||
}
|
||||
TEST(Config, UnknownDuplicateAndMalformedYamlDoNotMutateOutput)
|
||||
{
|
||||
TrackerConfig c;c.tracking_frame="original";std::string error;
|
||||
for(const auto* text:{"typo: 1","poll_period: 0.1\npoll_period: 0.2","sources: 3",
|
||||
"max_tracks: -1","sources: [{topic: /f_scan, unexpected: true}]","[]"})
|
||||
{
|
||||
TemporaryYaml file(text);EXPECT_FALSE(loadTrackerConfig(file.path,c,error))<<text;
|
||||
EXPECT_EQ(c.tracking_frame,"original");EXPECT_FALSE(error.empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
262
robot_dynamic_obstacle_tracker/test/core_test.cpp
Normal file
262
robot_dynamic_obstacle_tracker/test/core_test.cpp
Normal file
@@ -0,0 +1,262 @@
|
||||
#include <gtest/gtest.h>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <chrono>
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
#include <Eigen/Eigenvalues>
|
||||
#include <robot_dynamic_obstacle_tracker/data_association.h>
|
||||
#include <robot_dynamic_obstacle_tracker/detection_fusion.h>
|
||||
#include <robot_dynamic_obstacle_tracker/kalman_track.h>
|
||||
#include <robot_dynamic_obstacle_tracker/scan_clusterer.h>
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_core.h>
|
||||
#include "test_helpers.h"
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace robot_dynamic_obstacle_tracker;
|
||||
using namespace tracker_test;
|
||||
|
||||
TEST(Cluster, BoundingDiscCoversEveryReturn)
|
||||
{
|
||||
TrackerConfig config;
|
||||
ScanClusterer clusterer(config);
|
||||
auto s = scan(10); s.ranges.assign(100, 2.0f); s.angle_min = -0.5;
|
||||
PlanarTransform tf;
|
||||
tf.linear << 0,-1,1,0; tf.translation = {3,4};
|
||||
std::vector<Detection> out;
|
||||
ASSERT_EQ(clusterer.detect(s, tf, 0, out).status, Health::kValid);
|
||||
ASSERT_EQ(out.size(), 1u); // No arbitrary max-point cutoff for a nearby large object.
|
||||
for (std::size_t i=0; i<s.ranges.size(); ++i)
|
||||
{
|
||||
const double a = s.angle_min + i*s.angle_increment;
|
||||
EXPECT_LE((tf.apply({2*std::cos(a),2*std::sin(a)}) - out[0].position).norm(), out[0].radius);
|
||||
}
|
||||
}
|
||||
TEST(Cluster, MissingBeamSplitsClusters)
|
||||
{
|
||||
auto s = scan(10); s.ranges[3] = std::numeric_limits<float>::quiet_NaN();
|
||||
std::vector<Detection> out;
|
||||
const auto result = ScanClusterer(TrackerConfig{}).detect(s, {}, 0, out);
|
||||
EXPECT_EQ(result.status, Health::kValid); EXPECT_EQ(result.rejected_points, 1u);
|
||||
EXPECT_EQ(out.size(), 2u);
|
||||
}
|
||||
TEST(Cluster, AllNoReturnsIsEmptyButBrokenAndEmptyScanAreInvalid)
|
||||
{
|
||||
ScanClusterer clusterer(TrackerConfig{}); std::vector<Detection> out;
|
||||
auto s = scan(10); s.ranges.assign(10, std::numeric_limits<float>::infinity());
|
||||
EXPECT_EQ(clusterer.detect(s, {}, 0, out).status, Health::kValid); EXPECT_TRUE(out.empty());
|
||||
s.ranges.assign(10, std::numeric_limits<float>::quiet_NaN());
|
||||
EXPECT_EQ(clusterer.detect(s, {}, 0, out).status, Health::kInvalidInput);
|
||||
s.ranges.clear(); EXPECT_EQ(clusterer.detect(s, {}, 0, out).status, Health::kInvalidInput);
|
||||
s = scan(10); s.angle_increment = 0;
|
||||
EXPECT_EQ(clusterer.detect(s, {}, 0, out).status, Health::kInvalidInput);
|
||||
}
|
||||
TEST(Cluster, OverflowIsExplicit)
|
||||
{
|
||||
TrackerConfig c; c.max_detections=1;
|
||||
auto s = scan(10); s.ranges[3] = std::numeric_limits<float>::infinity();
|
||||
std::vector<Detection> out;
|
||||
EXPECT_EQ(ScanClusterer(c).detect(s, {}, 0, out).status, Health::kOverflow);
|
||||
c.max_scan_points=3;
|
||||
EXPECT_EQ(ScanClusterer(c).detect(s, {}, 0, out).status, Health::kOverflow);
|
||||
}
|
||||
TEST(Cluster, UpsideDownLaserIsSupported)
|
||||
{
|
||||
PlanarTransform tf; tf.linear(1,1)=-1;
|
||||
EXPECT_TRUE(tf.valid());
|
||||
std::vector<Detection> out;
|
||||
EXPECT_EQ(ScanClusterer(TrackerConfig{}).detect(scan(10), tf, 0, out).status, Health::kValid);
|
||||
}
|
||||
TEST(Fusion, TwoSensorsOneObjectAndConservativeExtent)
|
||||
{
|
||||
TrackerConfig c;
|
||||
auto a = detection(1,0,10,0), b = detection(1.1,0,10.02,1);
|
||||
std::vector<Detection> out;
|
||||
const auto r = fuseDetections({{a.stamp,0,{a}},{b.stamp,1,{b}}}, b.stamp, c, out);
|
||||
ASSERT_EQ(r.status, Health::kValid); ASSERT_EQ(out.size(),1u);
|
||||
EXPECT_EQ(out[0].sources.size(),2u);
|
||||
EXPECT_GE(out[0].radius, a.radius + 0.05 + c.fusion_max_speed*0.02 - 1e-10);
|
||||
EXPECT_GE(out[0].covariance(0,0), a.covariance(0,0));
|
||||
}
|
||||
TEST(Fusion, DoesNotMergeTwoDetectionsFromSameSource)
|
||||
{
|
||||
const auto a=detection(1,0,10), b=detection(1.1,0,10);
|
||||
std::vector<Detection> out;
|
||||
EXPECT_EQ(fuseDetections({{a.stamp,0,{a,b}}}, a.stamp, TrackerConfig{}, out).status,Health::kValid);
|
||||
EXPECT_EQ(out.size(),2u);
|
||||
EXPECT_EQ(fuseDetections({{a.stamp,0,{a}}}, stamp(11), TrackerConfig{}, out).status,Health::kOutOfOrder);
|
||||
}
|
||||
TEST(Fusion, AlignmentDoesNotRefreshActualObservationTime)
|
||||
{
|
||||
auto a=detection(1,0,10,0);
|
||||
std::vector<Detection> out;
|
||||
ASSERT_EQ(fuseDetections({{a.stamp,0,{a}},{stamp(10.02),1,{}}}, stamp(10.02),
|
||||
TrackerConfig{}, out).status,Health::kValid);
|
||||
ASSERT_EQ(out.size(),1u);
|
||||
EXPECT_EQ(out[0].stamp,stamp(10.02)); EXPECT_EQ(out[0].observed_stamp,stamp(10));
|
||||
TrackerCore core(TrackerConfig{});core.reset(1);
|
||||
ASSERT_EQ(core.update(stamp(10.02),out,{0,1}).status,Health::kValid);
|
||||
EXPECT_EQ(core.predictedTracks(stamp(10.02))[0].last_observed_stamp,stamp(10));
|
||||
}
|
||||
TEST(Kalman, JosephCovarianceStaysPositiveAndPredictionDoesNotRefreshObservation)
|
||||
{
|
||||
Track t; t.state_stamp=t.last_observed_stamp=stamp(10); t.state << 1,2,0.5,-0.2;
|
||||
ASSERT_TRUE(predictTrack(t,stamp(10.2),1));
|
||||
EXPECT_NEAR(t.state.x(),1.1,1e-10); EXPECT_EQ(t.last_observed_stamp,stamp(10));
|
||||
EXPECT_FALSE(predictTrack(t,stamp(9),1));
|
||||
for(int i=1;i<=100;++i)
|
||||
{
|
||||
const double time=10.2+0.1*i;
|
||||
ASSERT_TRUE(predictTrack(t,stamp(time),1));
|
||||
ASSERT_TRUE(correctTrack(t,detection(1.1+0.05*i,1.96-0.02*i,time)));
|
||||
Eigen::SelfAdjointEigenSolver<Eigen::Matrix4d> eigen(t.covariance);
|
||||
EXPECT_GT(eigen.eigenvalues().minCoeff(),0);
|
||||
EXPECT_TRUE(t.covariance.isApprox(t.covariance.transpose(),1e-12));
|
||||
}
|
||||
}
|
||||
TEST(Association, GlobalAssignmentAvoidsGreedyDeadEnd)
|
||||
{
|
||||
TrackerConfig c; c.association_distance=0.3;
|
||||
Track a,b; a.state.x()=0; b.state.x()=0.2;
|
||||
// A can see both; B can only see detection 0. Greedy A->0 would lose B.
|
||||
const auto result=associateDetections({a,b},{detection(0.1,0,10),detection(-0.2,0,10)},c);
|
||||
ASSERT_EQ(result.size(),2u); EXPECT_EQ(result[0],1); EXPECT_EQ(result[1],0);
|
||||
}
|
||||
TEST(Association, RejectsFarAndMahalanobisOutliers)
|
||||
{
|
||||
Track t; t.covariance = Eigen::Matrix4d::Identity()*0.001;
|
||||
TrackerConfig c;
|
||||
EXPECT_EQ(associateDetections({t},{detection(10,0,10)},c)[0],-1);
|
||||
EXPECT_EQ(associateDetections({t},{detection(0.9,0,10)},c)[0],-1);
|
||||
}
|
||||
TEST(Core, LearnsVelocityAndPreservesId)
|
||||
{
|
||||
TrackerCore core(TrackerConfig{}); core.reset(42);
|
||||
for(int i=0;i<40;++i)
|
||||
ASSERT_EQ(core.update(stamp(10+0.1*i),{detection(1+0.05*i,0,10+0.1*i)},{0}).status,Health::kValid);
|
||||
auto tracks=core.predictedTracks(stamp(13.9));
|
||||
ASSERT_EQ(tracks.size(),1u);
|
||||
EXPECT_EQ(tracks[0].track_id,1u); EXPECT_EQ(tracks[0].session_id,42u);
|
||||
EXPECT_NEAR(tracks[0].state.z(),0.5,0.02); EXPECT_NEAR(tracks[0].state.w(),0,1e-10);
|
||||
EXPECT_EQ(tracks[0].motion,MotionClass::kMoving);
|
||||
EXPECT_EQ(tracks[0].lifecycle,TrackLifecycle::kConfirmed);
|
||||
}
|
||||
TEST(Core, StationaryObjectIsRetainedAndClassified)
|
||||
{
|
||||
TrackerCore core(TrackerConfig{}); core.reset(1);
|
||||
for(int i=0;i<30;++i)
|
||||
core.update(stamp(10+0.1*i),{detection(1,0,10+0.1*i)},{0});
|
||||
auto tracks=core.predictedTracks(stamp(12.9)); ASSERT_EQ(tracks.size(),1u);
|
||||
EXPECT_EQ(tracks[0].motion,MotionClass::kStationary);
|
||||
}
|
||||
TEST(Core, CoastPredictExpireAndNeverReuseIdentity)
|
||||
{
|
||||
TrackerCore core(TrackerConfig{}); core.reset(8);
|
||||
for(int i=0;i<10;++i) core.update(stamp(10+0.1*i),{detection(1+0.05*i,0,10+0.1*i)},{0});
|
||||
const auto before=core.predictedTracks(stamp(10.9))[0];
|
||||
ASSERT_EQ(core.update(stamp(11.1),{}, {0}).status,Health::kValid);
|
||||
const auto coast=core.predictedTracks(stamp(11.2))[0];
|
||||
EXPECT_EQ(coast.last_observed_stamp,stamp(10.9));
|
||||
EXPECT_EQ(coast.lifecycle,TrackLifecycle::kCoasting);
|
||||
EXPECT_GT(coast.state.x(),before.state.x());
|
||||
EXPECT_GT(coast.covariance.trace(),before.covariance.trace());
|
||||
core.expire(stamp(12)); EXPECT_TRUE(core.predictedTracks(stamp(12)).empty());
|
||||
core.update(stamp(12),{detection(3,0,12)},{0});
|
||||
EXPECT_EQ(core.predictedTracks(stamp(12))[0].track_id,2u);
|
||||
}
|
||||
TEST(Core, TentativeExpiresAndUnrelatedSourceDoesNotCountAMiss)
|
||||
{
|
||||
TrackerCore core(TrackerConfig{}); core.reset(1);
|
||||
core.update(stamp(10),{detection(1,0,10)},{0});
|
||||
core.update(stamp(10.1),{}, {1});
|
||||
EXPECT_EQ(core.predictedTracks(stamp(10.1))[0].miss_count,0u);
|
||||
core.expire(stamp(10.4)); EXPECT_TRUE(core.predictedTracks(stamp(10.4)).empty());
|
||||
}
|
||||
TEST(Core, InvalidAndOutOfOrderInputDoNotAdvanceState)
|
||||
{
|
||||
TrackerCore core(TrackerConfig{}); core.reset(1);
|
||||
core.update(stamp(10),{detection(1,0,10)},{0});
|
||||
EXPECT_EQ(core.update(stamp(10),{}, {0}).status,Health::kOutOfOrder);
|
||||
auto bad=detection(1,0,10.1); bad.covariance(0,0)=-1;
|
||||
EXPECT_EQ(core.update(stamp(10.1),{bad},{0}).status,Health::kInvalidInput);
|
||||
EXPECT_EQ(core.lastUpdateStamp(),stamp(10));
|
||||
}
|
||||
TEST(Core, OverflowNeverSilentlyReportsHealthy)
|
||||
{
|
||||
TrackerConfig c; c.max_tracks=1;
|
||||
TrackerCore core(c); core.reset(1);
|
||||
EXPECT_EQ(core.update(stamp(10),{detection(1,0,10),detection(4,0,10)},{0}).status,Health::kOverflow);
|
||||
}
|
||||
TEST(Core, CrossingObjectsKeepDistinctIdentity)
|
||||
{
|
||||
TrackerConfig c; c.acceleration_noise=0.1;
|
||||
TrackerCore core(c); core.reset(1);
|
||||
for(int i=0;i<=40;++i)
|
||||
{
|
||||
const double time=10+i*0.1, x=i*0.05;
|
||||
std::vector<Detection> d{detection(-1+x,-0.2,time),detection(1-x,0.2,time)};
|
||||
if(i%2) std::reverse(d.begin(),d.end());
|
||||
ASSERT_EQ(core.update(stamp(time),d,{0}).status,Health::kValid);
|
||||
}
|
||||
const auto out=core.predictedTracks(stamp(14));
|
||||
ASSERT_EQ(out.size(),2u); EXPECT_EQ(out[0].track_id,1u); EXPECT_EQ(out[1].track_id,2u);
|
||||
EXPECT_NEAR(out[0].state.x(),1,0.02); EXPECT_NEAR(out[1].state.x(),-1,0.02);
|
||||
}
|
||||
TEST(Core, InstancesAreIndependent)
|
||||
{
|
||||
TrackerCore a(TrackerConfig{}),b(TrackerConfig{}); a.reset(1);b.reset(2);
|
||||
a.update(stamp(10),{detection(1,0,10)},{0}); b.update(stamp(10),{detection(5,0,10)},{0});
|
||||
a.reset(3);
|
||||
EXPECT_TRUE(a.predictedTracks(stamp(10)).empty());
|
||||
ASSERT_EQ(b.predictedTracks(stamp(10)).size(),1u);
|
||||
EXPECT_EQ(b.predictedTracks(stamp(10))[0].session_id,2u);
|
||||
}
|
||||
TEST(Core, RejectsUnknownSourcesAndRetainsNewestObservationStamp)
|
||||
{
|
||||
TrackerCore core(TrackerConfig{});core.reset(1);
|
||||
EXPECT_EQ(core.update(stamp(10),{detection(1,0,10,7)},{7}).status,Health::kInvalidInput);
|
||||
EXPECT_EQ(core.update(stamp(10),{detection(1,0,10,1)},{0}).status,Health::kInvalidInput);
|
||||
ASSERT_EQ(core.update(stamp(10),{detection(1,0,10)},{0}).status,Health::kValid);
|
||||
auto delayed=detection(1,0,10.02,1);delayed.observed_stamp=stamp(9.99);
|
||||
ASSERT_EQ(core.update(stamp(10.02),{delayed},{1}).status,Health::kValid);
|
||||
EXPECT_EQ(core.predictedTracks(stamp(10.02))[0].last_observed_stamp,stamp(10));
|
||||
}
|
||||
TEST(Core, MovingObjectStopsAndStartsWithSameIdentity)
|
||||
{
|
||||
TrackerCore core(TrackerConfig{});core.reset(1);
|
||||
double x=1;
|
||||
for(int i=0;i<100;++i)
|
||||
{
|
||||
const double time=10+0.1*i;
|
||||
if(i<30 || i>=65)x+=0.05;
|
||||
ASSERT_EQ(core.update(stamp(time),{detection(x,0,time)},{0}).status,Health::kValid);
|
||||
const auto out=core.predictedTracks(stamp(time));ASSERT_EQ(out.size(),1u);
|
||||
EXPECT_EQ(out[0].track_id,1u);
|
||||
if(i==60) { EXPECT_EQ(out[0].motion,MotionClass::kStationary); }
|
||||
if(i==99) { EXPECT_EQ(out[0].motion,MotionClass::kMoving); }
|
||||
}
|
||||
}
|
||||
TEST(CorePerformance, BoundedPopulationTimingAndFiniteState)
|
||||
{
|
||||
TrackerCore core(TrackerConfig{});core.reset(1);
|
||||
std::vector<double> durations;
|
||||
for(int cycle=0;cycle<300;++cycle)
|
||||
{
|
||||
const double time=10+cycle*0.05;
|
||||
std::vector<Detection> detections;
|
||||
for(int id=0;id<32;++id)detections.push_back(detection(id*2.0+cycle*0.005,0,time));
|
||||
const auto begin=std::chrono::steady_clock::now();
|
||||
ASSERT_EQ(core.update(stamp(time),detections,{0}).status,Health::kValid);
|
||||
const auto out=core.predictedTracks(stamp(time));ASSERT_EQ(out.size(),32u);
|
||||
durations.push_back(std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-begin).count());
|
||||
for(const auto& track:out) {EXPECT_TRUE(track.state.allFinite());EXPECT_TRUE(track.covariance.allFinite());}
|
||||
}
|
||||
std::sort(durations.begin(),durations.end());
|
||||
const double p99=durations[296], maximum=durations.back();
|
||||
RecordProperty("population",32);RecordProperty("cycles",300);
|
||||
RecordProperty("p99_ms",std::to_string(p99));RecordProperty("max_ms",std::to_string(maximum));
|
||||
std::cout<<"[ tracker timing ] 32 tracks, 300 updates: p99="<<p99<<" ms, max="<<maximum<<" ms\n";
|
||||
// Measurement only: this synthetic workload is not the host's 20 Hz acceptance gate.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
project(tracker_install_consumer LANGUAGES CXX)
|
||||
find_package(robot_dynamic_obstacle_tracker CONFIG REQUIRED)
|
||||
add_executable(tracker_install_consumer main.cpp)
|
||||
target_link_libraries(tracker_install_consumer PRIVATE
|
||||
robot_dynamic_obstacle_tracker::robot_dynamic_obstacle_tracker)
|
||||
@@ -0,0 +1,13 @@
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_core.h>
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_service.h>
|
||||
|
||||
int main()
|
||||
{
|
||||
robot_dynamic_obstacle_tracker::TrackerConfig config;
|
||||
std::string error;
|
||||
if (!config.validate(error)) return 1;
|
||||
robot_dynamic_obstacle_tracker::TrackerCore core(config);
|
||||
core.reset(1);
|
||||
robot_dynamic_obstacle_tracker::TrackerService service;
|
||||
return service.latestSnapshot() ? 0 : 2;
|
||||
}
|
||||
150
robot_dynamic_obstacle_tracker/test/sensor_ports_test.cpp
Normal file
150
robot_dynamic_obstacle_tracker/test/sensor_ports_test.cpp
Normal file
@@ -0,0 +1,150 @@
|
||||
#include <gtest/gtest.h>
|
||||
#include <cmath>
|
||||
#include <memory>
|
||||
#include <robot_sensor_msgs/LaserScan.h>
|
||||
#include <robot_sensor_ports/sensor_store.h>
|
||||
#include <robot_sensor_ports/sensor_types.h>
|
||||
#include <tf3/buffer_core.h>
|
||||
#include <robot_dynamic_obstacle_tracker/sensor_ports_input.h>
|
||||
#include "test_helpers.h"
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace robot_dynamic_obstacle_tracker;
|
||||
using namespace tracker_test;
|
||||
struct NativeRig
|
||||
{
|
||||
robot_sensor_ports::SensorStore store;
|
||||
std::shared_ptr<tf3::BufferCore> tf=std::make_shared<tf3::BufferCore>();
|
||||
Stamp now=stamp(10);
|
||||
SteadyTime steady=SteadyTime(std::chrono::seconds(1));
|
||||
TrackerService service;
|
||||
std::shared_ptr<TrackerInput> input;
|
||||
std::string error;
|
||||
NativeRig()
|
||||
{
|
||||
robot_sensor_ports::SensorStoreConfig store_config;
|
||||
robot_sensor_ports::SensorEntryConfig source;
|
||||
source.topic="/f_scan";source.data_type="robot_sensor_msgs/LaserScan";source.max_age=0.5;
|
||||
store_config.sensors.push_back(source);source.topic="/b_scan";store_config.sensors.push_back(source);
|
||||
if(!store.configure(store_config,error)) throw std::runtime_error(error);
|
||||
input=makeSensorPortsInput(store,tf,[this]{return now;});
|
||||
}
|
||||
void pose(double time,double x,double yaw=0,const std::string& frame="laser",bool is_static=false)
|
||||
{
|
||||
tf3::TransformStampedMsg t;
|
||||
const robot::Time stamp_robot(time);
|
||||
t.header.stamp=tf3::Time(stamp_robot.sec,stamp_robot.nsec);
|
||||
t.header.frame_id="odom";t.child_frame_id=frame;
|
||||
t.transform.translation.x=x;
|
||||
t.transform.rotation.z=std::sin(yaw*0.5);t.transform.rotation.w=std::cos(yaw*0.5);
|
||||
ASSERT_TRUE(tf->setTransform(t,"tracker_test",is_static));
|
||||
}
|
||||
void put(double time,double range=2,const std::string& topic="/f_scan",
|
||||
const std::string& frame="laser",bool wall=false)
|
||||
{
|
||||
robot_sensor_msgs::LaserScan s;
|
||||
s.header.stamp=robot::Time(time);s.header.frame_id=frame;
|
||||
s.angle_min=-0.03;s.angle_increment=0.01;s.range_min=0.05;s.range_max=20;
|
||||
for(int i=0;i<7;++i)
|
||||
s.ranges.push_back(static_cast<float>(wall?range/std::cos(s.angle_min+i*s.angle_increment):range));
|
||||
ASSERT_TRUE(robot_sensor_ports::put(store,topic,s,s.header.stamp));
|
||||
}
|
||||
void configure(bool dual=false)
|
||||
{
|
||||
TrackerConfig c;if(!dual)c.sources={{"/f_scan",true,0.3}};
|
||||
ASSERT_TRUE(service.configure(c,{input,[this]{return steady;}},error))<<error;
|
||||
}
|
||||
void tick() {ASSERT_TRUE(service.pollOnce(error))<<error;}
|
||||
};
|
||||
TEST(SensorPorts, RealStoreCursorAndExactHistoricalTf)
|
||||
{
|
||||
NativeRig r;r.pose(10,1);r.pose(10.1,5);r.put(10);r.now=stamp(10.1);r.configure();r.tick();
|
||||
auto out=r.service.latestSnapshot();
|
||||
ASSERT_EQ(out->status,Health::kValid);ASSERT_EQ(out->tracks.size(),1u);
|
||||
EXPECT_NEAR(out->tracks[0].state.x(),3,0.002); // Must not use latest TF (which gives x=7).
|
||||
r.tick();EXPECT_EQ(r.service.latestSnapshot()->tracks[0].hit_count,1u);
|
||||
}
|
||||
TEST(SensorPorts, LateTfRecoversAtExactStamp)
|
||||
{
|
||||
NativeRig r;r.put(10);r.configure();r.tick();
|
||||
EXPECT_EQ(r.service.latestSnapshot()->status,Health::kTfError);
|
||||
r.pose(10,0);r.steady+=std::chrono::milliseconds(20);r.tick();
|
||||
EXPECT_EQ(r.service.latestSnapshot()->status,Health::kValid);
|
||||
}
|
||||
TEST(SensorPorts, MissingRequiredRearCannotInitialize)
|
||||
{
|
||||
NativeRig r;TrackerConfig c;c.sources[1].topic="/not_configured";
|
||||
EXPECT_FALSE(r.service.configure(c,{r.input},r.error));
|
||||
}
|
||||
TEST(SensorPorts, DualScansFuseAfterDifferentExtrinsics)
|
||||
{
|
||||
NativeRig r;r.pose(10,0,0,"front");r.pose(10,4,3.141592653589793,"rear");
|
||||
r.put(10,2,"/f_scan","front");r.put(10,2,"/b_scan","rear");r.configure(true);r.tick();
|
||||
auto out=r.service.latestSnapshot();
|
||||
ASSERT_EQ(out->status,Health::kValid);ASSERT_EQ(out->tracks.size(),1u);
|
||||
EXPECT_NEAR(out->tracks[0].state.x(),2,0.002);EXPECT_EQ(out->tracks[0].observed_sources.size(),2u);
|
||||
}
|
||||
TEST(SensorPorts, EgoTranslationDoesNotCreateMovingWall)
|
||||
{
|
||||
NativeRig r;r.configure();
|
||||
for(int i=0;i<35;++i)
|
||||
{
|
||||
const double time=10+0.1*i, robot_x=0.03*i;
|
||||
r.now=stamp(time);r.steady+=std::chrono::milliseconds(100);
|
||||
r.pose(time,robot_x);r.put(time,3-robot_x,"/f_scan","laser",true);r.tick();
|
||||
ASSERT_EQ(r.service.latestSnapshot()->status,Health::kValid);
|
||||
}
|
||||
auto out=r.service.latestSnapshot();
|
||||
ASSERT_EQ(out->tracks.size(),1u);EXPECT_NEAR(out->tracks[0].state.x(),3,1e-5);
|
||||
EXPECT_LT(out->tracks[0].state.tail<2>().norm(),1e-4);
|
||||
EXPECT_EQ(out->tracks[0].motion,MotionClass::kStationary);
|
||||
}
|
||||
TEST(SensorPorts, NativeMovingScanSequenceEstimatesVelocity)
|
||||
{
|
||||
NativeRig r;r.pose(10,0,0,"laser",true);r.configure();
|
||||
for(int i=0;i<35;++i)
|
||||
{
|
||||
const double time=10+0.1*i;r.now=stamp(time);r.steady+=std::chrono::milliseconds(100);
|
||||
r.put(time,2+0.05*i,"/f_scan","laser",true);r.tick();
|
||||
ASSERT_EQ(r.service.latestSnapshot()->status,Health::kValid);
|
||||
}
|
||||
const auto out=r.service.latestSnapshot();
|
||||
ASSERT_EQ(out->tracks.size(),1u);EXPECT_NEAR(out->tracks[0].state.z(),0.5,0.02);
|
||||
EXPECT_EQ(out->tracks[0].motion,MotionClass::kMoving);
|
||||
}
|
||||
TEST(SensorPorts, EgoRotationDoesNotCreateMovingCylinder)
|
||||
{
|
||||
NativeRig r;r.configure();
|
||||
for(int i=0;i<35;++i)
|
||||
{
|
||||
const double time=10+0.1*i, yaw=-0.5+0.03*i;
|
||||
r.now=stamp(time);r.steady+=std::chrono::milliseconds(100);r.pose(time,0,yaw);
|
||||
robot_sensor_msgs::LaserScan scan;
|
||||
scan.header.stamp=robot::Time(time);scan.header.frame_id="laser";
|
||||
scan.angle_min=-0.8;scan.angle_increment=0.005;scan.range_min=0.05;scan.range_max=20;
|
||||
// Raycast a stationary circle at (3,0), radius 0.25, with a rotating sensor at the origin.
|
||||
for(int beam=0;beam<=320;++beam)
|
||||
{
|
||||
const double a=yaw+scan.angle_min+beam*scan.angle_increment;
|
||||
const double projection=3*std::cos(a);
|
||||
const double discriminant=projection*projection-(9-0.25*0.25);
|
||||
scan.ranges.push_back(discriminant>=0 && projection>0 ?
|
||||
static_cast<float>(projection-std::sqrt(discriminant)) : INFINITY);
|
||||
}
|
||||
ASSERT_TRUE(robot_sensor_ports::put(r.store,"/f_scan",scan,scan.header.stamp));r.tick();
|
||||
ASSERT_EQ(r.service.latestSnapshot()->status,Health::kValid);
|
||||
}
|
||||
const auto out=r.service.latestSnapshot();ASSERT_EQ(out->tracks.size(),1u);
|
||||
EXPECT_LT(out->tracks[0].state.tail<2>().norm(),0.03);
|
||||
EXPECT_EQ(out->tracks[0].motion,MotionClass::kStationary);
|
||||
}
|
||||
TEST(SensorPorts, HeaderStoreStampMismatchIsRejected)
|
||||
{
|
||||
NativeRig r;r.pose(10,0);
|
||||
robot_sensor_msgs::LaserScan scan;
|
||||
scan.header.stamp=robot::Time(9.0);
|
||||
ASSERT_TRUE(robot_sensor_ports::put(r.store,"/f_scan",scan,robot::Time(10.0)));
|
||||
r.configure();r.tick();EXPECT_EQ(r.service.latestSnapshot()->status,Health::kInvalidInput);
|
||||
}
|
||||
}
|
||||
238
robot_dynamic_obstacle_tracker/test/service_test.cpp
Normal file
238
robot_dynamic_obstacle_tracker/test/service_test.cpp
Normal file
@@ -0,0 +1,238 @@
|
||||
#include <gtest/gtest.h>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_service.h>
|
||||
#include "test_helpers.h"
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace robot_dynamic_obstacle_tracker;
|
||||
using namespace tracker_test;
|
||||
class FakeInput final : public TrackerInput
|
||||
{
|
||||
public:
|
||||
mutable std::mutex mutex;
|
||||
std::map<std::string,RawScan> scans;
|
||||
std::map<std::string,bool> tf_available;
|
||||
std::atomic<Stamp> now{stamp(10)};
|
||||
std::atomic<bool> throw_read{false};
|
||||
bool describeSource(const std::string& topic,double& age,std::string& error) const override
|
||||
{
|
||||
if(topic!="/f_scan" && topic!="/b_scan") {error="unknown source";return false;}
|
||||
age=0.5;return true;
|
||||
}
|
||||
ReadStatus readLatest(const std::string& topic,std::uint64_t& cursor,RawScan& out,std::string&) override
|
||||
{
|
||||
if(throw_read.load()) throw std::runtime_error("injected worker failure");
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
const auto it=scans.find(topic);
|
||||
if(it==scans.end() || it->second.sequence<=cursor) return ReadStatus::kNoData;
|
||||
out=it->second;cursor=out.sequence;return ReadStatus::kScan;
|
||||
}
|
||||
bool lookupTransform(const std::string&,const std::string& source,Stamp,
|
||||
PlanarTransform& out,std::string& error) override
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
const auto it=tf_available.find(source);
|
||||
if(it!=tf_available.end() && !it->second) {error="TF not arrived";return false;}
|
||||
out={};return true;
|
||||
}
|
||||
Stamp measurementNow() const override {return now.load();}
|
||||
void put(const std::string& topic,RawScan s)
|
||||
{std::lock_guard<std::mutex> lock(mutex);scans[topic]=std::move(s);}
|
||||
void setTf(bool available)
|
||||
{std::lock_guard<std::mutex> lock(mutex);tf_available["laser"]=available;}
|
||||
};
|
||||
struct Rig
|
||||
{
|
||||
TrackerConfig config;
|
||||
std::shared_ptr<FakeInput> input=std::make_shared<FakeInput>();
|
||||
std::atomic<Stamp> steady_ns{stamp(1)};
|
||||
TrackerService service;
|
||||
std::string error;
|
||||
TrackerDependencies dependencies()
|
||||
{
|
||||
return {input,[this] {return SteadyTime(std::chrono::nanoseconds(steady_ns.load()));}};
|
||||
}
|
||||
bool configure(bool two_sources=false)
|
||||
{
|
||||
if(!two_sources) config.sources={{"/f_scan",true,0.3}};
|
||||
return service.configure(config,dependencies(),error);
|
||||
}
|
||||
void advance(double dt,bool measurement=true)
|
||||
{
|
||||
steady_ns.fetch_add(stamp(dt));
|
||||
if(measurement) input->now.fetch_add(stamp(dt));
|
||||
}
|
||||
void tick() {ASSERT_TRUE(service.pollOnce(error)) << error;}
|
||||
};
|
||||
|
||||
TEST(Service, ConfigureRejectsMissingRequiredSourceAndAllowsOptional)
|
||||
{
|
||||
Rig r;r.config.sources={{"/missing",true,0.3}};
|
||||
EXPECT_FALSE(r.service.configure(r.config,r.dependencies(),r.error));
|
||||
r.config.sources={{"/f_scan",true,0.3},{"/missing",false,0.3}};
|
||||
ASSERT_TRUE(r.service.configure(r.config,r.dependencies(),r.error));
|
||||
r.input->put("/f_scan",scan(10));r.tick();
|
||||
EXPECT_EQ(r.service.latestSnapshot()->status,Health::kValid);
|
||||
}
|
||||
TEST(Service, StartupEmptyObservationAndDuplicateCursor)
|
||||
{
|
||||
Rig r;ASSERT_TRUE(r.configure());
|
||||
r.tick();EXPECT_EQ(r.service.latestSnapshot()->status,Health::kWarmingUp);
|
||||
auto s=scan(10);s.ranges.assign(7,std::numeric_limits<float>::infinity());
|
||||
r.input->put("/f_scan",s);r.tick();
|
||||
auto snapshot=r.service.latestSnapshot();
|
||||
EXPECT_EQ(snapshot->status,Health::kValid);EXPECT_TRUE(snapshot->tracks.empty());
|
||||
EXPECT_EQ(snapshot->sources[0].processed_count,1u);
|
||||
r.tick();EXPECT_EQ(r.service.latestSnapshot()->sources[0].processed_count,1u);
|
||||
}
|
||||
TEST(Service, TwoSourcesFuseOnlyOnce)
|
||||
{
|
||||
Rig r;ASSERT_TRUE(r.configure(true));
|
||||
r.input->put("/f_scan",scan(10));r.input->put("/b_scan",scan(10));r.tick();
|
||||
auto out=r.service.latestSnapshot();
|
||||
ASSERT_EQ(out->status,Health::kValid);ASSERT_EQ(out->tracks.size(),1u);
|
||||
EXPECT_EQ(out->tracks[0].hit_count,1u);EXPECT_EQ(out->tracks[0].observed_sources.size(),2u);
|
||||
}
|
||||
TEST(Service, FusionWaitIsBoundedAndMissingRearCannotBeHealthy)
|
||||
{
|
||||
Rig r;ASSERT_TRUE(r.configure(true));
|
||||
r.input->put("/f_scan",scan(10));r.tick();
|
||||
EXPECT_TRUE(r.service.latestSnapshot()->tracks.empty());
|
||||
r.advance(0.04);r.tick();
|
||||
EXPECT_EQ(r.service.latestSnapshot()->tracks.size(),1u);
|
||||
EXPECT_EQ(r.service.latestSnapshot()->status,Health::kWarmingUp);
|
||||
r.advance(0.31);r.tick();EXPECT_EQ(r.service.latestSnapshot()->status,Health::kStale);
|
||||
}
|
||||
TEST(Service, LateTfRetriesSameSequenceAndNeverCountsTwice)
|
||||
{
|
||||
Rig r;ASSERT_TRUE(r.configure());r.input->setTf(false);
|
||||
r.input->put("/f_scan",scan(10));r.tick();
|
||||
EXPECT_EQ(r.service.latestSnapshot()->status,Health::kTfError);
|
||||
r.advance(0.02);r.input->setTf(true);r.tick();
|
||||
auto out=r.service.latestSnapshot();
|
||||
ASSERT_EQ(out->status,Health::kValid);ASSERT_EQ(out->tracks.size(),1u);
|
||||
EXPECT_EQ(out->tracks[0].hit_count,1u);r.tick();
|
||||
EXPECT_EQ(r.service.latestSnapshot()->tracks[0].hit_count,1u);
|
||||
}
|
||||
TEST(Service, TfTimeoutDropsPendingAndRecoversWithNewScan)
|
||||
{
|
||||
Rig r;ASSERT_TRUE(r.configure());r.input->setTf(false);
|
||||
r.input->put("/f_scan",scan(10));r.tick();r.advance(0.11);r.tick();
|
||||
EXPECT_EQ(r.service.latestSnapshot()->sources[0].dropped_count,1u);
|
||||
r.input->setTf(true);r.input->put("/f_scan",scan(10.11,2));r.tick();
|
||||
EXPECT_EQ(r.service.latestSnapshot()->status,Health::kValid);
|
||||
}
|
||||
TEST(Service, RequiredRearStalenessIsVisibleWithHealthyFront)
|
||||
{
|
||||
Rig r;ASSERT_TRUE(r.configure(true));
|
||||
r.input->put("/f_scan",scan(10));r.input->put("/b_scan",scan(10));r.tick();
|
||||
r.advance(0.2);r.input->put("/f_scan",scan(10.2,2));r.tick();
|
||||
r.advance(0.04);r.tick();r.advance(0.08);r.tick();
|
||||
auto out=r.service.latestSnapshot();
|
||||
EXPECT_EQ(out->sources[0].status,Health::kValid);
|
||||
EXPECT_EQ(out->sources[1].status,Health::kStale);
|
||||
EXPECT_EQ(out->status,Health::kStale);
|
||||
}
|
||||
TEST(Service, SteadyWatchdogWorksWithPausedMeasurementClock)
|
||||
{
|
||||
Rig r;ASSERT_TRUE(r.configure());r.input->put("/f_scan",scan(10));r.tick();
|
||||
r.advance(0.31,false);r.tick();
|
||||
EXPECT_EQ(r.service.latestSnapshot()->status,Health::kStale);
|
||||
EXPECT_EQ(r.service.latestSnapshot()->tracks[0].last_observed_stamp,stamp(10));
|
||||
}
|
||||
TEST(Service, OldFutureAndDuplicateStampedSamplesAreRejected)
|
||||
{
|
||||
Rig r;ASSERT_TRUE(r.configure());
|
||||
r.input->put("/f_scan",scan(9,1));r.tick();EXPECT_EQ(r.service.latestSnapshot()->status,Health::kStale);
|
||||
r.input->put("/f_scan",scan(11,2));r.tick();EXPECT_EQ(r.service.latestSnapshot()->status,Health::kInvalidInput);
|
||||
r.input->put("/f_scan",scan(10,3));r.tick();EXPECT_EQ(r.service.latestSnapshot()->status,Health::kValid);
|
||||
r.input->put("/f_scan",scan(10,4));r.tick();EXPECT_EQ(r.service.latestSnapshot()->status,Health::kOutOfOrder);
|
||||
}
|
||||
TEST(Service, ClockResetInvalidatesIdentityAndRequiresNewMeasurements)
|
||||
{
|
||||
Rig r;ASSERT_TRUE(r.configure());r.input->put("/f_scan",scan(10));r.tick();
|
||||
const auto old=r.service.latestSnapshot();
|
||||
r.input->now.store(stamp(1));r.advance(0.01,false);r.tick();
|
||||
auto reset=r.service.latestSnapshot();
|
||||
EXPECT_GT(reset->measurement_epoch,old->measurement_epoch);
|
||||
EXPECT_NE(reset->session_id,old->session_id);EXPECT_TRUE(reset->tracks.empty());
|
||||
r.input->put("/f_scan",scan(1,2));r.tick();
|
||||
EXPECT_EQ(r.service.latestSnapshot()->status,Health::kValid);
|
||||
EXPECT_EQ(old->tracks.size(),1u); // Readers retain immutable old snapshots safely.
|
||||
}
|
||||
TEST(Service, OverflowInvalidScanAndRecovery)
|
||||
{
|
||||
Rig r;r.config.max_tracks=1;ASSERT_TRUE(r.configure());
|
||||
auto s=scan(10);s.ranges={1,1,1,INFINITY,4,4,4};
|
||||
r.input->put("/f_scan",s);r.tick();EXPECT_EQ(r.service.latestSnapshot()->status,Health::kOverflow);
|
||||
r.advance(0.1);s=scan(10.1,2);s.ranges.clear();
|
||||
r.input->put("/f_scan",s);r.tick();
|
||||
EXPECT_EQ(r.service.latestSnapshot()->sources[0].status,Health::kInvalidInput);
|
||||
// Overflow remains latched until a complete valid batch has been represented.
|
||||
EXPECT_EQ(r.service.latestSnapshot()->status,Health::kOverflow);
|
||||
r.advance(0.31);r.input->put("/f_scan",scan(10.41,3));r.tick();
|
||||
EXPECT_EQ(r.service.latestSnapshot()->status,Health::kValid);
|
||||
}
|
||||
TEST(Service, SynchronousExceptionsBecomeFaults)
|
||||
{
|
||||
Rig r;ASSERT_TRUE(r.configure());r.input->throw_read=true;
|
||||
EXPECT_FALSE(r.service.pollOnce(r.error));
|
||||
EXPECT_EQ(r.service.latestSnapshot()->status,Health::kFault);
|
||||
}
|
||||
template<class Predicate> bool await(Predicate predicate)
|
||||
{
|
||||
const auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(2);
|
||||
while(std::chrono::steady_clock::now()<deadline)
|
||||
{
|
||||
if(predicate())return true;
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
}
|
||||
return predicate();
|
||||
}
|
||||
TEST(ServiceThread, StartStopRestartAndConcurrentSnapshots)
|
||||
{
|
||||
auto input=std::make_shared<FakeInput>();input->put("/f_scan",scan(10));
|
||||
TrackerService service;TrackerConfig c;c.sources={{"/f_scan",true,0.3}};
|
||||
std::string error;ASSERT_TRUE(service.configure(c,{input},error));
|
||||
ASSERT_TRUE(service.start(error));ASSERT_TRUE(service.start(error));
|
||||
EXPECT_FALSE(service.configure(c,{input},error));EXPECT_FALSE(service.pollOnce(error));
|
||||
ASSERT_TRUE(await([&]{return service.latestSnapshot()->status==Health::kValid;}));
|
||||
const auto before=service.latestSnapshot();
|
||||
std::atomic<bool> reading{true};
|
||||
std::thread reader([&] {while(reading.load()) {const auto snapshot=service.latestSnapshot(); EXPECT_TRUE(snapshot);}});
|
||||
const auto start=std::chrono::steady_clock::now();service.stop();service.stop();
|
||||
reading=false;reader.join();
|
||||
EXPECT_LT(std::chrono::duration<double>(std::chrono::steady_clock::now()-start).count(),0.2);
|
||||
EXPECT_FALSE(service.running());EXPECT_EQ(service.latestSnapshot()->status,Health::kStopped);
|
||||
ASSERT_TRUE(service.start(error));
|
||||
ASSERT_TRUE(await([&]{return service.latestSnapshot()->status==Health::kValid;}));
|
||||
EXPECT_NE(service.latestSnapshot()->session_id,before->session_id);
|
||||
service.stop();
|
||||
}
|
||||
TEST(ServiceThread, ExceptionsDoNotTerminateProcessAndCanRestart)
|
||||
{
|
||||
auto input=std::make_shared<FakeInput>();input->throw_read=true;
|
||||
TrackerService service;TrackerConfig c;c.sources={{"/f_scan",true,0.3}};
|
||||
std::string error;ASSERT_TRUE(service.configure(c,{input},error));ASSERT_TRUE(service.start(error));
|
||||
ASSERT_TRUE(await([&]{return !service.running();}));
|
||||
EXPECT_EQ(service.latestSnapshot()->status,Health::kFault);
|
||||
input->throw_read=false;input->put("/f_scan",scan(10));
|
||||
ASSERT_TRUE(service.start(error));ASSERT_TRUE(await([&]{return service.latestSnapshot()->status==Health::kValid;}));
|
||||
}
|
||||
TEST(ServiceThread, RepeatedDestructionJoinsWorkers)
|
||||
{
|
||||
auto input=std::make_shared<FakeInput>();
|
||||
TrackerConfig c;c.sources={{"/f_scan",true,0.3}};
|
||||
for(int i=0;i<30;++i)
|
||||
{
|
||||
TrackerService service;std::string error;
|
||||
ASSERT_TRUE(service.configure(c,{input},error));ASSERT_TRUE(service.start(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
224
robot_dynamic_obstacle_tracker/test/simulated_lidar_test.cpp
Normal file
224
robot_dynamic_obstacle_tracker/test/simulated_lidar_test.cpp
Normal file
@@ -0,0 +1,224 @@
|
||||
#include <gtest/gtest.h>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <Eigen/Geometry>
|
||||
#include <robot/time.h>
|
||||
#include <robot_sensor_msgs/LaserScan.h>
|
||||
#include <robot_sensor_ports/sensor_store.h>
|
||||
#include <robot_sensor_ports/sensor_types.h>
|
||||
#include <tf3/buffer_core.h>
|
||||
#include <robot_dynamic_obstacle_tracker/sensor_ports_input.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace robot_dynamic_obstacle_tracker;
|
||||
constexpr double kPi = 3.14159265358979323846;
|
||||
|
||||
struct Circle
|
||||
{
|
||||
Eigen::Vector2d center;
|
||||
double radius;
|
||||
};
|
||||
|
||||
class SimulatedLidarRig
|
||||
{
|
||||
public:
|
||||
SimulatedLidarRig()
|
||||
{
|
||||
robot_sensor_ports::SensorStoreConfig store_config;
|
||||
robot_sensor_ports::SensorEntryConfig source;
|
||||
source.data_type = "robot_sensor_msgs/LaserScan";
|
||||
source.max_age = 0.3;
|
||||
source.topic = "/f_scan";
|
||||
store_config.sensors.push_back(source);
|
||||
source.topic = "/b_scan";
|
||||
store_config.sensors.push_back(source);
|
||||
store_ok_ = store_.configure(store_config, error_);
|
||||
input_ = makeSensorPortsInput(store_, tf_, [this] { return now_; });
|
||||
TrackerConfig config;
|
||||
service_ok_ = store_ok_ && service_.configure(config, dependencies(), error_);
|
||||
}
|
||||
|
||||
Stamp stamp(double time) const
|
||||
{
|
||||
const robot::Time value(time);
|
||||
return static_cast<Stamp>(value.sec) * 1000000000LL + value.nsec;
|
||||
}
|
||||
|
||||
bool ready() const { return store_ok_ && service_ok_; }
|
||||
const std::string& error() const { return error_; }
|
||||
void setTime(double time)
|
||||
{
|
||||
now_ = stamp(time);
|
||||
steady_ += std::chrono::milliseconds(100);
|
||||
}
|
||||
|
||||
bool step(double time, const std::vector<Circle>& circles, double robot_x, double robot_y,
|
||||
double robot_yaw)
|
||||
{
|
||||
setTime(time);
|
||||
const Eigen::Rotation2D<double> base_rotation(robot_yaw);
|
||||
const Eigen::Vector2d base_position(robot_x, robot_y);
|
||||
for (const bool front : {true, false})
|
||||
{
|
||||
const std::string frame = front ? "sim_front_laser" : "sim_rear_laser";
|
||||
const std::string topic = front ? "/f_scan" : "/b_scan";
|
||||
const double extrinsic_yaw = front ? 0.0 : kPi;
|
||||
const Eigen::Vector2d extrinsic(front ? 0.32 : -0.32, 0.0);
|
||||
const Eigen::Vector2d sensor_position = base_position + base_rotation * extrinsic;
|
||||
const double sensor_yaw = robot_yaw + extrinsic_yaw;
|
||||
if (!pushTransform(frame, time, sensor_position, sensor_yaw)) return false;
|
||||
if (!pushScan(topic, frame, time, sensor_position, sensor_yaw, circles)) return false;
|
||||
}
|
||||
return service_.pollOnce(error_);
|
||||
}
|
||||
|
||||
std::shared_ptr<const TrackSnapshot> snapshot() const { return service_.latestSnapshot(); }
|
||||
|
||||
private:
|
||||
TrackerDependencies dependencies()
|
||||
{
|
||||
return {input_, [this] { return steady_; }};
|
||||
}
|
||||
|
||||
bool pushTransform(const std::string& frame, double time, const Eigen::Vector2d& position,
|
||||
double yaw)
|
||||
{
|
||||
tf3::TransformStampedMsg transform;
|
||||
const robot::Time measurement_time(time);
|
||||
transform.header.stamp = tf3::Time(measurement_time.sec, measurement_time.nsec);
|
||||
transform.header.frame_id = "odom";
|
||||
transform.child_frame_id = frame;
|
||||
transform.transform.translation.x = position.x();
|
||||
transform.transform.translation.y = position.y();
|
||||
transform.transform.rotation.z = std::sin(yaw * 0.5);
|
||||
transform.transform.rotation.w = std::cos(yaw * 0.5);
|
||||
if (!tf_->setTransform(transform, "simulated_lidar_test", false))
|
||||
{
|
||||
error_ = "tf3 refused simulated sensor transform";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool pushScan(const std::string& topic, const std::string& frame, double time,
|
||||
const Eigen::Vector2d& sensor_position, double sensor_yaw,
|
||||
const std::vector<Circle>& circles)
|
||||
{
|
||||
robot_sensor_msgs::LaserScan scan;
|
||||
scan.header.stamp = robot::Time(time);
|
||||
scan.header.frame_id = frame;
|
||||
scan.angle_min = -0.75;
|
||||
scan.angle_increment = 1.5 / 240.0;
|
||||
scan.angle_max = scan.angle_min + 240 * scan.angle_increment;
|
||||
scan.range_min = 0.05;
|
||||
scan.range_max = 12.0;
|
||||
scan.scan_time = 0.1;
|
||||
scan.time_increment = scan.scan_time / 240.0;
|
||||
scan.ranges.assign(241, std::numeric_limits<float>::infinity());
|
||||
|
||||
for (std::size_t beam = 0; beam < scan.ranges.size(); ++beam)
|
||||
{
|
||||
const double local_angle = scan.angle_min + beam * scan.angle_increment;
|
||||
const double world_angle = sensor_yaw + local_angle;
|
||||
const Eigen::Vector2d direction(std::cos(world_angle), std::sin(world_angle));
|
||||
double nearest = scan.range_max;
|
||||
for (const auto& circle : circles)
|
||||
{
|
||||
const Eigen::Vector2d relative = circle.center - sensor_position;
|
||||
const double projection = relative.dot(direction);
|
||||
const double discriminant =
|
||||
projection * projection - (relative.squaredNorm() - circle.radius * circle.radius);
|
||||
if (projection <= 0.0 || discriminant < 0.0) continue;
|
||||
const double distance = projection - std::sqrt(discriminant);
|
||||
if (distance >= scan.range_min && distance < nearest) nearest = distance;
|
||||
}
|
||||
if (nearest < scan.range_max) scan.ranges[beam] = static_cast<float>(nearest);
|
||||
}
|
||||
if (!robot_sensor_ports::put(store_, topic, scan, scan.header.stamp))
|
||||
{
|
||||
error_ = "SensorStore rejected a simulated LaserScan";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
robot_sensor_ports::SensorStore store_;
|
||||
std::shared_ptr<tf3::BufferCore> tf_ = std::make_shared<tf3::BufferCore>();
|
||||
Stamp now_ = 0;
|
||||
SteadyTime steady_ = SteadyTime(std::chrono::seconds(1));
|
||||
std::shared_ptr<TrackerInput> input_;
|
||||
TrackerService service_;
|
||||
std::string error_;
|
||||
bool store_ok_ = false, service_ok_ = false;
|
||||
};
|
||||
|
||||
const Track* nearestTo(const std::vector<Track>& tracks, const Eigen::Vector2d& point)
|
||||
{
|
||||
const auto it = std::min_element(tracks.begin(), tracks.end(), [&](const Track& a, const Track& b) {
|
||||
return (a.state.head<2>() - point).squaredNorm() < (b.state.head<2>() - point).squaredNorm();
|
||||
});
|
||||
return it == tracks.end() ? nullptr : &*it;
|
||||
}
|
||||
|
||||
TEST(SimulatedLidar, TracksMovingAndStationaryObjectsWhileRobotMoves)
|
||||
{
|
||||
SimulatedLidarRig rig;
|
||||
ASSERT_TRUE(rig.ready()) << rig.error();
|
||||
|
||||
constexpr double start = 100.0;
|
||||
constexpr int steps = 101;
|
||||
const Eigen::Vector2d fixed_front(4.0, 1.0);
|
||||
const Eigen::Vector2d fixed_rear(-2.0, 0.7);
|
||||
std::vector<Circle> circles;
|
||||
std::shared_ptr<const TrackSnapshot> snapshot;
|
||||
for (int i = 0; i < steps; ++i)
|
||||
{
|
||||
const double elapsed = 0.1 * i;
|
||||
const double time = start + elapsed;
|
||||
const Eigen::Vector2d moving(2.5, -1.0 + 0.25 * elapsed);
|
||||
circles = {{fixed_front, 0.20}, {fixed_rear, 0.18}, {moving, 0.18}};
|
||||
ASSERT_TRUE(rig.step(time, circles, 0.04 * elapsed, 0.0, 0.01 * elapsed))
|
||||
<< "simulated frame " << i << ": " << rig.error();
|
||||
snapshot = rig.snapshot();
|
||||
ASSERT_EQ(snapshot->status, Health::kValid) << snapshot->reason;
|
||||
ASSERT_EQ(snapshot->sources.size(), 2u);
|
||||
EXPECT_EQ(snapshot->sources[0].status, Health::kValid);
|
||||
EXPECT_EQ(snapshot->sources[1].status, Health::kValid);
|
||||
}
|
||||
|
||||
ASSERT_TRUE(snapshot);
|
||||
ASSERT_EQ(snapshot->tracks.size(), 3u) << "unexpected duplicate, missed, or merged detections";
|
||||
|
||||
const double final_elapsed = 0.1 * (steps - 1);
|
||||
const Eigen::Vector2d moving_final(2.5, -1.0 + 0.25 * final_elapsed);
|
||||
const Track* moving = nearestTo(snapshot->tracks, moving_final);
|
||||
ASSERT_NE(moving, nullptr);
|
||||
ASSERT_LT((moving->state.head<2>() - moving_final).norm(), 0.45);
|
||||
EXPECT_NEAR(moving->state.w(), 0.25, 0.10);
|
||||
EXPECT_EQ(moving->lifecycle, TrackLifecycle::kConfirmed);
|
||||
EXPECT_EQ(moving->motion, MotionClass::kMoving);
|
||||
EXPECT_GE(moving->observed_sources.size(), 1u);
|
||||
EXPECT_GT(moving->last_observed_stamp, 0);
|
||||
|
||||
const Track* front = nearestTo(snapshot->tracks, fixed_front);
|
||||
ASSERT_NE(front, nullptr);
|
||||
ASSERT_LT((front->state.head<2>() - fixed_front).norm(), 0.45);
|
||||
EXPECT_LT(front->state.tail<2>().norm(), 0.12);
|
||||
EXPECT_EQ(front->motion, MotionClass::kStationary);
|
||||
ASSERT_EQ(front->observed_sources.size(), 1u);
|
||||
EXPECT_EQ(front->observed_sources.front(), 0u);
|
||||
|
||||
const Track* rear = nearestTo(snapshot->tracks, fixed_rear);
|
||||
ASSERT_NE(rear, nullptr);
|
||||
ASSERT_LT((rear->state.head<2>() - fixed_rear).norm(), 0.45);
|
||||
EXPECT_LT(rear->state.tail<2>().norm(), 0.12);
|
||||
EXPECT_EQ(rear->motion, MotionClass::kStationary);
|
||||
ASSERT_EQ(rear->observed_sources.size(), 1u);
|
||||
EXPECT_EQ(rear->observed_sources.front(), 1u);
|
||||
}
|
||||
} // namespace
|
||||
27
robot_dynamic_obstacle_tracker/test/test_helpers.h
Normal file
27
robot_dynamic_obstacle_tracker/test/test_helpers.h
Normal file
@@ -0,0 +1,27 @@
|
||||
#ifndef ROBOT_DYNAMIC_OBSTACLE_TRACKER_TEST_HELPERS_H_
|
||||
#define ROBOT_DYNAMIC_OBSTACLE_TRACKER_TEST_HELPERS_H_
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_types.h>
|
||||
namespace tracker_test
|
||||
{
|
||||
using robot_dynamic_obstacle_tracker::Stamp;
|
||||
using robot_dynamic_obstacle_tracker::Detection;
|
||||
using robot_dynamic_obstacle_tracker::RawScan;
|
||||
inline Stamp stamp(double seconds) { return static_cast<Stamp>(std::llround(seconds * 1e9)); }
|
||||
inline Detection detection(double x, double y, double time, std::size_t source = 0)
|
||||
{
|
||||
Detection d;
|
||||
d.position = {x,y}; d.stamp = stamp(time); d.sources = {source}; d.radius = 0.15;
|
||||
return d;
|
||||
}
|
||||
inline RawScan scan(double time, std::uint64_t sequence = 1, double range = 2.0)
|
||||
{
|
||||
RawScan s;
|
||||
s.stamp = stamp(time); s.sequence = sequence; s.frame = "laser";
|
||||
s.angle_min = -0.03; s.angle_increment = 0.01; s.range_min = 0.05; s.range_max = 20;
|
||||
s.ranges.assign(7, static_cast<float>(range));
|
||||
return s;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
6
robot_dynamic_obstacle_tracker/test/test_main.cpp
Normal file
6
robot_dynamic_obstacle_tracker/test/test_main.cpp
Normal file
@@ -0,0 +1,6 @@
|
||||
#include <gtest/gtest.h>
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
23
robot_dynamic_obstacle_tracker_rviz/CMakeLists.txt
Normal file
23
robot_dynamic_obstacle_tracker_rviz/CMakeLists.txt
Normal file
@@ -0,0 +1,23 @@
|
||||
cmake_minimum_required(VERSION 3.10)
|
||||
project(robot_dynamic_obstacle_tracker_rviz)
|
||||
|
||||
find_package(catkin REQUIRED COMPONENTS
|
||||
geometry_msgs roscpp robot_dynamic_obstacle_tracker robot_sensor_msgs
|
||||
robot_sensor_ports robot_time sensor_msgs tf2_ros visualization_msgs)
|
||||
find_package(Eigen3 REQUIRED)
|
||||
find_path(TF3_INCLUDE_DIR tf3/buffer_core.h REQUIRED)
|
||||
find_library(TF3_LIBRARY NAMES tf3 REQUIRED)
|
||||
|
||||
catkin_package(CATKIN_DEPENDS
|
||||
geometry_msgs roscpp robot_dynamic_obstacle_tracker robot_sensor_msgs
|
||||
robot_sensor_ports robot_time sensor_msgs tf2_ros visualization_msgs)
|
||||
|
||||
include_directories(${catkin_INCLUDE_DIRS} ${EIGEN3_INCLUDE_DIRS} ${TF3_INCLUDE_DIR})
|
||||
add_executable(tracker_rviz_sim src/tracker_rviz_sim.cpp)
|
||||
target_compile_features(tracker_rviz_sim PRIVATE cxx_std_17)
|
||||
target_compile_options(tracker_rviz_sim PRIVATE -Wall -Wextra -Wpedantic)
|
||||
target_link_libraries(tracker_rviz_sim ${catkin_LIBRARIES} ${TF3_LIBRARY})
|
||||
add_dependencies(tracker_rviz_sim ${catkin_EXPORTED_TARGETS})
|
||||
|
||||
install(TARGETS tracker_rviz_sim RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION})
|
||||
install(DIRECTORY launch rviz DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION})
|
||||
41
robot_dynamic_obstacle_tracker_rviz/README.md
Normal file
41
robot_dynamic_obstacle_tracker_rviz/README.md
Normal file
@@ -0,0 +1,41 @@
|
||||
# Dynamic obstacle tracker RViz review
|
||||
|
||||
This standalone ROS1 demo ray-casts two simulated LiDAR scans at 10 Hz, feeds
|
||||
those same scans through `SensorStore` -> `tf3` -> `TrackerService`, and opens
|
||||
RViz. The scene contains static clutter and several obstacles moving on
|
||||
bounded paths while the robot moves within a small area and turns slowly, so
|
||||
the scene stays visible during review. The default layout
|
||||
has 9 stationary and 3 moving circles; counts can be adjusted with the private
|
||||
ROS parameters `static_circle_count` (1-9) and `moving_circle_count` (1-3).
|
||||
|
||||
Build from the workspace root and launch:
|
||||
|
||||
```bash
|
||||
cd ~/T800_ws
|
||||
catkin_make --pkg robot_dynamic_obstacle_tracker_rviz -j2
|
||||
source devel/setup.bash
|
||||
export ROS_MASTER_URI=http://127.0.0.1:11321
|
||||
export ROS_IP=127.0.0.1
|
||||
roslaunch robot_dynamic_obstacle_tracker_rviz tracker_rviz_sim.launch
|
||||
```
|
||||
|
||||
For a denser scene, set the counts on the launch command, for example:
|
||||
|
||||
```bash
|
||||
roslaunch robot_dynamic_obstacle_tracker_rviz tracker_rviz_sim.launch \
|
||||
robot_dynamic_obstacle_tracker_rviz_sim/static_circle_count:=9 \
|
||||
robot_dynamic_obstacle_tracker_rviz_sim/moving_circle_count:=3
|
||||
```
|
||||
|
||||
The dedicated ROS master port keeps these demo topics and TF frames separate
|
||||
from any already-running Gazebo or robot navigation graph.
|
||||
|
||||
RViz shows front/rear simulated LiDAR in blue/orange, tracked stationary
|
||||
objects in green, moving objects in red, unknown motion in yellow, velocity
|
||||
arrows, and a 2 second constant-velocity prediction. Yellow and purple outlines
|
||||
with `GT STATIC`/`GT MOVING` labels show simulated ground truth, so missed or
|
||||
occluded detections remain visible for comparison. The node also publishes
|
||||
`/tracker/status`. Close the launch terminal with Ctrl-C when done.
|
||||
|
||||
This is a visualization harness for the tracker pipeline, not a Gazebo run and
|
||||
not yet an integration with `move_base2` or the real robot's scan topics.
|
||||
@@ -0,0 +1,8 @@
|
||||
<launch>
|
||||
<param name="/use_sim_time" value="false" />
|
||||
<node pkg="robot_dynamic_obstacle_tracker_rviz" type="tracker_rviz_sim"
|
||||
name="robot_dynamic_obstacle_tracker_rviz_sim" output="screen" />
|
||||
<node pkg="rviz" type="rviz" name="tracker_review_rviz"
|
||||
args="-d $(find robot_dynamic_obstacle_tracker_rviz)/rviz/tracker_review.rviz"
|
||||
output="screen" />
|
||||
</launch>
|
||||
20
robot_dynamic_obstacle_tracker_rviz/package.xml
Normal file
20
robot_dynamic_obstacle_tracker_rviz/package.xml
Normal file
@@ -0,0 +1,20 @@
|
||||
<?xml version="1.0"?>
|
||||
<package format="2">
|
||||
<name>robot_dynamic_obstacle_tracker_rviz</name>
|
||||
<version>0.1.0</version>
|
||||
<description>RViz review harness with moving and stationary simulated LiDAR obstacles.</description>
|
||||
<maintainer email="tdd@gmail.com">DuongTD</maintainer>
|
||||
<license>BSD-3-Clause</license>
|
||||
<buildtool_depend>catkin</buildtool_depend>
|
||||
<depend>robot_dynamic_obstacle_tracker</depend>
|
||||
<depend>robot_sensor_ports</depend>
|
||||
<depend>robot_sensor_msgs</depend>
|
||||
<depend>robot_time</depend>
|
||||
<depend>tf3</depend>
|
||||
<depend>roscpp</depend>
|
||||
<depend>sensor_msgs</depend>
|
||||
<depend>geometry_msgs</depend>
|
||||
<depend>visualization_msgs</depend>
|
||||
<depend>tf2_ros</depend>
|
||||
<exec_depend>rviz</exec_depend>
|
||||
</package>
|
||||
83
robot_dynamic_obstacle_tracker_rviz/rviz/tracker_review.rviz
Normal file
83
robot_dynamic_obstacle_tracker_rviz/rviz/tracker_review.rviz
Normal file
@@ -0,0 +1,83 @@
|
||||
Panels:
|
||||
- Class: rviz/Displays
|
||||
Name: Displays
|
||||
- Class: rviz/Views
|
||||
Name: Views
|
||||
Visualization Manager:
|
||||
Class: ""
|
||||
Global Options:
|
||||
Background Color: 35; 38; 42
|
||||
Fixed Frame: odom
|
||||
Frame Rate: 30
|
||||
Displays:
|
||||
- Class: rviz/Grid
|
||||
Enabled: true
|
||||
Name: Ground grid
|
||||
Plane: XY
|
||||
Plane Cell Count: 20
|
||||
Cell Size: 1
|
||||
Color: 105; 112; 120
|
||||
Alpha: 0.5
|
||||
Reference Frame: <Fixed Frame>
|
||||
- Class: rviz/TF
|
||||
Enabled: true
|
||||
Name: TF
|
||||
Frame Timeout: 15
|
||||
Show Arrows: true
|
||||
Show Axes: true
|
||||
Show Names: true
|
||||
Marker Scale: 0.45
|
||||
- Class: rviz/LaserScan
|
||||
Enabled: true
|
||||
Name: Front simulated LiDAR
|
||||
Topic: /f_scan
|
||||
Queue Size: 5
|
||||
Style: Points
|
||||
Size (Pixels): 4
|
||||
Color Transformer: FlatColor
|
||||
Color: 40; 190; 255
|
||||
Use Fixed Frame: true
|
||||
- Class: rviz/LaserScan
|
||||
Enabled: true
|
||||
Name: Rear simulated LiDAR
|
||||
Topic: /b_scan
|
||||
Queue Size: 5
|
||||
Style: Points
|
||||
Size (Pixels): 4
|
||||
Color Transformer: FlatColor
|
||||
Color: 255; 190; 40
|
||||
Use Fixed Frame: true
|
||||
- Class: rviz/MarkerArray
|
||||
Enabled: true
|
||||
Name: Tracked obstacles and velocity
|
||||
Marker Topic: /tracker/tracks
|
||||
- Class: rviz/MarkerArray
|
||||
Enabled: true
|
||||
Name: 2 second constant velocity prediction
|
||||
Marker Topic: /tracker/predictions
|
||||
- Class: rviz/MarkerArray
|
||||
Enabled: true
|
||||
Name: Simulated obstacle ground truth
|
||||
Marker Topic: /tracker/simulated_obstacles
|
||||
Tools:
|
||||
- Class: rviz/Interact
|
||||
- Class: rviz/MoveCamera
|
||||
- Class: rviz/Select
|
||||
- Class: rviz/FocusCamera
|
||||
- Class: rviz/Measure
|
||||
- Class: rviz/SetInitialPose
|
||||
- Class: rviz/SetGoal
|
||||
Views:
|
||||
Current:
|
||||
Class: rviz/Orbit
|
||||
Distance: 11
|
||||
Focal Point:
|
||||
X: 1
|
||||
Y: 0
|
||||
Z: 0
|
||||
Pitch: 1.15
|
||||
Yaw: 0.75
|
||||
Near Clip Distance: 0.01
|
||||
Window Geometry:
|
||||
Width: 1400
|
||||
Height: 900
|
||||
362
robot_dynamic_obstacle_tracker_rviz/src/tracker_rviz_sim.cpp
Normal file
362
robot_dynamic_obstacle_tracker_rviz/src/tracker_rviz_sim.cpp
Normal file
@@ -0,0 +1,362 @@
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <Eigen/Geometry>
|
||||
#include <geometry_msgs/Point.h>
|
||||
#include <geometry_msgs/TransformStamped.h>
|
||||
#include <robot/time.h>
|
||||
#include <robot_dynamic_obstacle_tracker/sensor_ports_input.h>
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_service.h>
|
||||
#include <robot_sensor_msgs/LaserScan.h>
|
||||
#include <robot_sensor_ports/sensor_store.h>
|
||||
#include <robot_sensor_ports/sensor_types.h>
|
||||
#include <ros/ros.h>
|
||||
#include <sensor_msgs/LaserScan.h>
|
||||
#include <std_msgs/ColorRGBA.h>
|
||||
#include <std_msgs/String.h>
|
||||
#include <tf2_ros/transform_broadcaster.h>
|
||||
#include <tf3/buffer_core.h>
|
||||
#include <visualization_msgs/Marker.h>
|
||||
#include <visualization_msgs/MarkerArray.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace robot_dynamic_obstacle_tracker;
|
||||
constexpr double kPi = 3.14159265358979323846;
|
||||
|
||||
struct Circle { Eigen::Vector2d center; double radius; };
|
||||
|
||||
Stamp toStamp(const ros::Time& stamp)
|
||||
{
|
||||
return static_cast<Stamp>(stamp.sec) * 1000000000LL + stamp.nsec;
|
||||
}
|
||||
|
||||
class TrackerRvizSim
|
||||
{
|
||||
public:
|
||||
TrackerRvizSim() : nh_(), private_nh_("~"), tf_(std::make_shared<tf3::BufferCore>())
|
||||
{
|
||||
robot_sensor_ports::SensorStoreConfig store_config;
|
||||
robot_sensor_ports::SensorEntryConfig source;
|
||||
source.data_type = "robot_sensor_msgs/LaserScan";
|
||||
source.max_age = 0.3;
|
||||
source.topic = "/f_scan";
|
||||
store_config.sensors.push_back(source);
|
||||
source.topic = "/b_scan";
|
||||
store_config.sensors.push_back(source);
|
||||
if (!store_.configure(store_config, error_)) throw std::runtime_error(error_);
|
||||
|
||||
input_ = makeSensorPortsInput(store_, tf_, [this] { return latest_stamp_; });
|
||||
TrackerConfig config;
|
||||
config.tracking_frame = "odom";
|
||||
config.sources = {{"/f_scan", true, 0.3}, {"/b_scan", true, 0.3}};
|
||||
if (!service_.configure(config, {input_, [] { return std::chrono::steady_clock::now(); }}, error_))
|
||||
throw std::runtime_error(error_);
|
||||
|
||||
front_pub_ = nh_.advertise<sensor_msgs::LaserScan>("/f_scan", 2);
|
||||
rear_pub_ = nh_.advertise<sensor_msgs::LaserScan>("/b_scan", 2);
|
||||
tracks_pub_ = nh_.advertise<visualization_msgs::MarkerArray>("/tracker/tracks", 2);
|
||||
prediction_pub_ = nh_.advertise<visualization_msgs::MarkerArray>("/tracker/predictions", 2);
|
||||
ground_truth_pub_ = nh_.advertise<visualization_msgs::MarkerArray>("/tracker/simulated_obstacles", 2);
|
||||
status_pub_ = nh_.advertise<std_msgs::String>("/tracker/status", 2);
|
||||
private_nh_.param("static_circle_count", static_circle_count_, 9);
|
||||
private_nh_.param("moving_circle_count", moving_circle_count_, 3);
|
||||
if (static_circle_count_ < 1 || static_circle_count_ > 9)
|
||||
{
|
||||
ROS_WARN("~static_circle_count must be in [1, 9]; clamping");
|
||||
static_circle_count_ = std::clamp(static_circle_count_, 1, 9);
|
||||
}
|
||||
if (moving_circle_count_ < 1 || moving_circle_count_ > 3)
|
||||
{
|
||||
ROS_WARN("~moving_circle_count must be in [1, 3]; clamping");
|
||||
moving_circle_count_ = std::clamp(moving_circle_count_, 1, 3);
|
||||
}
|
||||
start_wall_ = ros::WallTime::now();
|
||||
timer_ = nh_.createTimer(ros::Duration(0.1), &TrackerRvizSim::onTimer, this);
|
||||
ROS_INFO("Tracker RViz simulator started: %d static + %d moving circles; topics /f_scan, /b_scan, /tracker/tracks",
|
||||
static_circle_count_, moving_circle_count_);
|
||||
}
|
||||
|
||||
private:
|
||||
void publishTf(const ros::Time& stamp, double elapsed)
|
||||
{
|
||||
const double yaw = 0.08 * std::sin(0.11 * elapsed);
|
||||
const Eigen::Rotation2D<double> rotation(yaw);
|
||||
const Eigen::Vector2d base(0.35 * std::sin(0.08 * elapsed),
|
||||
0.20 * std::sin(0.07 * elapsed));
|
||||
std::vector<geometry_msgs::TransformStamped> ros_transforms;
|
||||
const auto append = [&](const std::string& child, const Eigen::Vector2d& xy, double angle,
|
||||
const std::string& parent) {
|
||||
tf3::TransformStampedMsg native;
|
||||
native.header.stamp = tf3::Time(stamp.sec, stamp.nsec);
|
||||
native.header.frame_id = parent;
|
||||
native.child_frame_id = child;
|
||||
native.transform.translation.x = xy.x();
|
||||
native.transform.translation.y = xy.y();
|
||||
native.transform.rotation.z = std::sin(angle * 0.5);
|
||||
native.transform.rotation.w = std::cos(angle * 0.5);
|
||||
if (!tf_->setTransform(native, "tracker_rviz_sim", false))
|
||||
throw std::runtime_error("tf3 rejected simulated transform for " + child);
|
||||
|
||||
geometry_msgs::TransformStamped ros_tf;
|
||||
ros_tf.header.stamp = stamp;
|
||||
ros_tf.header.frame_id = parent;
|
||||
ros_tf.child_frame_id = child;
|
||||
ros_tf.transform.translation.x = xy.x();
|
||||
ros_tf.transform.translation.y = xy.y();
|
||||
ros_tf.transform.rotation.z = std::sin(angle * 0.5);
|
||||
ros_tf.transform.rotation.w = std::cos(angle * 0.5);
|
||||
ros_transforms.push_back(ros_tf);
|
||||
};
|
||||
append("base_link", base, yaw, "odom");
|
||||
append("sim_front_laser", base + rotation * Eigen::Vector2d(0.32, 0.0), yaw, "odom");
|
||||
append("sim_rear_laser", base + rotation * Eigen::Vector2d(-0.32, 0.0), yaw + kPi, "odom");
|
||||
broadcaster_.sendTransform(ros_transforms);
|
||||
}
|
||||
|
||||
sensor_msgs::LaserScan makeScan(const std::string& frame, const Eigen::Vector2d& sensor_xy,
|
||||
double sensor_yaw, const std::vector<Circle>& circles,
|
||||
const ros::Time& stamp) const
|
||||
{
|
||||
sensor_msgs::LaserScan scan;
|
||||
scan.header.stamp = stamp;
|
||||
scan.header.frame_id = frame;
|
||||
scan.angle_min = -0.75f;
|
||||
scan.angle_increment = static_cast<float>(1.5 / 240.0);
|
||||
scan.angle_max = scan.angle_min + 240.0f * scan.angle_increment;
|
||||
scan.range_min = 0.05f;
|
||||
scan.range_max = 12.0f;
|
||||
scan.scan_time = 0.1f;
|
||||
scan.time_increment = scan.scan_time / 240.0f;
|
||||
scan.ranges.assign(241, std::numeric_limits<float>::infinity());
|
||||
for (std::size_t beam = 0; beam < scan.ranges.size(); ++beam)
|
||||
{
|
||||
const double angle = sensor_yaw + scan.angle_min + beam * scan.angle_increment;
|
||||
const Eigen::Vector2d direction(std::cos(angle), std::sin(angle));
|
||||
double nearest = scan.range_max;
|
||||
for (const auto& circle : circles)
|
||||
{
|
||||
const Eigen::Vector2d relative = circle.center - sensor_xy;
|
||||
const double projection = relative.dot(direction);
|
||||
const double discriminant = projection * projection -
|
||||
(relative.squaredNorm() - circle.radius * circle.radius);
|
||||
if (projection <= 0.0 || discriminant < 0.0) continue;
|
||||
const double distance = projection - std::sqrt(discriminant);
|
||||
if (distance >= scan.range_min && distance < nearest) nearest = distance;
|
||||
}
|
||||
if (nearest < scan.range_max) scan.ranges[beam] = static_cast<float>(nearest);
|
||||
}
|
||||
return scan;
|
||||
}
|
||||
|
||||
std::vector<Circle> makeObstacles(double elapsed) const
|
||||
{
|
||||
const std::vector<Circle> fixed = {
|
||||
{{3.6, 1.6}, 0.20}, {{3.8, -1.8}, 0.18}, {{5.2, 2.5}, 0.22},
|
||||
{{5.0, -1.3}, 0.19}, {{7.0, 0.5}, 0.20}, {{6.4, -2.5}, 0.22},
|
||||
{{-2.0, 0.7}, 0.18}, {{-3.2, -1.3}, 0.21}, {{-4.5, 1.8}, 0.19}};
|
||||
std::vector<Circle> obstacles(fixed.begin(), fixed.begin() + static_circle_count_);
|
||||
const std::vector<Circle> moving = {
|
||||
{{2.5, -0.6 + std::sin(0.25 * elapsed)}, 0.18},
|
||||
{{4.5, 0.2 + std::sin(0.35 * elapsed)}, 0.18},
|
||||
{{6.6, -0.3 + 1.4 * std::sin(0.22 * elapsed + 1.2)}, 0.20}};
|
||||
obstacles.insert(obstacles.end(), moving.begin(), moving.begin() + moving_circle_count_);
|
||||
return obstacles;
|
||||
}
|
||||
|
||||
void storeAndPublish(const std::string& topic, const sensor_msgs::LaserScan& scan,
|
||||
ros::Publisher& publisher)
|
||||
{
|
||||
robot_sensor_msgs::LaserScan native;
|
||||
native.header.stamp = robot::Time(scan.header.stamp.sec, scan.header.stamp.nsec);
|
||||
native.header.frame_id = scan.header.frame_id;
|
||||
native.angle_min = scan.angle_min;
|
||||
native.angle_max = scan.angle_max;
|
||||
native.angle_increment = scan.angle_increment;
|
||||
native.time_increment = scan.time_increment;
|
||||
native.scan_time = scan.scan_time;
|
||||
native.range_min = scan.range_min;
|
||||
native.range_max = scan.range_max;
|
||||
native.ranges = scan.ranges;
|
||||
native.intensities = scan.intensities;
|
||||
if (!robot_sensor_ports::put(store_, topic, native, native.header.stamp))
|
||||
throw std::runtime_error("SensorStore rejected simulated scan on " + topic);
|
||||
publisher.publish(scan);
|
||||
}
|
||||
|
||||
std_msgs::ColorRGBA color(float r, float g, float b, float a = 1.0f) const
|
||||
{
|
||||
std_msgs::ColorRGBA out; out.r = r; out.g = g; out.b = b; out.a = a; return out;
|
||||
}
|
||||
|
||||
void publishSnapshot(const ros::Time& stamp)
|
||||
{
|
||||
const auto snapshot = service_.latestSnapshot();
|
||||
if (!snapshot) return;
|
||||
visualization_msgs::MarkerArray tracks, predictions;
|
||||
visualization_msgs::Marker clear;
|
||||
clear.action = visualization_msgs::Marker::DELETEALL;
|
||||
tracks.markers.push_back(clear);
|
||||
predictions.markers.push_back(clear);
|
||||
int id = 0;
|
||||
for (const auto& track : snapshot->tracks)
|
||||
{
|
||||
const bool moving = track.motion == MotionClass::kMoving;
|
||||
const auto c = moving ? color(1.0f, 0.16f, 0.10f) :
|
||||
track.motion == MotionClass::kStationary ? color(0.15f, 0.85f, 0.25f) :
|
||||
color(1.0f, 0.75f, 0.10f);
|
||||
visualization_msgs::Marker body;
|
||||
body.header.frame_id = snapshot->frame; body.header.stamp = stamp;
|
||||
body.ns = "tracked_obstacles"; body.id = id++;
|
||||
body.type = visualization_msgs::Marker::CYLINDER;
|
||||
body.action = visualization_msgs::Marker::ADD;
|
||||
body.pose.position.x = track.state.x(); body.pose.position.y = track.state.y();
|
||||
body.pose.position.z = 0.08; body.pose.orientation.w = 1.0;
|
||||
body.scale.x = body.scale.y = std::max(0.12, 2.0 * track.radius);
|
||||
body.scale.z = 0.16; body.color = c;
|
||||
tracks.markers.push_back(body);
|
||||
|
||||
visualization_msgs::Marker label;
|
||||
label.header = body.header; label.ns = "track_labels"; label.id = id++;
|
||||
label.type = visualization_msgs::Marker::TEXT_VIEW_FACING;
|
||||
label.action = visualization_msgs::Marker::ADD;
|
||||
label.pose.position.x = track.state.x(); label.pose.position.y = track.state.y();
|
||||
label.pose.position.z = 0.38; label.pose.orientation.w = 1.0;
|
||||
label.scale.z = 0.22; label.color = color(1, 1, 1);
|
||||
label.text = std::string(track.motion == MotionClass::kMoving ? "MOVING" :
|
||||
track.motion == MotionClass::kStationary ? "STATIC" : "UNKNOWN") +
|
||||
" #" + std::to_string(track.track_id) + " v=" +
|
||||
std::to_string(track.state.tail<2>().norm()).substr(0, 4) + " m/s";
|
||||
tracks.markers.push_back(label);
|
||||
|
||||
visualization_msgs::Marker arrow;
|
||||
arrow.header = body.header; arrow.ns = "track_velocity"; arrow.id = id++;
|
||||
arrow.type = visualization_msgs::Marker::ARROW;
|
||||
arrow.action = visualization_msgs::Marker::ADD;
|
||||
geometry_msgs::Point start, end;
|
||||
start.x = track.state.x(); start.y = track.state.y(); start.z = 0.22;
|
||||
end.x = start.x + track.state.z(); end.y = start.y + track.state.w(); end.z = 0.22;
|
||||
arrow.points = {start, end}; arrow.scale.x = 0.025; arrow.scale.y = 0.07;
|
||||
arrow.scale.z = 0.08; arrow.color = c;
|
||||
tracks.markers.push_back(arrow);
|
||||
|
||||
visualization_msgs::Marker prediction;
|
||||
prediction.header = body.header; prediction.ns = "constant_velocity_prediction";
|
||||
prediction.id = id++; prediction.type = visualization_msgs::Marker::LINE_STRIP;
|
||||
prediction.action = visualization_msgs::Marker::ADD;
|
||||
prediction.scale.x = 0.035; prediction.color = c;
|
||||
for (int step = 0; step <= 20; ++step)
|
||||
{
|
||||
const double t = 0.1 * step;
|
||||
geometry_msgs::Point point;
|
||||
point.x = track.state.x() + t * track.state.z();
|
||||
point.y = track.state.y() + t * track.state.w(); point.z = 0.12;
|
||||
prediction.points.push_back(point);
|
||||
}
|
||||
predictions.markers.push_back(prediction);
|
||||
}
|
||||
tracks_pub_.publish(tracks);
|
||||
prediction_pub_.publish(predictions);
|
||||
std_msgs::String status;
|
||||
status.data = std::string("TrackerService: ") + healthName(snapshot->status) +
|
||||
" | tracks=" + std::to_string(snapshot->tracks.size()) +
|
||||
" | frame=" + snapshot->frame + " | " + snapshot->reason;
|
||||
status_pub_.publish(status);
|
||||
ROS_INFO_THROTTLE(2.0, "%s", status.data.c_str());
|
||||
}
|
||||
|
||||
void publishGroundTruth(const ros::Time& stamp, const std::vector<Circle>& obstacles)
|
||||
{
|
||||
visualization_msgs::MarkerArray markers;
|
||||
visualization_msgs::Marker clear;
|
||||
clear.action = visualization_msgs::Marker::DELETEALL;
|
||||
markers.markers.push_back(clear);
|
||||
int id = 0;
|
||||
for (std::size_t index = 0; index < obstacles.size(); ++index)
|
||||
{
|
||||
const bool moving = index >= static_cast<std::size_t>(static_circle_count_);
|
||||
const auto c = moving ? color(0.95f, 0.25f, 1.0f, 0.95f) : color(0.95f, 0.9f, 0.25f, 0.9f);
|
||||
visualization_msgs::Marker ring;
|
||||
ring.header.frame_id = "odom"; ring.header.stamp = stamp;
|
||||
ring.ns = moving ? "ground_truth_moving" : "ground_truth_static";
|
||||
ring.id = id++; ring.type = visualization_msgs::Marker::LINE_STRIP;
|
||||
ring.action = visualization_msgs::Marker::ADD;
|
||||
ring.scale.x = 0.035; ring.color = c;
|
||||
for (int step = 0; step <= 36; ++step)
|
||||
{
|
||||
const double angle = 2.0 * kPi * step / 36.0;
|
||||
geometry_msgs::Point point;
|
||||
point.x = obstacles[index].center.x() + obstacles[index].radius * std::cos(angle);
|
||||
point.y = obstacles[index].center.y() + obstacles[index].radius * std::sin(angle);
|
||||
point.z = 0.035;
|
||||
ring.points.push_back(point);
|
||||
}
|
||||
markers.markers.push_back(ring);
|
||||
|
||||
visualization_msgs::Marker label;
|
||||
label.header = ring.header; label.ns = "ground_truth_labels"; label.id = id++;
|
||||
label.type = visualization_msgs::Marker::TEXT_VIEW_FACING;
|
||||
label.action = visualization_msgs::Marker::ADD;
|
||||
label.pose.position.x = obstacles[index].center.x();
|
||||
label.pose.position.y = obstacles[index].center.y();
|
||||
label.pose.position.z = 0.32; label.pose.orientation.w = 1.0;
|
||||
label.scale.z = 0.14; label.color = c;
|
||||
label.text = std::string(moving ? "GT MOVING " : "GT STATIC ") + std::to_string(index);
|
||||
markers.markers.push_back(label);
|
||||
}
|
||||
ground_truth_pub_.publish(markers);
|
||||
}
|
||||
|
||||
void onTimer(const ros::TimerEvent&)
|
||||
{
|
||||
try
|
||||
{
|
||||
const ros::Time stamp = ros::Time::now();
|
||||
if (stamp.isZero()) { ROS_WARN_THROTTLE(2.0, "Waiting for a nonzero ROS time"); return; }
|
||||
latest_stamp_ = toStamp(stamp);
|
||||
const double elapsed = (ros::WallTime::now() - start_wall_).toSec();
|
||||
const double yaw = 0.08 * std::sin(0.11 * elapsed);
|
||||
const Eigen::Rotation2D<double> rotation(yaw);
|
||||
const Eigen::Vector2d base(0.35 * std::sin(0.08 * elapsed),
|
||||
0.20 * std::sin(0.07 * elapsed));
|
||||
const std::vector<Circle> obstacles = makeObstacles(elapsed);
|
||||
publishTf(stamp, elapsed);
|
||||
const auto front_xy = base + rotation * Eigen::Vector2d(0.32, 0.0);
|
||||
const auto rear_xy = base + rotation * Eigen::Vector2d(-0.32, 0.0);
|
||||
auto front = makeScan("sim_front_laser", front_xy, yaw, obstacles, stamp);
|
||||
auto rear = makeScan("sim_rear_laser", rear_xy, yaw + kPi, obstacles, stamp);
|
||||
storeAndPublish("/f_scan", front, front_pub_);
|
||||
storeAndPublish("/b_scan", rear, rear_pub_);
|
||||
publishGroundTruth(stamp, obstacles);
|
||||
if (!service_.pollOnce(error_)) throw std::runtime_error("TrackerService pollOnce: " + error_);
|
||||
publishSnapshot(stamp);
|
||||
}
|
||||
catch (const std::exception& ex) { ROS_ERROR_THROTTLE(1.0, "RViz simulator: %s", ex.what()); }
|
||||
}
|
||||
|
||||
ros::NodeHandle nh_, private_nh_;
|
||||
robot_sensor_ports::SensorStore store_;
|
||||
std::shared_ptr<tf3::BufferCore> tf_;
|
||||
std::shared_ptr<TrackerInput> input_;
|
||||
TrackerService service_;
|
||||
tf2_ros::TransformBroadcaster broadcaster_;
|
||||
ros::Publisher front_pub_, rear_pub_, tracks_pub_, prediction_pub_, ground_truth_pub_, status_pub_;
|
||||
ros::Timer timer_;
|
||||
ros::WallTime start_wall_;
|
||||
Stamp latest_stamp_ = 0;
|
||||
std::string error_;
|
||||
int static_circle_count_ = 9, moving_circle_count_ = 3;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
ros::init(argc, argv, "robot_dynamic_obstacle_tracker_rviz_sim");
|
||||
try { TrackerRvizSim node; ros::spin(); }
|
||||
catch (const std::exception& ex) { ROS_FATAL("Cannot start tracker RViz simulator: %s", ex.what()); return 1; }
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user