Move the sample filter out of the frame sampler so a second detector can use it

The handler was 1114 lines, of which roughly 200 were "read a pose from TF".
The rest was the filter: a sliding window, cluster rejection for localization
jumps, robust spread, a hold timer, and the diagnostics that make a failed
detection explainable. A detector that finds a dock plate in a laser scan
produces a pose per scan and needs all of that too, and writing it twice is
worse than the duplication - the two copies drift, and a fix lands in one.

PoseSampleFilter now owns the window, the clustering, the spread measurement,
the hold clock, the best-window record and the throttled progress log. The
handler keeps what is actually specific to being a TF source: the lookup and
its stamp-based dedupe, goal_frame, settle_delay and timeout, the simulated
goal path, writing the result back as a static transform, and the three
distinct timeout messages.

The line between them is source versus filtering. last_stamp_ stays with the
handler for that reason - deduplicating on a TF stamp is a property of that
source, and a detector reading from the shared sensor store will dedupe on an
arrival counter instead.

filter_enabled moves into the filter's config rather than staying with the
handler, because it decides whether the cluster keys are validated at all.
Split across two owners, that is one rule two places have to remember, and the
first time they disagree a config that used to load stops loading.

The filter validates its own keys and logs them with the instance name, so the
messages an operator has learned to read come out identical.

Behaviour is unchanged and the test files are untouched: 22 of 22 frame sampler
tests pass as they are. That is the point of doing it this way - the tests
cover exactly the code that moved, so passing them without editing them is what
distinguishes a refactor from a rewrite.

Both detectors now read the same YAML keys, so sample_window, max_spread_xy and
jump_threshold are learned once rather than once per detector.
This commit is contained in:
2026-08-26 12:30:51 +07:00
parent 3b7692ed8b
commit a6bc3dfa3d
4 changed files with 876 additions and 559 deletions

View File

@@ -162,6 +162,7 @@ endif()
add_library(action_core SHARED
src/action_types.cpp
src/action_registry.cpp
src/pose_sample_filter.cpp
)
target_compile_options(action_core PRIVATE -Wall -Wextra)

View File

