diff --git a/apps/lidar_odometry_step_1/lidar_odometry.cpp b/apps/lidar_odometry_step_1/lidar_odometry.cpp index 50a17b63..6c88130a 100644 --- a/apps/lidar_odometry_step_1/lidar_odometry.cpp +++ b/apps/lidar_odometry_step_1/lidar_odometry.cpp @@ -6,6 +6,7 @@ #include "tbb/tbb.h" #include +#include #include #include #include @@ -45,6 +46,27 @@ static bool step_1_failed(const LidarOdometryParams& params, const std::string& return false; } +//! Runs the IMU rest detection over the whole trajectory: the [start, end] LiDAR-clock times [s] at rest. +static std::vector> detect_stationary_segments(const Trajectory& trajectory, const LidarOdometryParams& params) +{ + if (trajectory.size() < 2) + return {}; + const double t0 = trajectory.begin()->first; + const double t1 = trajectory.rbegin()->first; + const double avg_dt = t1 > t0 ? (t1 - t0) / static_cast(trajectory.size() - 1) : 1.0 / 200.0; + + ImuRestDetector::Params rest_params; + rest_params.rest_min_t = params.stationary_rest_min_t; + rest_params.rest_th_acc_m_s2 = params.stationary_rest_th_acc; + ImuRestDetector detector(rest_params, avg_dt); + for (const auto& [time, pose_tuple] : trajectory) + { + const RawIMUData& imu = std::get<2>(pose_tuple); + detector.update(time, imu.guroscopes, imu.accelerometers); + } + return detector.finish(); +} + static void release_freed_heap() { #if defined(__GLIBC__) @@ -612,7 +634,28 @@ bool compute_step_1( int threshold = params.threshold_nr_poses; - const int n_iter = poses.size() / threshold; + // the nodes: chunks of `threshold` poses; a long enough stretch at rest is one node ("merge") or chunks kept out of + // the map ("skip_map_update") + const StationaryMode stationary_mode = parse_stationary_mode(params.stationary_mode); + if (stationary_mode == StationaryMode::Off && params.stationary_mode != "off") + spdlog::warn("unknown stationary_mode '{}', using 'off'", params.stationary_mode); + std::vector> rest_segments; + params.stationary_segments.clear(); + if (stationary_mode != StationaryMode::Off) + { + rest_segments = detect_stationary_segments(trajectory, params); + for (const auto& [t_start, t_end] : rest_segments) + params.stationary_segments.push_back({ t_start, t_end, {} }); + } + std::vector pose_times; + pose_times.reserve(timestamps.size()); + for (const auto& t : timestamps) + pose_times.push_back(t.first); + const std::vector nodes = + plan_nodes(pose_times, threshold, rest_segments, params.stationary_min_duration, stationary_mode == StationaryMode::Merge); + pose_times = {}; + + const size_t n_iter = nodes.size(); worker_data.clear(); worker_data.reserve(n_iter); @@ -629,20 +672,25 @@ bool compute_step_1( if (i % 50 == 0) std::cout << "\rrunning iterations: " << i + 1 << "/" << n_iter << std::endl << std::flush; - WorkerData& wd = worker_data.emplace_back(); // construct in-place - wd.intermediate_trajectory.reserve(threshold); - wd.intermediate_trajectory_motion_model.reserve(threshold); - wd.intermediate_trajectory_timestamps.reserve(threshold); - wd.imu_om_fi_ka.reserve(threshold); - wd.raw_imu_data.reserve(threshold); + const size_t start_idx = nodes[i].begin; + const size_t end_idx = nodes[i].end; + const size_t node_size = end_idx - start_idx; - const size_t start_idx = i * threshold; - const size_t end_idx = (i + 1) * threshold; + WorkerData& wd = worker_data.emplace_back(); // construct in-place + wd.intermediate_trajectory.reserve(node_size); + wd.intermediate_trajectory_motion_model.reserve(node_size); + wd.intermediate_trajectory_timestamps.reserve(node_size); + wd.imu_om_fi_ka.reserve(node_size); + wd.raw_imu_data.reserve(node_size); + // a merged stretch at rest: every pose is the first one, so the node stays rigid when the trajectory is propagated + wd.stationary = nodes[i].segment >= 0 && stationary_mode == StationaryMode::Merge; + wd.skip_map_update = nodes[i].segment >= 0 && stationary_mode == StationaryMode::SkipMapUpdate; for (size_t idx = start_idx; idx < end_idx; idx++) { - wd.intermediate_trajectory.emplace_back(poses[idx]); - wd.intermediate_trajectory_motion_model.emplace_back(poses[idx]); + const Eigen::Affine3d& pose = wd.stationary ? poses[start_idx] : poses[idx]; + wd.intermediate_trajectory.emplace_back(pose); + wd.intermediate_trajectory_motion_model.emplace_back(pose); wd.intermediate_trajectory_timestamps.emplace_back(timestamps[idx]); const TaitBryanPose tb = pose_tait_bryan_from_affine_matrix(poses[idx]); @@ -743,6 +791,9 @@ bool compute_step_1( worker_data.pop_back(); else { + if (nodes[i].segment >= 0) + params.stationary_segments[nodes[i].segment].worker_indices.push_back(static_cast(worker_data.size()) - 1); + std::vector intermediate_points; if (params.decimation > 0.0 && points.size() > 1000) @@ -787,6 +838,29 @@ bool compute_step_1( std::cout << "\rrunning iterations: " << n_iter << " (done)" << std::flush; std::cout << std::endl; + for (const StationarySegment& segment : params.stationary_segments) + { + const double duration = segment.t_end - segment.t_start; + if (segment.worker_indices.empty()) + spdlog::info("stationary segment {:.3f} - {:.3f} ({:.1f} s): not handled", segment.t_start, segment.t_end, duration); + else if (stationary_mode == StationaryMode::Merge) + spdlog::info( + "stationary segment {:.3f} - {:.3f} ({:.1f} s): merged into node {} ({} poses)", + segment.t_start, + segment.t_end, + duration, + segment.worker_indices.front(), + worker_data[segment.worker_indices.front()].intermediate_trajectory.size()); + else + spdlog::info( + "stationary segment {:.3f} - {:.3f} ({:.1f} s): nodes {} - {} kept out of the map", + segment.t_start, + segment.t_end, + duration, + segment.worker_indices.front(), + segment.worker_indices.back()); + } + if (params.run_report) params.run_report->cachePrepared(); params.m_g = worker_data[0].intermediate_trajectory[0]; @@ -834,8 +908,46 @@ static bool write_result_files( std::vector original_points_to_save; int original_points_to_save_counter = 0; + std::vector scan_of_worker(worker_data.size(), -1); // the scan_lio_N each node went into + + // closes the scan being collected: its points go to a cache file, its trajectory to worker_data_concatenated + const auto flush_scan = [&]() -> bool + { + std::filesystem::path path = params.working_directory_cache; + // path /= "cache"; + std::string fn = "session_chunk_" + std::to_string(original_points_to_save_counter) + ".cache"; + path /= fn; + wd.original_points_to_save_cache_file_name = path; + + std::cout << "original_points_to_save_cache_file_name " << path.string() << std::endl; + + if (!save_cache_data(params, wd.original_points_to_save_cache_file_name.string(), original_points_to_save)) + { + std::cout << "problem with save_vector_data for file '" << wd.original_points_to_save_cache_file_name.string() << "'" + << std::endl; + std::cout << __FILE__ << " " << __LINE__ << std::endl; + return false; + } + + original_points_to_save_counter++; + + worker_data_concatenated.push_back(wd); + wd.intermediate_trajectory.clear(); + wd.intermediate_trajectory_timestamps.clear(); + original_points_to_save.clear(); + wd.imu_om_fi_ka.clear(); + + counter = 0; + pose_offset = 0; + return true; + }; + for (int i = 0; i < worker_data.size(); i++) { + // a stretch at rest is a scan of its own, so steps 2 and 3 move it as one rigid body + if (worker_data[i].stationary && counter > 0 && !flush_scan()) + return false; + std::vector original_points; // = worker_data[i].load_points(worker_data[i].original_points_cache_file_name); if (!load_vector_data(worker_data[i].original_points_cache_file_name.string(), original_points)) { @@ -882,61 +994,15 @@ static bool write_result_files( wd.imu_om_fi_ka.insert(std::end(wd.imu_om_fi_ka), std::begin(worker_data[i].imu_om_fi_ka), std::end(worker_data[i].imu_om_fi_ka)); pose_offset += worker_data[i].intermediate_trajectory.size(); + scan_of_worker[i] = original_points_to_save_counter; counter++; - if (counter > 50) - { - std::filesystem::path path = params.working_directory_cache; - // path /= "cache"; - std::string fn = "session_chunk_" + std::to_string(original_points_to_save_counter) + ".cache"; - path /= fn; - wd.original_points_to_save_cache_file_name = path; - - std::cout << "original_points_to_save_cache_file_name " << path.string() << std::endl; - - if (!save_cache_data(params, wd.original_points_to_save_cache_file_name.string(), original_points_to_save)) - { - std::cout << "problem with save_vector_data for file '" << wd.original_points_to_save_cache_file_name.string() << "'" - << std::endl; - std::cout << __FILE__ << " " << __LINE__ << std::endl; - return false; - } - - original_points_to_save_counter++; - - worker_data_concatenated.push_back(wd); - wd.intermediate_trajectory.clear(); - wd.intermediate_trajectory_timestamps.clear(); - original_points_to_save.clear(); - wd.imu_om_fi_ka.clear(); - - counter = 0; - pose_offset = 0; - } - } - - if (counter > params.min_counter_concatenated_trajectory_nodes) - { - std::filesystem::path path = params.working_directory_cache; - // path /= "cache"; - std::string fn = "session_chunk_" + std::to_string(original_points_to_save_counter) + ".cache"; - path /= fn; - wd.original_points_to_save_cache_file_name = path; - - std::cout << "original_points_to_save_cache_file_name " << path.string() << std::endl; - - if (!save_cache_data(params, wd.original_points_to_save_cache_file_name.string(), original_points_to_save)) - { - std::cout << "problem with save_vector_data for file '" << wd.original_points_to_save_cache_file_name.string() << "'" - << std::endl; - std::cout << __FILE__ << " " << __LINE__ << std::endl; + if ((counter > 50 || worker_data[i].stationary) && !flush_scan()) return false; - } - - original_points_to_save_counter++; - - worker_data_concatenated.push_back(wd); } + if (counter > params.min_counter_concatenated_trajectory_nodes && !flush_scan()) + return false; + fs::path point_sizes_path = outwd / "point_sizes_per_chunk.json"; nlohmann::json j_point_sizes = point_sizes_per_chunk; std::ofstream out_point_sizes(point_sizes_path); @@ -952,6 +1018,49 @@ static bool write_result_files( success = static_cast(out_point_sizes) && success; } + if (parse_stationary_mode(params.stationary_mode) != StationaryMode::Off) + { + nlohmann::json j_stationary; + j_stationary["stationary_mode"] = params.stationary_mode; + j_stationary["stationary_rest_min_t"] = params.stationary_rest_min_t; + j_stationary["stationary_rest_th_acc"] = params.stationary_rest_th_acc; + j_stationary["stationary_min_duration"] = params.stationary_min_duration; + nlohmann::json j_segments = nlohmann::json::array(); + for (const StationarySegment& segment : params.stationary_segments) + { + nlohmann::json j_segment; + j_segment["t_start"] = segment.t_start; + j_segment["t_end"] = segment.t_end; + j_segment["duration"] = segment.t_end - segment.t_start; + j_segment["handled"] = !segment.worker_indices.empty(); + std::vector scan_indices; // the scan_lio_N its nodes went into, ascending + for (const int w : segment.worker_indices) + { + const int scan = w < static_cast(scan_of_worker.size()) ? scan_of_worker[w] : -1; + if (scan >= 0 && scan < static_cast(worker_data_concatenated.size()) && + (scan_indices.empty() || scan_indices.back() != scan)) + scan_indices.push_back(scan); + } + j_segment["scan_indices"] = scan_indices; + j_segments.push_back(j_segment); + } + j_stationary["segments"] = j_segments; + + const fs::path stationary_path = outwd / "stationary_segments.json"; + std::ofstream out_stationary(stationary_path); + if (!out_stationary) + { + success = false; + std::cerr << "Failed to open " << stationary_path << " for writing stationary segments.\n"; + } + else + { + out_stationary << j_stationary.dump(2); + out_stationary.close(); + success = static_cast(out_stationary) && success; + } + } + std::vector m_poses; std::vector file_names; std::vector> index_poses; diff --git a/apps/lidar_odometry_step_1/lidar_odometry_gui.cpp b/apps/lidar_odometry_step_1/lidar_odometry_gui.cpp index 06529d18..4eba5ac7 100644 --- a/apps/lidar_odometry_step_1/lidar_odometry_gui.cpp +++ b/apps/lidar_odometry_step_1/lidar_odometry_gui.cpp @@ -111,6 +111,15 @@ bool show_covs_indoor = false; bool show_covs_outdoor = false; int dec_covs = 10; bool simple_gui = true; + +//! stationary_mode values, in StationaryMode order +const char* const kStationaryModeNames[] = { "off", "merge", "skip_map_update" }; +const char* const kStationaryModeTooltip = + "What to do with a stretch at rest (from the accelerometer) of at least the minimum duration:\n" + "merge: one node with one fixed pose (no odometry, kept by consistency), added to the map once, one scan_lio_N;\n" + "skip map update: odometry runs as usual, but the points stay out of the map.\n" + "For handheld use: rest cannot be told from constant velocity or a steady turn about the vertical.\n" + "Applies on the next run."; bool step_1_done = false; bool step_2_done = false; bool step_3_done = false; @@ -936,6 +945,26 @@ void settings_gui() "rotation from the IMU frame to the lidar frame applied to the IMU readings during load,\n" "e.g. 0.7071 0 0 0.7071 for an IMU turned +90 deg about z; 1 0 0 0: unchanged. Applies on Load data."); + { + int mode = static_cast(parse_stationary_mode(params.stationary_mode)); + ImGui::SetNextItemWidth(ImGuiNumberWidth * 2); + if (ImGui::Combo("Stationary segments", &mode, "off\0merge\0skip map update\0")) + params.stationary_mode = kStationaryModeNames[mode]; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", kStationaryModeTooltip); + } + if (parse_stationary_mode(params.stationary_mode) != StationaryMode::Off) + { + ImGui::SetNextItemWidth(ImGuiNumberWidth); + ImGui::InputDouble("Minimum stationary duration [s]", ¶ms.stationary_min_duration, 0.0, 0.0, "%.1f"); + ImGui::SetNextItemWidth(ImGuiNumberWidth); + ImGui::InputDouble("Rest min time [s]", ¶ms.stationary_rest_min_t, 0.0, 0.0, "%.2f"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("time the accelerometer must stay below its threshold before rest is detected"); + ImGui::SetNextItemWidth(ImGuiNumberWidth); + ImGui::InputDouble("Rest acc threshold [m/s^2]", ¶ms.stationary_rest_th_acc, 0.0, 0.0, "%.2f"); + } + ImGui::NewLine(); } @@ -2735,6 +2764,18 @@ void display() if (ImGui::IsItemHovered()) ImGui::SetTooltip("IMU bias will be removed given there's a stationary period at the start of the recording"); + if (ImGui::BeginMenu("Stationary segments")) + { + const StationaryMode current = parse_stationary_mode(params.stationary_mode); + const char* labels[] = { "Off", "Merge (one fixed node, no odometry)", "Skip map update (odometry runs)" }; + for (int m = 0; m < 3; m++) + if (ImGui::MenuItem(labels[m], nullptr, static_cast(current) == m)) + params.stationary_mode = kStationaryModeNames[m]; + ImGui::EndMenu(); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", kStationaryModeTooltip); + ImGui::MenuItem("Multithread", nullptr, ¶ms.useMultithread); ImGui::SetNextItemWidth(ImGuiNumberWidth / 2); ImGui::InputDouble("Time threshold [s]", ¶ms.real_time_threshold_seconds, 0.0, 0.0, "%.3f"); diff --git a/apps/lidar_odometry_step_1/lidar_odometry_utils.cpp b/apps/lidar_odometry_step_1/lidar_odometry_utils.cpp index 8a25d42c..354bdb83 100644 --- a/apps/lidar_odometry_step_1/lidar_odometry_utils.cpp +++ b/apps/lidar_odometry_step_1/lidar_odometry_utils.cpp @@ -722,6 +722,79 @@ std::vector find_lidar_gaps(const std::vector& points, doubl return gaps; } +StationaryMode parse_stationary_mode(const std::string& mode) +{ + if (mode == "merge") + return StationaryMode::Merge; + if (mode == "skip_map_update") + return StationaryMode::SkipMapUpdate; + return StationaryMode::Off; +} + +std::vector plan_nodes( + const std::vector& pose_times, + size_t chunk_size, + const std::vector>& rest_segments, + double min_duration_s, + bool merge) +{ + std::vector nodes; + if (chunk_size == 0) + return nodes; + const size_t n_chunks = pose_times.size() / chunk_size; + if (n_chunks == 0) + return nodes; + + // [first, last] chunk of each merged stretch, ascending + struct Merge + { + size_t first; + size_t last; + int segment; + }; + std::vector merges; + for (size_t s = 0; s < rest_segments.size(); s++) + { + const double t_start = std::max(rest_segments[s].first, pose_times.front()); + const double t_end = rest_segments[s].second; + if (t_end - t_start < min_duration_s) + continue; + + size_t first = 0; + while (first < n_chunks && pose_times[first * chunk_size] < t_start) + first++; + size_t end = first; // one past the last chunk inside the stretch + while (end < n_chunks && pose_times[(end + 1) * chunk_size - 1] <= t_end) + end++; + if (end < first + 2) + continue; + if (!merges.empty() && first <= merges.back().last) + continue; + merges.push_back({ first, end - 1, static_cast(s) }); + } + + size_t next_merge = 0; + for (size_t c = 0; c < n_chunks;) + { + if (next_merge < merges.size() && merges[next_merge].first == c) + { + const Merge& m = merges[next_merge++]; + if (merge) + nodes.push_back({ m.first * chunk_size, (m.last + 1) * chunk_size, m.segment }); + else + for (size_t k = m.first; k <= m.last; k++) + nodes.push_back({ k * chunk_size, (k + 1) * chunk_size, m.segment }); + c = m.last + 1; + } + else + { + nodes.push_back({ c * chunk_size, (c + 1) * chunk_size, -1 }); + c++; + } + } + return nodes; +} + std::unordered_map MLvxCalib::GetIdToSnMapping(const std::string& filename) { if (!std::filesystem::exists(filename)) diff --git a/apps/lidar_odometry_step_1/lidar_odometry_utils.h b/apps/lidar_odometry_step_1/lidar_odometry_utils.h index a28624ea..4b823b0e 100644 --- a/apps/lidar_odometry_step_1/lidar_odometry_utils.h +++ b/apps/lidar_odometry_step_1/lidar_odometry_utils.h @@ -54,6 +54,25 @@ struct LoadProgress; // recording_source.h: progress of load_data class RunReport; class PointsGlobalSpill; // points_global_spill.h: step 2's map buffer kept in a file +//! A stretch at rest found by the IMU rest detection in compute_step_1. +struct StationarySegment +{ + double t_start = 0.0; //!< LiDAR-clock time [s] + double t_end = 0.0; //!< LiDAR-clock time [s] + std::vector worker_indices; //!< its nodes in worker_data; empty when the stretch was too short to handle +}; + +//! What compute_step_1 does with a long enough stretch at rest (LidarOdometryParams::stationary_mode). +enum class StationaryMode +{ + Off, //!< "off": no rest detection + Merge, //!< "merge": one node with one fixed pose, no odometry, added to the map once + SkipMapUpdate, //!< "skip_map_update": ordinary chunks with odometry, kept out of the map +}; + +//! Parses "off", "merge" or "skip_map_update"; anything else is Off. +StationaryMode parse_stationary_mode(const std::string& mode); + struct LidarOdometryParams { // version information - automatically generated from CMake build system @@ -129,6 +148,15 @@ struct LidarOdometryParams double vqf_restThGyr = 2.0; // gyro threshold for rest detection [°/s] double vqf_restThAcc = 0.5; // acc threshold for rest detection [m/s²] + // Stationary segments: rest detection from the accelerometer (its own VQF, independent of the AHRS above). A stretch at + // rest of at least stationary_min_duration is handled as stationary_mode says: "off", "merge" or "skip_map_update" + // (see StationaryMode). + std::string stationary_mode = "off"; + double stationary_rest_min_t = 1.5; // time the IMU must be still before rest is detected [s] + double stationary_rest_th_acc = 0.5; // acc threshold for rest detection [m/s²] + double stationary_min_duration = 10.0; // shortest stretch at rest that is handled [s] + std::vector stationary_segments; // detected by the last compute_step_1 + // VQF magnetometer (only used when vqf_useMagnetometer is true) bool vqf_useMagnetometer = false; // use 9D mode (with magnetometer) instead of 6D double vqf_tauMag = 9.0; // magnetometer time constant [s] @@ -416,6 +444,26 @@ struct LidarGap //! @return gaps longer than min_gap_s between consecutive points, in time order std::vector find_lidar_gaps(const std::vector& points, double min_gap_s); +//! A node of compute_step_1: the poses [begin, end) of the trajectory. +struct NodeRange +{ + size_t begin = 0; + size_t end = 0; + int segment = -1; //!< index of the stretch at rest this node belongs to, -1 for an ordinary chunk +}; + +//! Splits a trajectory into nodes of chunk_size poses (a remainder shorter than chunk_size is dropped). A stretch at +//! rest is handled if it lasts at least min_duration_s after the first pose and at least two chunks lie entirely +//! inside it: those chunks become one node when merge is set, and stay chunks marked with the stretch otherwise. +//! @param pose_times - pose timestamps [s], ascending +//! @param rest_segments - [start, end] times [s] at rest, ascending and not overlapping +std::vector plan_nodes( + const std::vector& pose_times, + size_t chunk_size, + const std::vector>& rest_segments, + double min_duration_s, + bool merge); + bool save_poses(const std::string& file_name, const std::vector& m_poses, const std::vector& filenames); fs::path get_next_result_path(const std::string& working_directory); diff --git a/apps/lidar_odometry_step_1/lidar_odometry_utils_optimizers.cpp b/apps/lidar_odometry_step_1/lidar_odometry_utils_optimizers.cpp index 7af393db..6148e715 100644 --- a/apps/lidar_odometry_step_1/lidar_odometry_utils_optimizers.cpp +++ b/apps/lidar_odometry_step_1/lidar_odometry_utils_optimizers.cpp @@ -2491,44 +2491,54 @@ static bool compute_step_2_impl( params.run_report->pause(false); } - spdlog::stopwatch stopwatch_worker_process_worker_step_1; - process_worker_step_1( - worker_data[i], - i > 0 ? worker_data[i - 1] : worker_data[0], - i > 1 ? worker_data[i - 2] : worker_data[0], - params, - pause, - i, - debug, - lookup_stats, - debugMsg, - total_iterations, - total_optimization_time_seconds, - acc_distance, - worker_data.size(), - loProgress, - ts_failure); - const double elapsed_seconds_process_worker_step_1 = stopwatch_worker_process_worker_step_1.elapsed().count(); - - spdlog::stopwatch stopwatch_worker_process_worker_step_2; - process_worker_step_2( - worker_data[i], - i > 0 ? worker_data[i - 1] : worker_data[0], - i > 1 ? worker_data[i - 2] : worker_data[0], - params, - pause, - i, - debug, - lookup_stats, - debugMsg, - total_iterations, - total_optimization_time_seconds, - acc_distance, - worker_data.size(), - loProgress, - ts_failure, - intermediate_points); - const double elapsed_seconds_process_worker_step_2 = stopwatch_worker_process_worker_step_2.elapsed().count(); + // a merged stretch at rest keeps its pose: no prediction and no optimization + const bool optimize = !worker_data[i].stationary; + if (!optimize) + spdlog::info("node {} / {} is at rest: pose kept", i + 1, worker_data.size()); + double elapsed_seconds_process_worker_step_1 = 0.0; + double elapsed_seconds_process_worker_step_2 = 0.0; + double elapsed_seconds_process_worker_step_lidar_odometry_core = 0.0; + if (optimize) + { + spdlog::stopwatch stopwatch_worker_process_worker_step_1; + process_worker_step_1( + worker_data[i], + i > 0 ? worker_data[i - 1] : worker_data[0], + i > 1 ? worker_data[i - 2] : worker_data[0], + params, + pause, + i, + debug, + lookup_stats, + debugMsg, + total_iterations, + total_optimization_time_seconds, + acc_distance, + worker_data.size(), + loProgress, + ts_failure); + elapsed_seconds_process_worker_step_1 = stopwatch_worker_process_worker_step_1.elapsed().count(); + + spdlog::stopwatch stopwatch_worker_process_worker_step_2; + process_worker_step_2( + worker_data[i], + i > 0 ? worker_data[i - 1] : worker_data[0], + i > 1 ? worker_data[i - 2] : worker_data[0], + params, + pause, + i, + debug, + lookup_stats, + debugMsg, + total_iterations, + total_optimization_time_seconds, + acc_distance, + worker_data.size(), + loProgress, + ts_failure, + intermediate_points); + elapsed_seconds_process_worker_step_2 = stopwatch_worker_process_worker_step_2.elapsed().count(); + } if (params.publish_trajectory) params.publish_trajectory(worker_data, false); @@ -2543,29 +2553,32 @@ static bool compute_step_2_impl( HDMAP_ZONE_END(before_iter); - spdlog::stopwatch stopwatch_worker_process_worker_step_lidar_odometry_core; - process_worker_step_lidar_odometry_core( - worker_data[i], - i > 0 ? worker_data[i - 1] : worker_data[0], - i > 1 ? worker_data[i - 2] : worker_data[0], - params, - pause, - i, - debug, - lookup_stats, - debugMsg, - total_iterations, - total_optimization_time_seconds, - acc_distance, - worker_data.size(), - loProgress, - ts_failure, - intermediate_points, - iter_end, - delta, - lm_factor); - const double elapsed_seconds_process_worker_step_lidar_odometry_core = - stopwatch_worker_process_worker_step_lidar_odometry_core.elapsed().count(); + if (optimize) + { + spdlog::stopwatch stopwatch_worker_process_worker_step_lidar_odometry_core; + process_worker_step_lidar_odometry_core( + worker_data[i], + i > 0 ? worker_data[i - 1] : worker_data[0], + i > 1 ? worker_data[i - 2] : worker_data[0], + params, + pause, + i, + debug, + lookup_stats, + debugMsg, + total_iterations, + total_optimization_time_seconds, + acc_distance, + worker_data.size(), + loProgress, + ts_failure, + intermediate_points, + iter_end, + delta, + lm_factor); + elapsed_seconds_process_worker_step_lidar_odometry_core = + stopwatch_worker_process_worker_step_lidar_odometry_core.elapsed().count(); + } HDMAP_ZONE_BEGIN(after_iter, "after_iterations"); @@ -2667,24 +2680,29 @@ static bool compute_step_2_impl( if (params.publish_trajectory) params.publish_trajectory(worker_data, false); - HDMAP_ZONE_BEGIN(transform_pts, "transform_points_global"); - for (int j = 0; j < intermediate_points.size(); j++) + // a chunk at rest (stationary_mode "skip_map_update") is kept out of the map and of the buffer it is rebuilt from + if (!worker_data[i].skip_map_update) { - Point3Di pp = intermediate_points[j]; - pp.point = worker_data[i].intermediate_trajectory[intermediate_points[j].index_pose] * pp.point; - if (PointsGlobalSpill* sp = params.points_global_spill) - sp->append(pp); - else - points_global.push_back(pp); - } - HDMAP_ZONE_END(transform_pts); + HDMAP_ZONE_BEGIN(transform_pts, "transform_points_global"); + for (int j = 0; j < intermediate_points.size(); j++) + { + Point3Di pp = intermediate_points[j]; + pp.point = worker_data[i].intermediate_trajectory[intermediate_points[j].index_pose] * pp.point; + if (PointsGlobalSpill* sp = params.points_global_spill) + sp->append(pp); + else + points_global.push_back(pp); + } + HDMAP_ZONE_END(transform_pts); - // if(reference_points.size() == 0){ - HDMAP_ZONE_BEGIN(update_rgd_after, "update_rgd"); + // if(reference_points.size() == 0){ + HDMAP_ZONE_BEGIN(update_rgd_after, "update_rgd"); - process_worker_step_update_rgd_after(acc_distance, params, points_global, worker_data[i], lookup_stats, intermediate_points); + process_worker_step_update_rgd_after( + acc_distance, params, points_global, worker_data[i], lookup_stats, intermediate_points); - HDMAP_ZONE_END(update_rgd_after); + HDMAP_ZONE_END(update_rgd_after); + } if (params.publish_processing_head && !worker_data[i].intermediate_trajectory.empty()) params.publish_processing_head(worker_data[i].intermediate_trajectory.back().translation()); @@ -2727,6 +2745,24 @@ static bool compute_step_2_impl( return true; } +//! Holds the poses of the stretches at rest in place: a strong prior that each of their updates is zero, added to the +//! normal equations of the consistency adjustment (poses in worker_data order, 6 parameters each). +static void fix_stationary_poses(const std::vector& worker_data, Eigen::SparseMatrix& AtPA) +{ + constexpr double weight = 1e12; + int pose_index = 0; + for (const WorkerData& wd : worker_data) + { + for (size_t j = 0; j < wd.intermediate_trajectory.size(); j++, pose_index++) + { + if (!wd.stationary) + continue; + for (int k = 0; k < 6; k++) + AtPA.coeffRef(pose_index * 6 + k, pose_index * 6 + k) += weight; + } + } +} + void Consistency(std::vector& worker_data, const LidarOdometryParams& params) { std::vector trajectory; @@ -3071,6 +3107,7 @@ void Consistency(std::vector& worker_data, const LidarOdometryParams } spdlog::info("NDT observations FINISHED"); + fix_stationary_poses(worker_data, AtPA); Eigen::SimplicialCholesky> solver(AtPA); Eigen::SparseMatrix x = solver.solve(AtPB); std::vector h_x; @@ -3096,7 +3133,8 @@ void Consistency(std::vector& worker_data, const LidarOdometryParams } for (int i = 0; i < indexes.size(); i++) - worker_data[indexes[i].first].intermediate_trajectory[indexes[i].second] = trajectory[i]; + if (!worker_data[indexes[i].first].stationary) // a stretch at rest keeps its pose + worker_data[indexes[i].first].intermediate_trajectory[indexes[i].second] = trajectory[i]; } void Consistency2(std::vector& worker_data, const LidarOdometryParams& params) @@ -3602,6 +3640,7 @@ void Consistency2(std::vector& worker_data, const LidarOdometryParam spdlog::info("NDT observations start FINISHED"); + fix_stationary_poses(worker_data, AtPA); Eigen::SimplicialCholesky> solver(AtPA); Eigen::SparseMatrix x = solver.solve(AtPB); std::vector h_x; @@ -3627,5 +3666,6 @@ void Consistency2(std::vector& worker_data, const LidarOdometryParam } for (int i = 0; i < indexes.size(); i++) - worker_data[indexes[i].first].intermediate_trajectory[indexes[i].second] = trajectory[i]; + if (!worker_data[indexes[i].first].stationary) // a stretch at rest keeps its pose + worker_data[indexes[i].first].intermediate_trajectory[indexes[i].second] = trajectory[i]; } diff --git a/apps/lidar_odometry_step_1/tests/CMakeLists.txt b/apps/lidar_odometry_step_1/tests/CMakeLists.txt index 6efc135f..b79fc19d 100644 --- a/apps/lidar_odometry_step_1/tests/CMakeLists.txt +++ b/apps/lidar_odometry_step_1/tests/CMakeLists.txt @@ -16,6 +16,7 @@ project(lidar_odometry_step_1_tests) add_executable(lidar_odometry_step_1_tests test_mlvx_calib.cpp test_lidar_gaps.cpp + test_plan_nodes.cpp test_imu_load.cpp ../lidar_odometry_utils.cpp ../output_folders.cpp diff --git a/apps/lidar_odometry_step_1/tests/test_plan_nodes.cpp b/apps/lidar_odometry_step_1/tests/test_plan_nodes.cpp new file mode 100644 index 00000000..2a5caff6 --- /dev/null +++ b/apps/lidar_odometry_step_1/tests/test_plan_nodes.cpp @@ -0,0 +1,101 @@ +#include + +#include "../lidar_odometry_utils.h" + +namespace +{ + // Pose times 0, 0.1, 0.2, ... for `count` poses + std::vector poseTimes(size_t count) + { + std::vector times; + for (size_t i = 0; i < count; i++) + times.push_back(0.1 * static_cast(i)); + return times; + } +} // namespace + +TEST_CASE("plan_nodes: no rest gives chunks and drops the remainder") +{ + const auto nodes = plan_nodes(poseTimes(105), 10, {}, 1.0, true); + REQUIRE(nodes.size() == 10); + for (size_t i = 0; i < nodes.size(); i++) + { + CHECK(nodes[i].begin == i * 10); + CHECK(nodes[i].end == (i + 1) * 10); + CHECK(nodes[i].segment == -1); + } +} + +TEST_CASE("plan_nodes: chunks entirely inside a stretch at rest become one node") +{ + // chunk c covers poses [10c, 10c + 10), times [c, c + 0.9]; rest from 2.5 s to 6.85 s holds chunks 3, 4 and 5 + const auto nodes = plan_nodes(poseTimes(100), 10, { { 2.5, 6.85 } }, 1.0, true); + REQUIRE(nodes.size() == 8); + CHECK(nodes[2].end == 30); + CHECK(nodes[3].begin == 30); + CHECK(nodes[3].end == 60); + CHECK(nodes[3].segment == 0); + CHECK(nodes[4].begin == 60); + CHECK(nodes[4].segment == -1); +} + +TEST_CASE("plan_nodes: short stretches stay ordinary chunks") +{ + SUBCASE("shorter than the minimum duration") + { + const auto nodes = plan_nodes(poseTimes(100), 10, { { 2.5, 6.85 } }, 5.0, true); + CHECK(nodes.size() == 10); + } + SUBCASE("only one whole chunk inside") + { + const auto nodes = plan_nodes(poseTimes(100), 10, { { 2.5, 3.95 } }, 1.0, true); + CHECK(nodes.size() == 10); + } +} + +TEST_CASE("plan_nodes: a stretch at rest before the first pose counts from the first pose") +{ + auto times = poseTimes(100); + for (double& t : times) + t += 100.0; + // 90 s at rest before the trajectory starts, 1.95 s after it: too short once cut to the trajectory + CHECK(plan_nodes(times, 10, { { 10.0, 101.95 } }, 3.0, true).size() == 10); + + const auto nodes = plan_nodes(times, 10, { { 10.0, 104.95 } }, 3.0, true); + REQUIRE(nodes.size() == 6); + CHECK(nodes[0].begin == 0); + CHECK(nodes[0].end == 50); + CHECK(nodes[0].segment == 0); +} + +TEST_CASE("plan_nodes: two stretches at rest") +{ + const auto nodes = plan_nodes(poseTimes(100), 10, { { 0.0, 1.95 }, { 2.0, 9.95 } }, 1.0, true); + REQUIRE(nodes.size() == 2); + CHECK(nodes[0].end == 20); + CHECK(nodes[0].segment == 0); + CHECK(nodes[1].begin == 20); + CHECK(nodes[1].end == 100); + CHECK(nodes[1].segment == 1); +} + +TEST_CASE("plan_nodes: without merging the chunks of a stretch at rest stay chunks, marked with it") +{ + const auto nodes = plan_nodes(poseTimes(100), 10, { { 2.5, 6.85 } }, 1.0, false); + REQUIRE(nodes.size() == 10); + for (size_t i = 0; i < nodes.size(); i++) + { + CHECK(nodes[i].begin == i * 10); + CHECK(nodes[i].end == (i + 1) * 10); + CHECK(nodes[i].segment == (i >= 3 && i <= 5 ? 0 : -1)); + } +} + +TEST_CASE("parse_stationary_mode") +{ + CHECK(parse_stationary_mode("off") == StationaryMode::Off); + CHECK(parse_stationary_mode("merge") == StationaryMode::Merge); + CHECK(parse_stationary_mode("skip_map_update") == StationaryMode::SkipMapUpdate); + CHECK(parse_stationary_mode("Merge") == StationaryMode::Off); + CHECK(parse_stationary_mode("") == StationaryMode::Off); +} diff --git a/apps/lidar_odometry_step_1/toml_io.h b/apps/lidar_odometry_step_1/toml_io.h index b1e86a00..121bceec 100644 --- a/apps/lidar_odometry_step_1/toml_io.h +++ b/apps/lidar_odometry_step_1/toml_io.h @@ -60,6 +60,10 @@ class TomlIO { "vqf_restFilterTau", &LidarOdometryParams::vqf_restFilterTau }, { "vqf_restThGyr", &LidarOdometryParams::vqf_restThGyr }, { "vqf_restThAcc", &LidarOdometryParams::vqf_restThAcc }, + { "stationary_mode", &LidarOdometryParams::stationary_mode }, + { "stationary_rest_min_t", &LidarOdometryParams::stationary_rest_min_t }, + { "stationary_rest_th_acc", &LidarOdometryParams::stationary_rest_th_acc }, + { "stationary_min_duration", &LidarOdometryParams::stationary_min_duration }, { "vqf_useMagnetometer", &LidarOdometryParams::vqf_useMagnetometer }, { "vqf_tauMag", &LidarOdometryParams::vqf_tauMag }, { "vqf_magDistRejectionEnabled", &LidarOdometryParams::vqf_magDistRejectionEnabled }, @@ -187,6 +191,7 @@ class TomlIO "convergence_delta_threshold" } }, { "lidar_odometry_debug_info", { "save_calibration_validation", "calibration_validation_points", "save_preview_point_clouds" } }, { "consistency", { "num_constistency_iter", "use_mutliple_gaussian" } }, + { "stationary_segments", { "stationary_mode", "stationary_rest_min_t", "stationary_rest_th_acc", "stationary_min_duration" } }, { "motion_model_uncertainty", { "lidar_odometry_motion_model_x_1_sigma_m", "lidar_odometry_motion_model_y_1_sigma_m", diff --git a/apps/mandeye_raw_data_viewer/mandeye_raw_data_viewer.cpp b/apps/mandeye_raw_data_viewer/mandeye_raw_data_viewer.cpp index c360f8ee..6b3a9649 100644 --- a/apps/mandeye_raw_data_viewer/mandeye_raw_data_viewer.cpp +++ b/apps/mandeye_raw_data_viewer/mandeye_raw_data_viewer.cpp @@ -16,6 +16,7 @@ #include #include +#include #include #include #include @@ -1192,69 +1193,31 @@ void loadFiles(std::vector input_file_names, const std::shared_ptr< } } - VQFParams vqf_params; - vqf_params.tauAcc = vqf_tauAcc > 0.0 ? vqf_tauAcc : 3.0; + ImuRestDetector::Params rest_params; + rest_params.tau_acc = vqf_tauAcc > 0.0 ? vqf_tauAcc : 3.0; + rest_params.averaging_period = SAMPLE_PERIOD; // produce warning if (std::fabs(avg_dt - SAMPLE_PERIOD) > 0.01) { spdlog::warn("The dt found is strange : {}", avg_dt); } spdlog::info("avg_dt: {}", avg_dt); - VQF vqf(vqf_params, avg_dt); + // VQF orientation and the motionless segments: runs of samples VQF flags as rest + ImuRestDetector rest_detector(rest_params, avg_dt); + if (rest_detector.window() > 1) + spdlog::info("VQF input averaged over {} samples", rest_detector.window()); std::map> trajectory; - // Motionless segments: runs of samples VQF flags as rest. It flags rest once the - // IMU has been still for restMinT, so each run is moved that much earlier. - motionless_segments.clear(); - bool resting = false; - double rest_start = 0.0, previous_t = 0.0; - - // VQF resets rest detection on any single sample deviating more than restThGyr / restThAcc, so - // the per-sample noise of an IMU much faster than SAMPLE_PERIOD (e.g. a 1451 Hz Murata) never lets - // it detect rest. Feed VQF a moving average over SAMPLE_PERIOD; at 200 Hz that is a single sample. - const size_t vqf_window = std::max(1, static_cast(std::lround(SAMPLE_PERIOD / avg_dt))); - if (vqf_window > 1) - spdlog::info("VQF input averaged over {} samples", vqf_window); - int counter = 1; for (size_t i = 0; i < imu_data.size(); i++) { const auto& [timestamp_pair, gyr, acc] = imu_data[i]; - const size_t window_begin = i + 1 >= vqf_window ? i + 1 - vqf_window : 0; - Eigen::Vector3d gyr_avg = Eigen::Vector3d::Zero(); - Eigen::Vector3d acc_avg = Eigen::Vector3d::Zero(); - for (size_t k = window_begin; k <= i; k++) - { - gyr_avg += std::get<1>(imu_data[k]).cast(); - acc_avg += std::get<2>(imu_data[k]).cast(); - } - gyr_avg /= static_cast(i + 1 - window_begin); - acc_avg /= static_cast(i + 1 - window_begin); - - const double g = 9.81; - vqf_real_t gyr_vqf[3] = { gyr_avg.x(), gyr_avg.y(), gyr_avg.z() }; - vqf_real_t acc_vqf[3] = { acc_avg.x() * g, acc_avg.y() * g, acc_avg.z() * g }; - - vqf.update(gyr_vqf, acc_vqf); + rest_detector.update(timestamp_pair.first, gyr.cast(), acc.cast()); - const bool rest = vqf.getRestDetected(); - if (rest && !resting) - { - rest_start = timestamp_pair.first - vqf_params.restMinT; - if (!motionless_segments.empty()) - rest_start = std::max(rest_start, motionless_segments.back().second); - } - else if (!rest && resting) - motionless_segments.emplace_back(rest_start, previous_t); - resting = rest; - previous_t = timestamp_pair.first; - - vqf_real_t quat[4]; - vqf.getQuat6D(quat); - Eigen::Quaterniond d(quat[0], quat[1], quat[2], quat[3]); + const Eigen::Quaterniond d = rest_detector.orientation(); Eigen::Affine3d t{ Eigen::Matrix4d::Identity() }; t.rotate(d); @@ -1280,8 +1243,7 @@ void loadFiles(std::vector input_file_names, const std::shared_ptr< imu_data_plot.roll.push_back(euler.x()); } - if (resting) - motionless_segments.emplace_back(rest_start, previous_t); + motionless_segments = rest_detector.finish(); spdlog::info("{} motionless segment(s) detected", motionless_segments.size()); // timeline x-axis is shown relative to the first IMU sample so it starts at 0 [s]; diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt index e1f0dcb8..ddc069a6 100644 --- a/core/CMakeLists.txt +++ b/core/CMakeLists.txt @@ -8,6 +8,7 @@ set(CORE_BASE_SOURCES src/gnss.cpp src/ground_control_points.cpp src/imu_preintegration.cpp + src/imu_rest_detection.cpp src/instrument_offset.cpp src/nmea.cpp src/point_cloud.cpp diff --git a/core/include/Core/imu_rest_detection.h b/core/include/Core/imu_rest_detection.h new file mode 100644 index 00000000..7898af99 --- /dev/null +++ b/core/include/Core/imu_rest_detection.h @@ -0,0 +1,61 @@ +#pragma once + +#include + +#include +#include +#include +#include + +class VQF; + +//! Finds the stretches in which the IMU is at rest from the accelerometer alone, with VQF's rest detection (the +//! gyroscope is left out: a gyro bias over VQF's bias clip would rule out rest). It misses rotation at a steady rate +//! about the vertical axis. Feed it every sample in time order with update(), then call finish() for the segments. +//! It also runs VQF's 6D orientation, with the gyroscope, on the same input. +class ImuRestDetector +{ +public: + //! VQF settings; the defaults are VQF's own. + struct Params + { + double tau_acc = 3.0; //!< accelerometer time constant [s] + double rest_min_t = 1.5; //!< time the IMU must be still before rest is detected [s] + double rest_filter_tau = 0.5; //!< low-pass time constant of the rest detection [s] + double rest_th_acc_m_s2 = 0.5; //!< accelerometer threshold [m/s^2] + //! VQF resets rest detection on any single sample over a threshold, so the noise of an IMU much faster than + //! 200 Hz would never let it detect rest. Its input is averaged over this period [s]. + double averaging_period = 1.0 / 200.0; + }; + + //! avg_dt is the IMU sample period [s]. + ImuRestDetector(const Params& params, double avg_dt); + ~ImuRestDetector(); + + //! Number of samples averaged into each VQF input. + size_t window() const + { + return window_; + } + + //! Feeds one sample: timestamp [s], gyroscope [rad/s], accelerometer [g]. + void update(double timestamp, const Eigen::Vector3d& gyr_rad_s, const Eigen::Vector3d& acc_g); + + //! VQF's 6D orientation after the last update(). + Eigen::Quaterniond orientation() const; + + //! The [start, end] times [s] at rest. VQF flags rest only after rest_min_t of stillness, so each segment starts + //! that much before the first flagged sample (never before the previous segment's end). + const std::vector>& finish(); + +private: + Params params_; + size_t window_ = 1; + std::unique_ptr vqf_; //!< orientation + std::unique_ptr rest_vqf_; //!< rest detection, fed a zero gyroscope + std::deque> recent_; //!< last window_ (gyr, acc) samples + bool resting_ = false; + double rest_start_ = 0.0; + double previous_t_ = 0.0; + std::vector> segments_; +}; diff --git a/core/include/Core/structures.h b/core/include/Core/structures.h index 88dc535a..233697e6 100644 --- a/core/include/Core/structures.h +++ b/core/include/Core/structures.h @@ -401,6 +401,10 @@ struct WorkerData std::vector raw_imu_data; Eigen::Vector3d imu_prediction_vector = Eigen::Vector3d::Zero(); bool show = false; + //! All poses are one fixed pose: the IMU was at rest. Odometry and consistency leave it unchanged. + bool stationary = false; + //! The IMU was at rest: the points are kept out of the odometry map (stationary_mode "skip_map_update"). + bool skip_map_update = false; std::vector intermediate_trajectory_prediction; // Eigen::Vector3d mean_shift = Eigen::Vector3d::Zero(); }; diff --git a/core/src/imu_rest_detection.cpp b/core/src/imu_rest_detection.cpp new file mode 100644 index 00000000..7767c139 --- /dev/null +++ b/core/src/imu_rest_detection.cpp @@ -0,0 +1,72 @@ +#include + +#include + +#include +#include + +ImuRestDetector::ImuRestDetector(const Params& params, double avg_dt) + : params_(params) +{ + VQFParams vqf_params; + vqf_params.tauAcc = params.tau_acc; + vqf_params.restMinT = params.rest_min_t; + vqf_params.restFilterTau = params.rest_filter_tau; + vqf_params.restThAcc = params.rest_th_acc_m_s2; + vqf_ = std::make_unique(vqf_params, avg_dt); + rest_vqf_ = std::make_unique(vqf_params, avg_dt); + window_ = std::max(1, static_cast(std::lround(params.averaging_period / avg_dt))); +} + +ImuRestDetector::~ImuRestDetector() = default; + +void ImuRestDetector::update(double timestamp, const Eigen::Vector3d& gyr_rad_s, const Eigen::Vector3d& acc_g) +{ + recent_.emplace_back(gyr_rad_s, acc_g); + if (recent_.size() > window_) + recent_.pop_front(); + + Eigen::Vector3d gyr_avg = Eigen::Vector3d::Zero(); + Eigen::Vector3d acc_avg = Eigen::Vector3d::Zero(); + for (const auto& [gyr, acc] : recent_) + { + gyr_avg += gyr; + acc_avg += acc; + } + gyr_avg /= static_cast(recent_.size()); + acc_avg /= static_cast(recent_.size()); + + const double g = 9.81; + vqf_real_t gyr_vqf[3] = { gyr_avg.x(), gyr_avg.y(), gyr_avg.z() }; + vqf_real_t acc_vqf[3] = { acc_avg.x() * g, acc_avg.y() * g, acc_avg.z() * g }; + vqf_->update(gyr_vqf, acc_vqf); + vqf_real_t no_gyr[3] = { 0.0, 0.0, 0.0 }; + rest_vqf_->update(no_gyr, acc_vqf); + + const bool rest = rest_vqf_->getRestDetected(); + if (rest && !resting_) + { + rest_start_ = timestamp - params_.rest_min_t; + if (!segments_.empty()) + rest_start_ = std::max(rest_start_, segments_.back().second); + } + else if (!rest && resting_) + segments_.emplace_back(rest_start_, previous_t_); + resting_ = rest; + previous_t_ = timestamp; +} + +Eigen::Quaterniond ImuRestDetector::orientation() const +{ + vqf_real_t quat[4]; + vqf_->getQuat6D(quat); + return Eigen::Quaterniond(quat[0], quat[1], quat[2], quat[3]); +} + +const std::vector>& ImuRestDetector::finish() +{ + if (resting_) + segments_.emplace_back(rest_start_, previous_t_); + resting_ = false; + return segments_; +} diff --git a/core/tests/CMakeLists.txt b/core/tests/CMakeLists.txt index e1df1346..a153c6f9 100644 --- a/core/tests/CMakeLists.txt +++ b/core/tests/CMakeLists.txt @@ -5,6 +5,7 @@ project(hdmapping_core_tests) # Unit tests for core/ (core_no_gui, the GUI-less build of the core library). # Uses doctest, same as shared/tests. add_executable(hdmapping_core_tests + test_imu_rest_detection.cpp test_pair_wise_icp.cpp test_instrument_offset.cpp ) diff --git a/core/tests/test_imu_rest_detection.cpp b/core/tests/test_imu_rest_detection.cpp new file mode 100644 index 00000000..4cc9a752 --- /dev/null +++ b/core/tests/test_imu_rest_detection.cpp @@ -0,0 +1,81 @@ +#include + +#include + +#include + +namespace +{ + //! Feeds rate_hz samples of a level IMU from t_begin to t_end; moving adds a rotation about z with gyro and + //! accelerometer jitter well over the rest thresholds. + void feed(ImuRestDetector& detector, double rate_hz, double t_begin, double t_end, bool moving) + { + const double dt = 1.0 / rate_hz; + for (double t = t_begin; t < t_end - dt / 2; t += dt) + { + Eigen::Vector3d gyr = Eigen::Vector3d::Zero(); + Eigen::Vector3d acc(0.0, 0.0, 1.0); + if (moving) + { + gyr.z() = 0.5 + 0.3 * std::sin(10.0 * t); + acc.x() = 0.2 * std::sin(7.0 * t); + } + detector.update(t, gyr, acc); + } + } +} // namespace + +TEST_CASE("ImuRestDetector finds still, moving, still") +{ + const double rate = 200.0; + ImuRestDetector detector({}, 1.0 / rate); + CHECK(detector.window() == 1); + feed(detector, rate, 0.0, 10.0, false); + feed(detector, rate, 10.0, 15.0, true); + feed(detector, rate, 15.0, 30.0, false); + const auto& segments = detector.finish(); + + REQUIRE(segments.size() == 2); + // VQF flags rest once still for rest_min_t; the segment starts that much earlier + CHECK(segments[0].first == doctest::Approx(0.0).epsilon(0.05)); + CHECK(segments[0].second == doctest::Approx(10.0).epsilon(0.01)); + // after motion the rest filter (rest_filter_tau) settles before the stillness starts to count + CHECK(segments[1].first >= 15.0); + CHECK(segments[1].first < 16.5); + CHECK(segments[1].second == doctest::Approx(30.0 - 1.0 / rate)); +} + +TEST_CASE("ImuRestDetector finds no rest while moving") +{ + ImuRestDetector detector({}, 1.0 / 200.0); + feed(detector, 200.0, 0.0, 20.0, true); + CHECK(detector.finish().empty()); +} + +TEST_CASE("ImuRestDetector ignores the gyroscope") +{ + // still with a 4 deg/s gyro bias, over VQF's 2 deg/s bias clip + ImuRestDetector detector({}, 1.0 / 200.0); + for (int i = 0; i < 2000; i++) + detector.update(i / 200.0, Eigen::Vector3d(4.0 * M_PI / 180.0, 0.0, 0.0), Eigen::Vector3d(0.0, 0.0, 1.0)); + const auto& segments = detector.finish(); + REQUIRE(segments.size() == 1); + CHECK(segments[0].second - segments[0].first > 8.0); +} + +TEST_CASE("ImuRestDetector averages a fast IMU") +{ + const double rate = 1400.0; + ImuRestDetector detector({}, 1.0 / rate); + CHECK(detector.window() == 7); + + // still, but each sample alternates far over the accelerometer threshold; the average over 1/200 s cancels it + for (int i = 0; i < static_cast(10.0 * rate); i++) + { + const double sign = i % 2 == 0 ? 1.0 : -1.0; + detector.update(i / rate, Eigen::Vector3d::Zero(), Eigen::Vector3d(sign * 0.1, 0.0, 1.0)); + } + const auto& segments = detector.finish(); + REQUIRE(segments.size() == 1); + CHECK(segments[0].second - segments[0].first > 8.0); +}