Blame internal/ceres/conjugate_gradients_solver.cc

Packit ea1746
// Ceres Solver - A fast non-linear least squares minimizer
Packit ea1746
// Copyright 2015 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: sameeragarwal@google.com (Sameer Agarwal)
Packit ea1746
//
Packit ea1746
// A preconditioned conjugate gradients solver
Packit ea1746
// (ConjugateGradientsSolver) for positive semidefinite linear
Packit ea1746
// systems.
Packit ea1746
//
Packit ea1746
// We have also augmented the termination criterion used by this
Packit ea1746
// solver to support not just residual based termination but also
Packit ea1746
// termination based on decrease in the value of the quadratic model
Packit ea1746
// that CG optimizes.
Packit ea1746
Packit ea1746
#include "ceres/conjugate_gradients_solver.h"
Packit ea1746
Packit ea1746
#include <cmath>
Packit ea1746
#include <cstddef>
Packit ea1746
#include "ceres/fpclassify.h"
Packit ea1746
#include "ceres/internal/eigen.h"
Packit ea1746
#include "ceres/linear_operator.h"
Packit ea1746
#include "ceres/stringprintf.h"
Packit ea1746
#include "ceres/types.h"
Packit ea1746
#include "glog/logging.h"
Packit ea1746
Packit ea1746
namespace ceres {
Packit ea1746
namespace internal {
Packit ea1746
namespace {
Packit ea1746
Packit ea1746
bool IsZeroOrInfinity(double x) {
Packit ea1746
  return ((x == 0.0) || (IsInfinite(x)));
Packit ea1746
}
Packit ea1746
Packit ea1746
}  // namespace
Packit ea1746
Packit ea1746
ConjugateGradientsSolver::ConjugateGradientsSolver(
Packit ea1746
    const LinearSolver::Options& options)
Packit ea1746
    : options_(options) {
Packit ea1746
}
Packit ea1746
Packit ea1746
LinearSolver::Summary ConjugateGradientsSolver::Solve(
Packit ea1746
    LinearOperator* A,
Packit ea1746
    const double* b,
Packit ea1746
    const LinearSolver::PerSolveOptions& per_solve_options,
Packit ea1746
    double* x) {
Packit ea1746
  CHECK_NOTNULL(A);
Packit ea1746
  CHECK_NOTNULL(x);
Packit ea1746
  CHECK_NOTNULL(b);
Packit ea1746
  CHECK_EQ(A->num_rows(), A->num_cols());
Packit ea1746
Packit ea1746
  LinearSolver::Summary summary;
Packit ea1746
  summary.termination_type = LINEAR_SOLVER_NO_CONVERGENCE;
Packit ea1746
  summary.message = "Maximum number of iterations reached.";
Packit ea1746
  summary.num_iterations = 0;
Packit ea1746
Packit ea1746
  const int num_cols = A->num_cols();
Packit ea1746
  VectorRef xref(x, num_cols);
Packit ea1746
  ConstVectorRef bref(b, num_cols);
Packit ea1746
Packit ea1746
  const double norm_b = bref.norm();
Packit ea1746
  if (norm_b == 0.0) {
Packit ea1746
    xref.setZero();
Packit ea1746
    summary.termination_type = LINEAR_SOLVER_SUCCESS;
Packit ea1746
    summary.message = "Convergence. |b| = 0.";
Packit ea1746
    return summary;
Packit ea1746
  }
Packit ea1746
Packit ea1746
  Vector r(num_cols);
Packit ea1746
  Vector p(num_cols);
Packit ea1746
  Vector z(num_cols);
Packit ea1746
  Vector tmp(num_cols);
Packit ea1746
Packit ea1746
  const double tol_r = per_solve_options.r_tolerance * norm_b;
Packit ea1746
Packit ea1746
  tmp.setZero();
Packit ea1746
  A->RightMultiply(x, tmp.data());
Packit ea1746
  r = bref - tmp;
Packit ea1746
  double norm_r = r.norm();
Packit ea1746
  if (options_.min_num_iterations == 0 && norm_r <= tol_r) {
Packit ea1746
    summary.termination_type = LINEAR_SOLVER_SUCCESS;
Packit ea1746
    summary.message =
Packit ea1746
        StringPrintf("Convergence. |r| = %e <= %e.", norm_r, tol_r);
Packit ea1746
    return summary;
Packit ea1746
  }
Packit ea1746
Packit ea1746
  double rho = 1.0;
Packit ea1746
Packit ea1746
  // Initial value of the quadratic model Q = x'Ax - 2 * b'x.
Packit ea1746
  double Q0 = -1.0 * xref.dot(bref + r);
Packit ea1746
Packit ea1746
  for (summary.num_iterations = 1;; ++summary.num_iterations) {
Packit ea1746
    // Apply preconditioner
Packit ea1746
    if (per_solve_options.preconditioner != NULL) {
Packit ea1746
      z.setZero();
Packit ea1746
      per_solve_options.preconditioner->RightMultiply(r.data(), z.data());
Packit ea1746
    } else {
Packit ea1746
      z = r;
Packit ea1746
    }
Packit ea1746
Packit ea1746
    double last_rho = rho;
Packit ea1746
    rho = r.dot(z);
Packit ea1746
    if (IsZeroOrInfinity(rho)) {
Packit ea1746
      summary.termination_type = LINEAR_SOLVER_FAILURE;
Packit ea1746
      summary.message = StringPrintf("Numerical failure. rho = r'z = %e.", rho);
Packit ea1746
      break;
Packit ea1746
    }
Packit ea1746
Packit ea1746
    if (summary.num_iterations == 1) {
Packit ea1746
      p = z;
Packit ea1746
    } else {
Packit ea1746
      double beta = rho / last_rho;
Packit ea1746
      if (IsZeroOrInfinity(beta)) {
Packit ea1746
        summary.termination_type = LINEAR_SOLVER_FAILURE;
Packit ea1746
        summary.message = StringPrintf(
Packit ea1746
            "Numerical failure. beta = rho_n / rho_{n-1} = %e, "
Packit ea1746
            "rho_n = %e, rho_{n-1} = %e", beta, rho, last_rho);
Packit ea1746
        break;
Packit ea1746
      }
Packit ea1746
      p = z + beta * p;
Packit ea1746
    }
Packit ea1746
Packit ea1746
    Vector& q = z;
Packit ea1746
    q.setZero();
Packit ea1746
    A->RightMultiply(p.data(), q.data());
Packit ea1746
    const double pq = p.dot(q);
Packit ea1746
    if ((pq <= 0) || IsInfinite(pq))  {
Packit ea1746
      summary.termination_type = LINEAR_SOLVER_NO_CONVERGENCE;
Packit ea1746
      summary.message = StringPrintf(
Packit ea1746
          "Matrix is indefinite, no more progress can be made. "
Packit ea1746
          "p'q = %e. |p| = %e, |q| = %e",
Packit ea1746
          pq, p.norm(), q.norm());
Packit ea1746
      break;
Packit ea1746
    }
Packit ea1746
Packit ea1746
    const double alpha = rho / pq;
Packit ea1746
    if (IsInfinite(alpha)) {
Packit ea1746
      summary.termination_type = LINEAR_SOLVER_FAILURE;
Packit ea1746
      summary.message =
Packit ea1746
          StringPrintf("Numerical failure. alpha = rho / pq = %e, "
Packit ea1746
                       "rho = %e, pq = %e.", alpha, rho, pq);
Packit ea1746
      break;
Packit ea1746
    }
Packit ea1746
Packit ea1746
    xref = xref + alpha * p;
Packit ea1746
Packit ea1746
    // Ideally we would just use the update r = r - alpha*q to keep
Packit ea1746
    // track of the residual vector. However this estimate tends to
Packit ea1746
    // drift over time due to round off errors. Thus every
Packit ea1746
    // residual_reset_period iterations, we calculate the residual as
Packit ea1746
    // r = b - Ax. We do not do this every iteration because this
Packit ea1746
    // requires an additional matrix vector multiply which would
Packit ea1746
    // double the complexity of the CG algorithm.
Packit ea1746
    if (summary.num_iterations % options_.residual_reset_period == 0) {
Packit ea1746
      tmp.setZero();
Packit ea1746
      A->RightMultiply(x, tmp.data());
Packit ea1746
      r = bref - tmp;
Packit ea1746
    } else {
Packit ea1746
      r = r - alpha * q;
Packit ea1746
    }
Packit ea1746
Packit ea1746
    // Quadratic model based termination.
Packit ea1746
    //   Q1 = x'Ax - 2 * b' x.
Packit ea1746
    const double Q1 = -1.0 * xref.dot(bref + r);
Packit ea1746
Packit ea1746
    // For PSD matrices A, let
Packit ea1746
    //
Packit ea1746
    //   Q(x) = x'Ax - 2b'x
Packit ea1746
    //
Packit ea1746
    // be the cost of the quadratic function defined by A and b. Then,
Packit ea1746
    // the solver terminates at iteration i if
Packit ea1746
    //
Packit ea1746
    //   i * (Q(x_i) - Q(x_i-1)) / Q(x_i) < q_tolerance.
Packit ea1746
    //
Packit ea1746
    // This termination criterion is more useful when using CG to
Packit ea1746
    // solve the Newton step. This particular convergence test comes
Packit ea1746
    // from Stephen Nash's work on truncated Newton
Packit ea1746
    // methods. References:
Packit ea1746
    //
Packit ea1746
    //   1. Stephen G. Nash & Ariela Sofer, Assessing A Search
Packit ea1746
    //   Direction Within A Truncated Newton Method, Operation
Packit ea1746
    //   Research Letters 9(1990) 219-221.
Packit ea1746
    //
Packit ea1746
    //   2. Stephen G. Nash, A Survey of Truncated Newton Methods,
Packit ea1746
    //   Journal of Computational and Applied Mathematics,
Packit ea1746
    //   124(1-2), 45-59, 2000.
Packit ea1746
    //
Packit ea1746
    const double zeta = summary.num_iterations * (Q1 - Q0) / Q1;
Packit ea1746
    if (zeta < per_solve_options.q_tolerance &&
Packit ea1746
        summary.num_iterations >= options_.min_num_iterations) {
Packit ea1746
      summary.termination_type = LINEAR_SOLVER_SUCCESS;
Packit ea1746
      summary.message =
Packit ea1746
          StringPrintf("Iteration: %d Convergence: zeta = %e < %e. |r| = %e",
Packit ea1746
                       summary.num_iterations,
Packit ea1746
                       zeta,
Packit ea1746
                       per_solve_options.q_tolerance,
Packit ea1746
                       r.norm());
Packit ea1746
      break;
Packit ea1746
    }
Packit ea1746
    Q0 = Q1;
Packit ea1746
Packit ea1746
    // Residual based termination.
Packit ea1746
    norm_r = r. norm();
Packit ea1746
    if (norm_r <= tol_r &&
Packit ea1746
        summary.num_iterations >= options_.min_num_iterations) {
Packit ea1746
      summary.termination_type = LINEAR_SOLVER_SUCCESS;
Packit ea1746
      summary.message =
Packit ea1746
          StringPrintf("Iteration: %d Convergence. |r| = %e <= %e.",
Packit ea1746
                       summary.num_iterations,
Packit ea1746
                       norm_r,
Packit ea1746
                       tol_r);
Packit ea1746
      break;
Packit ea1746
    }
Packit ea1746
Packit ea1746
    if (summary.num_iterations >= options_.max_num_iterations) {
Packit ea1746
      break;
Packit ea1746
    }
Packit ea1746
  }
Packit ea1746
Packit ea1746
  return summary;
Packit ea1746
}
Packit ea1746
Packit ea1746
}  // namespace internal
Packit ea1746
}  // namespace ceres