g2o
optimization_algorithm_levenberg.cpp
Go to the documentation of this file.
1 // g2o - General Graph Optimization
2 // Copyright (C) 2011 R. Kuemmerle, G. Grisetti, W. Burgard
3 // All rights reserved.
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 // * Redistributions of source code must retain the above copyright notice,
10 // this list of conditions and the following disclaimer.
11 // * Redistributions in binary form must reproduce the above copyright
12 // notice, this list of conditions and the following disclaimer in the
13 // documentation and/or other materials provided with the distribution.
14 //
15 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
16 // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
17 // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
18 // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
19 // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
21 // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 
28 
29 #include <iostream>
30 
31 #include "g2o/stuff/timeutil.h"
32 
33 #include "sparse_optimizer.h"
34 #include "solver.h"
35 #include "batch_stats.h"
36 using namespace std;
37 
38 namespace g2o {
39 
40  OptimizationAlgorithmLevenberg::OptimizationAlgorithmLevenberg(Solver* solver) :
42  {
43  _currentLambda = -1.;
44  _tau = 1e-5;
45  _goodStepUpperScale = 2./3.;
46  _goodStepLowerScale = 1./3.;
48  _maxTrialsAfterFailure = _properties.makeProperty<Property<int> >("maxTrialsAfterFailure", 10);
49  _ni=2.;
51  }
52 
54  {
55  }
56 
57  OptimizationAlgorithm::SolverResult OptimizationAlgorithmLevenberg::solve(int iteration, bool online)
58  {
59  assert(_optimizer && "_optimizer not set");
60  assert(_solver->optimizer() == _optimizer && "underlying linear solver operates on different graph");
61 
62  if (iteration == 0 && !online) { // built up the CCS structure, here due to easy time measure
63  bool ok = _solver->buildStructure();
64  if (! ok) {
65  cerr << __PRETTY_FUNCTION__ << ": Failure while building CCS structure" << endl;
66  return OptimizationAlgorithm::Fail;
67  }
68  }
69 
70  double t=get_monotonic_time();
73  if (globalStats) {
74  globalStats->timeResiduals = get_monotonic_time()-t;
76  }
77 
78  double currentChi = _optimizer->activeRobustChi2();
79  double tempChi=currentChi;
80 
82  if (globalStats) {
83  globalStats->timeQuadraticForm = get_monotonic_time()-t;
84  }
85 
86  // core part of the Levenbarg algorithm
87  if (iteration == 0) {
89  _ni = 2;
90  }
91 
92  double rho=0;
93  int& qmax = _levenbergIterations;
94  qmax = 0;
95  do {
96  _optimizer->push();
97  if (globalStats) {
98  globalStats->levenbergIterations++;
100  }
101  // update the diagonal of the system matrix
103  bool ok2 = _solver->solve();
104  if (globalStats) {
105  globalStats->timeLinearSolution+=get_monotonic_time()-t;
106  t=get_monotonic_time();
107  }
108  _optimizer->update(_solver->x());
109  if (globalStats) {
110  globalStats->timeUpdate = get_monotonic_time()-t;
111  }
112 
113  // restore the diagonal
115 
117  tempChi = _optimizer->activeRobustChi2();
118 
119  if (! ok2)
120  tempChi=std::numeric_limits<double>::max();
121 
122  rho = (currentChi-tempChi);
123  double scale = computeScale();
124  scale += 1e-3; // make sure it's non-zero :)
125  rho /= scale;
126 
127  if (rho>0 && g2o_isfinite(tempChi)){ // last step was good
128  double alpha = 1.-pow((2*rho-1),3);
129  // crop lambda between minimum and maximum factors
130  alpha = (std::min)(alpha, _goodStepUpperScale);
131  double scaleFactor = (std::max)(_goodStepLowerScale, alpha);
132  _currentLambda *= scaleFactor;
133  _ni = 2;
134  currentChi=tempChi;
136  } else {
138  _ni*=2;
139  _optimizer->pop(); // restore the last state before trying to optimize
140  }
141  qmax++;
142  } while (rho<0 && qmax < _maxTrialsAfterFailure->value() && ! _optimizer->terminate());
143 
144  if (qmax == _maxTrialsAfterFailure->value() || rho==0)
145  return Terminate;
146  return OK;
147  }
148 
150  {
151  if (_userLambdaInit->value() > 0)
152  return _userLambdaInit->value();
153  double maxDiagonal=0.;
154  for (size_t k = 0; k < _optimizer->indexMapping().size(); k++) {
156  assert(v);
157  int dim = v->dimension();
158  for (int j = 0; j < dim; ++j){
159  maxDiagonal = std::max(fabs(v->hessian(j,j)),maxDiagonal);
160  }
161  }
162  return _tau*maxDiagonal;
163  }
164 
166  {
167  double scale = 0.;
168  for (size_t j=0; j < _solver->vectorSize(); j++){
169  scale += _solver->x()[j] * (_currentLambda * _solver->x()[j] + _solver->b()[j]);
170  }
171  return scale;
172  }
173 
175  {
176  _maxTrialsAfterFailure->setValue(max_trials);
177  }
178 
180  {
181  _userLambdaInit->setValue(lambda);
182  }
183 
184  void OptimizationAlgorithmLevenberg::printVerbose(std::ostream& os) const
185  {
186  os
187  << "\t schur= " << _solver->schur()
188  << "\t lambda= " << FIXED(_currentLambda)
189  << "\t levenbergIter= " << _levenbergIterations;
190  }
191 
192 } // end namespace
double get_monotonic_time()
Definition: timeutil.cpp:113
virtual void restoreDiagonal()=0
virtual bool schur()=0
should the solver perform the schur complement or not
statistics about the optimization
Definition: batch_stats.h:40
bool terminate()
if external stop flag is given, return its state. False otherwise
#define __PRETTY_FUNCTION__
Definition: macros.h:89
double _goodStepLowerScale
lower bound for lambda decrease if a good LM step
virtual const double & hessian(int i, int j) const =0
get the element from the hessian matrix
double _goodStepUpperScale
upper bound for lambda decrease if a good LM step
double timeResiduals
residuals
Definition: batch_stats.h:49
int _levenbergIterations
the numer of levenberg iterations performed to accept the last step
virtual void printVerbose(std::ostream &os) const
void pop(SparseOptimizer::VertexContainer &vlist)
pop (restore) the estimate a subset of the variables from the stack
virtual bool setLambda(double lambda, bool backup=false)=0
int levenbergIterations
number of iterations performed by LM
Definition: batch_stats.h:52
void discardTop(SparseOptimizer::VertexContainer &vlist)
ignore the latest stored element on the stack, remove it from the stack but do not restore the estima...
Base for solvers operating on the approximated Hessian, e.g., Gauss-Newton, Levenberg.
utility functions for handling time related stuff
PropertyMap _properties
the properties of your solver, use this to store the parameters of your solver
int dimension() const
dimension of the estimated state belonging to this node
P * makeProperty(const std::string &name_, const typename P::ValueType &v)
Definition: property.h:119
void setValue(const T &v)
Definition: property.h:56
Generic interface for a sparse solver operating on a graph which solves one iteration of the lineariz...
Definition: solver.h:44
SparseOptimizer * _optimizer
the optimizer the solver is working on
static G2OBatchStatistics * globalStats()
Definition: batch_stats.h:73
const VertexContainer & indexMapping() const
the index mapping of the vertices
SparseOptimizer * optimizer() const
the optimizer (graph) on which the solver works
Definition: solver.h:106
virtual bool solve()=0
A general case Vertex for optimization.
double * x()
return x, the solution vector
Definition: solver.h:96
#define g2o_isfinite(x)
Definition: macros.h:101
void setUserLambdaInit(double lambda)
specify the initial lambda used for the first iteraion, if not given the SparseOptimizer tries to com...
double timeUpdate
time to apply the update
Definition: batch_stats.h:62
double * b()
return b, the right hand side of the system
Definition: solver.h:99
virtual bool buildSystem()=0
size_t vectorSize() const
return the size of the solution vector (x) and b
Definition: solver.h:103
double activeRobustChi2() const
const T & value() const
Definition: property.h:57
double timeQuadraticForm
construct the quadratic form in the graph
Definition: batch_stats.h:51
void setMaxTrialsAfterFailure(int max_trials)
the number of internal iteration if an update step increases chi^2 within Levenberg-Marquardt ...
void push(SparseOptimizer::VertexContainer &vlist)
push the estimate of a subset of the variables onto a stack
double timeLinearSolution
total time for solving Ax=b (including detup for schur)
Definition: batch_stats.h:59
virtual SolverResult solve(int iteration, bool online=false)
virtual bool buildStructure(bool zeroBlocks=false)=0