trust_region_minimizer_test.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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: keir@google.com (Keir Mierle)
  30. // sameeragarwal@google.com (Sameer Agarwal)
  31. //
  32. // This tests the TrustRegionMinimizer loop using a direct Evaluator
  33. // implementation, rather than having a test that goes through all the
  34. // Program and Problem machinery.
  35. #include "ceres/trust_region_minimizer.h"
  36. #include <cmath>
  37. #include <memory>
  38. #include "ceres/autodiff_cost_function.h"
  39. #include "ceres/cost_function.h"
  40. #include "ceres/dense_qr_solver.h"
  41. #include "ceres/dense_sparse_matrix.h"
  42. #include "ceres/evaluator.h"
  43. #include "ceres/internal/export.h"
  44. #include "ceres/linear_solver.h"
  45. #include "ceres/minimizer.h"
  46. #include "ceres/problem.h"
  47. #include "ceres/trust_region_strategy.h"
  48. #include "gtest/gtest.h"
  49. namespace ceres::internal {
  50. // Templated Evaluator for Powell's function. The template parameters
  51. // indicate which of the four variables/columns of the jacobian are
  52. // active. This is equivalent to constructing a problem and using the
  53. // SubsetManifold. This allows us to test the support for
  54. // the Evaluator::Plus operation besides checking for the basic
  55. // performance of the trust region algorithm.
  56. template <bool col1, bool col2, bool col3, bool col4>
  57. class PowellEvaluator2 : public Evaluator {
  58. public:
  59. // clang-format off
  60. PowellEvaluator2()
  61. : num_active_cols_(
  62. (col1 ? 1 : 0) +
  63. (col2 ? 1 : 0) +
  64. (col3 ? 1 : 0) +
  65. (col4 ? 1 : 0)) {
  66. VLOG(1) << "Columns: "
  67. << col1 << " "
  68. << col2 << " "
  69. << col3 << " "
  70. << col4;
  71. }
  72. // clang-format on
  73. // Implementation of Evaluator interface.
  74. std::unique_ptr<SparseMatrix> CreateJacobian() const final {
  75. CHECK(col1 || col2 || col3 || col4);
  76. auto dense_jacobian = std::make_unique<DenseSparseMatrix>(
  77. NumResiduals(), NumEffectiveParameters());
  78. dense_jacobian->SetZero();
  79. return dense_jacobian;
  80. }
  81. bool Evaluate(const Evaluator::EvaluateOptions& evaluate_options,
  82. const double* state,
  83. double* cost,
  84. double* residuals,
  85. double* gradient,
  86. SparseMatrix* jacobian) final {
  87. const double x1 = state[0];
  88. const double x2 = state[1];
  89. const double x3 = state[2];
  90. const double x4 = state[3];
  91. VLOG(1) << "State: "
  92. << "x1=" << x1 << ", "
  93. << "x2=" << x2 << ", "
  94. << "x3=" << x3 << ", "
  95. << "x4=" << x4 << ".";
  96. const double f1 = x1 + 10.0 * x2;
  97. const double f2 = sqrt(5.0) * (x3 - x4);
  98. const double f3 = pow(x2 - 2.0 * x3, 2.0);
  99. const double f4 = sqrt(10.0) * pow(x1 - x4, 2.0);
  100. VLOG(1) << "Function: "
  101. << "f1=" << f1 << ", "
  102. << "f2=" << f2 << ", "
  103. << "f3=" << f3 << ", "
  104. << "f4=" << f4 << ".";
  105. *cost = (f1 * f1 + f2 * f2 + f3 * f3 + f4 * f4) / 2.0;
  106. VLOG(1) << "Cost: " << *cost;
  107. if (residuals != nullptr) {
  108. residuals[0] = f1;
  109. residuals[1] = f2;
  110. residuals[2] = f3;
  111. residuals[3] = f4;
  112. }
  113. if (jacobian != nullptr) {
  114. DenseSparseMatrix* dense_jacobian;
  115. dense_jacobian = down_cast<DenseSparseMatrix*>(jacobian);
  116. dense_jacobian->SetZero();
  117. Matrix& jacobian_matrix = *(dense_jacobian->mutable_matrix());
  118. CHECK_EQ(jacobian_matrix.cols(), num_active_cols_);
  119. int column_index = 0;
  120. if (col1) {
  121. // clang-format off
  122. jacobian_matrix.col(column_index++) <<
  123. 1.0,
  124. 0.0,
  125. 0.0,
  126. sqrt(10.0) * 2.0 * (x1 - x4);
  127. // clang-format on
  128. }
  129. if (col2) {
  130. // clang-format off
  131. jacobian_matrix.col(column_index++) <<
  132. 10.0,
  133. 0.0,
  134. 2.0*(x2 - 2.0*x3),
  135. 0.0;
  136. // clang-format on
  137. }
  138. if (col3) {
  139. // clang-format off
  140. jacobian_matrix.col(column_index++) <<
  141. 0.0,
  142. sqrt(5.0),
  143. 4.0*(2.0*x3 - x2),
  144. 0.0;
  145. // clang-format on
  146. }
  147. if (col4) {
  148. // clang-format off
  149. jacobian_matrix.col(column_index++) <<
  150. 0.0,
  151. -sqrt(5.0),
  152. 0.0,
  153. sqrt(10.0) * 2.0 * (x4 - x1);
  154. // clang-format on
  155. }
  156. VLOG(1) << "\n" << jacobian_matrix;
  157. }
  158. if (gradient != nullptr) {
  159. int column_index = 0;
  160. if (col1) {
  161. gradient[column_index++] = f1 + f4 * sqrt(10.0) * 2.0 * (x1 - x4);
  162. }
  163. if (col2) {
  164. gradient[column_index++] = f1 * 10.0 + f3 * 2.0 * (x2 - 2.0 * x3);
  165. }
  166. if (col3) {
  167. gradient[column_index++] =
  168. f2 * sqrt(5.0) + f3 * (4.0 * (2.0 * x3 - x2));
  169. }
  170. if (col4) {
  171. gradient[column_index++] =
  172. -f2 * sqrt(5.0) + f4 * sqrt(10.0) * 2.0 * (x4 - x1);
  173. }
  174. }
  175. return true;
  176. }
  177. bool Plus(const double* state,
  178. const double* delta,
  179. double* state_plus_delta) const final {
  180. int delta_index = 0;
  181. state_plus_delta[0] = (col1 ? state[0] + delta[delta_index++] : state[0]);
  182. state_plus_delta[1] = (col2 ? state[1] + delta[delta_index++] : state[1]);
  183. state_plus_delta[2] = (col3 ? state[2] + delta[delta_index++] : state[2]);
  184. state_plus_delta[3] = (col4 ? state[3] + delta[delta_index++] : state[3]);
  185. return true;
  186. }
  187. int NumEffectiveParameters() const final { return num_active_cols_; }
  188. int NumParameters() const final { return 4; }
  189. int NumResiduals() const final { return 4; }
  190. private:
  191. const int num_active_cols_;
  192. };
  193. // Templated function to hold a subset of the columns fixed and check
  194. // if the solver converges to the optimal values or not.
  195. template <bool col1, bool col2, bool col3, bool col4>
  196. void IsTrustRegionSolveSuccessful(TrustRegionStrategyType strategy_type) {
  197. Solver::Options solver_options;
  198. LinearSolver::Options linear_solver_options;
  199. DenseQRSolver linear_solver(linear_solver_options);
  200. double parameters[4] = {3, -1, 0, 1.0};
  201. // If the column is inactive, then set its value to the optimal
  202. // value.
  203. parameters[0] = (col1 ? parameters[0] : 0.0);
  204. parameters[1] = (col2 ? parameters[1] : 0.0);
  205. parameters[2] = (col3 ? parameters[2] : 0.0);
  206. parameters[3] = (col4 ? parameters[3] : 0.0);
  207. Minimizer::Options minimizer_options(solver_options);
  208. minimizer_options.gradient_tolerance = 1e-26;
  209. minimizer_options.function_tolerance = 1e-26;
  210. minimizer_options.parameter_tolerance = 1e-26;
  211. minimizer_options.evaluator =
  212. std::make_unique<PowellEvaluator2<col1, col2, col3, col4>>();
  213. minimizer_options.jacobian = minimizer_options.evaluator->CreateJacobian();
  214. TrustRegionStrategy::Options trust_region_strategy_options;
  215. trust_region_strategy_options.trust_region_strategy_type = strategy_type;
  216. trust_region_strategy_options.linear_solver = &linear_solver;
  217. trust_region_strategy_options.initial_radius = 1e4;
  218. trust_region_strategy_options.max_radius = 1e20;
  219. trust_region_strategy_options.min_lm_diagonal = 1e-6;
  220. trust_region_strategy_options.max_lm_diagonal = 1e32;
  221. minimizer_options.trust_region_strategy =
  222. TrustRegionStrategy::Create(trust_region_strategy_options);
  223. TrustRegionMinimizer minimizer;
  224. Solver::Summary summary;
  225. minimizer.Minimize(minimizer_options, parameters, &summary);
  226. // The minimum is at x1 = x2 = x3 = x4 = 0.
  227. EXPECT_NEAR(0.0, parameters[0], 0.001);
  228. EXPECT_NEAR(0.0, parameters[1], 0.001);
  229. EXPECT_NEAR(0.0, parameters[2], 0.001);
  230. EXPECT_NEAR(0.0, parameters[3], 0.001);
  231. }
  232. TEST(TrustRegionMinimizer, PowellsSingularFunctionUsingLevenbergMarquardt) {
  233. // This case is excluded because this has a local minimum and does
  234. // not find the optimum. This should not affect the correctness of
  235. // this test since we are testing all the other 14 combinations of
  236. // column activations.
  237. //
  238. // IsSolveSuccessful<true, true, false, true>();
  239. const TrustRegionStrategyType kStrategy = LEVENBERG_MARQUARDT;
  240. // clang-format off
  241. IsTrustRegionSolveSuccessful<true, true, true, true >(kStrategy);
  242. IsTrustRegionSolveSuccessful<true, true, true, false>(kStrategy);
  243. IsTrustRegionSolveSuccessful<true, false, true, true >(kStrategy);
  244. IsTrustRegionSolveSuccessful<false, true, true, true >(kStrategy);
  245. IsTrustRegionSolveSuccessful<true, true, false, false>(kStrategy);
  246. IsTrustRegionSolveSuccessful<true, false, true, false>(kStrategy);
  247. IsTrustRegionSolveSuccessful<false, true, true, false>(kStrategy);
  248. IsTrustRegionSolveSuccessful<true, false, false, true >(kStrategy);
  249. IsTrustRegionSolveSuccessful<false, true, false, true >(kStrategy);
  250. IsTrustRegionSolveSuccessful<false, false, true, true >(kStrategy);
  251. IsTrustRegionSolveSuccessful<true, false, false, false>(kStrategy);
  252. IsTrustRegionSolveSuccessful<false, true, false, false>(kStrategy);
  253. IsTrustRegionSolveSuccessful<false, false, true, false>(kStrategy);
  254. IsTrustRegionSolveSuccessful<false, false, false, true >(kStrategy);
  255. // clang-format on
  256. }
  257. TEST(TrustRegionMinimizer, PowellsSingularFunctionUsingDogleg) {
  258. // The following two cases are excluded because they encounter a
  259. // local minimum.
  260. //
  261. // IsTrustRegionSolveSuccessful<true, true, false, true >(kStrategy);
  262. // IsTrustRegionSolveSuccessful<true, true, true, true >(kStrategy);
  263. const TrustRegionStrategyType kStrategy = DOGLEG;
  264. // clang-format off
  265. IsTrustRegionSolveSuccessful<true, true, true, false>(kStrategy);
  266. IsTrustRegionSolveSuccessful<true, false, true, true >(kStrategy);
  267. IsTrustRegionSolveSuccessful<false, true, true, true >(kStrategy);
  268. IsTrustRegionSolveSuccessful<true, true, false, false>(kStrategy);
  269. IsTrustRegionSolveSuccessful<true, false, true, false>(kStrategy);
  270. IsTrustRegionSolveSuccessful<false, true, true, false>(kStrategy);
  271. IsTrustRegionSolveSuccessful<true, false, false, true >(kStrategy);
  272. IsTrustRegionSolveSuccessful<false, true, false, true >(kStrategy);
  273. IsTrustRegionSolveSuccessful<false, false, true, true >(kStrategy);
  274. IsTrustRegionSolveSuccessful<true, false, false, false>(kStrategy);
  275. IsTrustRegionSolveSuccessful<false, true, false, false>(kStrategy);
  276. IsTrustRegionSolveSuccessful<false, false, true, false>(kStrategy);
  277. IsTrustRegionSolveSuccessful<false, false, false, true >(kStrategy);
  278. // clang-format on
  279. }
  280. class CurveCostFunction : public CostFunction {
  281. public:
  282. CurveCostFunction(int num_vertices, double target_length)
  283. : num_vertices_(num_vertices), target_length_(target_length) {
  284. set_num_residuals(1);
  285. for (int i = 0; i < num_vertices_; ++i) {
  286. mutable_parameter_block_sizes()->push_back(2);
  287. }
  288. }
  289. bool Evaluate(double const* const* parameters,
  290. double* residuals,
  291. double** jacobians) const override {
  292. residuals[0] = target_length_;
  293. for (int i = 0; i < num_vertices_; ++i) {
  294. int prev = (num_vertices_ + i - 1) % num_vertices_;
  295. double length = 0.0;
  296. for (int dim = 0; dim < 2; dim++) {
  297. const double diff = parameters[prev][dim] - parameters[i][dim];
  298. length += diff * diff;
  299. }
  300. residuals[0] -= sqrt(length);
  301. }
  302. if (jacobians == nullptr) {
  303. return true;
  304. }
  305. for (int i = 0; i < num_vertices_; ++i) {
  306. if (jacobians[i] != nullptr) {
  307. int prev = (num_vertices_ + i - 1) % num_vertices_;
  308. int next = (i + 1) % num_vertices_;
  309. double u[2], v[2];
  310. double norm_u = 0., norm_v = 0.;
  311. for (int dim = 0; dim < 2; dim++) {
  312. u[dim] = parameters[i][dim] - parameters[prev][dim];
  313. norm_u += u[dim] * u[dim];
  314. v[dim] = parameters[next][dim] - parameters[i][dim];
  315. norm_v += v[dim] * v[dim];
  316. }
  317. norm_u = sqrt(norm_u);
  318. norm_v = sqrt(norm_v);
  319. for (int dim = 0; dim < 2; dim++) {
  320. jacobians[i][dim] = 0.;
  321. if (norm_u > std::numeric_limits<double>::min()) {
  322. jacobians[i][dim] -= u[dim] / norm_u;
  323. }
  324. if (norm_v > std::numeric_limits<double>::min()) {
  325. jacobians[i][dim] += v[dim] / norm_v;
  326. }
  327. }
  328. }
  329. }
  330. return true;
  331. }
  332. private:
  333. int num_vertices_;
  334. double target_length_;
  335. };
  336. TEST(TrustRegionMinimizer, JacobiScalingTest) {
  337. int N = 6;
  338. std::vector<double*> y(N);
  339. const double pi = 3.1415926535897932384626433;
  340. for (int i = 0; i < N; i++) {
  341. double theta = i * 2. * pi / static_cast<double>(N);
  342. y[i] = new double[2];
  343. y[i][0] = cos(theta);
  344. y[i][1] = sin(theta);
  345. }
  346. Problem problem;
  347. problem.AddResidualBlock(new CurveCostFunction(N, 10.), nullptr, y);
  348. Solver::Options options;
  349. options.linear_solver_type = ceres::DENSE_QR;
  350. Solver::Summary summary;
  351. Solve(options, &problem, &summary);
  352. EXPECT_LE(summary.final_cost, 1e-10);
  353. for (int i = 0; i < N; i++) {
  354. delete[] y[i];
  355. }
  356. }
  357. struct ExpCostFunctor {
  358. template <typename T>
  359. bool operator()(const T* const x, T* residual) const {
  360. residual[0] = T(10.0) - exp(x[0]);
  361. return true;
  362. }
  363. static CostFunction* Create() {
  364. return new AutoDiffCostFunction<ExpCostFunctor, 1, 1>(new ExpCostFunctor);
  365. }
  366. };
  367. TEST(TrustRegionMinimizer, GradientToleranceConvergenceUpdatesStep) {
  368. double x = 5;
  369. Problem problem;
  370. problem.AddResidualBlock(ExpCostFunctor::Create(), nullptr, &x);
  371. problem.SetParameterLowerBound(&x, 0, 3.0);
  372. Solver::Options options;
  373. Solver::Summary summary;
  374. Solve(options, &problem, &summary);
  375. EXPECT_NEAR(3.0, x, 1e-12);
  376. const double expected_final_cost = 0.5 * pow(10.0 - exp(3.0), 2);
  377. EXPECT_NEAR(expected_final_cost, summary.final_cost, 1e-12);
  378. }
  379. } // namespace ceres::internal