1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
use super::{Bracket, Stats, UNINITIALIZED};
use crate::StrError;
/// Implements algorithms for bracketing a local minimum of f(x)
#[derive(Clone, Copy, Debug)]
pub struct MinBracketing {
/// Max number of iterations
///
/// ```text
/// n_iteration_max ≥ 2
/// ```
///
/// e.g., 100
pub n_iteration_max: usize,
/// Initial step
///
/// e.g., 1e-2
pub initial_step: f64,
/// Step expansion factor
///
/// e.g., 2.0
pub expansion_factor: f64,
}
impl MinBracketing {
/// Allocates a new instance with default parameters
pub fn new() -> Self {
MinBracketing {
n_iteration_max: 100,
initial_step: 1e-2,
expansion_factor: 2.0,
}
}
/// Validates the parameters
fn validate_params(&self) -> Result<(), StrError> {
if self.n_iteration_max < 2 {
return Err("n_iteration_max must be ≥ 2");
}
Ok(())
}
/// Employs a basic algorithm to try to bracket the minimum of f(x)
///
/// **Note:** This function is suitable for *unimodal functions*---it may fail otherwise.
/// The code is based on the one presented in Chapter 3 (page 36) of the Reference.
///
/// Searches (iteratively) for `a`, `b` and `xo` such that:
///
/// ```text
/// f(xo) < f(a) and f(xo) < f(b)
///
/// with a < xo < b
/// ```
///
/// Thus, `f(xo)` is the minimum of `f(x)` in the `[a, b]` interval.
///
/// # Input
///
/// * `x_guess` -- a starting guess
/// * `args` -- extra arguments for the callback function
/// * `f` -- is the callback function implementing `f(x)` as `f(x, args)`; it returns `f @ x` or it may return an error.
///
/// # Output
///
/// Returns `(bracket, stats)` where:
///
/// * `bracket` -- holds the results
/// * `stats` -- holds statistics about the computations
///
/// # Reference
///
/// * Kochenderfer MJ and Wheeler TA (2019) Algorithms for Optimization, The MIT Press, 512p
///
/// # Examples
///
/// 
///
/// ```
/// use russell_lab::*;
///
/// fn main() -> Result<(), StrError> {
/// // "4: f(x) = (x - 1)² + 5 sin(x)"
/// let f = |x: f64, _: &mut NoArgs| Ok(f64::powi(x - 1.0, 2) + 5.0 * f64::sin(x));
/// let args = &mut 0;
///
/// // bracketing
/// let bracketing = MinBracketing::new();
/// let (bracket, stats) = bracketing.basic(-3.0, args, f)?;
/// println!("\n(a, b) = ({}, {})", bracket.a, bracket.b);
/// println!("\n{}", stats);
/// Ok(())
/// }
/// ```
///
/// The output looks like:
///
/// ```text
/// (a, b) = (-1.7200000000000002, 2.12)
///
/// Number of function evaluations = 11
/// Number of Jacobian evaluations = 0
/// Number of iterations = 9
/// Error estimate = unavailable
/// Total computation time = 7.293µs
/// ```
pub fn basic<F, A>(&self, x_guess: f64, args: &mut A, mut f: F) -> Result<(Bracket, Stats), StrError>
where
F: FnMut(f64, &mut A) -> Result<f64, StrError>,
{
// validate parameters
self.validate_params()?;
// allocate stats struct
let mut stats = Stats::new();
// initialization
let mut step = self.initial_step;
let (mut a, mut xo) = (x_guess, x_guess + step);
let (mut fa, mut fxo) = (f(a, args)?, f(xo, args)?);
stats.n_function += 2;
// swap values (make sure to go "downhill")
if fxo > fa {
swap(&mut a, &mut xo);
swap(&mut fa, &mut fxo);
step = -step;
}
// iterations
let mut converged = false;
let mut b = UNINITIALIZED;
let mut fb = UNINITIALIZED;
for _ in 0..self.n_iteration_max {
stats.n_iterations += 1;
stats.n_function += 1;
b = xo + step;
fb = f(b, args)?;
if fb > fxo {
converged = true;
break;
}
a = xo;
fa = fxo;
xo = b;
fxo = fb;
step *= self.expansion_factor;
}
// check
if !converged {
return Err("try_bracket_min failed to converge");
}
// done
if a > b {
swap(&mut a, &mut b);
swap(&mut fa, &mut fb);
}
stats.stop_sw_total();
Ok((Bracket { a, b, fa, fb, xo, fxo }, stats))
}
}
/// Swaps two numbers
#[inline]
pub(super) fn swap(a: &mut f64, b: &mut f64) {
let a_copy = a.clone();
*a = *b;
*b = a_copy;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#[cfg(test)]
mod tests {
use super::{swap, Bracket, MinBracketing};
use crate::algo::testing::get_test_functions;
use crate::algo::NoArgs;
use crate::approx_eq;
#[test]
fn swap_works() {
let mut a = 12.34;
let mut b = 56.78;
swap(&mut a, &mut b);
assert_eq!(a, 56.78);
assert_eq!(b, 12.34);
}
#[test]
fn validate_params_works() {
let mut solver = MinBracketing::new();
solver.n_iteration_max = 0;
assert_eq!(solver.validate_params().err(), Some("n_iteration_max must be ≥ 2"));
}
#[test]
fn basic_captures_errors_1() {
let f = |x, _: &mut NoArgs| Ok(x * x - 1.0);
let args = &mut 0;
assert_eq!(f(1.0, args).unwrap(), 0.0);
let mut solver = MinBracketing::new();
solver.n_iteration_max = 0;
assert_eq!(solver.basic(0.0, args, f).err(), Some("n_iteration_max must be ≥ 2"));
}
#[test]
fn basic_captures_errors_2() {
struct Args {
count: usize,
target: usize,
}
let f = |x, args: &mut Args| {
let res = if args.count == args.target {
Err("stop")
} else {
Ok(x * x - 1.0)
};
args.count += 1;
res
};
let args = &mut Args { count: 0, target: 0 };
let solver = MinBracketing::new();
// first function call
assert_eq!(solver.basic(0.0, args, f).err(), Some("stop"));
// second function call
args.count = 0;
args.target = 1;
assert_eq!(solver.basic(0.0, args, f).err(), Some("stop"));
// third function call
args.count = 0;
args.target = 2;
assert_eq!(solver.basic(0.0, args, f).err(), Some("stop"));
}
fn check_consistency(bracket: &Bracket) {
assert!(bracket.a < bracket.xo);
assert!(bracket.xo < bracket.b);
assert!(bracket.fa > bracket.fxo);
assert!(bracket.fb > bracket.fxo);
}
#[test]
fn basic_works_1() {
let args = &mut 0;
let solver = MinBracketing::new();
for (i, test) in get_test_functions().iter().enumerate() {
if test.min1.is_none() {
continue;
}
println!("\n===================================================================");
println!("\n{}", test.name);
let x_guess = if i == 4 {
0.15
} else {
if i % 2 == 0 {
-0.1
} else {
0.1
}
};
let (bracket, stats) = solver.basic(x_guess, args, test.f).unwrap();
println!("\n{}", bracket);
println!("\n{}", stats);
check_consistency(&bracket);
approx_eq((test.f)(bracket.a, args).unwrap(), bracket.fa, 1e-15);
approx_eq((test.f)(bracket.b, args).unwrap(), bracket.fb, 1e-15);
approx_eq((test.f)(bracket.xo, args).unwrap(), bracket.fxo, 1e-15);
}
println!("\n===================================================================\n");
}
#[test]
fn basic_fails_on_non_converged() {
let f = |x, _: &mut NoArgs| Ok(f64::powi(x - 1.0, 2) + 5.0 * f64::sin(x));
let args = &mut 0;
assert!(f(1.0, args).unwrap() > 0.0);
let mut solver = MinBracketing::new();
solver.n_iteration_max = 2;
assert_eq!(
solver.basic(0.0, args, f).err(),
Some("try_bracket_min failed to converge")
);
}
}