Developer documentation
Version 3.0.3-105-gd3941f44
golden_section_search.h
Go to the documentation of this file.
1/* Copyright (c) 2008-2022 the MRtrix3 contributors.
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
6 *
7 * Covered Software is provided under this License on an "as is"
8 * basis, without warranty of any kind, either expressed, implied, or
9 * statutory, including, without limitation, warranties that the
10 * Covered Software is free of defects, merchantable, fit for a
11 * particular purpose or non-infringing.
12 * See the Mozilla Public License v. 2.0 for more details.
13 *
14 * For more details, see http://www.mrtrix.org/.
15 */
16
17#ifndef __math_golden_section_search_h__
18#define __math_golden_section_search_h__
19
20#include <cmath>
21
22#include "progressbar.h"
23#include "memory.h"
24
25namespace MR
26{
27 namespace Math
28 {
33
49 template <class FunctionType, typename ValueType>
50 ValueType golden_section_search (FunctionType& function,
51 const std::string& message,
52 ValueType min_bound,
53 ValueType init_estimate,
54 ValueType max_bound,
55 ValueType tolerance = 0.01) {
56
57 std::unique_ptr<ProgressBar> progress (message.size() ? new ProgressBar (message) : nullptr);
58
59 const ValueType g1 = 0.61803399, g2 = 1 - g1;
60 ValueType x0 = min_bound, x1, x2, x3 = max_bound;
61
62 if (abs(max_bound - init_estimate) > abs(init_estimate - min_bound)) {
63 x1 = init_estimate;
64 x2 = init_estimate + g2 * (max_bound - init_estimate);
65 } else {
66 x2 = init_estimate;
67 x1 = init_estimate - g2 * (init_estimate - min_bound);
68 }
69
70 ValueType f1 = function(x1);
71 ValueType f2 = function(x2);
72
73 while (tolerance * (abs(x1) + abs(x2)) < abs(x3 - x0)) {
74 if (f2 < f1) {
75 x0 = x1;
76 x1 = x2;
77 x2 = g1 * x1 + g2 * x3;
78 f1 = f2, f2 = function(x2);
79 } else {
80 x3 = x2;
81 x2 = x1;
82 x1 = g1 * x2 + g2 * x0;
83 f2 = f1, f1 = function(x1);
84 }
85 if (progress)
86 ++*progress;
87 }
88 return f1 < f2 ? x1 : x2;
89 }
90 }
91 }
92
93#endif
94
implements a progress meter to provide feedback to the user
Definition: progressbar.h:58
ValueType golden_section_search(FunctionType &function, const std::string &message, ValueType min_bound, ValueType init_estimate, ValueType max_bound, ValueType tolerance=0.01)
Computes the minimum of a 1D function using a golden section search.
Definition: base.h:24
constexpr std::enable_if< std::is_arithmetic< X >::value &&std::is_unsigned< X >::value, X >::type abs(X x)
Definition: types.h:297