From 8acbc5b0b0299d3744754afcb5c316778628b538 Mon Sep 17 00:00:00 2001 From: duongtd Date: Wed, 26 Aug 2026 09:18:49 +0700 Subject: [PATCH] Pick the majority cluster so a TF correction cannot stall a detection Localization correcting map->odom in the middle of a detection moves samples that were already collected into a different frame. The window then holds two clusters half a metre apart, the spread over the whole window stays above the limit for the rest of the timeout, and the action fails even though each cluster on its own is perfectly tight and the detector never made a mistake. jump_threshold > 0 turns on clustering. Samples are grouped by distance to the cluster CENTRE rather than to the nearest member: a sample caught while TF was interpolating sits between the two clusters and single-linkage would use it as a bridge to merge them back into one. A cluster may be committed only if it holds at least min_cluster_fraction of the window, at least min_cluster_samples in absolute terms, and has a sample newer than cluster_recency seconds. min_cluster_fraction is required to be > 0.5 so at most one cluster can ever qualify - no tie-break rule is needed, and two frames fighting 50/50 leave no winner, which is the right answer: with two centres 0.55 m apart, guessing docks half a metre off. The recency test is what separates the stale majority from the live one; a cluster that is large but cold is the pose from before the correction, in a frame localization has already discarded. Spread is then measured on the winning cluster only, so max_spread_xy/yaw keep their role as the safety gate. configure() rejects the combinations that can never succeed: jump_threshold below max_spread_xy would split good in-tolerance samples into fragments and fail on perfect data, min_cluster_fraction at exactly 0.5 loses uniqueness, and min_cluster_samples above min_samples can never be reached. filter_enabled: false is the deliberate escape hatch - commit the second sample and skip the window, spread and clustering entirely. The second and not the first, because the first lookup after the action starts can return a detection left in the buffer from before the robot stopped; a second sample with a different stamp proves the source is alive and the data is new. settle_delay and timeout still apply, and the timeout check drops to settle_delay alone since that path no longer needs a window. Defaults keep the previous behaviour: jump_threshold 0 means no clustering, filter_enabled true means the full filter. --- plugins/frame_sampler_action_handler.cpp | 321 ++++++++++++++++++++++- test/config/action_handlers_params.yaml | 60 +++++ test/frame_sampler_test.cpp | 173 ++++++++++++ 3 files changed, 544 insertions(+), 10 deletions(-) diff --git a/plugins/frame_sampler_action_handler.cpp b/plugins/frame_sampler_action_handler.cpp index 51ca43d..a87fbcd 100644 --- a/plugins/frame_sampler_action_handler.cpp +++ b/plugins/frame_sampler_action_handler.cpp @@ -31,6 +31,10 @@ constexpr double kDefaultMaxSpreadXy = 0.03; // [m] constexpr double kDefaultMaxSpreadYaw = 0.05; // [rad] constexpr double kDefaultHoldTime = 0.0; // [s] constexpr double kDefaultTimeout = 15.0; // [s] +constexpr double kDefaultJumpThreshold = 0.0; // [m] 0 = tắt lọc cụm +constexpr double kDefaultClusterRecency = 0.3; // [s] +constexpr double kDefaultMinClusterFraction = 0.6; +constexpr int kDefaultMinClusterSamples = 5; constexpr const char* kFrameKey = "goal_frame"; /// Chu kỳ in tiến trình hội tụ. Control loop chạy ~30 Hz; log mỗi cycle sẽ ngập log và làm chậm @@ -139,6 +143,35 @@ double robustSpread(std::vector& deviations) * phán-một-lần trước đây (một cửa sổ đầy, đủ `min_samples`, độ tản trong ngưỡng). Đặt > 0 khi hiện * trường có nhận nhầm. * + * ## Lọc cụm chống TF nhảy (`jump_threshold` > 0) + * + * Localization sửa `map→odom` giữa lúc dò nghĩa là mẫu ĐÃ THU nhảy sang hệ toạ độ khác: cửa sổ + * chứa hai (hay nhiều) cụm cách nhau cả nửa mét, độ tản toàn cửa sổ vượt ngưỡng mãi dù từng cụm tự + * nó chụm hoàn hảo — lượt dò fail suốt `timeout` trong khi phép dò không có lỗi gì. + * + * Bật `jump_threshold` thì mỗi lần đánh giá, mẫu được gom cụm theo khoảng cách tới **TÂM** cụm + * (không phải tới mẫu gần nhất — mẫu bắt giữa lúc TF nội suy nằm lưng chừng hai cụm sẽ bắc cầu nối + * chúng nếu đo kiểu single-linkage). Cụm được phép chốt phải: + * - chiếm ≥ `min_cluster_fraction` tổng mẫu cửa sổ. Buộc > 0.5: quá bán thì tối đa MỘT cụm đạt — + * khỏi cần luật xử hoà riêng, và hai hệ toạ độ giằng co 50/50 thì không phe nào đủ, handler + * chờ. Không biết thì không đẩy goal ra — hai tâm cách 0.55 m mà chọn bừa là dock sai nửa mét. + * - có ≥ `min_cluster_samples` mẫu — dưới sàn này median/spread không còn nghĩa thống kê; + * - có mẫu trong `cluster_recency` giây chót — cụm "đa số nhưng NGUỘI" là toạ độ trước correction, + * chốt theo nó là dock vào hệ toạ độ localization đã vứt bỏ. + * Độ tản sau đó chỉ tính trên cụm được chọn; `max_spread_*` giữ nguyên vai trò cổng an toàn. + * + * `cluster_recency` đồng thời là chân trời quyết định: TF đổi hẳn trong vòng ngần ấy giây trước + * lúc chốt thì không phân biệt được với flicker, handler vẫn có thể chốt theo cụm cũ. Đặt dài hơn + * flicker điển hình nhưng ngắn hơn nhiều so với `sample_window`. + * + * ## `filter_enabled: false` — bỏ lọc có chủ đích + * + * Chốt ngay mẫu THỨ HAI nhận được, không cửa sổ, không độ tản. Lấy mẫu thứ hai chứ không phải thứ + * nhất: lookup đầu tiên sau khi action bắt đầu có thể trả về detection CŨ còn sót trong buffer từ + * trước khi robot dừng; mẫu thứ hai (stamp khác) chứng minh nguồn còn sống và dữ liệu là mới. + * `settle_delay` và `timeout` vẫn có hiệu lực; mọi param cửa sổ/độ tản/cụm bị bỏ qua. Dùng khi cần + * loại trừ chính tầng lọc lúc debug, hoặc khi perception đã tự lọc xong và publish pose chốt. + * * ## Đọc tiến trình hội tụ * * Mỗi `kProgressLogPeriod` giây handler in một dòng: số mẫu trong cửa sổ, tâm, độ tản hiện tại và @@ -156,6 +189,12 @@ double robustSpread(std::vector& deviations) * - `max_spread_yaw` [rad] * - `hold_time` [s, 0] phải giữ trạng thái đạt liên tục ngần này mới chốt * - `timeout` [s] hết giờ mà chưa cửa sổ nào đạt → kFailed + * - `filter_enabled` [bool, true] false = chốt ngay mẫu thứ hai, bỏ toàn bộ cửa sổ/độ tản/cụm + * - `jump_threshold` [m, 0] 0 = tắt lọc cụm. Khoảng cách tới tâm cụm để mẫu được gom chung; + * đặt giữa độ tản dò thật (mm–cm) và biên độ TF nhảy (dm), bắt buộc > `max_spread_xy` + * - `cluster_recency` [s, 0.3] cụm không có mẫu mới hơn ngần này thì không được chốt + * - `min_cluster_fraction` [-, 0.6] tỉ lệ tổng mẫu cửa sổ mà cụm phải chiếm; bắt buộc > 0.5 + * - `min_cluster_samples` [-, 5] sàn mẫu tuyệt đối của cụm; bắt buộc ≤ `min_samples` * - `use_simulated_goal` [bool, false] chỉ dành cho Gazebo/dev: bỏ perception, chốt một pose * tương đối với `simulated_parent_frame` thành `output_frame` tĩnh. Không bật trên robot thật. * - `simulated_parent_frame` [string, "base_link"] parent của pose giả @@ -196,6 +235,11 @@ public: nh.param("max_spread_yaw", max_spread_yaw_, kDefaultMaxSpreadYaw); nh.param("hold_time", hold_time_, kDefaultHoldTime); nh.param("timeout", timeout_, kDefaultTimeout); + nh.param("filter_enabled", filter_enabled_, true); + nh.param("jump_threshold", jump_threshold_, kDefaultJumpThreshold); + nh.param("cluster_recency", cluster_recency_, kDefaultClusterRecency); + nh.param("min_cluster_fraction", min_cluster_fraction_, kDefaultMinClusterFraction); + nh.param("min_cluster_samples", min_cluster_samples_, kDefaultMinClusterSamples); nh.param("use_simulated_goal", use_simulated_goal_, false); nh.param("simulated_parent_frame", simulated_parent_frame_, std::string("base_link")); nh.param("simulated_offset_x", simulated_offset_x_, 0.0); @@ -245,7 +289,8 @@ public: hold_time_); return false; } - if (timeout_ > 0.0 && timeout_ <= settle_delay_ + sample_window_ + hold_time_) + if (filter_enabled_ && timeout_ > 0.0 && + timeout_ <= settle_delay_ + sample_window_ + hold_time_) { // Timeout ngắn hơn (thu mẫu + giữ trạng thái đạt) thì action LUÔN hỏng dù dò hoàn hảo — gần // như chắc chắn gõ nhầm. `hold_time` nằm trong tổng này vì nó cộng thêm sau cửa sổ đầu tiên. @@ -254,6 +299,55 @@ public: name_.c_str(), timeout_, settle_delay_ + sample_window_ + hold_time_); return false; } + if (!filter_enabled_ && timeout_ > 0.0 && timeout_ <= settle_delay_) + { + // Đường bỏ lọc chỉ cần settle + 2 mẫu, nhưng timeout ngắn hơn cả settle thì vẫn LUÔN hỏng. + robot::log_error("[action_core] '%s': timeout=%.3f s <= settle_delay=%.3f s; the action " + "would always fail.", + name_.c_str(), timeout_, settle_delay_); + return false; + } + if (!std::isfinite(jump_threshold_) || jump_threshold_ < 0.0) + { + robot::log_error("[action_core] '%s': jump_threshold=%.3f must be finite and >= 0.", + name_.c_str(), jump_threshold_); + return false; + } + if (filter_enabled_ && jump_threshold_ > 0.0) + { + if (jump_threshold_ <= max_spread_xy_) + { + // Ngưỡng gom cụm nằm DƯỚI độ tản hợp lệ thì mẫu tốt trong tolerance bị xé thành nhiều cụm, + // không cụm nào quá bán — action fail với dữ liệu hoàn hảo. + robot::log_error("[action_core] '%s': jump_threshold=%.3f must be > max_spread_xy=%.3f.", + name_.c_str(), jump_threshold_, max_spread_xy_); + return false; + } + if (!std::isfinite(cluster_recency_) || cluster_recency_ <= 0.0) + { + robot::log_error("[action_core] '%s': cluster_recency=%.3f must be > 0.", name_.c_str(), + cluster_recency_); + return false; + } + if (!std::isfinite(min_cluster_fraction_) || min_cluster_fraction_ <= 0.5 || + min_cluster_fraction_ > 1.0) + { + // > 0.5 để tối đa MỘT cụm đạt được — chính tính quá bán này thay cho luật xử hoà. Đúng 0.5 + // thì hai cụm 50/50 cùng đạt và handler phải chọn bừa giữa hai tâm cách nhau cả mét. + robot::log_error("[action_core] '%s': min_cluster_fraction=%.3f must be in (0.5, 1.0].", + name_.c_str(), min_cluster_fraction_); + return false; + } + if (min_cluster_samples_ < 3 || min_cluster_samples_ > min_samples_) + { + // Trần = min_samples: cụm là tập con của cửa sổ, sàn cụm cao hơn sàn cửa sổ thì dữ liệu + // hoàn hảo (cả cửa sổ là một cụm duy nhất) cũng không bao giờ chốt được. + robot::log_error( + "[action_core] '%s': min_cluster_samples=%d must be in [3, min_samples=%d].", + name_.c_str(), min_cluster_samples_, min_samples_); + return false; + } + } if (use_simulated_goal_) { if (simulated_parent_frame_.empty() || simulated_parent_frame_ == output_frame_) @@ -333,6 +427,33 @@ public: window_changed_ = window_changed_ || grew || shrank; } + // Bỏ lọc có chủ đích: chốt ngay mẫu THỨ HAI, không cửa sổ, không độ tản. Mẫu thứ nhất có thể + // là detection cũ còn sót trong buffer từ trước khi robot dừng; mẫu thứ hai (stamp khác) chứng + // minh nguồn còn sống và dữ liệu là mới. + if (!filter_enabled_) + { + if (total_samples_ >= 2) + { + if (!publish(samples_.back(), now)) + { + tick.status = ActionStatus::kFailed; + tick.message = "action '" + action_id_ + "': could not publish '" + output_frame_ + "'"; + return tick; + } + tick.status = ActionStatus::kSucceeded; + tick.message = "action '" + action_id_ + "': '" + output_frame_ + + "' from raw sample #2 (filter disabled) after " + formatSeconds(elapsed) + + " s"; + return tick; + } + if (timeout_ > 0.0 && elapsed >= timeout_) + { + return failOnTimeout(elapsed); + } + tick.status = ActionStatus::kRunning; + return tick; + } + // Cửa sổ đầu tiên phải đủ THỜI LƯỢNG, không chỉ đủ số mẫu: mẫu thu trong 0.2 s đầu nằm sát nhau // về thời gian nên trông chụm một cách giả tạo, chốt theo đó là chốt trước khi có bằng chứng. if (elapsed >= settle_delay_ + sample_window_ && window_changed_) @@ -388,6 +509,16 @@ private: robot::Time taken_at; }; + /// Một cụm mẫu trong cửa sổ (xem buildClusters). Tâm chạy = `sum / count`. + struct Cluster + { + double sum_x = 0.0; + double sum_y = 0.0; + std::size_t count = 0; + /// `taken_at` của mẫu mới nhất trong cụm — quyết định cụm còn TƯƠI hay đã nguội (pickCluster). + robot::Time newest; + }; + bool readFrameParam(const robot_protocol_msgs::Action& action, std::string& frame) const { const auto it = std::find_if(action.actionParameters.begin(), action.actionParameters.end(), @@ -422,6 +553,9 @@ private: best_spread_yaw_ = 0.0; best_description_.clear(); have_progress_log_ = false; + clusters_.clear(); + cluster_of_.clear(); + cluster_summary_[0] = '\0'; } /** @@ -502,10 +636,28 @@ private: return; } + // Lọc cụm (nếu bật): chọn cụm quá bán còn tươi rồi mới đo độ tản TRÊN RIÊNG cụm đó. TF nhảy + // làm cửa sổ chứa nhiều hệ toạ độ — đo độ tản cả cửa sổ khi ấy là đo khoảng cách giữa các hệ, + // không phải chất lượng phép dò. + const bool clustering = jump_threshold_ > 0.0; + int chosen = -1; + if (clustering) + { + buildClusters(); + chosen = pickCluster(now); + describeClusters(); + } + else + { + cluster_summary_[0] = '\0'; + } + Sample centre; double spread_xy = 0.0; double spread_yaw = 0.0; - filter(centre, spread_xy, spread_yaw); + // Không cụm nào đạt thì vẫn lọc CẢ cửa sổ — không phải để chốt (bị chặn bên dưới) mà để log và + // best window phản ánh đúng độ loạn thô của dữ liệu lúc chẩn đoán timeout. + filter(chosen, centre, spread_xy, spread_yaw); // Điểm = tỉ lệ so với ngưỡng, lấy trục tệ hơn. Cho biết cửa sổ còn thiếu bao nhiêu để đạt, và so // sánh được giữa hai trục có đơn vị khác nhau ([m] và [rad]). @@ -521,7 +673,8 @@ private: best_description_ = describeSamples(centre); } - if (spread_xy <= max_spread_xy_ && spread_yaw <= max_spread_yaw_) + const bool within = spread_xy <= max_spread_xy_ && spread_yaw <= max_spread_yaw_; + if (within && !(clustering && chosen < 0)) { if (!converged_) { @@ -542,10 +695,122 @@ private: converged_ = false; } + const char* note = converged_ ? " — within tolerance, holding" + : (clustering && chosen < 0 && clusters_.size() > 1) + ? " — no majority cluster, waiting" + : ""; logProgress(now, "%zu sample(s): centre=(%.3f, %.3f) yaw=%.4f rad, spread xy=%.4f/%.3f m " - "yaw=%.4f/%.3f rad%s", + "yaw=%.4f/%.3f rad%s%s", samples_.size(), centre.x, centre.y, centre.yaw, spread_xy, max_spread_xy_, - spread_yaw, max_spread_yaw_, converged_ ? " — within tolerance, holding" : ""); + spread_yaw, max_spread_yaw_, cluster_summary_, note); + } + + /** + * @brief Gom mẫu trong cửa sổ thành cụm theo khoảng cách tới TÂM cụm. + * + * Đo tới tâm, KHÔNG phải tới mẫu gần nhất: mẫu bắt giữa lúc TF nội suy nằm lưng chừng hai cụm, + * đo kiểu single-linkage sẽ lấy nó làm cầu nối dính hai cụm thành một. Tâm chạy bằng trung bình + * cộng — đủ cho việc GÁN (các cụm cách nhau hàng dm), tâm chốt cuối vẫn là median qua filter(). + * + * Xây lại từ đầu mỗi lần đánh giá: n ≤ vài chục nên rẻ, và không có trạng thái tăng dần để sai. + * Chỉ gom theo (x, y) — TF nhảy là lệch vị trí; yaw đã có cổng spread riêng trên cụm được chọn. + */ + void buildClusters() + { + clusters_.clear(); + cluster_of_.clear(); + + for (const Sample& s : samples_) + { + int best = -1; + double best_d = jump_threshold_; + for (std::size_t i = 0; i < clusters_.size(); ++i) + { + const Cluster& c = clusters_[i]; + const double d = std::hypot(s.x - c.sum_x / c.count, s.y - c.sum_y / c.count); + if (d < best_d) + { + best_d = d; + best = static_cast(i); + } + } + if (best < 0) + { + Cluster c; + c.sum_x = s.x; + c.sum_y = s.y; + c.count = 1; + c.newest = s.taken_at; + clusters_.push_back(c); + best = static_cast(clusters_.size()) - 1; + } + else + { + Cluster& c = clusters_[best]; + c.sum_x += s.x; + c.sum_y += s.y; + ++c.count; + c.newest = s.taken_at; // mẫu duyệt theo thứ tự thời gian nên đây luôn là mẫu mới nhất + } + cluster_of_.push_back(best); + } + } + + /** + * @brief Chọn cụm được phép chốt: quá bán, đủ sàn thống kê, và còn TƯƠI. + * + * `min_cluster_fraction` > 0.5 nên tối đa MỘT cụm đạt — không cần luật xử hoà. Điều kiện tươi + * chặn ca nguy hiểm nhất: TF vừa sửa hẳn, cụm cũ vẫn đông nhất trong cửa sổ nhưng đã ngừng nhận + * mẫu — toạ độ đó localization đã vứt bỏ, chốt theo nó là dock lệch đúng bằng cú nhảy. + * + * @return chỉ số cụm trong `clusters_`, hoặc -1 nếu không cụm nào đủ điều kiện. + */ + int pickCluster(const robot::Time& now) const + { + const double need = min_cluster_fraction_ * static_cast(samples_.size()); + for (std::size_t i = 0; i < clusters_.size(); ++i) + { + const Cluster& c = clusters_[i]; + if (static_cast(c.count) < need || + c.count < static_cast(min_cluster_samples_) || + (now - c.newest).toSec() > cluster_recency_) + { + continue; + } + return static_cast(i); + } + return -1; + } + + /// @brief Tóm tắt bố cục cụm vào `cluster_summary_` — "10@(x, y) 1@(x, y)" đọc phát biết ngay TF + /// nhảy đi đâu và mỗi phe đông cỡ nào, thứ mà một con số spread tổng không nói được. + /// Một cụm duy nhất thì để rỗng: không có gì đáng nói và log giữ nguyên dạng cũ. + void describeClusters() + { + if (clusters_.size() <= 1) + { + cluster_summary_[0] = '\0'; + return; + } + int off = std::snprintf(cluster_summary_, sizeof(cluster_summary_), ", %zu clusters:", + clusters_.size()); + constexpr std::size_t kMaxListed = 3; + for (std::size_t i = 0; i < clusters_.size() && i < kMaxListed; ++i) + { + if (off < 0 || static_cast(off) >= sizeof(cluster_summary_)) + { + return; + } + const Cluster& c = clusters_[i]; + off += std::snprintf(cluster_summary_ + off, sizeof(cluster_summary_) - off, + " %zu@(%.2f, %.2f)", c.count, c.sum_x / c.count, c.sum_y / c.count); + } + if (clusters_.size() > kMaxListed && off > 0 && + static_cast(off) < sizeof(cluster_summary_)) + { + std::snprintf(cluster_summary_ + off, sizeof(cluster_summary_) - off, " (+%zu)", + clusters_.size() - kMaxListed); + } } /// @brief In tiến độ hội tụ, tối đa một dòng mỗi `kProgressLogPeriod` giây. @@ -559,7 +824,7 @@ private: last_progress_log_ = now; have_progress_log_ = true; - char buffer[320]; + char buffer[512]; // dòng tiến độ + tóm tắt cụm (tối đa 176) phải vừa, không được cắt cụt std::snprintf(buffer, sizeof(buffer), format, args...); robot::log_info("[action_core] '%s': %s", name_.c_str(), buffer); } @@ -577,6 +842,15 @@ private: return tick; } + if (!filter_enabled_) + { + // Đường bỏ lọc mà vẫn timeout nghĩa là chỉ thấy đúng MỘT mẫu suốt lượt (>= 2 đã chốt từ lâu): + // không có mẫu thứ hai xác nhận, rất có thể là detection cũ đóng băng trong buffer. + tick.message = "action '" + action_id_ + "': '" + frame_ + "' produced only one sample in " + + formatSeconds(elapsed) + " s — need a second fresh sample (filter disabled)"; + return tick; + } + if (!best_valid_) { // Thấy, nhưng chưa cửa sổ nào đủ `min_samples`: nguồn publish quá thưa so với `sample_window`. @@ -659,13 +933,18 @@ private: "deviation p50=%.3f p90=%.3f max=%.3f m, bbox x=[%.3f, %.3f] y=[%.3f, %.3f]", samples_.size(), frame_.c_str(), ctx_.global_frame.c_str(), centre.x, centre.y, centre.yaw, at(0.5), at(0.9), dev.back(), min_x, max_x, min_y, max_y); - return buffer; + // Bố cục cụm cùng thời điểm chụp (rỗng khi lọc cụm tắt hoặc chỉ có một cụm): cho biết các mẫu + // văng chia PHE thế nào — "TF nhảy qua lại giữa hai chỗ" và "dò tản đều" cần hai cách xử trí + // ngược nhau mà p50/p90 không phân biệt được. + return std::string(buffer) + cluster_summary_; } /// @note Dùng buffer là member, không phải vector cục bộ: hàm này chạy mỗi khi cửa sổ đổi, tức /// gần như mỗi control cycle. `clear()` giữ nguyên capacity nên sau vài tick đầu là hết cấp /// phát. Vì vậy hàm không `const`. - void filter(Sample& out, double& spread_xy, double& spread_yaw) + /// @param cluster_id -1 = lọc CẢ cửa sổ; >= 0 = chỉ mẫu thuộc cụm đó theo `cluster_of_` (phải + /// gọi buildClusters() ngay trước, cùng một hình dạng `samples_`). + void filter(int cluster_id, Sample& out, double& spread_xy, double& spread_yaw) { buf_x_.clear(); buf_y_.clear(); @@ -675,8 +954,13 @@ private: double sum_sin = 0.0; double sum_cos = 0.0; - for (const Sample& s : samples_) + for (std::size_t i = 0; i < samples_.size(); ++i) { + if (cluster_id >= 0 && cluster_of_[i] != cluster_id) + { + continue; + } + const Sample& s = samples_[i]; buf_x_.push_back(s.x); buf_y_.push_back(s.y); sum_sin += std::sin(s.yaw); @@ -695,8 +979,13 @@ private: buf_dev_xy_.reserve(samples_.size()); buf_dev_yaw_.reserve(samples_.size()); - for (const Sample& s : samples_) + for (std::size_t i = 0; i < samples_.size(); ++i) { + if (cluster_id >= 0 && cluster_of_[i] != cluster_id) + { + continue; + } + const Sample& s = samples_[i]; buf_dev_xy_.push_back(std::hypot(s.x - out.x, s.y - out.y)); // Lệch góc phải quy về (-pi, pi], nếu không mẫu ở hai bên đường cắt bị tính thành ~2pi. buf_dev_yaw_.push_back( @@ -765,6 +1054,11 @@ private: double max_spread_yaw_ = kDefaultMaxSpreadYaw; double hold_time_ = kDefaultHoldTime; // [s] double timeout_ = kDefaultTimeout; + bool filter_enabled_ = true; + double jump_threshold_ = kDefaultJumpThreshold; // [m] 0 = tắt lọc cụm + double cluster_recency_ = kDefaultClusterRecency; // [s] + double min_cluster_fraction_ = kDefaultMinClusterFraction; + int min_cluster_samples_ = kDefaultMinClusterSamples; bool use_simulated_goal_ = false; std::string simulated_parent_frame_ = "base_link"; double simulated_offset_x_ = 0.0; // [m] @@ -806,6 +1100,13 @@ private: std::vector buf_y_; std::vector buf_dev_xy_; std::vector buf_dev_yaw_; + + /// Buffer gom cụm, xây lại mỗi lần đánh giá; member để giữ capacity như các buffer của filter(). + std::vector clusters_; + /// cluster_of_[i] = chỉ số cụm của samples_[i]; filter() dùng để lọc theo cụm được chọn. + std::vector cluster_of_; + /// Tóm tắt bố cục cụm của lần đánh giá gần nhất, gắn vào log tiến độ và mô tả best window. + char cluster_summary_[176] = {0}; }; } // namespace action_core diff --git a/test/config/action_handlers_params.yaml b/test/config/action_handlers_params.yaml index 864559c..e2b9af7 100644 --- a/test/config/action_handlers_params.yaml +++ b/test/config/action_handlers_params.yaml @@ -97,6 +97,66 @@ actions_detect_hold: hold_time: 0.5 # [s] timeout: 5.0 # [s] +# Lọc cụm chống TF nhảy: mẫu gom theo khoảng cách tới TÂM cụm, chỉ cụm quá bán còn tươi được chốt. +actions_detect_cluster: + handlers: + - {name: detect, type: FrameSamplerActionHandler} + detect: + action_types: [DetectCharger] + output_frame: dock_target + settle_delay: 0.2 # [s] + sample_window: 1.0 # [s] + min_samples: 10 + max_spread_xy: 0.03 # [m] + max_spread_yaw: 0.05 # [rad] + timeout: 5.0 # [s] + jump_threshold: 0.15 # [m] > max_spread_xy; TF nhảy trong test là 0.55 m + cluster_recency: 0.3 # [s] + min_cluster_fraction: 0.6 + min_cluster_samples: 5 + +# jump_threshold <= max_spread_xy: mẫu tốt trong tolerance bị xé cụm -> configure() phải từ chối. +actions_detect_cluster_bad_threshold: + handlers: + - {name: detect, type: FrameSamplerActionHandler} + detect: + action_types: [DetectCharger] + output_frame: dock_target + max_spread_xy: 0.03 + jump_threshold: 0.02 + +# min_cluster_fraction phải > 0.5 — đúng 0.5 thì hai cụm 50/50 cùng đạt, mất tính duy nhất. +actions_detect_cluster_bad_fraction: + handlers: + - {name: detect, type: FrameSamplerActionHandler} + detect: + action_types: [DetectCharger] + output_frame: dock_target + jump_threshold: 0.15 + min_cluster_fraction: 0.5 + +# Sàn cụm cao hơn min_samples: dữ liệu hoàn hảo cũng không bao giờ chốt được -> từ chối. +actions_detect_cluster_bad_floor: + handlers: + - {name: detect, type: FrameSamplerActionHandler} + detect: + action_types: [DetectCharger] + output_frame: dock_target + min_samples: 10 + jump_threshold: 0.15 + min_cluster_samples: 20 + +# Bỏ lọc có chủ đích: chốt ngay mẫu THỨ HAI, không cửa sổ, không độ tản. +actions_detect_unfiltered: + handlers: + - {name: detect, type: FrameSamplerActionHandler} + detect: + action_types: [DetectCharger] + output_frame: dock_target + filter_enabled: false + settle_delay: 0.2 # [s] + timeout: 5.0 # [s] + # output_frame trùng input_frame -> configure() phải từ chối. actions_detect_same_frame: handlers: diff --git a/test/frame_sampler_test.cpp b/test/frame_sampler_test.cpp index 6a651c7..832118d 100644 --- a/test/frame_sampler_test.cpp +++ b/test/frame_sampler_test.cpp @@ -316,6 +316,179 @@ TEST(FrameSampler, HoldTimeDelaysTheCommit) EXPECT_LE(stopped_at, kFirstVerdict + 0.5 + 0.05); } +// ================================================================================================ +// Lọc cụm — TF nhảy làm cửa sổ chứa nhiều hệ toạ độ +// ================================================================================================ + +TEST(FrameSampler, ClusterFilterIgnoresAMinorityOfJumpedSamples) +{ + Rig rig("actions_detect_cluster"); + ASSERT_TRUE(rig.loaded); + ASSERT_NE(rig.handler, nullptr); + ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(kStart))); + + // TF flicker: ~10% mẫu văng sang hệ toạ độ khác cách 0.55 m — đúng hình dạng dữ liệu hiện trường + // khi backend localization sửa map->odom qua lại. robustSpread cắt phân vị 90 không chịu nổi 10% + // lệch CÓ CẤU TRÚC thế này (spread ~1.1 m, fail suốt timeout); lọc cụm phải coi đây là ca thuận + // lợi: cụm chính 90% chụm hoàn hảo. + double stopped_at = 0.0; + EXPECT_EQ(runTicks(rig, 101.5, + [](Rig& r, int i, double t) { + const double s = (i % 2 == 0) ? 1.0 : -1.0; + const double jump = (i % 10 == 0) ? 0.55 : 0.0; + r.pushSample(2.0 + jump + s * 0.002, 1.0 - s * 0.002, 0.0, t); + }, + &stopped_at), + ActionStatus::kSucceeded); + + // Cụm chính quá bán và chụm ngay từ đầu — phải chốt ở cửa sổ ĐẦU TIÊN, không được chờ thêm. + EXPECT_NEAR(stopped_at, kFirstVerdict, 0.03); + + double x = 0.0, y = 0.0, yaw = 0.0; + ASSERT_TRUE(rig.readOutput(x, y, yaw)); + EXPECT_NEAR(x, 2.0, 0.005) << "tâm phải là cụm chính, mẫu nhảy không được kéo"; + EXPECT_NEAR(y, 1.0, 0.005); +} + +TEST(FrameSampler, ClusterFilterRefusesWithoutAMajority) +{ + Rig rig("actions_detect_cluster"); + ASSERT_NE(rig.handler, nullptr); + ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(kStart))); + + // Hai hệ toạ độ giằng co 50/50, mỗi cụm TỰ NÓ chụm hoàn hảo. Không phe nào quá bán -> không được + // chọn bừa một trong hai tâm cách nhau 0.55 m; phải chờ hết timeout rồi fail. + double stopped_at = 0.0; + EXPECT_EQ(runTicks(rig, 105.2, + [](Rig& r, int i, double t) { + const double jump = (i % 2 == 0) ? 0.55 : 0.0; + r.pushSample(2.0 + jump, 1.0, 0.0, t); + }, + &stopped_at), + ActionStatus::kFailed); + EXPECT_GE(stopped_at, kTimeoutAt); + + double x = 0.0, y = 0.0, yaw = 0.0; + EXPECT_FALSE(rig.readOutput(x, y, yaw)) << "không quá bán thì KHÔNG được ghi frame nào"; +} + +TEST(FrameSampler, ClusterFilterFollowsTheFreshClusterAfterATfCorrection) +{ + Rig rig("actions_detect_cluster"); + ASSERT_NE(rig.handler, nullptr); + ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(kStart))); + + // Trước 101.0: dò tản (±0.05 -> spread ~0.14, một cụm duy nhất nhưng không bao giờ đạt ngưỡng). + // Từ 101.0: TF đã sửa HẲN, mẫu chụm quanh vị trí mới cách 0.55 m. Handler phải chốt theo cụm + // mới; cụm cũ dù còn đông trong cửa sổ nhưng đã NGUỘI (quá cluster_recency không nhận mẫu). + double stopped_at = 0.0; + EXPECT_EQ(runTicks(rig, 105.2, + [](Rig& r, int i, double t) { + if (t < 101.0) + { + const double s = (i % 2 == 0) ? 1.0 : -1.0; + r.pushSample(2.0 + s * 0.05, 1.0, 0.0, t); + } + else + { + r.pushSample(2.55, 1.0, 0.0, t); + } + }, + &stopped_at), + ActionStatus::kSucceeded); + + // Cụm mới phải chiếm 60% cửa sổ 1.0 s -> sớm nhất ~101.6. Muộn hơn nhiều là fraction/recency sai. + EXPECT_GT(stopped_at, 101.55); + EXPECT_LT(stopped_at, 101.9); + + double x = 0.0, y = 0.0, yaw = 0.0; + ASSERT_TRUE(rig.readOutput(x, y, yaw)); + EXPECT_NEAR(x, 2.55, 0.005) << "phải chốt theo hệ toạ độ SAU correction, không phải cụm cũ"; +} + +TEST(FrameSampler, InterpolatedSamplesDoNotBridgeClusters) +{ + Rig rig("actions_detect_cluster"); + ASSERT_NE(rig.handler, nullptr); + ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(kStart))); + + // TF nội suy lúc nhảy sinh chuỗi mẫu LƠ LỬNG nối hai cụm, mỗi bước 0.14 m < jump_threshold 0.15. + // Đo kiểu single-linkage thì chuỗi này xích cả hai cụm thành một cụm khổng lồ "quá bán" với tâm + // sai; đo tới TÂM cụm thì mắt xích thứ hai đã cách tâm cụm chính 0.28 m và phải đứng riêng. + double stopped_at = 0.0; + EXPECT_EQ(runTicks(rig, 101.5, + [](Rig& r, int i, double t) { + double x = 2.0; + switch (i % 25) + { + case 0: x = 2.14; break; + case 1: x = 2.28; break; + case 2: x = 2.42; break; + case 3: x = 2.55; break; + default: break; + } + r.pushSample(x, 1.0, 0.0, t); + }, + &stopped_at), + ActionStatus::kSucceeded); + EXPECT_NEAR(stopped_at, kFirstVerdict, 0.03); + + double x = 0.0, y = 0.0, yaw = 0.0; + ASSERT_TRUE(rig.readOutput(x, y, yaw)); + EXPECT_NEAR(x, 2.0, 0.005) << "mẫu nội suy không được nối cụm lẫn kéo tâm"; +} + +TEST(FrameSampler, RefusesInvalidClusterConfigs) +{ + EXPECT_FALSE(Rig("actions_detect_cluster_bad_threshold").loaded) + << "jump_threshold <= max_spread_xy xé mẫu tốt thành nhiều cụm — phải chặn lúc boot"; + EXPECT_FALSE(Rig("actions_detect_cluster_bad_fraction").loaded) + << "fraction = 0.5 mất tính duy nhất của cụm quá bán"; + EXPECT_FALSE(Rig("actions_detect_cluster_bad_floor").loaded) + << "sàn cụm cao hơn min_samples thì dữ liệu hoàn hảo cũng không bao giờ chốt"; +} + +// ================================================================================================ +// filter_enabled: false — chốt ngay mẫu thứ hai +// ================================================================================================ + +TEST(FrameSampler, UnfilteredModeCommitsTheSecondSample) +{ + Rig rig("actions_detect_unfiltered"); + ASSERT_TRUE(rig.loaded); + ASSERT_NE(rig.handler, nullptr); + ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(kStart))); + + // Mẫu THỨ NHẤT có thể là detection cũ còn sót trong buffer — cố ý đặt nó ở chỗ sai hẳn. Handler + // không được chốt theo nó, và không phải chờ cửa sổ nào: mẫu thứ hai tới là chốt ngay tick đó. + rig.pushSample(9.9, 9.9, 3.0, 100.3); + EXPECT_EQ(rig.handler->update(robot::Time(100.3)).status, ActionStatus::kRunning); + + rig.pushSample(2.0, 1.0, 0.5, 100.4); + EXPECT_EQ(rig.handler->update(robot::Time(100.4)).status, ActionStatus::kSucceeded); + + double x = 0.0, y = 0.0, yaw = 0.0; + ASSERT_TRUE(rig.readOutput(x, y, yaw)); + EXPECT_NEAR(x, 2.0, 1e-6) << "phải chốt đúng mẫu THỨ HAI, không phải mẫu đầu"; + EXPECT_NEAR(y, 1.0, 1e-6); + EXPECT_NEAR(yaw, 0.5, 1e-6); +} + +TEST(FrameSampler, UnfilteredModeStillFailsWithASingleFrozenSample) +{ + Rig rig("actions_detect_unfiltered"); + ASSERT_NE(rig.handler, nullptr); + ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(kStart))); + + // Đúng MỘT mẫu rồi nguồn đứng im (stamp không đổi): không có mẫu thứ hai xác nhận nguồn còn + // sống -> phải chờ hết timeout rồi fail, không được chốt mẫu đơn độc. + rig.pushSample(2.0, 1.0, 0.0, 100.3); + EXPECT_EQ(runTicks(rig, 105.2, [](Rig&, int, double) {}), ActionStatus::kFailed); + + double x = 0.0, y = 0.0, yaw = 0.0; + EXPECT_FALSE(rig.readOutput(x, y, yaw)); +} + // ================================================================================================ // Đường lỗi — mỗi ca phải fail được // ================================================================================================