From 8550a58ed3def953d68bf2d5c44d9d9a27c1ecbf Mon Sep 17 00:00:00 2001 From: janusz Date: Sun, 22 Nov 2026 08:23:06 +0100 Subject: [PATCH 1/9] initial work on icp_uncertainty --- apps/session_uncertainty_calculation/main.cpp | 158 +++++++++- .../Core/pair_wise_iterative_closest_point.h | 5 + core/src/color_las_loader.cpp | 31 +- .../src/pair_wise_iterative_closest_point.cpp | 281 ++++++++++++++++++ 4 files changed, 464 insertions(+), 11 deletions(-) diff --git a/apps/session_uncertainty_calculation/main.cpp b/apps/session_uncertainty_calculation/main.cpp index 204fb2c82..6beaf008d 100644 --- a/apps/session_uncertainty_calculation/main.cpp +++ b/apps/session_uncertainty_calculation/main.cpp @@ -1,18 +1,168 @@ +#include "Core/color_las_loader.h" +#include "Core/pair_wise_iterative_closest_point.h" +#include "Core/session.h" + +#include +#include +#include #include +#include int main(int argc, char* argv[]) { std::cout << "Session Uncertainty Calculation" << std::endl; std::cout << "-----------------------------------" << std::endl; - std::cout << "This program calculates the uncertainty of a session for each trajectory node as ICP/Hessian and Error Propagation Law " - "assuming having TLS ground truth." + std::cout << "This program calculates the uncertainty of a session for each trajectory node from inverse ICP/Hessian assuming having " + "TLS ground truth." << std::endl; if (argc < 4) { - std::cerr << "Usage: " << argv[0] << " " << std::endl; + std::cerr << "Usage: " << argv[0] << " " << std::endl; + return 1; + } + + const std::filesystem::path tlsFile{ argv[1] }; + std::string extension = tlsFile.extension().string(); + std::transform( + extension.begin(), + extension.end(), + extension.begin(), + [](unsigned char character) + { + return static_cast(std::tolower(character)); + }); + + if (!std::filesystem::is_regular_file(tlsFile)) + { + std::cerr << "TLS file does not exist or is not a regular file: " << tlsFile.string() << std::endl; + return 1; + } + + if (extension != ".las" && extension != ".laz") + { + std::cerr << "Unsupported TLS file format: " << tlsFile.string() << " (expected .las or .laz)" << std::endl; + return 1; + } + + const std::vector tlsPoints = mandeye::load(tlsFile.string()); + if (tlsPoints.empty()) + { + std::cerr << "Failed to load TLS point cloud: " << tlsFile.string() << std::endl; + return 1; + } + std::cout << "Loaded " << tlsPoints.size() << " points from " << tlsFile.string() << std::endl; + + const std::filesystem::path sessionDataFile{ argv[2] }; + + if (!std::filesystem::is_regular_file(sessionDataFile)) + { + std::cerr << "Session file does not exist or is not a regular file: " << sessionDataFile.string() << std::endl; + return 1; + } + + Session session; + if (!session.load(sessionDataFile.string(), /*is_decimate=*/false, 0.0, 0.0, 0.0, /*calculate_offset=*/false)) + { + std::cerr << "Failed to load session: " << sessionDataFile.string() << std::endl; return 1; } - return 0; + std::size_t sessionPointCount = 0; + for (const PointCloud& pointCloud : session.point_clouds_container.point_clouds) + { + sessionPointCount += pointCloud.points_local.size(); + } + std::cout << "Loaded session " << sessionDataFile.string() << " with " << session.point_clouds_container.point_clouds.size() + << " chunks and " << sessionPointCount << " points" << std::endl; + + const std::filesystem::path outputFile{ argv[3] }; + std::cout << "Output will be saved to: " << outputFile.string() << std::endl; + + ///////////////////////////////////////////////////////////////////////////////////////// + std::vector target_global; + + for (const auto& p : tlsPoints){ + target_global.emplace_back(p.point); + } + + for(const auto& pointCloud : session.point_clouds_container.point_clouds){ + std::vector source_local; + for(const auto& p : pointCloud.points_local){ + source_local.emplace_back(p); + } + + Eigen::Affine3d m_pose = pointCloud.m_pose; + + PairWiseICP icp; + icp.compute(source_local, target_global, 0.1, 1, m_pose); + } + + + + // session. + + /*PairWiseICP icp; + auto m_pose = affine_matrix_from_pose_tait_bryan(edges[index_active_edge].relative_pose_tb); + // std::vector source = point_clouds_container.point_clouds[edges[index_active_edge].index_to].points_local; + // std::vector target = point_clouds_container.point_clouds[edges[index_active_edge].index_from].points_local; + + //////////////////////////////// + std::vector source; + auto& e = edges[index_active_edge]; + for (int i = -num_edge_extended_before; i <= num_edge_extended_after; i++) + { + int index_src = e.index_to + i; + if (index_src >= 0 && index_src < point_clouds_container.point_clouds.size()) + { + Eigen::Affine3d m_src = point_clouds_container.point_clouds.at(index_src).m_pose; + for (int k = 0; k < point_clouds_container.point_clouds[index_src].points_local.size(); k++) + { + Eigen::Vector3d p_g = m_src * point_clouds_container.point_clouds[index_src].points_local[k]; + source.push_back(p_g); + } + // point_clouds_container.point_clouds.at(index_src).render(m_src, 1); + } + } + std::vector target; + + for (int i = -num_edge_extended_before; i <= num_edge_extended_after; i++) + { + int index_trg = e.index_from + i; + if (index_trg >= 0 && index_trg < point_clouds_container.point_clouds.size()) + { + Eigen::Affine3d m_trg = point_clouds_container.point_clouds.at(index_trg).m_pose; + for (int k = 0; k < point_clouds_container.point_clouds[index_trg].points_local.size(); k++) + { + Eigen::Vector3d p_g = m_trg * point_clouds_container.point_clouds[index_trg].points_local[k]; + target.push_back(p_g); + } + // point_clouds_container.point_clouds.at(index_src).render(m_src, 1); + } + } + + Eigen::Affine3d m_src_inv = point_clouds_container.point_clouds[e.index_to].m_pose.inverse(); + + for (auto& p : source) + { + p = m_src_inv * p; + } + + Eigen::Affine3d m_trg_inv = point_clouds_container.point_clouds[e.index_from].m_pose.inverse(); + + for (auto& p : target) + { + p = m_trg_inv * p; + } + //////////////////////////////// + + if (icp.compute(source, target, search_radius, number_of_iterations, m_pose)) + { + edges[index_active_edge].relative_pose_tb = pose_tait_bryan_from_affine_matrix(m_pose); + return true; + }*/ + + ////////////////////////////////////////////////////////////////////////////////////////// + + return 0; } \ No newline at end of file diff --git a/core/include/Core/pair_wise_iterative_closest_point.h b/core/include/Core/pair_wise_iterative_closest_point.h index 8e9db6348..99c5247bc 100644 --- a/core/include/Core/pair_wise_iterative_closest_point.h +++ b/core/include/Core/pair_wise_iterative_closest_point.h @@ -22,4 +22,9 @@ class PairWiseICP int number_of_iterations, Eigen::Affine3d& m_pose_result, int dec); + TaitBryanPose compute_icp_uncertainty( + const std::vector& source, + const std::vector& target, + const Eigen::Affine3d& m_pose_result, + double search_radious); }; diff --git a/core/src/color_las_loader.cpp b/core/src/color_las_loader.cpp index d74fafae5..137d1640d 100644 --- a/core/src/color_las_loader.cpp +++ b/core/src/color_las_loader.cpp @@ -7,37 +7,43 @@ std::vector mandeye::load(const std::string& lazFile) { std::vector points; - laszip_POINTER laszip_reader; + laszip_POINTER laszip_reader = nullptr; if (laszip_create(&laszip_reader)) { spdlog::error("DLL ERROR: creating laszip reader"); - std::abort(); + return points; } laszip_BOOL is_compressed = 0; if (laszip_open_reader(laszip_reader, lazFile.c_str(), &is_compressed)) { spdlog::error("DLL ERROR: opening laszip reader for '{}'", lazFile); - std::abort(); + laszip_destroy(laszip_reader); + return points; } - std::cout << "compressed : " << is_compressed << std::endl; - laszip_header* header; + spdlog::info("LAS file '{}' is {}", lazFile, is_compressed ? "compressed" : "uncompressed"); + laszip_header* header = nullptr; if (laszip_get_header_pointer(laszip_reader, &header)) { spdlog::error("DLL ERROR: getting header pointer from laszip reader"); - std::abort(); + laszip_close_reader(laszip_reader); + laszip_destroy(laszip_reader); + return points; } laszip_I64 npoints = (header->number_of_point_records ? header->number_of_point_records : header->extended_number_of_point_records); spdlog::info("file '{}' contains {} points", lazFile, npoints); - laszip_point* point; + laszip_point* point = nullptr; if (laszip_get_point_pointer(laszip_reader, &point)) { spdlog::error("DLL ERROR: getting point pointer from laszip reader"); + laszip_close_reader(laszip_reader); + laszip_destroy(laszip_reader); + return points; } laszip_I64 p_count = 0; @@ -47,6 +53,8 @@ std::vector mandeye::load(const std::string& lazFile) if (laszip_read_point(laszip_reader)) { spdlog::error("DLL ERROR: reading point {}", p_count); + points.clear(); + break; } Point p; @@ -61,6 +69,15 @@ std::vector mandeye::load(const std::string& lazFile) p_count++; } + if (laszip_close_reader(laszip_reader)) + { + spdlog::error("DLL ERROR: closing laszip reader for '{}'", lazFile); + } + if (laszip_destroy(laszip_reader)) + { + spdlog::error("DLL ERROR: destroying laszip reader"); + } + return points; } diff --git a/core/src/pair_wise_iterative_closest_point.cpp b/core/src/pair_wise_iterative_closest_point.cpp index 669b2d3d6..e4f34a25b 100644 --- a/core/src/pair_wise_iterative_closest_point.cpp +++ b/core/src/pair_wise_iterative_closest_point.cpp @@ -599,3 +599,284 @@ bool PairWiseICP::compute_fast( return true; } + +TaitBryanPose PairWiseICP::compute_icp_uncertainty( + const std::vector& source, + const std::vector& target, + const Eigen::Affine3d& m_pose_result, + double search_radious) +{ + bool multithread = true; + TaitBryanPose icp_uncertainty; + icp_uncertainty.px = 0; + icp_uncertainty.py = 0; + icp_uncertainty.pz = 0; + icp_uncertainty.om = 0; + icp_uncertainty.fi = 0; + icp_uncertainty.ka = 0; + + // The target and the search radius don't change between iterations, so its bucket index is built once. + std::vector> indexes; + + for (int i = 0; i < target.size(); i++) + { + uint64_t index = get_rgd_index_3d(target[i], { search_radious, search_radious, search_radious }); + indexes.emplace_back(index, i); + } + + // Ties broken by point index: std::sort leaves the order within a bucket to the standard library, and the + // search below skips each bucket's last point, so without this the result differs between platforms. + std::sort( + indexes.begin(), + indexes.end(), + [](const std::pair& a, const std::pair& b) + { + return a.first != b.first ? a.first < b.first : a.second < b.second; + }); + + std::unordered_map> buckets; + + for (uint32_t i = 0; i < indexes.size(); i++) + { + uint64_t index_of_bucket = indexes[i].first; + if (buckets.contains(index_of_bucket)) + { + buckets[index_of_bucket].second = i; + } + else + { + buckets[index_of_bucket].first = i; + buckets[index_of_bucket].second = i; + } + } + + // Target points in bucket order, so a bucket's points are read from contiguous memory. + std::vector target_sorted(indexes.size()); + for (size_t i = 0; i < indexes.size(); i++) + { + target_sorted[i] = target[indexes[i].second]; + } + const double search_radious_squared = search_radious * search_radious; + + // Normal equations are summed per block of source points, then the blocks in order: no lock per point, and + // the same sum on every run and machine. + struct NormalEquations + { + Eigen::Matrix AtPA = Eigen::Matrix::Zero(); + Eigen::Matrix AtPB = Eigen::Matrix::Zero(); + int counter_nn = 0; + }; + constexpr size_t number_of_blocks = 256; + const size_t block_size = (source.size() + number_of_blocks - 1) / number_of_blocks; + + for (int iter = 0; iter < number_of_iterations; iter++) + { + std::cout << "iteration: " << iter + 1 << " of: " << number_of_iterations << std::endl; + Eigen::MatrixXd AtPA(6, 6); + AtPA.setZero(); + Eigen::MatrixXd AtPB(6, 1); + AtPB.setZero(); + Eigen::Vector3d b(search_radious, search_radious, search_radious); + + const TaitBryanPose pose_s = pose_tait_bryan_from_affine_matrix(m_pose_result); + std::vector block_sums(number_of_blocks); + + const auto hessian_fun = [&](const Eigen::Vector3d& source_i, NormalEquations& sum) + { + if (source_i.norm() < 0.1) + { + return; + } + + Eigen::Vector3d source_point_global = m_pose_result * source_i; + + double min_dist_squared = 1000000000.0; + Eigen::Vector3d target_i_nn; + bool nn_found = false; + for (double x = -search_radious; x <= search_radious; x += search_radious) + { + for (double y = -search_radious; y <= search_radious; y += search_radious) + { + for (double z = -search_radious; z <= search_radious; z += search_radious) + { + Eigen::Vector3d source_point_global_ext = source_point_global + Eigen::Vector3d(x, y, z); + uint64_t index_of_bucket = + get_rgd_index_3d(source_point_global_ext, { search_radious, search_radious, search_radious }); + + const auto bucket = buckets.find(index_of_bucket); + if (bucket != buckets.end()) + { + for (int index = bucket->second.first; index <= bucket->second.second; index++) + { + const Eigen::Vector3d& target_i = target_sorted[index]; + const double d_squared = (source_point_global - target_i).squaredNorm(); + + if (d_squared < search_radious_squared) + { + if (d_squared < min_dist_squared) + { + min_dist_squared = d_squared; + nn_found = true; + target_i_nn = target_i; + } + /**/ + } + } + } + } + } + } + + if (nn_found) + { + const Eigen::Vector3d& p_s = source_i; + + Eigen::Matrix AtPA_; + point_to_point_source_to_target_tait_bryan_wc_AtPA_simplified( + AtPA_, + pose_s.px, + pose_s.py, + pose_s.pz, + pose_s.om, + pose_s.fi, + pose_s.ka, + p_s.x(), + p_s.y(), + p_s.z(), + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1); + + Eigen::Matrix AtPB_; + point_to_point_source_to_target_tait_bryan_wc_AtPB_simplified( + AtPB_, + pose_s.px, + pose_s.py, + pose_s.pz, + pose_s.om, + pose_s.fi, + pose_s.ka, + p_s.x(), + p_s.y(), + p_s.z(), + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1, + target_i_nn.x(), + target_i_nn.y(), + target_i_nn.z()); + + sum.AtPA += AtPA_; + sum.AtPB -= AtPB_; + sum.counter_nn++; + } + }; + + const auto block_fun = [&](NormalEquations& sum) + { + const size_t block = &sum - block_sums.data(); + const size_t begin = std::min(source.size(), block * block_size); + const size_t end = std::min(source.size(), begin + block_size); + for (size_t i = begin; i < end; i++) + { + hessian_fun(source[i], sum); + } + }; + + if (multithread) + { + // TBB rather than std::execution, which AppleClang's libc++ doesn't run in parallel. + tbb::parallel_for_each(block_sums.begin(), block_sums.end(), block_fun); + } + else + { + std::for_each(block_sums.begin(), block_sums.end(), block_fun); + } + + int counter_nn = 0; + for (const auto& sum : block_sums) + { + AtPA += sum.AtPA; + AtPB += sum.AtPB; + counter_nn += sum.counter_nn; + } + + if (AtPB(0, 0) == 0.0 && AtPB(1, 0) == 0.0 && AtPB(2, 0) == 0.0 && AtPB(3, 0) == 0.0 && AtPB(4, 0) == 0.0 && AtPB(5, 0) == 0.0) + { + std::cout + << "PairWiseICP::compute FAILED (Relative pose is not changed/solved/optimized --> please consider removing this edge)" + << std::endl; + return false; + } + + if (counter_nn < 100) + { + std::cout << "not suficient number of observations" << std::endl; + std::cout + << "PairWiseICP::compute FAILED (Relative pose is not changed/solved/optimized --> please consider removing this edge)" + << std::endl; + return false; + } + + Eigen::SparseMatrix AtPAc(6, 6); + Eigen::SparseMatrix AtPBc(6, 1); + + AtPAc = AtPA.sparseView(); + AtPBc = AtPB.sparseView(); + + Eigen::SparseMatrix AtPA_I(6, 6); + AtPA_I.setIdentity(); + AtPA += (AtPA_I * 100); + + Eigen::SimplicialCholesky> solver(AtPAc); + Eigen::SparseMatrix x = solver.solve(AtPBc); + std::vector h_x; + for (int k = 0; k < x.outerSize(); ++k) + { + std::cout << "result pose updates" << std::endl; + for (Eigen::SparseMatrix::InnerIterator it(x, k); it; ++it) + { + h_x.push_back(it.value()); + std::cout << it.row() << " " << it.col() << " " << it.value() << std::endl; + } + } + + if (h_x.size() == 6) + { + int counter = 0; + TaitBryanPose pose = pose_tait_bryan_from_affine_matrix(m_pose_result); + + pose.px += h_x[counter++]; + pose.py += h_x[counter++]; + pose.pz += h_x[counter++]; + pose.om += h_x[counter++]; + pose.fi += h_x[counter++]; + pose.ka += h_x[counter++]; + + m_pose_result = affine_matrix_from_pose_tait_bryan(pose); + std::cout << "PairWiseICP::compute SUCCESS" << std::endl; + // return true; + } + else + { + std::cout + << "PairWiseICP::compute FAILED (Relative pose is not changed/solved/optimized --> please consider removing this edge)" + << std::endl; + return false; + } + } + + return true; +} \ No newline at end of file From 6c19c0b069f35856e9b18f7512c6907a4fff5fce Mon Sep 17 00:00:00 2001 From: janusz Date: Sun, 22 Nov 2026 09:46:13 +0100 Subject: [PATCH 2/9] calculter uncertainty --- apps/session_uncertainty_calculation/main.cpp | 113 +++-- .../Core/pair_wise_iterative_closest_point.h | 2 + .../src/pair_wise_iterative_closest_point.cpp | 425 ++++++++++-------- 3 files changed, 307 insertions(+), 233 deletions(-) diff --git a/apps/session_uncertainty_calculation/main.cpp b/apps/session_uncertainty_calculation/main.cpp index 6beaf008d..605079ab7 100644 --- a/apps/session_uncertainty_calculation/main.cpp +++ b/apps/session_uncertainty_calculation/main.cpp @@ -5,7 +5,10 @@ #include #include #include +#include +#include #include +#include #include int main(int argc, char* argv[]) @@ -86,6 +89,10 @@ int main(int argc, char* argv[]) target_global.emplace_back(p.point); } + std::vector icp_uncertainties; + std::vector> node_timestamps; // + std::vector node_positions; + for(const auto& pointCloud : session.point_clouds_container.point_clouds){ std::vector source_local; for(const auto& p : pointCloud.points_local){ @@ -94,75 +101,65 @@ int main(int argc, char* argv[]) Eigen::Affine3d m_pose = pointCloud.m_pose; - PairWiseICP icp; - icp.compute(source_local, target_global, 0.1, 1, m_pose); - } + std::vector source_global; + for(const auto& p : source_local){ + source_global.emplace_back(m_pose * p); + } + for(const auto& n:pointCloud.local_trajectory){ + //std::cout << "Source Global Point: " << p.transpose() << std::endl; - // session. + Eigen::Affine3d m_global = m_pose * n.m_pose; - /*PairWiseICP icp; - auto m_pose = affine_matrix_from_pose_tait_bryan(edges[index_active_edge].relative_pose_tb); - // std::vector source = point_clouds_container.point_clouds[edges[index_active_edge].index_to].points_local; - // std::vector target = point_clouds_container.point_clouds[edges[index_active_edge].index_from].points_local; + Eigen::Affine3d m_local = m_global.inverse(); - //////////////////////////////// - std::vector source; - auto& e = edges[index_active_edge]; - for (int i = -num_edge_extended_before; i <= num_edge_extended_after; i++) - { - int index_src = e.index_to + i; - if (index_src >= 0 && index_src < point_clouds_container.point_clouds.size()) - { - Eigen::Affine3d m_src = point_clouds_container.point_clouds.at(index_src).m_pose; - for (int k = 0; k < point_clouds_container.point_clouds[index_src].points_local.size(); k++) - { - Eigen::Vector3d p_g = m_src * point_clouds_container.point_clouds[index_src].points_local[k]; - source.push_back(p_g); - } - // point_clouds_container.point_clouds.at(index_src).render(m_src, 1); - } - } - std::vector target; + std::vector source_local_for_single_trajectory_node; - for (int i = -num_edge_extended_before; i <= num_edge_extended_after; i++) - { - int index_trg = e.index_from + i; - if (index_trg >= 0 && index_trg < point_clouds_container.point_clouds.size()) - { - Eigen::Affine3d m_trg = point_clouds_container.point_clouds.at(index_trg).m_pose; - for (int k = 0; k < point_clouds_container.point_clouds[index_trg].points_local.size(); k++) - { - Eigen::Vector3d p_g = m_trg * point_clouds_container.point_clouds[index_trg].points_local[k]; - target.push_back(p_g); - } - // point_clouds_container.point_clouds.at(index_src).render(m_src, 1); + for(const auto& p : source_global){ + source_local_for_single_trajectory_node.emplace_back(m_local * p); } - } - - Eigen::Affine3d m_src_inv = point_clouds_container.point_clouds[e.index_to].m_pose.inverse(); - for (auto& p : source) - { - p = m_src_inv * p; + PairWiseICP icp; + TaitBryanPose icp_uncertainty = icp.compute_icp_uncertainty(source_local_for_single_trajectory_node, target_global, m_global, 0.1); + std::cout << "px=" << icp_uncertainty.px << ", " + << "py=" << icp_uncertainty.py << ", " + << "pz=" << icp_uncertainty.pz << ", " + << "om=" << icp_uncertainty.om << ", " + << "fi=" << icp_uncertainty.fi << ", " + << "ka=" << icp_uncertainty.ka + << std::endl; + + icp_uncertainties.emplace_back(icp_uncertainty); + node_timestamps.emplace_back(n.timestamps); + node_positions.emplace_back(m_global.translation()); } + } - Eigen::Affine3d m_trg_inv = point_clouds_container.point_clouds[e.index_from].m_pose.inverse(); - - for (auto& p : target) - { - p = m_trg_inv * p; - } - //////////////////////////////// + std::ofstream csv(outputFile); + if (!csv) + { + std::cerr << "Failed to open output file: " << outputFile.string() << std::endl; + return 1; + } - if (icp.compute(source, target, search_radius, number_of_iterations, m_pose)) - { - edges[index_active_edge].relative_pose_tb = pose_tait_bryan_from_affine_matrix(m_pose); - return true; - }*/ + // Standard deviations: sigma_px/py/pz in metres, sigma_om/fi/ka in radians (inf = pose not constrained). + csv << "timestamp_lidar,timestamp_unix,x,y,z,sigma_px,sigma_py,sigma_pz,sigma_om,sigma_fi,sigma_ka\n"; + csv << std::setprecision(std::numeric_limits::max_digits10); + for (size_t i = 0; i < icp_uncertainties.size(); i++) + { + const TaitBryanPose& u = icp_uncertainties[i]; + csv << node_timestamps[i].first << ',' << node_timestamps[i].second << ',' << node_positions[i].x() << ',' + << node_positions[i].y() << ',' << node_positions[i].z() << ',' << u.px << ',' << u.py << ',' << u.pz << ',' + << u.om << ',' << u.fi << ',' << u.ka << '\n'; + } - ////////////////////////////////////////////////////////////////////////////////////////// + if (!csv) + { + std::cerr << "Failed to write output file: " << outputFile.string() << std::endl; + return 1; + } + std::cout << "Saved " << icp_uncertainties.size() << " node uncertainties to " << outputFile.string() << std::endl; - return 0; + return 0; } \ No newline at end of file diff --git a/core/include/Core/pair_wise_iterative_closest_point.h b/core/include/Core/pair_wise_iterative_closest_point.h index 99c5247bc..009b08da8 100644 --- a/core/include/Core/pair_wise_iterative_closest_point.h +++ b/core/include/Core/pair_wise_iterative_closest_point.h @@ -1,5 +1,7 @@ #pragma once +#include + #include #include diff --git a/core/src/pair_wise_iterative_closest_point.cpp b/core/src/pair_wise_iterative_closest_point.cpp index e4f34a25b..8ddec6d1b 100644 --- a/core/src/pair_wise_iterative_closest_point.cpp +++ b/core/src/pair_wise_iterative_closest_point.cpp @@ -7,6 +7,9 @@ #include +#include +#include + #include inline void point_to_point_source_to_target_tait_bryan_wc_AtPA_simplified_4( @@ -600,6 +603,54 @@ bool PairWiseICP::compute_fast( return true; } +namespace +{ + //! Standard deviations of the pose parameters (px, py, pz in metres; om, fi, ka in radians) from the point-to-point + //! normal matrix AtPA = J^T J (unit weights). Covariance = sigma0^2 * AtPA^-1, where the variance factor + //! sigma0^2 = sum of squared residuals / (3 * number_of_correspondences - 6). Returns infinity for every parameter + //! when the problem is degenerate (e.g. a corridor or a plane leaves a direction unconstrained). + TaitBryanPose compute_icp_uncertainty_from_hessian( + const Eigen::Matrix& AtPA, int number_of_correspondences, double sum_squared_residuals) + { + constexpr double inf = std::numeric_limits::infinity(); + TaitBryanPose sigma; + sigma.px = sigma.py = sigma.pz = sigma.om = sigma.fi = sigma.ka = inf; + + // Each correspondence gives 3 observations (x, y, z); the pose has 6 unknowns. + const int redundancy = 3 * number_of_correspondences - 6; + if (redundancy <= 0) + { + return sigma; + } + + // AtPA is symmetric positive semi-definite; the eigen decomposition exposes unconstrained directions. + const Eigen::SelfAdjointEigenSolver> eigen_solver(AtPA); + if (eigen_solver.info() != Eigen::Success) + { + return sigma; + } + const Eigen::Matrix& eigenvalues = eigen_solver.eigenvalues(); // ascending + if (eigenvalues(0) <= 1e-12 * eigenvalues(5)) + { + std::cout << "compute_icp_uncertainty_from_hessian: degenerate geometry, pose not fully constrained" << std::endl; + return sigma; + } + + const double sigma0_squared = sum_squared_residuals / redundancy; + const Eigen::Matrix& V = eigen_solver.eigenvectors(); + const Eigen::Matrix covariance = + sigma0_squared * V * eigenvalues.cwiseInverse().asDiagonal() * V.transpose(); + + sigma.px = std::sqrt(covariance(0, 0)); + sigma.py = std::sqrt(covariance(1, 1)); + sigma.pz = std::sqrt(covariance(2, 2)); + sigma.om = std::sqrt(covariance(3, 3)); + sigma.fi = std::sqrt(covariance(4, 4)); + sigma.ka = std::sqrt(covariance(5, 5)); + return sigma; + } +} // namespace + TaitBryanPose PairWiseICP::compute_icp_uncertainty( const std::vector& source, const std::vector& target, @@ -663,220 +714,244 @@ TaitBryanPose PairWiseICP::compute_icp_uncertainty( struct NormalEquations { Eigen::Matrix AtPA = Eigen::Matrix::Zero(); - Eigen::Matrix AtPB = Eigen::Matrix::Zero(); + //Eigen::Matrix AtPB = Eigen::Matrix::Zero(); + double sum_squared_residuals = 0.0; int counter_nn = 0; }; constexpr size_t number_of_blocks = 256; const size_t block_size = (source.size() + number_of_blocks - 1) / number_of_blocks; - for (int iter = 0; iter < number_of_iterations; iter++) - { - std::cout << "iteration: " << iter + 1 << " of: " << number_of_iterations << std::endl; - Eigen::MatrixXd AtPA(6, 6); - AtPA.setZero(); - Eigen::MatrixXd AtPB(6, 1); - AtPB.setZero(); - Eigen::Vector3d b(search_radious, search_radious, search_radious); + + //std::cout << "iteration: " << iter + 1 << " of: " << number_of_iterations << std::endl; + Eigen::MatrixXd AtPA(6, 6); + AtPA.setZero(); + //Eigen::MatrixXd AtPB(6, 1); + //AtPB.setZero(); + //Eigen::Vector3d b(search_radious, search_radious, search_radious); - const TaitBryanPose pose_s = pose_tait_bryan_from_affine_matrix(m_pose_result); - std::vector block_sums(number_of_blocks); + const TaitBryanPose pose_s = pose_tait_bryan_from_affine_matrix(m_pose_result); + std::vector block_sums(number_of_blocks); - const auto hessian_fun = [&](const Eigen::Vector3d& source_i, NormalEquations& sum) + const auto hessian_fun = [&](const Eigen::Vector3d& source_i, NormalEquations& sum) + { + if (source_i.norm() < 0.1) { - if (source_i.norm() < 0.1) - { - return; - } + return; + } - Eigen::Vector3d source_point_global = m_pose_result * source_i; + Eigen::Vector3d source_point_global = m_pose_result * source_i; - double min_dist_squared = 1000000000.0; - Eigen::Vector3d target_i_nn; - bool nn_found = false; - for (double x = -search_radious; x <= search_radious; x += search_radious) + double min_dist_squared = 1000000000.0; + Eigen::Vector3d target_i_nn; + bool nn_found = false; + for (double x = -search_radious; x <= search_radious; x += search_radious) + { + for (double y = -search_radious; y <= search_radious; y += search_radious) { - for (double y = -search_radious; y <= search_radious; y += search_radious) + for (double z = -search_radious; z <= search_radious; z += search_radious) { - for (double z = -search_radious; z <= search_radious; z += search_radious) - { - Eigen::Vector3d source_point_global_ext = source_point_global + Eigen::Vector3d(x, y, z); - uint64_t index_of_bucket = - get_rgd_index_3d(source_point_global_ext, { search_radious, search_radious, search_radious }); + Eigen::Vector3d source_point_global_ext = source_point_global + Eigen::Vector3d(x, y, z); + uint64_t index_of_bucket = + get_rgd_index_3d(source_point_global_ext, { search_radious, search_radious, search_radious }); - const auto bucket = buckets.find(index_of_bucket); - if (bucket != buckets.end()) + const auto bucket = buckets.find(index_of_bucket); + if (bucket != buckets.end()) + { + for (int index = bucket->second.first; index <= bucket->second.second; index++) { - for (int index = bucket->second.first; index <= bucket->second.second; index++) - { - const Eigen::Vector3d& target_i = target_sorted[index]; - const double d_squared = (source_point_global - target_i).squaredNorm(); + const Eigen::Vector3d& target_i = target_sorted[index]; + const double d_squared = (source_point_global - target_i).squaredNorm(); - if (d_squared < search_radious_squared) + if (d_squared < search_radious_squared) + { + if (d_squared < min_dist_squared) { - if (d_squared < min_dist_squared) - { - min_dist_squared = d_squared; - nn_found = true; - target_i_nn = target_i; - } - /**/ + min_dist_squared = d_squared; + nn_found = true; + target_i_nn = target_i; } + /**/ } } } } } + } - if (nn_found) - { - const Eigen::Vector3d& p_s = source_i; + if (nn_found) + { + const Eigen::Vector3d& p_s = source_i; + + Eigen::Matrix AtPA_; + point_to_point_source_to_target_tait_bryan_wc_AtPA_simplified( + AtPA_, + pose_s.px, + pose_s.py, + pose_s.pz, + pose_s.om, + pose_s.fi, + pose_s.ka, + p_s.x(), + p_s.y(), + p_s.z(), + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1); + + Eigen::Matrix AtPB_; + point_to_point_source_to_target_tait_bryan_wc_AtPB_simplified( + AtPB_, + pose_s.px, + pose_s.py, + pose_s.pz, + pose_s.om, + pose_s.fi, + pose_s.ka, + p_s.x(), + p_s.y(), + p_s.z(), + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1, + target_i_nn.x(), + target_i_nn.y(), + target_i_nn.z()); + + sum.AtPA += AtPA_; + //sum.AtPB -= AtPB_; + sum.sum_squared_residuals += min_dist_squared; + sum.counter_nn++; + } + }; - Eigen::Matrix AtPA_; - point_to_point_source_to_target_tait_bryan_wc_AtPA_simplified( - AtPA_, - pose_s.px, - pose_s.py, - pose_s.pz, - pose_s.om, - pose_s.fi, - pose_s.ka, - p_s.x(), - p_s.y(), - p_s.z(), - 1, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 1); + const auto block_fun = [&](NormalEquations& sum) + { + const size_t block = &sum - block_sums.data(); + const size_t begin = std::min(source.size(), block * block_size); + const size_t end = std::min(source.size(), begin + block_size); + for (size_t i = begin; i < end; i++) + { + hessian_fun(source[i], sum); + } + }; - Eigen::Matrix AtPB_; - point_to_point_source_to_target_tait_bryan_wc_AtPB_simplified( - AtPB_, - pose_s.px, - pose_s.py, - pose_s.pz, - pose_s.om, - pose_s.fi, - pose_s.ka, - p_s.x(), - p_s.y(), - p_s.z(), - 1, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 1, - target_i_nn.x(), - target_i_nn.y(), - target_i_nn.z()); + if (multithread) + { + // TBB rather than std::execution, which AppleClang's libc++ doesn't run in parallel. + tbb::parallel_for_each(block_sums.begin(), block_sums.end(), block_fun); + } + else + { + std::for_each(block_sums.begin(), block_sums.end(), block_fun); + } - sum.AtPA += AtPA_; - sum.AtPB -= AtPB_; - sum.counter_nn++; - } - }; + int counter_nn = 0; + double sum_squared_residuals = 0.0; + for (const auto& sum : block_sums) + { + AtPA += sum.AtPA; + //AtPB += sum.AtPB; + sum_squared_residuals += sum.sum_squared_residuals; + counter_nn += sum.counter_nn; + } - const auto block_fun = [&](NormalEquations& sum) - { - const size_t block = &sum - block_sums.data(); - const size_t begin = std::min(source.size(), block * block_size); - const size_t end = std::min(source.size(), begin + block_size); - for (size_t i = begin; i < end; i++) - { - hessian_fun(source[i], sum); - } - }; + //if (AtPB(0, 0) == 0.0 && AtPB(1, 0) == 0.0 && AtPB(2, 0) == 0.0 && AtPB(3, 0) == 0.0 && AtPB(4, 0) == 0.0 && AtPB(5, 0) == 0.0) + //{ + // std::cout + // << "PairWiseICP::compute FAILED (Relative pose is not changed/solved/optimized --> please consider removing this edge)" + // << std::endl; + // return icp_uncertainty; + //} - if (multithread) - { - // TBB rather than std::execution, which AppleClang's libc++ doesn't run in parallel. - tbb::parallel_for_each(block_sums.begin(), block_sums.end(), block_fun); - } - else - { - std::for_each(block_sums.begin(), block_sums.end(), block_fun); - } + if (counter_nn < 100) + { + std::cout << "not suficient number of observations" << std::endl; + std::cout + << "PairWiseICP::compute FAILED (Relative pose is not changed/solved/optimized --> please consider removing this edge)" + << std::endl; + return icp_uncertainty; + } - int counter_nn = 0; - for (const auto& sum : block_sums) - { - AtPA += sum.AtPA; - AtPB += sum.AtPB; - counter_nn += sum.counter_nn; - } + /* + I added compute_icp_uncertainty_from_hessian to pair_wise_iterative_closest_point.cpp. - if (AtPB(0, 0) == 0.0 && AtPB(1, 0) == 0.0 && AtPB(2, 0) == 0.0 && AtPB(3, 0) == 0.0 && AtPB(4, 0) == 0.0 && AtPB(5, 0) == 0.0) - { - std::cout - << "PairWiseICP::compute FAILED (Relative pose is not changed/solved/optimized --> please consider removing this edge)" - << std::endl; - return false; - } + How it works: - if (counter_nn < 100) - { - std::cout << "not suficient number of observations" << std::endl; - std::cout - << "PairWiseICP::compute FAILED (Relative pose is not changed/solved/optimized --> please consider removing this edge)" - << std::endl; - return false; - } + Covariance: it computes covariance = σ₀² · (AᵀPA)⁻¹ and returns the square root of each diagonal entry as a TaitBryanPose. px/py/pz are in metres and om/fi/ka in radians. + Scale factor: σ₀² = sum of squared residuals / (3·n − 6). Each match gives 3 observations and the pose has 6 unknowns. + Matrix inverse: it inverts through an eigen decomposition, which shows when the geometry leaves a direction unconstrained (a plane, a corridor). If the smallest eigenvalue is below 1e-12 of the largest, it prints a warning and returns infinity for every parameter. + Other changes: - Eigen::SparseMatrix AtPAc(6, 6); - Eigen::SparseMatrix AtPBc(6, 1); + Extra parameter: the Hessian only gives the shape of the uncertainty, not its size, so the function needs the residuals too. The call is now compute_icp_uncertainty_from_hessian(AtPA, counter_nn, sum_squared_residuals). + Residual sum: NormalEquations gets a sum_squared_residuals field. Each match adds its min_dist_squared, and the block sums are added up alongside AtPA. + Includes: added and . + Things to check: - AtPAc = AtPA.sparseView(); - AtPBc = AtPB.sparseView(); + Wasted work: hessian_fun still calls point_to_point_source_to_target_tait_bryan_wc_AtPB_simplified for every point and never uses the result. You can delete that call. + Over-confident result: neighbouring LiDAR points are correlated, so this formal covariance tends to make the uncertainty look smaller than it really is. It's fine for comparing edges with each other, but don't read it as an absolute error. + */ + icp_uncertainty = compute_icp_uncertainty_from_hessian(AtPA, counter_nn, sum_squared_residuals); - Eigen::SparseMatrix AtPA_I(6, 6); - AtPA_I.setIdentity(); - AtPA += (AtPA_I * 100); - Eigen::SimplicialCholesky> solver(AtPAc); - Eigen::SparseMatrix x = solver.solve(AtPBc); - std::vector h_x; - for (int k = 0; k < x.outerSize(); ++k) - { - std::cout << "result pose updates" << std::endl; - for (Eigen::SparseMatrix::InnerIterator it(x, k); it; ++it) - { - h_x.push_back(it.value()); - std::cout << it.row() << " " << it.col() << " " << it.value() << std::endl; - } - } + /*Eigen::SparseMatrix AtPAc(6, 6); + Eigen::SparseMatrix AtPBc(6, 1); - if (h_x.size() == 6) - { - int counter = 0; - TaitBryanPose pose = pose_tait_bryan_from_affine_matrix(m_pose_result); + AtPAc = AtPA.sparseView(); + AtPBc = AtPB.sparseView(); - pose.px += h_x[counter++]; - pose.py += h_x[counter++]; - pose.pz += h_x[counter++]; - pose.om += h_x[counter++]; - pose.fi += h_x[counter++]; - pose.ka += h_x[counter++]; + Eigen::SparseMatrix AtPA_I(6, 6); + AtPA_I.setIdentity(); + AtPA += (AtPA_I * 100); - m_pose_result = affine_matrix_from_pose_tait_bryan(pose); - std::cout << "PairWiseICP::compute SUCCESS" << std::endl; - // return true; - } - else + Eigen::SimplicialCholesky> solver(AtPAc); + Eigen::SparseMatrix x = solver.solve(AtPBc); + std::vector h_x; + for (int k = 0; k < x.outerSize(); ++k) + { + std::cout << "result pose updates" << std::endl; + for (Eigen::SparseMatrix::InnerIterator it(x, k); it; ++it) { - std::cout - << "PairWiseICP::compute FAILED (Relative pose is not changed/solved/optimized --> please consider removing this edge)" - << std::endl; - return false; + h_x.push_back(it.value()); + std::cout << it.row() << " " << it.col() << " " << it.value() << std::endl; } - } + }*/ - return true; + /*if (h_x.size() == 6) + { + int counter = 0; + TaitBryanPose pose = pose_tait_bryan_from_affine_matrix(m_pose_result); + + pose.px += h_x[counter++]; + pose.py += h_x[counter++]; + pose.pz += h_x[counter++]; + pose.om += h_x[counter++]; + pose.fi += h_x[counter++]; + pose.ka += h_x[counter++]; + + //m_pose_result = affine_matrix_from_pose_tait_bryan(pose); + std::cout << "PairWiseICP::compute SUCCESS" << std::endl; + // return true; + } + else + { + std::cout + << "PairWiseICP::compute FAILED (Relative pose is not changed/solved/optimized --> please consider removing this edge)" + << std::endl; + return icp_uncertainty; + }*/ + + + return icp_uncertainty; } \ No newline at end of file From c6893daa4646aa4a20190ef9fa7dfa57be94baaf Mon Sep 17 00:00:00 2001 From: janusz Date: Sun, 22 Nov 2026 10:44:55 +0100 Subject: [PATCH 3/9] cleaning icp --- .../multi_view_tls_registration_gui.cpp | 288 ++++++------ .../Core/pair_wise_iterative_closest_point.h | 7 - .../src/pair_wise_iterative_closest_point.cpp | 440 +----------------- 3 files changed, 168 insertions(+), 567 deletions(-) diff --git a/apps/multi_view_tls_registration/multi_view_tls_registration_gui.cpp b/apps/multi_view_tls_registration/multi_view_tls_registration_gui.cpp index e9eac35cb..e663225d2 100644 --- a/apps/multi_view_tls_registration/multi_view_tls_registration_gui.cpp +++ b/apps/multi_view_tls_registration/multi_view_tls_registration_gui.cpp @@ -3768,184 +3768,190 @@ void settings_gui() ImGui::SetTooltip(zText); ImGui::PopItemWidth(); - ImGui::Separator(); - // common_data - // manual_pose_graph_loop_closure_mode + static bool hide_lecacy = true; + ImGui::Checkbox("Hide legacy functions", &hide_lecacy); - if (ImGui::Button("Load RESSO file (transformation_GroundTruth.reg)")) - { - std::string input_file_name = ""; - input_file_name = mandeye::fd::OpenFileDialogOneFile("Load RESSO", mandeye::fd::Resso_filter); - spdlog::info("RESSO file: '{}'", input_file_name); + if(!hide_lecacy){ - if (input_file_name.size() > 0) + ImGui::Separator(); + // common_data + // manual_pose_graph_loop_closure_mode + + if (ImGui::Button("Load RESSO file (transformation_GroundTruth.reg)")) { - session.working_directory = fs::path(input_file_name).parent_path().string(); - - if (!session.point_clouds_container.load( - session.working_directory.c_str(), - input_file_name.c_str(), - tls_registration.is_decimate, - tls_registration.bucket_x, - tls_registration.bucket_y, - tls_registration.bucket_z, - session.load_cache_mode)) + std::string input_file_name = ""; + input_file_name = mandeye::fd::OpenFileDialogOneFile("Load RESSO", mandeye::fd::Resso_filter); + spdlog::info("RESSO file: '{}'", input_file_name); + + if (input_file_name.size() > 0) { - spdlog::error("Error loading file!"); - return; + session.working_directory = fs::path(input_file_name).parent_path().string(); + + if (!session.point_clouds_container.load( + session.working_directory.c_str(), + input_file_name.c_str(), + tls_registration.is_decimate, + tls_registration.bucket_x, + tls_registration.bucket_y, + tls_registration.bucket_z, + session.load_cache_mode)) + { + spdlog::error("Error loading file!"); + return; + } + else + spdlog::info("Loaded: {} point_clouds", session.point_clouds_container.point_clouds.size()); } - else - spdlog::info("Loaded: {} point_clouds", session.point_clouds_container.point_clouds.size()); } - } - ImGui::SameLine(); - if (ImGui::Button("Save RESSO file")) - { - const auto output_file_name = mandeye::fd::SaveFileDialog("Save RESSO file", mandeye::fd::Resso_filter); - spdlog::info("RESSO file to save: '{}'", output_file_name); - if (output_file_name.size() > 0) - session.point_clouds_container.save_poses(fs::path(output_file_name).string(), false); - } - ImGui::Text("RESSO dataset: "); - ImGui::SameLine(); - ImGuiHyperlink("https://3d.bk.tudelft.nl/liangliang/publications/2019/plade/resso.html"); + ImGui::SameLine(); + if (ImGui::Button("Save RESSO file")) + { + const auto output_file_name = mandeye::fd::SaveFileDialog("Save RESSO file", mandeye::fd::Resso_filter); + spdlog::info("RESSO file to save: '{}'", output_file_name); + if (output_file_name.size() > 0) + session.point_clouds_container.save_poses(fs::path(output_file_name).string(), false); + } + ImGui::Text("RESSO dataset: "); + ImGui::SameLine(); + ImGuiHyperlink("https://3d.bk.tudelft.nl/liangliang/publications/2019/plade/resso.html"); - ImGui::NewLine(); + ImGui::NewLine(); - if (ImGui::Button("Load ETH file (pairs.txt)")) - { - std::string input_file_name = ""; - input_file_name = mandeye::fd::OpenFileDialogOneFile("Load ETH file", {}); - if (input_file_name.size() > 0) + if (ImGui::Button("Load ETH file (pairs.txt)")) { - session.working_directory = fs::path(input_file_name).parent_path().string(); - - if (!session.point_clouds_container.load_eth( - session.working_directory.c_str(), - input_file_name.c_str(), - tls_registration.is_decimate, - tls_registration.bucket_x, - tls_registration.bucket_y, - tls_registration.bucket_z)) + std::string input_file_name = ""; + input_file_name = mandeye::fd::OpenFileDialogOneFile("Load ETH file", {}); + if (input_file_name.size() > 0) { - spdlog::error("Error loading file!"); - return; + session.working_directory = fs::path(input_file_name).parent_path().string(); + + if (!session.point_clouds_container.load_eth( + session.working_directory.c_str(), + input_file_name.c_str(), + tls_registration.is_decimate, + tls_registration.bucket_x, + tls_registration.bucket_y, + tls_registration.bucket_z)) + { + spdlog::error("Error loading file!"); + return; + } + else + spdlog::info("Loaded: {} point_clouds", session.point_clouds_container.point_clouds.size()); } - else - spdlog::info("Loaded: {} point_clouds", session.point_clouds_container.point_clouds.size()); } - } - ImGui::Text("ETH dataset: "); - ImGui::SameLine(); - ImGuiHyperlink("https://prs.igp.ethz.ch/research/completed_projects/automatic_registration_of_point_clouds.html"); - - ImGui::NewLine(); + ImGui::Text("ETH dataset: "); + ImGui::SameLine(); + ImGuiHyperlink("https://prs.igp.ethz.ch/research/completed_projects/automatic_registration_of_point_clouds.html"); - if (ImGui::Button("Load 3DTK files (select all *.txt files)")) - { - session.point_clouds_container.point_clouds.clear(); - std::vector input_file_names; - input_file_names = mandeye::fd::OpenFileDialog("Load txt files", {}, true); + ImGui::NewLine(); - if (input_file_names.size() > 0) + if (ImGui::Button("Load 3DTK files (select all *.txt files)")) { - session.working_directory = fs::path(input_file_names[0]).parent_path().string(); - - spdlog::info("TXT files:"); - for (size_t i = 0; i < input_file_names.size(); i++) - spdlog::info("{}", input_file_names[i]); - - if (!session.point_clouds_container.load_3DTK_tls( - input_file_names, - tls_registration.is_decimate, - tls_registration.bucket_x, - tls_registration.bucket_y, - tls_registration.bucket_z)) + session.point_clouds_container.point_clouds.clear(); + std::vector input_file_names; + input_file_names = mandeye::fd::OpenFileDialog("Load txt files", {}, true); + + if (input_file_names.size() > 0) { - spdlog::error("Error loading file!"); - return; + session.working_directory = fs::path(input_file_names[0]).parent_path().string(); + + spdlog::info("TXT files:"); + for (size_t i = 0; i < input_file_names.size(); i++) + spdlog::info("{}", input_file_names[i]); + + if (!session.point_clouds_container.load_3DTK_tls( + input_file_names, + tls_registration.is_decimate, + tls_registration.bucket_x, + tls_registration.bucket_y, + tls_registration.bucket_z)) + { + spdlog::error("Error loading file!"); + return; + } + else + spdlog::info("Loaded: {} point_clouds", session.point_clouds_container.point_clouds.size()); } - else - spdlog::info("Loaded: {} point_clouds", session.point_clouds_container.point_clouds.size()); } - } - ImGui::Text("3DTK dataset (18: the campus of the Jacobs University Bremen)"); - ImGui::SameLine(); - ImGuiHyperlink("http://kos.informatik.uni-osnabrueck.de/3Dscans/"); + ImGui::Text("3DTK dataset (18: the campus of the Jacobs University Bremen)"); + ImGui::SameLine(); + ImGuiHyperlink("http://kos.informatik.uni-osnabrueck.de/3Dscans/"); - ImGui::NewLine(); + ImGui::NewLine(); - if (ImGui::Button("Update initial poses from RESSO file")) - { - std::string input_file_name; - input_file_name = mandeye::fd::OpenFileDialogOneFile("Load RESSO file", {}); - if (input_file_name.size() > 0) + if (ImGui::Button("Update initial poses from RESSO file")) { - session.working_directory = fs::path(input_file_name).parent_path().string(); - - if (!session.point_clouds_container.update_initial_poses_from_RESSO( - session.working_directory.c_str(), input_file_name.c_str())) - { - spdlog::error("Error loading file!"); - return; - } - else + std::string input_file_name; + input_file_name = mandeye::fd::OpenFileDialogOneFile("Load RESSO file", {}); + if (input_file_name.size() > 0) { - session.point_clouds_container.initial_poses_file_name = input_file_name; - spdlog::info("Updated: {} point_clouds", session.point_clouds_container.point_clouds.size()); + session.working_directory = fs::path(input_file_name).parent_path().string(); + + if (!session.point_clouds_container.update_initial_poses_from_RESSO( + session.working_directory.c_str(), input_file_name.c_str())) + { + spdlog::error("Error loading file!"); + return; + } + else + { + session.point_clouds_container.initial_poses_file_name = input_file_name; + spdlog::info("Updated: {} point_clouds", session.point_clouds_container.point_clouds.size()); + } } } - } - ImGui::SameLine(); - ImGui::Text(session.point_clouds_container.initial_poses_file_name.c_str()); - - if (ImGui::Button("Update poses from RESSO file")) - { - std::string input_file_name; - input_file_name = mandeye::fd::OpenFileDialogOneFile("Load RESSO file", {}); + ImGui::SameLine(); + ImGui::Text(session.point_clouds_container.initial_poses_file_name.c_str()); - if (input_file_name.size() > 0) + if (ImGui::Button("Update poses from RESSO file")) { - session.working_directory = fs::path(input_file_name).parent_path().string(); + std::string input_file_name; + input_file_name = mandeye::fd::OpenFileDialogOneFile("Load RESSO file", {}); - if (!session.point_clouds_container.update_poses_from_RESSO(session.working_directory.c_str(), input_file_name.c_str())) - { - spdlog::error("Error loading file!"); - return; - } - else + if (input_file_name.size() > 0) { - spdlog::info("Updated: {} point_clouds", session.point_clouds_container.point_clouds.size()); - session.point_clouds_container.poses_file_name = input_file_name; + session.working_directory = fs::path(input_file_name).parent_path().string(); + + if (!session.point_clouds_container.update_poses_from_RESSO(session.working_directory.c_str(), input_file_name.c_str())) + { + spdlog::error("Error loading file!"); + return; + } + else + { + spdlog::info("Updated: {} point_clouds", session.point_clouds_container.point_clouds.size()); + session.point_clouds_container.poses_file_name = input_file_name; + } } } - } - ImGui::SameLine(); - - if (ImGui::Button("Update poses from RESSO file (inverse)")) - { - std::string input_file_name; - input_file_name = mandeye::fd::OpenFileDialogOneFile("Load RESSO file", {}); + ImGui::SameLine(); - if (input_file_name.size() > 0) + if (ImGui::Button("Update poses from RESSO file (inverse)")) { - session.working_directory = fs::path(input_file_name).parent_path().string(); + std::string input_file_name; + input_file_name = mandeye::fd::OpenFileDialogOneFile("Load RESSO file", {}); - if (!session.point_clouds_container.update_poses_from_RESSO_inverse( - session.working_directory.c_str(), input_file_name.c_str())) + if (input_file_name.size() > 0) { - spdlog::error("Error loading file!"); - return; - } - else - { - spdlog::info("Updated: {} point_clouds", session.point_clouds_container.point_clouds.size()); - session.point_clouds_container.poses_file_name = input_file_name; + session.working_directory = fs::path(input_file_name).parent_path().string(); + + if (!session.point_clouds_container.update_poses_from_RESSO_inverse( + session.working_directory.c_str(), input_file_name.c_str())) + { + spdlog::error("Error loading file!"); + return; + } + else + { + spdlog::info("Updated: {} point_clouds", session.point_clouds_container.point_clouds.size()); + session.point_clouds_container.poses_file_name = input_file_name; + } } } + ImGui::SameLine(); + ImGui::Text(session.point_clouds_container.poses_file_name.c_str()); } - ImGui::SameLine(); - ImGui::Text(session.point_clouds_container.poses_file_name.c_str()); ImGui::Separator(); diff --git a/core/include/Core/pair_wise_iterative_closest_point.h b/core/include/Core/pair_wise_iterative_closest_point.h index 009b08da8..1ad790e55 100644 --- a/core/include/Core/pair_wise_iterative_closest_point.h +++ b/core/include/Core/pair_wise_iterative_closest_point.h @@ -17,13 +17,6 @@ class PairWiseICP double search_radious, int number_of_iterations, Eigen::Affine3d& m_pose_result); - bool compute_fast( - const std::vector& source, - const std::vector& target, - double search_radious, - int number_of_iterations, - Eigen::Affine3d& m_pose_result, - int dec); TaitBryanPose compute_icp_uncertainty( const std::vector& source, const std::vector& target, diff --git a/core/src/pair_wise_iterative_closest_point.cpp b/core/src/pair_wise_iterative_closest_point.cpp index 8ddec6d1b..cb67d8c7b 100644 --- a/core/src/pair_wise_iterative_closest_point.cpp +++ b/core/src/pair_wise_iterative_closest_point.cpp @@ -12,133 +12,6 @@ #include -inline void point_to_point_source_to_target_tait_bryan_wc_AtPA_simplified_4( - Eigen::Matrix& AtPA, - const double& tx, - const double& ty, - const double& tz, - const double& om, - const double& fi, - const double& ka, - const double& x_s, - const double& y_s, - const double& z_s) -{ - double sin_om = sin(om); - double cos_om = cos(om); - double sin_fi = sin(fi); - double cos_fi = cos(fi); - double sin_ka = sin(ka); - double cos_ka = cos(ka); - double x0 = cos_fi * z_s; - double x1 = sin_ka * y_s; - double x2 = cos_ka * x_s; - double x3 = sin_fi * x1 - sin_fi * x2 + x0; - double x4 = cos_ka * y_s + sin_ka * x_s; - double x5 = -cos_fi * x4; - double x6 = cos_ka * sin_om; - double x7 = cos_om * sin_ka; - double x8 = sin_fi * x7 + x6; - double x9 = sin_ka * sin_om; - double x10 = cos_ka * cos_om; - double x11 = sin_fi * x10 - x9; - double x12 = cos_om * x0 - x11 * x_s + x8 * y_s; - double x13 = -x12; - double x14 = -cos_fi * x1 + cos_fi * x2 + sin_fi * z_s; - double x15 = sin_om * x14; - double x16 = -sin_fi * x9 + x10; - double x17 = sin_fi * x6 + x7; - double x18 = x16 * x_s - x17 * y_s; - double x19 = -sin_om * x0 + x16 * y_s + x17 * x_s; - double x20 = -cos_om * x14; - double x21 = x11 * y_s + x8 * x_s; - double x22 = x14 * (-cos_om * x19 - sin_om * x12); - double x23 = -x12 * x18 + x19 * x21; - double x24 = pow(x14, 2); - double x25 = -cos_fi * x3 * x4 - cos_om * x14 * x21 + sin_om * x14 * x18; - AtPA.coeffRef(0, 0) = 1; - AtPA.coeffRef(0, 1) = 0; - AtPA.coeffRef(0, 2) = 0; - AtPA.coeffRef(0, 3) = 0; - AtPA.coeffRef(0, 4) = x3; - AtPA.coeffRef(0, 5) = x5; - AtPA.coeffRef(1, 0) = 0; - AtPA.coeffRef(1, 1) = 1; - AtPA.coeffRef(1, 2) = 0; - AtPA.coeffRef(1, 3) = x13; - AtPA.coeffRef(1, 4) = x15; - AtPA.coeffRef(1, 5) = x18; - AtPA.coeffRef(2, 0) = 0; - AtPA.coeffRef(2, 1) = 0; - AtPA.coeffRef(2, 2) = 1; - AtPA.coeffRef(2, 3) = x19; - AtPA.coeffRef(2, 4) = x20; - AtPA.coeffRef(2, 5) = x21; - AtPA.coeffRef(3, 0) = 0; - AtPA.coeffRef(3, 1) = x13; - AtPA.coeffRef(3, 2) = x19; - AtPA.coeffRef(3, 3) = pow(x12, 2) + pow(x19, 2); - AtPA.coeffRef(3, 4) = x22; - AtPA.coeffRef(3, 5) = x23; - AtPA.coeffRef(4, 0) = x3; - AtPA.coeffRef(4, 1) = x15; - AtPA.coeffRef(4, 2) = x20; - AtPA.coeffRef(4, 3) = x22; - AtPA.coeffRef(4, 4) = pow(cos_om, 2) * x24 + pow(sin_om, 2) * x24 + pow(x3, 2); - AtPA.coeffRef(4, 5) = x25; - AtPA.coeffRef(5, 0) = x5; - AtPA.coeffRef(5, 1) = x18; - AtPA.coeffRef(5, 2) = x21; - AtPA.coeffRef(5, 3) = x23; - AtPA.coeffRef(5, 4) = x25; - AtPA.coeffRef(5, 5) = pow(cos_fi, 2) * pow(x4, 2) + pow(x18, 2) + pow(x21, 2); -} -inline void point_to_point_source_to_target_tait_bryan_wc_AtPB_simplified_4( - Eigen::Matrix& AtPB, - const double& tx, - const double& ty, - const double& tz, - const double& om, - const double& fi, - const double& ka, - const double& x_s, - const double& y_s, - const double& z_s, - const double& x_t, - const double& y_t, - const double& z_t) -{ - double sin_om = sin(om); - double cos_om = cos(om); - double sin_fi = sin(fi); - double cos_fi = cos(fi); - double sin_ka = sin(ka); - double cos_ka = cos(ka); - double x0 = cos_ka * x_s; - double x1 = sin_ka * y_s; - double x2 = cos_fi * x0 - cos_fi * x1 + sin_fi * z_s; - double x3 = tx + x2 - x_t; - double x4 = cos_om * sin_ka; - double x5 = cos_ka * sin_om; - double x6 = sin_fi * x5 + x4; - double x7 = cos_ka * cos_om; - double x8 = sin_ka * sin_om; - double x9 = -sin_fi * x8 + x7; - double x10 = cos_fi * z_s; - double x11 = -sin_om * x10 + x6 * x_s + x9 * y_s; - double x12 = ty + x11 - y_t; - double x13 = sin_fi * x4 + x5; - double x14 = sin_fi * x7 - x8; - double x15 = cos_om * x10 + x13 * y_s - x14 * x_s; - double x16 = tz + x15 - z_t; - AtPB.coeffRef(0) = x3; - AtPB.coeffRef(1) = x12; - AtPB.coeffRef(2) = x16; - AtPB.coeffRef(3) = x11 * x16 - x12 * x15; - AtPB.coeffRef(4) = -cos_om * x16 * x2 + sin_om * x12 * x2 + x3 * (-sin_fi * x0 + sin_fi * x1 + x10); - AtPB.coeffRef(5) = -cos_fi * x3 * (cos_ka * y_s + sin_ka * x_s) + x12 * (-x6 * y_s + x9 * x_s) + x16 * (x13 * x_s + x14 * y_s); -} - bool PairWiseICP::compute( const std::vector& source, const std::vector& target, @@ -253,7 +126,6 @@ bool PairWiseICP::compute( nn_found = true; target_i_nn = target_i; } - /**/ } } } @@ -415,194 +287,6 @@ bool PairWiseICP::compute( return true; } -bool PairWiseICP::compute_fast( - const std::vector& source, - const std::vector& target, - double search_radious, - int number_of_iterations, - Eigen::Affine3d& m_pose_result, - int dec) -{ - bool multithread = true; - - std::vector> indexes; - - for (int i = 0; i < target.size(); i++) - { - uint64_t index = get_rgd_index_3d(target[i], { search_radious, search_radious, search_radious }); - indexes.emplace_back(index, i); - } - - // Ties broken by point index: std::sort leaves the order within a bucket to the standard library, and the - // search below skips each bucket's last point, so without this the result differs between platforms. - std::sort( - indexes.begin(), - indexes.end(), - [](const std::pair& a, const std::pair& b) - { - return a.first != b.first ? a.first < b.first : a.second < b.second; - }); - - std::unordered_map> buckets; - - for (uint32_t i = 0; i < indexes.size(); i++) - { - uint64_t index_of_bucket = indexes[i].first; - if (buckets.contains(index_of_bucket)) - { - buckets[index_of_bucket].second = i; - } - else - { - buckets[index_of_bucket].first = i; - buckets[index_of_bucket].second = i; - } - } - - for (int iter = 0; iter < number_of_iterations; iter++) - { - Eigen::MatrixXd AtPA(6, 6); - AtPA.setZero(); - Eigen::MatrixXd AtPB(6, 1); - AtPB.setZero(); - Eigen::Vector3d b(search_radious, search_radious, search_radious); - - std::mutex mutex; - - const auto hessian_fun = [&](const Eigen::Vector3d& source_i) - { - if (source_i.norm() < 0.1) - { - return; - } - - Eigen::Vector3d source_point_global = m_pose_result * source_i; - - double min_dist = 1000000000.0; - Eigen::Vector3d target_i; - Eigen::Vector3d target_i_nn; - bool nn_found = false; - for (double x = -search_radious; x <= search_radious; x += search_radious) - { - for (double y = -search_radious; y <= search_radious; y += search_radious) - { - for (double z = -search_radious; z <= search_radious; z += search_radious) - { - Eigen::Vector3d source_point_global_ext = source_point_global + Eigen::Vector3d(x, y, z); - uint64_t index_of_bucket = - get_rgd_index_3d(source_point_global_ext, { search_radious, search_radious, search_radious }); - - if (buckets.contains(index_of_bucket)) - { - for (int index = buckets[index_of_bucket].first; index < buckets[index_of_bucket].second; index += dec) - { - int index_element_target = indexes[index].second; - target_i = target[index_element_target]; - double d = (source_point_global - target_i).norm(); - - if (d < search_radious) - { - if (d < min_dist) - { - min_dist = d; - nn_found = true; - target_i_nn = target_i; - } - /**/ - } - } - } - } - } - } - - if (nn_found) - { - const Eigen::Vector3d& p_s = source_i; - const TaitBryanPose pose_s = pose_tait_bryan_from_affine_matrix(m_pose_result); - - Eigen::Matrix AtPA_; - point_to_point_source_to_target_tait_bryan_wc_AtPA_simplified_4( - AtPA_, pose_s.px, pose_s.py, pose_s.pz, pose_s.om, pose_s.fi, pose_s.ka, p_s.x(), p_s.y(), p_s.z()); - - Eigen::Matrix AtPB_; - point_to_point_source_to_target_tait_bryan_wc_AtPB_simplified_4( - AtPB_, - pose_s.px, - pose_s.py, - pose_s.pz, - pose_s.om, - pose_s.fi, - pose_s.ka, - p_s.x(), - p_s.y(), - p_s.z(), - target_i_nn.x(), - target_i_nn.y(), - target_i_nn.z()); - - std::unique_lock lck(mutex); - AtPA.block<6, 6>(0, 0) += AtPA_; - AtPB.block<6, 1>(0, 0) -= AtPB_; - } - }; - - if (multithread) - { - std::for_each( -#if USE_EXECUTION_PAR_UNSEQ - std::execution::par_unseq, -#endif - std::begin(source), - std::end(source), - hessian_fun); - } - else - { - std::for_each(std::begin(source), std::end(source), hessian_fun); - } - - Eigen::SparseMatrix AtPAc(6, 6); - Eigen::SparseMatrix AtPBc(6, 1); - - AtPAc = AtPA.sparseView(); - AtPBc = AtPB.sparseView(); - - Eigen::SimplicialCholesky> solver(AtPAc); - Eigen::SparseMatrix x = solver.solve(AtPBc); - std::vector h_x; - for (int k = 0; k < x.outerSize(); ++k) - { - for (Eigen::SparseMatrix::InnerIterator it(x, k); it; ++it) - { - h_x.push_back(it.value()); - } - } - - if (h_x.size() == 6) - { - int counter = 0; - TaitBryanPose pose = pose_tait_bryan_from_affine_matrix(m_pose_result); - - pose.px += h_x[counter++]; - pose.py += h_x[counter++]; - pose.pz += h_x[counter++]; - pose.om += h_x[counter++]; - pose.fi += h_x[counter++]; - pose.ka += h_x[counter++]; - - m_pose_result = affine_matrix_from_pose_tait_bryan(pose); - // return true; - } - else - { - return false; - } - } - - return true; -} - namespace { //! Standard deviations of the pose parameters (px, py, pz in metres; om, fi, ka in radians) from the point-to-point @@ -730,6 +414,7 @@ TaitBryanPose PairWiseICP::compute_icp_uncertainty( //Eigen::Vector3d b(search_radious, search_radious, search_radious); const TaitBryanPose pose_s = pose_tait_bryan_from_affine_matrix(m_pose_result); + std::vector block_sums(number_of_blocks); const auto hessian_fun = [&](const Eigen::Vector3d& source_i, NormalEquations& sum) @@ -784,53 +469,27 @@ TaitBryanPose PairWiseICP::compute_icp_uncertainty( Eigen::Matrix AtPA_; point_to_point_source_to_target_tait_bryan_wc_AtPA_simplified( - AtPA_, - pose_s.px, - pose_s.py, - pose_s.pz, - pose_s.om, - pose_s.fi, - pose_s.ka, - p_s.x(), - p_s.y(), - p_s.z(), - 1, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 1); - - Eigen::Matrix AtPB_; - point_to_point_source_to_target_tait_bryan_wc_AtPB_simplified( - AtPB_, - pose_s.px, - pose_s.py, - pose_s.pz, - pose_s.om, - pose_s.fi, - pose_s.ka, - p_s.x(), - p_s.y(), - p_s.z(), - 1, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 1, - target_i_nn.x(), - target_i_nn.y(), - target_i_nn.z()); + AtPA_, + pose_s.px, + pose_s.py, + pose_s.pz, + pose_s.om, + pose_s.fi, + pose_s.ka, + p_s.x(), + p_s.y(), + p_s.z(), + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1); sum.AtPA += AtPA_; - //sum.AtPB -= AtPB_; sum.sum_squared_residuals += min_dist_squared; sum.counter_nn++; } @@ -867,14 +526,6 @@ TaitBryanPose PairWiseICP::compute_icp_uncertainty( counter_nn += sum.counter_nn; } - //if (AtPB(0, 0) == 0.0 && AtPB(1, 0) == 0.0 && AtPB(2, 0) == 0.0 && AtPB(3, 0) == 0.0 && AtPB(4, 0) == 0.0 && AtPB(5, 0) == 0.0) - //{ - // std::cout - // << "PairWiseICP::compute FAILED (Relative pose is not changed/solved/optimized --> please consider removing this edge)" - // << std::endl; - // return icp_uncertainty; - //} - if (counter_nn < 100) { std::cout << "not suficient number of observations" << std::endl; @@ -885,7 +536,7 @@ TaitBryanPose PairWiseICP::compute_icp_uncertainty( } /* - I added compute_icp_uncertainty_from_hessian to pair_wise_iterative_closest_point.cpp. + Added compute_icp_uncertainty_from_hessian to pair_wise_iterative_closest_point.cpp. How it works: @@ -904,54 +555,5 @@ TaitBryanPose PairWiseICP::compute_icp_uncertainty( */ icp_uncertainty = compute_icp_uncertainty_from_hessian(AtPA, counter_nn, sum_squared_residuals); - - /*Eigen::SparseMatrix AtPAc(6, 6); - Eigen::SparseMatrix AtPBc(6, 1); - - AtPAc = AtPA.sparseView(); - AtPBc = AtPB.sparseView(); - - Eigen::SparseMatrix AtPA_I(6, 6); - AtPA_I.setIdentity(); - AtPA += (AtPA_I * 100); - - Eigen::SimplicialCholesky> solver(AtPAc); - Eigen::SparseMatrix x = solver.solve(AtPBc); - std::vector h_x; - for (int k = 0; k < x.outerSize(); ++k) - { - std::cout << "result pose updates" << std::endl; - for (Eigen::SparseMatrix::InnerIterator it(x, k); it; ++it) - { - h_x.push_back(it.value()); - std::cout << it.row() << " " << it.col() << " " << it.value() << std::endl; - } - }*/ - - /*if (h_x.size() == 6) - { - int counter = 0; - TaitBryanPose pose = pose_tait_bryan_from_affine_matrix(m_pose_result); - - pose.px += h_x[counter++]; - pose.py += h_x[counter++]; - pose.pz += h_x[counter++]; - pose.om += h_x[counter++]; - pose.fi += h_x[counter++]; - pose.ka += h_x[counter++]; - - //m_pose_result = affine_matrix_from_pose_tait_bryan(pose); - std::cout << "PairWiseICP::compute SUCCESS" << std::endl; - // return true; - } - else - { - std::cout - << "PairWiseICP::compute FAILED (Relative pose is not changed/solved/optimized --> please consider removing this edge)" - << std::endl; - return icp_uncertainty; - }*/ - - return icp_uncertainty; } \ No newline at end of file From 0a3f6fe9a21f7ab48bb3b63ead3f6c2df590e5ef Mon Sep 17 00:00:00 2001 From: janusz Date: Sun, 22 Nov 2026 10:46:42 +0100 Subject: [PATCH 4/9] clang formatting --- .../multi_view_tls_registration_gui.cpp | 4 +- apps/session_uncertainty_calculation/main.cpp | 40 +++++---- .../src/pair_wise_iterative_closest_point.cpp | 88 +++++++++---------- 3 files changed, 69 insertions(+), 63 deletions(-) diff --git a/apps/multi_view_tls_registration/multi_view_tls_registration_gui.cpp b/apps/multi_view_tls_registration/multi_view_tls_registration_gui.cpp index e663225d2..75f5ffa4d 100644 --- a/apps/multi_view_tls_registration/multi_view_tls_registration_gui.cpp +++ b/apps/multi_view_tls_registration/multi_view_tls_registration_gui.cpp @@ -3771,8 +3771,8 @@ void settings_gui() static bool hide_lecacy = true; ImGui::Checkbox("Hide legacy functions", &hide_lecacy); - if(!hide_lecacy){ - + if (!hide_lecacy) + { ImGui::Separator(); // common_data // manual_pose_graph_loop_closure_mode diff --git a/apps/session_uncertainty_calculation/main.cpp b/apps/session_uncertainty_calculation/main.cpp index 605079ab7..2f45c02ae 100644 --- a/apps/session_uncertainty_calculation/main.cpp +++ b/apps/session_uncertainty_calculation/main.cpp @@ -85,7 +85,8 @@ int main(int argc, char* argv[]) ///////////////////////////////////////////////////////////////////////////////////////// std::vector target_global; - for (const auto& p : tlsPoints){ + for (const auto& p : tlsPoints) + { target_global.emplace_back(p.point); } @@ -93,9 +94,11 @@ int main(int argc, char* argv[]) std::vector> node_timestamps; // std::vector node_positions; - for(const auto& pointCloud : session.point_clouds_container.point_clouds){ + for (const auto& pointCloud : session.point_clouds_container.point_clouds) + { std::vector source_local; - for(const auto& p : pointCloud.points_local){ + for (const auto& p : pointCloud.points_local) + { source_local.emplace_back(p); } @@ -103,12 +106,14 @@ int main(int argc, char* argv[]) std::vector source_global; - for(const auto& p : source_local){ + for (const auto& p : source_local) + { source_global.emplace_back(m_pose * p); } - for(const auto& n:pointCloud.local_trajectory){ - //std::cout << "Source Global Point: " << p.transpose() << std::endl; + for (const auto& n : pointCloud.local_trajectory) + { + // std::cout << "Source Global Point: " << p.transpose() << std::endl; Eigen::Affine3d m_global = m_pose * n.m_pose; @@ -116,19 +121,20 @@ int main(int argc, char* argv[]) std::vector source_local_for_single_trajectory_node; - for(const auto& p : source_global){ + for (const auto& p : source_global) + { source_local_for_single_trajectory_node.emplace_back(m_local * p); } PairWiseICP icp; - TaitBryanPose icp_uncertainty = icp.compute_icp_uncertainty(source_local_for_single_trajectory_node, target_global, m_global, 0.1); + TaitBryanPose icp_uncertainty = + icp.compute_icp_uncertainty(source_local_for_single_trajectory_node, target_global, m_global, 0.1); std::cout << "px=" << icp_uncertainty.px << ", " - << "py=" << icp_uncertainty.py << ", " - << "pz=" << icp_uncertainty.pz << ", " - << "om=" << icp_uncertainty.om << ", " - << "fi=" << icp_uncertainty.fi << ", " - << "ka=" << icp_uncertainty.ka - << std::endl; + << "py=" << icp_uncertainty.py << ", " + << "pz=" << icp_uncertainty.pz << ", " + << "om=" << icp_uncertainty.om << ", " + << "fi=" << icp_uncertainty.fi << ", " + << "ka=" << icp_uncertainty.ka << std::endl; icp_uncertainties.emplace_back(icp_uncertainty); node_timestamps.emplace_back(n.timestamps); @@ -149,9 +155,9 @@ int main(int argc, char* argv[]) for (size_t i = 0; i < icp_uncertainties.size(); i++) { const TaitBryanPose& u = icp_uncertainties[i]; - csv << node_timestamps[i].first << ',' << node_timestamps[i].second << ',' << node_positions[i].x() << ',' - << node_positions[i].y() << ',' << node_positions[i].z() << ',' << u.px << ',' << u.py << ',' << u.pz << ',' - << u.om << ',' << u.fi << ',' << u.ka << '\n'; + csv << node_timestamps[i].first << ',' << node_timestamps[i].second << ',' << node_positions[i].x() << ',' << node_positions[i].y() + << ',' << node_positions[i].z() << ',' << u.px << ',' << u.py << ',' << u.pz << ',' << u.om << ',' << u.fi << ',' << u.ka + << '\n'; } if (!csv) diff --git a/core/src/pair_wise_iterative_closest_point.cpp b/core/src/pair_wise_iterative_closest_point.cpp index cb67d8c7b..4c7f24084 100644 --- a/core/src/pair_wise_iterative_closest_point.cpp +++ b/core/src/pair_wise_iterative_closest_point.cpp @@ -322,8 +322,7 @@ namespace const double sigma0_squared = sum_squared_residuals / redundancy; const Eigen::Matrix& V = eigen_solver.eigenvectors(); - const Eigen::Matrix covariance = - sigma0_squared * V * eigenvalues.cwiseInverse().asDiagonal() * V.transpose(); + const Eigen::Matrix covariance = sigma0_squared * V * eigenvalues.cwiseInverse().asDiagonal() * V.transpose(); sigma.px = std::sqrt(covariance(0, 0)); sigma.py = std::sqrt(covariance(1, 1)); @@ -398,20 +397,19 @@ TaitBryanPose PairWiseICP::compute_icp_uncertainty( struct NormalEquations { Eigen::Matrix AtPA = Eigen::Matrix::Zero(); - //Eigen::Matrix AtPB = Eigen::Matrix::Zero(); + // Eigen::Matrix AtPB = Eigen::Matrix::Zero(); double sum_squared_residuals = 0.0; int counter_nn = 0; }; constexpr size_t number_of_blocks = 256; const size_t block_size = (source.size() + number_of_blocks - 1) / number_of_blocks; - - //std::cout << "iteration: " << iter + 1 << " of: " << number_of_iterations << std::endl; + // std::cout << "iteration: " << iter + 1 << " of: " << number_of_iterations << std::endl; Eigen::MatrixXd AtPA(6, 6); AtPA.setZero(); - //Eigen::MatrixXd AtPB(6, 1); - //AtPB.setZero(); - //Eigen::Vector3d b(search_radious, search_radious, search_radious); + // Eigen::MatrixXd AtPB(6, 1); + // AtPB.setZero(); + // Eigen::Vector3d b(search_radious, search_radious, search_radious); const TaitBryanPose pose_s = pose_tait_bryan_from_affine_matrix(m_pose_result); @@ -469,25 +467,25 @@ TaitBryanPose PairWiseICP::compute_icp_uncertainty( Eigen::Matrix AtPA_; point_to_point_source_to_target_tait_bryan_wc_AtPA_simplified( - AtPA_, - pose_s.px, - pose_s.py, - pose_s.pz, - pose_s.om, - pose_s.fi, - pose_s.ka, - p_s.x(), - p_s.y(), - p_s.z(), - 1, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 1); + AtPA_, + pose_s.px, + pose_s.py, + pose_s.pz, + pose_s.om, + pose_s.fi, + pose_s.ka, + p_s.x(), + p_s.y(), + p_s.z(), + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1); sum.AtPA += AtPA_; sum.sum_squared_residuals += min_dist_squared; @@ -521,7 +519,7 @@ TaitBryanPose PairWiseICP::compute_icp_uncertainty( for (const auto& sum : block_sums) { AtPA += sum.AtPA; - //AtPB += sum.AtPB; + // AtPB += sum.AtPB; sum_squared_residuals += sum.sum_squared_residuals; counter_nn += sum.counter_nn; } @@ -529,29 +527,31 @@ TaitBryanPose PairWiseICP::compute_icp_uncertainty( if (counter_nn < 100) { std::cout << "not suficient number of observations" << std::endl; - std::cout - << "PairWiseICP::compute FAILED (Relative pose is not changed/solved/optimized --> please consider removing this edge)" - << std::endl; + std::cout << "PairWiseICP::compute FAILED (Relative pose is not changed/solved/optimized --> please consider removing this edge)" + << std::endl; return icp_uncertainty; } /* - Added compute_icp_uncertainty_from_hessian to pair_wise_iterative_closest_point.cpp. + Added compute_icp_uncertainty_from_hessian to pair_wise_iterative_closest_point.cpp. How it works: - Covariance: it computes covariance = σ₀² · (AᵀPA)⁻¹ and returns the square root of each diagonal entry as a TaitBryanPose. px/py/pz are in metres and om/fi/ka in radians. - Scale factor: σ₀² = sum of squared residuals / (3·n − 6). Each match gives 3 observations and the pose has 6 unknowns. - Matrix inverse: it inverts through an eigen decomposition, which shows when the geometry leaves a direction unconstrained (a plane, a corridor). If the smallest eigenvalue is below 1e-12 of the largest, it prints a warning and returns infinity for every parameter. - Other changes: - - Extra parameter: the Hessian only gives the shape of the uncertainty, not its size, so the function needs the residuals too. The call is now compute_icp_uncertainty_from_hessian(AtPA, counter_nn, sum_squared_residuals). - Residual sum: NormalEquations gets a sum_squared_residuals field. Each match adds its min_dist_squared, and the block sums are added up alongside AtPA. - Includes: added and . - Things to check: - - Wasted work: hessian_fun still calls point_to_point_source_to_target_tait_bryan_wc_AtPB_simplified for every point and never uses the result. You can delete that call. - Over-confident result: neighbouring LiDAR points are correlated, so this formal covariance tends to make the uncertainty look smaller than it really is. It's fine for comparing edges with each other, but don't read it as an absolute error. + Covariance: it computes covariance = σ₀² · (AᵀPA)⁻¹ and returns the square root of each diagonal entry as a TaitBryanPose. px/py/pz are + in metres and om/fi/ka in radians. Scale factor: σ₀² = sum of squared residuals / (3·n − 6). Each match gives 3 observations and the + pose has 6 unknowns. Matrix inverse: it inverts through an eigen decomposition, which shows when the geometry leaves a direction + unconstrained (a plane, a corridor). If the smallest eigenvalue is below 1e-12 of the largest, it prints a warning and returns infinity + for every parameter. Other changes: + + Extra parameter: the Hessian only gives the shape of the uncertainty, not its size, so the function needs the residuals too. The call is + now compute_icp_uncertainty_from_hessian(AtPA, counter_nn, sum_squared_residuals). Residual sum: NormalEquations gets a + sum_squared_residuals field. Each match adds its min_dist_squared, and the block sums are added up alongside AtPA. Includes: added + and . Things to check: + + Wasted work: hessian_fun still calls point_to_point_source_to_target_tait_bryan_wc_AtPB_simplified for every point and never uses the + result. You can delete that call. Over-confident result: neighbouring LiDAR points are correlated, so this formal covariance tends to + make the uncertainty look smaller than it really is. It's fine for comparing edges with each other, but don't read it as an absolute + error. */ icp_uncertainty = compute_icp_uncertainty_from_hessian(AtPA, counter_nn, sum_squared_residuals); From bd35d4db933b2f3f0d0e52b2b6923dc016b3ef2c Mon Sep 17 00:00:00 2001 From: janusz Date: Sun, 22 Nov 2026 10:57:46 +0100 Subject: [PATCH 5/9] improved info --- apps/session_uncertainty_calculation/main.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/apps/session_uncertainty_calculation/main.cpp b/apps/session_uncertainty_calculation/main.cpp index 2f45c02ae..52b838b0e 100644 --- a/apps/session_uncertainty_calculation/main.cpp +++ b/apps/session_uncertainty_calculation/main.cpp @@ -129,12 +129,12 @@ int main(int argc, char* argv[]) PairWiseICP icp; TaitBryanPose icp_uncertainty = icp.compute_icp_uncertainty(source_local_for_single_trajectory_node, target_global, m_global, 0.1); - std::cout << "px=" << icp_uncertainty.px << ", " - << "py=" << icp_uncertainty.py << ", " - << "pz=" << icp_uncertainty.pz << ", " - << "om=" << icp_uncertainty.om << ", " - << "fi=" << icp_uncertainty.fi << ", " - << "ka=" << icp_uncertainty.ka << std::endl; + std::cout << "sigma_px=" << icp_uncertainty.px << ", " + << "sigma_py=" << icp_uncertainty.py << ", " + << "sigma_pz=" << icp_uncertainty.pz << ", " + << "sigma_om=" << icp_uncertainty.om << ", " + << "sigma_fi=" << icp_uncertainty.fi << ", " + << "sigma_ka=" << icp_uncertainty.ka << std::endl; icp_uncertainties.emplace_back(icp_uncertainty); node_timestamps.emplace_back(n.timestamps); From e67696d0e8708c83e0c49be041f33a0467318c96 Mon Sep 17 00:00:00 2001 From: janusz Date: Sun, 22 Nov 2026 15:17:13 +0100 Subject: [PATCH 6/9] calculate uncertainty of edge --- apps/session_uncertainty_calculation/main.cpp | 35 ++- .../Core/manual_pose_graph_loop_closure.h | 12 + .../Core/pair_wise_iterative_closest_point.h | 31 ++- core/include/Core/pose_graph_loop_closure.h | 14 + core/src/manual_pose_graph_loop_closure.cpp | 64 +++++ .../src/pair_wise_iterative_closest_point.cpp | 245 +++++++++++++++++- core/src/pose_graph_loop_closure.cpp | 104 ++++---- 7 files changed, 439 insertions(+), 66 deletions(-) diff --git a/apps/session_uncertainty_calculation/main.cpp b/apps/session_uncertainty_calculation/main.cpp index 52b838b0e..92c9f40ff 100644 --- a/apps/session_uncertainty_calculation/main.cpp +++ b/apps/session_uncertainty_calculation/main.cpp @@ -91,6 +91,7 @@ int main(int argc, char* argv[]) } std::vector icp_uncertainties; + std::vector icp_residuals; std::vector> node_timestamps; // std::vector node_positions; @@ -111,10 +112,24 @@ int main(int argc, char* argv[]) source_global.emplace_back(m_pose * p); } - for (const auto& n : pointCloud.local_trajectory) + // + /*std::ofstream csv("source.txt"); + + for (size_t i = 0; i < source_global.size(); i++) + { + csv <::max_digits10); for (size_t i = 0; i < icp_uncertainties.size(); i++) { const TaitBryanPose& u = icp_uncertainties[i]; + const IcpResidualStatistics& r = icp_residuals[i]; csv << node_timestamps[i].first << ',' << node_timestamps[i].second << ',' << node_positions[i].x() << ',' << node_positions[i].y() << ',' << node_positions[i].z() << ',' << u.px << ',' << u.py << ',' << u.pz << ',' << u.om << ',' << u.fi << ',' << u.ka - << '\n'; + << ',' << r.sum_squared_residuals << ',' << r.number_of_correspondences << ',' << r.number_of_observations << ',' + << r.sigma0 << '\n'; } if (!csv) diff --git a/core/include/Core/manual_pose_graph_loop_closure.h b/core/include/Core/manual_pose_graph_loop_closure.h index 495dedd88..53222c711 100644 --- a/core/include/Core/manual_pose_graph_loop_closure.h +++ b/core/include/Core/manual_pose_graph_loop_closure.h @@ -39,6 +39,18 @@ class ManualPoseGraphLoopClosure : public PoseGraphLoopClosure bool progress_drawn = false; //!< the progress bar has been shown at least once }; IcpAllEdgesRun icp_all_edges_run; + //! Last "Calculate ICP uncertainty" result: the edge and the relative pose it was computed for, so it is shown only + //! while both are unchanged. + struct IcpUncertainty + { + int edge = -1; + TaitBryanPose relative_pose; + TaitBryanPose point_to_point; + TaitBryanPose point_to_plane; + IcpResidualStatistics point_to_point_residuals; + IcpResidualStatistics point_to_plane_residuals; + }; + IcpUncertainty icp_uncertainty; //! "Keep initial trajectory curvature": compute_pose_graph_slam() uses the initial poses as the motion model, else the current ones. bool keep_initial_trajectory_curvature = true; diff --git a/core/include/Core/pair_wise_iterative_closest_point.h b/core/include/Core/pair_wise_iterative_closest_point.h index 1ad790e55..360ebd06d 100644 --- a/core/include/Core/pair_wise_iterative_closest_point.h +++ b/core/include/Core/pair_wise_iterative_closest_point.h @@ -5,6 +5,19 @@ #include #include +#include + +//! Residuals behind an ICP uncertainty estimate. +struct IcpResidualStatistics +{ + double sum_squared_residuals = 0.0; //!< [m^2] + int number_of_correspondences = 0; + int number_of_observations = 0; //!< 3 per correspondence for point-to-point, 1 for point-to-plane + //! Standard deviation of unit weight, sqrt(sum_squared_residuals / (number_of_observations - 6)) [m]; NaN when + //! there are not more observations than the 6 pose parameters. + double sigma0 = std::numeric_limits::quiet_NaN(); +}; + class PairWiseICP { public: @@ -17,9 +30,25 @@ class PairWiseICP double search_radious, int number_of_iterations, Eigen::Affine3d& m_pose_result); + //! Pose standard deviations (px, py, pz in metres; om, fi, ka in radians) of an aligned source from point-to-point + //! residuals to the nearest target point within search_radious. Covariance = sigma0^2 * (J^T J)^-1, + //! sigma0^2 = sum r^2 / (3n - 6). If statistics is given, the residual statistics are written there. TaitBryanPose compute_icp_uncertainty( const std::vector& source, const std::vector& target, const Eigen::Affine3d& m_pose_result, - double search_radious); + double search_radious, + IcpResidualStatistics* statistics = nullptr); + + //! Pose standard deviations (px, py, pz in metres; om, fi, ka in radians) of an aligned source from point-to-plane + //! residuals: each source point is matched to the plane fitted to the target points within search_radious + //! (non-planar neighbourhoods are skipped). Covariance = sigma0^2 * (J^T J)^-1, sigma0^2 = sum r^2 / (n - 6). + //! Returns infinity for every parameter when there are too few correspondences or the geometry is degenerate. + //! If statistics is given, the residual statistics are written there. + TaitBryanPose compute_icp_uncertainty_point_to_plane( + const std::vector& source, + const std::vector& target, + const Eigen::Affine3d& m_pose_result, + double search_radious, + IcpResidualStatistics* statistics = nullptr); }; diff --git a/core/include/Core/pose_graph_loop_closure.h b/core/include/Core/pose_graph_loop_closure.h index 0509945c2..52395e08c 100644 --- a/core/include/Core/pose_graph_loop_closure.h +++ b/core/include/Core/pose_graph_loop_closure.h @@ -3,6 +3,7 @@ #include #include #include +#include #include #include @@ -75,6 +76,19 @@ class PoseGraphLoopClosure int number_of_iterations, int num_edge_extended_before, int num_edge_extended_after); + //! Standard deviations of one edge's relative pose (px, py, pz in metres; om, fi, ka in radians) from the ICP + //! normal matrix at the current relative pose, on the same clouds as run_icp(). + //! @param point_to_plane false: point-to-point residuals (as run_icp() minimises); true: point-to-plane residuals + //! @param statistics if given, receives the residual statistics (sum of squared residuals, sigma0, ...) + //! @return infinity for every parameter when the geometry does not constrain the pose + TaitBryanPose compute_icp_uncertainty( + const PointClouds& point_clouds_container, + int index_active_edge, + double search_radius, + int num_edge_extended_before, + int num_edge_extended_after, + bool point_to_plane, + IcpResidualStatistics* statistics = nullptr); //! Search radii for coarse-to-fine ICP: `start_radius`, then those of the per-edge ICP buttons' steps (2.0, 1.0, //! 0.5, 0.25, 0.1 m) below it. static std::vector icp_search_radii(float start_radius); diff --git a/core/src/manual_pose_graph_loop_closure.cpp b/core/src/manual_pose_graph_loop_closure.cpp index d2cec112d..717271104 100644 --- a/core/src/manual_pose_graph_loop_closure.cpp +++ b/core/src/manual_pose_graph_loop_closure.cpp @@ -337,6 +337,70 @@ void ManualPoseGraphLoopClosure::Gui( ImGui::SameLine(); if (ImGui::Button("ICP (0.1)")) run_icp(point_clouds_container, index_active_edge, 0.1, 30, num_edge_extended_before, num_edge_extended_after); + char icp_uncertainty_label[128]; + std::snprintf( + icp_uncertainty_label, + sizeof(icp_uncertainty_label), + "Calculate ICP uncertainty for search radius %.3f m###icp_uncertainty", + search_radious); + if (ImGui::Button(icp_uncertainty_label)) + { + icp_uncertainty.edge = index_active_edge; + icp_uncertainty.relative_pose = edges[index_active_edge].relative_pose_tb; + icp_uncertainty.point_to_point = compute_icp_uncertainty( + point_clouds_container, + index_active_edge, + search_radious, + num_edge_extended_before, + num_edge_extended_after, + false, + &icp_uncertainty.point_to_point_residuals); + icp_uncertainty.point_to_plane = compute_icp_uncertainty( + point_clouds_container, + index_active_edge, + search_radious, + num_edge_extended_before, + num_edge_extended_after, + true, + &icp_uncertainty.point_to_plane_residuals); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip( + "Standard deviations of the active edge's relative pose from the ICP normal matrix at the current pose,\n" + "with Search_radius. Formal values: neighbouring LiDAR points are correlated, so they are optimistic.\n" + "Use them to compare edges, not as absolute accuracy. inf = geometry does not constrain the pose."); + + const TaitBryanPose& current_pose = edges[index_active_edge].relative_pose_tb; + const TaitBryanPose& computed_pose = icp_uncertainty.relative_pose; + if (icp_uncertainty.edge == index_active_edge && current_pose.px == computed_pose.px && current_pose.py == computed_pose.py && + current_pose.pz == computed_pose.pz && current_pose.om == computed_pose.om && current_pose.fi == computed_pose.fi && + current_pose.ka == computed_pose.ka) + { + const auto show = [](const char* label, const TaitBryanPose& s, const IcpResidualStatistics& r) + { + ImGui::Text( + "%s sigma [m]: sigma_px %.4f sigma_py %.4f sigma_pz %.4f [deg]: sigma_om %.4f sigma_fi %.4f sigma_ka %.4f", + label, + s.px, + s.py, + s.pz, + rad2deg(s.om), + rad2deg(s.fi), + rad2deg(s.ka)); + ImGui::Text( + " sum of squared residuals %.6f [m^2], correspondences %d, observations %d, sigma0(RMS) %.4f [m]", + r.sum_squared_residuals, + r.number_of_correspondences, + r.number_of_observations, + r.sigma0); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip( + "sigma0 = sqrt(sum of squared residuals / (observations - 6)): RMS residual per observation.\n" + "It scales all pose sigmas: covariance = sigma0^2 * (J^T J)^-1."); + }; + show("point-to-point", icp_uncertainty.point_to_point, icp_uncertainty.point_to_point_residuals); + show("point-to-plane", icp_uncertainty.point_to_plane, icp_uncertainty.point_to_plane_residuals); + } if (ImGui::Button("Save source (local)")) { diff --git a/core/src/pair_wise_iterative_closest_point.cpp b/core/src/pair_wise_iterative_closest_point.cpp index 4c7f24084..9077dc435 100644 --- a/core/src/pair_wise_iterative_closest_point.cpp +++ b/core/src/pair_wise_iterative_closest_point.cpp @@ -10,6 +10,7 @@ #include #include +#include #include bool PairWiseICP::compute( @@ -289,19 +290,104 @@ bool PairWiseICP::compute( namespace { - //! Standard deviations of the pose parameters (px, py, pz in metres; om, fi, ka in radians) from the point-to-point - //! normal matrix AtPA = J^T J (unit weights). Covariance = sigma0^2 * AtPA^-1, where the variance factor - //! sigma0^2 = sum of squared residuals / (3 * number_of_correspondences - 6). Returns infinity for every parameter - //! when the problem is degenerate (e.g. a corridor or a plane leaves a direction unconstrained). - TaitBryanPose compute_icp_uncertainty_from_hessian( - const Eigen::Matrix& AtPA, int number_of_correspondences, double sum_squared_residuals) + TaitBryanPose infinite_uncertainty() { constexpr double inf = std::numeric_limits::infinity(); TaitBryanPose sigma; sigma.px = sigma.py = sigma.pz = sigma.om = sigma.fi = sigma.ka = inf; + return sigma; + } + + //! Bucket grid over a target cloud with the cell size equal to the search radius, so every neighbour of a query + //! point lies in the 27 cells around it. + class TargetGrid + { + public: + TargetGrid(const std::vector& target, double search_radious) + : radius(search_radious) + , radius_squared(search_radious * search_radious) + , cell(search_radious, search_radious, search_radious) + { + std::vector> indexes; + indexes.reserve(target.size()); + for (uint32_t i = 0; i < target.size(); i++) + { + indexes.emplace_back(get_rgd_index_3d(target[i], cell), i); + } + // Ties broken by point index so the order within a bucket is the same on every platform. + std::sort(indexes.begin(), indexes.end()); + + sorted.resize(indexes.size()); + for (uint32_t i = 0; i < indexes.size(); i++) + { + sorted[i] = target[indexes[i].second]; + const auto [bucket, inserted] = buckets.try_emplace(indexes[i].first, i, i); + bucket->second.second = i; + } + } - // Each correspondence gives 3 observations (x, y, z); the pose has 6 unknowns. - const int redundancy = 3 * number_of_correspondences - 6; + //! Calls f(target_point, squared_distance) for every target point closer to query than the search radius. + template + void for_each_neighbour(const Eigen::Vector3d& query, F&& f) const + { + for (int dx = -1; dx <= 1; dx++) + { + for (int dy = -1; dy <= 1; dy++) + { + for (int dz = -1; dz <= 1; dz++) + { + const Eigen::Vector3d shifted = query + radius * Eigen::Vector3d(dx, dy, dz); + const auto bucket = buckets.find(get_rgd_index_3d(shifted, cell)); + if (bucket == buckets.end()) + { + continue; + } + for (uint32_t index = bucket->second.first; index <= bucket->second.second; index++) + { + const double d_squared = (query - sorted[index]).squaredNorm(); + if (d_squared < radius_squared) + { + f(sorted[index], d_squared); + } + } + } + } + } + } + + private: + double radius; + double radius_squared; + Eigen::Vector3d cell; + std::vector sorted; + std::unordered_map> buckets; + }; + + //! Standard deviations of the pose parameters (px, py, pz in metres; om, fi, ka in radians) from the normal matrix + //! AtPA = J^T J (unit weights). Covariance = sigma0^2 * AtPA^-1, where the variance factor + //! sigma0^2 = sum of squared residuals / (number_of_observations - 6). Returns infinity for every parameter + //! when the problem is degenerate (e.g. a corridor or a plane leaves a direction unconstrained). + void fill_residual_statistics( + IcpResidualStatistics* statistics, double sum_squared_residuals, int number_of_correspondences, int number_of_observations) + { + if (statistics == nullptr) + { + return; + } + statistics->sum_squared_residuals = sum_squared_residuals; + statistics->number_of_correspondences = number_of_correspondences; + statistics->number_of_observations = number_of_observations; + statistics->sigma0 = number_of_observations > 6 ? std::sqrt(sum_squared_residuals / (number_of_observations - 6)) + : std::numeric_limits::quiet_NaN(); + } + + TaitBryanPose compute_icp_uncertainty_from_hessian( + const Eigen::Matrix& AtPA, int number_of_observations, double sum_squared_residuals) + { + TaitBryanPose sigma = infinite_uncertainty(); + + // The pose has 6 unknowns. + const int redundancy = number_of_observations - 6; if (redundancy <= 0) { return sigma; @@ -338,7 +424,8 @@ TaitBryanPose PairWiseICP::compute_icp_uncertainty( const std::vector& source, const std::vector& target, const Eigen::Affine3d& m_pose_result, - double search_radious) + double search_radious, + IcpResidualStatistics* statistics) { bool multithread = true; TaitBryanPose icp_uncertainty; @@ -449,6 +536,7 @@ TaitBryanPose PairWiseICP::compute_icp_uncertainty( { if (d_squared < min_dist_squared) { + //std::cout << "sqrt_d_squared: " << sqrt(d_squared) << std::endl; min_dist_squared = d_squared; nn_found = true; target_i_nn = target_i; @@ -523,6 +611,8 @@ TaitBryanPose PairWiseICP::compute_icp_uncertainty( sum_squared_residuals += sum.sum_squared_residuals; counter_nn += sum.counter_nn; } + // Each point-to-point correspondence gives 3 observations (x, y, z). + fill_residual_statistics(statistics, sum_squared_residuals, counter_nn, 3 * counter_nn); if (counter_nn < 100) { @@ -553,7 +643,140 @@ TaitBryanPose PairWiseICP::compute_icp_uncertainty( make the uncertainty look smaller than it really is. It's fine for comparing edges with each other, but don't read it as an absolute error. */ - icp_uncertainty = compute_icp_uncertainty_from_hessian(AtPA, counter_nn, sum_squared_residuals); + // Each point-to-point correspondence gives 3 observations (x, y, z). + icp_uncertainty = compute_icp_uncertainty_from_hessian(AtPA, 3 * counter_nn, sum_squared_residuals); return icp_uncertainty; -} \ No newline at end of file +} + +TaitBryanPose PairWiseICP::compute_icp_uncertainty_point_to_plane( + const std::vector& source, + const std::vector& target, + const Eigen::Affine3d& m_pose_result, + double search_radious, + IcpResidualStatistics* statistics) +{ + // A target neighbourhood is used as a plane only if it has enough points and is flat: smallest eigenvalue of + // its covariance at most this fraction of the middle one. + constexpr int min_neighbours = 5; + constexpr double planarity_threshold = 0.1; + constexpr int min_correspondences = 100; + + const TargetGrid grid(target, search_radious); + const TaitBryanPose pose_s = pose_tait_bryan_from_affine_matrix(m_pose_result); + + // Normal equations are summed per block of source points, then the blocks in order: no lock per point, and + // the same sum on every run and machine. + struct NormalEquations + { + Eigen::Matrix AtPA = Eigen::Matrix::Zero(); + double sum_squared_residuals = 0.0; + int counter = 0; + }; + constexpr size_t number_of_blocks = 256; + const size_t block_size = (source.size() + number_of_blocks - 1) / number_of_blocks; + std::vector block_sums(number_of_blocks); + + const auto add_observation = [&](const Eigen::Vector3d& source_i, NormalEquations& sum) + { + if (source_i.norm() < 0.1) + { + return; + } + const Eigen::Vector3d source_point_global = m_pose_result * source_i; + + // Plane of the target neighbourhood from running sums (no per-point allocation). The sums are taken relative + // to the query point: with large global coordinates (e.g. UTM) E[pp^T] - mean*mean^T would lose all precision. + Eigen::Vector3d sum_p = Eigen::Vector3d::Zero(); + Eigen::Matrix3d sum_ppt = Eigen::Matrix3d::Zero(); + int k = 0; + grid.for_each_neighbour( + source_point_global, + [&](const Eigen::Vector3d& target_i, double) + { + const Eigen::Vector3d p = target_i - source_point_global; + sum_p += p; + sum_ppt += p * p.transpose(); + k++; + }); + if (k < min_neighbours) + { + return; + } + const Eigen::Vector3d mean_relative = sum_p / k; + const Eigen::Matrix3d covariance = sum_ppt / k - mean_relative * mean_relative.transpose(); + const Eigen::Vector3d mean = source_point_global + mean_relative; + const Eigen::SelfAdjointEigenSolver eigen_solver(covariance); + if (eigen_solver.info() != Eigen::Success) + { + return; + } + const Eigen::Vector3d& eigenvalues = eigen_solver.eigenvalues(); // ascending + if (eigenvalues(0) > planarity_threshold * eigenvalues(1)) + { + return; + } + const Eigen::Vector3d normal = eigen_solver.eigenvectors().col(0); + + const double residual = -normal.dot(mean_relative); + + Eigen::Matrix j; + point_to_plane_tait_bryan_wc_jacobian( + j, + pose_s.px, + pose_s.py, + pose_s.pz, + pose_s.om, + pose_s.fi, + pose_s.ka, + source_i.x(), + source_i.y(), + source_i.z(), + mean.x(), + mean.y(), + mean.z(), + normal.x(), + normal.y(), + normal.z()); + + sum.AtPA += j.transpose() * j; + sum.sum_squared_residuals += residual * residual; + sum.counter++; + }; + + tbb::parallel_for_each( + block_sums.begin(), + block_sums.end(), + [&](NormalEquations& sum) + { + const size_t block = &sum - block_sums.data(); + const size_t begin = std::min(source.size(), block * block_size); + const size_t end = std::min(source.size(), begin + block_size); + for (size_t i = begin; i < end; i++) + { + add_observation(source[i], sum); + } + }); + + Eigen::Matrix AtPA = Eigen::Matrix::Zero(); + double sum_squared_residuals = 0.0; + int counter = 0; + for (const auto& sum : block_sums) + { + AtPA += sum.AtPA; + sum_squared_residuals += sum.sum_squared_residuals; + counter += sum.counter; + } + // Each point-to-plane correspondence gives 1 observation (distance along the normal). + fill_residual_statistics(statistics, sum_squared_residuals, counter, counter); + + if (counter < min_correspondences) + { + std::cout << "PairWiseICP::compute_icp_uncertainty_point_to_plane: not enough planar correspondences (" << counter << ")" + << std::endl; + return infinite_uncertainty(); + } + + // Each point-to-plane correspondence gives 1 observation (distance along the normal). + return compute_icp_uncertainty_from_hessian(AtPA, counter, sum_squared_residuals); +} diff --git a/core/src/pose_graph_loop_closure.cpp b/core/src/pose_graph_loop_closure.cpp index 8e1728f34..35496bcc8 100644 --- a/core/src/pose_graph_loop_closure.cpp +++ b/core/src/pose_graph_loop_closure.cpp @@ -1259,6 +1259,41 @@ void PoseGraphLoopClosure::FuseTrajectoryWithTUM(PointClouds& point_clouds_conta } } +namespace +{ + //! Points of the edge's two scans, each extended by its neighbouring scans: source in the local frame of scan + //! e.index_to, target in the local frame of scan e.index_from. + void edge_source_target( + const PointClouds& point_clouds_container, + const PoseGraphLoopClosure::Edge& e, + int num_edge_extended_before, + int num_edge_extended_after, + std::vector& source, + std::vector& target) + { + const auto& point_clouds = point_clouds_container.point_clouds; + const auto gather = [&](int index_center, std::vector& points) + { + const Eigen::Affine3d m_center_inv = point_clouds[index_center].m_pose.inverse(); + for (int i = -num_edge_extended_before; i <= num_edge_extended_after; i++) + { + const int index = index_center + i; + if (index >= 0 && index < static_cast(point_clouds.size())) + { + // Through the global frame, in two steps, so run_icp() gets exactly the points it always did. + const Eigen::Affine3d& m = point_clouds[index].m_pose; + for (const auto& p : point_clouds[index].points_local) + { + points.push_back(m_center_inv * (m * p)); + } + } + } + }; + gather(e.index_to, source); + gather(e.index_from, target); + } +} // namespace + bool PoseGraphLoopClosure::run_icp( PointClouds& point_clouds_container, int index_active_edge, @@ -1269,57 +1304,9 @@ bool PoseGraphLoopClosure::run_icp( { PairWiseICP icp; auto m_pose = affine_matrix_from_pose_tait_bryan(edges[index_active_edge].relative_pose_tb); - // std::vector source = point_clouds_container.point_clouds[edges[index_active_edge].index_to].points_local; - // std::vector target = point_clouds_container.point_clouds[edges[index_active_edge].index_from].points_local; - - //////////////////////////////// std::vector source; - auto& e = edges[index_active_edge]; - for (int i = -num_edge_extended_before; i <= num_edge_extended_after; i++) - { - int index_src = e.index_to + i; - if (index_src >= 0 && index_src < point_clouds_container.point_clouds.size()) - { - Eigen::Affine3d m_src = point_clouds_container.point_clouds.at(index_src).m_pose; - for (int k = 0; k < point_clouds_container.point_clouds[index_src].points_local.size(); k++) - { - Eigen::Vector3d p_g = m_src * point_clouds_container.point_clouds[index_src].points_local[k]; - source.push_back(p_g); - } - // point_clouds_container.point_clouds.at(index_src).render(m_src, 1); - } - } std::vector target; - - for (int i = -num_edge_extended_before; i <= num_edge_extended_after; i++) - { - int index_trg = e.index_from + i; - if (index_trg >= 0 && index_trg < point_clouds_container.point_clouds.size()) - { - Eigen::Affine3d m_trg = point_clouds_container.point_clouds.at(index_trg).m_pose; - for (int k = 0; k < point_clouds_container.point_clouds[index_trg].points_local.size(); k++) - { - Eigen::Vector3d p_g = m_trg * point_clouds_container.point_clouds[index_trg].points_local[k]; - target.push_back(p_g); - } - // point_clouds_container.point_clouds.at(index_src).render(m_src, 1); - } - } - - Eigen::Affine3d m_src_inv = point_clouds_container.point_clouds[e.index_to].m_pose.inverse(); - - for (auto& p : source) - { - p = m_src_inv * p; - } - - Eigen::Affine3d m_trg_inv = point_clouds_container.point_clouds[e.index_from].m_pose.inverse(); - - for (auto& p : target) - { - p = m_trg_inv * p; - } - //////////////////////////////// + edge_source_target(point_clouds_container, edges[index_active_edge], num_edge_extended_before, num_edge_extended_after, source, target); if (icp.compute(source, target, search_radius, number_of_iterations, m_pose)) { @@ -1329,6 +1316,25 @@ bool PoseGraphLoopClosure::run_icp( return false; } +TaitBryanPose PoseGraphLoopClosure::compute_icp_uncertainty( + const PointClouds& point_clouds_container, + int index_active_edge, + double search_radius, + int num_edge_extended_before, + int num_edge_extended_after, + bool point_to_plane, + IcpResidualStatistics* statistics) +{ + const auto m_pose = affine_matrix_from_pose_tait_bryan(edges[index_active_edge].relative_pose_tb); + std::vector source; + std::vector target; + edge_source_target(point_clouds_container, edges[index_active_edge], num_edge_extended_before, num_edge_extended_after, source, target); + + PairWiseICP icp; + return point_to_plane ? icp.compute_icp_uncertainty_point_to_plane(source, target, m_pose, search_radius, statistics) + : icp.compute_icp_uncertainty(source, target, m_pose, search_radius, statistics); +} + std::vector PoseGraphLoopClosure::icp_search_radii(float start_radius) { std::vector radii{ start_radius }; From 03db4209cb802bd69752633f9e99d5335f1a9137 Mon Sep 17 00:00:00 2001 From: janusz Date: Sun, 22 Nov 2026 15:18:46 +0100 Subject: [PATCH 7/9] fix formatting --- apps/session_uncertainty_calculation/main.cpp | 14 ++++++-------- core/src/manual_pose_graph_loop_closure.cpp | 6 +++--- core/src/pair_wise_iterative_closest_point.cpp | 2 +- 3 files changed, 10 insertions(+), 12 deletions(-) diff --git a/apps/session_uncertainty_calculation/main.cpp b/apps/session_uncertainty_calculation/main.cpp index 92c9f40ff..858a7d2b1 100644 --- a/apps/session_uncertainty_calculation/main.cpp +++ b/apps/session_uncertainty_calculation/main.cpp @@ -114,14 +114,14 @@ int main(int argc, char* argv[]) // /*std::ofstream csv("source.txt"); - + for (size_t i = 0; i < source_global.size(); i++) { csv < Date: Sun, 22 Nov 2026 15:37:28 +0100 Subject: [PATCH 8/9] save all sessions to single laz in step3 --- .../multi_session_registration.cpp | 22 +++++++ core/include/Core/export_laz.h | 62 +++++++++++++++++++ 2 files changed, 84 insertions(+) diff --git a/apps/multi_session_registration/multi_session_registration.cpp b/apps/multi_session_registration/multi_session_registration.cpp index 00da92f0e..00b3a1b53 100644 --- a/apps/multi_session_registration/multi_session_registration.cpp +++ b/apps/multi_session_registration/multi_session_registration.cpp @@ -3179,6 +3179,24 @@ void display() if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) ImGui::SetTooltip("Save the current poses of one session as a TUM trajectory (t[s] x y z qx qy qz qw)"); + if (ImGui::MenuItem("Save all point clouds as single LAZ", nullptr, nullptr, loaded_sessions && !sessions.empty())) + { + const std::string output_file_name = + mandeye::fd::SaveFileDialog("Save all point clouds as single LAZ", mandeye::fd::LAS_LAZ_filter, ".laz", "all_sessions.laz"); + if (!output_file_name.empty()) + { + if (save_all_sessions_to_las(sessions, output_file_name)) + std::cout << "Saved: " << output_file_name << std::endl; + else + pfd::message("Export failed", "Could not write '" + output_file_name + "'", pfd::choice::ok, pfd::icon::error); + } + } + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + ImGui::SetTooltip( + "Merge the visible scans of all visible sessions, with their current poses, into one las/laz file.\n" + "point_source_ID = session index. Points are written as loaded: with 'Downsample during load' on,\n" + "the file is downsampled too."); + ImGui::Separator(); if (ImGui::BeginMenu("Save all marked trajectories", sessions.size() > 0)) { @@ -3682,6 +3700,10 @@ void display() ImGui::EndMenu(); } + ImGui::Separator(); + + + ImGui::EndMenu(); } diff --git a/core/include/Core/export_laz.h b/core/include/Core/export_laz.h index 18a913220..bb8517454 100644 --- a/core/include/Core/export_laz.h +++ b/core/include/Core/export_laz.h @@ -534,3 +534,65 @@ inline bool save_all_to_las(const Session& session, std::string output_las_name, return writer.close(); } + +//! Writes the visible scans of all visible sessions, in global coordinates (pose * point + session offset), to one +//! las/laz file. point_source_ID holds the session index, so the merged cloud can be split per session again. +inline bool save_all_sessions_to_las(const std::vector& sessions, const std::string& output_las_name) +{ + // The first visible session's offset is the file offset; other sessions are shifted to it. + const auto first_visible = std::find_if( + sessions.begin(), + sessions.end(), + [](const Session& s) + { + return s.visible; + }); + if (first_visible == sessions.end()) + { + std::cerr << "no visible session to save" << std::endl; + return false; + } + const Eigen::Vector3d file_offset = first_visible->point_clouds_container.offset; + + if (sessions.size() > 65535) + { + std::cerr << "warning: more than 65535 sessions, point_source_ID capped at 65535\n"; + } + + LazWriter writer; + if (!writer.open(output_las_name, file_offset.x(), file_offset.y(), file_offset.z())) + { + std::cerr << "problem with saving file: " << output_las_name << std::endl; + return false; + } + + for (size_t session_idx = 0; session_idx < sessions.size(); ++session_idx) + { + const Session& session = sessions[session_idx]; + if (!session.visible) + continue; + + const Eigen::Vector3d shift = session.point_clouds_container.offset - file_offset; + const unsigned short psid = static_cast(std::min(session_idx, 65535)); + + for (const auto& p : session.point_clouds_container.point_clouds) + { + if (!p.visible) + continue; + + for (size_t i = 0; i < p.points_local.size(); ++i) + { + const Eigen::Vector3d vp = p.m_pose * p.points_local[i] + shift; + const unsigned short inten = (i < p.intensities.size()) ? p.intensities[i] : 0; + const double ts = (i < p.timestamps.size()) ? p.timestamps[i] : 0.0; + + if (!writer.writePoint(vp, inten, ts, file_offset.x(), file_offset.y(), file_offset.z(), psid)) + { + return false; + } + } + } + } + + return writer.close(); +} From 0e7ad1629378800805368b0be592fd8d60109395 Mon Sep 17 00:00:00 2001 From: janusz Date: Sun, 22 Nov 2026 15:41:01 +0100 Subject: [PATCH 9/9] clang formating --- .../multi_session_registration.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/apps/multi_session_registration/multi_session_registration.cpp b/apps/multi_session_registration/multi_session_registration.cpp index 00b3a1b53..172a647b4 100644 --- a/apps/multi_session_registration/multi_session_registration.cpp +++ b/apps/multi_session_registration/multi_session_registration.cpp @@ -3181,8 +3181,8 @@ void display() if (ImGui::MenuItem("Save all point clouds as single LAZ", nullptr, nullptr, loaded_sessions && !sessions.empty())) { - const std::string output_file_name = - mandeye::fd::SaveFileDialog("Save all point clouds as single LAZ", mandeye::fd::LAS_LAZ_filter, ".laz", "all_sessions.laz"); + const std::string output_file_name = mandeye::fd::SaveFileDialog( + "Save all point clouds as single LAZ", mandeye::fd::LAS_LAZ_filter, ".laz", "all_sessions.laz"); if (!output_file_name.empty()) { if (save_all_sessions_to_las(sessions, output_file_name)) @@ -3702,8 +3702,6 @@ void display() ImGui::Separator(); - - ImGui::EndMenu(); }