scirs2-optimize 0.4.2

Optimization module for SciRS2 (scirs2-optimize)
Documentation
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! BOBYQA: Bound Optimization BY Quadratic Approximation
//!
//! BOBYQA is a derivative-free optimization algorithm for problems with bound
//! constraints. It maintains a quadratic model of the objective function
//! interpolated through a set of points, and uses a trust-region framework
//! to ensure progress.
//!
//! This implementation provides the key structure and trust-region quadratic
//! approximation strategy described by Powell (2009).
//!
//! # References
//! - Powell, M.J.D. (2009). "The BOBYQA algorithm for bound constrained optimization
//!   without derivatives." Technical Report DAMTP 2009/NA06, Cambridge University.

use super::{clip, DfOptResult, DerivativeFreeOptimizer};
use crate::error::{OptimizeError, OptimizeResult};
use scirs2_core::ndarray::Array1;

/// Options for the BOBYQA algorithm
#[derive(Debug, Clone)]
pub struct BOBYQAOptions {
    /// Lower bounds (None = -inf for each variable)
    pub lower: Option<Vec<f64>>,
    /// Upper bounds (None = +inf for each variable)
    pub upper: Option<Vec<f64>>,
    /// Initial trust region radius
    pub rho_begin: f64,
    /// Final trust region radius (convergence)
    pub rho_end: f64,
    /// Maximum number of function evaluations
    pub max_fev: usize,
    /// Maximum number of iterations
    pub max_iter: usize,
    /// Number of interpolation points (npt). Must satisfy n+2 <= npt <= (n+1)(n+2)/2.
    /// Default: 2*n+1
    pub npt: Option<usize>,
    /// Absolute tolerance for function value change
    pub f_tol: f64,
    /// Absolute tolerance for step size
    pub x_tol: f64,
}

impl Default for BOBYQAOptions {
    fn default() -> Self {
        BOBYQAOptions {
            lower: None,
            upper: None,
            rho_begin: 1.0,
            rho_end: 1e-6,
            max_fev: 50000,
            max_iter: 10000,
            npt: None,
            f_tol: 1e-10,
            x_tol: 1e-8,
        }
    }
}

/// BOBYQA solver
pub struct BOBYQASolver {
    pub options: BOBYQAOptions,
}

impl BOBYQASolver {
    /// Create with default options
    pub fn new() -> Self {
        BOBYQASolver {
            options: BOBYQAOptions::default(),
        }
    }

    /// Create with custom options
    pub fn with_options(options: BOBYQAOptions) -> Self {
        BOBYQASolver { options }
    }

    /// Get effective lower/upper bounds for dimension n
    fn get_bounds(&self, n: usize) -> (Vec<f64>, Vec<f64>) {
        let lo = match &self.options.lower {
            Some(l) => l.clone(),
            None => vec![f64::NEG_INFINITY; n],
        };
        let hi = match &self.options.upper {
            Some(u) => u.clone(),
            None => vec![f64::INFINITY; n],
        };
        (lo, hi)
    }

    /// Project point onto box [lo, hi]
    fn project(&self, x: &[f64], lo: &[f64], hi: &[f64]) -> Vec<f64> {
        x.iter()
            .zip(lo.iter().zip(hi.iter()))
            .map(|(&xi, (&l, &h))| clip(xi, l, h))
            .collect()
    }

    /// Compute quadratic model gradient at current point via finite differences
    fn quadratic_gradient<F: Fn(&[f64]) -> f64>(
        &self,
        func: &F,
        x: &[f64],
        rho: f64,
        lo: &[f64],
        hi: &[f64],
        nfev: &mut usize,
    ) -> Vec<f64> {
        let h = rho * 0.01;
        let n = x.len();
        let mut g = vec![0.0; n];
        let fx = {
            *nfev += 1;
            func(x)
        };
        for i in 0..n {
            let mut xp = x.to_vec();
            xp[i] = clip(x[i] + h, lo[i], hi[i]);
            let actual_h = xp[i] - x[i];
            if actual_h.abs() > 1e-15 {
                *nfev += 1;
                g[i] = (func(&xp) - fx) / actual_h;
            } else {
                let mut xm = x.to_vec();
                xm[i] = clip(x[i] - h, lo[i], hi[i]);
                let actual_hm = x[i] - xm[i];
                if actual_hm.abs() > 1e-15 {
                    *nfev += 1;
                    g[i] = (fx - func(&xm)) / actual_hm;
                }
            }
        }
        g
    }

