gradient_problem_solver.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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: sameeragarwal@google.com (Sameer Agarwal)
  30. #ifndef CERES_PUBLIC_GRADIENT_PROBLEM_SOLVER_H_
  31. #define CERES_PUBLIC_GRADIENT_PROBLEM_SOLVER_H_
  32. #include <cmath>
  33. #include <string>
  34. #include <vector>
  35. #include "ceres/internal/disable_warnings.h"
  36. #include "ceres/internal/export.h"
  37. #include "ceres/internal/port.h"
  38. #include "ceres/iteration_callback.h"
  39. #include "ceres/types.h"
  40. namespace ceres {
  41. class GradientProblem;
  42. class CERES_EXPORT GradientProblemSolver {
  43. public:
  44. virtual ~GradientProblemSolver();
  45. // The options structure contains, not surprisingly, options that control how
  46. // the solver operates. The defaults should be suitable for a wide range of
  47. // problems; however, better performance is often obtainable with tweaking.
  48. //
  49. // The constants are defined inside types.h
  50. struct CERES_EXPORT Options {
  51. // Returns true if the options struct has a valid
  52. // configuration. Returns false otherwise, and fills in *error
  53. // with a message describing the problem.
  54. bool IsValid(std::string* error) const;
  55. // Minimizer options ----------------------------------------
  56. LineSearchDirectionType line_search_direction_type = LBFGS;
  57. LineSearchType line_search_type = WOLFE;
  58. NonlinearConjugateGradientType nonlinear_conjugate_gradient_type =
  59. FLETCHER_REEVES;
  60. // The LBFGS hessian approximation is a low rank approximation to
  61. // the inverse of the Hessian matrix. The rank of the
  62. // approximation determines (linearly) the space and time
  63. // complexity of using the approximation. Higher the rank, the
  64. // better is the quality of the approximation. The increase in
  65. // quality is however is bounded for a number of reasons.
  66. //
  67. // 1. The method only uses secant information and not actual
  68. // derivatives.
  69. //
  70. // 2. The Hessian approximation is constrained to be positive
  71. // definite.
  72. //
  73. // So increasing this rank to a large number will cost time and
  74. // space complexity without the corresponding increase in solution
  75. // quality. There are no hard and fast rules for choosing the
  76. // maximum rank. The best choice usually requires some problem
  77. // specific experimentation.
  78. //
  79. // For more theoretical and implementation details of the LBFGS
  80. // method, please see:
  81. //
  82. // Nocedal, J. (1980). "Updating Quasi-Newton Matrices with
  83. // Limited Storage". Mathematics of Computation 35 (151): 773-782.
  84. int max_lbfgs_rank = 20;
  85. // As part of the (L)BFGS update step (BFGS) / right-multiply step (L-BFGS),
  86. // the initial inverse Hessian approximation is taken to be the Identity.
  87. // However, Oren showed that using instead I * \gamma, where \gamma is
  88. // chosen to approximate an eigenvalue of the true inverse Hessian can
  89. // result in improved convergence in a wide variety of cases. Setting
  90. // use_approximate_eigenvalue_bfgs_scaling to true enables this scaling.
  91. //
  92. // It is important to note that approximate eigenvalue scaling does not
  93. // always improve convergence, and that it can in fact significantly degrade
  94. // performance for certain classes of problem, which is why it is disabled
  95. // by default. In particular it can degrade performance when the
  96. // sensitivity of the problem to different parameters varies significantly,
  97. // as in this case a single scalar factor fails to capture this variation
  98. // and detrimentally downscales parts of the jacobian approximation which
  99. // correspond to low-sensitivity parameters. It can also reduce the
  100. // robustness of the solution to errors in the jacobians.
  101. //
  102. // Oren S.S., Self-scaling variable metric (SSVM) algorithms
  103. // Part II: Implementation and experiments, Management Science,
  104. // 20(5), 863-874, 1974.
  105. bool use_approximate_eigenvalue_bfgs_scaling = false;
  106. // Degree of the polynomial used to approximate the objective
  107. // function. Valid values are BISECTION, QUADRATIC and CUBIC.
  108. //
  109. // BISECTION corresponds to pure backtracking search with no
  110. // interpolation.
  111. LineSearchInterpolationType line_search_interpolation_type = CUBIC;
  112. // If during the line search, the step_size falls below this
  113. // value, it is truncated to zero.
  114. double min_line_search_step_size = 1e-9;
  115. // Line search parameters.
  116. // Solving the line search problem exactly is computationally
  117. // prohibitive. Fortunately, line search based optimization
  118. // algorithms can still guarantee convergence if instead of an
  119. // exact solution, the line search algorithm returns a solution
  120. // which decreases the value of the objective function
  121. // sufficiently. More precisely, we are looking for a step_size
  122. // s.t.
  123. //
  124. // f(step_size) <= f(0) + sufficient_decrease * f'(0) * step_size
  125. //
  126. double line_search_sufficient_function_decrease = 1e-4;
  127. // In each iteration of the line search,
  128. //
  129. // new_step_size >= max_line_search_step_contraction * step_size
  130. //
  131. // Note that by definition, for contraction:
  132. //
  133. // 0 < max_step_contraction < min_step_contraction < 1
  134. //
  135. double max_line_search_step_contraction = 1e-3;
  136. // In each iteration of the line search,
  137. //
  138. // new_step_size <= min_line_search_step_contraction * step_size
  139. //
  140. // Note that by definition, for contraction:
  141. //
  142. // 0 < max_step_contraction < min_step_contraction < 1
  143. //
  144. double min_line_search_step_contraction = 0.6;
  145. // Maximum number of trial step size iterations during each line search,
  146. // if a step size satisfying the search conditions cannot be found within
  147. // this number of trials, the line search will terminate.
  148. int max_num_line_search_step_size_iterations = 20;
  149. // Maximum number of restarts of the line search direction algorithm before
  150. // terminating the optimization. Restarts of the line search direction
  151. // algorithm occur when the current algorithm fails to produce a new descent
  152. // direction. This typically indicates a numerical failure, or a breakdown
  153. // in the validity of the approximations used.
  154. int max_num_line_search_direction_restarts = 5;
  155. // The strong Wolfe conditions consist of the Armijo sufficient
  156. // decrease condition, and an additional requirement that the
  157. // step-size be chosen s.t. the _magnitude_ ('strong' Wolfe
  158. // conditions) of the gradient along the search direction
  159. // decreases sufficiently. Precisely, this second condition
  160. // is that we seek a step_size s.t.
  161. //
  162. // |f'(step_size)| <= sufficient_curvature_decrease * |f'(0)|
  163. //
  164. // Where f() is the line search objective and f'() is the derivative
  165. // of f w.r.t step_size (d f / d step_size).
  166. double line_search_sufficient_curvature_decrease = 0.9;
  167. // During the bracketing phase of the Wolfe search, the step size is
  168. // increased until either a point satisfying the Wolfe conditions is
  169. // found, or an upper bound for a bracket containing a point satisfying
  170. // the conditions is found. Precisely, at each iteration of the
  171. // expansion:
  172. //
  173. // new_step_size <= max_step_expansion * step_size.
  174. //
  175. // By definition for expansion, max_step_expansion > 1.0.
  176. double max_line_search_step_expansion = 10.0;
  177. // Maximum number of iterations for the minimizer to run for.
  178. int max_num_iterations = 50;
  179. // Maximum time for which the minimizer should run for.
  180. double max_solver_time_in_seconds = 1e9;
  181. // Minimizer terminates when
  182. //
  183. // (new_cost - old_cost) < function_tolerance * old_cost;
  184. //
  185. double function_tolerance = 1e-6;
  186. // Minimizer terminates when
  187. //
  188. // max_i |x - Project(Plus(x, -g(x))| < gradient_tolerance
  189. //
  190. // This value should typically be 1e-4 * function_tolerance.
  191. double gradient_tolerance = 1e-10;
  192. // Minimizer terminates when
  193. //
  194. // |step|_2 <= parameter_tolerance * ( |x|_2 + parameter_tolerance)
  195. //
  196. double parameter_tolerance = 1e-8;
  197. // Logging options ---------------------------------------------------------
  198. LoggingType logging_type = PER_MINIMIZER_ITERATION;
  199. // By default the Minimizer progress is logged to VLOG(1), which
  200. // is sent to STDERR depending on the vlog level. If this flag is
  201. // set to true, and logging_type is not SILENT, the logging output
  202. // is sent to STDOUT.
  203. bool minimizer_progress_to_stdout = false;
  204. // If true, the user's parameter blocks are updated at the end of
  205. // every Minimizer iteration, otherwise they are updated when the
  206. // Minimizer terminates. This is useful if, for example, the user
  207. // wishes to visualize the state of the optimization every
  208. // iteration.
  209. bool update_state_every_iteration = false;
  210. // Callbacks that are executed at the end of each iteration of the
  211. // Minimizer. An iteration may terminate midway, either due to
  212. // numerical failures or because one of the convergence tests has
  213. // been satisfied. In this case none of the callbacks are
  214. // executed.
  215. // Callbacks are executed in the order that they are specified in
  216. // this vector. By default, parameter blocks are updated only at
  217. // the end of the optimization, i.e when the Minimizer
  218. // terminates. This behaviour is controlled by
  219. // update_state_every_variable. If the user wishes to have access
  220. // to the update parameter blocks when his/her callbacks are
  221. // executed, then set update_state_every_iteration to true.
  222. //
  223. // The solver does NOT take ownership of these pointers.
  224. std::vector<IterationCallback*> callbacks;
  225. };
  226. struct CERES_EXPORT Summary {
  227. // A brief one line description of the state of the solver after
  228. // termination.
  229. std::string BriefReport() const;
  230. // A full multiline description of the state of the solver after
  231. // termination.
  232. std::string FullReport() const;
  233. bool IsSolutionUsable() const;
  234. // Minimizer summary -------------------------------------------------
  235. TerminationType termination_type = FAILURE;
  236. // Reason why the solver terminated.
  237. std::string message = "ceres::GradientProblemSolve was not called.";
  238. // Cost of the problem (value of the objective function) before
  239. // the optimization.
  240. double initial_cost = -1.0;
  241. // Cost of the problem (value of the objective function) after the
  242. // optimization.
  243. double final_cost = -1.0;
  244. // IterationSummary for each minimizer iteration in order.
  245. std::vector<IterationSummary> iterations;
  246. // Number of times the cost (and not the gradient) was evaluated.
  247. int num_cost_evaluations = -1;
  248. // Number of times the gradient (and the cost) were evaluated.
  249. int num_gradient_evaluations = -1;
  250. // Sum total of all time spent inside Ceres when Solve is called.
  251. double total_time_in_seconds = -1.0;
  252. // Time (in seconds) spent evaluating the cost.
  253. double cost_evaluation_time_in_seconds = -1.0;
  254. // Time (in seconds) spent evaluating the gradient.
  255. double gradient_evaluation_time_in_seconds = -1.0;
  256. // Time (in seconds) spent minimizing the interpolating polynomial
  257. // to compute the next candidate step size as part of a line search.
  258. double line_search_polynomial_minimization_time_in_seconds = -1.0;
  259. // Number of parameters in the problem.
  260. int num_parameters = -1;
  261. // Dimension of the tangent space of the problem.
  262. int num_tangent_parameters = -1;
  263. // Type of line search direction used.
  264. LineSearchDirectionType line_search_direction_type = LBFGS;
  265. // Type of the line search algorithm used.
  266. LineSearchType line_search_type = WOLFE;
  267. // When performing line search, the degree of the polynomial used
  268. // to approximate the objective function.
  269. LineSearchInterpolationType line_search_interpolation_type = CUBIC;
  270. // If the line search direction is NONLINEAR_CONJUGATE_GRADIENT,
  271. // then this indicates the particular variant of non-linear
  272. // conjugate gradient used.
  273. NonlinearConjugateGradientType nonlinear_conjugate_gradient_type =
  274. FLETCHER_REEVES;
  275. // If the type of the line search direction is LBFGS, then this
  276. // indicates the rank of the Hessian approximation.
  277. int max_lbfgs_rank = -1;
  278. };
  279. // Once a least squares problem has been built, this function takes
  280. // the problem and optimizes it based on the values of the options
  281. // parameters. Upon return, a detailed summary of the work performed
  282. // by the preprocessor, the non-linear minimizer and the linear
  283. // solver are reported in the summary object.
  284. virtual void Solve(const GradientProblemSolver::Options& options,
  285. const GradientProblem& problem,
  286. double* parameters,
  287. GradientProblemSolver::Summary* summary);
  288. };
  289. // Helper function which avoids going through the interface.
  290. CERES_EXPORT void Solve(const GradientProblemSolver::Options& options,
  291. const GradientProblem& problem,
  292. double* parameters,
  293. GradientProblemSolver::Summary* summary);
  294. } // namespace ceres
  295. #include "ceres/internal/reenable_warnings.h"
  296. #endif // CERES_PUBLIC_GRADIENT_PROBLEM_SOLVER_H_