Blame examples/slam/pose_graph_3d/pose_graph_3d.cc

Packit ea1746
// Ceres Solver - A fast non-linear least squares minimizer
Packit ea1746
// Copyright 2016 Google Inc. All rights reserved.
Packit ea1746
// http://ceres-solver.org/
Packit ea1746
//
Packit ea1746
// Redistribution and use in source and binary forms, with or without
Packit ea1746
// modification, are permitted provided that the following conditions are met:
Packit ea1746
//
Packit ea1746
// * Redistributions of source code must retain the above copyright notice,
Packit ea1746
//   this list of conditions and the following disclaimer.
Packit ea1746
// * Redistributions in binary form must reproduce the above copyright notice,
Packit ea1746
//   this list of conditions and the following disclaimer in the documentation
Packit ea1746
//   and/or other materials provided with the distribution.
Packit ea1746
// * Neither the name of Google Inc. nor the names of its contributors may be
Packit ea1746
//   used to endorse or promote products derived from this software without
Packit ea1746
//   specific prior written permission.
Packit ea1746
//
Packit ea1746
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
Packit ea1746
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
Packit ea1746
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
Packit ea1746
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
Packit ea1746
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
Packit ea1746
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
Packit ea1746
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
Packit ea1746
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
Packit ea1746
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
Packit ea1746
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
Packit ea1746
// POSSIBILITY OF SUCH DAMAGE.
Packit ea1746
//
Packit ea1746
// Author: vitus@google.com (Michael Vitus)
Packit ea1746
Packit ea1746
#include <iostream>
Packit ea1746
#include <fstream>
Packit ea1746
#include <string>
Packit ea1746
Packit ea1746
#include "ceres/ceres.h"
Packit ea1746
#include "common/read_g2o.h"
Packit ea1746
#include "gflags/gflags.h"
Packit ea1746
#include "glog/logging.h"
Packit ea1746
#include "pose_graph_3d_error_term.h"
Packit ea1746
#include "types.h"
Packit ea1746
Packit ea1746
DEFINE_string(input, "", "The pose graph definition filename in g2o format.");
Packit ea1746
Packit ea1746
namespace ceres {
Packit ea1746
namespace examples {
Packit ea1746
Packit ea1746
// Constructs the nonlinear least squares optimization problem from the pose
Packit ea1746
// graph constraints.
Packit ea1746
void BuildOptimizationProblem(const VectorOfConstraints& constraints,
Packit ea1746
                              MapOfPoses* poses, ceres::Problem* problem) {
Packit ea1746
  CHECK(poses != NULL);
Packit ea1746
  CHECK(problem != NULL);
Packit ea1746
  if (constraints.empty()) {
Packit ea1746
    LOG(INFO) << "No constraints, no problem to optimize.";
Packit ea1746
    return;
Packit ea1746
  }
Packit ea1746
Packit ea1746
  ceres::LossFunction* loss_function = NULL;
Packit ea1746
  ceres::LocalParameterization* quaternion_local_parameterization =
Packit ea1746
      new EigenQuaternionParameterization;
Packit ea1746
Packit ea1746
  for (VectorOfConstraints::const_iterator constraints_iter =
Packit ea1746
           constraints.begin();
Packit ea1746
       constraints_iter != constraints.end(); ++constraints_iter) {
Packit ea1746
    const Constraint3d& constraint = *constraints_iter;
Packit ea1746
Packit ea1746
    MapOfPoses::iterator pose_begin_iter = poses->find(constraint.id_begin);
Packit ea1746
    CHECK(pose_begin_iter != poses->end())
Packit ea1746
        << "Pose with ID: " << constraint.id_begin << " not found.";
Packit ea1746
    MapOfPoses::iterator pose_end_iter = poses->find(constraint.id_end);
Packit ea1746
    CHECK(pose_end_iter != poses->end())
Packit ea1746
        << "Pose with ID: " << constraint.id_end << " not found.";
Packit ea1746
Packit ea1746
    const Eigen::Matrix<double, 6, 6> sqrt_information =
Packit ea1746
        constraint.information.llt().matrixL();
Packit ea1746
    // Ceres will take ownership of the pointer.
Packit ea1746
    ceres::CostFunction* cost_function =
Packit ea1746
        PoseGraph3dErrorTerm::Create(constraint.t_be, sqrt_information);
Packit ea1746
Packit ea1746
    problem->AddResidualBlock(cost_function, loss_function,
Packit ea1746
                              pose_begin_iter->second.p.data(),
Packit ea1746
                              pose_begin_iter->second.q.coeffs().data(),
Packit ea1746
                              pose_end_iter->second.p.data(),
Packit ea1746
                              pose_end_iter->second.q.coeffs().data());
Packit ea1746
Packit ea1746
    problem->SetParameterization(pose_begin_iter->second.q.coeffs().data(),
Packit ea1746
                                 quaternion_local_parameterization);
Packit ea1746
    problem->SetParameterization(pose_end_iter->second.q.coeffs().data(),
Packit ea1746
                                 quaternion_local_parameterization);
Packit ea1746
  }
Packit ea1746
Packit ea1746
  // The pose graph optimization problem has six DOFs that are not fully
Packit ea1746
  // constrained. This is typically referred to as gauge freedom. You can apply
Packit ea1746
  // a rigid body transformation to all the nodes and the optimization problem
Packit ea1746
  // will still have the exact same cost. The Levenberg-Marquardt algorithm has
Packit ea1746
  // internal damping which mitigates this issue, but it is better to properly
Packit ea1746
  // constrain the gauge freedom. This can be done by setting one of the poses
Packit ea1746
  // as constant so the optimizer cannot change it.
Packit ea1746
  MapOfPoses::iterator pose_start_iter = poses->begin();
Packit ea1746
  CHECK(pose_start_iter != poses->end()) << "There are no poses.";
Packit ea1746
  problem->SetParameterBlockConstant(pose_start_iter->second.p.data());
Packit ea1746
  problem->SetParameterBlockConstant(pose_start_iter->second.q.coeffs().data());
Packit ea1746
}
Packit ea1746
Packit ea1746
// Returns true if the solve was successful.
Packit ea1746
bool SolveOptimizationProblem(ceres::Problem* problem) {
Packit ea1746
  CHECK(problem != NULL);
Packit ea1746
Packit ea1746
  ceres::Solver::Options options;
Packit ea1746
  options.max_num_iterations = 200;
Packit ea1746
  options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;
Packit ea1746
Packit ea1746
  ceres::Solver::Summary summary;
Packit ea1746
  ceres::Solve(options, problem, &summary);
Packit ea1746
Packit ea1746
  std::cout << summary.FullReport() << '\n';
Packit ea1746
Packit ea1746
  return summary.IsSolutionUsable();
Packit ea1746
}
Packit ea1746
Packit ea1746
// Output the poses to the file with format: id x y z q_x q_y q_z q_w.
Packit ea1746
bool OutputPoses(const std::string& filename, const MapOfPoses& poses) {
Packit ea1746
  std::fstream outfile;
Packit ea1746
  outfile.open(filename.c_str(), std::istream::out);
Packit ea1746
  if (!outfile) {
Packit ea1746
    LOG(ERROR) << "Error opening the file: " << filename;
Packit ea1746
    return false;
Packit ea1746
  }
Packit ea1746
  for (std::map<int, Pose3d, std::less<int>,
Packit ea1746
                Eigen::aligned_allocator<std::pair<const int, Pose3d> > >::
Packit ea1746
           const_iterator poses_iter = poses.begin();
Packit ea1746
       poses_iter != poses.end(); ++poses_iter) {
Packit ea1746
    const std::map<int, Pose3d, std::less<int>,
Packit ea1746
                   Eigen::aligned_allocator<std::pair<const int, Pose3d> > >::
Packit ea1746
        value_type& pair = *poses_iter;
Packit ea1746
    outfile << pair.first << " " << pair.second.p.transpose() << " "
Packit ea1746
            << pair.second.q.x() << " " << pair.second.q.y() << " "
Packit ea1746
            << pair.second.q.z() << " " << pair.second.q.w() << '\n';
Packit ea1746
  }
Packit ea1746
  return true;
Packit ea1746
}
Packit ea1746
Packit ea1746
}  // namespace examples
Packit ea1746
}  // namespace ceres
Packit ea1746
Packit ea1746
int main(int argc, char** argv) {
Packit ea1746
  google::InitGoogleLogging(argv[0]);
Packit ea1746
  CERES_GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
Packit ea1746
Packit ea1746
  CHECK(FLAGS_input != "") << "Need to specify the filename to read.";
Packit ea1746
Packit ea1746
  ceres::examples::MapOfPoses poses;
Packit ea1746
  ceres::examples::VectorOfConstraints constraints;
Packit ea1746
Packit ea1746
  CHECK(ceres::examples::ReadG2oFile(FLAGS_input, &poses, &constraints))
Packit ea1746
      << "Error reading the file: " << FLAGS_input;
Packit ea1746
Packit ea1746
  std::cout << "Number of poses: " << poses.size() << '\n';
Packit ea1746
  std::cout << "Number of constraints: " << constraints.size() << '\n';
Packit ea1746
Packit ea1746
  CHECK(ceres::examples::OutputPoses("poses_original.txt", poses))
Packit ea1746
      << "Error outputting to poses_original.txt";
Packit ea1746
Packit ea1746
  ceres::Problem problem;
Packit ea1746
  ceres::examples::BuildOptimizationProblem(constraints, &poses, &problem);
Packit ea1746
Packit ea1746
  CHECK(ceres::examples::SolveOptimizationProblem(&problem))
Packit ea1746
      << "The solve was not successful, exiting.";
Packit ea1746
Packit ea1746
  CHECK(ceres::examples::OutputPoses("poses_optimized.txt", poses))
Packit ea1746
      << "Error outputting to poses_original.txt";
Packit ea1746
Packit ea1746
  return 0;
Packit ea1746
}