From 7387caee8befcc324aa65b9a6d6ff3e89d073f22 Mon Sep 17 00:00:00 2001 From: MichalPelka Date: Thu, 26 Nov 2026 23:34:02 +0100 Subject: [PATCH] ICP covariance matrix and Monte Carlo ICP uncertainty - PairWiseICP / PoseGraphLoopClosure::compute_icp_uncertainty return the sigmas together with IcpResidualStatistics, which now carries the pose covariance sigma0^2 * (J^T J)^-1. - PairWiseICP::compute_icp_montecarlo runs ICP from randomly perturbed start poses (fixed seed) and returns the spread of the results (IcpSpread); PoseGraphLoopClosure::compute_icp_montecarlo runs it on an edge. - PairWiseICP::verbose (default true) silences the per-iteration log. - Step 2 loop closure GUI: an "uncertainty method" dropdown (point-to-point, point-to-plane, ICP Monte Carlo) with one Calculate button; shows the result tables and the 6x6 covariance in mm and degrees. The active edge's translation ellipsoid is drawn for the shown result (yellow: point-to-point/ plane at the current pose; magenta: Monte Carlo at the mean result). - session_uncertainty_calculation: new options --method, --search-radius, --runs, --start-offset-m, --start-offset-deg, --node-step, --decimation, --tls-decimation; the TLS is cropped to each chunk; one progress line per node with ETA. Defaults keep the previous results. The CSV gains the upper triangle of the pose covariance (cov_px_px ... cov_ka_ka) as extra columns. - scripts/plot_session_uncertainty.py plots that CSV: trajectory top view coloured by position sigma with x-y covariance ellipses, and the pose sigmas over time. Co-Authored-By: Claude Opus 5.5 Signed-off-by: MichalPelka --- .../multi_view_tls_registration_gui.cpp | 36 ++- apps/session_uncertainty_calculation/main.cpp | 287 ++++++++++++++++-- .../Core/manual_pose_graph_loop_closure.h | 42 ++- .../Core/pair_wise_iterative_closest_point.h | 53 +++- core/include/Core/pose_graph_loop_closure.h | 21 +- core/src/manual_pose_graph_loop_closure.cpp | 217 ++++++++++--- .../src/pair_wise_iterative_closest_point.cpp | 189 ++++++++---- core/src/pose_graph_loop_closure.cpp | 36 ++- scripts/README.md | 6 + scripts/plot_session_uncertainty.py | 205 +++++++++++++ 10 files changed, 944 insertions(+), 148 deletions(-) create mode 100644 scripts/plot_session_uncertainty.py 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 75f5ffa4..26e414cf 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 @@ -270,6 +270,7 @@ void observationPickingRender(const ObservationPicking& observation_picking); void renderLoopClosure( PointClouds& point_clouds_container, int index_loop_closure_source, int index_loop_closure_target, int before, int after); void renderLoopClosureLabels(PointClouds& point_clouds_container); +void drawEllipsoid(const Eigen::Matrix3d& transform, const Eigen::Vector3d& center, Color color); void renderGroundControlPoints(const GroundControlPoints& ground_control_points, const PointClouds& point_clouds_container); void renderGroundControlPointsLabels(const GroundControlPoints& ground_control_points, const PointClouds& point_clouds_container); void renderGNSS(const GNSS& gnss, const PointClouds& point_clouds_container); @@ -4312,6 +4313,34 @@ void renderLoopClosure( Vector3 pMidUp = Vector3{ static_cast(midUp.x()), static_cast(midUp.y()), static_cast(midUp.z()) }; DrawCylinderEx(pMid, pMidUp, tubeRadius, tubeRadius, 8, c); } + + // px, py, pz ellipsoid of the active edge's ICP uncertainty (Monte Carlo: magenta, at the mean result; else yellow, + // at the current pose) around the index_to scan origin. The covariance is in the index_from scan's frame and is + // rotated here to world. + const auto& loop_closure = session.pose_graph_loop_closure; + if (loop_closure.icp_uncertainty_is_current()) + { + const auto& uncertainty = loop_closure.icp_uncertainty; + const bool monte_carlo = uncertainty.method == ManualPoseGraphLoopClosure::IcpUncertaintyMethod::MonteCarlo; + const Eigen::Matrix& covariance_6 = monte_carlo ? uncertainty.spread.covariance : uncertainty.residuals.covariance; + if (covariance_6.allFinite()) + { + const auto& edge = loop_closure.edges[uncertainty.edge]; + const Eigen::Affine3d& m_from = pointClouds[edge.index_from].m_pose; + const TaitBryanPose& pose = edge.relative_pose_tb; + Eigen::Vector3d center_local(pose.px, pose.py, pose.pz); + if (monte_carlo) + { + center_local += uncertainty.spread.mean_offset.head<3>(); + } + const Eigen::Matrix3d covariance = m_from.linear() * covariance_6.topLeftCorner<3, 3>() * m_from.linear().transpose(); + // Eigen decomposition rather than Cholesky: a direction can have zero variance. + const Eigen::SelfAdjointEigenSolver eigen_solver(covariance); + const Eigen::Matrix3d transform = uncertainty.ellipsoid_sigma * eigen_solver.eigenvectors() * + eigen_solver.eigenvalues().cwiseMax(0.0).cwiseSqrt().asDiagonal(); + drawEllipsoid(transform, m_from * center_local, monte_carlo ? MAGENTA : YELLOW); + } + } } // Was GroundControlPoints::draw_ellipse() (core/src/ground_control_points.cpp) @@ -4323,8 +4352,13 @@ void renderLoopClosure( void drawUncertaintyEllipse(const Eigen::Matrix3d& covar, const Eigen::Vector3d& mean, Color color) { Eigen::LLT> cholSolver(covar); - Eigen::Matrix3d transform = cholSolver.matrixL(); + drawEllipsoid(cholSolver.matrixL(), mean, color); +} +//! Wireframe of the unit sphere mapped by x -> transform * x + center. +void drawEllipsoid(const Eigen::Matrix3d& transform, const Eigen::Vector3d& center, Color color) +{ + const Eigen::Vector3d& mean = center; const double pi = 3.141592; const double di = 0.02; const double dj = 0.04; diff --git a/apps/session_uncertainty_calculation/main.cpp b/apps/session_uncertainty_calculation/main.cpp index 858a7d2b..97da7fc4 100644 --- a/apps/session_uncertainty_calculation/main.cpp +++ b/apps/session_uncertainty_calculation/main.cpp @@ -1,15 +1,55 @@ #include "Core/color_las_loader.h" #include "Core/pair_wise_iterative_closest_point.h" #include "Core/session.h" +#include "Core/transformations.h" #include #include +#include +#include #include #include #include #include #include +#include +#include #include +#include + +namespace +{ + enum class Method + { + PointToPoint, + PointToPlane, + MonteCarlo + }; + + //! Seconds as h:mm:ss. + std::string format_duration(double seconds) + { + const long long total = static_cast(seconds + 0.5); + std::ostringstream out; + out << total / 3600 << ':' << std::setw(2) << std::setfill('0') << (total / 60) % 60 << ':' << std::setw(2) << std::setfill('0') + << total % 60; + return out.str(); + } + + void print_usage(const char* program) + { + std::cerr << "Usage: " << program << " [options]\n" + << "Options:\n" + << " --method point_to_point|point_to_plane|monte_carlo uncertainty method (default point_to_point)\n" + << " --search-radius ICP search radius (default 0.3)\n" + << " --runs monte_carlo: ICP runs per node (default 20)\n" + << " --start-offset-m monte_carlo: start offset on px, py, pz (default 0.05)\n" + << " --start-offset-deg monte_carlo: start offset on om, fi, ka (default 0.5)\n" + << " --node-step compute every n-th trajectory node of each chunk (default 1: all)\n" + << " --decimation voxel size the session points are decimated to (default 0: off)\n" + << " --tls-decimation voxel size the TLS points are decimated to (default 0: off)" << std::endl; + } +} // namespace int main(int argc, char* argv[]) { @@ -21,7 +61,72 @@ int main(int argc, char* argv[]) if (argc < 4) { - std::cerr << "Usage: " << argv[0] << " " << std::endl; + print_usage(argv[0]); + return 1; + } + + Method method = Method::PointToPoint; + double search_radius = 0.3; + int number_of_runs = 20; + double start_offset_m = 0.05; + double start_offset_deg = 0.5; + int node_step = 1; + double decimation = 0.0; + double tls_decimation = 0.0; + for (int i = 4; i < argc; i++) + { + const std::string option = argv[i]; + if (i + 1 >= argc) + { + std::cerr << "Missing value for option: " << option << std::endl; + print_usage(argv[0]); + return 1; + } + const std::string value = argv[++i]; + try + { + if (option == "--method") + { + if (value == "point_to_point") + method = Method::PointToPoint; + else if (value == "point_to_plane") + method = Method::PointToPlane; + else if (value == "monte_carlo") + method = Method::MonteCarlo; + else + throw std::invalid_argument(value); + } + else if (option == "--search-radius") + search_radius = std::stod(value); + else if (option == "--runs") + number_of_runs = std::stoi(value); + else if (option == "--start-offset-m") + start_offset_m = std::stod(value); + else if (option == "--start-offset-deg") + start_offset_deg = std::stod(value); + else if (option == "--node-step") + node_step = std::stoi(value); + else if (option == "--decimation") + decimation = std::stod(value); + else if (option == "--tls-decimation") + tls_decimation = std::stod(value); + else + { + std::cerr << "Unknown option: " << option << std::endl; + print_usage(argv[0]); + return 1; + } + } catch (const std::exception&) + { + std::cerr << "Invalid value for " << option << ": " << value << std::endl; + return 1; + } + } + if (search_radius <= 0.0 || number_of_runs < 2 || start_offset_m < 0.0 || start_offset_deg < 0.0 || node_step < 1 || decimation < 0.0 || + tls_decimation < 0.0) + { + std::cerr << "Invalid options: need search radius > 0, runs >= 2, start offsets >= 0, node step >= 1 and decimations >= 0" + << std::endl; return 1; } @@ -65,7 +170,7 @@ int main(int argc, char* argv[]) } Session session; - if (!session.load(sessionDataFile.string(), /*is_decimate=*/false, 0.0, 0.0, 0.0, /*calculate_offset=*/false)) + if (!session.load(sessionDataFile.string(), decimation > 0.0, decimation, decimation, decimation, /*calculate_offset=*/false)) { std::cerr << "Failed to load session: " << sessionDataFile.string() << std::endl; return 1; @@ -89,14 +194,41 @@ int main(int argc, char* argv[]) { target_global.emplace_back(p.point); } + if (tls_decimation > 0.0) + { + PointCloud tls; + tls.points_local = std::move(target_global); + tls.decimate(tls_decimation, tls_decimation, tls_decimation); + target_global = std::move(tls.points_local); + std::cout << "TLS decimated to " << target_global.size() << " points (voxel " << tls_decimation << " m)" << std::endl; + } std::vector icp_uncertainties; - std::vector icp_residuals; + std::vector icp_residuals; // point_to_point, point_to_plane + std::vector icp_spreads; // monte_carlo std::vector> node_timestamps; // std::vector node_positions; - for (const auto& pointCloud : session.point_clouds_container.point_clouds) + const auto& point_clouds = session.point_clouds_container.point_clouds; + size_t number_of_nodes = 0; + for (const auto& pointCloud : point_clouds) + { + number_of_nodes += (pointCloud.local_trajectory.size() + node_step - 1) / node_step; + } + size_t nodes_done = 0; + const char* const method_names[] = { "point_to_point", "point_to_plane", "monte_carlo" }; + std::cout << "Computing " << method_names[static_cast(method)] << " uncertainty for " << number_of_nodes << " trajectory nodes in " + << point_clouds.size() << " chunks (search radius " << search_radius << " m"; + if (method == Method::MonteCarlo) + { + std::cout << ", " << number_of_runs << " ICP runs per node"; + } + std::cout << ")" << std::endl; + const auto start_time = std::chrono::steady_clock::now(); + + for (size_t chunk_index = 0; chunk_index < point_clouds.size(); chunk_index++) { + const PointCloud& pointCloud = point_clouds[chunk_index]; std::vector source_local; for (const auto& p : pointCloud.points_local) { @@ -128,8 +260,48 @@ int main(int argc, char* argv[]) }*/ // + // Only TLS points near the chunk can be ICP neighbours: crop the target to the chunk's bounding box (points and + // trajectory) grown by the search radius, so each ICP indexes a small cloud instead of the whole TLS scan. + // Monte Carlo also moves the start pose by up to the start offsets (rotation about the node, at most the box + // diagonal away), plus 1 m for ICP drift. + Eigen::AlignedBox3d chunk_box; + for (const auto& p : source_global) + { + chunk_box.extend(p); + } for (const auto& n : pointCloud.local_trajectory) { + chunk_box.extend((m_pose * n.m_pose).translation()); + } + double margin = search_radius; + if (method == Method::MonteCarlo) + { + const double start_offset_rad = deg2rad(start_offset_deg); + margin += std::sqrt(3.0) * (start_offset_m + start_offset_rad * chunk_box.diagonal().norm()) + 1.0; + } + const Eigen::AlignedBox3d crop_box( + chunk_box.min() - Eigen::Vector3d::Constant(margin), chunk_box.max() + Eigen::Vector3d::Constant(margin)); + std::vector target_chunk; + for (const auto& p : target_global) + { + if (crop_box.contains(p)) + { + target_chunk.emplace_back(p); + } + } + std::cout << "chunk: " << source_global.size() << " points, " << target_chunk.size() << " of " << target_global.size() + << " TLS points within " << std::fixed << std::setprecision(2) << margin << " m of it" << std::defaultfloat + << std::setprecision(6) << std::endl; + + for (size_t node_index = 0; node_index < pointCloud.local_trajectory.size(); node_index += node_step) + { + const auto& n = pointCloud.local_trajectory[node_index]; + // "[ 12/7637 0.2%] chunk 1/61 node 12/125" + std::ostringstream where; + where << '[' << std::setw(static_cast(std::to_string(number_of_nodes).size())) << nodes_done + 1 << '/' << number_of_nodes + << ' ' << std::fixed << std::setprecision(1) << std::setw(5) << 100.0 * (nodes_done + 1) / number_of_nodes << "%] chunk " + << chunk_index + 1 << '/' << point_clouds.size() << " node " << node_index + 1 << '/' + << pointCloud.local_trajectory.size(); Eigen::Affine3d m_global = m_pose * n.m_pose; Eigen::Affine3d m_local = m_global.inverse(); @@ -142,21 +314,50 @@ int main(int argc, char* argv[]) } PairWiseICP icp; - IcpResidualStatistics residuals; - TaitBryanPose icp_uncertainty = - icp.compute_icp_uncertainty(source_local_for_single_trajectory_node, target_global, m_global, 0.3, &residuals); - // icp.compute_icp_uncertainty_point_to_plane(source_local_for_single_trajectory_node, target_global, m_global, 0.3); - 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.verbose = false; + TaitBryanPose icp_uncertainty; + if (method == Method::MonteCarlo) + { + const IcpSpread spread = icp.compute_icp_montecarlo( + source_local_for_single_trajectory_node, + target_chunk, + m_global, + search_radius, + 30, + number_of_runs, + start_offset_m, + deg2rad(start_offset_deg), + [&](int run) + { + std::cout << '\r' << where.str() << ": ICP run " << run << '/' << number_of_runs << std::flush; + }); + std::cout << '\r'; + const Eigen::Matrix sigma = spread.covariance.diagonal().cwiseSqrt(); + icp_uncertainty = TaitBryanPose{ sigma(0), sigma(1), sigma(2), sigma(3), sigma(4), sigma(5) }; + icp_spreads.emplace_back(spread); + } + else + { + IcpResidualStatistics residuals; + std::tie(icp_uncertainty, residuals) = method == Method::PointToPlane + ? icp.compute_icp_uncertainty_point_to_plane( + source_local_for_single_trajectory_node, target_chunk, m_global, search_radius) + : icp.compute_icp_uncertainty(source_local_for_single_trajectory_node, target_chunk, m_global, search_radius); + icp_residuals.emplace_back(residuals); + } + nodes_done++; + const double elapsed = std::chrono::duration(std::chrono::steady_clock::now() - start_time).count(); + const double per_node = elapsed / nodes_done; + std::cout << where.str() << std::fixed << std::setprecision(4) << " | sigma [mm] " << icp_uncertainty.px * 1000.0 << ' ' + << icp_uncertainty.py * 1000.0 << ' ' << icp_uncertainty.pz * 1000.0 << " [deg] " << std::setprecision(4) + << rad2deg(icp_uncertainty.om) << ' ' << rad2deg(icp_uncertainty.fi) << ' ' << rad2deg(icp_uncertainty.ka) + << std::setprecision(1) << " | " << per_node << " s/node, elapsed " << format_duration(elapsed) << ", ETA " + << format_duration(per_node * (number_of_nodes - nodes_done)) << std::defaultfloat << std::setprecision(6) + << std::endl; // TaitBryanPose icp_uncertainty_alternative_approach = icp_uncertainties.emplace_back(icp_uncertainty); - icp_residuals.emplace_back(residuals); node_timestamps.emplace_back(n.timestamps); node_positions.emplace_back(m_global.translation()); } @@ -170,17 +371,61 @@ int main(int argc, char* argv[]) } // Standard deviations: sigma_px/py/pz in metres, sigma_om/fi/ka in radians (inf = pose not constrained). - // Residuals: sum_squared_residuals in m^2, sigma0 = sqrt(sum_squared_residuals / (observations - 6)) in metres. - csv << "timestamp_lidar,timestamp_unix,x,y,z,sigma_px,sigma_py,sigma_pz,sigma_om,sigma_fi,sigma_ka," - "sum_squared_residuals,number_of_correspondences,number_of_observations,sigma0(RMS)\n"; + // point_to_point, point_to_plane: residuals, sum_squared_residuals in m^2, + // sigma0 = sqrt(sum_squared_residuals / (observations - 6)) in metres. + // monte_carlo: runs, converged runs and the mean converged pose minus the node pose (m, rad). + // Then the upper triangle of the 6x6 pose covariance (px, py, pz [m], om, fi, ka [rad]), row by row; nan = not computed. + const char* const parameter_names[] = { "px", "py", "pz", "om", "fi", "ka" }; + csv << "timestamp_lidar,timestamp_unix,x,y,z,sigma_px,sigma_py,sigma_pz,sigma_om,sigma_fi,sigma_ka,"; + if (method == Method::MonteCarlo) + { + csv << "number_of_runs,number_of_converged_runs,mean_offset_px,mean_offset_py,mean_offset_pz,mean_offset_om,mean_offset_fi," + "mean_offset_ka"; + } + else + { + csv << "sum_squared_residuals,number_of_correspondences,number_of_observations,sigma0(RMS)"; + } + for (int row = 0; row < 6; row++) + { + for (int col = row; col < 6; col++) + { + csv << ",cov_" << parameter_names[row] << '_' << parameter_names[col]; + } + } + csv << '\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]; - 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 << ',' - << r.sum_squared_residuals << ',' << r.number_of_correspondences << ',' << r.number_of_observations << ',' << r.sigma0 << '\n'; + << ',' << node_positions[i].z() << ',' << u.px << ',' << u.py << ',' << u.pz << ',' << u.om << ',' << u.fi << ',' << u.ka; + Eigen::Matrix covariance; + if (method == Method::MonteCarlo) + { + const IcpSpread& spread = icp_spreads[i]; + csv << ',' << spread.number_of_runs << ',' << spread.number_of_converged_runs; + for (int k = 0; k < 6; k++) + { + csv << ',' << spread.mean_offset(k); + } + covariance = spread.covariance; + } + else + { + const IcpResidualStatistics& r = icp_residuals[i]; + csv << ',' << r.sum_squared_residuals << ',' << r.number_of_correspondences << ',' << r.number_of_observations << ',' + << r.sigma0; + covariance = r.covariance; + } + for (int row = 0; row < 6; row++) + { + for (int col = row; col < 6; col++) + { + csv << ',' << covariance(row, col); + } + } + csv << '\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 53222c71..8632d8c2 100644 --- a/core/include/Core/manual_pose_graph_loop_closure.h +++ b/core/include/Core/manual_pose_graph_loop_closure.h @@ -39,18 +39,48 @@ 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. + //! Methods of the "Calculate ICP uncertainty" dropdown. + enum class IcpUncertaintyMethod : int + { + PointToPoint = 0, //!< sigma0^2 * (J^T J)^-1 from point-to-point residuals + PointToPlane = 1, //!< sigma0^2 * (J^T J)^-1 from point-to-plane residuals + MonteCarlo = 2, //!< spread of ICP runs from randomly perturbed start poses + }; + //! "Calculate ICP uncertainty": its settings and last result. The result is shown only while the method, the edge + //! and the relative pose it was computed for are unchanged. struct IcpUncertainty { + IcpUncertaintyMethod method = IcpUncertaintyMethod::PointToPlane; + int number_of_runs = 20; //!< Monte Carlo + double start_offset_m = 0.05; //!< Monte Carlo + double start_offset_deg = 0.5; //!< Monte Carlo + //! Size of the drawn translation ellipsoid, in standard deviations. + double ellipsoid_sigma = 10.0; + + IcpUncertaintyMethod computed_method = IcpUncertaintyMethod::PointToPlane; int edge = -1; TaitBryanPose relative_pose; - TaitBryanPose point_to_point; - TaitBryanPose point_to_plane; - IcpResidualStatistics point_to_point_residuals; - IcpResidualStatistics point_to_plane_residuals; + IcpResidualStatistics residuals; //!< point-to-point, point-to-plane + IcpSpread spread; //!< Monte Carlo }; IcpUncertainty icp_uncertainty; + //! True when edge is the active edge and its relative pose still equals relative_pose. + bool is_active_edge_at(int edge, const TaitBryanPose& relative_pose) const + { + if (edge != index_active_edge || edge < 0 || edge >= static_cast(edges.size())) + { + return false; + } + const TaitBryanPose& a = edges[edge].relative_pose_tb; + const TaitBryanPose& b = relative_pose; + return a.px == b.px && a.py == b.py && a.pz == b.pz && a.om == b.om && a.fi == b.fi && a.ka == b.ka; + } + //! True when icp_uncertainty was computed with the selected method for the active edge at its current relative pose. + bool icp_uncertainty_is_current() const + { + return icp_uncertainty.computed_method == icp_uncertainty.method && + is_active_edge_at(icp_uncertainty.edge, icp_uncertainty.relative_pose); + } //! "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 360ebd06..f6b9cdb8 100644 --- a/core/include/Core/pair_wise_iterative_closest_point.h +++ b/core/include/Core/pair_wise_iterative_closest_point.h @@ -3,11 +3,13 @@ #include #include +#include #include #include +#include -//! Residuals behind an ICP uncertainty estimate. +//! Residuals and pose covariance behind an ICP uncertainty estimate. struct IcpResidualStatistics { double sum_squared_residuals = 0.0; //!< [m^2] @@ -16,6 +18,23 @@ struct IcpResidualStatistics //! 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(); + //! Pose covariance sigma0^2 * (J^T J)^-1, rows and columns px, py, pz, om, fi, ka ([m^2], [m*rad], [rad^2]); NaN + //! when it is not computed (too few correspondences, degenerate geometry). + Eigen::Matrix covariance = Eigen::Matrix::Constant(std::numeric_limits::quiet_NaN()); +}; + +//! Spread of an ICP result over runs started from randomly perturbed poses (Monte Carlo). Parameters are in the order +//! px, py, pz [m], om, fi, ka [rad]. +struct IcpSpread +{ + int number_of_runs = 0; + int number_of_converged_runs = 0; //!< runs where PairWiseICP::compute() succeeded + //! Sample standard deviations of the starting offsets from the reference pose. + Eigen::Matrix start_sigma = Eigen::Matrix::Constant(std::numeric_limits::quiet_NaN()); + //! Mean converged pose minus the reference one. + Eigen::Matrix mean_offset = Eigen::Matrix::Constant(std::numeric_limits::quiet_NaN()); + //! Sample covariance of the converged poses; NaN with fewer than 2 converged runs. + Eigen::Matrix covariance = Eigen::Matrix::Constant(std::numeric_limits::quiet_NaN()); }; class PairWiseICP @@ -24,6 +43,9 @@ class PairWiseICP PairWiseICP() = default; ~PairWiseICP() = default; + //! false: compute() and compute_icp_montecarlo() print only failures, not every iteration. + bool verbose = true; + bool compute( const std::vector& source, const std::vector& target, @@ -32,23 +54,38 @@ class PairWiseICP 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( + //! sigma0^2 = sum r^2 / (3n - 6). + //! @return the standard deviations and the residual statistics with the covariance + std::pair compute_icp_uncertainty( const std::vector& source, const std::vector& target, const Eigen::Affine3d& m_pose_result, - double search_radious, - IcpResidualStatistics* statistics = nullptr); + double search_radious); //! 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( + //! @return the standard deviations and the residual statistics with the covariance + std::pair compute_icp_uncertainty_point_to_plane( const std::vector& source, const std::vector& target, const Eigen::Affine3d& m_pose_result, + double search_radious); + + //! Monte Carlo ICP: runs compute() number_of_runs times from m_pose plus a random Tait-Bryan offset, uniform in + //! [-start_offset_m, start_offset_m] on px, py, pz and [-start_offset_rad, start_offset_rad] on om, fi, ka, and + //! returns the spread of the results around m_pose. The offsets come from a fixed seed, so the result is + //! repeatable. Takes time. + //! @param on_run_done if given, called after each run with the number of runs done + IcpSpread compute_icp_montecarlo( + const std::vector& source, + const std::vector& target, + const Eigen::Affine3d& m_pose, double search_radious, - IcpResidualStatistics* statistics = nullptr); + int number_of_iterations, + int number_of_runs, + double start_offset_m, + double start_offset_rad, + const std::function& on_run_done = {}); }; diff --git a/core/include/Core/pose_graph_loop_closure.h b/core/include/Core/pose_graph_loop_closure.h index 52395e08..445339b5 100644 --- a/core/include/Core/pose_graph_loop_closure.h +++ b/core/include/Core/pose_graph_loop_closure.h @@ -79,16 +79,27 @@ class PoseGraphLoopClosure //! 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( + //! @return the standard deviations (infinity for every parameter when the geometry does not constrain the pose) and + //! the residual statistics with the covariance + std::pair 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); + bool point_to_plane); + //! Monte Carlo ICP ("ICP spread") of one edge's relative pose: PairWiseICP::compute_icp_montecarlo() on the same + //! clouds as run_icp(). The edge is left unchanged. + IcpSpread compute_icp_montecarlo( + const PointClouds& point_clouds_container, + int index_active_edge, + double search_radius, + int number_of_iterations, + int num_edge_extended_before, + int num_edge_extended_after, + int number_of_runs, + double start_offset_m, + double start_offset_rad) const; //! 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 99412915..a16b248f 100644 --- a/core/src/manual_pose_graph_loop_closure.cpp +++ b/core/src/manual_pose_graph_loop_closure.cpp @@ -25,6 +25,45 @@ #include +namespace +{ + constexpr const char* pose_parameter_names[] = { "px", "py", "pz", "om", "fi", "ka" }; + + //! Factors from px, py, pz [m] and om, fi, ka [rad] to mm and degrees. + Eigen::Matrix to_mm_deg() + { + return (Eigen::Matrix() << 1000.0, 1000.0, 1000.0, rad2deg(1.0), rad2deg(1.0), rad2deg(1.0)).finished(); + } + + //! Pose covariance (px, py, pz [m], om, fi, ka [rad]) as a table in mm and degrees, diagonal highlighted. + void covariance_table(const char* id, const Eigen::Matrix& covariance_m_rad) + { + const Eigen::Matrix scale = to_mm_deg(); + const Eigen::Matrix covariance = scale.asDiagonal() * covariance_m_rad * scale.asDiagonal(); + if (ImGui::BeginTable(id, 7, ImGuiTableFlags_Borders | ImGuiTableFlags_SizingFixedFit)) + { + ImGui::TableSetupColumn(""); + for (const char* name : pose_parameter_names) + ImGui::TableSetupColumn(name); + ImGui::TableHeadersRow(); + for (int row = 0; row < 6; row++) + { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(pose_parameter_names[row]); + for (int col = 0; col < 6; col++) + { + ImGui::TableNextColumn(); + if (row == col) + ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, ImGui::GetColorU32(ImGuiCol_TextSelectedBg)); + ImGui::Text("% .9f", covariance(row, col)); + } + } + ImGui::EndTable(); + } + } +} // namespace + void ManualPoseGraphLoopClosure::icp_all_edges_step( PointClouds& point_clouds_container, int num_edge_extended_before, int num_edge_extended_after) { @@ -337,6 +376,45 @@ 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); + const char* const icp_uncertainty_methods[] = { "point-to-point", "point-to-plane", "ICP Monte Carlo" }; + int method = static_cast(icp_uncertainty.method); + ImGui::PushItemWidth(ImGuiNumberWidth * 2); + ImGui::Combo("uncertainty method", &method, icp_uncertainty_methods, IM_ARRAYSIZE(icp_uncertainty_methods)); + ImGui::PopItemWidth(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip( + "point-to-point, point-to-plane: covariance sigma0^2 * (J^T J)^-1 from the ICP normal matrix at the current\n" + "pose. Formal values: neighbouring LiDAR points are correlated, so they are optimistic. Use them to compare\n" + "edges, not as absolute accuracy.\n" + "ICP Monte Carlo: covariance of the results of the edge's ICP (30 iterations) run 'runs' times, each from\n" + "the current relative pose plus a random offset up to the start offsets. Takes time."); + icp_uncertainty.method = static_cast(method); + const bool monte_carlo = icp_uncertainty.method == IcpUncertaintyMethod::MonteCarlo; + + ImGui::PushItemWidth(ImGuiNumberWidth); + if (monte_carlo) + { + ImGui::InputInt("runs", &icp_uncertainty.number_of_runs); + ImGui::SameLine(); + ImGui::InputDouble("start offset [m]", &icp_uncertainty.start_offset_m, 0.0, 0.0, "%.3f"); + ImGui::SameLine(); + ImGui::InputDouble("start offset [deg]", &icp_uncertainty.start_offset_deg, 0.0, 0.0, "%.2f"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip( + "Each run starts from the current relative pose plus a random offset, uniform in +- these offsets."); + ImGui::SameLine(); + } + ImGui::InputDouble("ellipsoid size [sigma]", &icp_uncertainty.ellipsoid_sigma, 0.0, 0.0, "%.1f"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip( + "px, py, pz ellipsoid of the active edge, +- this many standard deviations along its axes, around the\n" + "edge's 'index_to' scan origin (Monte Carlo: at the mean result)."); + ImGui::PopItemWidth(); + icp_uncertainty.number_of_runs = std::max(icp_uncertainty.number_of_runs, 2); + icp_uncertainty.start_offset_m = std::max(icp_uncertainty.start_offset_m, 0.0); + icp_uncertainty.start_offset_deg = std::max(icp_uncertainty.start_offset_deg, 0.0); + icp_uncertainty.ellipsoid_sigma = std::max(icp_uncertainty.ellipsoid_sigma, 0.0); + char icp_uncertainty_label[128]; std::snprintf( icp_uncertainty_label, @@ -345,61 +423,104 @@ void ManualPoseGraphLoopClosure::Gui( search_radious); if (ImGui::Button(icp_uncertainty_label)) { + icp_uncertainty.computed_method = icp_uncertainty.method; 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 (monte_carlo) + { + icp_uncertainty.spread = compute_icp_montecarlo( + point_clouds_container, + index_active_edge, + search_radious, + 30, + num_edge_extended_before, + num_edge_extended_after, + icp_uncertainty.number_of_runs, + icp_uncertainty.start_offset_m, + deg2rad(icp_uncertainty.start_offset_deg)); + } + else + { + icp_uncertainty.residuals = compute_icp_uncertainty( + point_clouds_container, + index_active_edge, + search_radious, + num_edge_extended_before, + num_edge_extended_after, + icp_uncertainty.method == IcpUncertaintyMethod::PointToPlane) + .second; + } } - 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) + + if (icp_uncertainty_is_current() && !monte_carlo) { - const auto show = [](const char* label, const TaitBryanPose& s, const IcpResidualStatistics& r) + const IcpResidualStatistics& r = icp_uncertainty.residuals; + if (ImGui::BeginTable("residuals", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_SizingFixedFit)) { - 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); + ImGui::TableSetupColumn("sum of squared residuals [m^2]"); + ImGui::TableSetupColumn("correspondences"); + ImGui::TableSetupColumn("observations"); + ImGui::TableSetupColumn("sigma0 (RMS) [m]"); + ImGui::TableHeadersRow(); + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::Text("%.6f", r.sum_squared_residuals); + ImGui::TableNextColumn(); + ImGui::Text("%d", r.number_of_correspondences); + ImGui::TableNextColumn(); + ImGui::Text("%d", r.number_of_observations); + ImGui::TableNextColumn(); + ImGui::Text("%.4f", 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); + "sigma0 = sqrt(sum of squared residuals / (observations - 6)): RMS residual per observation."); + ImGui::EndTable(); + } + ImGui::Text(" covariance [mm^2, mm*deg, deg^2]:"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip( + "covariance = sigma0^2 * (J^T J)^-1 of px, py, pz [mm] and om, fi, ka [deg].\n" + "The highlighted diagonal holds the variances (sigma^2).\n" + "nan = not computed (too few correspondences or degenerate geometry)."); + covariance_table("covariance", r.covariance); + } + + if (icp_uncertainty_is_current() && monte_carlo) + { + const IcpSpread& spread = icp_uncertainty.spread; + ImGui::Text("%d of %d runs converged", spread.number_of_converged_runs, spread.number_of_runs); + const Eigen::Matrix scale = to_mm_deg(); + if (ImGui::BeginTable("icp_spread", 5, ImGuiTableFlags_Borders | ImGuiTableFlags_SizingFixedFit)) + { + ImGui::TableSetupColumn("[mm, deg]"); + ImGui::TableSetupColumn("start sigma"); + ImGui::TableSetupColumn("result sigma"); + ImGui::TableSetupColumn("result / start"); + ImGui::TableSetupColumn("mean result - current"); + ImGui::TableHeadersRow(); + for (int i = 0; i < 6; i++) + { + const double result_sigma = std::sqrt(spread.covariance(i, i)); + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(pose_parameter_names[i]); + ImGui::TableNextColumn(); + ImGui::Text("%.4f", spread.start_sigma(i) * scale(i)); + ImGui::TableNextColumn(); + ImGui::Text("%.4f", result_sigma * scale(i)); + ImGui::TableNextColumn(); + ImGui::Text("%.2f", result_sigma / spread.start_sigma(i)); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip( + "near 1: ICP does not pull that parameter back, the geometry does not constrain it.\n" + "near 0: ICP returns to the same value; result sigma is its repeatability."); + ImGui::TableNextColumn(); + ImGui::Text("% .4f", spread.mean_offset(i) * scale(i)); + } + ImGui::EndTable(); + } + ImGui::Text(" covariance of the results [mm^2, mm*deg, deg^2]:"); + covariance_table("icp_spread_covariance", spread.covariance); } 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 caeaa5d3..e0b91e64 100644 --- a/core/src/pair_wise_iterative_closest_point.cpp +++ b/core/src/pair_wise_iterative_closest_point.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include @@ -20,7 +21,8 @@ bool PairWiseICP::compute( int number_of_iterations, Eigen::Affine3d& m_pose_result) { - std::cout << "PairWiseICP::compute" << std::endl; + if (verbose) + std::cout << "PairWiseICP::compute" << std::endl; bool multithread = true; // The target and the search radius don't change between iterations, so its bucket index is built once. @@ -79,7 +81,8 @@ bool PairWiseICP::compute( for (int iter = 0; iter < number_of_iterations; iter++) { - std::cout << "iteration: " << iter + 1 << " of: " << number_of_iterations << std::endl; + if (verbose) + std::cout << "iteration: " << iter + 1 << " of: " << number_of_iterations << std::endl; Eigen::MatrixXd AtPA(6, 6); AtPA.setZero(); Eigen::MatrixXd AtPB(6, 1); @@ -252,11 +255,13 @@ bool PairWiseICP::compute( std::vector h_x; for (int k = 0; k < x.outerSize(); ++k) { - std::cout << "result pose updates" << std::endl; + if (verbose) + 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 (verbose) + std::cout << it.row() << " " << it.col() << " " << it.value() << std::endl; } } @@ -273,7 +278,8 @@ bool PairWiseICP::compute( pose.ka += h_x[counter++]; m_pose_result = affine_matrix_from_pose_tait_bryan(pose); - std::cout << "PairWiseICP::compute SUCCESS" << std::endl; + if (verbose) + std::cout << "PairWiseICP::compute SUCCESS" << std::endl; // return true; } else @@ -363,26 +369,25 @@ namespace 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). + //! Writes the residual statistics (sigma0 = sqrt(sum of squared residuals / (number_of_observations - 6))) and + //! resets the covariance to NaN. void fill_residual_statistics( - IcpResidualStatistics* statistics, double sum_squared_residuals, int number_of_correspondences, int number_of_observations) + IcpResidualStatistics& residual_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(); + residual_statistics.sum_squared_residuals = sum_squared_residuals; + residual_statistics.number_of_correspondences = number_of_correspondences; + residual_statistics.number_of_observations = number_of_observations; + residual_statistics.sigma0 = number_of_observations > 6 ? std::sqrt(sum_squared_residuals / (number_of_observations - 6)) + : std::numeric_limits::quiet_NaN(); + // Set by compute_icp_uncertainty_from_hessian(). + residual_statistics.covariance.setConstant(std::numeric_limits::quiet_NaN()); } TaitBryanPose compute_icp_uncertainty_from_hessian( - const Eigen::Matrix& AtPA, int number_of_observations, double sum_squared_residuals) + const Eigen::Matrix& AtPA, + int number_of_observations, + double sum_squared_residuals, + IcpResidualStatistics& statistics) { TaitBryanPose sigma = infinite_uncertainty(); @@ -409,6 +414,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(); + statistics.covariance = covariance; sigma.px = std::sqrt(covariance(0, 0)); sigma.py = std::sqrt(covariance(1, 1)); @@ -420,14 +426,14 @@ namespace } } // namespace -TaitBryanPose PairWiseICP::compute_icp_uncertainty( +std::pair PairWiseICP::compute_icp_uncertainty( const std::vector& source, const std::vector& target, const Eigen::Affine3d& m_pose_result, - double search_radious, - IcpResidualStatistics* statistics) + double search_radious) { bool multithread = true; + IcpResidualStatistics icp_residual_statistics; TaitBryanPose icp_uncertainty; icp_uncertainty.px = 0; icp_uncertainty.py = 0; @@ -612,50 +618,29 @@ TaitBryanPose PairWiseICP::compute_icp_uncertainty( 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); + fill_residual_statistics(icp_residual_statistics, sum_squared_residuals, counter_nn, 3 * counter_nn); 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; + return { icp_uncertainty, icp_residual_statistics }; } - /* - 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. - */ // 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); + icp_uncertainty = compute_icp_uncertainty_from_hessian(AtPA, 3 * counter_nn, sum_squared_residuals, icp_residual_statistics); - return icp_uncertainty; + return { icp_uncertainty, icp_residual_statistics }; } -TaitBryanPose PairWiseICP::compute_icp_uncertainty_point_to_plane( +std::pair 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) + double search_radious) { + IcpResidualStatistics residual_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; @@ -768,15 +753,111 @@ TaitBryanPose PairWiseICP::compute_icp_uncertainty_point_to_plane( counter += sum.counter; } // Each point-to-plane correspondence gives 1 observation (distance along the normal). - fill_residual_statistics(statistics, sum_squared_residuals, counter, counter); + fill_residual_statistics(residual_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(); + return { infinite_uncertainty(), residual_statistics }; } // Each point-to-plane correspondence gives 1 observation (distance along the normal). - return compute_icp_uncertainty_from_hessian(AtPA, counter, sum_squared_residuals); + const TaitBryanPose sigma = compute_icp_uncertainty_from_hessian(AtPA, counter, sum_squared_residuals, residual_statistics); + return { sigma, residual_statistics }; +} + +IcpSpread PairWiseICP::compute_icp_montecarlo( + const std::vector& source, + const std::vector& target, + const Eigen::Affine3d& m_pose, + double search_radious, + int number_of_iterations, + int number_of_runs, + double start_offset_m, + double start_offset_rad, + const std::function& on_run_done) +{ + using Vector6d = Eigen::Matrix; + using Matrix6d = Eigen::Matrix; + + const auto to_vector = [](const TaitBryanPose& p) + { + return (Vector6d() << p.px, p.py, p.pz, p.om, p.fi, p.ka).finished(); + }; + const Vector6d reference = to_vector(pose_tait_bryan_from_affine_matrix(m_pose)); + + // std::mt19937's output is fixed by the standard (unlike std::uniform_real_distribution's), so every platform + // draws the same offsets. + std::mt19937 generator(0); + const auto uniform = [&generator](double half_width) + { + return half_width * (2.0 * static_cast(generator()) / static_cast(std::mt19937::max()) - 1.0); + }; + + std::vector start_offsets; + std::vector result_offsets; + for (int run = 0; run < number_of_runs; run++) + { + Vector6d start_offset; + for (int i = 0; i < 6; i++) + { + start_offset(i) = uniform(i < 3 ? start_offset_m : start_offset_rad); + } + start_offsets.push_back(start_offset); + + const Vector6d start = reference + start_offset; + const TaitBryanPose start_pose{ start(0), start(1), start(2), start(3), start(4), start(5) }; + Eigen::Affine3d m_pose_run = affine_matrix_from_pose_tait_bryan(start_pose); + if (compute(source, target, search_radious, number_of_iterations, m_pose_run)) + { + Vector6d offset = to_vector(pose_tait_bryan_from_affine_matrix(m_pose_run)) - reference; + for (int i = 3; i < 6; i++) + { + offset(i) = std::remainder(offset(i), 2.0 * M_PI); // angle difference in [-pi, pi] + } + result_offsets.push_back(offset); + } + if (on_run_done) + on_run_done(run + 1); + } + + const auto mean_of = [](const std::vector& samples) + { + Vector6d sum = Vector6d::Zero(); + for (const auto& s : samples) + { + sum += s; + } + return Vector6d(sum / static_cast(samples.size())); + }; + const auto covariance_of = [&mean_of](const std::vector& samples) + { + const Vector6d mean = mean_of(samples); + Matrix6d sum = Matrix6d::Zero(); + for (const auto& s : samples) + { + sum += (s - mean) * (s - mean).transpose(); + } + return Matrix6d(sum / static_cast(samples.size() - 1)); + }; + + IcpSpread spread; + spread.number_of_runs = number_of_runs; + spread.number_of_converged_runs = static_cast(result_offsets.size()); + if (start_offsets.size() >= 2) + { + spread.start_sigma = covariance_of(start_offsets).diagonal().cwiseSqrt(); + } + if (!result_offsets.empty()) + { + spread.mean_offset = mean_of(result_offsets); + } + if (result_offsets.size() >= 2) + { + spread.covariance = covariance_of(result_offsets); + } + if (verbose) + std::cout << "ICP Monte Carlo: " << spread.number_of_converged_runs << " of " << number_of_runs << " runs converged" << std::endl; + return spread; } diff --git a/core/src/pose_graph_loop_closure.cpp b/core/src/pose_graph_loop_closure.cpp index 35496bcc..a11d3b4e 100644 --- a/core/src/pose_graph_loop_closure.cpp +++ b/core/src/pose_graph_loop_closure.cpp @@ -1316,14 +1316,13 @@ bool PoseGraphLoopClosure::run_icp( return false; } -TaitBryanPose PoseGraphLoopClosure::compute_icp_uncertainty( +std::pair 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) + bool point_to_plane) { const auto m_pose = affine_matrix_from_pose_tait_bryan(edges[index_active_edge].relative_pose_tb); std::vector source; @@ -1331,8 +1330,35 @@ TaitBryanPose PoseGraphLoopClosure::compute_icp_uncertainty( 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); + return point_to_plane ? icp.compute_icp_uncertainty_point_to_plane(source, target, m_pose, search_radius) + : icp.compute_icp_uncertainty(source, target, m_pose, search_radius); +} + +IcpSpread PoseGraphLoopClosure::compute_icp_montecarlo( + const PointClouds& point_clouds_container, + int index_active_edge, + double search_radius, + int number_of_iterations, + int num_edge_extended_before, + int num_edge_extended_after, + int number_of_runs, + double start_offset_m, + double start_offset_rad) const +{ + 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 icp.compute_icp_montecarlo( + source, + target, + affine_matrix_from_pose_tait_bryan(edges[index_active_edge].relative_pose_tb), + search_radius, + number_of_iterations, + number_of_runs, + start_offset_m, + start_offset_rad); } std::vector PoseGraphLoopClosure::icp_search_radii(float start_radius) diff --git a/scripts/README.md b/scripts/README.md index 30fdfc85..c3fe7c17 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -43,3 +43,9 @@ ``` python3 scripts/lio_ate.py golden.tum trajectory.tum --max-ate-m 0.001 ``` + +* `plot_session_uncertainty.py` — plots the CSV written by `session_uncertainty_calculation` (any `--method`): a top view of the trajectory coloured by the position sigma with the x-y covariance ellipses, and the pose sigmas over time with sigma0 and correspondences (or converged Monte Carlo runs). Shows the figures, or saves them with `--output`. Needs `numpy` and `matplotlib`: + + ``` + python3 scripts/plot_session_uncertainty.py uncertainty.csv --output uncertainty.png + ``` diff --git a/scripts/plot_session_uncertainty.py b/scripts/plot_session_uncertainty.py new file mode 100644 index 00000000..b38bd4b2 --- /dev/null +++ b/scripts/plot_session_uncertainty.py @@ -0,0 +1,205 @@ +#!/usr/bin/env python3 +"""Plot the trajectory and pose uncertainty written by session_uncertainty_calculation. + +Reads the CSV of any --method (point_to_point, point_to_plane, monte_carlo) and shows: + 1. top view (x, y) of the trajectory coloured by the position sigma, with covariance ellipses; + 2. sigma_px, sigma_py, sigma_pz [mm] and sigma_om, sigma_fi, sigma_ka [deg] over time, plus the method's extra + columns (sigma0 and correspondences, or converged Monte Carlo runs). + +px, py, pz are the node's global position, so the x-y block of the covariance is drawn as is in the top view. +Nodes whose uncertainty was not computed (inf, nan) are drawn as grey crosses. + +Needs numpy and matplotlib (pip install numpy matplotlib). + + python3 scripts/plot_session_uncertainty.py uncertainty.csv + python3 scripts/plot_session_uncertainty.py uncertainty.csv --ellipse-scale 100 --output uncertainty.png +""" + +import argparse +import csv +import math +import os +import sys + +PARAMETERS = ["px", "py", "pz", "om", "fi", "ka"] + + +def read_csv(path): + """Returns a dict column name -> list of floats.""" + with open(path, newline="") as f: + reader = csv.DictReader(f) + columns = {name: [] for name in reader.fieldnames} + for row in reader: + for name in reader.fieldnames: + try: + columns[name].append(float(row[name])) + except (TypeError, ValueError): + columns[name].append(math.nan) + return columns + + +def covariance_matrices(columns, np): + """6x6 covariance per node from the cov__ upper triangle; None when the CSV has no covariance.""" + if "cov_px_px" not in columns: + return None + n = len(columns["x"]) + covariance = np.full((n, 6, 6), np.nan) + for i, a in enumerate(PARAMETERS): + for j in range(i, 6): + values = np.asarray(columns[f"cov_{a}_{PARAMETERS[j]}"]) + covariance[:, i, j] = values + covariance[:, j, i] = values + return covariance + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("csv", help="output of session_uncertainty_calculation") + parser.add_argument( + "--ellipse-scale", + type=float, + default=None, + help="ellipse half-axes in sigmas (default: chosen so the median ellipse is ~1%% of the trajectory extent)", + ) + parser.add_argument("--ellipse-step", type=int, default=0, help="draw every n-th ellipse (default: ~200 ellipses)") + parser.add_argument("--log", action="store_true", help="logarithmic colour scale and sigma axes") + parser.add_argument("--output", help="save the figures to this file (a _time suffix for the second) instead of showing them") + args = parser.parse_args() + + try: + import numpy as np + import matplotlib + + if args.output: + matplotlib.use("Agg") + import matplotlib.pyplot as plt + from matplotlib.collections import EllipseCollection + from matplotlib.colors import LogNorm, Normalize + except ImportError as error: + sys.exit(f"{error}: install with 'pip install numpy matplotlib'") + + columns = read_csv(args.csv) + if not columns.get("x"): + sys.exit(f"no nodes in {args.csv}") + + x = np.asarray(columns["x"]) + y = np.asarray(columns["y"]) + t = np.asarray(columns["timestamp_lidar"]) + t = t - t[0] + if t[-1] > 1e6: # nanoseconds + t = t * 1e-9 + sigma = {p: np.asarray(columns[f"sigma_{p}"]) for p in PARAMETERS} + sigma_mm = {p: sigma[p] * 1000.0 for p in PARAMETERS[:3]} + sigma_deg = {p: np.degrees(sigma[p]) for p in PARAMETERS[3:]} + position_sigma_mm = np.sqrt(sigma_mm["px"] ** 2 + sigma_mm["py"] ** 2 + sigma_mm["pz"] ** 2) + valid = np.isfinite(position_sigma_mm) + covariance = covariance_matrices(columns, np) + is_monte_carlo = "number_of_converged_runs" in columns + + print(f"{len(x)} nodes, {valid.sum()} with uncertainty") + if valid.any(): + for p in PARAMETERS[:3]: + v = sigma_mm[p][valid] + print(f" sigma_{p} [mm]: median {np.median(v):.4f}, 95% {np.percentile(v, 95):.4f}, max {v.max():.4f}") + for p in PARAMETERS[3:]: + v = sigma_deg[p][np.isfinite(sigma_deg[p])] + if v.size: + print(f" sigma_{p} [deg]: median {np.median(v):.5f}, 95% {np.percentile(v, 95):.5f}, max {v.max():.5f}") + + # --- top view + fig, ax = plt.subplots(figsize=(10, 8)) + ax.plot(x, y, color="lightgray", linewidth=1, zorder=1) + if (~valid).any(): + ax.scatter(x[~valid], y[~valid], marker="x", color="gray", s=20, label="not computed", zorder=2) + if valid.any(): + values = position_sigma_mm[valid] + positive = values[values > 0] + norm = ( + LogNorm(vmin=positive.min(), vmax=positive.max()) + if args.log and positive.size + else Normalize(vmin=values.min(), vmax=np.percentile(values, 99)) + ) + points = ax.scatter(x[valid], y[valid], c=values, cmap="viridis", norm=norm, s=12, zorder=3) + fig.colorbar(points, ax=ax, label="position sigma sqrt(px² + py² + pz²) [mm]") + + if covariance is not None: + xy = covariance[:, :2, :2] + ok = np.isfinite(xy).all(axis=(1, 2)) + indices = np.flatnonzero(ok) + step = args.ellipse_step if args.ellipse_step > 0 else max(1, len(indices) // 200) + indices = indices[::step] + if indices.size: + eigenvalues, eigenvectors = np.linalg.eigh(xy[indices]) + half_axes = np.sqrt(np.clip(eigenvalues, 0.0, None)) # ascending: minor, major + scale = args.ellipse_scale + if scale is None: + extent = max(np.ptp(x), np.ptp(y), 1e-9) + median_major = np.median(half_axes[:, 1]) + scale = 0.01 * extent / median_major if median_major > 0 else 1.0 + angles = np.degrees(np.arctan2(eigenvectors[:, 1, 1], eigenvectors[:, 0, 1])) + ax.add_collection( + EllipseCollection( + widths=2 * scale * half_axes[:, 1], + heights=2 * scale * half_axes[:, 0], + angles=angles, + units="xy", + offsets=np.column_stack([x[indices], y[indices]]), + offset_transform=ax.transData, + facecolors="none", + edgecolors="crimson", + linewidths=0.8, + zorder=4, + ) + ) + ax.plot([], [], color="crimson", label=f"x-y covariance, ±{scale:.3g} sigma (every {step}. node)") + + ax.set_aspect("equal", adjustable="datalim") + ax.set_xlabel("x [m]") + ax.set_ylabel("y [m]") + method = "Monte Carlo ICP" if is_monte_carlo else "ICP normal matrix" + ax.set_title(f"Trajectory and position uncertainty ({method}): {os.path.basename(args.csv)}") + if ax.get_legend_handles_labels()[0]: + ax.legend(loc="best") + fig.tight_layout() + + # --- sigmas over time + fig_time, axes = plt.subplots(3, 1, figsize=(12, 9), sharex=True) + for p in PARAMETERS[:3]: + axes[0].plot(t, sigma_mm[p], label=f"sigma_{p}", linewidth=1) + axes[0].set_ylabel("[mm]") + for p in PARAMETERS[3:]: + axes[1].plot(t, sigma_deg[p], label=f"sigma_{p}", linewidth=1) + axes[1].set_ylabel("[deg]") + for a in axes[:2]: + a.legend(loc="upper right") + a.grid(True, alpha=0.3) + if args.log: + a.set_yscale("log") + if is_monte_carlo: + axes[2].plot(t, columns["number_of_converged_runs"], label="converged runs", color="tab:green") + axes[2].plot(t, columns["number_of_runs"], label="runs", color="gray", linestyle="--") + axes[2].set_ylabel("ICP runs") + axes[2].legend(loc="upper right") + elif "sigma0(RMS)" in columns: + axes[2].plot(t, np.asarray(columns["sigma0(RMS)"]) * 1000.0, label="sigma0 (RMS residual)", color="tab:red") + axes[2].set_ylabel("sigma0 [mm]", color="tab:red") + twin = axes[2].twinx() + twin.plot(t, columns["number_of_correspondences"], color="tab:blue", linewidth=1) + twin.set_ylabel("correspondences", color="tab:blue") + axes[2].grid(True, alpha=0.3) + axes[2].set_xlabel("time [s]") + axes[0].set_title(f"Pose sigmas over time ({method})") + fig_time.tight_layout() + + if args.output: + fig.savefig(args.output, dpi=150) + stem, dot, extension = args.output.rpartition(".") + time_output = f"{stem}_time.{extension}" if dot else f"{args.output}_time" + fig_time.savefig(time_output, dpi=150) + print(f"saved {args.output} and {time_output}") + else: + plt.show() + + +if __name__ == "__main__": + main()