123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718 |
- #include "ceres/dogleg_strategy.h"
- #include <algorithm>
- #include <cmath>
- #include "Eigen/Dense"
- #include "ceres/array_utils.h"
- #include "ceres/internal/eigen.h"
- #include "ceres/linear_least_squares_problems.h"
- #include "ceres/linear_solver.h"
- #include "ceres/polynomial.h"
- #include "ceres/sparse_matrix.h"
- #include "ceres/trust_region_strategy.h"
- #include "ceres/types.h"
- #include "glog/logging.h"
- namespace ceres::internal {
- namespace {
- const double kMaxMu = 1.0;
- const double kMinMu = 1e-8;
- }
- DoglegStrategy::DoglegStrategy(const TrustRegionStrategy::Options& options)
- : linear_solver_(options.linear_solver),
- radius_(options.initial_radius),
- max_radius_(options.max_radius),
- min_diagonal_(options.min_lm_diagonal),
- max_diagonal_(options.max_lm_diagonal),
- mu_(kMinMu),
- min_mu_(kMinMu),
- max_mu_(kMaxMu),
- mu_increase_factor_(10.0),
- increase_threshold_(0.75),
- decrease_threshold_(0.25),
- dogleg_step_norm_(0.0),
- reuse_(false),
- dogleg_type_(options.dogleg_type) {
- CHECK(linear_solver_ != nullptr);
- CHECK_GT(min_diagonal_, 0.0);
- CHECK_LE(min_diagonal_, max_diagonal_);
- CHECK_GT(max_radius_, 0.0);
- }
- TrustRegionStrategy::Summary DoglegStrategy::ComputeStep(
- const TrustRegionStrategy::PerSolveOptions& per_solve_options,
- SparseMatrix* jacobian,
- const double* residuals,
- double* step) {
- CHECK(jacobian != nullptr);
- CHECK(residuals != nullptr);
- CHECK(step != nullptr);
- const int n = jacobian->num_cols();
- if (reuse_) {
-
-
-
- switch (dogleg_type_) {
- case TRADITIONAL_DOGLEG:
- ComputeTraditionalDoglegStep(step);
- break;
- case SUBSPACE_DOGLEG:
- ComputeSubspaceDoglegStep(step);
- break;
- }
- TrustRegionStrategy::Summary summary;
- summary.num_iterations = 0;
- summary.termination_type = LinearSolverTerminationType::SUCCESS;
- return summary;
- }
- reuse_ = true;
-
-
- if (diagonal_.rows() != n) {
- diagonal_.resize(n, 1);
- gradient_.resize(n, 1);
- gauss_newton_step_.resize(n, 1);
- }
-
-
-
-
-
-
- jacobian->SquaredColumnNorm(diagonal_.data());
- for (int i = 0; i < n; ++i) {
- diagonal_[i] =
- std::min(std::max(diagonal_[i], min_diagonal_), max_diagonal_);
- }
- diagonal_ = diagonal_.array().sqrt();
- ComputeGradient(jacobian, residuals);
- ComputeCauchyPoint(jacobian);
- LinearSolver::Summary linear_solver_summary =
- ComputeGaussNewtonStep(per_solve_options, jacobian, residuals);
- TrustRegionStrategy::Summary summary;
- summary.residual_norm = linear_solver_summary.residual_norm;
- summary.num_iterations = linear_solver_summary.num_iterations;
- summary.termination_type = linear_solver_summary.termination_type;
- if (linear_solver_summary.termination_type ==
- LinearSolverTerminationType::FATAL_ERROR) {
- return summary;
- }
- if (linear_solver_summary.termination_type !=
- LinearSolverTerminationType::FAILURE) {
- switch (dogleg_type_) {
-
- case TRADITIONAL_DOGLEG:
- ComputeTraditionalDoglegStep(step);
- break;
-
-
- case SUBSPACE_DOGLEG:
- if (!ComputeSubspaceModel(jacobian)) {
- summary.termination_type = LinearSolverTerminationType::FAILURE;
- break;
- }
- ComputeSubspaceDoglegStep(step);
- break;
- }
- }
- return summary;
- }
- void DoglegStrategy::ComputeGradient(SparseMatrix* jacobian,
- const double* residuals) {
- gradient_.setZero();
- jacobian->LeftMultiplyAndAccumulate(residuals, gradient_.data());
- gradient_.array() /= diagonal_.array();
- }
- void DoglegStrategy::ComputeCauchyPoint(SparseMatrix* jacobian) {
-
- Vector Jg(jacobian->num_rows());
- Jg.setZero();
-
-
- Vector scaled_gradient = (gradient_.array() / diagonal_.array()).matrix();
- jacobian->RightMultiplyAndAccumulate(scaled_gradient.data(), Jg.data());
- alpha_ = gradient_.squaredNorm() / Jg.squaredNorm();
- }
- void DoglegStrategy::ComputeTraditionalDoglegStep(double* dogleg) {
- VectorRef dogleg_step(dogleg, gradient_.rows());
-
-
- const double gradient_norm = gradient_.norm();
- const double gauss_newton_norm = gauss_newton_step_.norm();
- if (gauss_newton_norm <= radius_) {
- dogleg_step = gauss_newton_step_;
- dogleg_step_norm_ = gauss_newton_norm;
- dogleg_step.array() /= diagonal_.array();
- VLOG(3) << "GaussNewton step size: " << dogleg_step_norm_
- << " radius: " << radius_;
- return;
- }
-
-
-
- if (gradient_norm * alpha_ >= radius_) {
- dogleg_step = -(radius_ / gradient_norm) * gradient_;
- dogleg_step_norm_ = radius_;
- dogleg_step.array() /= diagonal_.array();
- VLOG(3) << "Cauchy step size: " << dogleg_step_norm_
- << " radius: " << radius_;
- return;
- }
-
-
-
-
-
-
- const double b_dot_a = -alpha_ * gradient_.dot(gauss_newton_step_);
- const double a_squared_norm = pow(alpha_ * gradient_norm, 2.0);
- const double b_minus_a_squared_norm =
- a_squared_norm - 2 * b_dot_a + pow(gauss_newton_norm, 2);
-
-
- const double c = b_dot_a - a_squared_norm;
- const double d = sqrt(c * c + b_minus_a_squared_norm *
- (pow(radius_, 2.0) - a_squared_norm));
- double beta = (c <= 0) ? (d - c) / b_minus_a_squared_norm
- : (radius_ * radius_ - a_squared_norm) / (d + c);
- dogleg_step =
- (-alpha_ * (1.0 - beta)) * gradient_ + beta * gauss_newton_step_;
- dogleg_step_norm_ = dogleg_step.norm();
- dogleg_step.array() /= diagonal_.array();
- VLOG(3) << "Dogleg step size: " << dogleg_step_norm_
- << " radius: " << radius_;
- }
- void DoglegStrategy::ComputeSubspaceDoglegStep(double* dogleg) {
- VectorRef dogleg_step(dogleg, gradient_.rows());
-
-
-
-
-
-
-
-
-
-
- const double gauss_newton_norm = gauss_newton_step_.norm();
- if (gauss_newton_norm <= radius_) {
- dogleg_step = gauss_newton_step_;
- dogleg_step_norm_ = gauss_newton_norm;
- dogleg_step.array() /= diagonal_.array();
- VLOG(3) << "GaussNewton step size: " << dogleg_step_norm_
- << " radius: " << radius_;
- return;
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- if (subspace_is_one_dimensional_) {
-
-
-
-
- dogleg_step = -(radius_ / gradient_.norm()) * gradient_;
- dogleg_step_norm_ = radius_;
- dogleg_step.array() /= diagonal_.array();
- VLOG(3) << "Dogleg subspace step size (1D): " << dogleg_step_norm_
- << " radius: " << radius_;
- return;
- }
- Vector2d minimum(0.0, 0.0);
- if (!FindMinimumOnTrustRegionBoundary(&minimum)) {
-
-
- LOG(WARNING) << "Failed to compute polynomial roots. "
- << "Taking traditional dogleg step instead.";
- ComputeTraditionalDoglegStep(dogleg);
- return;
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- const double kCosineThreshold = 0.99;
- const Vector2d grad_minimum = subspace_B_ * minimum + subspace_g_;
- const double cosine_angle =
- -minimum.dot(grad_minimum) / (minimum.norm() * grad_minimum.norm());
- if (cosine_angle < kCosineThreshold) {
- LOG(WARNING) << "First order optimality seems to be violated "
- << "in the subspace method!\n"
- << "Cosine of angle between x and B x + g is " << cosine_angle
- << ".\n"
- << "Taking a regular dogleg step instead.\n"
- << "Please consider filing a bug report if this "
- << "happens frequently or consistently.\n";
- ComputeTraditionalDoglegStep(dogleg);
- return;
- }
-
- dogleg_step = subspace_basis_ * minimum;
- dogleg_step_norm_ = radius_;
- dogleg_step.array() /= diagonal_.array();
- VLOG(3) << "Dogleg subspace step size: " << dogleg_step_norm_
- << " radius: " << radius_;
- }
- Vector DoglegStrategy::MakePolynomialForBoundaryConstrainedProblem() const {
- const double detB = subspace_B_.determinant();
- const double trB = subspace_B_.trace();
- const double r2 = radius_ * radius_;
- Matrix2d B_adj;
-
- B_adj << subspace_B_(1, 1) , -subspace_B_(0, 1),
- -subspace_B_(1, 0) , subspace_B_(0, 0);
-
- Vector polynomial(5);
- polynomial(0) = r2;
- polynomial(1) = 2.0 * r2 * trB;
- polynomial(2) = r2 * (trB * trB + 2.0 * detB) - subspace_g_.squaredNorm();
- polynomial(3) =
- -2.0 * (subspace_g_.transpose() * B_adj * subspace_g_ - r2 * detB * trB);
- polynomial(4) = r2 * detB * detB - (B_adj * subspace_g_).squaredNorm();
- return polynomial;
- }
- DoglegStrategy::Vector2d DoglegStrategy::ComputeSubspaceStepFromRoot(
- double y) const {
- const Matrix2d B_i = subspace_B_ + y * Matrix2d::Identity();
- return -B_i.partialPivLu().solve(subspace_g_);
- }
- double DoglegStrategy::EvaluateSubspaceModel(const Vector2d& x) const {
- return 0.5 * x.dot(subspace_B_ * x) + subspace_g_.dot(x);
- }
- bool DoglegStrategy::FindMinimumOnTrustRegionBoundary(Vector2d* minimum) const {
- CHECK(minimum != nullptr);
-
- minimum->setZero();
-
-
- const Vector polynomial = MakePolynomialForBoundaryConstrainedProblem();
-
- Vector roots_real;
- if (!FindPolynomialRoots(polynomial, &roots_real, nullptr)) {
-
-
- return false;
- }
-
-
-
-
- double minimum_value = std::numeric_limits<double>::max();
- bool valid_root_found = false;
- for (int i = 0; i < roots_real.size(); ++i) {
- const Vector2d x_i = ComputeSubspaceStepFromRoot(roots_real(i));
-
-
-
-
- if (x_i.norm() > 0) {
- const double f_i = EvaluateSubspaceModel((radius_ / x_i.norm()) * x_i);
- valid_root_found = true;
- if (f_i < minimum_value) {
- minimum_value = f_i;
- *minimum = x_i;
- }
- }
- }
- return valid_root_found;
- }
- LinearSolver::Summary DoglegStrategy::ComputeGaussNewtonStep(
- const PerSolveOptions& per_solve_options,
- SparseMatrix* jacobian,
- const double* residuals) {
- const int n = jacobian->num_cols();
- LinearSolver::Summary linear_solver_summary;
- linear_solver_summary.termination_type = LinearSolverTerminationType::FAILURE;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- while (mu_ < max_mu_) {
-
-
-
-
-
-
-
-
-
-
-
-
- LinearSolver::PerSolveOptions solve_options;
- solve_options.q_tolerance = 0.0;
- solve_options.r_tolerance = 0.0;
- lm_diagonal_ = diagonal_ * std::sqrt(mu_);
- solve_options.D = lm_diagonal_.data();
-
-
-
- InvalidateArray(n, gauss_newton_step_.data());
- linear_solver_summary = linear_solver_->Solve(
- jacobian, residuals, solve_options, gauss_newton_step_.data());
- if (per_solve_options.dump_format_type == CONSOLE ||
- (per_solve_options.dump_format_type != CONSOLE &&
- !per_solve_options.dump_filename_base.empty())) {
- if (!DumpLinearLeastSquaresProblem(per_solve_options.dump_filename_base,
- per_solve_options.dump_format_type,
- jacobian,
- solve_options.D,
- residuals,
- gauss_newton_step_.data(),
- 0)) {
- LOG(ERROR) << "Unable to dump trust region problem."
- << " Filename base: "
- << per_solve_options.dump_filename_base;
- }
- }
- if (linear_solver_summary.termination_type ==
- LinearSolverTerminationType::FATAL_ERROR) {
- return linear_solver_summary;
- }
- if (linear_solver_summary.termination_type ==
- LinearSolverTerminationType::FAILURE ||
- !IsArrayValid(n, gauss_newton_step_.data())) {
- mu_ *= mu_increase_factor_;
- VLOG(2) << "Increasing mu " << mu_;
- linear_solver_summary.termination_type =
- LinearSolverTerminationType::FAILURE;
- continue;
- }
- break;
- }
- if (linear_solver_summary.termination_type !=
- LinearSolverTerminationType::FAILURE) {
-
-
-
-
-
-
- gauss_newton_step_.array() *= -diagonal_.array();
- }
- return linear_solver_summary;
- }
- void DoglegStrategy::StepAccepted(double step_quality) {
- CHECK_GT(step_quality, 0.0);
- if (step_quality < decrease_threshold_) {
- radius_ *= 0.5;
- }
- if (step_quality > increase_threshold_) {
- radius_ = std::max(radius_, 3.0 * dogleg_step_norm_);
- }
-
-
-
- mu_ = std::max(min_mu_, 2.0 * mu_ / mu_increase_factor_);
- reuse_ = false;
- }
- void DoglegStrategy::StepRejected(double ) {
- radius_ *= 0.5;
- reuse_ = true;
- }
- void DoglegStrategy::StepIsInvalid() {
- mu_ *= mu_increase_factor_;
- reuse_ = false;
- }
- double DoglegStrategy::Radius() const { return radius_; }
- bool DoglegStrategy::ComputeSubspaceModel(SparseMatrix* jacobian) {
-
- Matrix basis_vectors(jacobian->num_cols(), 2);
- basis_vectors.col(0) = gradient_;
- basis_vectors.col(1) = gauss_newton_step_;
- Eigen::ColPivHouseholderQR<Matrix> basis_qr(basis_vectors);
- switch (basis_qr.rank()) {
- case 0:
-
-
-
- LOG(ERROR) << "Rank of subspace basis is 0. "
- << "This means that the gradient at the current iterate is "
- << "zero but the optimization has not been terminated. "
- << "You may have found a bug in Ceres.";
- return false;
- case 1:
-
-
-
- subspace_is_one_dimensional_ = true;
- return true;
- case 2:
- subspace_is_one_dimensional_ = false;
- break;
- default:
- LOG(ERROR) << "Rank of the subspace basis matrix is reported to be "
- << "greater than 2. As the matrix contains only two "
- << "columns this cannot be true and is indicative of "
- << "a bug.";
- return false;
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- subspace_basis_ =
- basis_qr.householderQ() * Matrix::Identity(jacobian->num_cols(), 2);
- subspace_g_ = subspace_basis_.transpose() * gradient_;
- Eigen::Matrix<double, 2, Eigen::Dynamic, Eigen::RowMajor> Jb(
- 2, jacobian->num_rows());
- Jb.setZero();
- Vector tmp;
- tmp = (subspace_basis_.col(0).array() / diagonal_.array()).matrix();
- jacobian->RightMultiplyAndAccumulate(tmp.data(), Jb.row(0).data());
- tmp = (subspace_basis_.col(1).array() / diagonal_.array()).matrix();
- jacobian->RightMultiplyAndAccumulate(tmp.data(), Jb.row(1).data());
- subspace_B_ = Jb * Jb.transpose();
- return true;
- }
- }
|