From fb1d124a71336d067a9b2d5e7b5679b3a47ae987 Mon Sep 17 00:00:00 2001 From: duongtd Date: Thu, 8 Oct 2026 15:44:39 +0700 Subject: [PATCH] fix(tracker)!: stabilize moving track output Publish bounded coasting tracks to bridge scan and TF latency. Keep motion evidence across short real observation gaps and record rejection gates for bag replay. BREAKING CHANGE: Track now carries MotionDiagnostics. Rebuild native consumers and the tracker library together. --- .gitignore | 3 + robot_dynamic_obstacle_tracker/CMakeLists.txt | 18 +- robot_dynamic_obstacle_tracker/README.md | 30 ++- .../config/tracker_params.yaml | 2 + .../config/tracker_params_olei.yaml | 2 + .../docs/slow_motion_replay_20261008.md | 128 +++++++++++ .../motion_estimator.h | 39 ++++ .../track_output_policy.h | 42 ++++ .../tracker_config.h | 2 + .../tracker_core.h | 9 +- .../tracker_types.h | 2 + robot_dynamic_obstacle_tracker/package.xml | 5 + .../src/motion_estimator.cpp | 65 ++++++ .../src/ros_tracker_node.cpp | 54 ++++- .../src/tracker_config.cpp | 4 + .../src/tracker_config_yaml.cpp | 1 + .../src/tracker_core.cpp | 99 +++------ .../test/config_test.cpp | 2 + .../test/core_test.cpp | 14 +- .../test/output_policy_test.cpp | 175 +++++++++++++++ .../test/service_test.cpp | 4 +- .../tools/analyze_ros_output.py | 98 +++++++++ .../tools/compare_replay.py | 128 +++++++++++ .../tools/replay_bag.cpp | 206 ++++++++++++++++++ 24 files changed, 1030 insertions(+), 102 deletions(-) create mode 100644 .gitignore create mode 100644 robot_dynamic_obstacle_tracker/docs/slow_motion_replay_20261008.md create mode 100644 robot_dynamic_obstacle_tracker/include/robot_dynamic_obstacle_tracker/motion_estimator.h create mode 100644 robot_dynamic_obstacle_tracker/include/robot_dynamic_obstacle_tracker/track_output_policy.h create mode 100644 robot_dynamic_obstacle_tracker/src/motion_estimator.cpp create mode 100644 robot_dynamic_obstacle_tracker/test/output_policy_test.cpp create mode 100644 robot_dynamic_obstacle_tracker/tools/analyze_ros_output.py create mode 100644 robot_dynamic_obstacle_tracker/tools/compare_replay.py create mode 100644 robot_dynamic_obstacle_tracker/tools/replay_bag.cpp diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4a0c968 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/artifacts/ +__pycache__/ +*.pyc diff --git a/robot_dynamic_obstacle_tracker/CMakeLists.txt b/robot_dynamic_obstacle_tracker/CMakeLists.txt index f5d8620..ec0fd1f 100644 --- a/robot_dynamic_obstacle_tracker/CMakeLists.txt +++ b/robot_dynamic_obstacle_tracker/CMakeLists.txt @@ -8,6 +8,7 @@ else() endif() option(TRACKER_WITH_SENSOR_PORTS "Build the native SensorReader/tf3 adapter" OFF) option(TRACKER_BUILD_TESTS "Build deterministic tracker tests" ON) +option(TRACKER_BUILD_BAG_REPLAY "Build optional offline ROS bag replay tool" OFF) set(TRACKER_SANITIZER "" CACHE STRING "Optional address,undefined or thread sanitizer") find_package(Eigen3 REQUIRED) find_package(Threads REQUIRED) @@ -15,7 +16,7 @@ find_package(yaml-cpp REQUIRED) if(TRACKER_CATKIN) find_package(catkin REQUIRED COMPONENTS - geometry_msgs nav_msgs roscpp sensor_msgs tf2_ros visualization_msgs) + geometry_msgs nav_msgs roscpp sensor_msgs std_msgs tf2_ros visualization_msgs) if(TRACKER_WITH_SENSOR_PORTS) find_package(robot_sensor_ports QUIET) find_package(robot_sensor_msgs QUIET) @@ -25,7 +26,7 @@ if(TRACKER_CATKIN) set(TRACKER_WITH_SENSOR_PORTS OFF) endif() endif() - set(tracker_catkin_depends geometry_msgs nav_msgs roscpp sensor_msgs tf2_ros visualization_msgs) + set(tracker_catkin_depends geometry_msgs nav_msgs roscpp sensor_msgs std_msgs tf2_ros visualization_msgs) if(TRACKER_WITH_SENSOR_PORTS) list(APPEND tracker_catkin_depends robot_sensor_ports robot_sensor_msgs robot_time) endif() @@ -40,7 +41,7 @@ endif() add_library(robot_dynamic_obstacle_tracker_core STATIC src/tracker_config.cpp src/scan_geometry.cpp src/scan_clusterer.cpp src/detection_fusion.cpp src/data_association.cpp src/kalman_track.cpp src/tracker_core.cpp - src/static_background_model.cpp) + src/static_background_model.cpp src/motion_estimator.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) @@ -106,7 +107,7 @@ if(TRACKER_BUILD_TESTS AND (NOT TRACKER_CATKIN OR CATKIN_ENABLE_TESTING)) if(NOT TRACKER_CATKIN) find_package(GTest REQUIRED) endif() - set(tracker_tests core service config) + set(tracker_tests core service config output_policy) if(TRACKER_WITH_SENSOR_PORTS) list(APPEND tracker_tests sensor_ports simulated_lidar) endif() @@ -138,6 +139,15 @@ if(TRACKER_BUILD_TESTS AND (NOT TRACKER_CATKIN OR CATKIN_ENABLE_TESTING)) endforeach() endif() +if(TRACKER_BUILD_BAG_REPLAY) + find_package(catkin REQUIRED COMPONENTS rosbag sensor_msgs tf2 tf2_msgs) + add_executable(tracker_bag_replay tools/replay_bag.cpp) + target_compile_features(tracker_bag_replay PRIVATE cxx_std_17) + target_compile_options(tracker_bag_replay PRIVATE -Wall -Wextra -Wpedantic) + target_include_directories(tracker_bag_replay SYSTEM PRIVATE ${catkin_INCLUDE_DIRS}) + target_link_libraries(tracker_bag_replay PRIVATE robot_dynamic_obstacle_tracker ${catkin_LIBRARIES}) +endif() + include(GNUInstallDirs) install(TARGETS robot_dynamic_obstacle_tracker_core robot_dynamic_obstacle_tracker EXPORT robot_dynamic_obstacle_trackerTargets diff --git a/robot_dynamic_obstacle_tracker/README.md b/robot_dynamic_obstacle_tracker/README.md index b5c9e01..402f818 100644 --- a/robot_dynamic_obstacle_tracker/README.md +++ b/robot_dynamic_obstacle_tracker/README.md @@ -14,7 +14,10 @@ ROS; có thể dùng qua SensorReader/tf3 hoặc input adapter riêng. Bản cat SensorReader/tf3 được build khi tìm thấy native dependencies; executable `tracker_olei_node` đọc LaserScan/TF ROS và xuất marker/status. -Header chính: **tracker_service.h**, **sensor_ports_input.h**, **tracker_types.h**. +Header chính: **tracker_service.h**, **sensor_ports_input.h**, **tracker_types.h**, +**track_output_policy.h**. Hàm `movingTrackOutput(snapshot, track, config)` dùng chung +quy tắc đầu ra cho node ROS và consumer native; consumer vẫn phải kiểm tra health và tuổi +snapshot của chính nó. MPCC local planner có thể sở hữu TrackerService qua SensorReader/tf3; package này chưa được nối vào move_base2. Node Olei chạy riêng chỉ xuất perception topics, không phát lệnh vận tốc. @@ -56,7 +59,7 @@ Build package catkin rồi chạy node sau khi Olei scan và TF đã có trên R Mặc định node nhận `/f_scan` (`sensor_msgs/LaserScan`) và tra TF tại đúng scan timestamp về `odom`. Nếu Olei driver đang phát `/front_scan/scan`, truyền `scan_topic:=/front_scan/scan`. Đầu ra là `/tracker/tracks`, `/tracker/debug_tracks`, `/tracker/predictions`, -`/tracker/status`; node không điều khiển robot. +`/tracker/status`, `/tracker/diagnostics`; node không điều khiển robot. 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”. @@ -75,12 +78,27 @@ trừ khi nó ổn định đủ lâu để học thành vật tĩnh. Tia sát biên che khuất hoặc chỗ độ sâu nhảy mạnh vẫn có thể tạo detection, nhưng không được tính là bằng chứng vùng trống để xác nhận `MOVING` và chưa được học ngay vào nền. -`/tracker/tracks` chỉ hiện `MOVING` đã xác nhận, còn mới và có health `valid`. +`/tracker/tracks` hiện track `MOVING` đã xác nhận khi health `valid`; nếu đang chờ +scan/TF hoặc hụt cụm ngắn, nhãn `PREDICTED #id` được giữ tối đa +`moving_coast_timeout` tính từ **quan sát thật cuối**. Profile Olei đặt 0,30 s; mặc định +thư viện là 0 để không đổi hành vi của profile khác. Dự báo còn lại luôn bị chặn bởi +`max_prediction` tính từ quan sát thật; coasting không cập nhật `last_observed_stamp`, hit +hay motion evidence. `motion_evidence_gap: 0.20` của profile Olei giữ ứng viên phân loại +qua 1–2 scan hụt; chỉ detection thật mới tăng số hit. Nếu quá hạn hoặc health lỗi, đầu ra +MOVING bị ẩn. `/tracker/debug_tracks` hiện cả `TENTATIVE`, `COASTING`, `STATIC` và `UNKNOWN` để chẩn đoán. `/tracker/predictions` chỉ dự báo cho cùng tập `MOVING` hợp lệ. MarkerArray là đầu ra RViz; -consumer dùng `TrackSnapshot` cùng lifecycle, motion, health và `last_observed_stamp`. +consumer native dùng `movingTrackOutput` với `TrackSnapshot`, lifecycle, motion, health và +`last_observed_stamp`. Việc thêm `MotionDiagnostics` vào `Track` đổi layout C++ công khai: +phải build lại tracker và các binary native dùng `Track` cùng lúc. `/tracker/status` có số scan đã xử lý/bỏ, phân loại tia, độ dời TF trong một scan và -`tf_waited/timeouts` để phân biệt chờ TF ngắn với scan thực sự bị loại. +`tf_waited/timeouts` để phân biệt chờ TF ngắn với scan thực sự bị loại. Status còn có +`confirmed_moving` (đang quan sát), `predicted_moving` và `output_moving` (tổng hai loại). +`/tracker/diagnostics` là `std_msgs/String` chứa CSV mỗi khung với ID, timestamp trạng +thái/quan sát, lifecycle, motion, tuổi, số hụt, loại đầu ra (0=ẩn, 1=quan sát, 2=dự đoán), +các gate chuyển động và vận tốc fit. `fast_gates`/`slow_gates` là bitmask: 1=thiếu lịch +sử, 2=residual lớn, 4=thiếu known-free, 8=độ dời nhỏ, 16=tốc độ thấp. Có thể tắt topic +chẩn đoán bằng private param `publish_diagnostics:=false`. Profile Olei xét thêm cửa sổ 1,2 s cho người đi chậm, giữ nhánh 0,55 s cho chuyển động nhanh; bằng chứng `known_free` và biên che khuất vẫn áp dụng. Một quan sát mơ hồ không lập tức xóa nhãn `MOVING`; nhãn chỉ được giữ thêm tối đa `motion_exit_hold` khi scan mới vẫn còn hợp lệ. @@ -159,3 +177,5 @@ 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). +Replay bag và kết quả sửa nhấp nháy Olei được ghi tại +[docs/slow_motion_replay_20261008.md](docs/slow_motion_replay_20261008.md). diff --git a/robot_dynamic_obstacle_tracker/config/tracker_params.yaml b/robot_dynamic_obstacle_tracker/config/tracker_params.yaml index 7994e3a..7bbbadc 100644 --- a/robot_dynamic_obstacle_tracker/config/tracker_params.yaml +++ b/robot_dynamic_obstacle_tracker/config/tracker_params.yaml @@ -50,6 +50,8 @@ motion_known_free_observations: 0 # Mặc định tắt vì profile mẫu không 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. +moving_coast_timeout: 0.0 # s; 0 giữ chính sách chỉ xuất track đang được quan sát. +motion_evidence_gap: 0.0 # s; 0 reset bằng chứng khi một scan không ghép được. 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ũ. diff --git a/robot_dynamic_obstacle_tracker/config/tracker_params_olei.yaml b/robot_dynamic_obstacle_tracker/config/tracker_params_olei.yaml index f2f19cc..da3abe4 100644 --- a/robot_dynamic_obstacle_tracker/config/tracker_params_olei.yaml +++ b/robot_dynamic_obstacle_tracker/config/tracker_params_olei.yaml @@ -53,6 +53,8 @@ motion_known_free_observations: 3 # Cần ít nhất 3 scan có bằng chứng v 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. +moving_coast_timeout: 0.30 # s từ quan sát thật cuối; xuất dự đoán ngắn khi chờ scan/TF hoặc mất cụm. +motion_evidence_gap: 0.20 # s; giữ bằng chứng qua 1–2 scan hụt, chỉ quan sát thật mới tăng số hit. 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. fragment_max_beam_gap: 12 # Chỉ gộp mảnh kề nhau trên cùng scan nếu chưa cùng một owner. diff --git a/robot_dynamic_obstacle_tracker/docs/slow_motion_replay_20261008.md b/robot_dynamic_obstacle_tracker/docs/slow_motion_replay_20261008.md new file mode 100644 index 0000000..5002258 --- /dev/null +++ b/robot_dynamic_obstacle_tracker/docs/slow_motion_replay_20261008.md @@ -0,0 +1,128 @@ +# Olei slow-motion bag: sửa và kiểm tra trên máy dev + +Ngày: 2026-10-08. Phạm vi sửa chỉ ở package `robot_dynamic_obstacle_tracker` trong +`src/AMR_T800/Test/robot_dynamic_obstacle_tracker`. Bag gốc lấy từ robot tại +`/home/robotics/kit_ws/src/logs/tracker_slow_20261007_182346/slow_motion.bag` và lưu +trong `artifacts/slow_motion_20261008/input/slow_motion.bag` ở clone dev; thư mục +`artifacts` bị Git bỏ qua. SHA-256: +`e6498108bb6d4997f43ecbee9e4fe40238f1a82ad6ef1dfc75317a158a20d433`. +Bag dài 236,761 s, có 3.551 `/f_scan` khoảng 15 Hz. `/odom` gần như đứng yên; +bag không có nhãn vị trí người, video đồng bộ hoặc chân trị để đo recall/false positive. + +## Lỗi tái hiện + +Bag gốc có 2.367 status `valid`, 629 khung `/tracker/tracks` có nhãn `MOVING`, +và **cả 629 khung này đều chỉ dài một chu kỳ xuất bản 10 Hz**. Nhiều track vẫn giữ +`MotionClass::kMoving`, nhưng tại thời điểm publish `predictedTracks(now)` chuyển +`TrackLifecycle` sang `kCoasting` khi tuổi quan sát vượt `coasting_delay=0.12 s`. +Node trước đây chỉ xuất `kConfirmed`. Trong replay có cùng thứ tự scan và TF của bag, +765/819 mẫu track `kCoasting`+`kMoving` có `miss_count=0`: đây là nhấp nháy do +độ trễ đầu tia scan, TF và timer, không phải 765 lần mất association. Tuổi scan được +tính từ tia đầu; scan kéo dài khoảng 0,0666 s và thời gian đến recorder thường +khoảng 0,073 s. + +## Thay đổi + +- Dùng chung `movingTrackOutput()` cho node ROS và consumer native. Track `MOVING` + có sức khỏe `valid` được xuất dạng quan sát hoặc `PREDICTED`, tối đa 0,30 s từ + quan sát thật cuối, và không vượt `max_prediction=0.50 s`. Kiểm session, + timestamp, state/covariance và lifecycle trước khi xuất. Dự đoán không tạo hit mới. +- Ứng viên phân loại chuyển động có thể đi qua khoảng hụt quan sát thật tối đa + `motion_evidence_gap=0.20 s`; khoảng dài hơn reset ứng viên. Chỉ detection thật + tăng hit. Profile khác giữ mặc định 0 để duy trì hành vi trước đây. +- Tách fit chuyển động sang `motion_estimator.cpp` và ghi bitmask điều kiện bác bỏ + (`history=1`, `residual=2`, `known-free=4`, `displacement=8`, `speed=16`). Node + xuất `/tracker/diagnostics` để phân biệt thiếu bằng chứng với track bị ẩn vì tuổi, + và status tách `confirmed_moving`, `predicted_moving`, `output_moving`. +- Sửa hai lỗi test đã có trước: overload `detect()` mơ hồ ở test core và kỳ vọng + `TfError` trong lúc service đang chờ TF chưa quá hạn. + +## Kết quả trên đúng bag này + +Hai bản offline dùng **cùng** runner `tracker_bag_replay`, config Olei, thứ tự +message tới từ rosbag, clock giả lập và trạng thái ban đầu. Baseline được build +từ snapshot commit `6a6bbf2`; candidate được build từ code sửa. Replay không cấp TF +tương lai trước khi message đó xuất hiện. Đây là so sánh có kiểm soát. Replay ROS +node thật dùng một ROS master riêng trên dev, `/clock` 100 Hz và phát bag 1×; chỉ +phát `/f_scan /tf /tf_static`, không phát marker tracker cũ. + +| Chỉ số | Baseline offline | Code sửa offline | Code sửa ROS node 1× | +|---|---:|---:|---:| +| Khung đầu ra | 2.368 | 2.368 | 2.369 | +| Khung có ít nhất một track MOVING | 546 | 1.314 | 1.317 | +| Lần chuyển từ rỗng sang có output | 546 | 19 | 19 | +| Lần xuất chỉ kéo dài một khung | 546 | 0 | 0 | +| Số track MOVING đồng thời tối đa | 2 | 2 | 2 | +| Khung có hai output | 10 | 29 | 29 | +| ID từng xuất MOVING | 14 | 14 | 14 | +| Scan xử lý / bị bỏ | 3.549 / 1 | 3.549 / 1 | 3.549 / 1 | + +ROS replay có 2.366 khung `valid`, hai khung `invalid_input` và một khung `stale` +lúc `/clock` mới khởi động; không có marker MOVING ở các khung này. Kiểm tra toàn +bộ 2.369 khung xác nhận marker, status và diagnostics thống nhất; các track được +xuất đều có nhãn MOVING, không tentative và tuổi quan sát tối đa 0,30 s. Trong +ROS replay có 734 khung dùng nhãn `PREDICTED #id`. Output cũ ghi trong bag gốc có +629 khung MOVING, cả 629 đều lẻ một khung, tối đa một track mỗi khung. Chênh +giữa bag gốc và hai lượt replay do bag bắt đầu sau khi node gốc đã chạy và lịch +timer/scan khi phát lại khác nhau; không so chúng như một thử nghiệm A/B đồng bộ. + +`motion_evidence_gap` không làm đổi nhãn phân loại trên **bag cụ thể này**: replay +chỉ bật sửa output và replay bật cả hai thay đổi đều có 1.314 khung active, +19 lần bắt đầu output, 14 ID MOVING. Lợi ích của nó được kiểm tra bằng fixture +người đi 0,10 m/s có mỗi scan thứ ba không có detection; track vẫn vào MOVING mà +không tăng hit ở scan hụt. Fixture nhiễu tại chỗ với các scan hụt không bị gọi MOVING. + +Độ ổn định output tăng nhưng hai ID cùng xuất còn ở khoảng 22,0–23,8 s và +138,0–139,1 s (29 khung). Nhiều khung trong các khoảng này có hai track được cập +nhật thật, `miss_count=0`, nên giới hạn tuổi dự đoán không giải quyết được chúng. +Không có nhãn người chuẩn để khẳng định đó là tách một người hay hai người riêng. +Số ID debug (486) và số ID đã từng MOVING (14) không giảm. Thay đổi này xử lý +nhấp nháy đầu ra và giữ bằng chứng qua hụt ngắn; chưa chứng minh đã giải quyết +nhầm vật tĩnh hoặc bỏ sót người chậm ngoài fixture. Scan gốc vẫn phải đi vào +costmap để tránh vật cản ngay cả khi tracker giữ `UNKNOWN`. + +## Kiểm chứng build và test + +Standalone CMake build với `TRACKER_WITH_SENSOR_PORTS=OFF`, +`TRACKER_BUILD_TESTS=ON`, `TRACKER_BUILD_BAG_REPLAY=ON`: 4/4 CTest targets đạt. +Workspace catkin cách ly build node ROS và bốn bộ GoogleTest: 58 testcase +(29 core, 18 service, 4 config, 7 output policy), 0 fail. `catkin_test_results` +in 116 vì tính thêm các test suite; số testcase thực lấy từ XML. +Không chạy adapter `SensorReader/tf3` trong lượt này. Kết quả node ROS 1× ở trên +kiểm tra nhánh LaserScan/TF Olei, nhưng robot thật chưa chạy bản sửa này. + +Từ thư mục clone dev: + +```bash +cd /home/duongtd/T800_ws/src/AMR_T800/Test/robot_dynamic_obstacle_tracker +source /opt/ros/noetic/setup.bash +cmake -S robot_dynamic_obstacle_tracker -B artifacts/slow_motion_20261008/fixed_build \ + -DCMAKE_BUILD_TYPE=RelWithDebInfo -DTRACKER_WITH_SENSOR_PORTS=OFF \ + -DTRACKER_BUILD_TESTS=ON -DTRACKER_BUILD_BAG_REPLAY=ON \ + -DCMAKE_PREFIX_PATH=/opt/ros/noetic -DPYTHON_EXECUTABLE=/usr/bin/python3 +cmake --build artifacts/slow_motion_20261008/fixed_build -j2 +(cd artifacts/slow_motion_20261008/fixed_build && ctest --output-on-failure) +artifacts/slow_motion_20261008/fixed_build/tracker_bag_replay \ + artifacts/slow_motion_20261008/input/slow_motion.bag \ + robot_dynamic_obstacle_tracker/config/tracker_params_olei.yaml \ + artifacts/slow_motion_20261008/fixed +/usr/bin/python3 robot_dynamic_obstacle_tracker/tools/compare_replay.py \ + artifacts/slow_motion_20261008/baseline artifacts/slow_motion_20261008/fixed \ + artifacts/slow_motion_20261008/comparison.json \ + --plot artifacts/slow_motion_20261008/comparison.svg +``` + +`baseline` CSV là sản phẩm của bản nguồn đóng băng trước khi sửa và có sẵn trong +artifact dev. `compare_replay.py` từ chối output trên dữ liệu không `valid`, +track không MOVING hoặc quá hạn 0,30 s. Để phân tích một ROS output bag khác: + +```bash +source /opt/ros/noetic/setup.bash +/usr/bin/python3 robot_dynamic_obstacle_tracker/tools/analyze_ros_output.py \ + artifacts/slow_motion_20261008/ros_fixed.bag \ + artifacts/slow_motion_20261008/ros_fixed_summary.json --validate +``` + +Artifact trên dev: `artifacts/slow_motion_20261008/comparison.json`, +`comparison.svg`, `ros_fixed.bag`, `ros_fixed_summary.json`, build/test log, +CSV từng frame và `ros_tracker.log`. Không push hay cài lên robot trong lượt này. diff --git a/robot_dynamic_obstacle_tracker/include/robot_dynamic_obstacle_tracker/motion_estimator.h b/robot_dynamic_obstacle_tracker/include/robot_dynamic_obstacle_tracker/motion_estimator.h new file mode 100644 index 0000000..9bce215 --- /dev/null +++ b/robot_dynamic_obstacle_tracker/include/robot_dynamic_obstacle_tracker/motion_estimator.h @@ -0,0 +1,39 @@ +#ifndef ROBOT_DYNAMIC_OBSTACLE_TRACKER_MOTION_ESTIMATOR_H_ +#define ROBOT_DYNAMIC_OBSTACLE_TRACKER_MOTION_ESTIMATOR_H_ +#include +#include +#include +#include + +namespace robot_dynamic_obstacle_tracker +{ +struct MotionObservation +{ + std::int64_t stamp = 0; // Actual observation time [ns], never a prediction time. + Eigen::Vector2d position = Eigen::Vector2d::Zero(); + bool known_free = false; +}; +struct MotionFit +{ + bool ready = false; + double speed = 0.0, slope_sigma = 0.0, residual = 0.0, displacement = 0.0; + std::size_t observations = 0, free_observations = 0; +}; +enum MotionGate : std::uint32_t +{ + kMotionHistory = 1, kMotionResidual = 2, kMotionFreeSpace = 4, + kMotionDisplacement = 8, kMotionSpeed = 16 +}; +struct MotionDiagnostics +{ + MotionFit fast, slow; + std::uint32_t fast_rejected = kMotionHistory, slow_rejected = kMotionHistory; + bool velocity_uncertain = false; +}; + +MotionFit fitMotionWindow(const std::deque& observations, double window, + std::size_t minimum_observations); +std::uint32_t movingEvidenceRejections(const MotionFit& fit, double max_residual, + std::size_t free_observations, double displacement, double speed); +} // namespace robot_dynamic_obstacle_tracker +#endif diff --git a/robot_dynamic_obstacle_tracker/include/robot_dynamic_obstacle_tracker/track_output_policy.h b/robot_dynamic_obstacle_tracker/include/robot_dynamic_obstacle_tracker/track_output_policy.h new file mode 100644 index 0000000..c536719 --- /dev/null +++ b/robot_dynamic_obstacle_tracker/include/robot_dynamic_obstacle_tracker/track_output_policy.h @@ -0,0 +1,42 @@ +#ifndef ROBOT_DYNAMIC_OBSTACLE_TRACKER_TRACK_OUTPUT_POLICY_H_ +#define ROBOT_DYNAMIC_OBSTACLE_TRACKER_TRACK_OUTPUT_POLICY_H_ +#include +#include +#include +#include + +namespace robot_dynamic_obstacle_tracker +{ +enum class MovingOutputState { kHidden, kObserved, kPredicted }; +struct MovingTrackOutput +{ + MovingOutputState state = MovingOutputState::kHidden; + double observation_age = 0.0; + double prediction_horizon = 0.0; + bool eligible() const { return state != MovingOutputState::kHidden; } +}; + +// Shared by ROS visualization and native consumers. A predicted output never +// changes the track's lifecycle, hit count or actual last-observation timestamp. +inline MovingTrackOutput movingTrackOutput(const TrackSnapshot& snapshot, const Track& track, + const TrackerConfig& config) +{ + MovingTrackOutput out; + if (snapshot.status != Health::kValid || track.motion != MotionClass::kMoving || + track.lifecycle == TrackLifecycle::kTentative || track.last_observed_stamp <= 0 || + track.session_id != snapshot.session_id || track.state_stamp < track.last_observed_stamp || + track.state_stamp > snapshot.state_stamp || !track.state.allFinite() || + !track.covariance.allFinite() || (track.covariance.diagonal().array() < 0.0).any()) return out; + const Stamp age_ns = snapshot.state_stamp - track.last_observed_stamp; + out.observation_age = secondsBetween(snapshot.state_stamp, track.last_observed_stamp); + if (age_ns < 0 || age_ns > static_cast(std::llround(config.max_prediction * 1e9))) return out; + const bool predicted = track.lifecycle == TrackLifecycle::kCoasting || track.miss_count > 0 || + age_ns > static_cast(std::llround(config.coasting_delay * 1e9)); + if (predicted && (config.moving_coast_timeout <= 0.0 || + age_ns > static_cast(std::llround(config.moving_coast_timeout * 1e9)))) return out; + out.state = predicted ? MovingOutputState::kPredicted : MovingOutputState::kObserved; + out.prediction_horizon = std::max(0.0, config.max_prediction - out.observation_age); + return out; +} +} // namespace robot_dynamic_obstacle_tracker +#endif diff --git a/robot_dynamic_obstacle_tracker/include/robot_dynamic_obstacle_tracker/tracker_config.h b/robot_dynamic_obstacle_tracker/include/robot_dynamic_obstacle_tracker/tracker_config.h index eea5ef6..0e73aa3 100644 --- a/robot_dynamic_obstacle_tracker/include/robot_dynamic_obstacle_tracker/tracker_config.h +++ b/robot_dynamic_obstacle_tracker/include/robot_dynamic_obstacle_tracker/tracker_config.h @@ -44,6 +44,8 @@ struct TrackerConfig 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 moving_coast_timeout = 0.0; // [s] since real observation; 0 hides coasting output. + double motion_evidence_gap = 0.0; // [s] allowed between real motion observations; 0 resets on any miss. double fragment_join_distance = 0.0, fragment_max_radius = 0.65; // [m], 0 disables grouping. std::size_t fragment_max_beam_gap = 12; double fragment_max_range_gap = 0.30; // [m], preserve adjacent people at different depths. diff --git a/robot_dynamic_obstacle_tracker/include/robot_dynamic_obstacle_tracker/tracker_core.h b/robot_dynamic_obstacle_tracker/include/robot_dynamic_obstacle_tracker/tracker_core.h index fe892d8..b2591da 100644 --- a/robot_dynamic_obstacle_tracker/include/robot_dynamic_obstacle_tracker/tracker_core.h +++ b/robot_dynamic_obstacle_tracker/include/robot_dynamic_obstacle_tracker/tracker_core.h @@ -17,21 +17,16 @@ public: std::vector predictedTracks(Stamp now) const; Stamp lastUpdateStamp() const { return last_update_; } private: - struct Observation - { - Stamp stamp = 0; - Eigen::Vector2d position = Eigen::Vector2d::Zero(); - bool known_free = false; - }; struct Record { Track track; - std::deque observations; + std::deque observations; std::size_t moving_hits = 0, stationary_hits = 0; Stamp moving_candidate_since = 0, stationary_candidate_since = 0; Stamp last_moving_evidence_stamp = 0; }; void classify(Record&); + void resetMotionCandidates(Record&); void addObservation(Record&, const Detection&); TrackerConfig config_; std::vector tracks_; diff --git a/robot_dynamic_obstacle_tracker/include/robot_dynamic_obstacle_tracker/tracker_types.h b/robot_dynamic_obstacle_tracker/include/robot_dynamic_obstacle_tracker/tracker_types.h index 97b1ab2..b9e3a83 100644 --- a/robot_dynamic_obstacle_tracker/include/robot_dynamic_obstacle_tracker/tracker_types.h +++ b/robot_dynamic_obstacle_tracker/include/robot_dynamic_obstacle_tracker/tracker_types.h @@ -6,6 +6,7 @@ #include #include #include +#include namespace robot_dynamic_obstacle_tracker { @@ -80,6 +81,7 @@ struct Track MotionClass motion = MotionClass::kUnknown; std::vector observed_sources; std::uint64_t hit_count = 0, miss_count = 0; + MotionDiagnostics motion_diagnostics; // Evidence from last real correction; not recomputed on prediction. }; struct SourceHealth diff --git a/robot_dynamic_obstacle_tracker/package.xml b/robot_dynamic_obstacle_tracker/package.xml index d16fbb8..3348d6e 100644 --- a/robot_dynamic_obstacle_tracker/package.xml +++ b/robot_dynamic_obstacle_tracker/package.xml @@ -11,6 +11,8 @@ nav_msgs roscpp roscpp + std_msgs + std_msgs sensor_msgs sensor_msgs tf2_ros @@ -30,4 +32,7 @@ tf3 tf3 gtest + rosbag + tf2 + tf2_msgs diff --git a/robot_dynamic_obstacle_tracker/src/motion_estimator.cpp b/robot_dynamic_obstacle_tracker/src/motion_estimator.cpp new file mode 100644 index 0000000..d041681 --- /dev/null +++ b/robot_dynamic_obstacle_tracker/src/motion_estimator.cpp @@ -0,0 +1,65 @@ +#include +#include +#include + +namespace robot_dynamic_obstacle_tracker +{ +MotionFit fitMotionWindow(const std::deque& observations, double window, + std::size_t minimum_observations) +{ + MotionFit result; + if (observations.empty() || window <= 0.0 || minimum_observations < 3) return result; + const Stamp observed = observations.back().stamp; + auto first = observations.begin(); + while (first != observations.end() && secondsBetween(observed, first->stamp) > window) ++first; + if (first == observations.end() || secondsBetween(observed, first->stamp) < window * 0.65) return result; + double mean_time = 0.0; + Eigen::Vector2d mean_position = Eigen::Vector2d::Zero(); + for (auto it = first; it != observations.end(); ++it) + { + ++result.observations; + mean_time += secondsBetween(it->stamp, first->stamp); + mean_position += it->position; + if (it->known_free) ++result.free_observations; + } + const auto count = result.observations; + if (count < minimum_observations) return result; + mean_time /= static_cast(count); + mean_position /= static_cast(count); + double time_variance = 0.0; + Eigen::Vector2d cross = Eigen::Vector2d::Zero(); + for (auto it = first; it != observations.end(); ++it) + { + const double dt = secondsBetween(it->stamp, first->stamp) - mean_time; + time_variance += dt * dt; + cross += dt * (it->position - mean_position); + } + if (time_variance <= 1e-9) return result; + const Eigen::Vector2d velocity = cross / time_variance; + double residual2 = 0.0; + for (auto it = first; it != observations.end(); ++it) + { + const double dt = secondsBetween(it->stamp, first->stamp) - mean_time; + residual2 += (it->position - mean_position - dt * velocity).squaredNorm(); + } + result.speed = velocity.norm(); + result.residual = std::sqrt(residual2 / static_cast(count)); + result.slope_sigma = std::sqrt(residual2 / (static_cast(count - 2) * time_variance)); + result.displacement = (observations.back().position - first->position).norm(); + result.ready = std::isfinite(result.speed) && std::isfinite(result.residual) && + std::isfinite(result.slope_sigma) && std::isfinite(result.displacement); + return result; +} + +std::uint32_t movingEvidenceRejections(const MotionFit& fit, double max_residual, + std::size_t free_observations, double displacement, double speed) +{ + if (!fit.ready) return kMotionHistory; + std::uint32_t rejected = 0; + if (fit.residual > max_residual) rejected |= kMotionResidual; + if (fit.free_observations < free_observations) rejected |= kMotionFreeSpace; + if (fit.displacement < displacement) rejected |= kMotionDisplacement; + if (fit.speed - 0.5 * fit.slope_sigma < speed) rejected |= kMotionSpeed; + return rejected; +} +} // namespace robot_dynamic_obstacle_tracker diff --git a/robot_dynamic_obstacle_tracker/src/ros_tracker_node.cpp b/robot_dynamic_obstacle_tracker/src/ros_tracker_node.cpp index e72f957..705dc8e 100644 --- a/robot_dynamic_obstacle_tracker/src/ros_tracker_node.cpp +++ b/robot_dynamic_obstacle_tracker/src/ros_tracker_node.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include @@ -14,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -154,7 +156,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; + output_config_ = config; input_->registerSource(scan_topic, max_age); input_->setTopic(scan_topic); @@ -164,6 +166,9 @@ public: debug_tracks_pub_ = nh_.advertise("/tracker/debug_tracks", 2); prediction_pub_ = nh_.advertise("/tracker/predictions", 2); status_pub_ = nh_.advertise("/tracker/status", 2); + private_nh_.param("publish_diagnostics", publish_diagnostics_, true); + if (publish_diagnostics_) + diagnostics_pub_ = nh_.advertise("/tracker/diagnostics", 2); bool publish_odom_tf = false; private_nh_.param("publish_odom_tf", publish_odom_tf, false); @@ -220,14 +225,28 @@ private: predictions.markers.push_back(clear); int id = 0; std::size_t confirmed_moving = 0; + std::size_t predicted_moving = 0; + std::ostringstream diagnostic_csv; + if (publish_diagnostics_) + diagnostic_csv << "session,id,state_stamp_ns,observed_stamp_ns,lifecycle,motion,age,misses,output,fast_gates,slow_gates,fast_speed,slow_speed,fast_free,slow_free,velocity_uncertain\n"; 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 = snapshot->status == Health::kValid && moving && - track.lifecycle == TrackLifecycle::kConfirmed && - age <= max_prediction_; - if (fresh_moving) ++confirmed_moving; + const auto output = movingTrackOutput(*snapshot, track, output_config_); + const bool fresh_moving = output.eligible(); + if (output.state == MovingOutputState::kObserved) ++confirmed_moving; + if (output.state == MovingOutputState::kPredicted) ++predicted_moving; + if (publish_diagnostics_) + { + const auto& d = track.motion_diagnostics; + diagnostic_csv << track.session_id << ',' << track.track_id << ',' << track.state_stamp << ',' + << track.last_observed_stamp << ',' << static_cast(track.lifecycle) << ',' + << static_cast(track.motion) << ',' + << secondsBetween(snapshot->state_stamp, track.last_observed_stamp) << ',' << track.miss_count << ',' + << static_cast(output.state) << ',' << d.fast_rejected << ',' << d.slow_rejected << ',' + << d.fast.speed << ',' << d.slow.speed << ',' << d.fast.free_observations << ',' + << d.slow.free_observations << ',' << d.velocity_uncertain << '\n'; + } 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); @@ -258,7 +277,12 @@ private: std::to_string(track.track_id); if (track.lifecycle != TrackLifecycle::kConfirmed) label.color.a = 0.55f; debug_tracks.markers.push_back(label); - if (fresh_moving) tracks.markers.push_back(label); + if (fresh_moving) + { + if (output.state == MovingOutputState::kPredicted) + label.text = "PREDICTED #" + std::to_string(track.track_id); + tracks.markers.push_back(label); + } visualization_msgs::Marker arrow; arrow.header = body.header; arrow.ns = "track_velocity"; arrow.id = id++; @@ -278,10 +302,10 @@ private: prediction.action = visualization_msgs::Marker::ADD; prediction.scale.x = 0.035; prediction.color = body.color; const int prediction_steps = fresh_moving ? - static_cast(std::ceil(std::max(0.0, max_prediction_ - age) / 0.1)) : 0; + static_cast(std::ceil(output.prediction_horizon / 0.1)) : 0; for (int step = 0; step <= prediction_steps; ++step) { - const double dt = std::min(max_prediction_ - age, 0.1 * step); + const double dt = std::min(output.prediction_horizon, 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; @@ -296,6 +320,8 @@ private: status.data = std::string("TrackerService: ") + healthName(snapshot->status) + " | tracks=" + std::to_string(snapshot->tracks.size()) + " | confirmed_moving=" + std::to_string(confirmed_moving) + + " | predicted_moving=" + std::to_string(predicted_moving) + + " | output_moving=" + std::to_string(confirmed_moving + predicted_moving) + " | frame=" + snapshot->frame + " | " + snapshot->reason; if (!snapshot->sources.empty()) status.data += " | scans processed/dropped=" + @@ -320,6 +346,12 @@ private: std::to_string(snapshot->sources.front().tf_waited_count) + "/" + std::to_string(snapshot->sources.front().tf_timeout_count); status_pub_.publish(status); + if (publish_diagnostics_) + { + std_msgs::String diagnostic_message; + diagnostic_message.data = diagnostic_csv.str(); + diagnostics_pub_.publish(diagnostic_message); + } ROS_INFO_THROTTLE(2.0, "%s", status.data.c_str()); } @@ -332,8 +364,10 @@ private: ros::Subscriber scan_subscriber_; ros::Subscriber odom_subscriber_; ros::Publisher tracks_pub_, debug_tracks_pub_, prediction_pub_, status_pub_; + ros::Publisher diagnostics_pub_; + bool publish_diagnostics_ = true; ros::Timer timer_; - double max_prediction_ = 0.5; + TrackerConfig output_config_; }; } // namespace } // namespace robot_dynamic_obstacle_tracker diff --git a/robot_dynamic_obstacle_tracker/src/tracker_config.cpp b/robot_dynamic_obstacle_tracker/src/tracker_config.cpp index 42cca07..61ea765 100644 --- a/robot_dynamic_obstacle_tracker/src/tracker_config.cpp +++ b/robot_dynamic_obstacle_tracker/src/tracker_config.cpp @@ -60,6 +60,8 @@ bool TrackerConfig::validate(std::string& error) const if (!std::isfinite(slow_motion_window) || slow_motion_window < 0.0 || !std::isfinite(motion_enter_hold) || motion_enter_hold < 0.0 || !std::isfinite(motion_exit_hold) || motion_exit_hold < 0.0 || + !std::isfinite(moving_coast_timeout) || moving_coast_timeout < 0.0 || + !std::isfinite(motion_evidence_gap) || motion_evidence_gap < 0.0 || !std::isfinite(background_track_hold) || background_track_hold < 0.0) { error = "slow motion and hold durations must be finite and >= 0"; return false; } if (slow_motion_window > 0.0 && @@ -90,6 +92,8 @@ bool TrackerConfig::validate(std::string& error) const slow_moving_speed <= stationary_speed)) || motion_enter_hold >= track_timeout || motion_exit_hold >= track_timeout || coasting_delay >= track_timeout || + moving_coast_timeout > max_prediction || motion_evidence_gap > max_prediction || + (moving_coast_timeout > 0.0 && moving_coast_timeout < coasting_delay) || background_match_distance < background_resolution || background_depth_margin > background_match_distance || fragment_join_distance > fragment_max_radius * 2.0 || diff --git a/robot_dynamic_obstacle_tracker/src/tracker_config_yaml.cpp b/robot_dynamic_obstacle_tracker/src/tracker_config_yaml.cpp index d1f30a6..080fb9c 100644 --- a/robot_dynamic_obstacle_tracker/src/tracker_config_yaml.cpp +++ b/robot_dynamic_obstacle_tracker/src/tracker_config_yaml.cpp @@ -40,6 +40,7 @@ bool loadTrackerConfig(const std::string& path, TrackerConfig& out, std::string& 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(moving_coast_timeout) LOAD_FIELD(motion_evidence_gap) LOAD_FIELD(fragment_join_distance) LOAD_FIELD(fragment_max_radius) LOAD_FIELD(fragment_max_beam_gap) LOAD_FIELD(fragment_max_range_gap) LOAD_FIELD(association_tentative_penalty) LOAD_FIELD(association_coasting_penalty) diff --git a/robot_dynamic_obstacle_tracker/src/tracker_core.cpp b/robot_dynamic_obstacle_tracker/src/tracker_core.cpp index 5713bea..3b8b38a 100644 --- a/robot_dynamic_obstacle_tracker/src/tracker_core.cpp +++ b/robot_dynamic_obstacle_tracker/src/tracker_core.cpp @@ -115,8 +115,17 @@ void TrackerCore::expire(Stamp now) return secondsBetween(now, r.track.last_observed_stamp) > timeout; }), tracks_.end()); } +void TrackerCore::resetMotionCandidates(Record& r) +{ + r.moving_hits = r.stationary_hits = 0; + r.moving_candidate_since = r.stationary_candidate_since = 0; +} void TrackerCore::classify(Record& r) { + r.track.motion_diagnostics = {}; + auto& diagnostic = r.track.motion_diagnostics; + diagnostic.velocity_uncertain = r.track.covariance.bottomRightCorner<2,2>().diagonal().maxCoeff() > + config_.motion_velocity_sigma * config_.motion_velocity_sigma; const Stamp observed = r.observations.empty() ? 0 : r.observations.back().stamp; const auto retainRecentMotion = [&] { if (r.track.motion != MotionClass::kMoving || !r.last_moving_evidence_stamp || @@ -128,76 +137,21 @@ void TrackerCore::classify(Record& r) r.track.covariance.bottomRightCorner<2,2>().diagonal().maxCoeff() > config_.motion_velocity_sigma * config_.motion_velocity_sigma) { - r.moving_hits = r.stationary_hits = 0; - r.moving_candidate_since = r.stationary_candidate_since = 0; + resetMotionCandidates(r); if (r.track.lifecycle != TrackLifecycle::kConfirmed) r.track.motion = MotionClass::kUnknown; else retainRecentMotion(); return; } - struct MotionFit - { - bool ready = false; - double speed = 0.0, slope_sigma = 0.0, residual = 0.0, displacement = 0.0; - std::size_t free_observations = 0; - }; - const auto fit = [&](double window) { - MotionFit result; - auto first = r.observations.begin(); - while (first != r.observations.end() && - secondsBetween(observed, first->stamp) > window) ++first; - if (first == r.observations.end() || - secondsBetween(observed, first->stamp) < window * 0.65) return result; - std::size_t count = 0; - double mean_time = 0.0; - Eigen::Vector2d mean_position = Eigen::Vector2d::Zero(); - for (auto it = first; it != r.observations.end(); ++it) - { - ++count; - mean_time += secondsBetween(it->stamp, first->stamp); - mean_position += it->position; - if (it->known_free) ++result.free_observations; - } - if (count < config_.motion_min_observations) return result; - mean_time /= static_cast(count); - mean_position /= static_cast(count); - double time_variance = 0.0; - Eigen::Vector2d cross = Eigen::Vector2d::Zero(); - for (auto it = first; it != r.observations.end(); ++it) - { - const double dt = secondsBetween(it->stamp, first->stamp) - mean_time; - time_variance += dt * dt; - cross += dt * (it->position - mean_position); - } - if (time_variance <= 1e-9) return result; - const Eigen::Vector2d velocity = cross / time_variance; - double residual2 = 0.0; - for (auto it = first; it != r.observations.end(); ++it) - { - const double dt = secondsBetween(it->stamp, first->stamp) - mean_time; - residual2 += (it->position - mean_position - dt * velocity).squaredNorm(); - } - result.speed = velocity.norm(); - result.residual = std::sqrt(residual2 / static_cast(count)); - result.slope_sigma = std::sqrt(residual2 / - (static_cast(count - 2) * time_variance)); - result.displacement = (r.observations.back().position - first->position).norm(); - result.ready = std::isfinite(result.speed) && std::isfinite(result.residual) && - std::isfinite(result.slope_sigma) && std::isfinite(result.displacement); - return result; - }; - const auto supportsMoving = [&](const MotionFit& estimate, double displacement, double speed) { - return estimate.ready && estimate.residual <= config_.motion_max_residual && - estimate.free_observations >= config_.motion_known_free_observations && - estimate.displacement >= displacement && - estimate.speed - 0.5 * estimate.slope_sigma >= speed; - }; - const MotionFit fast = fit(config_.motion_window); - const bool fast_moving = supportsMoving(fast, config_.motion_min_displacement, - config_.moving_speed); - const bool slow_moving = config_.slow_motion_window > 0.0 && - supportsMoving(fit(config_.slow_motion_window), - config_.slow_motion_min_displacement, config_.slow_moving_speed); + diagnostic.fast = fitMotionWindow(r.observations, config_.motion_window, config_.motion_min_observations); + diagnostic.slow = fitMotionWindow(r.observations, config_.slow_motion_window, config_.motion_min_observations); + diagnostic.fast_rejected = movingEvidenceRejections(diagnostic.fast, config_.motion_max_residual, + config_.motion_known_free_observations, config_.motion_min_displacement, config_.moving_speed); + diagnostic.slow_rejected = movingEvidenceRejections(diagnostic.slow, config_.motion_max_residual, + config_.motion_known_free_observations, config_.slow_motion_min_displacement, config_.slow_moving_speed); + const auto& fast = diagnostic.fast; + const bool fast_moving = diagnostic.fast_rejected == 0; + const bool slow_moving = config_.slow_motion_window > 0.0 && diagnostic.slow_rejected == 0; const bool stationary = fast.ready && fast.residual <= config_.motion_max_residual && fast.displacement < config_.motion_min_displacement && fast.speed + 0.5 * fast.slope_sigma <= config_.stationary_speed; @@ -223,8 +177,7 @@ void TrackerCore::classify(Record& r) } else { - r.moving_hits = r.stationary_hits = 0; - r.moving_candidate_since = r.stationary_candidate_since = 0; + resetMotionCandidates(r); retainRecentMotion(); } } @@ -285,6 +238,10 @@ ProcessingResult TrackerCore::update(Stamp stamp, const std::vector& const auto index = static_cast(assignment[i]); if (!correctTrack(r.track, measurements[index])) return {Health::kFault, "Kalman correction failed"}; used[index] = true; + const Stamp observed = measurements[index].observed_stamp ? measurements[index].observed_stamp : stamp; + if (config_.motion_evidence_gap > 0.0 && + secondsBetween(observed, r.track.last_observed_stamp) > config_.motion_evidence_gap) + resetMotionCandidates(r); r.track.last_observed_stamp = std::max(r.track.last_observed_stamp, measurements[index].observed_stamp ? measurements[index].observed_stamp : stamp); r.track.observed_sources = measurements[index].sources; @@ -305,7 +262,13 @@ ProcessingResult TrackerCore::update(Stamp stamp, const std::vector& 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 (covered) + { + ++r.track.miss_count; + if (config_.motion_evidence_gap <= 0.0 || + secondsBetween(stamp, r.track.last_observed_stamp) > config_.motion_evidence_gap) + resetMotionCandidates(r); + } if (r.track.lifecycle == TrackLifecycle::kConfirmed) r.track.lifecycle = TrackLifecycle::kCoasting; } } diff --git a/robot_dynamic_obstacle_tracker/test/config_test.cpp b/robot_dynamic_obstacle_tracker/test/config_test.cpp index 437eb42..219f9dc 100644 --- a/robot_dynamic_obstacle_tracker/test/config_test.cpp +++ b/robot_dynamic_obstacle_tracker/test/config_test.cpp @@ -39,6 +39,8 @@ TEST(Config, OleiProfileEnablesBackgroundAndVisibilityEvidence) EXPECT_TRUE(config.background_enabled); EXPECT_GT(config.fragment_join_distance, 0.0); EXPECT_GT(config.motion_known_free_observations, 0u); + EXPECT_DOUBLE_EQ(config.moving_coast_timeout, 0.30); + EXPECT_DOUBLE_EQ(config.motion_evidence_gap, 0.20); } TEST(Config, RejectsInvalidThresholdsCapacityAndSources) { diff --git a/robot_dynamic_obstacle_tracker/test/core_test.cpp b/robot_dynamic_obstacle_tracker/test/core_test.cpp index 22609ad..b0ac99a 100644 --- a/robot_dynamic_obstacle_tracker/test/core_test.cpp +++ b/robot_dynamic_obstacle_tracker/test/core_test.cpp @@ -38,7 +38,7 @@ TEST(Cluster, MissingBeamSplitsClusters) { auto s = scan(10); s.ranges[3] = std::numeric_limits::quiet_NaN(); std::vector out; - const auto result = ScanClusterer(TrackerConfig{}).detect(s, {}, 0, out); + const auto result = ScanClusterer(TrackerConfig{}).detect(s, PlanarTransform{}, 0, out); EXPECT_EQ(result.status, Health::kValid); EXPECT_EQ(result.rejected_points, 1u); EXPECT_EQ(out.size(), 2u); } @@ -46,21 +46,21 @@ TEST(Cluster, AllNoReturnsIsEmptyButBrokenAndEmptyScanAreInvalid) { ScanClusterer clusterer(TrackerConfig{}); std::vector out; auto s = scan(10); s.ranges.assign(10, std::numeric_limits::infinity()); - EXPECT_EQ(clusterer.detect(s, {}, 0, out).status, Health::kValid); EXPECT_TRUE(out.empty()); + EXPECT_EQ(clusterer.detect(s, PlanarTransform{}, 0, out).status, Health::kValid); EXPECT_TRUE(out.empty()); s.ranges.assign(10, std::numeric_limits::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); + EXPECT_EQ(clusterer.detect(s, PlanarTransform{}, 0, out).status, Health::kInvalidInput); + s.ranges.clear(); EXPECT_EQ(clusterer.detect(s, PlanarTransform{}, 0, out).status, Health::kInvalidInput); s = scan(10); s.angle_increment = 0; - EXPECT_EQ(clusterer.detect(s, {}, 0, out).status, Health::kInvalidInput); + EXPECT_EQ(clusterer.detect(s, PlanarTransform{}, 0, out).status, Health::kInvalidInput); } TEST(Cluster, OverflowIsExplicit) { TrackerConfig c; c.max_detections=1; auto s = scan(10); s.ranges[3] = std::numeric_limits::infinity(); std::vector out; - EXPECT_EQ(ScanClusterer(c).detect(s, {}, 0, out).status, Health::kOverflow); + EXPECT_EQ(ScanClusterer(c).detect(s, PlanarTransform{}, 0, out).status, Health::kOverflow); c.max_scan_points=3; - EXPECT_EQ(ScanClusterer(c).detect(s, {}, 0, out).status, Health::kOverflow); + EXPECT_EQ(ScanClusterer(c).detect(s, PlanarTransform{}, 0, out).status, Health::kOverflow); } TEST(Cluster, UpsideDownLaserIsSupported) { diff --git a/robot_dynamic_obstacle_tracker/test/output_policy_test.cpp b/robot_dynamic_obstacle_tracker/test/output_policy_test.cpp new file mode 100644 index 0000000..d6bf917 --- /dev/null +++ b/robot_dynamic_obstacle_tracker/test/output_policy_test.cpp @@ -0,0 +1,175 @@ +#include +#include +#include +#include +#include "test_helpers.h" + +namespace +{ +using namespace robot_dynamic_obstacle_tracker; +using namespace tracker_test; + +TrackerConfig oleiConfig() +{ + TrackerConfig config; + std::string error; + if (!loadTrackerConfig(std::string(TRACKER_SOURCE_DIR) + "/config/tracker_params_olei.yaml", config, error)) + throw std::runtime_error(error); + return config; +} + +TEST(OutputPolicy, ScanAndTfLatencyDoesNotHideAnEstablishedMovingTrack) +{ + const auto config = oleiConfig(); + Track track; track.lifecycle = TrackLifecycle::kCoasting; track.motion = MotionClass::kMoving; + track.last_observed_stamp = stamp(10); track.state_stamp = stamp(10.16); track.hit_count = 30; + TrackSnapshot snapshot; snapshot.status = Health::kValid; snapshot.state_stamp = stamp(10.16); + const auto output = movingTrackOutput(snapshot, track, config); + EXPECT_EQ(output.state, MovingOutputState::kPredicted); + EXPECT_NEAR(output.prediction_horizon, 0.34, 1e-9); + EXPECT_EQ(track.last_observed_stamp, stamp(10)); + EXPECT_EQ(track.hit_count, 30u); + EXPECT_EQ(track.miss_count, 0u); + EXPECT_EQ(track.lifecycle, TrackLifecycle::kCoasting); +} + +TEST(OutputPolicy, RealMissesHaveAHardObservationDeadline) +{ + const auto config = oleiConfig(); + Track track; track.lifecycle = TrackLifecycle::kCoasting; track.motion = MotionClass::kMoving; + track.last_observed_stamp = stamp(10); track.miss_count = 2; + TrackSnapshot snapshot; snapshot.status = Health::kValid; + for (double age : {0.2, 0.3, 0.300001, 0.5, 0.8}) + { + snapshot.state_stamp = track.state_stamp = stamp(10 + age); + const auto output = movingTrackOutput(snapshot, track, config); + EXPECT_EQ(output.eligible(), age <= config.moving_coast_timeout) << age; + if (output.eligible()) + { + EXPECT_LE(age + output.prediction_horizon, config.max_prediction + 1e-9); + } + EXPECT_EQ(track.last_observed_stamp, stamp(10)); + } +} + +TEST(OutputPolicy, UnhealthyUnknownTentativeAndInvalidTracksAreHidden) +{ + const auto config = oleiConfig(); + Track track; track.lifecycle = TrackLifecycle::kCoasting; track.motion = MotionClass::kMoving; + track.last_observed_stamp = stamp(10); track.state_stamp = stamp(10.15); + TrackSnapshot snapshot; snapshot.state_stamp = stamp(10.15); + for (auto health : {Health::kStale, Health::kTfError, Health::kFault, Health::kOverflow, + Health::kWarmingUp, Health::kStopped, Health::kInvalidInput, Health::kOutOfOrder}) + { + snapshot.status = health; + EXPECT_FALSE(movingTrackOutput(snapshot, track, config).eligible()); + } + snapshot.status = Health::kValid; + for (auto motion : {MotionClass::kUnknown, MotionClass::kStationary}) + { + auto copy = track; + copy.motion = motion; + EXPECT_FALSE(movingTrackOutput(snapshot, copy, config).eligible()); + } + auto copy = track; copy.lifecycle = TrackLifecycle::kTentative; + EXPECT_FALSE(movingTrackOutput(snapshot, copy, config).eligible()); + copy = track; copy.last_observed_stamp = stamp(11); + EXPECT_FALSE(movingTrackOutput(snapshot, copy, config).eligible()); + copy = track; copy.state.x() = std::numeric_limits::quiet_NaN(); + EXPECT_FALSE(movingTrackOutput(snapshot, copy, config).eligible()); + copy = track; copy.covariance(0, 0) = -1; + EXPECT_FALSE(movingTrackOutput(snapshot, copy, config).eligible()); +} + +TEST(OutputPolicy, LegacyProfileCanDisableCoastingOutput) +{ + TrackerConfig config; + Track track; track.lifecycle = TrackLifecycle::kCoasting; track.motion = MotionClass::kMoving; + track.last_observed_stamp = stamp(10); track.state_stamp = stamp(10.15); + TrackSnapshot snapshot; snapshot.status = Health::kValid; snapshot.state_stamp = track.state_stamp; + EXPECT_FALSE(movingTrackOutput(snapshot, track, config).eligible()); +} + +TEST(SlowMotion, IntermittentRealDetectionsCanConfirmWithoutPredictingEvidence) +{ + auto config = oleiConfig(); + auto legacy_config = config; legacy_config.motion_evidence_gap = 0.0; + TrackerCore core(config), legacy(legacy_config); core.reset(1); legacy.reset(2); + bool legacy_moved = false; + for (int frame = 0; frame < 90; ++frame) + { + const double time = 10.0 + frame / 15.0; + std::vector observations; + if (frame % 3 != 2) + { + auto d = detection(2.0 + 0.10 * (time - 10.0), 0.0, time); + d.beam_count = 12; d.known_free_beams = 6; observations.push_back(d); + } + ASSERT_EQ(core.update(stamp(time), observations, {0}).status, Health::kValid); + ASSERT_EQ(legacy.update(stamp(time), observations, {0}).status, Health::kValid); + const auto tracks = core.predictedTracks(stamp(time + 0.13)); + ASSERT_EQ(tracks.size(), 1u); + for (const auto& track : legacy.predictedTracks(stamp(time))) + { + legacy_moved |= track.motion == MotionClass::kMoving; + } + if (frame >= 25) + { + TrackSnapshot snapshot; snapshot.session_id = 1; + snapshot.status = Health::kValid; snapshot.state_stamp = stamp(time + 0.13); + EXPECT_EQ(tracks.front().motion, MotionClass::kMoving) << frame; + EXPECT_TRUE(movingTrackOutput(snapshot, tracks.front(), config).eligible()) << frame; + EXPECT_EQ(tracks.front().track_id, 1u); + } + if (observations.empty()) + { + EXPECT_LT(tracks.front().last_observed_stamp, stamp(time)); + } + } + EXPECT_FALSE(legacy_moved); + const auto last = core.predictedTracks(stamp(16)).front(); + for (int frame = 90; frame < 100; ++frame) + { + const auto now = stamp(10.0 + frame / 15.0); + ASSERT_EQ(core.update(now, {}, {0}).status, Health::kValid); + for (const auto& track : core.predictedTracks(now)) + { + EXPECT_EQ(track.last_observed_stamp, last.last_observed_stamp); + TrackSnapshot snapshot; snapshot.session_id = 1; + snapshot.status = Health::kValid; snapshot.state_stamp = now; + if (secondsBetween(now, track.last_observed_stamp) > config.moving_coast_timeout) + { + EXPECT_FALSE(movingTrackOutput(snapshot, track, config).eligible()); + } + } + } +} + +TEST(SlowMotion, NoisyStationaryObservationsStayNonMovingWithFreeSpaceEvidence) +{ + auto config = oleiConfig(); TrackerCore core(config); core.reset(1); + for (int frame = 0; frame < 120; ++frame) + { + const double time = 10 + frame / 15.0; + auto d = detection(2.0 + 0.055 * std::sin(frame * 1.7), 0.025 * std::cos(frame * 0.9), time); + d.beam_count = 12; d.known_free_beams = 6; + ASSERT_EQ(core.update(stamp(time), frame % 3 == 2 ? std::vector{} : std::vector{d}, {0}).status, + Health::kValid); + for (const auto& track : core.predictedTracks(stamp(time))) + EXPECT_NE(track.motion, MotionClass::kMoving) << frame; + } +} + +TEST(Config, RejectsUnboundedCoastOutputAndMotionEvidence) +{ + auto config = oleiConfig(); std::string error; + config.moving_coast_timeout = config.max_prediction + 0.01; + EXPECT_FALSE(config.validate(error)); + config = oleiConfig(); config.moving_coast_timeout = std::numeric_limits::infinity(); + EXPECT_FALSE(config.validate(error)); + config = oleiConfig(); config.motion_evidence_gap = config.max_prediction + 0.01; + EXPECT_FALSE(config.validate(error)); + config = oleiConfig(); config.motion_evidence_gap = -0.01; + EXPECT_FALSE(config.validate(error)); +} +} // namespace diff --git a/robot_dynamic_obstacle_tracker/test/service_test.cpp b/robot_dynamic_obstacle_tracker/test/service_test.cpp index a6bdbcf..3fe4bf2 100644 --- a/robot_dynamic_obstacle_tracker/test/service_test.cpp +++ b/robot_dynamic_obstacle_tracker/test/service_test.cpp @@ -122,7 +122,9 @@ 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); + EXPECT_EQ(r.service.latestSnapshot()->status,Health::kWarmingUp); + EXPECT_EQ(r.service.latestSnapshot()->sources[0].tf_waited_count,1u); + EXPECT_EQ(r.service.latestSnapshot()->sources[0].tf_timeout_count,0u); 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); diff --git a/robot_dynamic_obstacle_tracker/tools/analyze_ros_output.py b/robot_dynamic_obstacle_tracker/tools/analyze_ros_output.py new file mode 100644 index 0000000..e3a1784 --- /dev/null +++ b/robot_dynamic_obstacle_tracker/tools/analyze_ros_output.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""Summarize tracker MarkerArray output in a recorded ROS replay bag.""" + +import argparse +import csv +import json +import math +import re +from pathlib import Path + +import rosbag + + +def labels(message): + return [marker.text for marker in message.markers + if marker.ns == "track_labels" and marker.action == marker.ADD] + + +def on_runs(counts): + lengths = [] + for index, count in enumerate(counts): + if count and (index == 0 or not counts[index - 1]): + end = index + while end + 1 < len(counts) and counts[end + 1]: + end += 1 + lengths.append(end - index + 1) + return lengths + + +def analyze(path, validate): + topics = ("/tracker/tracks", "/tracker/status", "/tracker/diagnostics") + messages = {topic: [] for topic in topics} + with rosbag.Bag(str(path)) as bag: + for topic, message, stamp in bag.read_messages(topics=topics): + messages[topic].append((stamp, message)) + frame_labels = [labels(message) for _, message in messages["/tracker/tracks"]] + counts = list(map(len, frame_labels)) + runs = on_runs(counts) + ids = set() + predicted_frames = 0 + for items in frame_labels: + predicted_frames += any(item.startswith("PREDICTED #") for item in items) + ids.update(item.split("#", 1)[1] for item in items if "#" in item) + if validate: + if not counts or len(counts) != len(messages["/tracker/status"]) or len(counts) != len(messages["/tracker/diagnostics"]): + raise ValueError("Output, status and diagnostics message counts differ") + for index, ((_, status), (_, diagnostic)) in enumerate(zip( + messages["/tracker/status"], messages["/tracker/diagnostics"])): + match = re.search(r"confirmed_moving=(\d+) \| predicted_moving=(\d+) \| output_moving=(\d+)", status.data) + if not match: + raise ValueError(f"Missing output counters in status frame {index}") + observed, predicted, total = map(int, match.groups()) + if total != counts[index] or total != observed + predicted: + raise ValueError(f"Status and marker output differ in frame {index}") + evidence = list(csv.DictReader(diagnostic.data.splitlines())) + emitting = [row for row in evidence if int(row["output"]) != 0] + predicted_evidence = [row for row in emitting if int(row["output"]) == 2] + if len(emitting) != total or len(predicted_evidence) != predicted: + raise ValueError(f"Diagnostic and marker output differ in frame {index}") + if predicted != sum(label.startswith("PREDICTED #") for label in frame_labels[index]): + raise ValueError(f"Predicted markers and status differ in frame {index}") + if total and "TrackerService: valid" not in status.data: + raise ValueError(f"Unhealthy output in frame {index}") + for row in emitting: + age = float(row["age"]) + if (int(row["motion"]) != 2 or int(row["lifecycle"]) == 0 or + not math.isfinite(age) or age < 0 or age > .300001): + raise ValueError(f"Invalid moving output age or class in frame {index}") + if int(row["state_stamp_ns"]) < int(row["observed_stamp_ns"]): + raise ValueError(f"Prediction is older than last observation in frame {index}") + return { + "bag": str(path), "output_frames": len(counts), + "status_frames": len(messages["/tracker/status"]), + "diagnostic_frames": len(messages["/tracker/diagnostics"]), + "active_frames": sum(bool(count) for count in counts), + "output_onsets": len(runs), + "isolated_output_runs": sum(length == 1 for length in runs), + "longest_output_run_frames": max(runs, default=0), + "predicted_frames": predicted_frames, + "max_simultaneous_tracks": max(counts, default=0), + "frames_with_multiple_outputs": sum(count > 1 for count in counts), + "distinct_output_ids": len(ids), + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("bag", type=Path) + parser.add_argument("output", type=Path) + parser.add_argument("--validate", action="store_true", help="Check status, markers and evidence on each frame") + args = parser.parse_args() + report = analyze(args.bag, args.validate) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/robot_dynamic_obstacle_tracker/tools/compare_replay.py b/robot_dynamic_obstacle_tracker/tools/compare_replay.py new file mode 100644 index 0000000..71cdec2 --- /dev/null +++ b/robot_dynamic_obstacle_tracker/tools/compare_replay.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Compare two tracker_bag_replay runs made from the same recorded inputs.""" + +import argparse +import csv +import json +import math +from collections import Counter, defaultdict +from pathlib import Path + + +def rows(path): + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def summarize(prefix): + frames = rows(Path(str(prefix) + "_frames.csv")) + tracks = rows(Path(str(prefix) + "_tracks.csv")) + if not frames: + raise ValueError(f"No output frames in {prefix}") + counts = [int(frame["eligible_moving"]) for frame in frames] + output_tracks = [track for track in tracks if int(track["eligible"]) != 0] + frame_tracks = defaultdict(list) + for track in tracks: + frame_tracks[int(track["frame"])].append(track) + for index, (frame, count) in enumerate(zip(frames, counts)): + if count != sum(int(track["eligible"]) for track in frame_tracks[index]): + raise ValueError(f"Output count and track rows disagree in {prefix}, frame {index}") + if count and frame["status"] != "valid": + raise ValueError(f"Unhealthy output in {prefix}, frame {index}") + onsets = [index for index, count in enumerate(counts) + if count and (index == 0 or not counts[index - 1])] + runs = [] + for index in onsets: + end = index + while end + 1 < len(counts) and counts[end + 1]: + end += 1 + runs.append(end - index + 1) + invalid = [] + for track in output_tracks: + age = float(track["age"]) + if int(track["motion"]) != 2 or int(track["lifecycle"]) == 0 or not math.isfinite(age): + invalid.append((track["frame"], track["id"])) + if any(not math.isfinite(float(track[column])) for column in ("x", "y", "vx", "vy", "pxx", "pyy")): + invalid.append((track["frame"], track["id"])) + if invalid: + raise ValueError(f"Invalid published moving tracks in {prefix}: {invalid[:5]}") + moving = [track for track in tracks if int(track["motion"]) == 2] + delayed = [track for track in moving if int(track["lifecycle"]) == 2] + by_id = Counter(track["id"] for track in output_tracks) + summary = { + "frames": len(frames), + "duration_s": float(frames[-1]["time"]), + "processed_scans": int(frames[-1]["processed"]), + "dropped_scans": int(frames[-1]["dropped"]), + "tf_waited": int(frames[-1]["tf_waited"]), + "tf_timeouts": int(frames[-1]["tf_timeouts"]), + "valid_frames": sum(frame["status"] == "valid" for frame in frames), + "active_frames": sum(count > 0 for count in counts), + "output_onsets": len(onsets), + "isolated_output_runs": sum(length == 1 for length in runs), + "longest_output_run_frames": max(runs, default=0), + "max_simultaneous_tracks": max(counts), + "frames_with_multiple_outputs": sum(count > 1 for count in counts), + "distinct_output_ids": len(by_id), + "distinct_debug_ids": len({track["id"] for track in tracks}), + "moving_track_samples": len(moving), + "coasting_moving_samples": len(delayed), + "coasting_moving_with_zero_misses": sum(int(track["misses"]) == 0 for track in delayed), + "max_output_observation_age_s": max((float(track["age"]) for track in output_tracks), default=0), + } + return summary, frames, tracks + + +def plot_series(baseline, candidate, output): + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + fig, (full, detail) = plt.subplots(2, 1, figsize=(12, 6), constrained_layout=True) + for axis in (full, detail): + for frames, label, color in ((baseline, "Baseline", "#aa3344"), + (candidate, "Fixed", "#087b67")): + axis.step([float(row["time"]) for row in frames], + [int(row["eligible_moving"]) for row in frames], + where="post", label=label, color=color, alpha=.8, linewidth=.9) + axis.set_ylabel("Published moving tracks") + axis.set_ylim(-.15, max(max(int(row["eligible_moving"]) for row in baseline), + max(int(row["eligible_moving"]) for row in candidate)) + .3) + axis.grid(alpha=.25) + full.set_title("Same bag and recorded arrival order, cold-start replay") + full.legend(loc="upper right") + detail.set_xlim(75, 95) + detail.set_xlabel("Seconds after bag start") + fig.savefig(output) + plt.close(fig) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("baseline", type=Path, help="CSV prefix from frozen baseline build") + parser.add_argument("candidate", type=Path, help="CSV prefix from changed build") + parser.add_argument("output", type=Path, help="Output JSON summary") + parser.add_argument("--plot", type=Path, help="Optional SVG/PNG comparison") + parser.add_argument("--coast-limit", type=float, default=.30) + args = parser.parse_args() + old, old_frames, _ = summarize(args.baseline) + new, new_frames, new_tracks = summarize(args.candidate) + if len(old_frames) != len(new_frames) or any( + old_frame["time"] != new_frame["time"] for old_frame, new_frame in zip(old_frames, new_frames) + ): + raise ValueError("Baseline and candidate output times differ; rerun both on the same bag") + for track in new_tracks: + if int(track["eligible"]) and float(track["age"]) > args.coast_limit + 1e-8: + raise ValueError(f"Output older than coast limit: frame={track['frame']}, id={track['id']}") + report = {"baseline": old, "candidate": new, + "comparison": {"active_frame_change": new["active_frames"] - old["active_frames"], + "output_onset_change": new["output_onsets"] - old["output_onsets"], + "duplicate_frame_change": new["frames_with_multiple_outputs"] - old["frames_with_multiple_outputs"]}} + args.output.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + if args.plot: + plot_series(old_frames, new_frames, args.plot) + print(json.dumps(report, indent=2, ensure_ascii=False)) + + +if __name__ == "__main__": + main() diff --git a/robot_dynamic_obstacle_tracker/tools/replay_bag.cpp b/robot_dynamic_obstacle_tracker/tools/replay_bag.cpp new file mode 100644 index 0000000..56bd52a --- /dev/null +++ b/robot_dynamic_obstacle_tracker/tools/replay_bag.cpp @@ -0,0 +1,206 @@ +// Offline replay of recorded arrival order, including delayed TF. No ROS master, +// subscriptions, wall-clock sleeps or robot connections are used. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef TRACKER_REPLAY_LEGACY +#include +#endif + +namespace tracking = robot_dynamic_obstacle_tracker; +namespace +{ +using tracking::Stamp; +Stamp stampOf(const ros::Time& time) { return static_cast(time.toNSec()); } +ros::Time timeOf(Stamp stamp) { ros::Time out; out.fromNSec(stamp); return out; } + +class BagInput final : public tracking::TrackerInput +{ +public: + explicit BagInput(const tracking::TrackerConfig& config) : config_(config) {} + Stamp now = 0; + tf2::BufferCore tf; + std::map scans; + bool describeSource(const std::string& topic, double& age, std::string& error) const override + { + for (const auto& source : config_.sources) + if (source.topic == topic) { age = source.max_age; return true; } + error = "unknown replay source"; return false; + } + tracking::ReadStatus readLatest(const std::string& topic, std::uint64_t& cursor, + tracking::RawScan& out, std::string&) override + { + const auto it = scans.find(topic); + if (it == scans.end() || it->second.sequence <= cursor) return tracking::ReadStatus::kNoData; + out = it->second; cursor = out.sequence; return tracking::ReadStatus::kScan; + } + bool lookupTransform(const std::string& target, const std::string& source, Stamp stamp, + tracking::PlanarTransform& out, std::string& error) override + { + try + { + const auto transform = tf.lookupTransform(target, source, timeOf(stamp)); + const auto& q = transform.transform.rotation; + const Eigen::Quaterniond rotation(q.w, q.x, q.y, q.z); + if (!rotation.coeffs().allFinite() || std::abs(rotation.norm() - 1.0) > 1e-3) + { error = "invalid quaternion"; return false; } + const Eigen::Matrix3d matrix = rotation.normalized().toRotationMatrix(); + if (std::abs(std::abs(matrix(2, 2)) - 1.0) > 1e-6) + { error = "nonplanar TF"; return false; } + out.linear = matrix.topLeftCorner<2, 2>(); + out.translation = {transform.transform.translation.x, transform.transform.translation.y}; + return out.valid(); + } + catch (const tf2::TransformException& ex) { error = ex.what(); return false; } + } + Stamp measurementNow() const override { return now; } + void receive(const std::string& topic, const sensor_msgs::LaserScan& message) + { + auto& scan = scans[topic]; + ++scan.sequence; + scan.stamp = stampOf(message.header.stamp); scan.frame = message.header.frame_id; + scan.angle_min = message.angle_min; scan.angle_increment = message.angle_increment; + scan.range_min = message.range_min; scan.range_max = message.range_max; + scan.time_increment = message.time_increment; scan.scan_time = message.scan_time; + scan.ranges = message.ranges; + } +private: + tracking::TrackerConfig config_; +}; + +bool legacyEligible(const tracking::TrackSnapshot& snapshot, const tracking::Track& track, + const tracking::TrackerConfig& config) +{ + return snapshot.status == tracking::Health::kValid && + track.motion == tracking::MotionClass::kMoving && + track.lifecycle == tracking::TrackLifecycle::kConfirmed && + tracking::secondsBetween(snapshot.state_stamp, track.last_observed_stamp) <= config.max_prediction; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 4) + { std::cerr << "usage: tracker_bag_replay INPUT.bag CONFIG.yaml OUTPUT_PREFIX\n"; return 2; } + try + { + ros::Time::init(); + tracking::TrackerConfig config; + std::string error; + if (!tracking::loadTrackerConfig(argv[2], config, error)) throw std::runtime_error(error); + rosbag::Bag bag(argv[1], rosbag::bagmode::Read); + std::vector topics{"/tf", "/tf_static"}; + for (const auto& source : config.sources) topics.push_back(source.topic); + rosbag::View view(bag, rosbag::TopicQuery(topics)); + if (view.size() == 0) throw std::runtime_error("bag contains no input messages"); + const Stamp start = stampOf(view.getBeginTime()), end = stampOf(view.getEndTime()); + const Stamp tick_period = static_cast(std::llround(config.poll_period * 1e9)); + if (tick_period <= 0) throw std::runtime_error("poll period is below clock resolution"); + auto input = std::make_shared(config); + input->now = start; + tracking::TrackerService service; + if (!service.configure(config, {input, [&] { + return tracking::SteadyTime(std::chrono::nanoseconds(input->now - start)); }}, error)) + throw std::runtime_error(error); + std::ofstream frames(std::string(argv[3]) + "_frames.csv"); + std::ofstream tracks(std::string(argv[3]) + "_tracks.csv"); + if (!frames || !tracks) throw std::runtime_error("cannot open output CSV files"); + frames << std::setprecision(17); + tracks << std::setprecision(17); + frames << "frame,time,status,tracks,legacy_moving,eligible_moving,processed,dropped,tf_waited,tf_timeouts,candidate_beams,known_free_beams\n"; + tracks << "frame,time,session,id,lifecycle,motion,x,y,vx,vy,radius,age,hits,misses,pxx,pyy,legacy_eligible,eligible,fast_gates,slow_gates,fast_speed,slow_speed,fast_free,slow_free,fast_displacement,slow_displacement,velocity_uncertain\n"; + Stamp next_tick = start, next_output = start; + std::size_t frame = 0, scan_count = 0; + const auto step = [&] { + input->now = next_tick; + if (!service.pollOnce(error)) throw std::runtime_error(error); + if (next_tick >= next_output) + { + const auto snapshot = service.latestSnapshot(); + std::size_t legacy_count = 0, eligible_count = 0; + const double time = tracking::secondsBetween(next_tick, start); + for (const auto& track : snapshot->tracks) + { + const bool legacy = legacyEligible(*snapshot, track, config); +#ifdef TRACKER_REPLAY_LEGACY + const bool eligible = legacy; +#else + const bool eligible = tracking::movingTrackOutput(*snapshot, track, config).eligible(); +#endif + legacy_count += legacy; eligible_count += eligible; + tracks << frame << ',' << time << ',' << track.session_id << ',' << track.track_id << ',' + << static_cast(track.lifecycle) << ',' << static_cast(track.motion) << ',' + << track.state.x() << ',' << track.state.y() << ',' << track.state.z() << ',' + << track.state.w() << ',' << track.radius << ',' + << tracking::secondsBetween(next_tick, track.last_observed_stamp) << ',' + << track.hit_count << ',' << track.miss_count << ',' << track.covariance(0, 0) << ',' + << track.covariance(1, 1) << ',' << legacy << ',' << eligible; +#ifdef TRACKER_REPLAY_LEGACY + tracks << ",-1,-1,0,0,0,0,0,0,0\n"; +#else + const auto& d = track.motion_diagnostics; + tracks << ',' << d.fast_rejected << ',' << d.slow_rejected << ',' << d.fast.speed << ',' + << d.slow.speed << ',' << d.fast.free_observations << ',' << d.slow.free_observations << ',' + << d.fast.displacement << ',' << d.slow.displacement << ',' << d.velocity_uncertain << '\n'; +#endif + } + std::uint64_t processed = 0, dropped = 0, waited = 0, timeouts = 0; + std::size_t candidates = 0, known_free = 0; + for (const auto& source : snapshot->sources) + { + processed += source.processed_count; dropped += source.dropped_count; + waited += source.tf_waited_count; timeouts += source.tf_timeout_count; + candidates += source.last_candidate_beams; known_free += source.last_known_free_beams; + } + frames << frame << ',' << time << ',' << tracking::healthName(snapshot->status) << ',' + << snapshot->tracks.size() << ',' << legacy_count << ',' << eligible_count << ',' + << processed << ',' << dropped << ',' << waited << ',' << timeouts << ',' + << candidates << ',' << known_free << '\n'; + ++frame; next_output += 100000000; + } + next_tick += tick_period; + }; + for (const auto& message : view) + { + const Stamp received = stampOf(message.getTime()); + // Never make a transform visible to the tracker before its recorded arrival. + while (next_tick < received) step(); + if (message.getTopic() == "/tf" || message.getTopic() == "/tf_static") + { + const auto transforms = message.instantiate(); + if (!transforms) throw std::runtime_error("TF topic has incompatible message type"); + for (const auto& transform : transforms->transforms) + if (!input->tf.setTransform(transform, "bag", message.getTopic() == "/tf_static")) + throw std::runtime_error("invalid recorded transform"); + } + else + { + const auto scan = message.instantiate(); + if (!scan) throw std::runtime_error("scan topic has incompatible message type"); + input->receive(message.getTopic(), *scan); ++scan_count; + } + } + while (next_tick <= end) step(); + if (!frames || !tracks) throw std::runtime_error("failed to write replay output"); + std::cout << "scans=" << scan_count << " output_frames=" << frame + << " duration=" << tracking::secondsBetween(end, start) << '\n'; + return 0; + } + catch (const std::exception& ex) { std::cerr << ex.what() << '\n'; return 1; } +}