pose_graph_3d.cc 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. // Ceres Solver - A fast non-linear least squares minimizer
  2. // Copyright 2023 Google Inc. All rights reserved.
  3. // http://ceres-solver.org/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are met:
  7. //
  8. // * Redistributions of source code must retain the above copyright notice,
  9. // this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above copyright notice,
  11. // this list of conditions and the following disclaimer in the documentation
  12. // and/or other materials provided with the distribution.
  13. // * Neither the name of Google Inc. nor the names of its contributors may be
  14. // used to endorse or promote products derived from this software without
  15. // specific prior written permission.
  16. //
  17. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  18. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  20. // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  21. // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  22. // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  23. // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  24. // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  25. // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  26. // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  27. // POSSIBILITY OF SUCH DAMAGE.
  28. //
  29. // Author: vitus@google.com (Michael Vitus)
  30. #include <fstream>
  31. #include <iostream>
  32. #include <string>
  33. #include "ceres/ceres.h"
  34. #include "common/read_g2o.h"
  35. #include "gflags/gflags.h"
  36. #include "glog/logging.h"
  37. #include "pose_graph_3d_error_term.h"
  38. #include "types.h"
  39. DEFINE_string(input, "", "The pose graph definition filename in g2o format.");
  40. namespace ceres::examples {
  41. namespace {
  42. // Constructs the nonlinear least squares optimization problem from the pose
  43. // graph constraints.
  44. void BuildOptimizationProblem(const VectorOfConstraints& constraints,
  45. MapOfPoses* poses,
  46. ceres::Problem* problem) {
  47. CHECK(poses != nullptr);
  48. CHECK(problem != nullptr);
  49. if (constraints.empty()) {
  50. LOG(INFO) << "No constraints, no problem to optimize.";
  51. return;
  52. }
  53. ceres::LossFunction* loss_function = nullptr;
  54. ceres::Manifold* quaternion_manifold = new EigenQuaternionManifold;
  55. for (const auto& constraint : constraints) {
  56. auto pose_begin_iter = poses->find(constraint.id_begin);
  57. CHECK(pose_begin_iter != poses->end())
  58. << "Pose with ID: " << constraint.id_begin << " not found.";
  59. auto pose_end_iter = poses->find(constraint.id_end);
  60. CHECK(pose_end_iter != poses->end())
  61. << "Pose with ID: " << constraint.id_end << " not found.";
  62. const Eigen::Matrix<double, 6, 6> sqrt_information =
  63. constraint.information.llt().matrixL();
  64. // Ceres will take ownership of the pointer.
  65. ceres::CostFunction* cost_function =
  66. PoseGraph3dErrorTerm::Create(constraint.t_be, sqrt_information);
  67. problem->AddResidualBlock(cost_function,
  68. loss_function,
  69. pose_begin_iter->second.p.data(),
  70. pose_begin_iter->second.q.coeffs().data(),
  71. pose_end_iter->second.p.data(),
  72. pose_end_iter->second.q.coeffs().data());
  73. problem->SetManifold(pose_begin_iter->second.q.coeffs().data(),
  74. quaternion_manifold);
  75. problem->SetManifold(pose_end_iter->second.q.coeffs().data(),
  76. quaternion_manifold);
  77. }
  78. // The pose graph optimization problem has six DOFs that are not fully
  79. // constrained. This is typically referred to as gauge freedom. You can apply
  80. // a rigid body transformation to all the nodes and the optimization problem
  81. // will still have the exact same cost. The Levenberg-Marquardt algorithm has
  82. // internal damping which mitigates this issue, but it is better to properly
  83. // constrain the gauge freedom. This can be done by setting one of the poses
  84. // as constant so the optimizer cannot change it.
  85. auto pose_start_iter = poses->begin();
  86. CHECK(pose_start_iter != poses->end()) << "There are no poses.";
  87. problem->SetParameterBlockConstant(pose_start_iter->second.p.data());
  88. problem->SetParameterBlockConstant(pose_start_iter->second.q.coeffs().data());
  89. }
  90. // Returns true if the solve was successful.
  91. bool SolveOptimizationProblem(ceres::Problem* problem) {
  92. CHECK(problem != nullptr);
  93. ceres::Solver::Options options;
  94. options.max_num_iterations = 200;
  95. options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;
  96. ceres::Solver::Summary summary;
  97. ceres::Solve(options, problem, &summary);
  98. std::cout << summary.FullReport() << '\n';
  99. return summary.IsSolutionUsable();
  100. }
  101. // Output the poses to the file with format: id x y z q_x q_y q_z q_w.
  102. bool OutputPoses(const std::string& filename, const MapOfPoses& poses) {
  103. std::fstream outfile;
  104. outfile.open(filename.c_str(), std::istream::out);
  105. if (!outfile) {
  106. LOG(ERROR) << "Error opening the file: " << filename;
  107. return false;
  108. }
  109. for (const auto& pair : poses) {
  110. outfile << pair.first << " " << pair.second.p.transpose() << " "
  111. << pair.second.q.x() << " " << pair.second.q.y() << " "
  112. << pair.second.q.z() << " " << pair.second.q.w() << '\n';
  113. }
  114. return true;
  115. }
  116. } // namespace
  117. } // namespace ceres::examples
  118. int main(int argc, char** argv) {
  119. google::InitGoogleLogging(argv[0]);
  120. GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
  121. CHECK(FLAGS_input != "") << "Need to specify the filename to read.";
  122. ceres::examples::MapOfPoses poses;
  123. ceres::examples::VectorOfConstraints constraints;
  124. CHECK(ceres::examples::ReadG2oFile(FLAGS_input, &poses, &constraints))
  125. << "Error reading the file: " << FLAGS_input;
  126. std::cout << "Number of poses: " << poses.size() << '\n';
  127. std::cout << "Number of constraints: " << constraints.size() << '\n';
  128. CHECK(ceres::examples::OutputPoses("poses_original.txt", poses))
  129. << "Error outputting to poses_original.txt";
  130. ceres::Problem problem;
  131. ceres::examples::BuildOptimizationProblem(constraints, &poses, &problem);
  132. CHECK(ceres::examples::SolveOptimizationProblem(&problem))
  133. << "The solve was not successful, exiting.";
  134. CHECK(ceres::examples::OutputPoses("poses_optimized.txt", poses))
  135. << "Error outputting to poses_original.txt";
  136. return 0;
  137. }