Skip to main content

lib_jsl_optimization/
trust_constr.rs

1//! `trust-constr`: a trust-region interior-point method for nonlinearly constrained problems
2//! (Byrd, Hribar and Nocedal, 1999; SciPy's `minimize(method='trust-constr')`).
3//!
4//! See the book entry [Constrained optimisation](https://jwkunz.github.io/lib_jsl/book/optimization/constrained.html#cobyla-and-trust-constr).
5
6use crate::constrained::{ConstrainedOptions, ConstrainedProblem, ConstrainedResult, solve_dense};
7use lib_jsl_core::ErrorsJSL;
8
9fn dot(a: &[f64], b: &[f64]) -> f64 {
10    a.iter().zip(b).map(|(x, y)| x * y).sum()
11}
12
13fn norm(a: &[f64]) -> f64 {
14    dot(a, a).sqrt()
15}
16
17fn matvec(m: &[Vec<f64>], v: &[f64]) -> Vec<f64> {
18    m.iter().map(|r| dot(r, v)).collect()
19}
20
21fn rmatvec(m: &[Vec<f64>], v: &[f64], n: usize) -> Vec<f64> {
22    let mut out = vec![0.0; n];
23    for (r, vi) in m.iter().zip(v) {
24        out.iter_mut().zip(r).for_each(|(o, a)| *o += vi * a);
25    }
26    out
27}
28
29/// Solves `(A Aᵀ + εI) y = r` (the projections of the Byrd-Omojokun step).
30fn aat_solve(a: &[Vec<f64>], r: &[f64]) -> Vec<f64> {
31    let m = a.len();
32    let trace: f64 = a.iter().map(|row| dot(row, row)).sum::<f64>().max(1.0);
33    let k: Vec<Vec<f64>> = (0..m).map(|i| (0..m).map(|j| dot(&a[i], &a[j]) + if i == j { 1e-14 * trace } else { 0.0 }).collect()).collect();
34    solve_dense(k, r.to_vec()).unwrap_or_else(|| vec![0.0; m])
35}
36
37/// `P v = v − Aᵀ(AAᵀ)⁻¹A v`, the projection onto the null space of `A`.
38fn project(a: &[Vec<f64>], v: &[f64]) -> Vec<f64> {
39    if a.is_empty() {
40        return v.to_vec();
41    }
42    let y = aat_solve(a, &matvec(a, v));
43    let aty = rmatvec(a, &y, v.len());
44    v.iter().zip(&aty).map(|(p, q)| p - q).collect()
45}
46
47/// The two `t` where `‖z + t d‖ = Δ`.
48fn to_boundary(z: &[f64], d: &[f64], delta: f64) -> f64 {
49    let (a, b, c) = (dot(d, d), 2.0 * dot(z, d), dot(z, z) - delta * delta);
50    (-b + (b * b - 4.0 * a * c).max(0.0).sqrt()) / (2.0 * a)
51}
52
53/// One Byrd-Omojokun step for `min gᵀd + ½ dᵀHd` subject to `A d + c = 0`, `‖d‖ ≤ Δ` and
54/// `d_i ≥ −τ` for the scaled slack components `i ≥ n_x`.
55fn byrd_omojokun_step(h: &dyn Fn(&[f64]) -> Vec<f64>, g: &[f64], a: &[Vec<f64>], c: &[f64], delta: f64, n_x: usize) -> Vec<f64> {
56    let nz = g.len();
57    let tau = 0.995;
58    // Normal step: dogleg on min ‖A v + c‖ within 0.8Δ (and half the slack fraction to boundary).
59    let mut v = vec![0.0; nz];
60    if !a.is_empty() && norm(c) > 0.0 {
61        let gn = rmatvec(a, &aat_solve(a, c), nz).iter().map(|t| -t).collect::<Vec<_>>();
62        let r = 0.8 * delta;
63        v = if norm(&gn) <= r {
64            gn
65        } else {
66            let grad = rmatvec(a, c, nz);
67            let ag = matvec(a, &grad);
68            let alpha = dot(&grad, &grad) / dot(&ag, &ag).max(f64::MIN_POSITIVE);
69            let cauchy: Vec<f64> = grad.iter().map(|t| -alpha * t).collect();
70            if norm(&cauchy) >= r {
71                cauchy.iter().map(|t| t * r / norm(&cauchy)).collect()
72            } else {
73                let dir: Vec<f64> = gn.iter().zip(&cauchy).map(|(p, q)| p - q).collect();
74                let t = to_boundary(&cauchy, &dir, r);
75                cauchy.iter().zip(&dir).map(|(p, q)| p + t * q).collect()
76            }
77        };
78        let scale = v[n_x..].iter().filter(|t| **t < -0.5 * tau).fold(1.0f64, |m, t| m.min(-0.5 * tau / t));
79        v.iter_mut().for_each(|t| *t *= scale);
80    }
81    // Tangential step: projected (Steihaug) CG on the reduced model from v, within Δ.
82    let hv = h(&v);
83    let mut r: Vec<f64> = g.iter().zip(&hv).map(|(p, q)| p + q).collect();
84    let mut d = v.clone();
85    let mut pr = project(a, &r);
86    let mut p: Vec<f64> = pr.iter().map(|t| -t).collect();
87    let tol = 0.01 * norm(&pr).min(1.0) * norm(&pr);
88    let mut rpr = dot(&r, &pr);
89    for _ in 0..2 * nz + 5 {
90        if norm(&pr) <= tol || rpr <= 0.0 {
91            break;
92        }
93        let hp = h(&p);
94        let curv = dot(&p, &hp);
95        if curv <= 0.0 {
96            let t = to_boundary(&d, &p, delta);
97            d.iter_mut().zip(&p).for_each(|(x, y)| *x += t * y);
98            break;
99        }
100        let alpha = rpr / curv;
101        let trial: Vec<f64> = d.iter().zip(&p).map(|(x, y)| x + alpha * y).collect();
102        if norm(&trial) >= delta {
103            let t = to_boundary(&d, &p, delta);
104            d.iter_mut().zip(&p).for_each(|(x, y)| *x += t * y);
105            break;
106        }
107        d = trial;
108        r.iter_mut().zip(&hp).for_each(|(x, y)| *x += alpha * y);
109        pr = project(a, &r);
110        let rpr_new = dot(&r, &pr);
111        let beta = rpr_new / rpr;
112        rpr = rpr_new;
113        p = p.iter().zip(&pr).map(|(x, y)| -y + beta * x).collect();
114    }
115    // Fraction to the boundary for the slacks.
116    let scale = d[n_x..].iter().filter(|t| **t < -tau).fold(1.0f64, |m, t| m.min(-tau / t));
117    d.iter_mut().for_each(|t| *t *= scale);
118    d
119}
120
121// ANCHOR: trust_constr
122/// Minimises `f(x)` subject to `h(x) = 0` and `g(x) ≤ 0` by a trust-region interior-point
123/// method (SciPy's `minimize(method='trust-constr')` with a BFGS Hessian).
124///
125/// Inequalities get slacks, `g(x) + s = 0`, `s > 0`, and the barrier problem
126/// `min f(x) − μ Σ ln sᵢ` subject to the equalities is solved by Byrd and Omojokun's
127/// trust-region SQP for a decreasing sequence of `μ` (0.1, then a factor 0.2 each time the
128/// barrier problem is solved to a tolerance that falls with it). Each SQP step is the sum of a
129/// normal step, which reduces the linearised constraint violation within 0.8 of the trust
130/// region, and a tangential step, projected conjugate gradients on the quadratic model in the
131/// null space of the constraint Jacobian. Slack steps are scaled by `S` and kept a fraction
132/// 0.995 from the boundary. Steps are accepted by the ℓ₂ merit function `φ + ν‖c‖`, the
133/// Lagrangian Hessian is a damped BFGS approximation, and the multipliers are least-squares
134/// estimates. `max_iterations` counts SQP iterations over all barrier problems.
135pub fn trust_constr<P: ConstrainedProblem>(problem: &P, x0: Vec<f64>, options: ConstrainedOptions) -> Result<ConstrainedResult, ErrorsJSL> {
136    trust_constr_with(problem, x0, options, HessianUpdate::Bfgs, None)
137}
138
139/// How the Hessian of the Lagrangian is obtained (SciPy's `hess` argument).
140#[derive(Clone, Copy, Debug, PartialEq, Eq)]
141#[non_exhaustive]
142pub enum HessianUpdate {
143    /// Damped BFGS: always positive definite (SciPy's `BFGS()`).
144    Bfgs,
145    /// Symmetric rank-one: may be indefinite, which the trust region and the conjugate-gradient
146    /// iteration handle through negative curvature (SciPy's `SR1()`).
147    Sr1,
148    /// The exact Hessian from [`ConstrainedProblem::lagrangian_hessian`], evaluated at the current
149    /// point with the current multiplier estimates.
150    Exact,
151}
152
153/// What the callback of [`trust_constr_with`] sees after each iteration. `Display` gives the line
154/// that SciPy prints with `verbose=2`, so a callback that prints it is the verbosity option:
155/// `Some(&mut |s| { println!("{s}"); false })`.
156#[derive(Clone, Copy, Debug)]
157pub struct TrustConstrState<'a> {
158    pub x: &'a [f64],
159    pub objective_value: f64,
160    pub iterations: usize,
161    /// The trust-region radius.
162    pub radius: f64,
163}
164
165impl std::fmt::Display for TrustConstrState<'_> {
166    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
167        write!(f, "iter {:4}  f = {:+.8e}  radius = {:.2e}", self.iterations, self.objective_value, self.radius)
168    }
169}
170
171/// [`trust_constr`] with a choice of the Hessian and a callback. The callback is called after every
172/// iteration and stops the solve by returning `true` (the result then has `converged = false`).
173/// `HessianUpdate::Exact` needs [`ConstrainedProblem::lagrangian_hessian`] to return the matrix.
174pub fn trust_constr_with<P: ConstrainedProblem>(problem: &P, x0: Vec<f64>, options: ConstrainedOptions, hessian: HessianUpdate, mut callback: Option<&mut dyn FnMut(&TrustConstrState) -> bool>) -> Result<ConstrainedResult, ErrorsJSL> {
175    let n = x0.len();
176    if n == 0 {
177        return Err(ErrorsJSL::Misconfiguration("Initial parameters must be a non-empty vector."));
178    }
179    let mut x = x0;
180    let ng = problem.inequalities(&x).len();
181    let mut s: Vec<f64> = problem.inequalities(&x).iter().map(|g| (-1.5 * g).max(1.0)).collect();
182    let mut mu = if ng > 0 { 0.1 } else { 0.0 };
183    let mut barrier_tol = if ng > 0 { 0.1f64.max(options.tolerance) } else { options.tolerance };
184    let mut bfgs: Vec<Vec<f64>> = (0..n).map(|i| (0..n).map(|j| if i == j { 1.0 } else { 0.0 }).collect()).collect();
185    let mut delta: f64 = 1.0;
186    let mut nu: f64 = 1.0;
187    let mut iterations = 0;
188    // Constraint values c(z) = [h(x); g(x) + s] and the scaled Jacobian [Jh 0; Jg S].
189    let eval = |x: &[f64], s: &[f64]| -> (Vec<f64>, Vec<Vec<f64>>) {
190        let h = problem.equalities(x);
191        let g = problem.inequalities(x);
192        let (jh, jg) = (problem.equality_jacobian(x), problem.inequality_jacobian(x));
193        let mut c = h;
194        c.extend(g.iter().zip(s).map(|(a, b)| a + b));
195        let mut a: Vec<Vec<f64>> = jh.into_iter().map(|mut r| {
196            r.extend(std::iter::repeat_n(0.0, s.len()));
197            r
198        }).collect();
199        for (i, mut r) in jg.into_iter().enumerate() {
200            r.extend((0..s.len()).map(|k| if k == i { s[i] } else { 0.0 }));
201            a.push(r);
202        }
203        (c, a)
204    };
205    let converged;
206    let mut stopped = false;
207    let mut lambda: Vec<f64>;
208    loop {
209        // Solve the barrier problem for this μ.
210        loop {
211            let fx = problem.objective(&x);
212            let gx = problem.gradient(&x);
213            let (c, a) = eval(&x, &s);
214            let mut grad = gx.clone();
215            grad.extend(std::iter::repeat_n(-mu, ng));
216            // Least-squares multipliers and the optimality of the barrier problem.
217            lambda = if a.is_empty() { Vec::new() } else { aat_solve(&a, &matvec(&a, &grad)).iter().map(|t| -t).collect() };
218            let lag: Vec<f64> = grad.iter().zip(rmatvec(&a, &lambda, n + ng)).map(|(p, q)| p + q).collect();
219            let opt = lag.iter().fold(0.0f64, |m, v| m.max(v.abs()));
220            let viol = c.iter().fold(0.0f64, |m, v| m.max(v.abs()));
221            if (opt <= barrier_tol && viol <= barrier_tol) || iterations >= options.max_iterations {
222                break;
223            }
224            iterations += 1;
225            // The exact Hessian: as a matrix if the problem has one, else through products.
226            let mut exact_hv: Option<(Vec<f64>, Vec<f64>)> = None;
227            if hessian == HessianUpdate::Exact {
228                let (ne, ni) = (problem.equalities(&x).len(), ng);
229                let (eq, ineq): (Vec<f64>, Vec<f64>) = if lambda.len() == ne + ni { (lambda[..ne].to_vec(), lambda[ne..].to_vec()) } else { (vec![0.0; ne], vec![0.0; ni]) };
230                match problem.lagrangian_hessian(&x, &eq, &ineq) {
231                    Some(h) => bfgs = h,
232                    None => {
233                        if problem.lagrangian_hessian_vector(&x, &eq, &ineq, &vec![0.0; n]).is_none() {
234                            return Err(ErrorsJSL::Misconfiguration("HessianUpdate::Exact needs the problem's lagrangian_hessian or lagrangian_hessian_vector"));
235                        }
236                        exact_hv = Some((eq, ineq));
237                    }
238                }
239            }
240            let hmul = |d: &[f64]| -> Vec<f64> {
241                let mut out = match &exact_hv {
242                    Some((eq, ineq)) => problem.lagrangian_hessian_vector(&x, eq, ineq, &d[..n]).unwrap_or_else(|| vec![0.0; n]),
243                    None => matvec(&bfgs, &d[..n]),
244                };
245                out.extend(d[n..].iter().map(|t| mu * t));
246                out
247            };
248            let d = byrd_omojokun_step(&hmul, &grad, &a, &c, delta, n);
249            // Merit: barrier objective plus ν‖c‖, with ν raised to make the step a descent.
250            let ad: Vec<f64> = matvec(&a, &d).iter().zip(&c).map(|(p, q)| p + q).collect();
251            let quad = dot(&grad, &d) + 0.5 * dot(&d, &hmul(&d));
252            let vpred = norm(&c) - norm(&ad);
253            if vpred > 1e-14 {
254                nu = nu.max(quad / (0.9 * vpred) + 1e-8);
255            }
256            let predicted = -quad + nu * vpred;
257            let barrier = |fx: f64, s: &[f64]| fx - mu * s.iter().map(|v| v.ln()).sum::<f64>();
258            let x_new: Vec<f64> = x.iter().zip(&d[..n]).map(|(p, q)| p + q).collect();
259            let s_new: Vec<f64> = s.iter().zip(&d[n..]).map(|(p, q)| p * (1.0 + q)).collect();
260            let (c_new, _) = eval(&x_new, &s_new);
261            let f_new = problem.objective(&x_new);
262            let actual = barrier(fx, &s) + nu * norm(&c) - barrier(f_new, &s_new) - nu * norm(&c_new);
263            let ratio = if predicted > 0.0 { actual / predicted } else { -1.0 };
264            let dn = norm(&d);
265            if ratio >= 0.75 {
266                delta = delta.max(7.0 * dn);
267            } else if ratio >= 0.3 {
268                delta = delta.max(2.0 * dn);
269            } else if ratio < 0.1 {
270                delta = 0.25 * dn.max(1e-16);
271            }
272            if delta < 1e-14 {
273                break;
274            }
275            if ratio > 1e-4 && f_new.is_finite() && s_new.iter().all(|v| *v > 0.0) {
276                // Damped BFGS on the Lagrangian's x-part, with the current multipliers.
277                let lag_x = |x: &[f64]| -> Vec<f64> {
278                    let mut l = problem.gradient(x);
279                    let mut jac = problem.equality_jacobian(x);
280                    jac.extend(problem.inequality_jacobian(x));
281                    for (row, lm) in jac.iter().zip(&lambda) {
282                        l.iter_mut().zip(row).for_each(|(o, r)| *o += lm * r);
283                    }
284                    l
285                };
286                let (l0, l1) = (lag_x(&x), lag_x(&x_new));
287                let sv: Vec<f64> = d[..n].to_vec();
288                let mut yv: Vec<f64> = l1.iter().zip(&l0).map(|(p, q)| p - q).collect();
289                let bs = matvec(&bfgs, &sv);
290                let sbs = dot(&sv, &bs);
291                let sy = dot(&sv, &yv);
292                if hessian == HessianUpdate::Sr1 {
293                    // B += (y − Bs)(y − Bs)ᵀ / ((y − Bs)ᵀ s), skipped when the denominator is small.
294                    let r: Vec<f64> = yv.iter().zip(&bs).map(|(y, b)| y - b).collect();
295                    let den = dot(&r, &sv);
296                    if den.abs() > 1e-8 * norm(&r) * norm(&sv) && den.abs() > 1e-300 {
297                        for i in 0..n {
298                            for j in 0..n {
299                                bfgs[i][j] += r[i] * r[j] / den;
300                            }
301                        }
302                    }
303                } else if hessian == HessianUpdate::Bfgs && sbs > 1e-300 {
304                    if sy < 0.2 * sbs {
305                        let theta = 0.8 * sbs / (sbs - sy);
306                        yv = yv.iter().zip(&bs).map(|(y, b)| theta * y + (1.0 - theta) * b).collect();
307                    }
308                    let sy = dot(&sv, &yv);
309                    if sy > 1e-300 {
310                        for i in 0..n {
311                            for j in 0..n {
312                                bfgs[i][j] += yv[i] * yv[j] / sy - bs[i] * bs[j] / sbs;
313                            }
314                        }
315                    }
316                }
317                x = x_new;
318                s = s_new;
319            }
320            if let Some(cb) = callback.as_deref_mut() {
321                let state = TrustConstrState { x: &x, objective_value: problem.objective(&x), iterations, radius: delta };
322                if cb(&state) {
323                    stopped = true;
324                    break;
325                }
326            }
327        }
328        if stopped {
329            converged = false;
330            break;
331        }
332        if ng == 0 || iterations >= options.max_iterations {
333            converged = iterations < options.max_iterations;
334            break;
335        }
336        if barrier_tol <= options.tolerance {
337            converged = true;
338            break;
339        }
340        mu *= 0.2;
341        barrier_tol = (0.2 * barrier_tol).max(options.tolerance);
342        delta = delta.max(1.0);
343    }
344    let h = problem.equalities(&x);
345    let g = problem.inequalities(&x);
346    let violation = h.iter().map(|v| v.abs()).chain(g.iter().map(|v| v.max(0.0))).fold(0.0, f64::max);
347    let ne = h.len();
348    let (eq, ineq) = if lambda.len() == ne + ng { (lambda[..ne].to_vec(), lambda[ne..].to_vec()) } else { (vec![0.0; ne], vec![0.0; ng]) };
349    Ok(ConstrainedResult {
350        objective_value: problem.objective(&x),
351        parameters: x,
352        equality_multipliers: eq,
353        inequality_multipliers: ineq,
354        constraint_violation: violation,
355        iterations,
356        converged: converged && violation <= options.tolerance.max(1e-6),
357    })
358}
359// ANCHOR_END: trust_constr
360
361#[cfg(test)]
362mod tests {
363    use super::*;
364
365    struct Hs071;
366    impl ConstrainedProblem for Hs071 {
367        fn objective(&self, x: &[f64]) -> f64 {
368            x[0] * x[3] * (x[0] + x[1] + x[2]) + x[2]
369        }
370        fn equalities(&self, x: &[f64]) -> Vec<f64> {
371            vec![x.iter().map(|v| v * v).sum::<f64>() - 40.0]
372        }
373        fn inequalities(&self, x: &[f64]) -> Vec<f64> {
374            let mut g = vec![25.0 - x.iter().product::<f64>()];
375            for &v in x {
376                g.push(1.0 - v);
377                g.push(v - 5.0);
378            }
379            g
380        }
381    }
382
383    struct Circle;
384    impl ConstrainedProblem for Circle {
385        // min x + y on the unit circle: (−1/√2, −1/√2).
386        fn objective(&self, x: &[f64]) -> f64 {
387            x[0] + x[1]
388        }
389        fn equalities(&self, x: &[f64]) -> Vec<f64> {
390            vec![x[0] * x[0] + x[1] * x[1] - 1.0]
391        }
392    }
393
394    /// Circle with its exact Lagrangian Hessian.
395    struct ExactCircle;
396    impl ConstrainedProblem for ExactCircle {
397        fn objective(&self, x: &[f64]) -> f64 {
398            x[0] + x[1]
399        }
400        fn gradient(&self, _x: &[f64]) -> Vec<f64> {
401            vec![1.0, 1.0]
402        }
403        fn equalities(&self, x: &[f64]) -> Vec<f64> {
404            vec![x[0] * x[0] + x[1] * x[1] - 1.0]
405        }
406        fn equality_jacobian(&self, x: &[f64]) -> Vec<Vec<f64>> {
407            vec![vec![2.0 * x[0], 2.0 * x[1]]]
408        }
409        fn lagrangian_hessian(&self, _x: &[f64], eq: &[f64], _ineq: &[f64]) -> Option<Vec<Vec<f64>>> {
410            Some(vec![vec![2.0 * eq[0], 0.0], vec![0.0, 2.0 * eq[0]]])
411        }
412    }
413
414    /// Circle with only Hessian-vector products.
415    struct HessianVectorCircle;
416    impl ConstrainedProblem for HessianVectorCircle {
417        fn objective(&self, x: &[f64]) -> f64 {
418            x[0] + x[1]
419        }
420        fn gradient(&self, _x: &[f64]) -> Vec<f64> {
421            vec![1.0, 1.0]
422        }
423        fn equalities(&self, x: &[f64]) -> Vec<f64> {
424            vec![x[0] * x[0] + x[1] * x[1] - 1.0]
425        }
426        fn equality_jacobian(&self, x: &[f64]) -> Vec<Vec<f64>> {
427            vec![vec![2.0 * x[0], 2.0 * x[1]]]
428        }
429        fn lagrangian_hessian_vector(&self, _x: &[f64], eq: &[f64], _ineq: &[f64], v: &[f64]) -> Option<Vec<f64>> {
430            Some(v.iter().map(|t| 2.0 * eq[0] * t).collect())
431        }
432    }
433
434    #[test]
435    fn hessian_vector_products_and_the_printing_callback() {
436        let o = ConstrainedOptions { tolerance: 1e-8, max_iterations: 1000 };
437        let s = 0.5f64.sqrt();
438        let r = trust_constr_with(&HessianVectorCircle, vec![2.0, 0.5], o, HessianUpdate::Exact, None).unwrap();
439        assert!(r.converged && (r.parameters[0] + s).abs() < 1e-7 && (r.parameters[1] + s).abs() < 1e-7);
440        let mut lines = Vec::new();
441        let mut cb = |st: &TrustConstrState| {
442            lines.push(st.to_string());
443            false
444        };
445        trust_constr_with(&Circle, vec![2.0, 0.5], o, HessianUpdate::Bfgs, Some(&mut cb)).unwrap();
446        assert!(lines.len() > 3 && lines[0].starts_with("iter    1  f = "), "{:?}", lines.first());
447    }
448
449    #[test]
450    fn exact_and_sr1_hessians_and_the_callback() {
451        let o = ConstrainedOptions { tolerance: 1e-8, max_iterations: 1000 };
452        let s = 0.5f64.sqrt();
453        let exact = trust_constr_with(&ExactCircle, vec![2.0, 0.5], o, HessianUpdate::Exact, None).unwrap();
454        assert!(exact.converged && (exact.parameters[0] + s).abs() < 1e-7 && (exact.parameters[1] + s).abs() < 1e-7);
455        let sr1 = trust_constr_with(&Circle, vec![2.0, 0.5], o, HessianUpdate::Sr1, None).unwrap();
456        assert!(sr1.converged && (sr1.parameters[0] + s).abs() < 1e-6, "{:?}", sr1.parameters);
457        // Exact without the Hessian is refused; the callback sees every iteration and can stop.
458        assert!(trust_constr_with(&Circle, vec![2.0, 0.5], o, HessianUpdate::Exact, None).is_err());
459        let mut seen = 0;
460        let mut cb = |st: &TrustConstrState| {
461            seen += 1;
462            st.iterations >= 3
463        };
464        let stopped = trust_constr_with(&Circle, vec![2.0, 0.5], o, HessianUpdate::Bfgs, Some(&mut cb)).unwrap();
465        assert!(!stopped.converged && stopped.iterations == 3 && seen == 3);
466    }
467
468    #[test]
469    fn solves_equality_and_mixed_problems() {
470        let o = ConstrainedOptions { tolerance: 1e-8, max_iterations: 1000 };
471        let r = trust_constr(&Circle, vec![2.0, 0.5], o).unwrap();
472        let s = 0.5f64.sqrt();
473        assert!(r.converged && (r.parameters[0] + s).abs() < 1e-7 && (r.parameters[1] + s).abs() < 1e-7, "{:?}", r.parameters);
474        assert!((r.equality_multipliers[0] - s).abs() < 1e-6, "{:?}", r.equality_multipliers);
475        // HS071: the optimum (1, 4.743, 3.821, 1.379) with f = 17.014.
476        let r = trust_constr(&Hs071, vec![1.0, 5.0, 5.0, 1.0], o).unwrap();
477        assert!(r.converged && (r.objective_value - 17.0140173).abs() < 1e-5, "{:?} {} {}", r.parameters, r.objective_value, r.iterations);
478        assert!((r.parameters[1] - 4.743).abs() < 1e-3, "{:?}", r.parameters);
479    }
480}