Autoware.Auto
more_thuente_line_search.hpp
Go to the documentation of this file.
1 // Copyright 2020 the Autoware Foundation
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //    http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 // Co-developed by Tier IV, Inc. and Apex.AI, Inc.
16 
17 
18 // This file contains modified code from the following open source projects
19 // published under the licenses listed below:
20 //
21 // Software License Agreement (BSD License)
22 //
23 // Point Cloud Library (PCL) - www.pointclouds.org
24 // Copyright (c) 2010-2011, Willow Garage, Inc.
25 // Copyright (c) 2012-, Open Perception, Inc.
26 //
27 // All rights reserved.
28 //
29 // Redistribution and use in source and binary forms, with or without
30 // modification, are permitted provided that the following conditions
31 // are met:
32 //
33 // * Redistributions of source code must retain the above copyright
34 // notice, this list of conditions and the following disclaimer.
35 // * Redistributions in binary form must reproduce the above
36 // copyright notice, this list of conditions and the following
37 // disclaimer in the documentation and/or other materials provided
38 // with the distribution.
39 // * Neither the name of the copyright holder(s) nor the names of its
40 // contributors may be used to endorse or promote products derived
41 // from this software without specific prior written permission.
42 //
43 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
44 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
45 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
46 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
47 // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
48 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
49 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
50 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
51 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
52 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
53 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
54 // POSSIBILITY OF SUCH DAMAGE.
55 
56 #ifndef OPTIMIZATION__LINE_SEARCH__MORE_THUENTE_LINE_SEARCH_HPP_
57 #define OPTIMIZATION__LINE_SEARCH__MORE_THUENTE_LINE_SEARCH_HPP_
58 
60 #include <optimization/utils.hpp>
62 
63 #include <limits>
64 #include <algorithm>
65 #include <utility>
66 
67 namespace autoware
68 {
69 namespace common
70 {
71 namespace comp = helper_functions::comparisons;
72 namespace optimization
73 {
74 
75 namespace detail
76 {
78 constexpr common::types::float32_t kDelta = 0.66F;
79 } // namespace detail
80 
94 class OPTIMIZATION_PUBLIC MoreThuenteLineSearch : public LineSearch<MoreThuenteLineSearch>
95 {
96 public:
101  {
102  kMinimization,
103  kMaximization
104  };
105 
119  const StepT max_step,
120  const StepT min_step,
121  const OptimizationDirection optimization_direction = OptimizationDirection::kMinimization,
122  const StepT mu = 1.e-4F,
123  const StepT eta = 0.1F, // Default value suggested in Section 5 of the paper.
124  const std::int32_t max_iterations = 10)
125  : LineSearch{max_step},
126  m_step_min{min_step},
127  m_optimization_direction{optimization_direction},
128  m_mu{mu},
129  m_eta{eta},
130  m_max_iterations{max_iterations}
131  {
132  if (min_step < 0.0F) {throw std::domain_error("Min step cannot be negative.");}
133  if (max_step < min_step) {throw std::domain_error("Max step cannot be smaller than min step.");}
134  if (mu < 0.0F || mu > 1.0F) {throw std::domain_error("mu must be in (0, 1).");}
135  if (eta < 0.0F || eta > 1.0F) {throw std::domain_error("eta must be in (0, 1).");}
136  if (max_iterations < 1) {throw std::domain_error("Less than 1 iteration is not allowed.");}
137  m_compute_mode.set_score().set_jacobian();
138  }
139 
157  template<typename DomainValueT, typename OptimizationProblemT>
158  DomainValueT compute_next_step_(
159  const DomainValueT & x0,
160  const DomainValueT & initial_step,
161  OptimizationProblemT & optimization_problem);
162 
163 private:
165  struct Interval
166  {
167  StepT a_l;
168  StepT a_u;
169  };
170 
174  template<typename OptimizationProblemT>
175  class ObjectiveFunction;
176 
181  template<typename ObjectiveFunctionT>
182  class AuxiliaryFunction;
183 
184  // Find the next step as described in section 4 of the paper.
185  template<typename FunctionValueT>
186  StepT find_next_step_length(
187  const FunctionValueT & f_t, const FunctionValueT & f_l, const FunctionValueT & f_u);
188 
189  // Find the next [a_l, a_u] interval as described in the "Updating Algorithm" with function psi
190  // and "Modifier Updating Algorithm" with function phi.
191  template<typename FunctionValueT>
192  Interval update_interval(
193  const FunctionValueT & f_t, const FunctionValueT & f_l, const FunctionValueT & f_u);
194 
195  StepT m_step_min{};
196  OptimizationDirection m_optimization_direction;
197  ComputeMode m_compute_mode{};
198  StepT m_mu{};
199  StepT m_eta{};
200  std::int32_t m_max_iterations{};
201 };
202 
203 template<typename DomainValueT, typename OptimizationProblemT>
205  const DomainValueT & x0, const DomainValueT & initial_step,
206  OptimizationProblemT & optimization_problem)
207 {
208  auto a_t = std::min(static_cast<StepT>(initial_step.norm()), get_step_max());
209  if (a_t < m_step_min) {
210  // We don't want to perform the line search as the initial step is out of allowed bounds. We
211  // assume that the optimizer knows what it is doing and return the initial_step unmodified.
212  return initial_step;
213  }
214  // Function phi as defined in eq. 1.3
215  using FunctionPhi = ObjectiveFunction<OptimizationProblemT>;
216  // Function phi as defined right before eq. 2.1
217  using FunctionPsi = AuxiliaryFunction<FunctionPhi>;
218  FunctionPhi phi{x0, initial_step, optimization_problem, m_optimization_direction};
219  FunctionPsi psi{phi, m_mu};
220 
221 
222  Interval interval{m_step_min, get_step_max()};
223  const auto phi_0 = phi(0.0F);
224  auto phi_t = phi(a_t);
225  auto psi_t = psi(a_t);
226  auto f_l = psi(interval.a_l);
227  auto f_u = psi(interval.a_u);
228 
229  bool use_auxiliary_function = true;
230  // Follows the "Search Algorithm" as presented in the paper.
231  for (auto step_iterations = 0; step_iterations < m_max_iterations; ++step_iterations) {
232  constexpr decltype(psi_t.value) ZERO{};
233  if ((psi_t.value <= ZERO) &&
234  (std::abs(phi_t.derivative) <= m_eta * std::abs(phi_0.derivative)))
235  {
236  // We reached the termination condition as the step satisfies the strong Wolfe conditions (the
237  // ones in the if condition). This means we have converged and are ready to return the found
238  // step.
239  break;
240  }
241 
242  // Pick next step size by interpolating either phi or psi depending on which update algorithm is
243  // currently being used.
244  if (use_auxiliary_function) {
245  a_t = find_next_step_length(psi_t, f_l, f_u);
246  } else {
247  a_t = find_next_step_length(phi_t, f_l, f_u);
248  }
249  if (a_t < m_step_min || std::isnan(a_t)) {
250  // This can happen if we are closer than the minimum step to the optimum. We don't want to do
251  // anything in this case.
252  a_t = 0.0F;
253  break;
254  }
255  phi_t = phi(a_t);
256  psi_t = psi(a_t);
257 
258  // Decide if we want to switch to using a "Modified Updating Algorithm" (shown after theorem 3.2
259  // in the paper) by switching from using function psi to using function phi. The decision
260  // follows the logic in the paragraph right before theorem 3.3 in the paper.
261  if (use_auxiliary_function && (psi_t.value <= 0.0 && psi_t.derivative > 0.0)) {
262  use_auxiliary_function = false;
263  // We now want to switch to using phi so compute the required values.
264  f_l = phi(interval.a_l);
265  f_u = phi(interval.a_u);
266  }
267 
268  if (use_auxiliary_function) {
269  // Update the interval that will be used to generate the next step using the
270  // "Updating Algorithm" (right after theorem 2.1 in the paper).
271  interval = update_interval(psi_t, f_l, f_u);
272  f_l = psi(interval.a_l);
273  f_u = psi(interval.a_u);
274  } else {
275  // Update the interval that will be used to generate the next step using the
276  // "Modified Updating Algorithm" (right after theorem 3.2 in the paper).
277  interval = update_interval(phi_t, f_l, f_u);
278  f_l = phi(interval.a_l);
279  f_u = phi(interval.a_u);
280  }
281  constexpr auto EPS = std::numeric_limits<StepT>::epsilon();
282  if (comp::approx_eq(interval.a_u, interval.a_l, m_step_min, EPS)) {
283  // The interval has converged to a point so we can stop here.
284  a_t = interval.a_u;
285  break;
286  }
287  }
288  return a_t * phi.get_step_direction();
289 }
290 
291 template<typename OptimizationProblemT>
292 class MoreThuenteLineSearch::ObjectiveFunction
293 {
294  using ValueT = typename OptimizationProblemT::Value;
295  using JacobianT = typename OptimizationProblemT::Jacobian;
296  using DomainValueT = typename OptimizationProblemT::DomainValue;
297 
298 public:
301  {
302  StepT argument;
303  ValueT value;
304  ValueT derivative;
305  };
306 
307  ObjectiveFunction(
308  const DomainValueT & starting_state,
309  const DomainValueT & initial_step,
310  OptimizationProblemT & underlying_function,
311  const OptimizationDirection direction)
312  : m_starting_state{starting_state},
313  m_step_direction{initial_step.normalized()},
314  m_underlying_function{underlying_function}
315  {
316  m_compute_mode.set_score().set_jacobian();
317  m_underlying_function.evaluate(m_starting_state, m_compute_mode);
318  m_underlying_function.jacobian(m_starting_state, m_underlying_function_jacobian);
319  const auto derivative = m_underlying_function_jacobian.dot(m_step_direction);
320  switch (direction) {
321  case OptimizationDirection::kMinimization:
322  if (derivative > ValueT{0.0}) {
323  m_step_direction *= -1.0;
324  }
325  break;
326  case OptimizationDirection::kMaximization:
327  if (derivative < ValueT{0.0}) {
328  m_step_direction *= -1.0;
329  }
330  // The function phi must have a derivative < 0 following the introduction of the
331  // More-Thuente paper. In case we want to solve a maximization problem, the derivative will
332  // be positive and we need to make a dual problem from it by flipping the values of phi.
333  m_multiplier = ValueT{-1.0};
334  break;
335  }
336  }
337 
339  FunctionValue operator()(const StepT & step_size)
340  {
341  if (step_size < StepT{0.0}) {throw std::runtime_error("Step cannot be negative");}
342  const auto current_state = m_starting_state + step_size * m_step_direction;
343  m_underlying_function.evaluate(current_state, m_compute_mode);
344  m_underlying_function.jacobian(current_state, m_underlying_function_jacobian);
345  return {
346  step_size,
347  m_multiplier * m_underlying_function(current_state),
348  m_multiplier * m_underlying_function_jacobian.dot(m_step_direction)};
349  }
350 
352  const DomainValueT & get_step_direction() const noexcept {return m_step_direction;}
353 
354 private:
355  DomainValueT m_starting_state;
356  DomainValueT m_step_direction;
357  OptimizationProblemT & m_underlying_function;
358  ComputeMode m_compute_mode{};
359  JacobianT m_underlying_function_jacobian;
360  ValueT m_multiplier{1.0};
361 };
362 
363 
364 template<typename ObjectiveFunctionT>
365 class MoreThuenteLineSearch::AuxiliaryFunction
366 {
367  using FunctionValue = typename ObjectiveFunctionT::FunctionValue;
368 
369 public:
371  AuxiliaryFunction(ObjectiveFunctionT & objective_function, const StepT & mu)
372  : m_objective_function{objective_function},
373  m_mu{mu},
374  m_initial_objective_function_value{objective_function(0.0F)} {}
375 
377  FunctionValue operator()(const StepT & step_size)
378  {
379  const auto & objective_function_value = m_objective_function(step_size);
380  const auto value =
381  objective_function_value.value -
382  m_initial_objective_function_value.value -
383  m_mu * step_size * objective_function_value.derivative;
384  const auto derivative =
385  objective_function_value.derivative - m_mu * m_initial_objective_function_value.derivative;
386  return {step_size, value, derivative};
387  }
388 
389 private:
390  ObjectiveFunctionT & m_objective_function;
391  StepT m_mu{};
392  FunctionValue m_initial_objective_function_value{};
393  FunctionValue m_value{};
394 };
395 
396 template<typename FunctionValueT>
397 MoreThuenteLineSearch::StepT MoreThuenteLineSearch::find_next_step_length(
398  const FunctionValueT & f_t, const FunctionValueT & f_l, const FunctionValueT & f_u)
399 {
400  if (std::isnan(f_t.argument) || std::isnan(f_l.argument) || std::isnan(f_u.argument)) {
401  throw std::runtime_error("Got nan values in the step computation function.");
402  }
403  constexpr auto kValueEps = 0.00001;
404  constexpr auto kStepEps = 0.00001F;
405  // A lambda to calculate the minimizer of the cubic that interpolates f_a, f_a_derivative, f_b and
406  // f_b_derivative on [a, b]. Equation 2.4.52 [Sun, Yuan 2006]
407  const auto find_cubic_minimizer = [kStepEps](const auto & f_a, const auto & f_b) -> StepT {
408  if (comp::approx_eq(f_a.argument, f_b.argument, kStepEps, kStepEps)) {
409  return f_a.argument;
410  }
411  const auto z = 3.0F * (f_a.value - f_b.value) /
412  (f_b.argument - f_a.argument) + f_a.derivative + f_b.derivative;
413  const auto w = std::sqrt(z * z - f_a.derivative * f_b.derivative);
414  // Equation 2.4.56 [Sun, Yuan 2006]
415  return f_b.argument - (f_b.argument - f_a.argument) * (f_b.derivative + w - z) /
416  (f_b.derivative - f_a.derivative + 2.0F * w);
417  };
418 
419  // A lambda to calculate the minimizer of the quadratic that interpolates f_a, f_b and f'_a
420  const auto find_a_q = [kStepEps](
421  const FunctionValueT & f_a, const FunctionValueT & f_b) -> StepT {
422  if (comp::approx_eq(f_a.argument, f_b.argument, kStepEps, kStepEps)) {
423  return f_a.argument;
424  }
425  return f_a.argument + 0.5F *
426  (f_b.argument - f_a.argument) * (f_b.argument - f_a.argument) * f_a.derivative /
427  (f_a.value - f_b.value + (f_b.argument - f_a.argument) * f_a.derivative);
428  };
429 
430  // A lambda to calculate the minimizer of the quadratic that interpolates f'_a, and f'_b
431  const auto find_a_s = [kStepEps](
432  const FunctionValueT & f_a, const FunctionValueT & f_b) -> StepT {
433  if (comp::approx_eq(f_a.argument, f_b.argument, kStepEps, kStepEps)) {
434  return f_a.argument;
435  }
436  return f_a.argument +
437  (f_b.argument - f_a.argument) * f_a.derivative / (f_a.derivative - f_b.derivative);
438  };
439 
440  // We cover here all the cases presented in the More-Thuente paper in section 4.
441  if (f_t.value > f_l.value) { // Case 1 from section 4.
442  const auto a_c = find_cubic_minimizer(f_l, f_t);
443  const auto a_q = find_a_q(f_l, f_t);
444  if (std::fabs(a_c - f_l.argument) < std::fabs(a_q - f_l.argument)) {
445  return a_c;
446  } else {
447  return 0.5F * (a_q + a_c);
448  }
449  } else if (f_t.derivative * f_l.derivative < 0) { // Case 2 from section 4.
450  const auto a_c = find_cubic_minimizer(f_l, f_t);
451  const auto a_s = find_a_s(f_l, f_t);
452  if (std::fabs(a_c - f_t.argument) >= std::fabs(a_s - f_t.argument)) {
453  return a_c;
454  } else {
455  return a_s;
456  }
457  } else if (comp::abs_lte(std::abs(f_t.derivative), std::abs(f_l.derivative), kValueEps)) {
458  // Case 3 from section 4.
459  const auto a_c = find_cubic_minimizer(f_l, f_t);
460  const auto a_s = find_a_s(f_l, f_t);
461  if (std::fabs(a_c - f_t.argument) < std::fabs(a_s - f_t.argument)) {
462  return std::min(
463  f_t.argument + detail::kDelta * (f_u.argument - f_t.argument),
464  static_cast<StepT>(a_c));
465  } else {
466  return std::max(
467  f_t.argument + detail::kDelta * (f_u.argument - f_t.argument),
468  static_cast<StepT>(a_s));
469  }
470  } else { // Case 4 from section 4.
471  return find_cubic_minimizer(f_t, f_u);
472  }
473 }
474 
475 template<typename FunctionValueT>
476 MoreThuenteLineSearch::Interval MoreThuenteLineSearch::update_interval(
477  const FunctionValueT & f_t, const FunctionValueT & f_l, const FunctionValueT & f_u)
478 {
479  // Following either "Updating Algorithm" or "Modifier Updating Algorithm" depending on the
480  // provided function f (can be psi or phi).
481  if (f_t.value > f_l.value) {
482  return {f_l.argument, f_t.argument}; // case a
483  } else if (f_t.derivative * (f_t.argument - f_l.argument) < 0) {
484  return {f_t.argument, f_u.argument}; // case b
485  } else if (f_t.derivative * (f_t.argument - f_l.argument) > 0) {
486  return {f_t.argument, f_l.argument}; // case c
487  }
488  // Converged to a point.
489  return {f_t.argument, f_t.argument};
490 }
491 
492 } // namespace optimization
493 } // namespace common
494 } // namespace autoware
495 
496 
497 #endif // OPTIMIZATION__LINE_SEARCH__MORE_THUENTE_LINE_SEARCH_HPP_
Definition: common/optimization/include/optimization/utils.hpp:38
OptimizationDirection
An enum that defines the direction of optimization.
Definition: more_thuente_line_search.hpp:100
Base class (CRTP) to mange the step length during optimization.
Definition: line_search.hpp:34
float float32_t
Definition: types.hpp:36
constexpr common::types::float32_t kDelta
This value is used in More-Thuente paper without explanation (in the paper: Section 4...
Definition: more_thuente_line_search.hpp:78
bool abs_lte(const T &a, const T &b, const T &eps)
Check for approximate less than or equal in absolute terms.
Definition: float_comparisons.hpp:69
w
Definition: catr_diff.py:22
This class describes a More-Thuente line search as presented in the paper "Line Search Algorithms wit...
Definition: more_thuente_line_search.hpp:94
Definition: bool_comparisons.hpp:32
bool approx_eq(const T &a, const T &b, const T &abs_eps, const T &rel_eps)
Check for approximate equality in absolute and relative terms.
Definition: float_comparisons.hpp:139
DomainValueT compute_next_step_(const DomainValueT &x0, const DomainValueT &initial_step, OptimizationProblemT &optimization_problem)
Calculates the next step.
Definition: more_thuente_line_search.hpp:204
A utility struct that holds the argument, value and derivative of a function.
Definition: more_thuente_line_search.hpp:300
MoreThuenteLineSearch(const StepT max_step, const StepT min_step, const OptimizationDirection optimization_direction=OptimizationDirection::kMinimization, const StepT mu=1.e-4F, const StepT eta=0.1F, const std::int32_t max_iterations=10)
Constructs a new instance.
Definition: more_thuente_line_search.hpp:118
This file defines the lanelet2_map_provider_node class.
Definition: quick_sort.hpp:24