    /// Solve the trust-region subproblem subject to bounds.
    /// Minimizes: g^T d + 0.5 d^T H d   s.t. ||d|| <= rho, lo <= x+d <= hi
    /// Uses a truncated steepest descent / conjugate gradient approach.
    fn trust_region_step(
        &self,
        g: &[f64],
        hess_diag: &[f64],
        x: &[f64],
        rho: f64,
        lo: &[f64],
        hi: &[f64],
    ) -> Vec<f64> {
        let n = x.len();
        // Cauchy point: steepest descent clipped to trust region and bounds
        let gn = g.iter().map(|v| v * v).sum::<f64>().sqrt();
        if gn < 1e-15 {
            return vec![0.0; n];
        }

        // Compute gT H g for scaling
        let gt_hg: f64 = g
            .iter()
            .zip(hess_diag.iter())
            .map(|(&gi, &hi_v)| gi * hi_v.max(0.0) * gi)
            .sum();

        let tau = if gt_hg > 0.0 {
            (gn * gn / gt_hg).min(rho / gn)
        } else {
            rho / gn
        };

        let d: Vec<f64> = g.iter().map(|&gi| -tau * gi).collect();

        // Scale to fit trust region
        let dn = d.iter().map(|v| v * v).sum::<f64>().sqrt();
        let scale = if dn > rho { rho / dn } else { 1.0 };
        let d: Vec<f64> = d.iter().map(|v| v * scale).collect();

        // Clip to bounds
        x.iter()
            .zip(d.iter())
            .zip(lo.iter().zip(hi.iter()))
            .map(|((&xi, &di), (&l, &h))| clip(xi + di, l, h) - xi)
            .collect()
    }

    /// Estimate diagonal Hessian via finite differences
    fn hessian_diagonal<F: Fn(&[f64]) -> f64>(
        &self,
        func: &F,
        x: &[f64],
        fx: f64,
        h: f64,
        lo: &[f64],
        hi: &[f64],
        nfev: &mut usize,
    ) -> Vec<f64> {
        let n = x.len();
        let mut hd = vec![0.0; n];
        for i in 0..n {
            let mut xp = x.to_vec();
            let mut xm = x.to_vec();
            xp[i] = clip(x[i] + h, lo[i], hi[i]);
            xm[i] = clip(x[i] - h, lo[i], hi[i]);
            let hp = xp[i] - x[i];
            let hm = x[i] - xm[i];
            if hp.abs() > 1e-15 && hm.abs() > 1e-15 {
                let fp = {
                    *nfev += 1;
                    func(&xp)
                };
                let fm = {
                    *nfev += 1;
                    func(&xm)
                };
                hd[i] = (fp - 2.0 * fx + fm) / (hp * hm);
            }
        }
        hd
    }
}

impl Default for BOBYQASolver {
    fn default() -> Self {
        BOBYQASolver::new()
    }
}

