Skip to main content

lib_jsl_optimization/
cobyqa.rs

1//! COBYQA: constrained optimisation by quadratic approximations (Ragonneau, 2022; SciPy's
2//! `minimize(method='COBYQA')`), a derivative-free trust-region method for problems with bounds and
3//! nonlinear inequality and equality constraints.
4//!
5//! The objective and each constraint get a quadratic model that interpolates their values at
6//! `2n + 1` points (more with [`CobyqaOptions::npt`]), the one of least Frobenius norm of the change
7//! of its Hessian from the previous model. Each iteration takes a Byrd–Omojokun step from the best
8//! point: a *normal* step that reduces the violation of the linearised constraints, and a
9//! *tangential* step that reduces the model of the Lagrangian without undoing that, both within the
10//! trust region and the bounds; the step is judged on an ℓ₂ merit function whose penalty parameter
11//! rises with the Lagrange multiplier estimates. Steps that do not pay are followed by moves that
12//! restore the geometry of the interpolation set, and the resolution `ρ` of the trust region falls
13//! from `rhobeg` to `rhoend`.
14//!
15//! See the book entry [Constrained optimisation](https://jwkunz.github.io/lib_jsl/book/optimization/constrained.html#cobyqa).
16
17#![allow(clippy::needless_range_loop)]
18
19use crate::constrained::{ConstrainedProblem, bound_constrained_qp};
20use lib_jsl_core::ErrorsJSL;
21use lib_jsl_linalg::{Eigh, UPLO};
22use ndarray::Array2;
23use std::cell::RefCell;
24
25const TINY: f64 = f64::MIN_POSITIVE;
26const EPS: f64 = f64::EPSILON;
27/// SciPy's `BARRIER`: function values are clipped to ±2¹⁰⁰ and NaN becomes +2¹⁰⁰.
28const BARRIER: f64 = 1.267_650_600_228_229_4e30;
29
30type V = Vec<f64>;
31type M = Vec<Vec<f64>>;
32
33// ---------------------------------------------------------------------------------------------
34// Options and result
35// ---------------------------------------------------------------------------------------------
36
37/// Options for [`cobyqa`], with SciPy's defaults.
38#[derive(Clone, Copy, Debug)]
39#[non_exhaustive]
40pub struct CobyqaOptions {
41    /// The initial trust-region radius.
42    pub rhobeg: f64,
43    /// The final radius (the accuracy wanted).
44    pub rhoend: f64,
45    /// The largest number of evaluations of the problem (default `500 n`).
46    pub max_evaluations: Option<usize>,
47    /// The largest number of iterations (default `1000 n`).
48    pub max_iterations: Option<usize>,
49    /// The number of interpolation points, from `n + 1` to `(n + 1)(n + 2)/2` (default `2 n + 1`).
50    pub npt: Option<usize>,
51    /// The constraint violation accepted for a point to count as feasible (default `√ε`).
52    pub feasibility_tol: f64,
53    /// The run stops successfully at a feasible point with an objective at most this (default `−∞`).
54    pub target: f64,
55    /// Map the variables to the unit box `[−1, 1]ⁿ` first (SciPy's `scale`); needs finite bounds on every
56    /// variable and is ignored otherwise.
57    pub scale: bool,
58    /// The most non-dominated points kept in the filter that the result is chosen from (default: all).
59    pub filter_size: Option<usize>,
60    /// Keep the objective and violation at every evaluation (the last `history_size` of them) in the result.
61    pub store_history: bool,
62    pub history_size: Option<usize>,
63    /// The constants of the method (SciPy's keyword arguments); the defaults are SciPy's.
64    pub constants: CobyqaConstants,
65}
66
67/// The constants of the method, with SciPy's defaults; [`CobyqaConstants::validate`] checks the ranges and
68/// relations that SciPy enforces.
69#[derive(Clone, Copy, Debug, PartialEq)]
70#[non_exhaustive]
71pub struct CobyqaConstants {
72    pub decrease_radius_factor: f64,
73    pub increase_radius_factor: f64,
74    pub increase_radius_threshold: f64,
75    pub decrease_radius_threshold: f64,
76    pub decrease_resolution_factor: f64,
77    pub large_resolution_threshold: f64,
78    pub moderate_resolution_threshold: f64,
79    pub low_ratio: f64,
80    pub high_ratio: f64,
81    pub very_low_ratio: f64,
82    pub penalty_increase_threshold: f64,
83    pub penalty_increase_factor: f64,
84    pub short_step_threshold: f64,
85    pub low_radius_factor: f64,
86    pub byrd_omojokun_factor: f64,
87    pub threshold_ratio_constraints: f64,
88    pub large_shift_factor: f64,
89    pub large_gradient_factor: f64,
90    pub resolution_factor: f64,
91    pub improve_tcg: bool,
92}
93
94impl Default for CobyqaConstants {
95    fn default() -> Self {
96        CobyqaConstants {
97            decrease_radius_factor: 0.5,
98            increase_radius_factor: std::f64::consts::SQRT_2,
99            increase_radius_threshold: 2.0,
100            decrease_radius_threshold: 1.4,
101            decrease_resolution_factor: 0.1,
102            large_resolution_threshold: 250.0,
103            moderate_resolution_threshold: 16.0,
104            low_ratio: 0.1,
105            high_ratio: 0.7,
106            very_low_ratio: 0.01,
107            penalty_increase_threshold: 1.5,
108            penalty_increase_factor: 2.0,
109            short_step_threshold: 0.5,
110            low_radius_factor: 0.1,
111            byrd_omojokun_factor: 0.8,
112            threshold_ratio_constraints: 2.0,
113            large_shift_factor: 10.0,
114            large_gradient_factor: 10.0,
115            resolution_factor: 2.0,
116            improve_tcg: true,
117        }
118    }
119}
120
121impl CobyqaConstants {
122    /// The checks of SciPy's `_set_default_constants`.
123    pub fn validate(&self) -> Result<(), ErrorsJSL> {
124        let open01 = |v: f64| v > 0.0 && v < 1.0;
125        let ok = open01(self.decrease_radius_factor)
126            && self.increase_radius_threshold > 1.0
127            && self.increase_radius_factor > 1.0
128            && self.decrease_radius_threshold > 1.0
129            && self.decrease_radius_threshold < self.increase_radius_factor
130            && open01(self.decrease_resolution_factor)
131            && self.large_resolution_threshold > 1.0
132            && self.moderate_resolution_threshold > 1.0
133            && self.moderate_resolution_threshold <= self.large_resolution_threshold
134            && open01(self.low_ratio)
135            && open01(self.high_ratio)
136            && self.low_ratio <= self.high_ratio
137            && open01(self.very_low_ratio)
138            && self.penalty_increase_threshold >= 1.0
139            && self.penalty_increase_factor > 1.0
140            && self.penalty_increase_factor >= self.penalty_increase_threshold
141            && open01(self.short_step_threshold)
142            && open01(self.low_radius_factor)
143            && open01(self.byrd_omojokun_factor)
144            && self.threshold_ratio_constraints > 1.0
145            && self.large_shift_factor >= 0.0
146            && self.large_gradient_factor > 1.0
147            && self.resolution_factor > 1.0;
148        if ok { Ok(()) } else { Err(ErrorsJSL::InvalidInputRange("the constants of COBYQA are out of range (see CobyqaConstants::validate)")) }
149    }
150}
151
152/// Linear constraints `a_ub x ≤ b_ub` and `a_eq x = b_eq` (rows of `a_ub`, `a_eq`), kept exact by
153/// [`cobyqa_with`] instead of being modelled.
154#[derive(Clone, Debug, Default)]
155pub struct LinearConstraints {
156    pub a_ub: Vec<Vec<f64>>,
157    pub b_ub: Vec<f64>,
158    pub a_eq: Vec<Vec<f64>>,
159    pub b_eq: Vec<f64>,
160}
161
162impl Default for CobyqaOptions {
163    fn default() -> Self {
164        CobyqaOptions { rhobeg: 1.0, rhoend: 1e-6, max_evaluations: None, max_iterations: None, npt: None, feasibility_tol: EPS.sqrt(), target: f64::NEG_INFINITY, scale: false, filter_size: None, store_history: false, history_size: None, constants: CobyqaConstants::default() }
165    }
166}
167
168impl CobyqaOptions {
169    /// The defaults with the given initial and final radii.
170    pub fn with_radii(rhobeg: f64, rhoend: f64) -> Self {
171        CobyqaOptions { rhobeg, rhoend, ..Default::default() }
172    }
173
174    /// Limits on the evaluations and iterations.
175    pub fn with_limits(mut self, max_evaluations: usize, max_iterations: usize) -> Self {
176        self.max_evaluations = Some(max_evaluations);
177        self.max_iterations = Some(max_iterations);
178        self
179    }
180
181    /// The number of interpolation points.
182    pub fn with_npt(mut self, npt: usize) -> Self {
183        self.npt = Some(npt);
184        self
185    }
186
187    /// Stop at a feasible point with an objective at most `target`.
188    pub fn with_target(mut self, target: f64) -> Self {
189        self.target = target;
190        self
191    }
192
193    /// Scale the variables to the unit box (needs finite bounds).
194    pub fn with_scale(mut self, scale: bool) -> Self {
195        self.scale = scale;
196        self
197    }
198
199    /// Limit the filter that the result is chosen from.
200    pub fn with_filter_size(mut self, size: usize) -> Self {
201        self.filter_size = Some(size);
202        self
203    }
204
205    /// Keep the objective and violation of the last `size` evaluations in the result.
206    pub fn with_history(mut self, size: usize) -> Self {
207        self.store_history = true;
208        self.history_size = Some(size);
209        self
210    }
211
212    /// The constants of the method.
213    pub fn with_constants(mut self, constants: CobyqaConstants) -> Self {
214        self.constants = constants;
215        self
216    }
217}
218
219/// Why [`cobyqa`] stopped.
220#[derive(Clone, Copy, Debug, PartialEq, Eq)]
221pub enum CobyqaStatus {
222    /// The resolution reached `rhoend`.
223    RadiusReached,
224    /// The target objective value was reached at a feasible point.
225    TargetReached,
226    /// The callback asked to stop.
227    CallbackStop,
228    /// Every variable is fixed by the bounds.
229    AllFixed,
230    /// The evaluation limit was reached.
231    MaxEvaluations,
232    /// The iteration limit was reached.
233    MaxIterations,
234    /// The bounds are infeasible (`lower > upper`).
235    InfeasibleBounds,
236    /// A linear algebra failure (a non-finite interpolation system).
237    LinearAlgebra,
238}
239
240/// The result of [`cobyqa`].
241#[derive(Clone, Debug)]
242#[non_exhaustive]
243pub struct CobyqaResult {
244    /// The best point found: feasible if one was seen (the least objective), otherwise the least penalised merit.
245    pub x: Vec<f64>,
246    pub fun: f64,
247    /// The largest constraint violation at `x`.
248    pub maxcv: f64,
249    pub nfev: usize,
250    pub nit: usize,
251    pub success: bool,
252    pub status: CobyqaStatus,
253    /// The objective and violation at every evaluation (empty unless `store_history`).
254    pub fun_history: Vec<f64>,
255    pub maxcv_history: Vec<f64>,
256}
257
258enum Stop {
259    Target,
260    Callback,
261    MaxEval,
262    LinAlg,
263}
264
265// ---------------------------------------------------------------------------------------------
266// Small dense helpers
267// ---------------------------------------------------------------------------------------------
268
269fn dot(a: &[f64], b: &[f64]) -> f64 {
270    a.iter().zip(b).map(|(x, y)| x * y).sum()
271}
272
273fn norm(a: &[f64]) -> f64 {
274    dot(a, a).sqrt()
275}
276
277fn add(a: &[f64], b: &[f64]) -> V {
278    a.iter().zip(b).map(|(x, y)| x + y).collect()
279}
280
281fn sub(a: &[f64], b: &[f64]) -> V {
282    a.iter().zip(b).map(|(x, y)| x - y).collect()
283}
284
285fn scaled(a: &[f64], s: f64) -> V {
286    a.iter().map(|x| s * x).collect()
287}
288
289fn axpy(y: &mut [f64], s: f64, x: &[f64]) {
290    y.iter_mut().zip(x).for_each(|(a, b)| *a += s * b);
291}
292
293/// `A v` for `A` given by rows.
294fn matvec(a: &[V], v: &[f64]) -> V {
295    a.iter().map(|r| dot(r, v)).collect()
296}
297
298/// `Aᵀ w` for `A` given by rows (`n` columns).
299fn matvec_t(a: &[V], w: &[f64], n: usize) -> V {
300    let mut out = vec![0.0; n];
301    for (r, wi) in a.iter().zip(w) {
302        axpy(&mut out, *wi, r);
303    }
304    out
305}
306
307fn clip(x: &[f64], lo: &[f64], hi: &[f64]) -> V {
308    x.iter().zip(lo.iter().zip(hi)).map(|(v, (l, h))| v.max(*l).min(*h)).collect()
309}
310
311fn get_arrays_tol(arrays: &[&[f64]]) -> f64 {
312    let size = arrays.iter().map(|a| a.len()).max().unwrap_or(1).max(1) as f64;
313    let weight = arrays.iter().map(|a| a.iter().filter(|v| v.is_finite()).fold(1.0f64, |m, v| m.max(v.abs()))).fold(1.0f64, f64::max);
314    10.0 * EPS * size * weight
315}
316
317fn argmax_all(x: &[f64]) -> Vec<usize> {
318    let m = x.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
319    (0..x.len()).filter(|&i| x[i] >= m).collect()
320}
321
322fn argmin_all(x: &[f64]) -> Vec<usize> {
323    let m = x.iter().cloned().fold(f64::INFINITY, f64::min);
324    (0..x.len()).filter(|&i| x[i] <= m).collect()
325}
326
327fn argmin_first(x: &[f64]) -> usize {
328    let mut b = 0;
329    for i in 1..x.len() {
330        if x[i] < x[b] {
331            b = i;
332        }
333    }
334    b
335}
336
337/// The distance to the trust-region boundary along `sd` from `step`: the largest `α ≥ 0` with
338/// `‖step + α sd‖ ≤ delta`, or `None` when it is not determined (SciPy's `ZeroDivisionError`).
339fn alpha_tr(step: &[f64], sd: &[f64], delta: f64) -> Option<f64> {
340    let step_sd = dot(step, sd);
341    let sd_sq = dot(sd, sd);
342    let dist_tr_sq = delta * delta - dot(step, step);
343    let temp = (step_sd * step_sd + sd_sq * dist_tr_sq).max(0.0).sqrt();
344    if step_sd <= 0.0 && sd_sq > TINY * (temp - step_sd).abs() {
345        Some(((temp - step_sd) / sd_sq).max(0.0))
346    } else if (temp + step_sd).abs() > TINY * dist_tr_sq {
347        Some((dist_tr_sq / (temp + step_sd)).max(0.0))
348    } else {
349        None
350    }
351}
352
353/// Pivoted Householder QR of the `n × k` matrix whose columns are `cols`: the full orthogonal factor
354/// `Q` (`n × n`, by columns) and the number of columns of `R` whose diagonal is not negligible against
355/// its column (SciPy's `n_act`).
356fn qr_pivot(cols: &[V], n: usize, tol_scale: usize) -> (usize, M) {
357    let k = cols.len();
358    // a[j] is column j of the working matrix.
359    let mut a: Vec<V> = cols.to_vec();
360    let mut perm: Vec<usize> = (0..k).collect();
361    let mut vs: Vec<V> = Vec::new();
362    let r = n.min(k);
363    for j in 0..r {
364        // Pivot: the remaining column of largest trailing norm.
365        let mut best = j;
366        let mut bn = -1.0;
367        for c in j..k {
368            let nn: f64 = a[c][j..].iter().map(|v| v * v).sum();
369            if nn > bn {
370                bn = nn;
371                best = c;
372            }
373        }
374        a.swap(j, best);
375        perm.swap(j, best);
376        let tail: f64 = a[j][j..].iter().map(|v| v * v).sum::<f64>().sqrt();
377        let mut v = vec![0.0; n];
378        if tail > 0.0 {
379            let alpha = if a[j][j] > 0.0 { -tail } else { tail };
380            v[j..].copy_from_slice(&a[j][j..]);
381            v[j] -= alpha;
382            let vn = norm(&v);
383            if vn > 0.0 {
384                v.iter_mut().for_each(|t| *t /= vn);
385                for c in j..k {
386                    let s = 2.0 * dot(&v, &a[c]);
387                    axpy(&mut a[c], -s, &v);
388                }
389            }
390        }
391        vs.push(v);
392    }
393    // R = a (upper triangle); n_act counts columns whose diagonal exceeds the threshold.
394    let mut n_act = 0;
395    for j in 0..r {
396        let colnorm: f64 = (0..=j.min(r - 1)).map(|i| a[j][i] * a[j][i]).sum::<f64>().sqrt();
397        if a[j][j].abs() >= 10.0 * EPS * tol_scale as f64 * colnorm {
398            n_act += 1;
399        }
400    }
401    // Q = H₀ H₁ … H_{r−1}: columns by applying the reflectors in reverse to the identity.
402    let mut q: M = (0..n).map(|j| (0..n).map(|i| if i == j { 1.0 } else { 0.0 }).collect()).collect();
403    for v in vs.iter().rev() {
404        for col in q.iter_mut() {
405            let s = 2.0 * dot(v, col);
406            axpy(col, -s, v);
407        }
408    }
409    (n_act, q)
410}
411
412/// `Q[:, n_act:] Q[:, n_act:]ᵀ g`: the projection onto the span of the trailing columns of `q`.
413fn project_free(q: &[V], n_act: usize, g: &[f64]) -> V {
414    let n = g.len();
415    let mut out = vec![0.0; n];
416    for col in &q[n_act..] {
417        let c = dot(col, g);
418        axpy(&mut out, c, col);
419    }
420    out
421}
422
423fn qr_tangential(aub: &[V], aeq: &[V], free_xl: &[bool], free_xu: &[bool], free_ub: &[bool]) -> (usize, M) {
424    let n = free_xl.len();
425    let mut cols: Vec<V> = aeq.to_vec();
426    for (i, r) in aub.iter().enumerate() {
427        if !free_ub[i] {
428            cols.push(r.clone());
429        }
430    }
431    for i in 0..n {
432        if !free_xl[i] {
433            let mut e = vec![0.0; n];
434            e[i] = -1.0;
435            cols.push(e);
436        }
437    }
438    for i in 0..n {
439        if !free_xu[i] {
440            let mut e = vec![0.0; n];
441            e[i] = 1.0;
442            cols.push(e);
443        }
444    }
445    qr_pivot(&cols, n, n)
446}
447
448fn qr_normal(aub: &[V], free_xl: &[bool], free_xu: &[bool], free_slack: &[bool], free_ub: &[bool]) -> (usize, M) {
449    let m = aub.len();
450    let n = free_xl.len();
451    let dim = n + m;
452    let mut cols: Vec<V> = Vec::new();
453    for i in 0..m {
454        if !free_ub[i] {
455            let mut r = aub[i].clone();
456            r.extend((0..m).map(|j| if j == i { -1.0 } else { 0.0 }));
457            cols.push(r);
458        }
459    }
460    for i in 0..m {
461        if !free_slack[i] {
462            let mut r = vec![0.0; n];
463            r.extend((0..m).map(|j| if j == i { -1.0 } else { 0.0 }));
464            cols.push(r);
465        }
466    }
467    for i in 0..n {
468        if !free_xl[i] {
469            let mut r = vec![0.0; dim];
470            r[i] = -1.0;
471            cols.push(r);
472        }
473    }
474    for i in 0..n {
475        if !free_xu[i] {
476            let mut r = vec![0.0; dim];
477            r[i] = 1.0;
478            cols.push(r);
479        }
480    }
481    qr_pivot(&cols, dim, dim)
482}
483
484// ---------------------------------------------------------------------------------------------
485// Geometry subsolvers
486// ---------------------------------------------------------------------------------------------
487
488fn cauchy_geom(cst: f64, grad: &[f64], curv: &dyn Fn(&[f64]) -> f64, xl: &[f64], xu: &[f64], delta: f64) -> (V, f64) {
489    let n = grad.len();
490    let mut fixed_xl: Vec<bool> = (0..n).map(|i| xl[i] < 0.0 && grad[i] > 0.0).collect();
491    let mut fixed_xu: Vec<bool> = (0..n).map(|i| xu[i] > 0.0 && grad[i] < 0.0).collect();
492    let mut cs = vec![0.0; n];
493    for i in 0..n {
494        if fixed_xl[i] {
495            cs[i] = xl[i];
496        }
497        if fixed_xu[i] {
498            cs[i] = xu[i];
499        }
500    }
501    if norm(&cs) > delta {
502        let mut working: Vec<bool> = (0..n).map(|i| fixed_xl[i] || fixed_xu[i]).collect();
503        loop {
504            let g_norm = (0..n).filter(|&i| working[i]).map(|i| grad[i] * grad[i]).sum::<f64>().sqrt();
505            let rest: f64 = (0..n).filter(|&i| !working[i]).map(|i| cs[i] * cs[i]).sum();
506            let delta_reduced = if delta * delta - rest >= 0.0 { (delta * delta - rest).sqrt() } else { f64::NAN };
507            let mu = if g_norm > TINY * delta_reduced.abs() { (delta_reduced / g_norm).max(0.0) } else { break };
508            for i in 0..n {
509                if working[i] {
510                    cs[i] = mu * grad[i];
511                }
512            }
513            fixed_xl = (0..n).map(|i| working[i] && cs[i] < xl[i]).collect();
514            fixed_xu = (0..n).map(|i| working[i] && cs[i] > xu[i]).collect();
515            if !fixed_xl.iter().any(|&b| b) && !fixed_xu.iter().any(|&b| b) {
516                break;
517            }
518            for i in 0..n {
519                if fixed_xl[i] {
520                    cs[i] = xl[i];
521                }
522                if fixed_xu[i] {
523                    cs[i] = xu[i];
524                }
525                if fixed_xl[i] || fixed_xu[i] {
526                    working[i] = false;
527                }
528            }
529        }
530    }
531    let grad_step = dot(grad, &cs);
532    if grad_step >= 0.0 {
533        let s_norm = norm(&cs);
534        let alpha_tr = if s_norm > TINY * delta { (delta / s_norm).max(0.0) } else { 0.0 };
535        let curv_step = curv(&cs);
536        let alpha_quad = if curv_step < -TINY * grad_step { (-grad_step / curv_step).max(0.0) } else { f64::INFINITY };
537        let mut alpha_bd = f64::INFINITY;
538        for i in 0..n {
539            if xl[i] > f64::NEG_INFINITY && cs[i] < TINY * xl[i] {
540                alpha_bd = alpha_bd.min(xl[i] / cs[i]);
541            }
542            if xu[i] < f64::INFINITY && cs[i] > TINY * xu[i] {
543                alpha_bd = alpha_bd.min(xu[i] / cs[i]);
544            }
545        }
546        let alpha = alpha_tr.min(alpha_quad).min(alpha_bd);
547        let step = clip(&scaled(&cs, alpha), xl, xu);
548        (step, cst + alpha * grad_step + 0.5 * alpha * alpha * curv_step)
549    } else {
550        (vec![0.0; n], cst)
551    }
552}
553
554fn cauchy_geometry(cst: f64, grad: &[f64], curv: &dyn Fn(&[f64]) -> f64, xl: &[f64], xu: &[f64], delta: f64) -> V {
555    let xl: V = xl.iter().map(|v| v.min(0.0)).collect();
556    let xu: V = xu.iter().map(|v| v.max(0.0)).collect();
557    let (s1, q1) = cauchy_geom(cst, grad, curv, &xl, &xu, delta);
558    let neg: V = grad.iter().map(|g| -g).collect();
559    let (s2, q2) = cauchy_geom(-cst, &neg, &|x: &[f64]| -curv(x), &xl, &xu, delta);
560    if q1.abs() >= q2.abs() { s1 } else { s2 }
561}
562
563/// The best step along a line through the base point and an interpolation point, within the trust
564/// region and the bounds (`xpt` holds the directions, one per vector).
565fn spider_geometry(cst: f64, grad: &[f64], curv: &dyn Fn(&[f64]) -> f64, xpt: &[V], xl: &[f64], xu: &[f64], delta: f64) -> V {
566    let n = grad.len();
567    let xl: V = xl.iter().map(|v| v.min(0.0)).collect();
568    let xu: V = xu.iter().map(|v| v.max(0.0)).collect();
569    let mut step = vec![0.0; n];
570    let mut q_val = cst;
571    for p in xpt {
572        let s_norm = norm(p);
573        if s_norm <= TINY * delta {
574            continue;
575        }
576        let alpha_tr = (delta / s_norm).max(0.0);
577        // The bound limits (as SciPy computes them: the limits for the positive direction are
578        // not tightened, only the clip below applies).
579        let mut alpha_xl_pos = f64::NEG_INFINITY;
580        let mut alpha_xu_neg = f64::NEG_INFINITY;
581        for i in 0..n {
582            if xl[i] > f64::NEG_INFINITY && p[i] > -TINY * xl[i] {
583                alpha_xl_pos = alpha_xl_pos.max(xl[i] / p[i]);
584            }
585            if xu[i] < f64::INFINITY && p[i] < -TINY * xu[i] {
586                alpha_xu_neg = alpha_xu_neg.max(xu[i] / p[i]);
587            }
588        }
589        let alpha_bd_pos = f64::INFINITY;
590        let alpha_bd_neg = alpha_xl_pos.max(alpha_xu_neg).min(0.0);
591        let grad_step = dot(grad, p);
592        let curv_step = curv(p);
593        let alpha_quad_pos = if (grad_step >= 0.0 && curv_step < -TINY * grad_step) || (grad_step <= 0.0 && curv_step > -TINY * grad_step) { (-grad_step / curv_step).max(0.0) } else { f64::INFINITY };
594        let alpha_quad_neg = if (grad_step >= 0.0 && curv_step > TINY * grad_step) || (grad_step <= 0.0 && curv_step < TINY * grad_step) { (-grad_step / curv_step).min(0.0) } else { f64::NEG_INFINITY };
595        let mut alpha_pos = alpha_tr.min(alpha_bd_pos);
596        let mut alpha_neg = (-alpha_tr).max(alpha_bd_neg);
597        let q_at = |a: f64| cst + a * grad_step + 0.5 * a * a * curv_step;
598        let mut q_pos = q_at(alpha_pos);
599        let mut q_neg = q_at(alpha_neg);
600        if alpha_quad_pos < alpha_pos {
601            let qq = q_at(alpha_quad_pos);
602            if qq.abs() > q_pos.abs() {
603                alpha_pos = alpha_quad_pos;
604                q_pos = qq;
605            }
606        }
607        if alpha_quad_neg > alpha_neg {
608            let qq = q_at(alpha_quad_neg);
609            if qq.abs() > q_neg.abs() {
610                alpha_neg = alpha_quad_neg;
611                q_neg = qq;
612            }
613        }
614        if q_pos.abs() >= q_neg.abs() && q_pos.abs() > q_val.abs() {
615            step = clip(&scaled(p, alpha_pos), &xl, &xu);
616            q_val = q_pos;
617        } else if q_neg.abs() > q_pos.abs() && q_neg.abs() > q_val.abs() {
618            step = clip(&scaled(p, alpha_neg), &xl, &xu);
619            q_val = q_neg;
620        }
621    }
622    step
623}
624
625// ---------------------------------------------------------------------------------------------
626// Trust-region subsolvers
627// ---------------------------------------------------------------------------------------------
628
629/// The tangential step with bounds only (truncated conjugate gradient, then an improving search on
630/// the boundary of the trust region).
631fn tangential_bound(grad0: &[f64], hess_prod: &dyn Fn(&[f64]) -> V, xl: &[f64], xu: &[f64], delta: f64, improve_tcg: bool) -> V {
632    let n = grad0.len();
633    let xl: V = xl.iter().map(|v| v.min(0.0)).collect();
634    let xu: V = xu.iter().map(|v| v.max(0.0)).collect();
635    let mut grad = grad0.to_vec();
636    let grad_orig = grad0.to_vec();
637    let mut free_bd: Vec<bool> = (0..n).map(|i| (xl[i] < 0.0 || grad[i] < 0.0) && (xu[i] > 0.0 || grad[i] > 0.0)).collect();
638    let mut step = vec![0.0; n];
639    let mut sd = vec![0.0; n];
640    for i in 0..n {
641        if free_bd[i] {
642            sd[i] = -grad[i];
643        }
644    }
645    let mut k = 0;
646    let mut reduct = 0.0;
647    let mut boundary_reached = false;
648    while k < free_bd.iter().filter(|&&b| b).count() {
649        let grad_sd = dot(&grad, &sd);
650        if grad_sd >= -10.0 * EPS * n as f64 * 1.0f64.max(norm(&grad)) {
651            break;
652        }
653        let Some(a_tr) = alpha_tr(&step, &sd, delta) else { break };
654        if -a_tr * grad_sd <= 1e-8 * reduct {
655            break;
656        }
657        let hess_sd = hess_prod(&sd);
658        let curv_sd = dot(&sd, &hess_sd);
659        let alpha_quad = if curv_sd > TINY * grad_sd.abs() { (-grad_sd / curv_sd).max(0.0) } else { f64::INFINITY };
660        let mut alpha = a_tr.min(alpha_quad);
661        if -alpha * (grad_sd + 0.5 * alpha * curv_sd) <= 1e-8 * reduct {
662            break;
663        }
664        let mut all_xl = vec![f64::INFINITY; n];
665        let mut all_xu = vec![f64::INFINITY; n];
666        for i in 0..n {
667            if xl[i] > f64::NEG_INFINITY && sd[i] < -TINY * (xl[i] - step[i]).abs() {
668                all_xl[i] = ((xl[i] - step[i]) / sd[i]).max(0.0);
669            }
670            if xu[i] < f64::INFINITY && sd[i] > TINY * (xu[i] - step[i]).abs() {
671                all_xu[i] = ((xu[i] - step[i]) / sd[i]).max(0.0);
672            }
673        }
674        let alpha_xl = all_xl.iter().cloned().fold(f64::INFINITY, f64::min);
675        let alpha_xu = all_xu.iter().cloned().fold(f64::INFINITY, f64::min);
676        let alpha_bd = alpha_xl.min(alpha_xu);
677        alpha = alpha.min(alpha_bd);
678        if alpha > 0.0 {
679            for i in 0..n {
680                if free_bd[i] {
681                    step[i] = (step[i] + alpha * sd[i]).max(xl[i]).min(xu[i]);
682                }
683            }
684            axpy(&mut grad, alpha, &hess_sd);
685            reduct -= alpha * (grad_sd + 0.5 * alpha * curv_sd);
686        }
687        if alpha < a_tr.min(alpha_bd) {
688            let gh: f64 = (0..n).filter(|&i| free_bd[i]).map(|i| grad[i] * hess_sd[i]).sum();
689            let beta = gh / curv_sd;
690            for i in 0..n {
691                sd[i] = if free_bd[i] { beta * sd[i] - grad[i] } else { 0.0 };
692            }
693            k += 1;
694        } else if alpha < a_tr {
695            let i_new;
696            if alpha_xl <= alpha {
697                i_new = argmin_first(&all_xl);
698                step[i_new] = xl[i_new];
699            } else {
700                i_new = argmin_first(&all_xu);
701                step[i_new] = xu[i_new];
702            }
703            free_bd[i_new] = false;
704            for i in 0..n {
705                sd[i] = if free_bd[i] { -grad[i] } else { 0.0 };
706            }
707            k = 0;
708        } else {
709            if alpha_xl <= alpha {
710                for i in argmin_all(&all_xl) {
711                    step[i] = xl[i];
712                    free_bd[i] = false;
713                }
714            }
715            if alpha_xu <= alpha {
716                for i in argmin_all(&all_xu) {
717                    step[i] = xu[i];
718                    free_bd[i] = false;
719                }
720            }
721            boundary_reached = true;
722            break;
723        }
724    }
725    if improve_tcg && boundary_reached {
726        let step_base = step.clone();
727        let comparator = dot(&grad_orig, &step_base) + 0.5 * dot(&step_base, &hess_prod(&step_base));
728        while free_bd.iter().any(|&b| b) {
729            let idx: Vec<usize> = (0..n).filter(|&i| free_bd[i]).collect();
730            let step_sq: f64 = idx.iter().map(|&i| step[i] * step[i]).sum();
731            let grad_sq: f64 = idx.iter().map(|&i| grad[i] * grad[i]).sum();
732            let grad_step: f64 = idx.iter().map(|&i| grad[i] * step[i]).sum();
733            let grad_sd = -(step_sq * grad_sq - grad_step * grad_step).max(0.0).sqrt();
734            for i in 0..n {
735                sd[i] = if free_bd[i] { grad_step * step[i] - step_sq * grad[i] } else { 0.0 };
736            }
737            if grad_sd >= -1e-8 * reduct || idx.iter().any(|&i| grad_sd >= -TINY * sd[i].abs()) {
738                break;
739            }
740            for &i in &idx {
741                sd[i] /= -grad_sd;
742            }
743            let mut temp_xl = vec![0.0; n];
744            let mut temp_xu = vec![0.0; n];
745            for &i in &idx {
746                temp_xl[i] = step[i] * step[i] + sd[i] * sd[i] - xl[i] * xl[i];
747                temp_xu[i] = step[i] * step[i] + sd[i] * sd[i] - xu[i] * xu[i];
748            }
749            for i in 0..n {
750                if temp_xl[i] > 0.0 {
751                    temp_xl[i] = temp_xl[i].sqrt() - sd[i];
752                }
753                if temp_xu[i] > 0.0 {
754                    temp_xu[i] = temp_xu[i].sqrt() + sd[i];
755                }
756            }
757            let dist_xl: V = (0..n).map(|i| (step[i] - xl[i]).max(0.0)).collect();
758            let dist_xu: V = (0..n).map(|i| (xu[i] - step[i]).max(0.0)).collect();
759            let mut all_t_xl = vec![1.0f64; n];
760            let mut all_t_xu = vec![1.0f64; n];
761            for i in 0..n {
762                if temp_xl[i] > TINY * dist_xl[i] {
763                    all_t_xl[i] = all_t_xl[i].min(dist_xl[i] / temp_xl[i]);
764                }
765                if temp_xu[i] > TINY * dist_xu[i] {
766                    all_t_xu[i] = all_t_xu[i].min(dist_xu[i] / temp_xu[i]);
767                }
768            }
769            let t_xl = all_t_xl.iter().cloned().fold(f64::INFINITY, f64::min);
770            let t_xu = all_t_xu.iter().cloned().fold(f64::INFINITY, f64::min);
771            let t_bd = t_xl.min(t_xu);
772            let hess_step = hess_prod(&step);
773            let hess_sd = hess_prod(&sd);
774            let curv_step = dot(&step, &hess_step);
775            let curv_sd = dot(&sd, &hess_sd);
776            let curv_step_sd = dot(&step, &hess_sd);
777            let n_samples = (((20 - 3) as f64) * t_bd + 3.0) as usize;
778            let t_samples: V = (0..n_samples).map(|j| if n_samples == 1 { t_bd } else { t_bd / n_samples as f64 + (t_bd - t_bd / n_samples as f64) * j as f64 / (n_samples - 1) as f64 }).collect();
779            let sin_values: V = t_samples.iter().map(|t| 2.0 * t / (1.0 + t * t)).collect();
780            let all_reduct: V = (0..n_samples).map(|j| sin_values[j] * (grad_step * t_samples[j] - grad_sd - t_samples[j] * curv_step + sin_values[j] * (t_samples[j] * curv_step_sd - 0.5 * (curv_sd - curv_step)))).collect();
781            if all_reduct.iter().all(|&r| r <= 0.0) {
782                break;
783            }
784            let i_max = argmax_all(&all_reduct)[0];
785            let cos_value = (1.0 - t_samples[i_max] * t_samples[i_max]) / (1.0 + t_samples[i_max] * t_samples[i_max]);
786            for &i in &idx {
787                step[i] = cos_value * step[i] + sin_values[i_max] * sd[i];
788            }
789            for i in 0..n {
790                grad[i] += (cos_value - 1.0) * hess_step[i] + sin_values[i_max] * hess_sd[i];
791            }
792            reduct += all_reduct[i_max];
793            if t_bd < 1.0 && i_max == n_samples - 1 {
794                if t_xl <= t_bd {
795                    for i in argmin_all(&all_t_xl) {
796                        step[i] = xl[i];
797                        free_bd[i] = false;
798                    }
799                }
800                if t_xu <= t_bd {
801                    for i in argmin_all(&all_t_xu) {
802                        step[i] = xu[i];
803                        free_bd[i] = false;
804                    }
805                }
806            } else {
807                break;
808            }
809        }
810        if dot(&grad_orig, &step) + 0.5 * dot(&step, &hess_prod(&step)) > comparator {
811            step = step_base;
812        }
813    }
814    step
815}
816
817/// The tangential step with linearised constraints too (the inequalities in `aub s ≤ bub`, the
818/// equalities `aeq s = 0`).
819#[allow(clippy::too_many_arguments)]
820fn tangential_constrained(grad0: &[f64], hess_prod: &dyn Fn(&[f64]) -> V, xl: &[f64], xu: &[f64], aub: &[V], bub: &[f64], aeq: &[V], delta: f64, improve_tcg: bool) -> V {
821    let n = grad0.len();
822    let xl: V = xl.iter().map(|v| v.min(0.0)).collect();
823    let xu: V = xu.iter().map(|v| v.max(0.0)).collect();
824    let bub: V = bub.iter().map(|v| v.max(0.0)).collect();
825    let mut grad = grad0.to_vec();
826    let grad_orig = grad0.to_vec();
827    let mut free_xl: Vec<bool> = (0..n).map(|i| xl[i] < 0.0 || grad[i] < 0.0).collect();
828    let mut free_xu: Vec<bool> = (0..n).map(|i| xu[i] > 0.0 || grad[i] > 0.0).collect();
829    let mut free_ub: Vec<bool> = (0..aub.len()).map(|i| bub[i] > 0.0 || dot(&aub[i], &grad) > 0.0).collect();
830    let (mut n_act, mut q) = qr_tangential(aub, aeq, &free_xl, &free_xu, &free_ub);
831    let mut step = vec![0.0; n];
832    let mut sd: V = project_free(&q, n_act, &grad).iter().map(|v| -v).collect();
833    let mut resid = bub.clone();
834    let mut k = 0;
835    let mut reduct = 0.0;
836    let mut boundary_reached = false;
837    while k < n - n_act {
838        let grad_sd = dot(&grad, &sd);
839        if grad_sd >= -10.0 * EPS * n as f64 * 1.0f64.max(norm(&grad)) {
840            break;
841        }
842        let Some(a_tr) = alpha_tr(&step, &sd, delta) else { break };
843        if -a_tr * grad_sd <= 1e-8 * reduct {
844            break;
845        }
846        let hess_sd = hess_prod(&sd);
847        let curv_sd = dot(&sd, &hess_sd);
848        let alpha_quad = if curv_sd > TINY * grad_sd.abs() { (-grad_sd / curv_sd).max(0.0) } else { f64::INFINITY };
849        let mut alpha = a_tr.min(alpha_quad);
850        if -alpha * (grad_sd + 0.5 * alpha * curv_sd) <= 1e-8 * reduct {
851            break;
852        }
853        let mut all_xl = vec![f64::INFINITY; n];
854        let mut all_xu = vec![f64::INFINITY; n];
855        for i in 0..n {
856            if free_xl[i] && xl[i] > f64::NEG_INFINITY && sd[i] < -TINY * (xl[i] - step[i]).abs() {
857                all_xl[i] = ((xl[i] - step[i]) / sd[i]).max(0.0);
858            }
859            if free_xu[i] && xu[i] < f64::INFINITY && sd[i] > TINY * (xu[i] - step[i]).abs() {
860                all_xu[i] = ((xu[i] - step[i]) / sd[i]).max(0.0);
861            }
862        }
863        let alpha_xl = all_xl.iter().cloned().fold(f64::INFINITY, f64::min);
864        let alpha_xu = all_xu.iter().cloned().fold(f64::INFINITY, f64::min);
865        let alpha_bd = alpha_xl.min(alpha_xu);
866        let aub_sd = matvec(aub, &sd);
867        let mut all_ub = vec![f64::INFINITY; aub.len()];
868        for i in 0..aub.len() {
869            if free_ub[i] && aub_sd[i] > TINY * resid[i].abs() {
870                all_ub[i] = resid[i] / aub_sd[i];
871            }
872        }
873        let alpha_ub = all_ub.iter().cloned().fold(f64::INFINITY, f64::min);
874        alpha = alpha.min(alpha_bd).min(alpha_ub);
875        if alpha > 0.0 {
876            step = clip(&add(&step, &scaled(&sd, alpha)), &xl, &xu);
877            axpy(&mut grad, alpha, &hess_sd);
878            for i in 0..resid.len() {
879                resid[i] = (resid[i] - alpha * aub_sd[i]).max(0.0);
880            }
881            reduct -= alpha * (grad_sd + 0.5 * alpha * curv_sd);
882        }
883        if alpha < a_tr.min(alpha_bd).min(alpha_ub) {
884            let grad_proj = project_free(&q, n_act, &grad);
885            let beta = dot(&grad_proj, &hess_sd) / curv_sd;
886            sd = sub(&scaled(&sd, beta), &grad_proj);
887            k += 1;
888        } else if alpha < a_tr {
889            if alpha_xl <= alpha {
890                let i = argmin_first(&all_xl);
891                step[i] = xl[i];
892                free_xl[i] = false;
893            } else if alpha_xu <= alpha {
894                let i = argmin_first(&all_xu);
895                step[i] = xu[i];
896                free_xu[i] = false;
897            } else {
898                let i = argmin_first(&all_ub);
899                free_ub[i] = false;
900            }
901            (n_act, q) = qr_tangential(aub, aeq, &free_xl, &free_xu, &free_ub);
902            sd = project_free(&q, n_act, &grad).iter().map(|v| -v).collect();
903            k = 0;
904        } else {
905            if alpha_xl <= alpha {
906                for i in argmin_all(&all_xl) {
907                    step[i] = xl[i];
908                    free_xl[i] = false;
909                }
910            }
911            if alpha_xu <= alpha {
912                for i in argmin_all(&all_xu) {
913                    step[i] = xu[i];
914                    free_xu[i] = false;
915                }
916            }
917            if alpha_ub <= alpha {
918                for i in argmin_all(&all_ub) {
919                    free_ub[i] = false;
920                }
921            }
922            (n_act, q) = qr_tangential(aub, aeq, &free_xl, &free_xu, &free_ub);
923            boundary_reached = true;
924            break;
925        }
926    }
927    if improve_tcg && boundary_reached && n_act < n {
928        let step_base = step.clone();
929        while n_act < n {
930            let step_proj = project_free(&q, n_act, &step);
931            let grad_proj = project_free(&q, n_act, &grad);
932            let step_sq = dot(&step_proj, &step_proj);
933            let grad_sq = dot(&grad_proj, &grad_proj);
934            let grad_step = dot(&grad_proj, &step_proj);
935            let grad_sd = -(step_sq * grad_sq - grad_step * grad_step).max(0.0).sqrt();
936            let mut sd = project_free(&q, n_act, &sub(&scaled(&step, grad_step), &scaled(&grad, step_sq)));
937            if grad_sd >= -1e-8 * reduct || sd.iter().any(|v| grad_sd >= -TINY * v.abs()) {
938                break;
939            }
940            sd.iter_mut().for_each(|v| *v /= -grad_sd);
941            let mut temp_xl = vec![0.0; n];
942            let mut temp_xu = vec![0.0; n];
943            let dist_xl: V = (0..n).map(|i| (step[i] - xl[i]).max(0.0)).collect();
944            let dist_xu: V = (0..n).map(|i| (xu[i] - step[i]).max(0.0)).collect();
945            for i in 0..n {
946                if free_xl[i] {
947                    temp_xl[i] = sd[i] * sd[i] - dist_xl[i] * (dist_xl[i] - 2.0 * step_proj[i]);
948                }
949                if free_xu[i] {
950                    temp_xu[i] = sd[i] * sd[i] - dist_xu[i] * (dist_xu[i] + 2.0 * step_proj[i]);
951                }
952                if temp_xl[i] > 0.0 {
953                    temp_xl[i] = temp_xl[i].sqrt() - sd[i];
954                }
955                if temp_xu[i] > 0.0 {
956                    temp_xu[i] = temp_xu[i].sqrt() + sd[i];
957                }
958            }
959            let mut all_t_xl = vec![1.0f64; n];
960            let mut all_t_xu = vec![1.0f64; n];
961            for i in 0..n {
962                if temp_xl[i] > TINY * dist_xl[i] {
963                    all_t_xl[i] = all_t_xl[i].min(dist_xl[i] / temp_xl[i]);
964                }
965                if temp_xu[i] > TINY * dist_xu[i] {
966                    all_t_xu[i] = all_t_xu[i].min(dist_xu[i] / temp_xu[i]);
967                }
968            }
969            let t_xl = all_t_xl.iter().cloned().fold(f64::INFINITY, f64::min);
970            let t_xu = all_t_xu.iter().cloned().fold(f64::INFINITY, f64::min);
971            let t_bd = t_xl.min(t_xu);
972            let aub_step = matvec(aub, &step_proj);
973            let aub_sd = matvec(aub, &sd);
974            let mut temp_ub = vec![0.0; aub.len()];
975            for i in 0..aub.len() {
976                if free_ub[i] {
977                    temp_ub[i] = aub_sd[i] * aub_sd[i] - resid[i] * (resid[i] + 2.0 * aub_step[i]);
978                }
979                if temp_ub[i] > 0.0 {
980                    temp_ub[i] = temp_ub[i].sqrt() + aub_sd[i];
981                }
982            }
983            let mut all_t_ub = vec![1.0f64; aub.len()];
984            for i in 0..aub.len() {
985                if temp_ub[i] > TINY * resid[i] {
986                    all_t_ub[i] = all_t_ub[i].min(resid[i] / temp_ub[i]);
987                }
988            }
989            let t_ub = all_t_ub.iter().cloned().fold(1.0, f64::min);
990            let t_min = t_bd.min(t_ub);
991            let hess_step = hess_prod(&step_proj);
992            let hess_sd = hess_prod(&sd);
993            let curv_step = dot(&step_proj, &hess_step);
994            let curv_sd = dot(&sd, &hess_sd);
995            let curv_step_sd = dot(&step_proj, &hess_sd);
996            let n_samples = (((20 - 3) as f64) * t_min + 3.0) as usize;
997            let t_samples: V = (0..n_samples).map(|j| if n_samples == 1 { t_min } else { t_min / n_samples as f64 + (t_min - t_min / n_samples as f64) * j as f64 / (n_samples - 1) as f64 }).collect();
998            let sin_values: V = t_samples.iter().map(|t| 2.0 * t / (1.0 + t * t)).collect();
999            let all_reduct: V = (0..n_samples).map(|j| sin_values[j] * (grad_step * t_samples[j] - grad_sd - sin_values[j] * (0.5 * t_samples[j] * t_samples[j] * curv_step - 2.0 * t_samples[j] * curv_step_sd + 0.5 * curv_sd))).collect();
1000            if all_reduct.iter().all(|&r| r <= 0.0) {
1001                break;
1002            }
1003            let i_max = argmax_all(&all_reduct)[0];
1004            let cos_value = (1.0 - t_samples[i_max] * t_samples[i_max]) / (1.0 + t_samples[i_max] * t_samples[i_max]);
1005            let mut moved = step.clone();
1006            axpy(&mut moved, cos_value - 1.0, &step_proj);
1007            axpy(&mut moved, sin_values[i_max], &sd);
1008            step = clip(&moved, &xl, &xu);
1009            axpy(&mut grad, cos_value - 1.0, &hess_step);
1010            axpy(&mut grad, sin_values[i_max], &hess_sd);
1011            for i in 0..resid.len() {
1012                resid[i] = (resid[i] - (cos_value - 1.0) * aub_step[i] - sin_values[i_max] * aub_sd[i]).max(0.0);
1013            }
1014            reduct += all_reduct[i_max];
1015            if t_min < 1.0 && i_max == n_samples - 1 {
1016                if t_xl <= t_min {
1017                    for i in argmin_all(&all_t_xl) {
1018                        step[i] = xl[i];
1019                        free_xl[i] = false;
1020                    }
1021                }
1022                if t_xu <= t_min {
1023                    for i in argmin_all(&all_t_xu) {
1024                        step[i] = xu[i];
1025                        free_xl[i] = false;
1026                    }
1027                }
1028                if t_ub <= t_min {
1029                    for i in argmin_all(&all_t_ub) {
1030                        free_ub[i] = false;
1031                    }
1032                }
1033                (n_act, q) = qr_tangential(aub, aeq, &free_xl, &free_xu, &free_ub);
1034            } else {
1035                break;
1036            }
1037        }
1038        if dot(&grad_orig, &step) + 0.5 * dot(&step, &hess_prod(&step)) > dot(&grad_orig, &step_base) + 0.5 * dot(&step_base, &hess_prod(&step_base)) {
1039            step = step_base;
1040        }
1041    }
1042    step
1043}
1044
1045/// The normal step: reduces the violation of the linearised constraints `aub s ≤ bub`, `aeq s = beq`
1046/// within the bounds and a trust region of radius `delta`.
1047#[allow(clippy::too_many_arguments)]
1048fn normal_step(aub: &[V], bub: &[f64], aeq: &[V], beq: &[f64], xl: &[f64], xu: &[f64], delta: f64, improve_tcg: bool) -> V {
1049    let n = xl.len();
1050    let m = aub.len();
1051    let xl: V = xl.iter().map(|v| v.min(0.0)).collect();
1052    let xu: V = xu.iter().map(|v| v.max(0.0)).collect();
1053    // grad = [aeqᵀ(−beq); max(0, −bub)] (the point s = 0 of the stacked variables (s, slack)).
1054    let neg_beq: V = beq.iter().map(|v| -v).collect();
1055    let mut grad: V = matvec_t(aeq, &neg_beq, n);
1056    grad.extend(bub.iter().map(|v| (-v).max(0.0)));
1057    let mut free_xl: Vec<bool> = (0..n).map(|i| xl[i] < 0.0 || grad[i] < 0.0).collect();
1058    let mut free_xu: Vec<bool> = (0..n).map(|i| xu[i] > 0.0 || grad[i] > 0.0).collect();
1059    let mut free_slack: Vec<bool> = bub.iter().map(|&b| b < 0.0).collect();
1060    let mut free_ub: Vec<bool> = (0..m).map(|i| bub[i] > 0.0 || dot(&aub[i], &grad[..n]) - grad[n + i] > 0.0).collect();
1061    let (mut n_act, mut q) = qr_normal(aub, &free_xl, &free_xu, &free_slack, &free_ub);
1062    let delta_slack = (dot(beq, beq) + dot(&grad[n..], &grad[n..])).sqrt();
1063    let mut step = vec![0.0; n];
1064    let mut sd: V = project_free(&q, n_act, &grad).iter().map(|v| -v).collect();
1065    let mut resid: V = (0..m).map(|i| bub[i] + grad[n + i]).collect();
1066    let mut k = 0;
1067    let mut reduct = 0.0;
1068    let mut boundary_reached = false;
1069    while k < n + m - n_act {
1070        let grad_sd = dot(&grad, &sd);
1071        if grad_sd >= -10.0 * EPS * n as f64 * 1.0f64.max(norm(&grad)) {
1072            break;
1073        }
1074        let mut a_tr = alpha_tr(&step, &sd[..n], delta).unwrap_or(f64::INFINITY);
1075        if let Some(a2) = alpha_tr(&grad[n..], &sd[n..], delta_slack) {
1076            a_tr = a_tr.min(a2);
1077        }
1078        if -a_tr * grad_sd <= 1e-8 * reduct {
1079            break;
1080        }
1081        let mut hess_sd: V = matvec_t(aeq, &matvec(aeq, &sd[..n]), n);
1082        hess_sd.extend_from_slice(&sd[n..]);
1083        let curv_sd = dot(&sd, &hess_sd);
1084        let alpha_quad = if curv_sd > TINY * grad_sd.abs() { (-grad_sd / curv_sd).max(0.0) } else { f64::INFINITY };
1085        let mut alpha = a_tr.min(alpha_quad);
1086        if -alpha * (grad_sd + 0.5 * alpha * curv_sd) <= 1e-8 * reduct {
1087            break;
1088        }
1089        let mut all_xl = vec![f64::INFINITY; n];
1090        let mut all_xu = vec![f64::INFINITY; n];
1091        let mut all_slack = vec![f64::INFINITY; m];
1092        for i in 0..n {
1093            if free_xl[i] && xl[i] > f64::NEG_INFINITY && sd[i] < -TINY * (xl[i] - step[i]).abs() {
1094                all_xl[i] = ((xl[i] - step[i]) / sd[i]).max(0.0);
1095            }
1096            if free_xu[i] && xu[i] < f64::INFINITY && sd[i] > TINY * (xu[i] - step[i]).abs() {
1097                all_xu[i] = ((xu[i] - step[i]) / sd[i]).max(0.0);
1098            }
1099        }
1100        for i in 0..m {
1101            if free_slack[i] && sd[n + i] < -TINY * grad[n + i].abs() {
1102                all_slack[i] = (-grad[n + i] / sd[n + i]).max(0.0);
1103            }
1104        }
1105        let alpha_xl = all_xl.iter().cloned().fold(f64::INFINITY, f64::min);
1106        let alpha_xu = all_xu.iter().cloned().fold(f64::INFINITY, f64::min);
1107        let alpha_slack = all_slack.iter().cloned().fold(f64::INFINITY, f64::min);
1108        let alpha_bd = alpha_xl.min(alpha_xu).min(alpha_slack);
1109        let aub_sd: V = (0..m).map(|i| dot(&aub[i], &sd[..n]) - sd[n + i]).collect();
1110        let mut all_ub = vec![f64::INFINITY; m];
1111        for i in 0..m {
1112            if free_ub[i] && aub_sd[i] > TINY * resid[i].abs() {
1113                all_ub[i] = resid[i] / aub_sd[i];
1114            }
1115        }
1116        let alpha_ub = all_ub.iter().cloned().fold(f64::INFINITY, f64::min);
1117        alpha = alpha.min(alpha_bd).min(alpha_ub);
1118        if alpha > 0.0 {
1119            step = clip(&add(&step, &scaled(&sd[..n], alpha)), &xl, &xu);
1120            axpy(&mut grad, alpha, &hess_sd);
1121            for i in 0..m {
1122                resid[i] = (resid[i] - alpha * aub_sd[i]).max(0.0);
1123            }
1124            reduct -= alpha * (grad_sd + 0.5 * alpha * curv_sd);
1125        }
1126        if alpha < a_tr.min(alpha_bd).min(alpha_ub) {
1127            let grad_proj = project_free(&q, n_act, &grad);
1128            let beta = dot(&grad_proj, &hess_sd) / curv_sd;
1129            sd = sub(&scaled(&sd, beta), &grad_proj);
1130            k += 1;
1131        } else if alpha < a_tr {
1132            if alpha_xl <= alpha {
1133                let i = argmin_first(&all_xl);
1134                step[i] = xl[i];
1135                free_xl[i] = false;
1136            } else if alpha_xu <= alpha {
1137                let i = argmin_first(&all_xu);
1138                step[i] = xu[i];
1139                free_xu[i] = false;
1140            } else if alpha_slack <= alpha {
1141                let i = argmin_first(&all_slack);
1142                free_slack[i] = false;
1143            } else {
1144                let i = argmin_first(&all_ub);
1145                free_ub[i] = false;
1146            }
1147            (n_act, q) = qr_normal(aub, &free_xl, &free_xu, &free_slack, &free_ub);
1148            sd = project_free(&q, n_act, &grad).iter().map(|v| -v).collect();
1149            k = 0;
1150        } else {
1151            if alpha_xl <= alpha {
1152                for i in argmin_all(&all_xl) {
1153                    step[i] = xl[i];
1154                    free_xl[i] = false;
1155                }
1156            }
1157            if alpha_xu <= alpha {
1158                for i in argmin_all(&all_xu) {
1159                    step[i] = xu[i];
1160                    free_xu[i] = false;
1161                }
1162            }
1163            boundary_reached = true;
1164            break;
1165        }
1166    }
1167    if improve_tcg && boundary_reached {
1168        let step_base = step.clone();
1169        let mut free_bd: Vec<bool> = (0..n).map(|i| free_xl[i] && free_xu[i]).collect();
1170        let resid_grad = |s: &[f64]| -> V {
1171            let ru: V = (0..m).map(|i| (dot(&aub[i], s) - bub[i]).max(0.0)).collect();
1172            let re: V = (0..aeq.len()).map(|i| dot(&aeq[i], s) - beq[i]).collect();
1173            add(&matvec_t(aub, &ru, n), &matvec_t(aeq, &re, n))
1174        };
1175        let mut grad = resid_grad(&step);
1176        let mut sd = vec![0.0; n];
1177        while free_bd.iter().any(|&b| b) {
1178            let idx: Vec<usize> = (0..n).filter(|&i| free_bd[i]).collect();
1179            let step_sq: f64 = idx.iter().map(|&i| step[i] * step[i]).sum();
1180            let grad_sq: f64 = idx.iter().map(|&i| grad[i] * grad[i]).sum();
1181            let grad_step: f64 = idx.iter().map(|&i| grad[i] * step[i]).sum();
1182            let grad_sd = -(step_sq * grad_sq - grad_step * grad_step).max(0.0).sqrt();
1183            for i in 0..n {
1184                sd[i] = if free_bd[i] { grad_step * step[i] - step_sq * grad[i] } else { 0.0 };
1185            }
1186            if grad_sd >= -1e-8 * reduct || idx.iter().any(|&i| grad_sd >= -TINY * sd[i].abs()) {
1187                break;
1188            }
1189            for &i in &idx {
1190                sd[i] /= -grad_sd;
1191            }
1192            let mut temp_xl = vec![0.0; n];
1193            let mut temp_xu = vec![0.0; n];
1194            for &i in &idx {
1195                temp_xl[i] = step[i] * step[i] + sd[i] * sd[i] - xl[i] * xl[i];
1196                temp_xu[i] = step[i] * step[i] + sd[i] * sd[i] - xu[i] * xu[i];
1197            }
1198            for i in 0..n {
1199                if temp_xl[i] > 0.0 {
1200                    temp_xl[i] = temp_xl[i].sqrt() - sd[i];
1201                }
1202                if temp_xu[i] > 0.0 {
1203                    temp_xu[i] = temp_xu[i].sqrt() + sd[i];
1204                }
1205            }
1206            let dist_xl: V = (0..n).map(|i| (step[i] - xl[i]).max(0.0)).collect();
1207            let dist_xu: V = (0..n).map(|i| (xu[i] - step[i]).max(0.0)).collect();
1208            let mut all_t_xl = vec![1.0f64; n];
1209            let mut all_t_xu = vec![1.0f64; n];
1210            for i in 0..n {
1211                if temp_xl[i] > TINY * dist_xl[i] {
1212                    all_t_xl[i] = all_t_xl[i].min(dist_xl[i] / temp_xl[i]);
1213                }
1214                if temp_xu[i] > TINY * dist_xu[i] {
1215                    all_t_xu[i] = all_t_xu[i].min(dist_xu[i] / temp_xu[i]);
1216                }
1217            }
1218            let t_xl = all_t_xl.iter().cloned().fold(f64::INFINITY, f64::min);
1219            let t_xu = all_t_xu.iter().cloned().fold(f64::INFINITY, f64::min);
1220            let t_bd = t_xl.min(t_xu);
1221            let n_samples = (((20 - 3) as f64) * t_bd + 3.0) as usize;
1222            let t_samples: V = (0..n_samples).map(|j| if n_samples == 1 { t_bd } else { t_bd / n_samples as f64 + (t_bd - t_bd / n_samples as f64) * j as f64 / (n_samples - 1) as f64 }).collect();
1223            let viol = |s: &[f64]| -> f64 {
1224                let a: f64 = (0..m).map(|i| (dot(&aub[i], s) - bub[i]).max(0.0).powi(2)).sum();
1225                let b: f64 = (0..aeq.len()).map(|i| (dot(&aeq[i], s) - beq[i]).powi(2)).sum();
1226                a + b
1227            };
1228            let base_viol = viol(&step);
1229            let step_proj: V = (0..n).map(|i| if free_bd[i] { step[i] } else { 0.0 }).collect();
1230            let all_reduct: V = (0..n_samples)
1231                .map(|j| {
1232                    let t = t_samples[j];
1233                    let sv = 2.0 * t / (1.0 + t * t);
1234                    let alt: V = (0..n).map(|i| step[i] + sv * (sd[i] - t * step_proj[i])).collect();
1235                    let alt = clip(&alt, &xl, &xu);
1236                    0.5 * (base_viol - viol(&alt))
1237                })
1238                .collect();
1239            if all_reduct.iter().all(|&r| r <= 0.0) {
1240                break;
1241            }
1242            let i_max = argmax_all(&all_reduct)[0];
1243            let t = t_samples[i_max];
1244            let cos_value = (1.0 - t * t) / (1.0 + t * t);
1245            let sin_value = 2.0 * t / (1.0 + t * t);
1246            for &i in &idx {
1247                step[i] = cos_value * step[i] + sin_value * sd[i];
1248            }
1249            grad = resid_grad(&step);
1250            reduct += all_reduct[i_max];
1251            if t_bd < 1.0 && i_max == n_samples - 1 {
1252                if t_xl <= t_bd {
1253                    for i in argmin_all(&all_t_xl) {
1254                        step[i] = xl[i];
1255                        free_bd[i] = false;
1256                    }
1257                }
1258                if t_xu <= t_bd {
1259                    for i in argmin_all(&all_t_xu) {
1260                        step[i] = xu[i];
1261                        free_bd[i] = false;
1262                    }
1263                }
1264            } else {
1265                break;
1266            }
1267        }
1268        let viol = |s: &[f64]| -> f64 {
1269            let a: f64 = (0..m).map(|i| (dot(&aub[i], s) - bub[i]).max(0.0).powi(2)).sum();
1270            let b: f64 = (0..aeq.len()).map(|i| (dot(&aeq[i], s) - beq[i]).powi(2)).sum();
1271            a + b
1272        };
1273        if viol(&step) > viol(&step_base) {
1274            step = step_base;
1275        }
1276    }
1277    step
1278}
1279
1280// ---------------------------------------------------------------------------------------------
1281// Interpolation set and quadratic models
1282// ---------------------------------------------------------------------------------------------
1283
1284struct Eig {
1285    values: Vec<f64>,
1286    /// Eigenvectors, one per entry of `values` (columns of the eigenvector matrix).
1287    vectors: Vec<V>,
1288    right_scaling: V,
1289}
1290
1291struct Interp {
1292    n: usize,
1293    x_base: V,
1294    /// The interpolation points relative to `x_base`: `xpt[k]` is point `k`.
1295    xpt: Vec<V>,
1296    cache: RefCell<Option<Eig>>,
1297}
1298
1299impl Interp {
1300    fn npt(&self) -> usize {
1301        self.xpt.len()
1302    }
1303
1304    fn point(&self, k: usize) -> V {
1305        add(&self.x_base, &self.xpt[k])
1306    }
1307
1308    fn invalidate(&self) {
1309        *self.cache.borrow_mut() = None;
1310    }
1311
1312    fn with_eig<R>(&self, f: impl FnOnce(&Eig) -> R) -> Result<R, Stop> {
1313        if self.cache.borrow().is_none() {
1314            let (n, npt) = (self.n, self.npt());
1315            let scale = self.xpt.iter().map(|p| norm(p)).fold(EPS, f64::max);
1316            let xs: Vec<V> = self.xpt.iter().map(|p| p.iter().map(|v| v / scale).collect()).collect();
1317            let dim = npt + n + 1;
1318            let mut a = Array2::<f64>::zeros((dim, dim));
1319            for i in 0..npt {
1320                for j in 0..npt {
1321                    let d = dot(&xs[i], &xs[j]);
1322                    a[[i, j]] = 0.5 * d * d;
1323                }
1324                a[[i, npt]] = 1.0;
1325                a[[npt, i]] = 1.0;
1326                for r in 0..n {
1327                    a[[i, npt + 1 + r]] = xs[i][r];
1328                    a[[npt + 1 + r, i]] = xs[i][r];
1329                }
1330            }
1331            if a.iter().any(|v| !v.is_finite()) {
1332                return Err(Stop::LinAlg);
1333            }
1334            let (values, vecs) = a.eigh(UPLO::Lower).map_err(|_| Stop::LinAlg)?;
1335            let vectors: Vec<V> = (0..dim).map(|j| (0..dim).map(|i| vecs[[i, j]]).collect()).collect();
1336            let mut right_scaling = vec![0.0; dim];
1337            for k in 0..npt {
1338                right_scaling[k] = 1.0 / (scale * scale);
1339            }
1340            right_scaling[npt] = scale * scale;
1341            for r in 0..n {
1342                right_scaling[npt + 1 + r] = scale;
1343            }
1344            *self.cache.borrow_mut() = Some(Eig { values: values.to_vec(), vectors, right_scaling });
1345        }
1346        let guard = self.cache.borrow();
1347        Ok(f(guard.as_ref().unwrap()))
1348    }
1349
1350    /// Solves the interpolation system for the right-hand side `rhs` (length `npt + n + 1`); the flag
1351    /// reports an (effectively) singular system.
1352    fn solve(&self, rhs: &[f64]) -> Result<(V, bool), Stop> {
1353        self.with_eig(|e| {
1354            let scaled_rhs: V = rhs.iter().zip(&e.right_scaling).map(|(r, s)| r * s).collect();
1355            if scaled_rhs.iter().any(|v| !v.is_finite()) {
1356                return Err(Stop::LinAlg);
1357            }
1358            let dim = rhs.len();
1359            let mut out = vec![0.0; dim];
1360            let mut ill = false;
1361            for (lam, vec) in e.values.iter().zip(&e.vectors) {
1362                if lam.abs() > EPS {
1363                    let c = dot(vec, &scaled_rhs) / lam;
1364                    axpy(&mut out, c, vec);
1365                } else {
1366                    ill = true;
1367                }
1368            }
1369            for (o, s) in out.iter_mut().zip(&e.right_scaling) {
1370                *o *= s;
1371            }
1372            Ok((out, ill))
1373        })?
1374    }
1375}
1376
1377#[derive(Clone)]
1378struct Quad {
1379    c: f64,
1380    g: V,
1381    /// Coefficients of the implicit part of the Hessian, `Σ ih[k] xpt_k xpt_kᵀ`.
1382    ih: V,
1383    /// The explicit part of the Hessian.
1384    eh: M,
1385}
1386
1387impl Quad {
1388    fn from_values(ip: &Interp, values: &[f64]) -> Result<Quad, Stop> {
1389        let (c, g, ih, _) = Quad::model(ip, values)?;
1390        Ok(Quad { c, g, ih, eh: vec![vec![0.0; ip.n]; ip.n] })
1391    }
1392
1393    fn model(ip: &Interp, values: &[f64]) -> Result<(f64, V, V, bool), Stop> {
1394        let (n, npt) = (ip.n, ip.npt());
1395        let mut rhs = values.to_vec();
1396        rhs.extend(std::iter::repeat_n(0.0, n + 1));
1397        let (x, ill) = ip.solve(&rhs)?;
1398        Ok((x[npt], x[npt + 1..].to_vec(), x[..npt].to_vec(), ill))
1399    }
1400
1401    fn value(&self, x: &[f64], ip: &Interp) -> f64 {
1402        let d = sub(x, &ip.x_base);
1403        let implicit: f64 = ip.xpt.iter().zip(&self.ih).map(|(p, h)| h * dot(p, &d).powi(2)).sum();
1404        let explicit = dot(&d, &matvec(&self.eh, &d));
1405        self.c + dot(&self.g, &d) + 0.5 * (implicit + explicit)
1406    }
1407
1408    fn hess_prod(&self, v: &[f64], ip: &Interp) -> V {
1409        let mut out = matvec(&self.eh, v);
1410        for (p, h) in ip.xpt.iter().zip(&self.ih) {
1411            axpy(&mut out, h * dot(p, v), p);
1412        }
1413        out
1414    }
1415
1416    fn grad(&self, x: &[f64], ip: &Interp) -> V {
1417        let d = sub(x, &ip.x_base);
1418        add(&self.g, &self.hess_prod(&d, ip))
1419    }
1420
1421    fn curv(&self, v: &[f64], ip: &Interp) -> f64 {
1422        dot(v, &matvec(&self.eh, v)) + ip.xpt.iter().zip(&self.ih).map(|(p, h)| h * dot(p, v).powi(2)).sum::<f64>()
1423    }
1424
1425    /// The change of the model when point `k_new` (previously in direction `dir_old`) is replaced and the
1426    /// values change by `values_diff`; the interpolation set already holds the new point.
1427    fn update(&mut self, ip: &Interp, k_new: usize, dir_old: &[f64], values_diff: &[f64]) -> Result<bool, Stop> {
1428        let n = ip.n;
1429        for i in 0..n {
1430            for j in 0..n {
1431                self.eh[i][j] += self.ih[k_new] * dir_old[i] * dir_old[j];
1432            }
1433        }
1434        self.ih[k_new] = 0.0;
1435        let (c, g, ih, ill) = Quad::model(ip, values_diff)?;
1436        self.c += c;
1437        axpy(&mut self.g, 1.0, &g);
1438        axpy(&mut self.ih, 1.0, &ih);
1439        Ok(ill)
1440    }
1441
1442    fn shift_x_base(&mut self, ip: &Interp, new_base: &[f64]) {
1443        let n = ip.n;
1444        self.c = self.value(new_base, ip);
1445        self.g = self.grad(new_base, ip);
1446        let shift = sub(new_base, &ip.x_base);
1447        let mut w = vec![0.0; n];
1448        for (p, h) in ip.xpt.iter().zip(&self.ih) {
1449            for i in 0..n {
1450                w[i] += h * (p[i] - 0.5 * shift[i]);
1451            }
1452        }
1453        for i in 0..n {
1454            for j in 0..n {
1455                self.eh[i][j] += shift[i] * w[j] + w[i] * shift[j];
1456            }
1457        }
1458    }
1459}
1460
1461struct Models {
1462    ip: Interp,
1463    fun_val: V,
1464    /// `cub_val[k]` is the vector of inequality values at point `k`.
1465    cub_val: Vec<V>,
1466    ceq_val: Vec<V>,
1467    fun: Quad,
1468    cub: Vec<Quad>,
1469    ceq: Vec<Quad>,
1470}
1471
1472impl Models {
1473    fn m_ub(&self) -> usize {
1474        self.cub.len()
1475    }
1476
1477    fn m_eq(&self) -> usize {
1478        self.ceq.len()
1479    }
1480
1481    fn cub_at(&self, x: &[f64]) -> V {
1482        self.cub.iter().map(|q| q.value(x, &self.ip)).collect()
1483    }
1484
1485    fn ceq_at(&self, x: &[f64]) -> V {
1486        self.ceq.iter().map(|q| q.value(x, &self.ip)).collect()
1487    }
1488
1489    fn reset(&mut self) -> Result<(), Stop> {
1490        self.fun = Quad::from_values(&self.ip, &self.fun_val)?;
1491        for i in 0..self.cub.len() {
1492            let col: V = self.cub_val.iter().map(|r| r[i]).collect();
1493            self.cub[i] = Quad::from_values(&self.ip, &col)?;
1494        }
1495        for i in 0..self.ceq.len() {
1496            let col: V = self.ceq_val.iter().map(|r| r[i]).collect();
1497            self.ceq[i] = Quad::from_values(&self.ip, &col)?;
1498        }
1499        Ok(())
1500    }
1501
1502    fn update_interpolation(&mut self, k_new: usize, x_new: &[f64], fun_val: f64, cub_val: &[f64], ceq_val: &[f64]) -> Result<bool, Stop> {
1503        let npt = self.ip.npt();
1504        let mut fun_diff = vec![0.0; npt];
1505        fun_diff[k_new] = fun_val - self.fun.value(x_new, &self.ip);
1506        let cub_old = self.cub_at(x_new);
1507        let ceq_old = self.ceq_at(x_new);
1508        self.fun_val[k_new] = fun_val;
1509        self.cub_val[k_new] = cub_val.to_vec();
1510        self.ceq_val[k_new] = ceq_val.to_vec();
1511        let dir_old = self.ip.xpt[k_new].clone();
1512        self.ip.xpt[k_new] = sub(x_new, &self.ip.x_base);
1513        self.ip.invalidate();
1514        let mut ill = self.fun.update(&self.ip, k_new, &dir_old, &fun_diff)?;
1515        for i in 0..self.cub.len() {
1516            let mut d = vec![0.0; npt];
1517            d[k_new] = cub_val[i] - cub_old[i];
1518            let u = self.cub[i].update(&self.ip, k_new, &dir_old, &d)?;
1519            ill = ill || u;
1520        }
1521        for i in 0..self.ceq.len() {
1522            let mut d = vec![0.0; npt];
1523            d[k_new] = ceq_val[i] - ceq_old[i];
1524            let u = self.ceq[i].update(&self.ip, k_new, &dir_old, &d)?;
1525            ill = ill || u;
1526        }
1527        Ok(ill)
1528    }
1529
1530    /// The determinants (Lagrange-polynomial based) used to choose the point to drop: for `k_new = None` all
1531    /// of them, otherwise only the one of that point.
1532    fn determinants(&self, x_new: &[f64], k_new: Option<usize>) -> Result<V, Stop> {
1533        let (n, npt) = (self.ip.n, self.ip.npt());
1534        let shift = sub(x_new, &self.ip.x_base);
1535        let mut new_col = vec![0.0; npt + n + 1];
1536        for k in 0..npt {
1537            new_col[k] = 0.5 * dot(&self.ip.xpt[k], &shift).powi(2);
1538        }
1539        new_col[npt] = 1.0;
1540        new_col[npt + 1..].copy_from_slice(&shift);
1541        let (inv_new_col, _) = self.ip.solve(&new_col)?;
1542        let beta = 0.5 * dot(&shift, &shift).powi(2) - dot(&new_col, &inv_new_col);
1543        let coord = |k: usize| -> Result<f64, Stop> {
1544            let mut e = vec![0.0; npt + n + 1];
1545            e[k] = 1.0;
1546            Ok(self.ip.solve(&e)?.0[k])
1547        };
1548        match k_new {
1549            None => (0..npt).map(|k| Ok(coord(k)? * beta + inv_new_col[k].powi(2))).collect(),
1550            Some(k) => Ok(vec![coord(k)? * beta + inv_new_col[k].powi(2)]),
1551        }
1552    }
1553
1554    fn shift_x_base(&mut self, new_base: &[f64]) {
1555        let ip = &self.ip;
1556        self.fun.shift_x_base(ip, new_base);
1557        for q in self.cub.iter_mut().chain(self.ceq.iter_mut()) {
1558            q.shift_x_base(ip, new_base);
1559        }
1560        let shift = sub(new_base, &self.ip.x_base);
1561        self.ip.x_base = add(&self.ip.x_base, &shift);
1562        for p in self.ip.xpt.iter_mut() {
1563            *p = sub(p, &shift);
1564        }
1565        self.ip.invalidate();
1566    }
1567}
1568
1569// ---------------------------------------------------------------------------------------------
1570// The problem as the framework sees it
1571// ---------------------------------------------------------------------------------------------
1572
1573type Callback<'a> = Box<dyn FnMut(&[f64]) -> bool + 'a>;
1574
1575/// A callback for [`cobyqa_with`]: it receives the best point and returns `true` to stop.
1576pub type StopCallback<'a> = &'a mut dyn FnMut(&[f64]) -> bool;
1577
1578struct Pb<'a, P: ConstrainedProblem> {
1579    p: &'a P,
1580    lin: &'a Lin,
1581    x0: V,
1582    n_eval: usize,
1583    feasibility_tol: f64,
1584    // The filter of non-dominated evaluations (for the result).
1585    fun_filter: V,
1586    maxcv_filter: V,
1587    x_filter: Vec<V>,
1588    filter_size: usize,
1589    store_history: bool,
1590    history_size: usize,
1591    fun_history: V,
1592    maxcv_history: V,
1593    callback: Option<Callback<'a>>,
1594}
1595
1596/// The linear constraints of the reduced problem.
1597#[derive(Clone, Debug, Default)]
1598struct Lin {
1599    a_ub: Vec<V>,
1600    b_ub: V,
1601    a_eq: Vec<V>,
1602    b_eq: V,
1603}
1604
1605/// The violations of every constraint (linear and nonlinear) at `x`.
1606fn violation_vec(lin: &Lin, x: &[f64], cub: &[f64], ceq: &[f64]) -> V {
1607    let mut v: V = lin.a_ub.iter().zip(&lin.b_ub).map(|(r, b)| (dot(r, x) - b).max(0.0)).collect();
1608    v.extend(lin.a_eq.iter().zip(&lin.b_eq).map(|(r, b)| (dot(r, x) - b).abs()));
1609    v.extend(cub.iter().map(|c| c.max(0.0)));
1610    v.extend(ceq.iter().map(|c| c.abs()));
1611    v
1612}
1613
1614fn maxcv_of(lin: &Lin, x: &[f64], cub: &[f64], ceq: &[f64]) -> f64 {
1615    violation_vec(lin, x, cub, ceq).into_iter().fold(0.0, f64::max)
1616}
1617
1618impl<P: ConstrainedProblem> Pb<'_, P> {
1619    fn eval(&mut self, x: &[f64], penalty: f64) -> Result<(f64, V, V), Stop> {
1620        let f = self.p.objective(x);
1621        let cub = self.p.inequalities(x);
1622        let ceq = self.p.equalities(x);
1623        self.n_eval += 1;
1624        let maxcv = maxcv_of(self.lin, x, &cub, &ceq);
1625        if self.store_history {
1626            self.fun_history.push(f);
1627            self.maxcv_history.push(maxcv);
1628            if self.fun_history.len() > self.history_size {
1629                self.fun_history.remove(0);
1630                self.maxcv_history.remove(0);
1631            }
1632        }
1633        let include = if f.is_nan() && maxcv.is_nan() {
1634            self.fun_filter.is_empty()
1635        } else if f.is_nan() {
1636            self.fun_filter.iter().zip(&self.maxcv_filter).all(|(ff, mf)| (ff.is_nan() && maxcv < *mf) || mf.is_nan())
1637        } else if maxcv.is_nan() {
1638            self.fun_filter.iter().zip(&self.maxcv_filter).all(|(ff, mf)| (mf.is_nan() && f < *ff) || ff.is_nan())
1639        } else {
1640            self.fun_filter.iter().zip(&self.maxcv_filter).all(|(ff, mf)| f < *ff || maxcv < *mf)
1641        };
1642        if include {
1643            self.fun_filter.push(f);
1644            self.maxcv_filter.push(maxcv);
1645            self.x_filter.push(x.to_vec());
1646            let last = self.fun_filter.len() - 1;
1647            for k in (0..last).rev() {
1648                let remove = if f.is_nan() {
1649                    self.fun_filter[k].is_nan()
1650                } else if maxcv.is_nan() {
1651                    self.maxcv_filter[k].is_nan()
1652                } else {
1653                    self.fun_filter[k].is_nan() || self.maxcv_filter[k].is_nan() || (f <= self.fun_filter[k] && maxcv <= self.maxcv_filter[k])
1654                };
1655                if remove {
1656                    self.fun_filter.remove(k);
1657                    self.maxcv_filter.remove(k);
1658                    self.x_filter.remove(k);
1659                }
1660            }
1661            if self.fun_filter.len() > self.filter_size {
1662                self.fun_filter.remove(0);
1663                self.maxcv_filter.remove(0);
1664                self.x_filter.remove(0);
1665            }
1666        }
1667        if self.callback.is_some() {
1668            let (xb, _, _) = self.best_eval(penalty);
1669            if self.callback.as_mut().is_some_and(|cb| cb(&xb)) {
1670                return Err(Stop::Callback);
1671            }
1672        }
1673        let clipf = |v: f64| if v.is_nan() { BARRIER } else { v.clamp(-BARRIER, BARRIER) };
1674        Ok((clipf(f), cub.iter().map(|&v| clipf(v)).collect(), ceq.iter().map(|&v| clipf(v)).collect()))
1675    }
1676
1677    fn best_eval(&mut self, penalty: f64) -> (V, f64, f64) {
1678        if self.fun_filter.is_empty() {
1679            let x0 = self.x0.clone();
1680            let _ = self.eval(&x0, 0.0);
1681        }
1682        let ff = &self.fun_filter;
1683        let mf = &self.maxcv_filter;
1684        let finite: Vec<bool> = mf.iter().map(|v| v.is_finite()).collect();
1685        let nanmin = |v: &[f64]| v.iter().cloned().filter(|x| !x.is_nan()).fold(f64::INFINITY, f64::min);
1686        let last = |idx: &[usize]| *idx.last().unwrap();
1687        let i;
1688        if finite.iter().any(|&b| b) {
1689            let feasible: Vec<bool> = mf.iter().map(|v| *v <= self.feasibility_tol).collect();
1690            let feas_idx: Vec<usize> = (0..ff.len()).filter(|&k| feasible[k]).collect();
1691            if !feas_idx.is_empty() && feas_idx.iter().any(|&k| !ff[k].is_nan()) {
1692                let fmin = nanmin(&feas_idx.iter().map(|&k| ff[k]).collect::<Vec<_>>());
1693                let mut idx: Vec<usize> = feas_idx.iter().cloned().filter(|&k| ff[k] <= fmin).collect();
1694                if idx.len() > 1 {
1695                    let cmin = idx.iter().map(|&k| mf[k]).fold(f64::INFINITY, f64::min);
1696                    idx.retain(|&k| mf[k] <= cmin);
1697                }
1698                i = last(&idx);
1699            } else if !feas_idx.is_empty() {
1700                i = last(&feas_idx);
1701            } else {
1702                let merit: V = (0..ff.len()).map(|k| if finite[k] { ff[k] + penalty * mf[k] } else { f64::NAN }).collect();
1703                if merit.iter().all(|v| v.is_nan()) {
1704                    let mmin = nanmin(mf);
1705                    let idx: Vec<usize> = (0..ff.len()).filter(|&k| mf[k] <= mmin).collect();
1706                    i = last(&idx);
1707                } else {
1708                    let mmin = nanmin(&merit);
1709                    let mut idx: Vec<usize> = (0..ff.len()).filter(|&k| merit[k] <= mmin).collect();
1710                    if idx.len() > 1 {
1711                        let cmin = idx.iter().map(|&k| mf[k]).fold(f64::INFINITY, f64::min);
1712                        idx.retain(|&k| mf[k] <= cmin);
1713                    }
1714                    if idx.len() > 1 {
1715                        let fmin = idx.iter().map(|&k| ff[k]).fold(f64::INFINITY, f64::min);
1716                        idx.retain(|&k| ff[k] <= fmin);
1717                    }
1718                    i = last(&idx);
1719                }
1720            }
1721        } else if !ff.iter().all(|v| v.is_nan()) {
1722            let fmin = nanmin(ff);
1723            let idx: Vec<usize> = (0..ff.len()).filter(|&k| ff[k] <= fmin).collect();
1724            i = last(&idx);
1725        } else {
1726            i = ff.len() - 1;
1727        }
1728        (self.x_filter[i].clone(), ff[i], mf[i])
1729    }
1730}
1731
1732// ---------------------------------------------------------------------------------------------
1733// The trust-region framework
1734// ---------------------------------------------------------------------------------------------
1735
1736struct Tr {
1737    n: usize,
1738    xl: V,
1739    xu: V,
1740    constrained: bool,
1741    nonlinear: bool,
1742    c: CobyqaConstants,
1743    lin: Lin,
1744    models: Models,
1745    penalty: f64,
1746    best_index: usize,
1747    lm_ub: V,
1748    lm_eq: V,
1749    lm_lin_ub: V,
1750    lm_lin_eq: V,
1751    resolution: f64,
1752    radius: f64,
1753}
1754
1755impl Tr {
1756    fn x_best(&self) -> V {
1757        self.models.ip.point(self.best_index)
1758    }
1759
1760    fn fun_best(&self) -> f64 {
1761        self.models.fun_val[self.best_index]
1762    }
1763
1764    fn cub_best(&self) -> &V {
1765        &self.models.cub_val[self.best_index]
1766    }
1767
1768    fn ceq_best(&self) -> &V {
1769        &self.models.ceq_val[self.best_index]
1770    }
1771
1772    fn set_radius(&mut self, r: f64) {
1773        self.radius = r;
1774        if self.radius <= self.c.decrease_radius_threshold * self.resolution {
1775            self.radius = self.resolution;
1776        }
1777    }
1778
1779    fn lag_hess_prod(&self, v: &[f64]) -> V {
1780        let ip = &self.models.ip;
1781        let mut out = self.models.fun.hess_prod(v, ip);
1782        for (q, l) in self.models.cub.iter().zip(&self.lm_ub) {
1783            axpy(&mut out, *l, &q.hess_prod(v, ip));
1784        }
1785        for (q, l) in self.models.ceq.iter().zip(&self.lm_eq) {
1786            axpy(&mut out, *l, &q.hess_prod(v, ip));
1787        }
1788        out
1789    }
1790
1791    fn sqp_fun(&self, step: &[f64]) -> f64 {
1792        let xb = self.x_best();
1793        let g = self.models.fun.grad(&xb, &self.models.ip);
1794        dot(step, &add(&g, &scaled(&self.lag_hess_prod(step), 0.5)))
1795    }
1796
1797    fn sqp_cub(&self, step: &[f64]) -> V {
1798        let xb = self.x_best();
1799        let ip = &self.models.ip;
1800        self.models.cub.iter().map(|q| q.value(&xb, ip) + dot(&q.grad(&xb, ip), step)).collect()
1801    }
1802
1803    fn sqp_ceq(&self, step: &[f64]) -> V {
1804        let xb = self.x_best();
1805        let ip = &self.models.ip;
1806        self.models.ceq.iter().map(|q| q.value(&xb, ip) + dot(&q.grad(&xb, ip), step)).collect()
1807    }
1808
1809    fn merit_vals(&self, x: &[f64], fun_val: f64, cub: &[f64], ceq: &[f64]) -> f64 {
1810        let mut m = fun_val;
1811        if self.penalty > 0.0 {
1812            let c = violation_vec(&self.lin, x, cub, ceq);
1813            if c.iter().any(|&v| v != 0.0) {
1814                m += self.penalty * norm(&c);
1815            }
1816        }
1817        m
1818    }
1819
1820    /// The linearised constraints at `x_best`: `aub s ≤ bub`, `aeq s = beq`.
1821    fn linearizations(&self) -> (Vec<V>, V, Vec<V>, V) {
1822        let xb = self.x_best();
1823        let ip = &self.models.ip;
1824        let mut aub: Vec<V> = self.lin.a_ub.clone();
1825        let mut bub: V = self.lin.a_ub.iter().zip(&self.lin.b_ub).map(|(r, b)| b - dot(r, &xb)).collect();
1826        aub.extend(self.models.cub.iter().map(|q| q.grad(&xb, ip)));
1827        bub.extend(self.models.cub.iter().map(|q| -q.value(&xb, ip)));
1828        let mut aeq: Vec<V> = self.lin.a_eq.clone();
1829        let mut beq: V = self.lin.a_eq.iter().zip(&self.lin.b_eq).map(|(r, b)| b - dot(r, &xb)).collect();
1830        aeq.extend(self.models.ceq.iter().map(|q| q.grad(&xb, ip)));
1831        beq.extend(self.models.ceq.iter().map(|q| -q.value(&xb, ip)));
1832        (aub, bub, aeq, beq)
1833    }
1834
1835    fn trust_region_step(&self) -> (V, V) {
1836        let (aub, mut bub, aeq, beq) = self.linearizations();
1837        let xb = self.x_best();
1838        let mut xl = sub(&self.xl, &xb);
1839        let mut xu = sub(&self.xu, &xb);
1840        let radius = self.c.byrd_omojokun_factor * self.radius;
1841        let ns = normal_step(&aub, &bub, &aeq, &beq, &xl, &xu, radius, self.c.improve_tcg);
1842        let radius = (self.radius * self.radius - dot(&ns, &ns)).max(0.0).sqrt();
1843        xl = sub(&xl, &ns);
1844        xu = sub(&xu, &ns);
1845        for (b, r) in bub.iter_mut().zip(&aub) {
1846            *b = (*b - dot(r, &ns)).max(0.0);
1847        }
1848        let g_best = add(&self.models.fun.grad(&xb, &self.models.ip), &self.lag_hess_prod(&ns));
1849        let hp = |v: &[f64]| self.lag_hess_prod(v);
1850        let ts = if !self.constrained { tangential_bound(&g_best, &hp, &xl, &xu, radius, self.c.improve_tcg) } else { tangential_constrained(&g_best, &hp, &xl, &xu, &aub, &bub, &aeq, radius, self.c.improve_tcg) };
1851        (ns, ts)
1852    }
1853
1854    fn geometry_step(&self, k_new: usize) -> Result<V, Stop> {
1855        let ip = &self.models.ip;
1856        let npt = ip.npt();
1857        let mut coord = vec![0.0; npt];
1858        coord[k_new] = 1.0;
1859        let lag = Quad::from_values(ip, &coord)?;
1860        let xb = self.x_best();
1861        let g_lag = lag.grad(&xb, ip);
1862        let xl = sub(&self.xl, &xb);
1863        let xu = sub(&self.xu, &xb);
1864        let curv = |v: &[f64]| lag.curv(v, ip);
1865        let mut step = cauchy_geometry(0.0, &g_lag, &curv, &xl, &xu, self.radius);
1866        let mut sigma = self.models.determinants(&add(&xb, &step), Some(k_new))?[0];
1867        // The directions from the best point to the other interpolation points.
1868        let dirs: Vec<V> = (0..npt).filter(|&k| k != self.best_index).map(|k| sub(&ip.xpt[k], &ip.xpt[self.best_index])).collect();
1869        // SciPy swaps the columns 0 and best_index before dropping the first: the best point's slot is
1870        // taken by point 0.
1871        let dirs: Vec<V> = if self.best_index == 0 {
1872            dirs
1873        } else {
1874            let mut order: Vec<usize> = (0..npt).collect();
1875            order.swap(0, self.best_index);
1876            order[1..].iter().map(|&k| sub(&ip.xpt[k], &ip.xpt[self.best_index])).collect()
1877        };
1878        let step_alt = spider_geometry(0.0, &g_lag, &curv, &dirs, &xl, &xu, self.radius);
1879        let sigma_alt = self.models.determinants(&add(&xb, &step_alt), Some(k_new))?[0];
1880        if sigma_alt.abs() > sigma.abs() {
1881            step = step_alt;
1882            sigma = sigma_alt;
1883        }
1884        if self.constrained {
1885            let (aub, bub, aeq, beq) = self.linearizations();
1886            let n = self.n;
1887            let tol_bd = get_arrays_tol(&[&xl, &xu]);
1888            let tol_ub = get_arrays_tol(&[&bub]);
1889            let free_xl: Vec<bool> = xl.iter().map(|&v| v <= -tol_bd).collect();
1890            let free_xu: Vec<bool> = xu.iter().map(|&v| v >= tol_bd).collect();
1891            let free_ub: Vec<bool> = bub.iter().map(|&v| v >= tol_ub).collect();
1892            let (n_act, q) = qr_tangential(&aub, &aeq, &free_xl, &free_xu, &free_ub);
1893            let g_proj = project_free(&q, n_act, &g_lag);
1894            let norm_proj = norm(&g_proj);
1895            if 0 < n_act && n_act < n && norm_proj > TINY * self.radius {
1896                let mut step_alt = scaled(&g_proj, self.radius / norm_proj);
1897                if lag.curv(&step_alt, ip) < 0.0 {
1898                    step_alt = step_alt.iter().map(|v| -v).collect();
1899                }
1900                let cbd_max = (0..n).map(|i| (xl[i] - step_alt[i]).max(step_alt[i] - xu[i])).fold(0.0f64, f64::max);
1901                let cub_max = (0..aub.len()).map(|i| dot(&aub[i], &step_alt) - bub[i]).fold(0.0f64, f64::max);
1902                let ceq_max = (0..aeq.len()).map(|i| (dot(&aeq[i], &step_alt) - beq[i]).abs()).fold(0.0f64, f64::max);
1903                let maxcv_val = cbd_max.max(cub_max).max(ceq_max);
1904                let mut tol = 0.0f64;
1905                for i in 0..n {
1906                    if !free_xl[i] || !free_xu[i] {
1907                        tol = tol.max(step_alt[i].abs());
1908                    }
1909                }
1910                for (i, r) in aub.iter().enumerate() {
1911                    if !free_ub[i] {
1912                        tol = tol.max(dot(r, &step_alt).abs());
1913                    }
1914                }
1915                let tol = (10.0 * tol).min(0.01 * norm(&step_alt));
1916                if maxcv_val <= tol {
1917                    let sigma_alt = self.models.determinants(&add(&xb, &step_alt), Some(k_new))?[0];
1918                    if sigma_alt.abs() >= 0.1 * sigma.abs() {
1919                        step = clip(&step_alt, &xl, &xu);
1920                    }
1921                }
1922            }
1923        }
1924        Ok(step)
1925    }
1926
1927    fn second_order_correction(&self, step: &[f64]) -> V {
1928        let (aub, bub, aeq, beq) = self.linearizations();
1929        let xb = self.x_best();
1930        let xl = sub(&self.xl, &xb);
1931        let xu = sub(&self.xu, &xb);
1932        normal_step(&aub, &bub, &aeq, &beq, &xl, &xu, norm(step), self.c.improve_tcg)
1933    }
1934
1935    fn reduction_ratio(&self, step: &[f64], fun_val: f64, cub: &[f64], ceq: &[f64]) -> f64 {
1936        let xb = self.x_best();
1937        let xn = add(&xb, step);
1938        let merit_old = self.merit_vals(&xb, self.fun_best(), self.cub_best(), self.ceq_best());
1939        let merit_new = self.merit_vals(&xn, fun_val, cub, ceq);
1940        let merit_model_old = self.merit_vals(&xb, 0.0, &self.models.cub_at(&xb), &self.models.ceq_at(&xb));
1941        let merit_model_new = self.merit_vals(&xn, self.sqp_fun(step), &self.sqp_cub(step), &self.sqp_ceq(step));
1942        if (merit_model_old - merit_model_new).abs() > TINY * (merit_old - merit_new).abs() { (merit_old - merit_new) / (merit_model_old - merit_model_new).abs() } else { -1.0 }
1943    }
1944
1945    /// Raises the penalty if the step would otherwise not be a descent step of the merit function; returns
1946    /// whether the best point stayed the same.
1947    fn increase_penalty(&mut self, step: &[f64]) -> bool {
1948        let (aub, bub, aeq, beq) = self.linearizations();
1949        let before: f64 = bub.iter().map(|v| (-v).max(0.0).powi(2)).sum::<f64>() + beq.iter().map(|v| v * v).sum::<f64>();
1950        let after: f64 = aub.iter().zip(&bub).map(|(r, b)| (dot(r, step) - b).max(0.0).powi(2)).sum::<f64>() + aeq.iter().zip(&beq).map(|(r, b)| (dot(r, step) - b).powi(2)).sum::<f64>();
1951        let viol_diff = (before.sqrt() - after.sqrt()).max(0.0);
1952        let sqp_val = self.sqp_fun(step);
1953        let mut threshold = (self.lm_lin_ub.iter().chain(&self.lm_lin_eq).chain(&self.lm_ub).chain(&self.lm_eq).map(|v| v * v).sum::<f64>()).sqrt();
1954        if viol_diff.abs() > TINY * sqp_val.abs() {
1955            threshold = threshold.max(sqp_val / viol_diff);
1956        }
1957        let best_save = self.best_index;
1958        if self.penalty <= self.c.penalty_increase_threshold * threshold {
1959            self.penalty = (self.c.penalty_increase_factor * threshold).max(1.0);
1960            self.set_best_index();
1961        }
1962        best_save == self.best_index
1963    }
1964
1965    fn decrease_penalty(&mut self) {
1966        self.penalty = self.penalty.min(self.low_penalty());
1967        self.set_best_index();
1968    }
1969
1970    fn set_best_index(&mut self) {
1971        let m = &self.models;
1972        let mut best = self.best_index;
1973        let mut m_best = self.merit_vals(&m.ip.point(best), m.fun_val[best], &m.cub_val[best], &m.ceq_val[best]);
1974        let mut r_best = maxcv_of(&self.lin, &m.ip.point(best), &m.cub_val[best], &m.ceq_val[best]);
1975        let tol = 10.0 * EPS * (m.ip.n.max(m.ip.npt()) as f64) * m_best.abs().max(1.0);
1976        for k in 0..m.ip.npt() {
1977            if k != self.best_index {
1978                let xk = m.ip.point(k);
1979                let m_val = self.merit_vals(&xk, m.fun_val[k], &m.cub_val[k], &m.ceq_val[k]);
1980                let r_val = maxcv_of(&self.lin, &xk, &m.cub_val[k], &m.ceq_val[k]);
1981                if m_val < m_best || (m_val < m_best + tol && r_val < r_best) {
1982                    best = k;
1983                    m_best = m_val;
1984                    r_best = r_val;
1985                }
1986            }
1987        }
1988        self.best_index = best;
1989    }
1990
1991    fn index_to_remove(&self, x_new: Option<&[f64]>) -> Result<(usize, f64), Stop> {
1992        let ip = &self.models.ip;
1993        let npt = ip.npt();
1994        let dist_sq: V = (0..npt).map(|k| sub(&ip.xpt[k], &ip.xpt[self.best_index]).iter().map(|v| v * v).sum()).collect();
1995        let (sigma, weights): (V, V) = match x_new {
1996            None => (vec![1.0; npt], dist_sq.clone()),
1997            Some(x) => {
1998                let sigma = self.models.determinants(x, None)?;
1999                let scale = (self.c.low_radius_factor * self.radius).max(self.resolution);
2000                let mut w: V = dist_sq.iter().map(|d| (d / (scale * scale)).max(1.0).powi(3)).collect();
2001                w[self.best_index] = -1.0;
2002                (sigma, w)
2003            }
2004        };
2005        let prod: V = (0..npt).map(|k| weights[k] * sigma[k].abs()).collect();
2006        let k_max = argmax_all(&prod)[0];
2007        Ok((k_max, dist_sq[k_max].sqrt()))
2008    }
2009
2010    fn update_radius(&mut self, step: &[f64], ratio: f64) {
2011        let s_norm = norm(step);
2012        if ratio <= self.c.low_ratio {
2013            self.set_radius(self.c.decrease_radius_factor * self.radius);
2014        } else if ratio <= self.c.high_ratio {
2015            self.set_radius((self.c.decrease_radius_factor * self.radius).max(s_norm));
2016        } else {
2017            self.set_radius((self.c.increase_radius_factor * self.radius).min((self.c.decrease_radius_factor * self.radius).max(self.c.increase_radius_threshold * s_norm)));
2018        }
2019    }
2020
2021    fn enhance_resolution(&mut self, rhoend: f64) {
2022        if self.c.large_resolution_threshold * rhoend < self.resolution {
2023            self.resolution *= self.c.decrease_resolution_factor;
2024        } else if self.c.moderate_resolution_threshold * rhoend < self.resolution {
2025            self.resolution = (self.resolution * rhoend).sqrt();
2026        } else {
2027            self.resolution = rhoend;
2028        }
2029        self.radius = (self.c.decrease_radius_factor * self.radius).max(self.resolution);
2030    }
2031
2032    fn set_multipliers(&mut self, x: &[f64]) {
2033        let ip = &self.models.ip;
2034        let n = self.n;
2035        let incl_lin_ub: Vec<bool> = self.lin.a_ub.iter().zip(&self.lin.b_ub).map(|(r, b)| dot(r, x) >= *b).collect();
2036        let incl_ub: Vec<bool> = self.cub_best().iter().map(|&v| v >= 0.0).collect();
2037        let incl_xl: Vec<bool> = (0..n).map(|i| self.xl[i] >= x[i]).collect();
2038        let incl_xu: Vec<bool> = (0..n).map(|i| self.xu[i] <= x[i]).collect();
2039        let m_lin_act = incl_lin_ub.iter().filter(|&&b| b).count();
2040        let m_ub_act = incl_ub.iter().filter(|&&b| b).count();
2041        let m_lin_eq = self.lin.a_eq.len();
2042        if m_lin_act + m_ub_act + m_lin_eq + self.models.m_eq() == 0 {
2043            return;
2044        }
2045        // Rows: the equalities (free multipliers) first, then the active bounds and inequalities (≥ 0).
2046        let mut rows: Vec<V> = self.lin.a_eq.clone();
2047        rows.extend(self.models.ceq.iter().map(|q| q.grad(x, ip)));
2048        let n_free = rows.len();
2049        let unit = |i: usize, s: f64| {
2050            let mut e = vec![0.0; n];
2051            e[i] = s;
2052            e
2053        };
2054        for i in 0..n {
2055            if incl_xl[i] {
2056                rows.push(unit(i, -1.0));
2057            }
2058        }
2059        for i in 0..n {
2060            if incl_xu[i] {
2061                rows.push(unit(i, 1.0));
2062            }
2063        }
2064        let n_bd = rows.len() - n_free;
2065        for (r, inc) in self.lin.a_ub.iter().zip(&incl_lin_ub) {
2066            if *inc {
2067                rows.push(r.clone());
2068            }
2069        }
2070        for (q, inc) in self.models.cub.iter().zip(&incl_ub) {
2071            if *inc {
2072                rows.push(q.grad(x, ip));
2073            }
2074        }
2075        let g = self.models.fun.grad(x, ip);
2076        // min ‖Cᵀy + g‖² subject to y ≥ 0 beyond the free ones: ½ yᵀ(2CCᵀ)y + 2(Cg)ᵀy.
2077        let k = rows.len();
2078        let mut mm: M = (0..k).map(|i| (0..k).map(|j| 2.0 * dot(&rows[i], &rows[j])).collect()).collect();
2079        let trace: f64 = (0..k).map(|i| mm[i][i]).sum::<f64>().max(1.0);
2080        for i in 0..k {
2081            mm[i][i] += 1e-13 * trace / k as f64;
2082        }
2083        let qq: V = rows.iter().map(|r| 2.0 * dot(r, &g)).collect();
2084        let Some(y) = bound_constrained_qp(&mm, &qq, n_free) else { return };
2085        let mut pos = n_free + n_bd;
2086        for (i, inc) in incl_lin_ub.iter().enumerate() {
2087            if *inc {
2088                self.lm_lin_ub[i] = y[pos];
2089                pos += 1;
2090            } else {
2091                self.lm_lin_ub[i] = 0.0;
2092            }
2093        }
2094        for (i, inc) in incl_ub.iter().enumerate() {
2095            if *inc {
2096                self.lm_ub[i] = y[pos];
2097                pos += 1;
2098            } else {
2099                self.lm_ub[i] = 0.0;
2100            }
2101        }
2102        self.lm_lin_eq.copy_from_slice(&y[..m_lin_eq]);
2103        self.lm_eq.copy_from_slice(&y[m_lin_eq..n_free]);
2104    }
2105
2106    fn low_penalty(&self) -> f64 {
2107        let m = &self.models;
2108        let npt = m.ip.npt();
2109        let (m_ub, m_eq) = (m.m_ub(), m.m_eq());
2110        let (l_ub, l_eq) = (self.lin.a_ub.len(), self.lin.a_eq.len());
2111        let ncol = l_ub + m_ub + 2 * l_eq + 2 * m_eq;
2112        if ncol == 0 {
2113            return 0.0;
2114        }
2115        // The columns: linear inequality residuals, nonlinear inequality values, then ± the linear and
2116        // nonlinear equality residuals.
2117        let points: Vec<V> = (0..npt).map(|k| m.ip.point(k)).collect();
2118        let col = |k: usize, c: usize| -> f64 {
2119            if c < l_ub {
2120                dot(&self.lin.a_ub[c], &points[k]) - self.lin.b_ub[c]
2121            } else if c < l_ub + m_ub {
2122                m.cub_val[k][c - l_ub]
2123            } else {
2124                let e = c - l_ub - m_ub;
2125                let (sign, e) = if e < l_eq + m_eq { (1.0, e) } else { (-1.0, e - l_eq - m_eq) };
2126                let v = if e < l_eq { dot(&self.lin.a_eq[e], &points[k]) - self.lin.b_eq[e] } else { m.ceq_val[k][e - l_eq] };
2127                sign * v
2128            }
2129        };
2130        let mut f_min = f64::INFINITY;
2131        let mut f_max = f64::NEG_INFINITY;
2132        for v in &m.fun_val {
2133            f_min = f_min.min(*v);
2134            f_max = f_max.max(*v);
2135        }
2136        let mut have = false;
2137        let mut c_diff = f64::INFINITY;
2138        for c in 0..ncol {
2139            let c_min = (0..npt).map(|k| col(k, c)).fold(f64::INFINITY, f64::min);
2140            let c_max = (0..npt).map(|k| col(k, c)).fold(f64::NEG_INFINITY, f64::max);
2141            if c_min < self.c.threshold_ratio_constraints * c_max {
2142                have = true;
2143                c_diff = c_diff.min(c_max - c_min.min(0.0));
2144            }
2145        }
2146        if !have {
2147            return 0.0;
2148        }
2149        if c_diff > TINY * (f_max - f_min) { (f_max - f_min) / c_diff } else { f64::INFINITY }
2150    }
2151}
2152
2153// ---------------------------------------------------------------------------------------------
2154// The driver
2155// ---------------------------------------------------------------------------------------------
2156
2157/// A problem with some variables fixed (equal bounds) and the rest scaled to the unit box when asked, seen as
2158/// a problem in the free, scaled variables: `x_orig[free] = shift + factor ∘ x`.
2159struct Reduced<'a, P: ConstrainedProblem> {
2160    p: &'a P,
2161    free: Vec<usize>,
2162    full: V,
2163    shift: V,
2164    factor: V,
2165}
2166
2167impl<P: ConstrainedProblem> Reduced<'_, P> {
2168    fn expand(&self, x: &[f64]) -> V {
2169        let mut f = self.full.clone();
2170        for (k, &i) in self.free.iter().enumerate() {
2171            f[i] = self.shift[k] + self.factor[k] * x[k];
2172        }
2173        f
2174    }
2175}
2176
2177impl<P: ConstrainedProblem> ConstrainedProblem for Reduced<'_, P> {
2178    fn objective(&self, x: &[f64]) -> f64 {
2179        self.p.objective(&self.expand(x))
2180    }
2181    fn equalities(&self, x: &[f64]) -> Vec<f64> {
2182        self.p.equalities(&self.expand(x))
2183    }
2184    fn inequalities(&self, x: &[f64]) -> Vec<f64> {
2185        self.p.inequalities(&self.expand(x))
2186    }
2187}
2188
2189fn build_result<P: ConstrainedProblem>(pb: &mut Pb<P>, penalty: f64, success: bool, status: CobyqaStatus, nit: usize, feas_tol: f64, full: &dyn Fn(&[f64]) -> V) -> CobyqaResult {
2190    let (x, fun, maxcv) = pb.best_eval(penalty);
2191    let mut ok = success && fun.is_finite() && maxcv.is_finite();
2192    if status != CobyqaStatus::TargetReached {
2193        ok = ok && maxcv <= feas_tol;
2194    }
2195    CobyqaResult { x: full(&x), fun, maxcv, nfev: pb.n_eval, nit, success: ok, status, fun_history: pb.fun_history.clone(), maxcv_history: pb.maxcv_history.clone() }
2196}
2197
2198// ANCHOR: cobyqa
2199/// Minimises `problem.objective` subject to the bounds `lower ≤ x ≤ upper` (`None`: unbounded) and to the
2200/// problem's `inequalities(x) ≤ 0` and `equalities(x) = 0`, without derivatives, by COBYQA (SciPy's
2201/// `minimize(method='COBYQA')`). The gradient and Jacobian methods of [`ConstrainedProblem`] are never
2202/// called. See [`cobyqa_with`] for linear constraints and a callback.
2203pub fn cobyqa<P: ConstrainedProblem>(problem: &P, x0: Vec<f64>, lower: Option<&[f64]>, upper: Option<&[f64]>, options: CobyqaOptions) -> Result<CobyqaResult, ErrorsJSL> {
2204    cobyqa_with(problem, x0, lower, upper, None, options, None)
2205}
2206
2207/// [`cobyqa`] with linear constraints, which are kept exact (their linearisations are the constraints
2208/// themselves, and they count in the merit function and the multipliers) instead of being modelled, and a
2209/// callback that receives the best point after every evaluation and stops the run by returning `true`
2210/// (status [`CobyqaStatus::CallbackStop`], a success).
2211pub fn cobyqa_with<P: ConstrainedProblem>(
2212    problem: &P,
2213    x0: Vec<f64>,
2214    lower: Option<&[f64]>,
2215    upper: Option<&[f64]>,
2216    linear: Option<&LinearConstraints>,
2217    options: CobyqaOptions,
2218    callback: Option<StopCallback<'_>>,
2219) -> Result<CobyqaResult, ErrorsJSL> {
2220    let n_orig = x0.len();
2221    if n_orig == 0 {
2222        return Err(ErrorsJSL::Misconfiguration("Initial parameters must be a non-empty vector."));
2223    }
2224    if x0.iter().any(|v| !v.is_finite()) {
2225        return Err(ErrorsJSL::InvalidInputRange("the initial point must be finite"));
2226    }
2227    options.constants.validate()?;
2228    let xl_full: V = lower.map_or(vec![f64::NEG_INFINITY; n_orig], |l| l.iter().map(|v| if v.is_nan() { f64::NEG_INFINITY } else { *v }).collect());
2229    let xu_full: V = upper.map_or(vec![f64::INFINITY; n_orig], |u| u.iter().map(|v| if v.is_nan() { f64::INFINITY } else { *v }).collect());
2230    if xl_full.len() != n_orig || xu_full.len() != n_orig {
2231        return Err(ErrorsJSL::IncompatibleArraySizes((xl_full.len().min(xu_full.len()), n_orig)));
2232    }
2233    if !(options.rhobeg > 0.0 && options.rhoend >= 0.0 && options.rhobeg >= options.rhoend) {
2234        return Err(ErrorsJSL::InvalidInputRange("need rhobeg > 0 and 0 ≤ rhoend ≤ rhobeg"));
2235    }
2236    let lin_in = linear.cloned().unwrap_or_default();
2237    if lin_in.a_ub.len() != lin_in.b_ub.len() || lin_in.a_eq.len() != lin_in.b_eq.len() || lin_in.a_ub.iter().chain(&lin_in.a_eq).any(|r| r.len() != n_orig) {
2238        return Err(ErrorsJSL::InvalidInputRange("linear constraints need rows of the problem's dimension and one bound per row"));
2239    }
2240    let bounds_feasible = (0..n_orig).all(|i| xl_full[i] <= xu_full[i] && xl_full[i] < f64::INFINITY && xu_full[i] > f64::NEG_INFINITY);
2241    // Fixed variables are removed.
2242    let tol = get_arrays_tol(&[&xl_full, &xu_full]);
2243    let fixed: Vec<bool> = (0..n_orig).map(|i| xl_full[i] <= xu_full[i] && (xl_full[i] - xu_full[i]).abs() < tol).collect();
2244    let free: Vec<usize> = (0..n_orig).filter(|&i| !fixed[i]).collect();
2245    let mut full = x0.clone();
2246    for i in 0..n_orig {
2247        if fixed[i] {
2248            full[i] = (0.5 * (xl_full[i] + xu_full[i])).clamp(xl_full[i], xu_full[i]);
2249        }
2250    }
2251    let n = free.len();
2252    let mut xl: V = free.iter().map(|&i| xl_full[i]).collect();
2253    let mut xu: V = free.iter().map(|&i| xu_full[i]).collect();
2254    let mut x0r: V = free.iter().map(|&i| x0[i]).collect();
2255    if bounds_feasible {
2256        x0r = clip(&x0r, &xl, &xu);
2257    }
2258    // The linear constraints in the free variables (the fixed ones move to the right-hand side), then scaled.
2259    let reduce = |rows: &[V], rhs: &[f64]| -> (Vec<V>, V) {
2260        let a: Vec<V> = rows.iter().map(|r| free.iter().map(|&i| r[i]).collect()).collect();
2261        let b: V = rows.iter().zip(rhs).map(|(r, b)| b - (0..n_orig).filter(|&i| fixed[i]).map(|i| r[i] * full[i]).sum::<f64>()).collect();
2262        (a, b)
2263    };
2264    let (mut a_ub, mut b_ub) = reduce(&lin_in.a_ub, &lin_in.b_ub);
2265    let (mut a_eq, mut b_eq) = reduce(&lin_in.a_eq, &lin_in.b_eq);
2266    let scale = options.scale && bounds_feasible && n > 0 && xl.iter().chain(&xu).all(|v| v.is_finite());
2267    let (shift, factor): (V, V) = if scale { ((0..n).map(|i| 0.5 * (xu[i] + xl[i])).collect(), (0..n).map(|i| 0.5 * (xu[i] - xl[i])).collect()) } else { (vec![0.0; n], vec![1.0; n]) };
2268    if scale {
2269        for (rows, rhs) in [(&mut a_ub, &mut b_ub), (&mut a_eq, &mut b_eq)] {
2270            for (r, b) in rows.iter_mut().zip(rhs.iter_mut()) {
2271                *b -= dot(r, &shift);
2272                for (v, f) in r.iter_mut().zip(&factor) {
2273                    *v *= f;
2274                }
2275            }
2276        }
2277        x0r = (0..n).map(|i| (x0r[i] - shift[i]) / factor[i]).collect();
2278        xl = vec![-1.0; n];
2279        xu = vec![1.0; n];
2280    }
2281    let lin = Lin { a_ub, b_ub, a_eq, b_eq };
2282    let reduced = Reduced { p: problem, free: free.clone(), full: full.clone(), shift, factor };
2283    let expand = |x: &[f64]| reduced.expand(x);
2284    let probe_x0 = if n == 0 { vec![] } else { x0r.clone() };
2285    let (m_ub, m_eq) = (problem.inequalities(&expand(&probe_x0)).len(), problem.equalities(&expand(&probe_x0)).len());
2286    let reduced_ref = &reduced;
2287    let cb = callback.map(|f| Box::new(move |xr: &[f64]| f(&reduced_ref.expand(xr))) as Callback<'_>);
2288    let mut pb = Pb {
2289        p: &reduced,
2290        lin: &lin,
2291        x0: x0r.clone(),
2292        n_eval: 0,
2293        feasibility_tol: options.feasibility_tol,
2294        fun_filter: Vec::new(),
2295        maxcv_filter: Vec::new(),
2296        x_filter: Vec::new(),
2297        filter_size: options.filter_size.unwrap_or(usize::MAX).max(1),
2298        store_history: options.store_history,
2299        history_size: options.history_size.unwrap_or(usize::MAX).max(1),
2300        fun_history: Vec::new(),
2301        maxcv_history: Vec::new(),
2302        callback: cb,
2303    };
2304    if !bounds_feasible {
2305        return Ok(build_result(&mut pb, 0.0, false, CobyqaStatus::InfeasibleBounds, 0, options.feasibility_tol, &expand));
2306    }
2307    if n == 0 {
2308        let _ = pb.eval(&[], 0.0);
2309        return Ok(build_result(&mut pb, 0.0, true, CobyqaStatus::AllFixed, 0, options.feasibility_tol, &expand));
2310    }
2311    let npt = options.npt.unwrap_or(2 * n + 1);
2312    if npt == 0 || npt > (n + 1) * (n + 2) / 2 || npt < n + 1 {
2313        return Err(ErrorsJSL::InvalidInputRange("npt must be between n + 1 and (n + 1)(n + 2)/2"));
2314    }
2315    let max_eval = options.max_evaluations.unwrap_or((500 * n).max(npt + 1));
2316    let max_iter = options.max_iterations.unwrap_or(1000 * n);
2317    let (mut rhobeg, mut rhoend) = (options.rhobeg, options.rhoend);
2318    // The interpolation set.
2319    let max_radius = 0.5 * (0..n).map(|i| xu[i] - xl[i]).fold(f64::INFINITY, f64::min);
2320    if rhobeg > max_radius {
2321        rhobeg = max_radius;
2322        rhoend = rhoend.min(max_radius);
2323    }
2324    let mut x_base = x0r.clone();
2325    let very_close_xl: Vec<bool> = (0..n).map(|i| x_base[i] <= xl[i] + 0.5 * rhobeg).collect();
2326    for i in 0..n {
2327        if very_close_xl[i] {
2328            x_base[i] = xl[i];
2329        }
2330    }
2331    for i in 0..n {
2332        if xl[i] + 0.5 * rhobeg < x_base[i] && x_base[i] <= xl[i] + rhobeg {
2333            x_base[i] = (xl[i] + rhobeg).min(xu[i]);
2334        }
2335    }
2336    let very_close_xu: Vec<bool> = (0..n).map(|i| x_base[i] >= xu[i] - 0.5 * rhobeg).collect();
2337    for i in 0..n {
2338        if very_close_xu[i] {
2339            x_base[i] = xu[i];
2340        }
2341    }
2342    for i in 0..n {
2343        if x_base[i] < xu[i] - 0.5 * rhobeg && xu[i] - rhobeg <= x_base[i] {
2344            x_base[i] = (xu[i] - rhobeg).max(xl[i]);
2345        }
2346    }
2347    let mut xpt: Vec<V> = vec![vec![0.0; n]; npt];
2348    for k in 1..npt {
2349        if k <= n {
2350            xpt[k][k - 1] = if very_close_xu[k - 1] { -rhobeg } else { rhobeg };
2351        } else if k <= 2 * n {
2352            let i = k - n - 1;
2353            xpt[k][i] = if very_close_xl[i] {
2354                2.0 * rhobeg
2355            } else if very_close_xu[i] {
2356                -2.0 * rhobeg
2357            } else {
2358                -rhobeg
2359            };
2360        } else {
2361            let spread = (k - n - 1) / n;
2362            let k1 = k - (1 + spread) * n - 1;
2363            let k2 = (k1 + spread) % n;
2364            xpt[k][k1] = xpt[k1 + 1][k1];
2365            xpt[k][k2] = xpt[k2 + 1][k2];
2366        }
2367    }
2368    let ip = Interp { n, x_base, xpt, cache: RefCell::new(None) };
2369    // Evaluate the interpolation points.
2370    let mut fun_val = vec![f64::NAN; npt];
2371    let mut cub_val: Vec<V> = vec![vec![]; npt];
2372    let mut ceq_val: Vec<V> = vec![vec![]; npt];
2373    let finish = |pb: &mut Pb<Reduced<P>>, success: bool, status: CobyqaStatus, nit: usize, penalty: f64| build_result(pb, penalty, success, status, nit, options.feasibility_tol, &expand);
2374    let c = options.constants;
2375    for k in 0..npt {
2376        if pb.n_eval >= max_eval {
2377            return Ok(finish(&mut pb, false, CobyqaStatus::MaxIterations, 0, 0.0));
2378        }
2379        let x = ip.point(k);
2380        let (f, cub, ceq) = match pb.eval(&x, 0.0) {
2381            Ok(v) => v,
2382            Err(_) => return Ok(finish(&mut pb, true, CobyqaStatus::CallbackStop, 0, 0.0)),
2383        };
2384        fun_val[k] = f;
2385        cub_val[k] = cub;
2386        ceq_val[k] = ceq;
2387        if f <= options.target && maxcv_of(&lin, &x, &cub_val[k], &ceq_val[k]) <= options.feasibility_tol {
2388            return Ok(finish(&mut pb, true, CobyqaStatus::TargetReached, 0, 0.0));
2389        }
2390    }
2391    let build = || -> Result<Models, Stop> {
2392        let fun = Quad::from_values(&ip, &fun_val)?;
2393        let cub: Result<Vec<Quad>, Stop> = (0..m_ub).map(|i| Quad::from_values(&ip, &cub_val.iter().map(|r| r[i]).collect::<Vec<_>>())).collect();
2394        let ceq: Result<Vec<Quad>, Stop> = (0..m_eq).map(|i| Quad::from_values(&ip, &ceq_val.iter().map(|r| r[i]).collect::<Vec<_>>())).collect();
2395        Ok(Models { ip: Interp { n, x_base: ip.x_base.clone(), xpt: ip.xpt.clone(), cache: RefCell::new(None) }, fun_val: fun_val.clone(), cub_val: cub_val.clone(), ceq_val: ceq_val.clone(), fun, cub: cub?, ceq: ceq? })
2396    };
2397    let models = match build() {
2398        Ok(m) => m,
2399        Err(_) => return Ok(finish(&mut pb, false, CobyqaStatus::LinearAlgebra, 0, 0.0)),
2400    };
2401    let nonlinear = m_ub + m_eq > 0;
2402    let constrained = nonlinear || !lin.a_ub.is_empty() || !lin.a_eq.is_empty();
2403    let (l_ub, l_eq) = (lin.a_ub.len(), lin.a_eq.len());
2404    let mut tr = Tr { n, xl: xl.clone(), xu: xu.clone(), constrained, nonlinear, c, lin: lin.clone(), models, penalty: 0.0, best_index: 0, lm_ub: vec![0.0; m_ub], lm_eq: vec![0.0; m_eq], lm_lin_ub: vec![0.0; l_ub], lm_lin_eq: vec![0.0; l_eq], resolution: rhobeg, radius: rhobeg };
2405    tr.set_best_index();
2406    let xb = tr.x_best();
2407    tr.set_multipliers(&xb);
2408
2409    let eval_step = |pb: &mut Pb<Reduced<P>>, tr: &Tr, step: &[f64]| -> Result<(f64, V, V), Stop> {
2410        if pb.n_eval >= max_eval {
2411            return Err(Stop::MaxEval);
2412        }
2413        let x_eval = add(&tr.x_best(), step);
2414        let (f, cub, ceq) = pb.eval(&x_eval, tr.penalty)?;
2415        if f <= options.target && maxcv_of(&tr.lin, &x_eval, &cub, &ceq) <= options.feasibility_tol {
2416            return Err(Stop::Target);
2417        }
2418        Ok((f, cub, ceq))
2419    };
2420    let stop_status = |s: &Stop| match s {
2421        Stop::Target => (true, CobyqaStatus::TargetReached),
2422        Stop::Callback => (true, CobyqaStatus::CallbackStop),
2423        Stop::MaxEval => (false, CobyqaStatus::MaxEvaluations),
2424        Stop::LinAlg => (false, CobyqaStatus::LinearAlgebra),
2425    };
2426
2427    let mut n_iter = 0;
2428    let mut n_short = 0;
2429    let mut n_very_short = 0;
2430    let mut n_alt = 0;
2431    let (success, status);
2432    'main: loop {
2433        if n_iter >= max_iter {
2434            status = CobyqaStatus::MaxIterations;
2435            success = false;
2436            break;
2437        }
2438        n_iter += 1;
2439        if norm(&sub(&tr.x_best(), &tr.models.ip.x_base)) >= tr.c.large_shift_factor * tr.radius {
2440            let xb = tr.x_best();
2441            tr.models.shift_x_base(&xb);
2442        }
2443        let radius_save = tr.radius;
2444        let (ns, ts) = tr.trust_region_step();
2445        let mut step = add(&ns, &ts);
2446        let s_norm = norm(&step);
2447        let mut k_new = 0usize;
2448        let (enhance, improve);
2449        if s_norm <= tr.c.short_step_threshold * tr.resolution {
2450            let r = tr.radius * tr.c.decrease_resolution_factor;
2451            tr.set_radius(r);
2452            if radius_save > tr.resolution {
2453                n_short = 0;
2454                n_very_short = 0;
2455            } else {
2456                n_short += 1;
2457                n_very_short += 1;
2458                if s_norm > 0.1 * tr.resolution {
2459                    n_very_short = 0;
2460                }
2461            }
2462            enhance = n_short >= 5 || n_very_short >= 3;
2463            if enhance {
2464                n_short = 0;
2465                n_very_short = 0;
2466                improve = false;
2467            } else {
2468                match tr.index_to_remove(None) {
2469                    Ok((k, dist)) => {
2470                        k_new = k;
2471                        improve = dist > tr.radius.max(tr.c.resolution_factor * tr.resolution);
2472                    }
2473                    Err(s) => {
2474                        (success, status) = stop_status(&s);
2475                        break 'main;
2476                    }
2477                }
2478            }
2479        } else {
2480            let same_best = tr.increase_penalty(&step);
2481            if same_best {
2482                let (mut f, mut cub, mut ceq) = match eval_step(&mut pb, &tr, &step) {
2483                    Ok(v) => v,
2484                    Err(s) => {
2485                        (success, status) = stop_status(&s);
2486                        break 'main;
2487                    }
2488                };
2489                let merit_old = tr.merit_vals(&tr.x_best(), tr.fun_best(), tr.cub_best(), tr.ceq_best());
2490                let merit_new = tr.merit_vals(&add(&tr.x_best(), &step), f, &cub, &ceq);
2491                if tr.nonlinear && merit_new > merit_old && norm(&ns) > tr.c.byrd_omojokun_factor * tr.c.byrd_omojokun_factor * tr.radius {
2492                    let soc = tr.second_order_correction(&step);
2493                    if norm(&soc) > 0.0 {
2494                        axpy(&mut step, 1.0, &soc);
2495                        match eval_step(&mut pb, &tr, &step) {
2496                            Ok(v) => (f, cub, ceq) = v,
2497                            Err(s) => {
2498                                (success, status) = stop_status(&s);
2499                                break 'main;
2500                            }
2501                        }
2502                    }
2503                }
2504                let ratio = tr.reduction_ratio(&step, f, &cub, &ceq);
2505                let x_new = add(&tr.x_best(), &step);
2506                let k = match tr.index_to_remove(Some(&x_new)) {
2507                    Ok((k, _)) => k,
2508                    Err(s) => {
2509                        (success, status) = stop_status(&s);
2510                        break 'main;
2511                    }
2512                };
2513                let ill = match tr.models.update_interpolation(k, &x_new, f, &cub, &ceq) {
2514                    Ok(v) => v,
2515                    Err(s) => {
2516                        (success, status) = stop_status(&s);
2517                        break 'main;
2518                    }
2519                };
2520                tr.set_best_index();
2521                tr.update_radius(&step, ratio);
2522                if tr.radius <= tr.resolution {
2523                    if ratio >= tr.c.very_low_ratio {
2524                        n_alt = 0;
2525                    } else {
2526                        n_alt += 1;
2527                        let xb = tr.x_best();
2528                        let grad = tr.models.fun.grad(&xb, &tr.models.ip);
2529                        let alt = match Quad::from_values(&tr.models.ip, &tr.models.fun_val) {
2530                            Ok(q) => q.grad(&xb, &tr.models.ip),
2531                            Err(s) => {
2532                                (success, status) = stop_status(&s);
2533                                break 'main;
2534                            }
2535                        };
2536                        if norm(&grad) < tr.c.large_gradient_factor * norm(&alt) {
2537                            n_alt = 0;
2538                        }
2539                        if n_alt >= 3 {
2540                            if let Err(s) = tr.models.reset() {
2541                                (success, status) = stop_status(&s);
2542                                break 'main;
2543                            }
2544                            n_alt = 0;
2545                        }
2546                    }
2547                }
2548                tr.set_multipliers(&x_new);
2549                match tr.index_to_remove(None) {
2550                    Ok((k2, dist)) => {
2551                        k_new = k2;
2552                        improve = ill || (ratio <= tr.c.low_ratio && dist > tr.radius.max(tr.c.resolution_factor * tr.resolution));
2553                    }
2554                    Err(s) => {
2555                        (success, status) = stop_status(&s);
2556                        break 'main;
2557                    }
2558                }
2559                enhance = radius_save <= tr.resolution && ratio <= tr.c.low_ratio && !improve;
2560            } else {
2561                enhance = false;
2562                improve = false;
2563            }
2564        }
2565        if enhance {
2566            if tr.resolution <= rhoend {
2567                success = true;
2568                status = CobyqaStatus::RadiusReached;
2569                break;
2570            }
2571            tr.enhance_resolution(rhoend);
2572            tr.decrease_penalty();
2573        }
2574        if improve {
2575            let step = match tr.geometry_step(k_new) {
2576                Ok(s) => s,
2577                Err(s) => {
2578                    (success, status) = stop_status(&s);
2579                    break 'main;
2580                }
2581            };
2582            let (f, cub, ceq) = match eval_step(&mut pb, &tr, &step) {
2583                Ok(v) => v,
2584                Err(s) => {
2585                    (success, status) = stop_status(&s);
2586                    break 'main;
2587                }
2588            };
2589            let x_new = add(&tr.x_best(), &step);
2590            if let Err(s) = tr.models.update_interpolation(k_new, &x_new, f, &cub, &ceq) {
2591                (success, status) = stop_status(&s);
2592                break 'main;
2593            }
2594            tr.set_best_index();
2595        }
2596    }
2597    Ok(finish(&mut pb, success, status, n_iter, tr.penalty))
2598}
2599// ANCHOR_END: cobyqa
2600
2601#[cfg(test)]
2602mod tests {
2603    use super::*;
2604
2605    struct Rosen;
2606    impl ConstrainedProblem for Rosen {
2607        fn objective(&self, x: &[f64]) -> f64 {
2608            100.0 * (x[1] - x[0] * x[0]).powi(2) + (1.0 - x[0]).powi(2)
2609        }
2610    }
2611
2612    struct Disc;
2613    impl ConstrainedProblem for Disc {
2614        fn objective(&self, x: &[f64]) -> f64 {
2615            Rosen.objective(x)
2616        }
2617        fn inequalities(&self, x: &[f64]) -> Vec<f64> {
2618            vec![x[0] * x[0] + x[1] * x[1] - 1.5]
2619        }
2620    }
2621
2622    struct Tutorial;
2623    impl ConstrainedProblem for Tutorial {
2624        fn objective(&self, x: &[f64]) -> f64 {
2625            x[0] * x[1]
2626        }
2627        fn inequalities(&self, x: &[f64]) -> Vec<f64> {
2628            vec![x[0] * x[0] + x[1] * x[1] - 1.0, -x[1]]
2629        }
2630    }
2631
2632    struct Hs071;
2633    impl ConstrainedProblem for Hs071 {
2634        fn objective(&self, x: &[f64]) -> f64 {
2635            x[0] * x[3] * (x[0] + x[1] + x[2]) + x[2]
2636        }
2637        fn inequalities(&self, x: &[f64]) -> Vec<f64> {
2638            vec![25.0 - x[0] * x[1] * x[2] * x[3]]
2639        }
2640        fn equalities(&self, x: &[f64]) -> Vec<f64> {
2641            vec![x.iter().map(|v| v * v).sum::<f64>() - 40.0]
2642        }
2643    }
2644
2645    struct Weighted;
2646    impl ConstrainedProblem for Weighted {
2647        fn objective(&self, x: &[f64]) -> f64 {
2648            x.iter().enumerate().map(|(i, v)| (i as f64 + 1.0) * (v - 1.0).powi(2)).sum()
2649        }
2650    }
2651
2652    // The evaluation counts below are SciPy's (1.17, `minimize(method='COBYQA')`) with a margin: 144, 103,
2653    // 31, 49 (which stops short of feasibility there) and 29.
2654    #[test]
2655    fn matches_scipy_on_unconstrained_and_nonlinearly_constrained_problems() {
2656        let r = cobyqa(&Rosen, vec![-1.2, 1.0], None, None, CobyqaOptions::default()).unwrap();
2657        assert!(r.success && (r.x[0] - 1.0).abs() < 1e-4 && (r.x[1] - 1.0).abs() < 1e-4 && r.nfev < 220, "{:?} {}", r.x, r.nfev);
2658        let r = cobyqa(&Disc, vec![-1.0, 0.0], None, None, CobyqaOptions::default()).unwrap();
2659        assert!(r.success && (r.x[0] - 0.907234).abs() < 1e-5 && (r.x[1] - 0.822755).abs() < 1e-5 && r.nfev < 160, "{:?} {}", r.x, r.nfev);
2660        assert!((r.fun - 0.00861565).abs() < 1e-7);
2661        let r = cobyqa(&Tutorial, vec![1.0, 1.0], None, None, CobyqaOptions::default()).unwrap();
2662        let s = 0.5f64.sqrt();
2663        assert!(r.success && (r.x[0] + s).abs() < 1e-5 && (r.x[1] - s).abs() < 1e-5 && r.nfev < 60, "{:?} {}", r.x, r.nfev);
2664        // Bounds and one inequality and one equality constraint: Hock and Schittkowski's no. 71.
2665        let r = cobyqa(&Hs071, vec![1.0, 5.0, 5.0, 1.0], Some(&[1.0; 4]), Some(&[5.0; 4]), CobyqaOptions::default()).unwrap();
2666        let want = [1.0, 4.743, 3.82115, 1.379408];
2667        assert!(r.success && r.maxcv < 1e-6 && (r.fun - 17.014017).abs() < 1e-4 && r.x.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-3) && r.nfev < 100, "{r:?}");
2668    }
2669
2670    #[test]
2671    fn bounds_fixed_variables_and_errors() {
2672        let r = cobyqa(&Weighted, vec![0.0; 5], Some(&[-2.0; 5]), Some(&[0.5; 5]), CobyqaOptions::default()).unwrap();
2673        assert!(r.success && r.x.iter().all(|v| (v - 0.5).abs() < 1e-6) && (r.fun - 3.75).abs() < 1e-8 && r.nfev < 50, "{r:?}");
2674        // The second variable is fixed at 0.25 by its bounds.
2675        let r = cobyqa(&Weighted, vec![0.0, 0.25, 0.0], Some(&[-3.0, 0.25, -3.0]), Some(&[3.0, 0.25, 3.0]), CobyqaOptions::default()).unwrap();
2676        assert!(r.success && (r.x[0] - 1.0).abs() < 1e-4 && r.x[1] == 0.25 && (r.x[2] - 1.0).abs() < 1e-4, "{:?}", r.x);
2677        let r = cobyqa(&Weighted, vec![0.0, 0.0], Some(&[1.0, 1.0]), Some(&[1.0, 1.0]), CobyqaOptions::default()).unwrap();
2678        assert_eq!(r.status, CobyqaStatus::AllFixed);
2679        let r = cobyqa(&Weighted, vec![0.0, 0.0], Some(&[1.0, 0.0]), Some(&[0.0, 1.0]), CobyqaOptions::default()).unwrap();
2680        assert_eq!(r.status, CobyqaStatus::InfeasibleBounds);
2681        assert!(cobyqa(&Weighted, vec![], None, None, CobyqaOptions::default()).is_err());
2682        assert!(cobyqa(&Weighted, vec![0.0], None, None, CobyqaOptions::with_radii(1e-3, 1.0)).is_err());
2683        // An evaluation budget that runs out, and a target that is reached.
2684        let o = CobyqaOptions { max_evaluations: Some(12), ..Default::default() };
2685        let r = cobyqa(&Rosen, vec![-1.2, 1.0], None, None, o).unwrap();
2686        assert_eq!(r.status, CobyqaStatus::MaxEvaluations);
2687        let o = CobyqaOptions { target: 1.0, ..Default::default() };
2688        let r = cobyqa(&Rosen, vec![-1.2, 1.0], None, None, o).unwrap();
2689        assert!(r.status == CobyqaStatus::TargetReached && r.fun <= 1.0);
2690    }
2691
2692    #[test]
2693    fn a_pure_equality_constrained_problem_and_a_full_quadratic_model() {
2694        struct Line;
2695        impl ConstrainedProblem for Line {
2696            fn objective(&self, x: &[f64]) -> f64 {
2697                x[0] * x[0] + x[1] * x[1]
2698            }
2699            fn equalities(&self, x: &[f64]) -> Vec<f64> {
2700                vec![x[0] + x[1] - 1.0]
2701            }
2702        }
2703        let r = cobyqa(&Line, vec![2.0, -1.0], None, None, CobyqaOptions::default()).unwrap();
2704        assert!(r.success && (r.x[0] - 0.5).abs() < 1e-5 && (r.x[1] - 0.5).abs() < 1e-5, "{:?}", r.x);
2705        // The full model (n + 1)(n + 2)/2 interpolates a quadratic function exactly: very few iterations.
2706        let o = CobyqaOptions { npt: Some(6), ..Default::default() };
2707        let r = cobyqa(&Rosen, vec![-1.2, 1.0], None, None, o).unwrap();
2708        assert!(r.success && (r.x[0] - 1.0).abs() < 1e-4, "{:?} {}", r.x, r.nfev);
2709        let o = CobyqaOptions { npt: Some(7), ..Default::default() };
2710        assert!(cobyqa(&Rosen, vec![-1.2, 1.0], None, None, o).is_err());
2711    }
2712
2713    // SciPy 1.17's COBYQA on the same problems: (1.4, 1.7) after 30 evaluations; (0.618796, 0.381204)
2714    // after 88; (−1.612771, 2.612771) after 33; and a callback that stops it at its 20th evaluation.
2715    #[test]
2716    fn linear_constraints_scaling_callback_and_history() {
2717        struct Wiki;
2718        impl ConstrainedProblem for Wiki {
2719            fn objective(&self, x: &[f64]) -> f64 {
2720                (x[0] - 1.0).powi(2) + (x[1] - 2.5).powi(2)
2721            }
2722        }
2723        let l = LinearConstraints { a_ub: vec![vec![-1.0, 2.0], vec![1.0, 2.0], vec![1.0, -2.0]], b_ub: vec![2.0, 6.0, 2.0], ..Default::default() };
2724        let r = cobyqa_with(&Wiki, vec![2.0, 0.0], Some(&[0.0, 0.0]), None, Some(&l), CobyqaOptions::default(), None).unwrap();
2725        assert!(r.success && (r.x[0] - 1.4).abs() < 1e-5 && (r.x[1] - 1.7).abs() < 1e-5 && (r.fun - 0.8).abs() < 1e-8 && r.nfev < 40, "{r:?}");
2726        let l = LinearConstraints { a_ub: vec![vec![1.0, 1.0]], b_ub: vec![1.0], ..Default::default() };
2727        let r = cobyqa_with(&Rosen, vec![-1.2, 1.0], None, None, Some(&l), CobyqaOptions::default(), None).unwrap();
2728        assert!(r.success && (r.x[0] - 0.618796).abs() < 1e-4 && (r.x[1] - 0.381204).abs() < 1e-4 && (r.fun - 0.14560702).abs() < 1e-6 && r.nfev < 130, "{r:?}");
2729        let l = LinearConstraints { a_eq: vec![vec![1.0, 1.0]], b_eq: vec![1.0], ..Default::default() };
2730        let r = cobyqa_with(&Rosen, vec![-1.2, 1.0], None, None, Some(&l), CobyqaOptions::default(), None).unwrap();
2731        assert!(r.success && (r.x[0] + 1.612771).abs() < 1e-4 && (r.x[1] - 2.612771).abs() < 1e-4 && r.maxcv < 1e-10, "{r:?}");
2732        // Linear constraints with a fixed variable: x₁ = 0.5 is substituted.
2733        let l = LinearConstraints { a_ub: vec![vec![1.0, 1.0, 1.0]], b_ub: vec![1.0], ..Default::default() };
2734        let r = cobyqa_with(&Weighted, vec![0.0, 0.5, 0.0], Some(&[-3.0, 0.5, -3.0]), Some(&[3.0, 0.5, 3.0]), Some(&l), CobyqaOptions::default(), None).unwrap();
2735        assert!(r.success && r.x[1] == 0.5 && r.x[0] + r.x[2] <= 0.5 + 1e-6 && r.maxcv < 1e-8, "{r:?}");
2736        assert!(cobyqa_with(&Wiki, vec![2.0, 0.0], None, None, Some(&LinearConstraints { a_ub: vec![vec![1.0]], b_ub: vec![1.0], ..Default::default() }), CobyqaOptions::default(), None).is_err());
2737
2738        // Scaling to the unit box changes the path, not the answer (it is in the original variables).
2739        let o = CobyqaOptions::default().with_scale(true);
2740        let r = cobyqa(&Rosen, vec![-1.2, 1.0], Some(&[-2.0, -2.0]), Some(&[2.0, 2.0]), o).unwrap();
2741        assert!(r.success && (r.x[0] - 1.0).abs() < 1e-4 && (r.x[1] - 1.0).abs() < 1e-4 && r.nfev < 180, "{r:?}");
2742        let r = cobyqa(&Weighted, vec![0.0; 5], Some(&[-2.0; 5]), Some(&[0.5; 5]), o).unwrap();
2743        assert!(r.success && r.x.iter().all(|v| (v - 0.5).abs() < 1e-6) && r.nfev < 50, "{r:?}");
2744
2745        // The callback sees the best point after each evaluation; stopping at the 20th is SciPy's run.
2746        let mut calls = 0;
2747        let mut cb = |_x: &[f64]| {
2748            calls += 1;
2749            calls >= 20
2750        };
2751        let r = cobyqa_with(&Rosen, vec![-1.2, 1.0], None, None, None, CobyqaOptions::default(), Some(&mut cb)).unwrap();
2752        assert!(r.status == CobyqaStatus::CallbackStop && r.success && r.nfev == 20 && (r.fun - 2.89673748).abs() < 1e-6, "{r:?}");
2753
2754        // History and filter size.
2755        let r = cobyqa(&Rosen, vec![-1.2, 1.0], None, None, CobyqaOptions::default().with_history(5).with_filter_size(1)).unwrap();
2756        assert_eq!(r.fun_history.len(), 5);
2757        assert_eq!(r.maxcv_history.len(), 5);
2758        assert!(r.fun_history.iter().all(|&v| v < 1e-6) && r.success, "{r:?}");
2759        assert!(cobyqa(&Rosen, vec![-1.2, 1.0], None, None, CobyqaOptions::default()).unwrap().fun_history.is_empty());
2760    }
2761
2762    #[test]
2763    fn constants_are_validated_and_can_be_changed() {
2764        let bad = CobyqaConstants { decrease_radius_factor: 1.5, ..Default::default() };
2765        assert!(cobyqa(&Rosen, vec![-1.2, 1.0], None, None, CobyqaOptions::default().with_constants(bad)).is_err());
2766        let bad = CobyqaConstants { decrease_radius_threshold: 2.0, ..Default::default() }; // not below the increase factor
2767        assert!(bad.validate().is_err());
2768        assert!(CobyqaConstants::default().validate().is_ok());
2769        let c = CobyqaConstants { improve_tcg: false, byrd_omojokun_factor: 0.7, ..Default::default() };
2770        let r = cobyqa(&Disc, vec![-1.0, 0.0], None, None, CobyqaOptions::default().with_constants(c)).unwrap();
2771        assert!(r.success && (r.x[0] - 0.907234).abs() < 1e-4 && (r.x[1] - 0.822755).abs() < 1e-4, "{r:?}");
2772    }
2773}