fix(tracker): suppress false moving tracks
Use short-lived odom background and observed free-space evidence to reject edge jitter and occlusion ghosts. Preserve track identity across clustered fragments and reset state on TF discontinuities.
This commit is contained in:
@@ -39,7 +39,8 @@ 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)
|
||||
src/data_association.cpp src/kalman_track.cpp src/tracker_core.cpp
|
||||
src/static_background_model.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)
|
||||
@@ -63,8 +64,11 @@ 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})
|
||||
set(tracker_native_includes ${catkin_INCLUDE_DIRS}
|
||||
${robot_sensor_ports_INCLUDE_DIRS} ${robot_sensor_msgs_INCLUDE_DIRS}
|
||||
${robot_time_INCLUDE_DIRS} ${TRACKER_TF3_INCLUDE_DIR})
|
||||
set(tracker_native_libraries ${catkin_LIBRARIES}
|
||||
${robot_sensor_ports_LIBRARIES} ${robot_time_LIBRARIES} ${TRACKER_TF3_LIBRARY})
|
||||
if(catkin_EXPORTED_TARGETS)
|
||||
add_dependencies(robot_dynamic_obstacle_tracker ${catkin_EXPORTED_TARGETS})
|
||||
endif()
|
||||
|
||||
@@ -6,8 +6,10 @@ ROS; có thể dùng qua SensorReader/tf3 hoặc input adapter riêng. Bản cat
|
||||
|
||||
## 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_core**: clustering với uncertainty theo khoảng cách/bề rộng,
|
||||
mô hình nền tĩnh cục bộ, gộp mảnh gần nhau, fusion nhiều nguồn, Hungarian association,
|
||||
Kalman constant velocity, lifecycle và phân loại chuyển động theo lịch sử quan sát.
|
||||
Chỉ phụ thuộc Eigen/STL.
|
||||
- **robot_dynamic_obstacle_tracker**: service, snapshot bất biến, YAML loader; adapter
|
||||
SensorReader/tf3 được build khi tìm thấy native dependencies; executable `tracker_olei_node`
|
||||
đọc LaserScan/TF ROS và xuất marker/status.
|
||||
@@ -57,6 +59,17 @@ Mặc định node nhận `/f_scan` (`sensor_msgs/LaserScan`) và tra TF tại
|
||||
Nếu driver/TF chưa hoạt động, health sẽ báo `warming_up`, `stale` hoặc `tf_error`; trạng thái đó
|
||||
không được diễn giải thành “không có vật cản”.
|
||||
|
||||
Profile Olei bật mô hình nền trong `odom`, giới hạn vùng tracking động 12 m và xét tia đi xuyên
|
||||
qua vùng từng quan sát là trống trước khi xác nhận `MOVING`. Bề mặt tĩnh bị người che vẫn được
|
||||
giữ trong nền; chỉ tia thực sự nhìn xuyên vị trí cũ nhiều lần mới xóa nền. Track mới ở vùng chưa
|
||||
quan sát có thể ở `UNKNOWN` cho tới khi đủ bằng chứng. Scan gốc vẫn phải đi vào costmap/lớp
|
||||
tránh va chạm; tracker không thay thế nguồn phát hiện vật cản tức thời.
|
||||
|
||||
`/tracker/tracks` hiện `TENTATIVE`, `COASTING`, `STATIC`, `UNKNOWN` hoặc `MOVING` theo trạng thái
|
||||
thật. Chỉ dùng `TrackLifecycle::kConfirmed` cùng `MotionClass::kMoving` và kiểm tuổi
|
||||
`last_observed_stamp` khi đưa dự đoán động cho planner. `/tracker/status` có số scan đã xử lý/bỏ,
|
||||
số tia được khớp nền, tia ứng viên và tia ứng viên trong vùng từng thấy là trống.
|
||||
|
||||
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.
|
||||
@@ -71,6 +84,8 @@ Sử dụng pollOnce thay start khi cần replay đồng bộ; hai cách này d
|
||||
- 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.
|
||||
Nếu `odom → laser` đổi vị trí/góc vượt ngưỡng cấu hình giữa hai scan, tracker đổi session/epoch
|
||||
và xóa track cùng nền cũ trước khi nhận scan mới.
|
||||
- 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,
|
||||
@@ -78,8 +93,12 @@ Sử dụng pollOnce thay start khi cần replay đồng bộ; hai cách này d
|
||||
- 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.
|
||||
- Disc vẫn bao cụm; padding là giả định cho phần bề mặt không quan sát được. Profile Olei lọc
|
||||
bề mặt nền đã trưởng thành, còn profile mẫu hai LiDAR giữ `background_enabled: false`.
|
||||
Các mảnh nhỏ gần nhau chỉ được gộp khi disc hợp nhất còn dưới `fragment_max_radius`;
|
||||
hai track đã xác nhận riêng không bị gộp ở điểm giao nhau.
|
||||
- Vùng LiDAR trước đây chỉ trả dữ liệu không hợp lệ cần thêm quan sát vùng trống trước khi một
|
||||
ứng viên được gọi là `MOVING`; vật động rất chậm/sát tường có thể ở `UNKNOWN` lâu hơn.
|
||||
- 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.
|
||||
|
||||
@@ -13,6 +13,10 @@ 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
|
||||
tf_max_translation_speed: 3.0 # m/s; reset trạng thái khi TF nhảy lớn.
|
||||
tf_translation_jump_margin: 0.30 # m.
|
||||
tf_max_yaw_rate: 4.0 # rad/s.
|
||||
tf_yaw_jump_margin: 0.15 # rad.
|
||||
# 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
|
||||
@@ -23,6 +27,9 @@ 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.
|
||||
measurement_range_scale: 0.005 # Hệ số tăng uncertainty khi vật ở xa; tăng để bớt tin tâm cụm xa.
|
||||
measurement_extent_scale: 0.2 # Hệ số theo bề rộng cụm; tăng khi tâm cụm bị che khuất hay nhảy.
|
||||
measurement_max_sigma: 0.35 # m; trần uncertainty để không ghép nhầm vật quá xa nhau.
|
||||
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.
|
||||
@@ -35,3 +42,26 @@ 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.
|
||||
confirmation_min_span: 0.15 # s; thời gian quan sát tối thiểu trước khi xác nhận track.
|
||||
motion_window: 0.55 # s; cửa sổ kiểm tra quỹ đạo, tăng để giảm nhãn giả nhưng tăng trễ.
|
||||
motion_min_observations: 5 # Số scan thật tối thiểu trong cửa sổ.
|
||||
motion_known_free_beams: 0 # Mặc định tắt yêu cầu tia rơi vào vùng từng quan sát là trống.
|
||||
motion_known_free_observations: 0 # Mặc định tắt vì profile mẫu không dùng nền.
|
||||
motion_min_displacement: 0.10 # m; độ dời tối thiểu để gọi là moving.
|
||||
motion_max_residual: 0.12 # m; sai số quỹ đạo tối đa, giảm để lọc tâm cụm nhảy.
|
||||
coasting_delay: 0.12 # s; thiếu scan ngắn hơn mức này chưa xem là coast.
|
||||
fragment_join_distance: 0.0 # m; profile mẫu tắt gộp mảnh để giữ hành vi hai LiDAR cũ.
|
||||
fragment_max_radius: 0.65 # m; cụm sau gộp không được rộng hơn mức này.
|
||||
# Mô hình nền tĩnh cục bộ; mặc định tắt để giữ profile hai LiDAR cũ.
|
||||
background_enabled: false
|
||||
background_resolution: 0.10 # m; ô nền nhỏ hơn giảm trộn vật gần nhau nhưng tăng CPU.
|
||||
background_match_distance: 0.32 # m; vùng khớp nền rộng để hấp thụ tia rung ở mép vật tĩnh.
|
||||
background_depth_margin: 0.25 # m; điểm gần hơn nền quá mức này vẫn là ứng viên vật động.
|
||||
background_min_span: 0.50 # s; nền phải được nhìn ổn định đủ lâu.
|
||||
background_min_hits: 8 # Số scan khác nhau cần thấy cùng bề mặt.
|
||||
background_free_min_span: 0.20 # s; vùng trống phải được quan sát đủ lâu.
|
||||
background_free_min_hits: 3 # Số scan nhìn xuyên vùng trống trước khi tin.
|
||||
background_clear_scans: 4 # Số lần tia thực sự đi xuyên vị trí cũ trước khi xóa nền.
|
||||
background_retention: 20.0 # s; nền quá cũ tự hết hạn.
|
||||
background_radius: 12.0 # m; bán kính theo dõi động và lưu nền quanh LiDAR.
|
||||
background_dynamic_padding: 0.20 # m; không học điểm nằm sát track đang moving.
|
||||
|
||||
@@ -10,6 +10,10 @@ fusion_distance: 0.25
|
||||
fusion_max_speed: 3.0
|
||||
future_tolerance: 0.02
|
||||
clock_jump_reset: 1.0
|
||||
tf_max_translation_speed: 3.0 # m/s; vượt tốc độ + biên độ bên dưới thì xóa track/nền.
|
||||
tf_translation_jump_margin: 0.30 # m; dung sai cho odom/TF rung giữa hai scan.
|
||||
tf_max_yaw_rate: 4.0 # rad/s.
|
||||
tf_yaw_jump_margin: 0.15 # rad.
|
||||
max_scan_points: 32768
|
||||
max_detections: 128
|
||||
max_tracks: 128
|
||||
@@ -19,6 +23,9 @@ cluster_angle_scale: 1.5
|
||||
min_radius: 0.10
|
||||
extent_padding: 0.10
|
||||
measurement_sigma: 0.05
|
||||
measurement_range_scale: 0.005 # Hệ số uncertainty theo khoảng cách; tăng để bớt tin cụm xa.
|
||||
measurement_extent_scale: 0.2 # Hệ số uncertainty theo bề rộng cụm.
|
||||
measurement_max_sigma: 0.35 # m; trần uncertainty khi ghép track.
|
||||
initial_velocity_sigma: 1.0
|
||||
acceleration_noise: 1.0
|
||||
gate_chi2: 9.21
|
||||
@@ -31,3 +38,26 @@ max_prediction: 0.5
|
||||
moving_speed: 0.15
|
||||
stationary_speed: 0.08
|
||||
motion_velocity_sigma: 0.7
|
||||
confirmation_min_span: 0.15 # s; track mới cần tồn tại đủ lâu.
|
||||
motion_window: 0.55 # s; đo độ dời nhất quán qua nhiều scan.
|
||||
motion_min_observations: 5 # Số quan sát thật tối thiểu.
|
||||
motion_known_free_beams: 3 # Tối thiểu 3 tia của cụm vào vùng từng thấy là trống.
|
||||
motion_known_free_observations: 3 # Cần ít nhất 3 scan có bằng chứng vùng trống để gọi MOVING.
|
||||
motion_min_displacement: 0.10 # m; vật chưa dời đủ giữ UNKNOWN.
|
||||
motion_max_residual: 0.12 # m; quỹ đạo nhiễu hơn mức này giữ UNKNOWN.
|
||||
coasting_delay: 0.12 # s; thiếu scan ngắn chưa coi là coast.
|
||||
fragment_join_distance: 0.55 # m; gộp các mảnh gần nhau của cùng vật trước khi cấp ID.
|
||||
fragment_max_radius: 0.65 # m; chặn gộp hai vật cách nhau quá xa.
|
||||
# Nền tĩnh cục bộ trong odom, dùng để loại tia của tường/kệ khi người đi che rồi lộ lại.
|
||||
background_enabled: true
|
||||
background_resolution: 0.10 # m; giảm để phân biệt vật sát nhau, nhưng tốn CPU hơn.
|
||||
background_match_distance: 0.32 # m; hấp thụ tia rung dọc cạnh vật tĩnh.
|
||||
background_depth_margin: 0.25 # m; người gần hơn nền quá mức này vẫn được giữ.
|
||||
background_min_span: 0.50 # s; nền chỉ chín sau nhiều scan.
|
||||
background_min_hits: 8 # Số scan khác nhau phải nhìn thấy cùng bề mặt.
|
||||
background_free_min_span: 0.20 # s; vùng trống phải được nhìn xuyên đủ lâu.
|
||||
background_free_min_hits: 3 # Số scan khác nhau nhìn thấy vùng trống.
|
||||
background_clear_scans: 4 # Chỉ xóa nền khi tia đi xuyên chỗ cũ nhiều lần; tia bị người che không tính.
|
||||
background_retention: 20.0 # s; nền cũ hết hạn để tránh odom trôi kéo dài.
|
||||
background_radius: 12.0 # m; ngoài vùng này không xuất track động cho local planner.
|
||||
background_dynamic_padding: 0.20 # m; không học người đang moving thành nền.
|
||||
|
||||
@@ -1,6 +1,56 @@
|
||||
# Kiểm chứng tracker
|
||||
|
||||
Ngày triển khai: 2026-10-06.
|
||||
Ngày triển khai: 2026-10-06; cập nhật: 2026-10-07. Các mục 1–5 bên dưới lưu kết quả gốc
|
||||
ngày 2026-10-06; phần cập nhật này là bằng chứng mới nhất.
|
||||
|
||||
## Cập nhật 2026-10-07: Olei bag một người
|
||||
|
||||
Bag robot 34,5 s chứa 514 `/f_scan` ở 15 Hz, `/odom`, `/tf` và marker tracker cũ. Người vận hành
|
||||
xác nhận chỉ **một người** đi qua đi lại. `/odom` không đổi vị trí/góc trong bag. Replay chỉ phát
|
||||
`/f_scan /odom /tf /tf_static`, không phát lại marker tracker cũ.
|
||||
|
||||
| Khoảng từ đầu bag | Marker cũ: trung bình / tối đa `MOVING`, số ID | Node mới replay 1×: trung bình / tối đa `MOVING`, số ID |
|
||||
|---|---:|---:|
|
||||
| 0–20 s | 2,096 / 4; 12 ID | 0 / 0; 0 ID |
|
||||
| 20–29 s | 8,311 / 12; 36 ID | 0,400 / 1; 1 ID |
|
||||
| 29–35 s | 2,636 / 5; 9 ID | 0 / 0; 0 ID |
|
||||
|
||||
Replay 1× cuối cùng tạo 344 frame marker; status cuối `valid`, 510 scan xử lý, 3 scan bị bỏ.
|
||||
Chỉ có một ID `MOVING #39` trong cửa sổ 20–29 s; không có frame nào chứa hai nhãn `MOVING`.
|
||||
ID cụ thể và số frame có thể đổi giữa các lượt replay do lịch xử lý ROS và scan mới nhất trong
|
||||
queue. JSON kết quả và log của lượt cuối ở
|
||||
`/tmp/tracker_analysis_20261007/post_tf_guard_fixed_replay_summary.json` và
|
||||
`/tmp/tracker_analysis_20261007/fixed_node.log`. Bản mới dùng mô hình nền cục bộ
|
||||
có xét tia bị che, bằng chứng vùng trống,
|
||||
gộp mảnh nhỏ và cửa sổ quỹ đạo. Test catkin bật adapter native đã chạy lại **29 core + 18
|
||||
service + 4 config + 8 SensorPorts + 1 LiDAR mô phỏng = 60 case**, 0 failure; standalone CTest
|
||||
3 executable pass. Trước khi bật adapter, lượt catkin riêng có 47 case và cũng 0 failure.
|
||||
|
||||
Giới hạn bằng chứng: chưa có nhãn vị trí và thời điểm chuẩn của người để đo recall/ID switch;
|
||||
bag robot đứng yên nên chưa xác nhận deskew hay nền khi robot chạy thật; ca tường tĩnh với sensor
|
||||
tịnh tiến trong `odom` đã qua test tổng hợp. Chưa đo CPU trên NUC.
|
||||
Ứng viên xuất hiện ở vùng LiDAR trước đó chỉ trả dữ liệu không hợp lệ có thể ở `UNKNOWN` lâu hơn.
|
||||
Scan gốc phải tiếp tục cấp cho costmap để tránh va chạm trong khoảng này.
|
||||
|
||||
Lệnh replay thủ công trên máy dev, mỗi khối ở một terminal sau khi build và source workspace:
|
||||
|
||||
export ROS_MASTER_URI=http://127.0.0.1:11333
|
||||
export ROS_HOSTNAME=127.0.0.1
|
||||
roscore -p 11333
|
||||
|
||||
source /home/duongtd/T800_ws/devel/setup.bash
|
||||
export ROS_MASTER_URI=http://127.0.0.1:11333
|
||||
export ROS_HOSTNAME=127.0.0.1
|
||||
rosparam set /use_sim_time true
|
||||
roslaunch robot_dynamic_obstacle_tracker tracker_olei.launch publish_odom_tf:=false
|
||||
|
||||
export ROS_MASTER_URI=http://127.0.0.1:11333
|
||||
export ROS_HOSTNAME=127.0.0.1
|
||||
rosbag play --clock /tmp/tracker_analysis_20261007/olei_tracker.bag \
|
||||
--topics /f_scan /odom /tf /tf_static
|
||||
|
||||
Đường dẫn `/tmp/tracker_analysis_20261007/olei_tracker.bag` là bản sao trên máy dev của bag robot
|
||||
`/home/robotics/kit_ws/src/logs/tracker_failure_20261007_095727/olei_tracker.bag`.
|
||||
|
||||
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.
|
||||
|
||||
@@ -9,7 +9,8 @@ class ScanClusterer
|
||||
public:
|
||||
explicit ScanClusterer(const TrackerConfig& config);
|
||||
ProcessingResult detect(const RawScan&, const PlanarTransform&, std::size_t source,
|
||||
std::vector<Detection>& out) const;
|
||||
std::vector<Detection>& out,
|
||||
const std::vector<std::uint8_t>* candidate_beams = nullptr) const;
|
||||
private:
|
||||
TrackerConfig config_;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
#ifndef ROBOT_DYNAMIC_OBSTACLE_TRACKER_STATIC_BACKGROUND_MODEL_H_
|
||||
#define ROBOT_DYNAMIC_OBSTACLE_TRACKER_STATIC_BACKGROUND_MODEL_H_
|
||||
|
||||
#include <cstdint>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_config.h>
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_types.h>
|
||||
|
||||
namespace robot_dynamic_obstacle_tracker
|
||||
{
|
||||
struct BackgroundStats
|
||||
{
|
||||
std::size_t static_beams = 0, candidate_beams = 0, outside_beams = 0;
|
||||
std::size_t known_free_beams = 0;
|
||||
};
|
||||
|
||||
// Short-lived occupied surface evidence in odom. A ray only clears cells it traverses;
|
||||
// a return in front of a wall never clears the occluded wall.
|
||||
class StaticBackgroundModel
|
||||
{
|
||||
public:
|
||||
explicit StaticBackgroundModel(const TrackerConfig& config);
|
||||
void reset();
|
||||
void classify(const RawScan& scan, const PlanarTransform& transform,
|
||||
std::vector<std::uint8_t>& candidate_beams,
|
||||
BackgroundStats* stats = nullptr) const;
|
||||
void integrate(const RawScan& scan, const PlanarTransform& transform,
|
||||
const std::vector<Track>& tracks);
|
||||
std::size_t cellCount() const { return cells_.size(); }
|
||||
|
||||
private:
|
||||
struct Key
|
||||
{
|
||||
int x = 0, y = 0;
|
||||
bool operator==(const Key& other) const { return x == other.x && y == other.y; }
|
||||
};
|
||||
struct KeyHash
|
||||
{
|
||||
std::size_t operator()(const Key& key) const;
|
||||
};
|
||||
struct Cell
|
||||
{
|
||||
Eigen::Vector2d center = Eigen::Vector2d::Zero();
|
||||
Stamp first_hit = 0, last_hit = 0, last_free = 0;
|
||||
std::size_t hits = 0, free_scans = 0;
|
||||
};
|
||||
struct FreeCell
|
||||
{
|
||||
Stamp first_free = 0, last_free = 0;
|
||||
std::size_t free_scans = 0;
|
||||
};
|
||||
Key keyFor(const Eigen::Vector2d& point) const;
|
||||
Cell* nearestCell(const Eigen::Vector2d& point, double distance);
|
||||
const Cell* nearestCell(const Eigen::Vector2d& point, double distance,
|
||||
bool mature_only = false) const;
|
||||
bool mature(const Cell& cell) const;
|
||||
bool knownFree(const Eigen::Vector2d& point, Stamp stamp) const;
|
||||
bool nearMovingTrack(const Eigen::Vector2d& point, const std::vector<Track>& tracks) const;
|
||||
bool validRange(const RawScan& scan, float range) const;
|
||||
TrackerConfig config_;
|
||||
std::unordered_map<Key, Cell, KeyHash> cells_;
|
||||
std::unordered_map<Key, FreeCell, KeyHash> free_cells_;
|
||||
};
|
||||
} // namespace robot_dynamic_obstacle_tracker
|
||||
#endif
|
||||
@@ -21,17 +21,36 @@ struct TrackerConfig
|
||||
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].
|
||||
double tf_max_translation_speed = 3.0, tf_translation_jump_margin = 0.30; // [m/s], [m].
|
||||
double tf_max_yaw_rate = 4.0, tf_yaw_jump_margin = 0.15; // [rad/s], [rad].
|
||||
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 measurement_range_scale = 0.005, measurement_extent_scale = 0.2;
|
||||
double measurement_max_sigma = 0.35; // [m], cap for uncertain cluster centroids.
|
||||
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].
|
||||
double confirmation_min_span = 0.15, motion_window = 0.55; // [s].
|
||||
std::size_t motion_min_observations = 5;
|
||||
std::size_t motion_known_free_beams = 0, motion_known_free_observations = 0;
|
||||
double motion_min_displacement = 0.10, motion_max_residual = 0.12; // [m].
|
||||
double coasting_delay = 0.12; // [s], publishing delay without a missed scan.
|
||||
double fragment_join_distance = 0.0, fragment_max_radius = 0.65; // [m], 0 disables grouping.
|
||||
|
||||
bool background_enabled = false; // Enable for single-LiDAR Olei profile.
|
||||
double background_resolution = 0.10, background_match_distance = 0.32; // [m].
|
||||
double background_depth_margin = 0.25; // [m], keep returns clearly in front of background.
|
||||
double background_min_span = 0.50, background_retention = 20.0; // [s].
|
||||
double background_free_min_span = 0.20; // [s].
|
||||
double background_radius = 12.0, background_dynamic_padding = 0.20; // [m].
|
||||
std::size_t background_min_hits = 8, background_clear_scans = 4;
|
||||
std::size_t background_free_min_hits = 3;
|
||||
|
||||
bool validate(std::string& error) const;
|
||||
};
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#ifndef ROBOT_DYNAMIC_OBSTACLE_TRACKER_TRACKER_CORE_H_
|
||||
#define ROBOT_DYNAMIC_OBSTACLE_TRACKER_TRACKER_CORE_H_
|
||||
#include <deque>
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_config.h>
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_types.h>
|
||||
namespace robot_dynamic_obstacle_tracker
|
||||
@@ -16,8 +17,20 @@ public:
|
||||
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; };
|
||||
struct Observation
|
||||
{
|
||||
Stamp stamp = 0;
|
||||
Eigen::Vector2d position = Eigen::Vector2d::Zero();
|
||||
bool known_free = false;
|
||||
};
|
||||
struct Record
|
||||
{
|
||||
Track track;
|
||||
std::deque<Observation> observations;
|
||||
std::size_t moving_hits = 0, stationary_hits = 0;
|
||||
};
|
||||
void classify(Record&);
|
||||
void addObservation(Record&, const Detection&);
|
||||
TrackerConfig config_;
|
||||
std::vector<Record> tracks_;
|
||||
std::uint64_t session_id_ = 0, next_id_ = 1;
|
||||
|
||||
@@ -43,6 +43,8 @@ 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].
|
||||
std::size_t beam_count = 0; // 0 for external detections without scan support metadata.
|
||||
std::size_t known_free_beams = 0; // Returns in space observed free before this scan.
|
||||
Stamp stamp = 0;
|
||||
Stamp observed_stamp = 0; // Actual last return time; 0 means stamp for unfused detections.
|
||||
std::vector<std::size_t> sources;
|
||||
@@ -75,6 +77,8 @@ struct SourceHealth
|
||||
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;
|
||||
std::size_t last_static_beams = 0, last_candidate_beams = 0, last_outside_beams = 0;
|
||||
std::size_t last_known_free_beams = 0;
|
||||
SteadyTime last_receive_steady_time{}, last_success_steady_time{};
|
||||
std::string reason;
|
||||
};
|
||||
|
||||
@@ -56,6 +56,8 @@ ProcessingResult fuseDetections(const std::vector<DetectionFrame>& frames, Stamp
|
||||
merged.covariance = Eigen::Matrix2d::Identity() * variance;
|
||||
merged.position = center;
|
||||
merged.observed_stamp = std::max(merged.observed_stamp, d.observed_stamp);
|
||||
merged.beam_count += d.beam_count;
|
||||
merged.known_free_beams += d.known_free_beams;
|
||||
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));
|
||||
|
||||
@@ -9,6 +9,7 @@ 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.known_free_beams > d.beam_count ||
|
||||
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;
|
||||
@@ -45,8 +46,9 @@ bool correctTrack(Track& t, const Detection& d)
|
||||
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());
|
||||
// Expand immediately for safety; shrink over subsequent observations after an outlier.
|
||||
const double observed_radius = d.radius + (d.position - t.state.head<2>()).norm();
|
||||
t.radius = std::max(observed_radius, 0.5 * (t.radius + observed_radius));
|
||||
return t.state.allFinite() && t.covariance.allFinite();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,6 +154,7 @@ public:
|
||||
private_nh_.param("max_scan_age", max_age, max_age);
|
||||
config.sources = {{scan_topic, true, max_age}};
|
||||
if (!config.validate(error)) throw std::runtime_error("invalid tracker config: " + error);
|
||||
max_prediction_ = config.max_prediction;
|
||||
|
||||
input_->registerSource(scan_topic, max_age);
|
||||
input_->setTopic(scan_topic);
|
||||
@@ -216,9 +217,14 @@ private:
|
||||
tracks.markers.push_back(clear);
|
||||
predictions.markers.push_back(clear);
|
||||
int id = 0;
|
||||
std::size_t confirmed_moving = 0;
|
||||
for (const auto& track : snapshot->tracks)
|
||||
{
|
||||
const double age = std::max(0.0, secondsBetween(snapshot->state_stamp, track.last_observed_stamp));
|
||||
const bool moving = track.motion == MotionClass::kMoving;
|
||||
const bool fresh_moving = moving && track.lifecycle == TrackLifecycle::kConfirmed &&
|
||||
age <= max_prediction_;
|
||||
if (fresh_moving) ++confirmed_moving;
|
||||
const auto color = moving ? makeColor(1.0f, 0.16f, 0.10f) :
|
||||
track.motion == MotionClass::kStationary ? makeColor(0.15f, 0.85f, 0.25f) :
|
||||
makeColor(1.0f, 0.75f, 0.10f);
|
||||
@@ -231,6 +237,7 @@ private:
|
||||
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 = color;
|
||||
if (track.lifecycle != TrackLifecycle::kConfirmed) body.color.a = 0.35f;
|
||||
tracks.markers.push_back(body);
|
||||
|
||||
visualization_msgs::Marker label;
|
||||
@@ -240,9 +247,12 @@ private:
|
||||
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.20; label.color = makeColor(1, 1, 1);
|
||||
label.text = std::string(moving ? "MOVING #" :
|
||||
label.text = std::string(track.lifecycle == TrackLifecycle::kTentative ? "TENTATIVE #" :
|
||||
track.lifecycle == TrackLifecycle::kCoasting ? "COASTING #" :
|
||||
moving ? "MOVING #" :
|
||||
track.motion == MotionClass::kStationary ? "STATIC #" : "UNKNOWN #") +
|
||||
std::to_string(track.track_id);
|
||||
if (track.lifecycle != TrackLifecycle::kConfirmed) label.color.a = 0.55f;
|
||||
tracks.markers.push_back(label);
|
||||
|
||||
visualization_msgs::Marker arrow;
|
||||
@@ -253,30 +263,44 @@ private:
|
||||
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 = color;
|
||||
arrow.scale.z = 0.08; arrow.color = body.color;
|
||||
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 = color;
|
||||
for (int step = 0; step <= 10; ++step)
|
||||
prediction.scale.x = 0.035; prediction.color = body.color;
|
||||
const int prediction_steps = moving && age <= max_prediction_ ?
|
||||
static_cast<int>(std::ceil(std::max(0.0, max_prediction_ - age) / 0.1)) : 0;
|
||||
for (int step = 0; step <= prediction_steps; ++step)
|
||||
{
|
||||
const double dt = 0.1 * step;
|
||||
const double dt = std::min(max_prediction_ - age, 0.1 * step);
|
||||
geometry_msgs::Point point;
|
||||
point.x = track.state.x() + dt * track.state.z();
|
||||
point.y = track.state.y() + dt * track.state.w(); point.z = 0.12;
|
||||
prediction.points.push_back(point);
|
||||
}
|
||||
predictions.markers.push_back(prediction);
|
||||
if (prediction_steps > 0) 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()) +
|
||||
" | confirmed_moving=" + std::to_string(confirmed_moving) +
|
||||
" | frame=" + snapshot->frame + " | " + snapshot->reason;
|
||||
if (!snapshot->sources.empty())
|
||||
status.data += " | scans processed/dropped=" +
|
||||
std::to_string(snapshot->sources.front().processed_count) + "/" +
|
||||
std::to_string(snapshot->sources.front().dropped_count) +
|
||||
" | beams static/candidate/outside=" +
|
||||
std::to_string(snapshot->sources.front().last_static_beams) + "/" +
|
||||
std::to_string(snapshot->sources.front().last_candidate_beams) + "/" +
|
||||
std::to_string(snapshot->sources.front().last_outside_beams);
|
||||
if (!snapshot->sources.empty())
|
||||
status.data += " | known_free_candidates=" +
|
||||
std::to_string(snapshot->sources.front().last_known_free_beams);
|
||||
status_pub_.publish(status);
|
||||
ROS_INFO_THROTTLE(2.0, "%s", status.data.c_str());
|
||||
}
|
||||
@@ -291,6 +315,7 @@ private:
|
||||
ros::Subscriber odom_subscriber_;
|
||||
ros::Publisher tracks_pub_, prediction_pub_, status_pub_;
|
||||
ros::Timer timer_;
|
||||
double max_prediction_ = 0.5;
|
||||
};
|
||||
} // namespace
|
||||
} // namespace robot_dynamic_obstacle_tracker
|
||||
|
||||
@@ -11,13 +11,15 @@ ScanClusterer::ScanClusterer(const TrackerConfig& config) : config_(config)
|
||||
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
|
||||
std::size_t source, std::vector<Detection>& out,
|
||||
const std::vector<std::uint8_t>* candidate_beams) 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() ||
|
||||
(candidate_beams && candidate_beams->size() != scan.ranges.size()) ||
|
||||
!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) ||
|
||||
@@ -28,21 +30,34 @@ ProcessingResult ScanClusterer::detect(const RawScan& scan, const PlanarTransfor
|
||||
|
||||
std::vector<Eigen::Vector2d> cluster;
|
||||
cluster.reserve(scan.ranges.size());
|
||||
double cluster_range_sum = 0.0;
|
||||
std::size_t cluster_known_free_beams = 0;
|
||||
auto flush = [&]() {
|
||||
if (cluster.empty()) return;
|
||||
if (cluster.size() < config_.min_cluster_points) { ++result.small_clusters; cluster.clear(); return; }
|
||||
if (cluster.size() < config_.min_cluster_points)
|
||||
{ ++result.small_clusters; cluster.clear(); cluster_range_sum = 0.0;
|
||||
cluster_known_free_beams = 0; 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.beam_count = cluster.size();
|
||||
detection.known_free_beams = cluster_known_free_beams;
|
||||
const double mean_range = cluster_range_sum / static_cast<double>(cluster.size());
|
||||
const double sigma = std::min(config_.measurement_max_sigma,
|
||||
std::hypot(config_.measurement_sigma,
|
||||
std::hypot(config_.measurement_range_scale * mean_range,
|
||||
config_.measurement_extent_scale * visible_radius)));
|
||||
detection.covariance = Eigen::Matrix2d::Identity() * sigma * 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();
|
||||
cluster_range_sum = 0.0;
|
||||
cluster_known_free_beams = 0;
|
||||
};
|
||||
double previous_range = 0;
|
||||
std::size_t valid_returns = 0, no_returns = 0;
|
||||
@@ -57,12 +72,15 @@ ProcessingResult ScanClusterer::detect(const RawScan& scan, const PlanarTransfor
|
||||
continue;
|
||||
}
|
||||
++valid_returns;
|
||||
if (candidate_beams && !(*candidate_beams)[i]) { flush(); continue; }
|
||||
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);
|
||||
cluster_range_sum += r;
|
||||
if (candidate_beams && (*candidate_beams)[i] == 2) ++cluster_known_free_beams;
|
||||
previous_range = r;
|
||||
}
|
||||
flush();
|
||||
|
||||
200
robot_dynamic_obstacle_tracker/src/static_background_model.cpp
Normal file
200
robot_dynamic_obstacle_tracker/src/static_background_model.cpp
Normal file
@@ -0,0 +1,200 @@
|
||||
#include <robot_dynamic_obstacle_tracker/static_background_model.h>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
|
||||
namespace robot_dynamic_obstacle_tracker
|
||||
{
|
||||
StaticBackgroundModel::StaticBackgroundModel(const TrackerConfig& config) : config_(config) {}
|
||||
|
||||
void StaticBackgroundModel::reset() { cells_.clear(); free_cells_.clear(); }
|
||||
|
||||
std::size_t StaticBackgroundModel::KeyHash::operator()(const Key& key) const
|
||||
{
|
||||
const auto x = static_cast<std::uint32_t>(key.x);
|
||||
const auto y = static_cast<std::uint32_t>(key.y);
|
||||
return static_cast<std::size_t>((static_cast<std::uint64_t>(x) << 32) | y);
|
||||
}
|
||||
|
||||
StaticBackgroundModel::Key StaticBackgroundModel::keyFor(const Eigen::Vector2d& point) const
|
||||
{
|
||||
return {static_cast<int>(std::floor(point.x() / config_.background_resolution)),
|
||||
static_cast<int>(std::floor(point.y() / config_.background_resolution))};
|
||||
}
|
||||
|
||||
const StaticBackgroundModel::Cell* StaticBackgroundModel::nearestCell(
|
||||
const Eigen::Vector2d& point, double distance, bool mature_only) const
|
||||
{
|
||||
const Key key = keyFor(point);
|
||||
const Cell* nearest = nullptr;
|
||||
double best = distance * distance;
|
||||
const int cells = static_cast<int>(std::ceil(distance / config_.background_resolution));
|
||||
for (int dx = -cells; dx <= cells; ++dx)
|
||||
for (int dy = -cells; dy <= cells; ++dy)
|
||||
{
|
||||
const auto it = cells_.find({key.x + dx, key.y + dy});
|
||||
if (it == cells_.end() || (mature_only && !mature(it->second))) continue;
|
||||
const double d2 = (it->second.center - point).squaredNorm();
|
||||
if (d2 <= best) { best = d2; nearest = &it->second; }
|
||||
}
|
||||
return nearest;
|
||||
}
|
||||
|
||||
StaticBackgroundModel::Cell* StaticBackgroundModel::nearestCell(
|
||||
const Eigen::Vector2d& point, double distance)
|
||||
{
|
||||
return const_cast<Cell*>(static_cast<const StaticBackgroundModel*>(this)->nearestCell(
|
||||
point, distance, false));
|
||||
}
|
||||
|
||||
bool StaticBackgroundModel::mature(const Cell& cell) const
|
||||
{
|
||||
return cell.hits >= config_.background_min_hits &&
|
||||
secondsBetween(cell.last_hit, cell.first_hit) >= config_.background_min_span &&
|
||||
cell.free_scans < config_.background_clear_scans;
|
||||
}
|
||||
|
||||
bool StaticBackgroundModel::knownFree(const Eigen::Vector2d& point, Stamp stamp) const
|
||||
{
|
||||
const auto it = free_cells_.find(keyFor(point));
|
||||
return it != free_cells_.end() &&
|
||||
it->second.free_scans >= config_.background_free_min_hits &&
|
||||
secondsBetween(it->second.last_free, it->second.first_free) >=
|
||||
config_.background_free_min_span &&
|
||||
secondsBetween(stamp, it->second.last_free) <= config_.background_retention;
|
||||
}
|
||||
|
||||
bool StaticBackgroundModel::validRange(const RawScan& scan, float range) const
|
||||
{
|
||||
return std::isfinite(range) && range >= scan.range_min && range <= scan.range_max;
|
||||
}
|
||||
|
||||
bool StaticBackgroundModel::nearMovingTrack(
|
||||
const Eigen::Vector2d& point, const std::vector<Track>& tracks) const
|
||||
{
|
||||
for (const auto& track : tracks)
|
||||
if (track.motion == MotionClass::kMoving &&
|
||||
(point - track.state.head<2>()).norm() <=
|
||||
track.radius + config_.background_dynamic_padding)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
void StaticBackgroundModel::classify(const RawScan& scan, const PlanarTransform& transform,
|
||||
std::vector<std::uint8_t>& candidate_beams,
|
||||
BackgroundStats* stats) const
|
||||
{
|
||||
if (stats) *stats = {};
|
||||
candidate_beams.assign(scan.ranges.size(), 1);
|
||||
if (!config_.background_enabled || !transform.valid() ||
|
||||
scan.ranges.size() > config_.max_scan_points || scan.stamp <= 0 ||
|
||||
!std::isfinite(scan.angle_min) || !std::isfinite(scan.angle_increment) ||
|
||||
!std::isfinite(scan.range_min) || !std::isfinite(scan.range_max) ||
|
||||
scan.range_max <= scan.range_min) return;
|
||||
for (std::size_t i = 0; i < scan.ranges.size(); ++i)
|
||||
{
|
||||
const float range = scan.ranges[i];
|
||||
if (!validRange(scan, range)) continue;
|
||||
if (range > config_.background_radius)
|
||||
{ candidate_beams[i] = 0; if (stats) ++stats->outside_beams; continue; }
|
||||
const double angle = scan.angle_min + static_cast<double>(i) * scan.angle_increment;
|
||||
const Eigen::Vector2d point = transform.apply({range * std::cos(angle), range * std::sin(angle)});
|
||||
const Cell* cell = nearestCell(point, config_.background_match_distance, true);
|
||||
// A nearby wall must not hide a return clearly closer to the laser.
|
||||
if (cell && (cell->center - transform.translation).norm() - range <=
|
||||
config_.background_depth_margin)
|
||||
{ candidate_beams[i] = 0; if (stats) ++stats->static_beams; }
|
||||
else
|
||||
{
|
||||
if (stats) ++stats->candidate_beams;
|
||||
if (knownFree(point, scan.stamp))
|
||||
{ candidate_beams[i] = 2; if (stats) ++stats->known_free_beams; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void StaticBackgroundModel::integrate(const RawScan& scan, const PlanarTransform& transform,
|
||||
const std::vector<Track>& tracks)
|
||||
{
|
||||
if (!config_.background_enabled || !transform.valid()) return;
|
||||
const Eigen::Vector2d origin = transform.translation;
|
||||
const double radius2 = config_.background_radius * config_.background_radius;
|
||||
for (auto it = cells_.begin(); it != cells_.end(); )
|
||||
{
|
||||
if (secondsBetween(scan.stamp, it->second.last_hit) > config_.background_retention ||
|
||||
(it->second.center - origin).squaredNorm() > radius2)
|
||||
it = cells_.erase(it);
|
||||
else ++it;
|
||||
}
|
||||
for (auto it = free_cells_.begin(); it != free_cells_.end(); )
|
||||
{
|
||||
const Eigen::Vector2d center((it->first.x + 0.5) * config_.background_resolution,
|
||||
(it->first.y + 0.5) * config_.background_resolution);
|
||||
if (secondsBetween(scan.stamp, it->second.last_free) > config_.background_retention ||
|
||||
(center - origin).squaredNorm() > radius2)
|
||||
it = free_cells_.erase(it);
|
||||
else ++it;
|
||||
}
|
||||
|
||||
// Integrate endpoints first so neighboring free rays cannot erase a visible surface.
|
||||
for (std::size_t i = 0; i < scan.ranges.size(); ++i)
|
||||
{
|
||||
const float range = scan.ranges[i];
|
||||
if (!validRange(scan, range) || range > config_.background_radius) continue;
|
||||
const double angle = scan.angle_min + static_cast<double>(i) * scan.angle_increment;
|
||||
const Eigen::Vector2d point = transform.apply({range * std::cos(angle), range * std::sin(angle)});
|
||||
if (nearMovingTrack(point, tracks)) continue;
|
||||
Cell* cell = nearestCell(point, config_.background_resolution * 1.2);
|
||||
if (!cell)
|
||||
{
|
||||
auto& created = cells_[keyFor(point)];
|
||||
created.center = point;
|
||||
created.first_hit = created.last_hit = scan.stamp;
|
||||
created.hits = 1;
|
||||
continue;
|
||||
}
|
||||
if (cell->last_hit != scan.stamp)
|
||||
{
|
||||
cell->center = 0.9 * cell->center + 0.1 * point;
|
||||
cell->last_hit = scan.stamp;
|
||||
++cell->hits;
|
||||
cell->free_scans = 0;
|
||||
}
|
||||
}
|
||||
|
||||
const double step = config_.background_resolution * 0.5;
|
||||
for (std::size_t i = 0; i < scan.ranges.size(); ++i)
|
||||
{
|
||||
const float range = scan.ranges[i];
|
||||
if (!validRange(scan, range)) continue;
|
||||
const double clear_until = std::min<double>(range - 2.5 * config_.background_resolution,
|
||||
config_.background_radius);
|
||||
if (clear_until <= 0) continue;
|
||||
const double angle = scan.angle_min + static_cast<double>(i) * scan.angle_increment;
|
||||
const Eigen::Vector2d direction = transform.linear *
|
||||
Eigen::Vector2d(std::cos(angle), std::sin(angle));
|
||||
for (double distance = 0.0; distance < clear_until; distance += step)
|
||||
{
|
||||
const auto key = keyFor(origin + distance * direction);
|
||||
auto& free = free_cells_[key];
|
||||
if (free.last_free != scan.stamp)
|
||||
{
|
||||
if (free.free_scans == 0) free.first_free = scan.stamp;
|
||||
free.last_free = scan.stamp;
|
||||
++free.free_scans;
|
||||
}
|
||||
const auto it = cells_.find(key);
|
||||
if (it == cells_.end()) continue;
|
||||
auto& cell = it->second;
|
||||
if (cell.last_hit == scan.stamp || cell.last_free == scan.stamp) continue;
|
||||
cell.last_free = scan.stamp;
|
||||
++cell.free_scans;
|
||||
}
|
||||
}
|
||||
for (auto it = cells_.begin(); it != cells_.end(); )
|
||||
{
|
||||
if (it->second.free_scans >= config_.background_clear_scans) it = cells_.erase(it);
|
||||
else ++it;
|
||||
}
|
||||
}
|
||||
} // namespace robot_dynamic_obstacle_tracker
|
||||
@@ -28,22 +28,59 @@ bool TrackerConfig::validate(std::string& error) const
|
||||
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(tf_max_translation_speed); CHECK_POSITIVE(tf_translation_jump_margin);
|
||||
CHECK_POSITIVE(tf_max_yaw_rate); CHECK_POSITIVE(tf_yaw_jump_margin);
|
||||
CHECK_POSITIVE(cluster_gap); CHECK_POSITIVE(cluster_angle_scale);
|
||||
CHECK_POSITIVE(min_radius); CHECK_POSITIVE(measurement_sigma);
|
||||
CHECK_POSITIVE(measurement_max_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);
|
||||
CHECK_POSITIVE(motion_window); CHECK_POSITIVE(motion_min_displacement);
|
||||
CHECK_POSITIVE(motion_max_residual); CHECK_POSITIVE(coasting_delay);
|
||||
CHECK_POSITIVE(fragment_max_radius);
|
||||
CHECK_POSITIVE(background_resolution); CHECK_POSITIVE(background_match_distance);
|
||||
CHECK_POSITIVE(background_depth_margin);
|
||||
CHECK_POSITIVE(background_min_span); CHECK_POSITIVE(background_retention);
|
||||
CHECK_POSITIVE(background_free_min_span);
|
||||
CHECK_POSITIVE(background_radius); CHECK_POSITIVE(background_dynamic_padding);
|
||||
#undef CHECK_POSITIVE
|
||||
if (!std::isfinite(measurement_range_scale) || measurement_range_scale < 0.0 ||
|
||||
!std::isfinite(measurement_extent_scale) || measurement_extent_scale < 0.0 ||
|
||||
!std::isfinite(confirmation_min_span) || confirmation_min_span < 0.0 ||
|
||||
!std::isfinite(fragment_join_distance) || fragment_join_distance < 0.0)
|
||||
{ error = "measurement scales and confirmation_min_span must be finite and >= 0"; return false; }
|
||||
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)
|
||||
max_tracks < 1 || max_tracks > 512 || confirmation_hits < 1 || motion_hysteresis_hits < 1 ||
|
||||
motion_min_observations < 3 || background_min_hits < 2 || background_clear_scans < 1 ||
|
||||
background_free_min_hits < 2 ||
|
||||
((motion_known_free_beams == 0) != (motion_known_free_observations == 0)) ||
|
||||
motion_known_free_observations > motion_min_observations ||
|
||||
motion_known_free_beams > max_scan_points)
|
||||
{ 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)
|
||||
max_prediction > track_timeout || fusion_wait > tf_wait || poll_period > tf_wait ||
|
||||
measurement_max_sigma < measurement_sigma ||
|
||||
motion_window <= confirmation_min_span ||
|
||||
coasting_delay >= track_timeout ||
|
||||
background_match_distance < background_resolution ||
|
||||
background_depth_margin > background_match_distance ||
|
||||
fragment_join_distance > fragment_max_radius * 2.0 ||
|
||||
background_min_span >= background_retention ||
|
||||
background_free_min_span >= background_retention ||
|
||||
background_radius <= background_match_distance)
|
||||
{ error = "inconsistent motion thresholds, retention, prediction or wait periods"; return false; }
|
||||
if (background_resolution < 0.05 || background_resolution > 0.5 ||
|
||||
background_match_distance > 1.0 || background_radius > 15.0 ||
|
||||
background_retention > 120.0 || background_dynamic_padding > 2.0 ||
|
||||
background_min_hits > 100 || background_clear_scans > 100 ||
|
||||
background_free_min_hits > 100 ||
|
||||
motion_window > 2.0 || motion_min_observations > 64)
|
||||
{ error = "background or motion settings exceed bounded runtime limits"; 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; }
|
||||
|
||||
@@ -23,12 +23,28 @@ bool loadTrackerConfig(const std::string& path, TrackerConfig& out, std::string&
|
||||
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(tf_max_translation_speed) LOAD_FIELD(tf_translation_jump_margin)
|
||||
LOAD_FIELD(tf_max_yaw_rate) LOAD_FIELD(tf_yaw_jump_margin)
|
||||
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(measurement_range_scale) LOAD_FIELD(measurement_extent_scale)
|
||||
LOAD_FIELD(measurement_max_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)
|
||||
LOAD_FIELD(confirmation_min_span) LOAD_FIELD(motion_window)
|
||||
LOAD_FIELD(motion_min_observations) LOAD_FIELD(motion_min_displacement)
|
||||
LOAD_FIELD(motion_known_free_beams) LOAD_FIELD(motion_known_free_observations)
|
||||
LOAD_FIELD(motion_max_residual) LOAD_FIELD(coasting_delay)
|
||||
LOAD_FIELD(fragment_join_distance) LOAD_FIELD(fragment_max_radius)
|
||||
LOAD_FIELD(background_enabled) LOAD_FIELD(background_resolution)
|
||||
LOAD_FIELD(background_match_distance) LOAD_FIELD(background_min_span)
|
||||
LOAD_FIELD(background_depth_margin)
|
||||
LOAD_FIELD(background_free_min_span) LOAD_FIELD(background_free_min_hits)
|
||||
LOAD_FIELD(background_retention) LOAD_FIELD(background_radius)
|
||||
LOAD_FIELD(background_dynamic_padding) LOAD_FIELD(background_min_hits)
|
||||
LOAD_FIELD(background_clear_scans)
|
||||
#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");
|
||||
|
||||
@@ -8,6 +8,70 @@
|
||||
|
||||
namespace robot_dynamic_obstacle_tracker
|
||||
{
|
||||
namespace
|
||||
{
|
||||
int nearbyConfirmedOwner(const Detection& detection, const std::vector<Track>& tracks,
|
||||
double join_distance)
|
||||
{
|
||||
int owner = -1;
|
||||
double best = join_distance;
|
||||
for (std::size_t i = 0; i < tracks.size(); ++i)
|
||||
{
|
||||
if (tracks[i].lifecycle == TrackLifecycle::kTentative) continue;
|
||||
const double distance = (tracks[i].state.head<2>() - detection.position).norm();
|
||||
if (distance < best) { best = distance; owner = static_cast<int>(i); }
|
||||
}
|
||||
return owner;
|
||||
}
|
||||
|
||||
std::vector<Detection> groupFragments(const std::vector<Detection>& input,
|
||||
const std::vector<Track>& tracks,
|
||||
const TrackerConfig& config)
|
||||
{
|
||||
if (config.fragment_join_distance <= 0.0) return input;
|
||||
std::vector<Detection> output;
|
||||
output.reserve(input.size());
|
||||
std::vector<bool> consumed(input.size(), false);
|
||||
for (std::size_t i = 0; i < input.size(); ++i)
|
||||
{
|
||||
if (consumed[i]) continue;
|
||||
Detection group = input[i];
|
||||
consumed[i] = true;
|
||||
if (group.beam_count > 0 && group.radius <= config.fragment_max_radius)
|
||||
{
|
||||
int owner = nearbyConfirmedOwner(group, tracks, config.fragment_join_distance);
|
||||
for (std::size_t j = i + 1; j < input.size(); ++j)
|
||||
{
|
||||
const auto& other = input[j];
|
||||
if (consumed[j] || other.beam_count == 0 ||
|
||||
other.radius > config.fragment_max_radius || other.sources != group.sources ||
|
||||
(other.position - group.position).norm() > config.fragment_join_distance) continue;
|
||||
const int other_owner = nearbyConfirmedOwner(other, tracks, config.fragment_join_distance);
|
||||
if (owner >= 0 && other_owner >= 0 && owner != other_owner) continue;
|
||||
const double a = static_cast<double>(group.beam_count);
|
||||
const double b = static_cast<double>(other.beam_count);
|
||||
const Eigen::Vector2d center = (a * group.position + b * other.position) / (a + b);
|
||||
const double radius = std::max(group.radius + (group.position - center).norm(),
|
||||
other.radius + (other.position - center).norm());
|
||||
if (radius > config.fragment_max_radius) continue;
|
||||
const Eigen::Vector2d da = group.position - center, db = other.position - center;
|
||||
group.covariance = (a * (group.covariance + da * da.transpose()) +
|
||||
b * (other.covariance + db * db.transpose())) / (a + b);
|
||||
group.position = center;
|
||||
group.radius = radius;
|
||||
group.beam_count += other.beam_count;
|
||||
group.known_free_beams += other.known_free_beams;
|
||||
group.observed_stamp = std::max(group.observed_stamp, other.observed_stamp);
|
||||
if (owner < 0) owner = other_owner;
|
||||
consumed[j] = true;
|
||||
}
|
||||
}
|
||||
output.push_back(std::move(group));
|
||||
}
|
||||
return output;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TrackerCore::TrackerCore(const TrackerConfig& config) : config_(config)
|
||||
{
|
||||
std::string error;
|
||||
@@ -21,24 +85,83 @@ void TrackerCore::reset(std::uint64_t session)
|
||||
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 ?
|
||||
const double timeout = r.track.lifecycle == TrackLifecycle::kTentative ?
|
||||
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 ||
|
||||
if (r.track.lifecycle != TrackLifecycle::kConfirmed ||
|
||||
r.observations.size() < config_.motion_min_observations ||
|
||||
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; }
|
||||
const double span = secondsBetween(r.observations.back().stamp, r.observations.front().stamp);
|
||||
if (span < config_.motion_window * 0.65)
|
||||
{ r.moving_hits = r.stationary_hits = 0; r.track.motion = MotionClass::kUnknown; return; }
|
||||
|
||||
double mean_time = 0.0;
|
||||
Eigen::Vector2d mean_position = Eigen::Vector2d::Zero();
|
||||
for (const auto& observation : r.observations)
|
||||
{
|
||||
mean_time += secondsBetween(observation.stamp, r.observations.front().stamp);
|
||||
mean_position += observation.position;
|
||||
}
|
||||
mean_time /= static_cast<double>(r.observations.size());
|
||||
mean_position /= static_cast<double>(r.observations.size());
|
||||
double time_variance = 0.0;
|
||||
Eigen::Vector2d cross = Eigen::Vector2d::Zero();
|
||||
for (const auto& observation : r.observations)
|
||||
{
|
||||
const double dt = secondsBetween(observation.stamp, r.observations.front().stamp) - mean_time;
|
||||
time_variance += dt * dt;
|
||||
cross += dt * (observation.position - mean_position);
|
||||
}
|
||||
if (time_variance <= 1e-9)
|
||||
{ r.moving_hits = r.stationary_hits = 0; r.track.motion = MotionClass::kUnknown; return; }
|
||||
const Eigen::Vector2d velocity = cross / time_variance;
|
||||
const double speed = velocity.norm();
|
||||
double residual2 = 0.0;
|
||||
for (const auto& observation : r.observations)
|
||||
{
|
||||
const double dt = secondsBetween(observation.stamp, r.observations.front().stamp) - mean_time;
|
||||
residual2 += (observation.position - mean_position - dt * velocity).squaredNorm();
|
||||
}
|
||||
const double residual = std::sqrt(residual2 / static_cast<double>(r.observations.size()));
|
||||
const double slope_sigma = std::sqrt(residual2 /
|
||||
(static_cast<double>(r.observations.size() - 2) * time_variance));
|
||||
const double displacement = (r.observations.back().position -
|
||||
r.observations.front().position).norm();
|
||||
const bool consistent = residual <= config_.motion_max_residual;
|
||||
const std::size_t free_observations = static_cast<std::size_t>(std::count_if(
|
||||
r.observations.begin(), r.observations.end(), [](const Observation& observation) {
|
||||
return observation.known_free;
|
||||
}));
|
||||
if (consistent && free_observations >= config_.motion_known_free_observations &&
|
||||
displacement >= config_.motion_min_displacement &&
|
||||
speed - 0.5 * slope_sigma >= config_.moving_speed)
|
||||
{ ++r.moving_hits; r.stationary_hits = 0; }
|
||||
else if (consistent && displacement < config_.motion_min_displacement &&
|
||||
speed + 0.5 * slope_sigma <= config_.stationary_speed)
|
||||
{ ++r.stationary_hits; r.moving_hits = 0; }
|
||||
else
|
||||
{ r.stationary_hits = r.moving_hits = 0; r.track.motion = MotionClass::kUnknown; }
|
||||
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;
|
||||
}
|
||||
|
||||
void TrackerCore::addObservation(Record& r, const Detection& detection)
|
||||
{
|
||||
const Stamp observed = detection.observed_stamp ? detection.observed_stamp : detection.stamp;
|
||||
if (r.observations.empty() || observed > r.observations.back().stamp)
|
||||
r.observations.push_back({observed, detection.position,
|
||||
config_.motion_known_free_beams == 0 ||
|
||||
detection.known_free_beams >= config_.motion_known_free_beams});
|
||||
while (!r.observations.empty() &&
|
||||
secondsBetween(observed, r.observations.front().stamp) > config_.motion_window)
|
||||
r.observations.pop_front();
|
||||
}
|
||||
ProcessingResult TrackerCore::update(Stamp stamp, const std::vector<Detection>& detections,
|
||||
const std::vector<std::size_t>& sources)
|
||||
{
|
||||
@@ -57,9 +180,13 @@ ProcessingResult TrackerCore::update(Stamp stamp, const std::vector<Detection>&
|
||||
}))
|
||||
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_;
|
||||
next.erase(std::remove_if(next.begin(), next.end(), [&](const Record& r) {
|
||||
const double timeout = r.track.lifecycle == TrackLifecycle::kTentative ?
|
||||
config_.tentative_timeout : config_.track_timeout;
|
||||
return secondsBetween(stamp, r.track.last_observed_stamp) > timeout;
|
||||
}), next.end());
|
||||
std::vector<Track> predicted;
|
||||
predicted.reserve(next.size());
|
||||
for (auto& record : next)
|
||||
@@ -68,22 +195,28 @@ ProcessingResult TrackerCore::update(Stamp stamp, const std::vector<Detection>&
|
||||
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);
|
||||
const auto measurements = groupFragments(detections, predicted, config_);
|
||||
const auto assignment = associateDetections(predicted, measurements, config_);
|
||||
std::vector<bool> used(measurements.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"};
|
||||
if (!correctTrack(r.track, measurements[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;
|
||||
measurements[index].observed_stamp ? measurements[index].observed_stamp : stamp);
|
||||
r.track.observed_sources = measurements[index].sources;
|
||||
++r.track.hit_count;
|
||||
r.track.miss_count = 0;
|
||||
r.track.lifecycle = r.track.hit_count >= config_.confirmation_hits ?
|
||||
addObservation(r, measurements[index]);
|
||||
const bool already_confirmed = r.track.lifecycle != TrackLifecycle::kTentative;
|
||||
r.track.lifecycle = already_confirmed ||
|
||||
(r.track.hit_count >= config_.confirmation_hits &&
|
||||
secondsBetween(r.observations.back().stamp,
|
||||
r.observations.front().stamp) >= config_.confirmation_min_span) ?
|
||||
TrackLifecycle::kConfirmed : TrackLifecycle::kTentative;
|
||||
classify(r);
|
||||
}
|
||||
@@ -94,17 +227,17 @@ ProcessingResult TrackerCore::update(Stamp stamp, const std::vector<Detection>&
|
||||
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;
|
||||
if (r.track.lifecycle == TrackLifecycle::kConfirmed) r.track.lifecycle = TrackLifecycle::kCoasting;
|
||||
}
|
||||
}
|
||||
ProcessingResult result;
|
||||
for (std::size_t j = 0; j < detections.size(); ++j)
|
||||
for (std::size_t j = 0; j < measurements.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];
|
||||
const auto& d = measurements[j];
|
||||
r.track.session_id = session_id_; r.track.track_id = next_id_++;
|
||||
r.track.state.head<2>() = d.position;
|
||||
r.track.covariance.setZero();
|
||||
@@ -114,7 +247,9 @@ ProcessingResult TrackerCore::update(Stamp stamp, const std::vector<Detection>&
|
||||
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;
|
||||
addObservation(r, d);
|
||||
if (config_.confirmation_hits == 1 && config_.confirmation_min_span == 0)
|
||||
r.track.lifecycle = TrackLifecycle::kConfirmed;
|
||||
next.push_back(std::move(r));
|
||||
}
|
||||
tracks_ = std::move(next);
|
||||
@@ -129,13 +264,16 @@ std::vector<Track> TrackerCore::predictedTracks(Stamp now) const
|
||||
{
|
||||
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;
|
||||
const double timeout = track.lifecycle == TrackLifecycle::kTentative ?
|
||||
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)
|
||||
if ((track.miss_count > 0 || age > config_.coasting_delay) &&
|
||||
track.lifecycle == TrackLifecycle::kConfirmed)
|
||||
track.lifecycle = TrackLifecycle::kCoasting;
|
||||
if (age > config_.max_prediction) track.motion = MotionClass::kUnknown;
|
||||
out.push_back(std::move(track));
|
||||
}
|
||||
return out;
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
#include <thread>
|
||||
#include <robot_dynamic_obstacle_tracker/detection_fusion.h>
|
||||
#include <robot_dynamic_obstacle_tracker/scan_clusterer.h>
|
||||
#include <robot_dynamic_obstacle_tracker/static_background_model.h>
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_core.h>
|
||||
|
||||
namespace robot_dynamic_obstacle_tracker
|
||||
@@ -44,8 +45,13 @@ struct TrackerService::Impl
|
||||
double max_age = 0;
|
||||
std::uint64_t cursor = 0;
|
||||
Stamp last_seen_stamp = 0;
|
||||
Stamp last_tf_stamp = 0;
|
||||
std::string last_tf_frame;
|
||||
PlanarTransform last_transform;
|
||||
std::optional<RawScan> pending;
|
||||
std::optional<DetectionFrame> ready;
|
||||
std::optional<RawScan> ready_scan;
|
||||
PlanarTransform ready_transform;
|
||||
SteadyTime pending_since{}, ready_since{};
|
||||
};
|
||||
mutable std::mutex lifecycle_mutex;
|
||||
@@ -59,6 +65,7 @@ struct TrackerService::Impl
|
||||
std::unique_ptr<ScanClusterer> clusterer;
|
||||
std::unique_ptr<TrackerCore> core;
|
||||
std::vector<Source> sources;
|
||||
std::vector<std::unique_ptr<StaticBackgroundModel>> backgrounds;
|
||||
std::shared_ptr<const TrackSnapshot> snapshot = std::make_shared<TrackSnapshot>();
|
||||
std::uint64_t session = 0, generation = 0, epoch = 0;
|
||||
Stamp last_now = 0;
|
||||
@@ -96,6 +103,7 @@ struct TrackerService::Impl
|
||||
{
|
||||
session = next_session.fetch_add(1);
|
||||
core->reset(session);
|
||||
for (auto& background : backgrounds) background->reset();
|
||||
batch_result = {};
|
||||
started_at = steady; last_success = {}; last_now = now; last_steady = steady;
|
||||
for (std::size_t i = 0; i < sources.size(); ++i)
|
||||
@@ -155,9 +163,51 @@ struct TrackerService::Impl
|
||||
{ source.pending.reset(); ++health.dropped_count; }
|
||||
return;
|
||||
}
|
||||
if (transform.valid() && source.last_tf_stamp)
|
||||
{
|
||||
const double dt = secondsBetween(source.pending->stamp, source.last_tf_stamp);
|
||||
const Eigen::Vector2d previous_axis = source.last_transform.linear.col(0);
|
||||
const Eigen::Vector2d current_axis = transform.linear.col(0);
|
||||
const double yaw_delta = std::abs(std::atan2(
|
||||
previous_axis.x() * current_axis.y() - previous_axis.y() * current_axis.x(),
|
||||
previous_axis.dot(current_axis)));
|
||||
if (source.pending->frame != source.last_tf_frame || dt <= 0.0 ||
|
||||
(transform.translation - source.last_transform.translation).norm() >
|
||||
config.tf_max_translation_speed * dt + config.tf_translation_jump_margin ||
|
||||
yaw_delta > config.tf_max_yaw_rate * dt + config.tf_yaw_jump_margin)
|
||||
{
|
||||
++epoch;
|
||||
reset(false, now, steady);
|
||||
batch_result = {Health::kTfError, "tracking TF discontinuity; state reset"};
|
||||
return;
|
||||
}
|
||||
}
|
||||
DetectionFrame frame;
|
||||
frame.stamp = source.pending->stamp; frame.source = index;
|
||||
const auto result = clusterer->detect(*source.pending, transform, index, frame.detections);
|
||||
std::vector<std::uint8_t> candidate_beams;
|
||||
BackgroundStats background_stats;
|
||||
if (config.background_enabled)
|
||||
{
|
||||
backgrounds[index]->classify(*source.pending, transform, candidate_beams, &background_stats);
|
||||
health.last_static_beams = background_stats.static_beams;
|
||||
health.last_candidate_beams = background_stats.candidate_beams;
|
||||
health.last_outside_beams = background_stats.outside_beams;
|
||||
health.last_known_free_beams = background_stats.known_free_beams;
|
||||
}
|
||||
const auto result = clusterer->detect(*source.pending, transform, index, frame.detections,
|
||||
config.background_enabled ? &candidate_beams : nullptr);
|
||||
if (result.status == Health::kValid)
|
||||
{
|
||||
// Save the frame before ready_scan takes ownership of the pending scan.
|
||||
source.last_tf_stamp = frame.stamp;
|
||||
source.last_tf_frame = source.pending->frame;
|
||||
source.last_transform = transform;
|
||||
}
|
||||
if (result.status == Health::kValid && config.background_enabled)
|
||||
{
|
||||
source.ready_scan = std::move(*source.pending);
|
||||
source.ready_transform = transform;
|
||||
}
|
||||
source.pending.reset();
|
||||
if (result.status != Health::kValid)
|
||||
{ health.status = result.status; health.reason = result.reason; ++health.dropped_count; return; }
|
||||
@@ -166,6 +216,12 @@ struct TrackerService::Impl
|
||||
|
||||
void consume(Stamp now, SteadyTime steady)
|
||||
{
|
||||
struct BackgroundFrame
|
||||
{
|
||||
std::size_t source = 0;
|
||||
RawScan scan;
|
||||
PlanarTransform transform;
|
||||
};
|
||||
// Flush all possible batches in time order, at most one frame per configured source.
|
||||
for (std::size_t iteration = 0; iteration < sources.size(); ++iteration)
|
||||
{
|
||||
@@ -180,6 +236,7 @@ struct TrackerService::Impl
|
||||
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<BackgroundFrame> background_frames;
|
||||
std::vector<std::size_t> observed;
|
||||
Stamp batch_stamp = earliest;
|
||||
for (std::size_t i = 0; i < sources.size(); ++i)
|
||||
@@ -188,10 +245,15 @@ struct TrackerService::Impl
|
||||
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.ready.reset(); source.ready_scan.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);
|
||||
if (config.background_enabled && source.ready_scan)
|
||||
{
|
||||
background_frames.push_back({i, std::move(*source.ready_scan), source.ready_transform});
|
||||
source.ready_scan.reset();
|
||||
}
|
||||
observed.push_back(i);
|
||||
frames.push_back(std::move(*source.ready)); source.ready.reset();
|
||||
}
|
||||
@@ -199,6 +261,12 @@ struct TrackerService::Impl
|
||||
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);
|
||||
if (batch_result.status == Health::kValid && config.background_enabled)
|
||||
{
|
||||
const auto moving_tracks = core->predictedTracks(batch_stamp);
|
||||
for (const auto& frame : background_frames)
|
||||
backgrounds[frame.source]->integrate(frame.scan, frame.transform, moving_tracks);
|
||||
}
|
||||
for (const auto& frame : frames)
|
||||
{
|
||||
auto& health = sources[frame.source].health;
|
||||
@@ -289,9 +357,14 @@ bool TrackerService::configure(const TrackerConfig& config, const TrackerDepende
|
||||
const auto steady = dependencies.steady_now();
|
||||
auto core = std::make_unique<TrackerCore>(config);
|
||||
auto clusterer = std::make_unique<ScanClusterer>(config);
|
||||
std::vector<std::unique_ptr<StaticBackgroundModel>> backgrounds;
|
||||
backgrounds.reserve(config.sources.size());
|
||||
for (std::size_t i = 0; i < config.sources.size(); ++i)
|
||||
backgrounds.push_back(std::make_unique<StaticBackgroundModel>(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.backgrounds = std::move(backgrounds);
|
||||
p.epoch = 0; p.stopping.store(false); p.configured = true; p.reset(true, now, steady);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -28,6 +28,18 @@ TEST(Config, PackagedYamlLoadsAndMatchesDefaults)
|
||||
EXPECT_EQ(c.max_tracks,TrackerConfig{}.max_tracks);
|
||||
EXPECT_DOUBLE_EQ(c.acceleration_noise,TrackerConfig{}.acceleration_noise);
|
||||
}
|
||||
TEST(Config, OleiProfileEnablesBackgroundAndVisibilityEvidence)
|
||||
{
|
||||
TrackerConfig config;
|
||||
std::string error;
|
||||
ASSERT_TRUE(loadTrackerConfig(std::string(TRACKER_SOURCE_DIR)+
|
||||
"/config/tracker_params_olei.yaml", config, error)) << error;
|
||||
ASSERT_EQ(config.sources.size(), 1u);
|
||||
EXPECT_EQ(config.sources.front().topic, "/f_scan");
|
||||
EXPECT_TRUE(config.background_enabled);
|
||||
EXPECT_GT(config.fragment_join_distance, 0.0);
|
||||
EXPECT_GT(config.motion_known_free_observations, 0u);
|
||||
}
|
||||
TEST(Config, RejectsInvalidThresholdsCapacityAndSources)
|
||||
{
|
||||
TrackerConfig c;std::string error;
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#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/static_background_model.h>
|
||||
#include <robot_dynamic_obstacle_tracker/tracker_core.h>
|
||||
#include "test_helpers.h"
|
||||
|
||||
@@ -237,6 +238,165 @@ TEST(Core, MovingObjectStopsAndStartsWithSameIdentity)
|
||||
if(i==99) { EXPECT_EQ(out[0].motion,MotionClass::kMoving); }
|
||||
}
|
||||
}
|
||||
TEST(Background, PersonOccludesWallWithoutCreatingMovingWallFragments)
|
||||
{
|
||||
TrackerConfig config;
|
||||
config.background_enabled = true;
|
||||
StaticBackgroundModel background(config);
|
||||
ScanClusterer clusterer(config);
|
||||
TrackerCore core(config); core.reset(7);
|
||||
PlanarTransform transform;
|
||||
auto wall = scan(10);
|
||||
wall.angle_min = -1.0; wall.angle_increment = 0.02;
|
||||
wall.ranges.assign(101, std::numeric_limits<float>::infinity());
|
||||
for (int beam = 20; beam <= 80; ++beam) wall.ranges[beam] = 4.0f;
|
||||
std::vector<std::uint8_t> candidates;
|
||||
std::vector<Detection> detections;
|
||||
for (int frame = 0; frame < 12; ++frame)
|
||||
{
|
||||
wall.stamp = stamp(10.0 + 0.1 * frame);
|
||||
background.classify(wall, transform, candidates);
|
||||
background.integrate(wall, transform, {});
|
||||
}
|
||||
background.classify(wall, transform, candidates);
|
||||
ASSERT_EQ(clusterer.detect(wall, transform, 0, detections, &candidates).status, Health::kValid);
|
||||
EXPECT_TRUE(detections.empty());
|
||||
auto closer = wall;
|
||||
closer.ranges[50] = 3.70f; // Within the spatial margin, but clearly in front of the wall.
|
||||
background.classify(closer, transform, candidates);
|
||||
EXPECT_EQ(candidates[50], 2u); // The wall rays previously traversed this free space.
|
||||
|
||||
std::uint64_t moving_id = 0;
|
||||
for (int frame = 0; frame < 18; ++frame)
|
||||
{
|
||||
auto current = wall;
|
||||
current.stamp = stamp(11.2 + 0.1 * frame);
|
||||
const int first = 29 + frame;
|
||||
for (int beam = first; beam < first + 5; ++beam) current.ranges[beam] = 2.0f;
|
||||
background.classify(current, transform, candidates);
|
||||
ASSERT_EQ(clusterer.detect(current, transform, 0, detections, &candidates).status, Health::kValid);
|
||||
ASSERT_EQ(detections.size(), 1u) << "frame=" << frame;
|
||||
background.integrate(current, transform, core.predictedTracks(current.stamp));
|
||||
ASSERT_EQ(core.update(current.stamp, detections, {0}).status, Health::kValid);
|
||||
const auto tracks = core.predictedTracks(current.stamp);
|
||||
ASSERT_EQ(tracks.size(), 1u) << "frame=" << frame;
|
||||
if (moving_id == 0) moving_id = tracks.front().track_id;
|
||||
EXPECT_EQ(tracks.front().track_id, moving_id);
|
||||
if (frame >= 12) { EXPECT_EQ(tracks.front().motion, MotionClass::kMoving); }
|
||||
}
|
||||
wall.stamp = stamp(13.1);
|
||||
background.classify(wall, transform, candidates);
|
||||
EXPECT_EQ(clusterer.detect(wall, transform, 0, detections, &candidates).status, Health::kValid);
|
||||
EXPECT_TRUE(detections.empty()) << "wall returns after occlusion must remain background";
|
||||
}
|
||||
TEST(Background, WallStaysStaticAsLaserTranslatesInOdom)
|
||||
{
|
||||
TrackerConfig config; config.background_enabled=true;
|
||||
StaticBackgroundModel background(config);
|
||||
ScanClusterer clusterer(config);
|
||||
auto wall=scan(10);
|
||||
wall.angle_min=-0.5;wall.angle_increment=0.01;
|
||||
wall.ranges.resize(101);
|
||||
PlanarTransform transform;
|
||||
std::vector<std::uint8_t> candidates;
|
||||
std::vector<Detection> detections;
|
||||
for(int frame=0;frame<42;++frame)
|
||||
{
|
||||
const double laser_x=frame<12 ? 0.0 : 0.02*(frame-11);
|
||||
transform.translation={laser_x,0.0};
|
||||
wall.stamp=stamp(10.0+0.1*frame);
|
||||
for(std::size_t beam=0;beam<wall.ranges.size();++beam)
|
||||
{
|
||||
const double angle=wall.angle_min+beam*wall.angle_increment;
|
||||
wall.ranges[beam]=static_cast<float>((4.0-laser_x)/std::cos(angle));
|
||||
}
|
||||
background.classify(wall,transform,candidates);
|
||||
ASSERT_EQ(clusterer.detect(wall,transform,0,detections,&candidates).status,Health::kValid);
|
||||
if(frame>=12) { EXPECT_TRUE(detections.empty()) << "frame=" << frame; }
|
||||
background.integrate(wall,transform,{});
|
||||
}
|
||||
}
|
||||
TEST(Core, AlternatingStaticCentroidNoiseNeverBecomesMoving)
|
||||
{
|
||||
TrackerCore core(TrackerConfig{}); core.reset(10);
|
||||
for (int frame = 0; frame < 60; ++frame)
|
||||
{
|
||||
const double time = 10.0 + 0.1 * frame;
|
||||
const double x = 2.0 + (frame % 2 ? 0.06 : -0.06);
|
||||
ASSERT_EQ(core.update(stamp(time), {detection(x, 0, time)}, {0}).status, Health::kValid);
|
||||
for (const auto& track : core.predictedTracks(stamp(time)))
|
||||
EXPECT_NE(track.motion, MotionClass::kMoving) << "frame=" << frame;
|
||||
}
|
||||
}
|
||||
TEST(Core, NearbyFragmentsOfOneMovingObjectShareOneIdentity)
|
||||
{
|
||||
TrackerConfig config;
|
||||
config.fragment_join_distance = 0.55;
|
||||
TrackerCore core(config); core.reset(11);
|
||||
for (int frame = 0; frame < 25; ++frame)
|
||||
{
|
||||
const double time = 10.0 + 0.1 * frame;
|
||||
auto left = detection(1.0 + 0.04 * frame, 0.0, time);
|
||||
auto right = detection(1.32 + 0.04 * frame, 0.0, time);
|
||||
left.beam_count = right.beam_count = 4;
|
||||
ASSERT_EQ(core.update(stamp(time), {left, right}, {0}).status, Health::kValid);
|
||||
const auto tracks = core.predictedTracks(stamp(time));
|
||||
ASSERT_EQ(tracks.size(), 1u) << "frame=" << frame;
|
||||
EXPECT_EQ(tracks.front().track_id, 1u);
|
||||
if (frame >= 12) { EXPECT_EQ(tracks.front().motion, MotionClass::kMoving); }
|
||||
}
|
||||
}
|
||||
TEST(Core, MotionInUnobservedSpaceNeedsFreeSpaceEvidence)
|
||||
{
|
||||
TrackerConfig config;
|
||||
config.motion_known_free_beams = 3;
|
||||
config.motion_known_free_observations = 3;
|
||||
TrackerCore core(config); core.reset(13);
|
||||
for (int frame = 0; frame < 30; ++frame)
|
||||
{
|
||||
const double time = 10.0 + 0.1 * frame;
|
||||
auto observation = detection(1.0 + 0.04 * frame, 0, time);
|
||||
observation.beam_count = 6;
|
||||
observation.known_free_beams = frame < 15 ? 0 : 4;
|
||||
ASSERT_EQ(core.update(stamp(time), {observation}, {0}).status, Health::kValid);
|
||||
const auto tracks = core.predictedTracks(stamp(time));
|
||||
ASSERT_EQ(tracks.size(), 1u);
|
||||
if (frame < 15) { EXPECT_NE(tracks.front().motion, MotionClass::kMoving); }
|
||||
if (frame >= 22) { EXPECT_EQ(tracks.front().motion, MotionClass::kMoving); }
|
||||
}
|
||||
}
|
||||
TEST(Core, ConfirmedCrossingObjectsAreNotGrouped)
|
||||
{
|
||||
TrackerConfig config;
|
||||
config.fragment_join_distance = 0.55;
|
||||
TrackerCore core(config); core.reset(12);
|
||||
for (int frame = 0; frame <= 40; ++frame)
|
||||
{
|
||||
const double time = 10.0 + 0.1 * frame, progress = 0.05 * frame;
|
||||
auto a = detection(-1.0 + progress, -0.2, time);
|
||||
auto b = detection(1.0 - progress, 0.2, time);
|
||||
a.beam_count = b.beam_count = 5;
|
||||
ASSERT_EQ(core.update(stamp(time), {a, b}, {0}).status, Health::kValid);
|
||||
EXPECT_EQ(core.predictedTracks(stamp(time)).size(), 2u) << "frame=" << frame;
|
||||
}
|
||||
}
|
||||
TEST(Kalman, RadiusRecoversAfterOneOversizedDetection)
|
||||
{
|
||||
Track track;
|
||||
track.state_stamp = stamp(10);
|
||||
track.radius = 0.2;
|
||||
auto large = detection(0, 0, 10); large.radius = 1.5;
|
||||
ASSERT_TRUE(correctTrack(track, large));
|
||||
EXPECT_GE(track.radius, 1.5);
|
||||
for (int frame = 1; frame <= 6; ++frame)
|
||||
{
|
||||
const double time = 10.0 + 0.1 * frame;
|
||||
ASSERT_TRUE(predictTrack(track, stamp(time), 1.0));
|
||||
auto normal = detection(0, 0, time); normal.radius = 0.2;
|
||||
ASSERT_TRUE(correctTrack(track, normal));
|
||||
}
|
||||
EXPECT_LT(track.radius, 0.25);
|
||||
}
|
||||
TEST(CorePerformance, BoundedPopulationTimingAndFiniteState)
|
||||
{
|
||||
TrackerCore core(TrackerConfig{});core.reset(1);
|
||||
|
||||
@@ -18,6 +18,8 @@ public:
|
||||
mutable std::mutex mutex;
|
||||
std::map<std::string,RawScan> scans;
|
||||
std::map<std::string,bool> tf_available;
|
||||
Eigen::Vector2d tf_translation = Eigen::Vector2d::Zero();
|
||||
double tf_yaw = 0.0;
|
||||
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
|
||||
@@ -39,13 +41,20 @@ public:
|
||||
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;
|
||||
out={};out.translation=tf_translation;
|
||||
const double c=std::cos(tf_yaw),s=std::sin(tf_yaw);
|
||||
out.linear << c,-s,s,c;
|
||||
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;}
|
||||
void setTfTranslation(double x,double y)
|
||||
{std::lock_guard<std::mutex> lock(mutex);tf_translation={x,y};}
|
||||
void setTfYaw(double yaw)
|
||||
{std::lock_guard<std::mutex> lock(mutex);tf_yaw=yaw;}
|
||||
};
|
||||
struct Rig
|
||||
{
|
||||
@@ -166,6 +175,50 @@ TEST(Service, ClockResetInvalidatesIdentityAndRequiresNewMeasurements)
|
||||
EXPECT_EQ(r.service.latestSnapshot()->status,Health::kValid);
|
||||
EXPECT_EQ(old->tracks.size(),1u); // Readers retain immutable old snapshots safely.
|
||||
}
|
||||
TEST(Service, OdometryTfJumpResetsTracksAndBackgroundBeforeUsingNextScan)
|
||||
{
|
||||
Rig r;r.config.background_enabled=true;ASSERT_TRUE(r.configure());
|
||||
r.input->put("/f_scan",scan(10));r.tick();
|
||||
const auto before=r.service.latestSnapshot();
|
||||
ASSERT_EQ(before->tracks.size(),1u);
|
||||
r.advance(0.1);r.input->setTfTranslation(10.0,0.0);
|
||||
r.input->put("/f_scan",scan(10.1,2));r.tick();
|
||||
const auto reset=r.service.latestSnapshot();
|
||||
EXPECT_EQ(reset->status,Health::kTfError);
|
||||
EXPECT_NE(reset->session_id,before->session_id);
|
||||
EXPECT_GT(reset->measurement_epoch,before->measurement_epoch);
|
||||
EXPECT_TRUE(reset->tracks.empty());
|
||||
EXPECT_EQ(before->tracks.size(),1u);
|
||||
r.advance(0.1);r.input->put("/f_scan",scan(10.2,3));r.tick();
|
||||
EXPECT_EQ(r.service.latestSnapshot()->status,Health::kValid);
|
||||
}
|
||||
TEST(Service, SmoothTfWithBackgroundKeepsSessionAcrossScans)
|
||||
{
|
||||
Rig r;r.config.background_enabled=true;ASSERT_TRUE(r.configure());
|
||||
r.input->put("/f_scan",scan(10));r.tick();
|
||||
const auto session=r.service.latestSnapshot()->session_id;
|
||||
for(int frame=1;frame<12;++frame)
|
||||
{
|
||||
r.advance(0.1);
|
||||
r.input->setTfTranslation(0.02*frame,0.0);
|
||||
r.input->put("/f_scan",scan(10.0+0.1*frame,frame+1));r.tick();
|
||||
const auto snapshot=r.service.latestSnapshot();
|
||||
EXPECT_EQ(snapshot->session_id,session) << "frame=" << frame;
|
||||
EXPECT_EQ(snapshot->status,Health::kValid);
|
||||
}
|
||||
}
|
||||
TEST(Service, SuddenOdometryYawJumpResetsSession)
|
||||
{
|
||||
Rig r;r.config.background_enabled=true;ASSERT_TRUE(r.configure());
|
||||
r.input->put("/f_scan",scan(10));r.tick();
|
||||
const auto session=r.service.latestSnapshot()->session_id;
|
||||
r.advance(0.1);r.input->setTfYaw(1.0);
|
||||
r.input->put("/f_scan",scan(10.1,2));r.tick();
|
||||
const auto snapshot=r.service.latestSnapshot();
|
||||
EXPECT_EQ(snapshot->status,Health::kTfError);
|
||||
EXPECT_NE(snapshot->session_id,session);
|
||||
EXPECT_TRUE(snapshot->tracks.empty());
|
||||
}
|
||||
TEST(Service, OverflowInvalidScanAndRecovery)
|
||||
{
|
||||
Rig r;r.config.max_tracks=1;ASSERT_TRUE(r.configure());
|
||||
|
||||
Reference in New Issue
Block a user