impl DerivativeFreeOptimizer for BOBYQASolver {
    fn minimize<F>(&self, func: F, x0: &[f64]) -> OptimizeResult<DfOptResult>
    where
        F: Fn(&[f64]) -> f64,
    {
        let n = x0.len();
        if n == 0 {
            return Err(OptimizeError::InvalidInput(
                "x0 must be non-empty".to_string(),
            ));
        }

        let (lo, hi) = self.get_bounds(n);

        // Validate bounds
        for i in 0..n {
            if lo[i] > hi[i] {
                return Err(OptimizeError::InvalidInput(format!(
                    "lower[{}] > upper[{}]",
                    i, i
                )));
            }
        }

        let mut x = self.project(x0, &lo, &hi);
        let mut rho = self.options.rho_begin;
        let rho_end = self.options.rho_end;

        let mut nfev = 0usize;
        let mut nit = 0usize;

        let mut fx = {
            nfev += 1;
            func(&x)
        };

        // Main trust-region loop
        // We reduce rho geometrically when no progress is made
        let rho_factor = 0.5_f64;
        let max_rho_reductions = 100usize;
        let mut rho_reductions = 0usize;

        loop {
            if nit >= self.options.max_iter || nfev >= self.options.max_fev {
                break;
            }

            if rho < rho_end || rho_reductions >= max_rho_reductions {
                return Ok(DfOptResult {
                    x: Array1::from_vec(x),
                    fun: fx,
                    nfev,
                    nit,
                    success: rho < rho_end * 10.0,
                    message: if rho < rho_end * 10.0 {
                        "Converged: trust region radius below tolerance".to_string()
                    } else {
                        "Maximum trust region reductions reached".to_string()
                    },
                });
            }

            // Compute gradient
            let g = self.quadratic_gradient(&func, &x, rho, &lo, &hi, &mut nfev);

            // Compute diagonal Hessian
            let h_step = rho * 0.1;
            let hd = self.hessian_diagonal(&func, &x, fx, h_step, &lo, &hi, &mut nfev);

            // Solve trust-region subproblem
            let d = self.trust_region_step(&g, &hd, &x, rho, &lo, &hi);

            let step_norm = d.iter().map(|v| v * v).sum::<f64>().sqrt();
            if step_norm < 1e-15 {
                rho *= rho_factor;
                rho_reductions += 1;
                nit += 1;
                continue;
            }

            let xnew: Vec<f64> = x.iter().zip(d.iter()).map(|(&xi, &di)| xi + di).collect();
            let xnew = self.project(&xnew, &lo, &hi);
            nfev += 1;
            let fnew = func(&xnew);

            // Predicted reduction (linear model)
            let pred = -g.iter().zip(d.iter()).map(|(&gi, &di)| gi * di).sum::<f64>();

            // Actual reduction
            let actual = fx - fnew;

            // Accept/reject step
            let ratio = if pred.abs() > 1e-15 {
                actual / pred
            } else if actual > 0.0 {
                1.0
            } else {
                0.0
            };

            let f_change = (fnew - fx).abs();

            if ratio > 0.0 || fnew < fx {
                // Accept step
                x = xnew;
                fx = fnew;

                // Expand trust region on good progress
                if ratio > 0.75 {
                    rho = (rho * 2.0).min(self.options.rho_begin);
                    rho_reductions = rho_reductions.saturating_sub(1);
                }
            } else {
                // Reject step, shrink trust region
                rho *= rho_factor;
                rho_reductions += 1;
            }

            // Check function value convergence
            if f_change < self.options.f_tol && step_norm < self.options.x_tol {
                return Ok(DfOptResult {
                    x: Array1::from_vec(x),
                    fun: fx,
                    nfev,
                    nit,
                    success: true,
                    message: "Converged: function/step tolerance".to_string(),
                });
            }

            nit += 1;
        }

        Ok(DfOptResult {
            x: Array1::from_vec(x),
            fun: fx,
            nfev,
            nit,
            success: false,
            message: "Maximum iterations or function evaluations reached".to_string(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_abs_diff_eq;

    #[test]
    fn test_bobyqa_unconstrained_quadratic() {
        let solver = BOBYQASolver::new();
        let result = solver
            .minimize(
                |x: &[f64]| (x[0] - 2.0).powi(2) + (x[1] - 3.0).powi(2),
                &[0.0, 0.0],
            )
            .expect("optimization failed");
        assert_abs_diff_eq!(result.x[0], 2.0, epsilon = 1e-2);
        assert_abs_diff_eq!(result.x[1], 3.0, epsilon = 1e-2);
        assert_abs_diff_eq!(result.fun, 0.0, epsilon = 1e-3);
    }

    #[test]
    fn test_bobyqa_bounded_simple() {
        let opts = BOBYQAOptions {
            lower: Some(vec![1.0, 1.0]),
            upper: Some(vec![5.0, 5.0]),
            ..Default::default()
        };
        let solver = BOBYQASolver::with_options(opts);
        // Minimum at (-3, -4) but bounded to [1,5]^2, so bound-constrained min is (1,1)
        let result = solver
            .minimize(
                |x: &[f64]| (x[0] + 3.0).powi(2) + (x[1] + 4.0).powi(2),
                &[2.0, 2.0],
            )
            .expect("optimization failed");
        assert_abs_diff_eq!(result.x[0], 1.0, epsilon = 1e-2);
        assert_abs_diff_eq!(result.x[1], 1.0, epsilon = 1e-2);
    }

    #[test]
    fn test_bobyqa_interior_minimum() {
        // Interior minimum within bounds
        let opts = BOBYQAOptions {
            lower: Some(vec![-10.0, -10.0]),
            upper: Some(vec![10.0, 10.0]),
            rho_begin: 1.0,
            rho_end: 1e-7,
            max_fev: 100000,
            ..Default::default()
        };
        let solver = BOBYQASolver::with_options(opts);
        let result = solver
            .minimize(
                |x: &[f64]| (x[0] - 1.5).powi(2) + (x[1] + 0.5).powi(2),
                &[5.0, 5.0],
            )
            .expect("optimization failed");
        assert_abs_diff_eq!(result.x[0], 1.5, epsilon = 1e-2);
        assert_abs_diff_eq!(result.x[1], -0.5, epsilon = 1e-2);
    }

    #[test]
    fn test_bobyqa_1d_bounded() {
        let opts = BOBYQAOptions {
            lower: Some(vec![0.0]),
            upper: Some(vec![4.0]),
            rho_begin: 0.5,
            rho_end: 1e-8,
            max_fev: 10000,
            ..Default::default()
        };
        let solver = BOBYQASolver::with_options(opts);
        // Minimum at x=-2, bounded minimum at x=0
        let result = solver
            .minimize(|x: &[f64]| (x[0] + 2.0).powi(2), &[2.0])
            .expect("optimization failed");
        assert_abs_diff_eq!(result.x[0], 0.0, epsilon = 1e-2);
    }

    #[test]
    fn test_bobyqa_initial_point_on_bound() {
        let opts = BOBYQAOptions {
            lower: Some(vec![0.0, 0.0]),
            upper: Some(vec![3.0, 3.0]),
            ..Default::default()
        };
        let solver = BOBYQASolver::with_options(opts);
        // Start at boundary
        let result = solver
            .minimize(
                |x: &[f64]| (x[0] - 1.0).powi(2) + (x[1] - 1.0).powi(2),
                &[0.0, 0.0],
            )
            .expect("optimization failed");
        // Should find interior minimum at (1, 1)
        assert_abs_diff_eq!(result.x[0], 1.0, epsilon = 1e-2);
        assert_abs_diff_eq!(result.x[1], 1.0, epsilon = 1e-2);
    }
}