Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
233 changes: 171 additions & 62 deletions apps/lidar_odometry_step_1/lidar_odometry.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include "tbb/tbb.h"
#include <mutex>

#include <Core/imu_rest_detection.h>
#include <Core/system_info.hpp>
#include <Fusion.h>
#include <HDMapping/SessionPaths.h>
Expand Down Expand Up @@ -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<std::pair<double, double>> 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<double>(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__)
Expand Down Expand Up @@ -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<std::pair<double, double>> 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<double> pose_times;
pose_times.reserve(timestamps.size());
for (const auto& t : timestamps)
pose_times.push_back(t.first);
const std::vector<NodeRange> 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);

Expand All @@ -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]);
Expand Down Expand Up @@ -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<int>(worker_data.size()) - 1);

std::vector<Point3Di> intermediate_points;

if (params.decimation > 0.0 && points.size() > 1000)
Expand Down Expand Up @@ -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];
Expand Down Expand Up @@ -834,8 +908,46 @@ static bool write_result_files(

std::vector<Point3Di> original_points_to_save;
int original_points_to_save_counter = 0;
std::vector<int> 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<Point3Di> 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))
{
Expand Down Expand Up @@ -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);
Expand All @@ -952,6 +1018,49 @@ static bool write_result_files(
success = static_cast<bool>(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<int> scan_indices; // the scan_lio_N its nodes went into, ascending
for (const int w : segment.worker_indices)
{
const int scan = w < static_cast<int>(scan_of_worker.size()) ? scan_of_worker[w] : -1;
if (scan >= 0 && scan < static_cast<int>(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<bool>(out_stationary) && success;
}
}

std::vector<Eigen::Affine3d> m_poses;
std::vector<std::string> file_names;
std::vector<std::vector<int>> index_poses;
Expand Down
41 changes: 41 additions & 0 deletions apps/lidar_odometry_step_1/lidar_odometry_gui.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<int>(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]", &params.stationary_min_duration, 0.0, 0.0, "%.1f");
ImGui::SetNextItemWidth(ImGuiNumberWidth);
ImGui::InputDouble("Rest min time [s]", &params.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]", &params.stationary_rest_th_acc, 0.0, 0.0, "%.2f");
}

ImGui::NewLine();
}

Expand Down Expand Up @@ -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<int>(current) == m))
params.stationary_mode = kStationaryModeNames[m];
ImGui::EndMenu();
}
if (ImGui::IsItemHovered())
ImGui::SetTooltip("%s", kStationaryModeTooltip);

ImGui::MenuItem("Multithread", nullptr, &params.useMultithread);
ImGui::SetNextItemWidth(ImGuiNumberWidth / 2);
ImGui::InputDouble("Time threshold [s]", &params.real_time_threshold_seconds, 0.0, 0.0, "%.3f");
Expand Down
Loading
Loading