@@ -0,0 +1,276 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* action_core — lọc một chuỗi mẫu pose nhiễu thành một pose đủ tin để chốt.
*
* Author: DuongTD
*********************************************************************/
#ifndef ACTION_CORE_POSE_SAMPLE_FILTER_H_
#define ACTION_CORE_POSE_SAMPLE_FILTER_H_
#include <cstddef>
#include <string>
#include <vector>
#include <robot/time.h>
namespace action_core
{
/// @brief Một mẫu pose 2D trong một frame cố định.
struct PoseSample
{
double x = 0.0; // [m]
double y = 0.0; // [m]
double yaw = 0.0; // [rad]
/**
* Thời điểm bên gọi THU được mẫu, không phải stamp của nguồn.
*
* Cửa sổ trượt cắt theo trục thời gian của chính bên gọi, cùng trục với `timeout` của nó. Stamp
* của nguồn có thể nằm trên trục khác — TF do một tiến trình khác publish, scan mang sim time —
* và trộn hai trục lại là cửa sổ dài ngắn tuỳ hứng.
*/
robot::Time taken_at;
};
/**
* @struct PoseSampleFilterConfig
* @brief Tham số của bộ lọc. Mọi khoá có default tại chỗ khai, có đơn vị, và đi qua @ref validate.
*/
struct PoseSampleFilterConfig
{
/**
* Công tắc tầng lọc. `false` = bên gọi tự quyết định, bộ lọc không được dùng.
*
* Nằm ở đây chứ không ở bên gọi vì nó quyết định luôn việc nhóm khoá cụm bên dưới có được kiểm
* hay không — tách ra hai chỗ là hai nơi cùng phải nhớ một luật.
*/
bool enabled = true;
/// [s] Độ dài cửa sổ TRƯỢT. Chỉ mẫu trong ngần này giây gần nhất được xét.
double sample_window = 2.0;
/// Số mẫu tối thiểu trong cửa sổ để cửa sổ đó được chấm điểm.
int min_samples = 20;
/// [m] Độ tản tối đa của cửa sổ (của CỤM được chọn khi bật lọc cụm).
double max_spread_xy = 0.03;
/// [rad] Như trên, cho góc.
double max_spread_yaw = 0.05;
/// [s] Phải giữ trạng thái đạt liên tục ngần này mới chốt. 0 = chốt ngay cửa sổ đạt đầu tiên.
double hold_time = 0.0;
/// [m] Khoảng cách tới TÂM cụm để mẫu được gom chung. 0 = tắt lọc cụm.
double jump_threshold = 0.0;
/// [s] Cụm không nhận mẫu mới hơn ngần này thì không được chốt.
double cluster_recency = 0.3;
/// Tỉ lệ tổng mẫu cửa sổ mà cụm phải chiếm. Bắt buộc > 0.5.
double min_cluster_fraction = 0.6;
/// Sàn mẫu tuyệt đối của cụm được chốt. Bắt buộc nằm trong [3, min_samples].
int min_cluster_samples = 5;
/**
* @brief Kiểm miền giá trị, log lỗi kèm @p owner rồi trả false.
*
* Kiểm lúc cấu hình chứ không phải lúc chạy: một ngưỡng không thể đạt được sẽ biểu hiện thành
* "dò mãi không ra", nhìn giống hệt cảm biến chết.
*/
bool validate(const std::string& owner) const;
};
/**
* @class PoseSampleFilter
* @brief Cửa sổ trượt + lọc cụm + độ tản bền + giữ trạng thái, trên một chuỗi mẫu pose.
*
* Bên gọi đưa mẫu vào, bộ lọc trả lời một câu: *đã đủ tin để chốt chưa, và nếu rồi thì chốt pose
* nào.* Nó không biết mẫu từ đâu ra — TF do perception publish, hay pose khớp được từ một scan
* LiDAR — nên cùng một bộ lọc phục vụ được cả hai, và người vận hành học **một** tập khoá YAML.
*
* ## Bốn lớp, mỗi lớp chặn một kiểu hỏng khác nhau
*
* 1. **Cửa sổ trượt** — chỉ xét `sample_window` giây gần nhất, đánh giá lại mỗi khi cửa sổ đổi.
* Mẫu xấu lúc nguồn mới bám không làm hỏng cả lượt: nó trôi ra khỏi cửa sổ.
* 2. **Lọc cụm** — localization sửa `map->odom` giữa chừng thì mẫu ĐÃ THU nhảy sang hệ toạ độ
* khác. Cửa sổ chứa hai 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. Chọn cụm quá bán còn tươi rồi mới đo độ tản trên riêng nó.
* 3. **Độ tản bền** — 2 x phân vị 90 quanh trung vị, không phải min-max. Một mẫu nhận nhầm trong
* ba mươi mẫu không được phép đánh hỏng cả lượt.
* 4. **Giữ trạng thái** — `hold_time` bắt cửa sổ đạt liên tục, chặn ca perception thỉnh thoảng bám
* nhầm vật thể khác một cách ỔN ĐỊNH (mẫu vẫn chụm, chỉ là chụm quanh sai chỗ).
*
* ## Chẩn đoán là phần không được cắt bớt
*
* Lượt dò hỏng mà chỉ có một con số `spread` thì không phân biệt được hai nguyên nhân đòi hai cách
* xử lý trái ngược: vài mẫu văng xa (nhận nhầm ở nguồn) và mọi mẫu đều lệch (dò thật sự không ổn
* định). Nên bộ lọc giữ **cửa sổ tốt nhất từng thấy** cùng p50/p90/max và hộp bao — xem
* @ref bestDescription.
*
* @note Không thread-safe. Một instance cho một lượt dò, gọi từ một thread.
*/
class PoseSampleFilter
{
public:
PoseSampleFilter() = default;
/// @brief Nhận tham số. Sai miền thì giữ nguyên bộ cũ và trả false.
bool configure(const PoseSampleFilterConfig& config, const std::string& owner);
const PoseSampleFilterConfig& config() const
{
return config_;
}
/**
* @brief Nhãn dùng trong log và trong mô tả chẩn đoán. Gọi lúc bắt đầu một lượt.
* @param source Thứ đang được lấy mẫu — tên TF frame thô, hay tên topic scan.
* @param frame Frame mà mẫu nằm trong đó, thường là `map`.
*/
void setLabels(const std::string& source, const std::string& frame);
/// @brief Xoá sạch trạng thái của lượt trước. Gọi ở start() và cancel() của bên gọi.
void reset();
/// @brief Thêm một mẫu vào cửa sổ. @return true — cửa sổ đã đổi.
bool addSample(const PoseSample& sample);
/// @brief Bỏ mẫu già hơn `sample_window`. @return true — cửa sổ đã đổi.
bool pruneExpired(const robot::Time& now);
/**
* @brief Chấm điểm cửa sổ hiện tại: cụm, độ tản, đồng hồ giữ, cửa sổ tốt nhất, log tiến độ.
*
* Chỉ gọi khi cửa sổ ĐỔI. Cửa sổ không đổi thì độ tản cũng không đổi — lọc lại mỗi control cycle
* chỉ tốn CPU và cấp phát vô ích.
*/
void evaluate(const robot::Time& now);
/// @brief Cửa sổ đang đạt ngưỡng liên tục hay không.
bool converged() const
{
return converged_;
}
/// @brief Đã giữ trạng thái đạt đủ `hold_time` chưa. Đây là điều kiện chốt.
bool holdSatisfied(const robot::Time& now) const;
/// @brief Pose để chốt. Chỉ có nghĩa khi @ref converged.
const PoseSample& holdPose() const
{
return hold_pose_;
}
/// @brief Số mẫu đang nằm trong cửa sổ.
std::size_t windowSize() const
{
return samples_.size();
}
/// @brief Mẫu mới nhất. Bên gọi phải tự bảo đảm cửa sổ không rỗng.
const PoseSample& newest() const
{
return samples_.back();
}
/**
* @brief Tổng mẫu thu được CẢ LƯỢT, kể cả mẫu đã trôi khỏi cửa sổ.
*
* Phân biệt "không thấy gì" với "thấy nhưng nguồn publish quá thưa" lúc timeout — hai lỗi khác
* hẳn nhau mà `windowSize()` không nói được.
*/
std::size_t totalSamples() const
{
return total_samples_;
}
/// @brief Đã có ít nhất một cửa sổ được chấm điểm chưa.
bool hasBest() const
{
return best_valid_;
}
/// @brief Điểm cửa sổ tốt nhất = tỉ lệ so với ngưỡng, lấy trục tệ hơn. < 1.0 nghĩa là đã đạt.
double bestScore() const
{
return best_score_;
}
double bestSpreadXy() const
{
return best_spread_xy_;
}
double bestSpreadYaw() const
{
return best_spread_yaw_;
}
/// @brief Hình dạng cửa sổ tốt nhất: p50/p90/max của độ lệch, hộp bao, bố cục cụm.
const std::string& bestDescription() const
{
return best_description_;
}
private:
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.
robot::Time newest;
};
void buildClusters();
int pickCluster(const robot::Time& now) const;
void describeClusters();
void filter(int cluster_id, PoseSample& out, double& spread_xy, double& spread_yaw);
std::string describeSamples(const PoseSample& centre) const;
void logThrottled(const robot::Time& now, const char* text);
PoseSampleFilterConfig config_;
std::string owner_;
std::string source_label_;
std::string frame_label_;
/// Cửa sổ trượt, mẫu cũ nhất ở đầu.
std::vector<PoseSample> samples_;
std::size_t total_samples_ = 0;
bool converged_ = false;
robot::Time converged_since_;
PoseSample hold_pose_;
/// Cửa sổ tốt nhất từng thấy, CHỈ để chẩn đoán lúc timeout — không bao giờ được publish.
bool best_valid_ = false;
double best_score_ = 0.0;
double best_spread_xy_ = 0.0; // [m]
double best_spread_yaw_ = 0.0; // [rad]
std::string best_description_;
robot::Time last_progress_log_;
bool have_progress_log_ = false;
/// Buffer dùng lại cho filter(): hàm đó chạy gần như mỗi control cycle. clear() giữ capacity nên
/// sau vài tick đầu là hết cấp phát.
std::vector<double> buf_x_;
std::vector<double> buf_y_;
std::vector<double> buf_dev_xy_;
std::vector<double> buf_dev_yaw_;
std::vector<Cluster> clusters_;
/// cluster_of_[i] = chỉ số cụm của samples_[i].
std::vector<int> cluster_of_;
/// Tóm tắt bố cục cụm của lần đánh giá gần nhất.
char cluster_summary_[176] = { 0 };
};
} // namespace action_core
#endif // ACTION_CORE_POSE_SAMPLE_FILTER_H_

View File

@@ -20,6 +20,8 @@
#include <robot/robot.h>
#include <tf3/buffer_core.h>
#include <action_core/pose_sample_filter.h>
namespace action_core
{
namespace
@@ -37,51 +39,10 @@ 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
/// chính vòng điều khiển. 1 Hz đủ để đọc xem tập mẫu đang co lại hay không.
constexpr double kProgressLogPeriod = 1.0; // [s]
double yawOf(const tf3::QuaternionMsg& q)
{
return std::atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z));
}
/// @brief Trung vị theo từng trục. Bền hơn trung bình trước outlier — LiDAR thỉnh thoảng bắt nhầm.
/// @note Nhận tham chiếu và SẮP XẾP LẠI @p v tại chỗ. Gọi trên buffer dùng lại được, không phải bản
/// sao — hàm này chạy mỗi khi cửa sổ trượt đổi, tức gần như mỗi control cycle.
double median(std::vector<double>& v)
{
const std::size_t mid = v.size() / 2;
std::nth_element(v.begin(), v.begin() + mid, v.end());
const double hi = v[mid];
if (v.size() % 2 != 0)
{
return hi;
}
std::nth_element(v.begin(), v.begin() + mid - 1, v.end());
return 0.5 * (hi + v[mid - 1]);
}
/**
* @brief Độ tản BỀN: 2 x phân vị 90 của độ lệch so với tâm.
*
* Không dùng `max - min`: một mẫu nhận nhầm duy nhất trong ba mươi mẫu sẽ thổi nó lên hàng mét và
* đánh hỏng cả lượt dò — mà đó đúng là tình huống trung vị sinh ra để chịu được. Cắt ở phân vị 90
* cho phép tối đa 10% mẫu rác, đồng thời vẫn bắt được dữ liệu tản thật (khi ấy MỌI mẫu đều lệch,
* không chỉ vài mẫu).
*/
/// @note Như @ref median: nhận tham chiếu và sắp xếp lại tại chỗ, tránh cấp phát mỗi cycle.
double robustSpread(std::vector<double>& deviations)
{
if (deviations.empty())
{
return 0.0;
}
const std::size_t idx =
std::min(deviations.size() - 1, static_cast<std::size_t>(deviations.size() * 0.9));
std::nth_element(deviations.begin(), deviations.begin() + idx, deviations.end());
return 2.0 * deviations[idx];
}
} // namespace
/**
@@ -172,6 +133,12 @@ double robustSpread(std::vector<double>& deviations)
* `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.
*
* ## Bộ lọc nằm ở đâu
*
* Toàn bộ phần cửa sổ trượt, lọc cụm, độ tản và giữ trạng thái nằm trong @ref PoseSampleFilter.
* Handler này chỉ là **nguồn mẫu**: nó tra TF, đẩy mẫu vào bộ lọc, rồi ghi kết quả ra TF. Bộ dò
* hình học từ LiDAR dùng đúng bộ lọc đó với đúng tập khoá YAML đó — người vận hành học một lần.
*
* ## Đọ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à
@@ -229,23 +196,26 @@ public:
nh.param("output_frame", output_frame_, std::string());
nh.param("input_frame", input_frame_, std::string());
nh.param("settle_delay", settle_delay_, kDefaultSettleDelay);
nh.param("sample_window", sample_window_, kDefaultSampleWindow);
nh.param("min_samples", min_samples_, kDefaultMinSamples);
nh.param("max_spread_xy", max_spread_xy_, kDefaultMaxSpreadXy);
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);
nh.param("simulated_offset_y", simulated_offset_y_, 0.0);
nh.param("simulated_offset_yaw", simulated_offset_yaw_, 0.0);
PoseSampleFilterConfig filter_config;
nh.param("filter_enabled", filter_config.enabled, true);
nh.param("sample_window", filter_config.sample_window, kDefaultSampleWindow);
nh.param("min_samples", filter_config.min_samples, kDefaultMinSamples);
nh.param("max_spread_xy", filter_config.max_spread_xy, kDefaultMaxSpreadXy);
nh.param("max_spread_yaw", filter_config.max_spread_yaw, kDefaultMaxSpreadYaw);
nh.param("hold_time", filter_config.hold_time, kDefaultHoldTime);
nh.param("jump_threshold", filter_config.jump_threshold, kDefaultJumpThreshold);
nh.param("cluster_recency", filter_config.cluster_recency, kDefaultClusterRecency);
nh.param("min_cluster_fraction", filter_config.min_cluster_fraction,
kDefaultMinClusterFraction);
nh.param("min_cluster_samples", filter_config.min_cluster_samples, kDefaultMinClusterSamples);
if (action_types_.empty())
{
robot::log_error("[action_core] '%s': action_types is empty — never called.", name_.c_str());
@@ -265,41 +235,32 @@ public:
return false;
}
if (!std::isfinite(settle_delay_) || settle_delay_ < 0.0 ||
!std::isfinite(sample_window_) || sample_window_ <= 0.0)
!std::isfinite(filter_config.sample_window) || filter_config.sample_window <= 0.0)
{
robot::log_error("[action_core] '%s': settle_delay=%.3f / sample_window=%.3f invalid.",
name_.c_str(), settle_delay_, sample_window_);
name_.c_str(), settle_delay_, filter_config.sample_window);
return false;
}
if (min_samples_ < 1)
// Miền của nhóm khoá lọc thuộc về chính bộ lọc — cùng một luật cho mọi nguồn mẫu, không phải
// chép sang từng handler rồi để chúng trôi lệch nhau.
if (!filter_.configure(filter_config, name_))
{
robot::log_error("[action_core] '%s': min_samples=%d must be >= 1.", name_.c_str(),
min_samples_);
return false;
}
if (!std::isfinite(max_spread_xy_) || max_spread_xy_ <= 0.0 ||
!std::isfinite(max_spread_yaw_) || max_spread_yaw_ <= 0.0)
{
robot::log_error("[action_core] '%s': max_spread_xy/yaw must be > 0.", name_.c_str());
return false;
}
if (!std::isfinite(hold_time_) || hold_time_ < 0.0)
{
robot::log_error("[action_core] '%s': hold_time=%.3f must be finite and >= 0.", name_.c_str(),
hold_time_);
return false;
}
if (filter_enabled_ && timeout_ > 0.0 &&
timeout_ <= settle_delay_ + sample_window_ + hold_time_)
if (filter_config.enabled && timeout_ > 0.0 &&
timeout_ <= settle_delay_ + filter_config.sample_window + filter_config.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.
robot::log_error("[action_core] '%s': timeout=%.3f s <= "
"settle_delay+sample_window+hold_time=%.3f s; the action would always fail.",
name_.c_str(), timeout_, settle_delay_ + sample_window_ + hold_time_);
name_.c_str(), timeout_,
settle_delay_ + filter_config.sample_window + filter_config.hold_time);
return false;
}
if (!filter_enabled_ && timeout_ > 0.0 && timeout_ <= settle_delay_)
if (!filter_config.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 "
@@ -307,47 +268,6 @@ public:
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_)
@@ -400,9 +320,10 @@ public:
{
return false;
}
filter_.setLabels(frame_, ctx_.global_frame);
robot::log_info("[action_core] '%s': sampling '%s' for %.2f s (settle %.2f s) -> '%s'.",
name_.c_str(), frame_.c_str(), sample_window_, settle_delay_,
name_.c_str(), frame_.c_str(), filter_.config().sample_window, settle_delay_,
output_frame_.c_str());
return true;
}
@@ -423,18 +344,18 @@ public:
if (elapsed >= settle_delay_)
{
const bool grew = collectSample(now);
const bool shrank = pruneExpired(now);
const bool shrank = filter_.pruneExpired(now);
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 (!filter_.config().enabled)
{
if (total_samples_ >= 2)
if (filter_.totalSamples() >= 2)
{
if (!publish(samples_.back(), now))
if (!publish(filter_.newest(), now))
{
tick.status = ActionStatus::kFailed;
tick.message = "action '" + action_id_ + "': could not publish '" + output_frame_ + "'";
@@ -456,16 +377,16 @@ public:
// 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_)
if (elapsed >= settle_delay_ + filter_.config().sample_window && window_changed_)
{
window_changed_ = false;
evaluateWindow(now);
filter_.evaluate(now);
}
// Thành công được xét TRƯỚC timeout: một cửa sổ đạt đúng vào tick cuối vẫn là dò thành công.
if (converged_ && (now - converged_since_).toSec() >= hold_time_)
if (filter_.holdSatisfied(now))
{
if (!publish(hold_pose_, now))
if (!publish(filter_.holdPose(), now))
{
tick.status = ActionStatus::kFailed;
tick.message = "action '" + action_id_ + "': could not publish '" + output_frame_ + "'";
@@ -474,7 +395,7 @@ public:
tick.status = ActionStatus::kSucceeded;
tick.message = "action '" + action_id_ + "': '" + output_frame_ + "' from " +
std::to_string(samples_.size()) + " sample(s) after " +
std::to_string(filter_.windowSize()) + " sample(s) after " +
formatSeconds(elapsed) + " s";
return tick;
}
@@ -498,27 +419,6 @@ public:
}
private:
struct Sample
{
double x = 0.0;
double y = 0.0;
double yaw = 0.0; // [rad]
/// Thời điểm TICK thu được mẫu, không phải stamp của TF. Cửa sổ trượt cắt theo trục thời gian
/// của chính handler, cùng trục với `timeout` — stamp TF có thể lệch trục nếu nguồn publish
/// dùng đồng hồ khác.
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(),
@@ -542,20 +442,9 @@ private:
/// hưởng mẫu, cửa sổ tốt nhất hay đồng hồ giữ trạng thái của lượt trước.
void resetRun()
{
samples_.clear();
total_samples_ = 0;
filter_.reset();
have_last_stamp_ = false;
window_changed_ = false;
converged_ = false;
best_valid_ = false;
best_score_ = 0.0;
best_spread_xy_ = 0.0;
best_spread_yaw_ = 0.0;
best_description_.clear();
have_progress_log_ = false;
clusters_.clear();
cluster_of_.clear();
cluster_summary_[0] = '\0';
}
/**
@@ -583,250 +472,12 @@ private:
last_stamp_ = tf.header.stamp;
have_last_stamp_ = true;
Sample s;
PoseSample s;
s.x = tf.transform.translation.x;
s.y = tf.transform.translation.y;
s.yaw = yawOf(tf.transform.rotation);
s.taken_at = now;
samples_.push_back(s);
++total_samples_;
return true;
}
/**
* @brief Bỏ mẫu già hơn `sample_window` khỏi đầu cửa sổ.
* @return true nếu có mẫu bị bỏ.
*
* Đây là phần khiến cửa sổ TRƯỢT thay vì tích luỹ. Không có nó thì mẫu xấu của giây đầu ở lại mãi
* và độ tản không bao giờ giảm được — perception ổn định về sau vẫn bị báo hỏng.
*/
bool pruneExpired(const robot::Time& now)
{
// Mẫu được push theo thứ tự thời gian nên chỉ cần cắt từ đầu; số phần tử bỏ mỗi tick là 0 hoặc
// rất nhỏ, không phải quét lại toàn cửa sổ.
std::size_t expired = 0;
while (expired < samples_.size() &&
(now - samples_[expired].taken_at).toSec() > sample_window_)
{
++expired;
}
if (expired == 0)
{
return false;
}
samples_.erase(samples_.begin(), samples_.begin() + expired);
return true;
}
/**
* @brief Chấm điểm cửa sổ hiện tại: cập nhật đồng hồ giữ trạng thái, cửa sổ tốt nhất, log tiến độ.
*
* Chỉ chạy khi cửa sổ ĐỔI (thêm mẫu mới hoặc bỏ mẫu quá hạn). Cửa sổ không đổi thì độ tản cũng
* không đổi — lọc lại mỗi control cycle chỉ tốn CPU và cấp phát vô ích.
*/
void evaluateWindow(const robot::Time& now)
{
if (static_cast<int>(samples_.size()) < min_samples_)
{
// Chưa đủ mẫu để nói được gì về độ tản. Đang đạt mà mất mẫu thì cũng coi như tuột — không
// được chốt dựa trên một cửa sổ vừa mỏng đi.
converged_ = false;
logProgress(now, "%zu sample(s) in the %.2f s window, need %d — waiting", samples_.size(),
sample_window_, min_samples_);
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;
// 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]).
const double score = std::max(spread_xy / max_spread_xy_, spread_yaw / max_spread_yaw_);
if (!best_valid_ || score < best_score_)
{
best_valid_ = true;
best_score_ = score;
best_spread_xy_ = spread_xy;
best_spread_yaw_ = spread_yaw;
// Chụp lại hình dạng cửa sổ NGAY LÚC NÀY: tới lúc timeout thì `samples_` đã là cửa sổ khác,
// mô tả khi ấy sẽ không còn ứng với các con số tốt nhất. Chỉ chạy khi có cải thiện.
best_description_ = describeSamples(centre);
}
const bool within = spread_xy <= max_spread_xy_ && spread_yaw <= max_spread_yaw_;
if (within && !(clustering && chosen < 0))
{
if (!converged_)
{
converged_ = true;
converged_since_ = now;
}
// Luôn chốt theo tâm MỚI NHẤT: mẫu càng gần thời điểm chốt càng ứng với hiện trạng.
//
// TODO(DuongTD): tâm có thể trôi chậm trong lúc giữ trạng thái (mỗi cửa sổ đều chụm nhưng cả
// chuỗi cửa sổ đang bò đi) — cổng hiện tại không bắt được vì nó chỉ đo độ tản TRONG một cửa
// sổ. Rủi ro: dock_target lệch dần theo drift của AMCL. Hướng xử lý: so `hold_pose_` lúc bắt
// đầu giữ với lúc chốt, vượt `max_drift_xy` thì reset đồng hồ. Cần đo drift thật ở hiện
// trường trước khi đặt ngưỡng.
hold_pose_ = centre;
}
else
{
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%s",
samples_.size(), centre.x, centre.y, centre.yaw, spread_xy, max_spread_xy_,
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<int>(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<int>(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<double>(samples_.size());
for (std::size_t i = 0; i < clusters_.size(); ++i)
{
const Cluster& c = clusters_[i];
if (static_cast<double>(c.count) < need ||
c.count < static_cast<std::size_t>(min_cluster_samples_) ||
(now - c.newest).toSec() > cluster_recency_)
{
continue;
}
return static_cast<int>(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<std::size_t>(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<std::size_t>(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.
template <typename... Args>
void logProgress(const robot::Time& now, const char* format, Args... args)
{
if (have_progress_log_ && (now - last_progress_log_).toSec() < kProgressLogPeriod)
{
return;
}
last_progress_log_ = now;
have_progress_log_ = true;
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);
return filter_.addSample(s);
}
/// @brief Hết `timeout` mà chưa cửa sổ nào đạt. Ba nguyên nhân, ba thông điệp khác nhau.
@@ -835,14 +486,14 @@ private:
ActionTick tick;
tick.status = ActionStatus::kFailed;
if (total_samples_ == 0)
if (filter_.totalSamples() == 0)
{
// Không thấy gì cả: perception chưa chạy, sai tên frame, hoặc vật thể ngoài tầm.
tick.message = "action '" + action_id_ + "': frame '" + frame_ + "' did not appear in time";
return tick;
}
if (!filter_enabled_)
if (!filter_.config().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.
@@ -851,14 +502,15 @@ private:
return tick;
}
if (!best_valid_)
if (!filter_.hasBest())
{
// Thấy, nhưng chưa cửa sổ nào đủ `min_samples`: nguồn publish quá thưa so với `sample_window`.
// Đây là lỗi CẤU HÌNH/tần số, không phải lỗi chất lượng dò — nới `max_spread_*` vô ích.
tick.message = "action '" + action_id_ + "': '" + frame_ + "' published too sparsely — " +
std::to_string(total_samples_) + " sample(s) in " + formatSeconds(elapsed) +
" s, need " + std::to_string(min_samples_) + " within any " +
formatSeconds(sample_window_) + " s window";
std::to_string(filter_.totalSamples()) + " sample(s) in " +
formatSeconds(elapsed) + " s, need " +
std::to_string(filter_.config().min_samples) + " within any " +
formatSeconds(filter_.config().sample_window) + " s window";
return tick;
}
@@ -872,13 +524,15 @@ private:
// Hộp bao cho biết các mẫu văng đi ĐÂU. Chạy đúng một lần mỗi lượt dò hỏng.
robot::log_error("[action_core] '%s': no window converged in %.2f s. Best window (%.0f%% of the "
"tolerance): %s\n",
name_.c_str(), elapsed, best_score_ * 100.0, best_description_.c_str());
name_.c_str(), elapsed, filter_.bestScore() * 100.0,
filter_.bestDescription().c_str());
tick.message = "action '" + action_id_ + "': detection unstable (best spread xy=" +
std::to_string(best_spread_xy_) + " m, yaw=" + std::to_string(best_spread_yaw_) +
" rad in " + formatSeconds(elapsed) + " s; limits " +
std::to_string(max_spread_xy_) + " m / " + std::to_string(max_spread_yaw_) +
" rad)";
std::to_string(filter_.bestSpreadXy()) +
" m, yaw=" + std::to_string(filter_.bestSpreadYaw()) + " rad in " +
formatSeconds(elapsed) + " s; limits " +
std::to_string(filter_.config().max_spread_xy) + " m / " +
std::to_string(filter_.config().max_spread_yaw) + " rad)";
return tick;
}
@@ -889,114 +543,7 @@ private:
return buffer;
}
/**
* @brief Mô tả hình dạng tập mẫu để chẩn đoán một lượt dò hỏng.
*
* Ba phân vị của độ lệch cộng hộp bao trong frame cố định. Đọc theo cặp:
* - `p50` nhỏ mà `p90` lớn: đa số mẫu chụm, một nhúm văng ra — mẫu nhận nhầm ở nguồn.
* - `p50` xấp xỉ `p90`: mọi mẫu đều lệch — phép dò thật sự không ổn định.
* Hộp bao chỉ ra các mẫu văng nằm ở đâu, thứ mà không con số tổng hợp nào nói được.
*/
std::string describeSamples(const Sample& centre) const
{
if (samples_.empty())
{
return "no sample to describe";
}
std::vector<double> dev;
dev.reserve(samples_.size());
double min_x = samples_.front().x;
double max_x = min_x;
double min_y = samples_.front().y;
double max_y = min_y;
for (const Sample& s : samples_)
{
dev.push_back(std::hypot(s.x - centre.x, s.y - centre.y));
min_x = std::min(min_x, s.x);
max_x = std::max(max_x, s.x);
min_y = std::min(min_y, s.y);
max_y = std::max(max_y, s.y);
}
std::sort(dev.begin(), dev.end());
const auto at = [&dev](double q) {
const std::size_t i =
std::min(dev.size() - 1, static_cast<std::size_t>(dev.size() * q));
return dev[i];
};
char buffer[320];
std::snprintf(buffer, sizeof(buffer),
"%zu sample(s) of '%s' in '%s': median=(%.3f, %.3f) yaw=%.4f rad, "
"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);
// 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`.
/// @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();
buf_x_.reserve(samples_.size());
buf_y_.reserve(samples_.size());
double sum_sin = 0.0;
double sum_cos = 0.0;
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);
sum_cos += std::cos(s.yaw);
}
out.x = median(buf_x_);
out.y = median(buf_y_);
// Gộp góc bằng vector đơn vị. Trung bình số học của các mẫu quanh ±π cho ra ~0 — lệch 180°.
out.yaw = std::atan2(sum_sin, sum_cos);
// Độ tản đo quanh TÂM ĐÃ LỌC, không phải min-max thô: xem robustSpread.
buf_dev_xy_.clear();
buf_dev_yaw_.clear();
buf_dev_xy_.reserve(samples_.size());
buf_dev_yaw_.reserve(samples_.size());
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(
std::fabs(std::atan2(std::sin(s.yaw - out.yaw), std::cos(s.yaw - out.yaw))));
}
spread_xy = robustSpread(buf_dev_xy_);
spread_yaw = robustSpread(buf_dev_yaw_);
}
bool publish(const Sample& s, const robot::Time& now)
bool publish(const PoseSample& s, const robot::Time& now)
{
tf3::TransformStampedMsg out;
out.header.stamp = tf3::Time(now.sec, now.nsec);
@@ -1030,7 +577,7 @@ private:
}
const double parent_yaw = yawOf(parent.transform.rotation);
Sample simulated;
PoseSample simulated;
simulated.x = parent.transform.translation.x +
std::cos(parent_yaw) * simulated_offset_x_ -
std::sin(parent_yaw) * simulated_offset_y_;
@@ -1048,65 +595,27 @@ private:
std::string output_frame_;
std::string input_frame_;
double settle_delay_ = kDefaultSettleDelay;
double sample_window_ = kDefaultSampleWindow;
int min_samples_ = kDefaultMinSamples;
double max_spread_xy_ = kDefaultMaxSpreadXy;
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]
double simulated_offset_y_ = 0.0; // [m]
double simulated_offset_yaw_ = 0.0; // [rad]
/// Cửa sổ trượt, lọc cụm, độ tản, giữ trạng thái và chẩn đoán — dùng chung với mọi nguồn mẫu.
PoseSampleFilter filter_;
robot::Time started_at_;
std::string action_id_;
std::string frame_;
bool simulated_goal_published_ = false;
/// Cửa sổ trượt, mẫu cũ nhất ở đầu. Chỉ chứa mẫu trong `sample_window` giây gần nhất.
std::vector<Sample> samples_;
/// Tổng mẫu thu được cả lượt. Phân biệt "không thấy gì" với "thấy nhưng publish quá thưa" lúc
/// timeout — `samples_.size()` không nói được vì mẫu cũ đã bị cắt khỏi cửa sổ.
std::size_t total_samples_ = 0;
/// Stamp của TF đã lấy mẫu gần nhất; chống đếm hai lần cùng một pose. Thuộc về NGUỒN mẫu, không
/// phải bộ lọc — nguồn khác (một scan LiDAR) dedupe theo thứ khác.
tf3::Time last_stamp_;
bool have_last_stamp_ = false;
/// Cửa sổ đã đổi kể từ lần chấm điểm gần nhất. Không đổi thì độ tản cũng không đổi.
bool window_changed_ = false;
/// Trạng thái giữ: cửa sổ đang đạt ngưỡng liên tục từ `converged_since_`.
bool converged_ = false;
robot::Time converged_since_;
Sample hold_pose_;
/// Cửa sổ tốt nhất từng thấy, chỉ để chẩn đoán lúc timeout — không bao giờ được publish.
bool best_valid_ = false;
double best_score_ = 0.0; // tỉ lệ so với ngưỡng; < 1.0 nghĩa là đã đạt
double best_spread_xy_ = 0.0; // [m]
double best_spread_yaw_ = 0.0; // [rad]
std::string best_description_;
robot::Time last_progress_log_;
bool have_progress_log_ = false;
/// Buffer dùng lại cho `filter()`: hàm đó chạy gần như mỗi control cycle.
std::vector<double> buf_x_;
std::vector<double> buf_y_;
std::vector<double> buf_dev_xy_;
std::vector<double> 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<Cluster> 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<int> 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

531
src/pose_sample_filter.cpp Normal file
View File

@@ -0,0 +1,531 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* action_core — cài đặt PoseSampleFilter.
*
* Author: DuongTD
*********************************************************************/
#include <action_core/pose_sample_filter.h>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <robot/robot.h>
namespace action_core
{
namespace
{
/// 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
/// chính vòng điều khiển. 1 Hz đủ để đọc xem tập mẫu đang co lại hay không.
constexpr double kProgressLogPeriod = 1.0; // [s]
/// @brief Trung vị. Bền hơn trung bình trước outlier — LiDAR thỉnh thoảng bắt nhầm.
/// @note Nhận tham chiếu và SẮP XẾP LẠI @p v tại chỗ. Gọi trên buffer dùng lại được, không phải bản
/// sao — hàm này chạy mỗi khi cửa sổ trượt đổi, tức gần như mỗi control cycle.
double median(std::vector<double>& v)
{
const std::size_t mid = v.size() / 2;
std::nth_element(v.begin(), v.begin() + mid, v.end());
const double hi = v[mid];
if (v.size() % 2 != 0)
{
return hi;
}
std::nth_element(v.begin(), v.begin() + mid - 1, v.end());
return 0.5 * (hi + v[mid - 1]);
}
/**
* @brief Độ tản BỀN: 2 x phân vị 90 của độ lệch so với tâm.
*
* Không dùng `max - min`: một mẫu nhận nhầm duy nhất trong ba mươi mẫu sẽ thổi nó lên hàng mét và
* đánh hỏng cả lượt dò — mà đó đúng là tình huống trung vị sinh ra để chịu được. Cắt ở phân vị 90
* cho phép tối đa 10% mẫu rác, đồng thời vẫn bắt được dữ liệu tản thật (khi ấy MỌI mẫu đều lệch,
* không chỉ vài mẫu).
*
* @note Như @ref median: nhận tham chiếu và sắp xếp lại tại chỗ, tránh cấp phát mỗi cycle.
*/
double robustSpread(std::vector<double>& deviations)
{
if (deviations.empty())
{
return 0.0;
}
const std::size_t idx =
std::min(deviations.size() - 1, static_cast<std::size_t>(deviations.size() * 0.9));
std::nth_element(deviations.begin(), deviations.begin() + idx, deviations.end());
return 2.0 * deviations[idx];
}
} // namespace
// ================================================================================================
// Config
// ================================================================================================
bool PoseSampleFilterConfig::validate(const std::string& owner) const
{
if (!std::isfinite(sample_window) || sample_window <= 0.0)
{
robot::log_error("[action_core] '%s': sample_window=%.3f invalid.", owner.c_str(),
sample_window);
return false;
}
if (min_samples < 1)
{
robot::log_error("[action_core] '%s': min_samples=%d must be >= 1.", owner.c_str(), min_samples);
return false;
}
if (!std::isfinite(max_spread_xy) || max_spread_xy <= 0.0 || !std::isfinite(max_spread_yaw) ||
max_spread_yaw <= 0.0)
{
robot::log_error("[action_core] '%s': max_spread_xy/yaw must be > 0.", owner.c_str());
return false;
}
if (!std::isfinite(hold_time) || hold_time < 0.0)
{
robot::log_error("[action_core] '%s': hold_time=%.3f must be finite and >= 0.", owner.c_str(),
hold_time);
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.",
owner.c_str(), jump_threshold);
return false;
}
// Nhóm cụm chỉ có hiệu lực khi tầng lọc bật VÀ lọc cụm bật. Kiểm ngoài phạm vi đó là từ chối một
// cấu hình chưa bao giờ được dùng tới.
if (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.",
owner.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.", owner.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].",
owner.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].",
owner.c_str(), min_cluster_samples, min_samples);
return false;
}
}
return true;
}
// ================================================================================================
// Vòng đời
// ================================================================================================
bool PoseSampleFilter::configure(const PoseSampleFilterConfig& config, const std::string& owner)
{
if (!config.validate(owner))
{
return false; // Giữ bộ cũ; một cấu hình áp nửa vời còn tệ hơn không áp.
}
config_ = config;
owner_ = owner;
return true;
}
void PoseSampleFilter::setLabels(const std::string& source, const std::string& frame)
{
source_label_ = source;
frame_label_ = frame;
}
void PoseSampleFilter::reset()
{
samples_.clear();
total_samples_ = 0;
converged_ = false;
best_valid_ = false;
best_score_ = 0.0;
best_spread_xy_ = 0.0;
best_spread_yaw_ = 0.0;
best_description_.clear();
have_progress_log_ = false;
clusters_.clear();
cluster_of_.clear();
cluster_summary_[0] = '\0';
}
bool PoseSampleFilter::addSample(const PoseSample& sample)
{
samples_.push_back(sample);
++total_samples_;
return true;
}
/**
* Đây là phần khiến cửa sổ TRƯỢT thay vì tích luỹ. Không có nó thì mẫu xấu của giây đầu ở lại mãi
* và độ tản không bao giờ giảm được — perception ổn định về sau vẫn bị báo hỏng.
*/
bool PoseSampleFilter::pruneExpired(const robot::Time& now)
{
// Mẫu được push theo thứ tự thời gian nên chỉ cần cắt từ đầu; số phần tử bỏ mỗi tick là 0 hoặc
// rất nhỏ, không phải quét lại toàn cửa sổ.
std::size_t expired = 0;
while (expired < samples_.size() &&
(now - samples_[expired].taken_at).toSec() > config_.sample_window)
{
++expired;
}
if (expired == 0)
{
return false;
}
samples_.erase(samples_.begin(), samples_.begin() + static_cast<std::ptrdiff_t>(expired));
return true;
}
bool PoseSampleFilter::holdSatisfied(const robot::Time& now) const
{
return converged_ && (now - converged_since_).toSec() >= config_.hold_time;
}
// ================================================================================================
// Chấm điểm
// ================================================================================================
void PoseSampleFilter::evaluate(const robot::Time& now)
{
if (static_cast<int>(samples_.size()) < config_.min_samples)
{
// Chưa đủ mẫu để nói được gì về độ tản. Đang đạt mà mất mẫu thì cũng coi như tuột — không được
// chốt dựa trên một cửa sổ vừa mỏng đi.
converged_ = false;
char buffer[512];
std::snprintf(buffer, sizeof(buffer),
"%zu sample(s) in the %.2f s window, need %d — waiting", samples_.size(),
config_.sample_window, config_.min_samples);
logThrottled(now, buffer);
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 = config_.jump_threshold > 0.0;
int chosen = -1;
if (clustering)
{
buildClusters();
chosen = pickCluster(now);
describeClusters();
}
else
{
cluster_summary_[0] = '\0';
}
PoseSample centre;
double spread_xy = 0.0;
double spread_yaw = 0.0;
// 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]).
const double score =
std::max(spread_xy / config_.max_spread_xy, spread_yaw / config_.max_spread_yaw);
if (!best_valid_ || score < best_score_)
{
best_valid_ = true;
best_score_ = score;
best_spread_xy_ = spread_xy;
best_spread_yaw_ = spread_yaw;
// Chụp lại hình dạng cửa sổ NGAY LÚC NÀY: tới lúc timeout thì `samples_` đã là cửa sổ khác, mô
// tả khi ấy sẽ không còn ứng với các con số tốt nhất. Chỉ chạy khi có cải thiện.
best_description_ = describeSamples(centre);
}
const bool within = spread_xy <= config_.max_spread_xy && spread_yaw <= config_.max_spread_yaw;
if (within && !(clustering && chosen < 0))
{
if (!converged_)
{
converged_ = true;
converged_since_ = now;
}
// Luôn chốt theo tâm MỚI NHẤT: mẫu càng gần thời điểm chốt càng ứng với hiện trạng.
//
// TODO(DuongTD): tâm có thể trôi chậm trong lúc giữ trạng thái (mỗi cửa sổ đều chụm nhưng cả
// chuỗi cửa sổ đang bò đi) — cổng hiện tại không bắt được vì nó chỉ đo độ tản TRONG một cửa sổ.
// Rủi ro: dock_target lệch dần theo drift của AMCL. Hướng xử lý: so `hold_pose_` lúc bắt đầu
// giữ với lúc chốt, vượt `max_drift_xy` thì reset đồng hồ. Cần đo drift thật ở hiện trường
// trước khi đặt ngưỡng.
hold_pose_ = centre;
}
else
{
converged_ = false;
}
const char* note = converged_ ? " — within tolerance, holding"
: (clustering && chosen < 0 && clusters_.size() > 1)
? " — no majority cluster, waiting"
: "";
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),
"%zu sample(s): centre=(%.3f, %.3f) yaw=%.4f rad, spread xy=%.4f/%.3f m "
"yaw=%.4f/%.3f rad%s%s",
samples_.size(), centre.x, centre.y, centre.yaw, spread_xy, config_.max_spread_xy,
spread_yaw, config_.max_spread_yaw, cluster_summary_, note);
logThrottled(now, buffer);
}
// ================================================================================================
// 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 PoseSampleFilter::buildClusters()
{
clusters_.clear();
cluster_of_.clear();
for (const PoseSample& s : samples_)
{
int best = -1;
double best_d = config_.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<int>(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<int>(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);
}
}
/**
* `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.
*/
int PoseSampleFilter::pickCluster(const robot::Time& now) const
{
const double need = config_.min_cluster_fraction * static_cast<double>(samples_.size());
for (std::size_t i = 0; i < clusters_.size(); ++i)
{
const Cluster& c = clusters_[i];
if (static_cast<double>(c.count) < need ||
c.count < static_cast<std::size_t>(config_.min_cluster_samples) ||
(now - c.newest).toSec() > config_.cluster_recency)
{
continue;
}
return static_cast<int>(i);
}
return -1;
}
/// Tóm tắt bố cục cụm — "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 PoseSampleFilter::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<std::size_t>(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<std::size_t>(off) < sizeof(cluster_summary_))
{
std::snprintf(cluster_summary_ + off, sizeof(cluster_summary_) - off, " (+%zu)",
clusters_.size() - kMaxListed);
}
}
// ================================================================================================
// Lọc và chẩn đoán
// ================================================================================================
/// @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 PoseSampleFilter::filter(int cluster_id, PoseSample& out, double& spread_xy,
double& spread_yaw)
{
buf_x_.clear();
buf_y_.clear();
buf_x_.reserve(samples_.size());
buf_y_.reserve(samples_.size());
double sum_sin = 0.0;
double sum_cos = 0.0;
for (std::size_t i = 0; i < samples_.size(); ++i)
{
if (cluster_id >= 0 && cluster_of_[i] != cluster_id)
{
continue;
}
const PoseSample& s = samples_[i];
buf_x_.push_back(s.x);
buf_y_.push_back(s.y);
sum_sin += std::sin(s.yaw);
sum_cos += std::cos(s.yaw);
}
out.x = median(buf_x_);
out.y = median(buf_y_);
// Gộp góc bằng vector đơn vị. Trung bình số học của các mẫu quanh ±π cho ra ~0 — lệch 180°.
out.yaw = std::atan2(sum_sin, sum_cos);
// Độ tản đo quanh TÂM ĐÃ LỌC, không phải min-max thô: xem robustSpread.
buf_dev_xy_.clear();
buf_dev_yaw_.clear();
buf_dev_xy_.reserve(samples_.size());
buf_dev_yaw_.reserve(samples_.size());
for (std::size_t i = 0; i < samples_.size(); ++i)
{
if (cluster_id >= 0 && cluster_of_[i] != cluster_id)
{
continue;
}
const PoseSample& 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(
std::fabs(std::atan2(std::sin(s.yaw - out.yaw), std::cos(s.yaw - out.yaw))));
}
spread_xy = robustSpread(buf_dev_xy_);
spread_yaw = robustSpread(buf_dev_yaw_);
}
/**
* Ba phân vị của độ lệch cộng hộp bao trong frame cố định. Đọc theo cặp:
* - `p50` nhỏ mà `p90` lớn: đa số mẫu chụm, một nhúm văng ra — mẫu nhận nhầm ở nguồn.
* - `p50` xấp xỉ `p90`: mọi mẫu đều lệch — phép dò thật sự không ổn định.
* Hộp bao chỉ ra các mẫu văng nằm ở đâu, thứ mà không con số tổng hợp nào nói được.
*/
std::string PoseSampleFilter::describeSamples(const PoseSample& centre) const
{
if (samples_.empty())
{
return "no sample to describe";
}
std::vector<double> dev;
dev.reserve(samples_.size());
double min_x = samples_.front().x;
double max_x = min_x;
double min_y = samples_.front().y;
double max_y = min_y;
for (const PoseSample& s : samples_)
{
dev.push_back(std::hypot(s.x - centre.x, s.y - centre.y));
min_x = std::min(min_x, s.x);
max_x = std::max(max_x, s.x);
min_y = std::min(min_y, s.y);
max_y = std::max(max_y, s.y);
}
std::sort(dev.begin(), dev.end());
const auto at = [&dev](double q) {
const std::size_t i = std::min(dev.size() - 1, static_cast<std::size_t>(dev.size() * q));
return dev[i];
};
char buffer[320];
std::snprintf(buffer, sizeof(buffer),
"%zu sample(s) of '%s' in '%s': median=(%.3f, %.3f) yaw=%.4f rad, "
"deviation p50=%.3f p90=%.3f max=%.3f m, bbox x=[%.3f, %.3f] y=[%.3f, %.3f]",
samples_.size(), source_label_.c_str(), frame_label_.c_str(), centre.x, centre.y,
centre.yaw, at(0.5), at(0.9), dev.back(), min_x, max_x, min_y, max_y);
// 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_;
}
void PoseSampleFilter::logThrottled(const robot::Time& now, const char* text)
{
if (have_progress_log_ && (now - last_progress_log_).toSec() < kProgressLogPeriod)
{
return;
}
last_progress_log_ = now;
have_progress_log_ = true;
robot::log_info("[action_core] '%s': %s", owner_.c_str(), text);
}
} // namespace action_core