Skip to main content

lib_jsl_optimization/
slsqp.rs

1//! SLSQP: sequential least-squares quadratic programming (Kraft, 1988; SciPy's
2//! `minimize(method='SLSQP')`) for smooth problems with bounds and nonlinear equality and
3//! inequality constraints.
4//!
5//! Each iteration minimises a quadratic model `½ dᵀBd + ∇fᵀd` of the objective subject to the
6//! linearised constraints and the bounds (`B` is a positive definite BFGS approximation of the
7//! Hessian of the Lagrangian, updated by Powell's damped formula), steps along `d` by a line search
8//! on an ℓ₁ merit function whose penalty weights follow the multipliers of the subproblem, and stops
9//! when the objective and the constraints settle to `ftol`. A subproblem whose linearised constraints
10//! are inconsistent is relaxed by a scalar that scales their constants.
11//!
12//! See the book entry [Constrained optimisation](https://jwkunz.github.io/lib_jsl/book/optimization/constrained.html#slsqp).
13
14use crate::constrained::{ConstrainedProblem, bound_constrained_qp, solve_dense};
15use lib_jsl_core::ErrorsJSL;
16
17type V = Vec<f64>;
18type M = Vec<Vec<f64>>;
19
20/// Options for [`slsqp`], with SciPy's defaults.
21#[derive(Clone, Copy, Debug)]
22#[non_exhaustive]
23pub struct SlsqpOptions {
24    /// The tolerance on the objective's change and on the constraint violation (SciPy's `ftol`).
25    pub ftol: f64,
26    /// The largest number of iterations (SciPy's `maxiter`).
27    pub max_iterations: usize,
28}
29
30impl Default for SlsqpOptions {
31    fn default() -> Self {
32        SlsqpOptions { ftol: 1e-6, max_iterations: 100 }
33    }
34}
35
36impl SlsqpOptions {
37    pub fn new(ftol: f64, max_iterations: usize) -> Self {
38        SlsqpOptions { ftol, max_iterations }
39    }
40}
41
42/// Why [`slsqp`] stopped.
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44#[non_exhaustive]
45pub enum SlsqpStatus {
46    /// The objective and the constraints settled to `ftol`.
47    Converged,
48    /// The subproblem has no solution even with the constraints relaxed (SciPy's mode 4).
49    InconsistentConstraints,
50    /// The search direction is not a descent direction of the merit function, after a restart from
51    /// the identity matrix (SciPy's mode 8).
52    PositiveDirectionalDerivative,
53    /// No acceptable step in ten tries of the line search, after a restart.
54    LineSearchFailed,
55    /// The iteration limit was reached (SciPy's mode 9).
56    IterationLimit,
57    /// The objective or a constraint was not finite.
58    NotFinite,
59}
60
61/// The result of [`slsqp`].
62#[derive(Clone, Debug)]
63#[non_exhaustive]
64pub struct SlsqpResult {
65    pub x: Vec<f64>,
66    pub fun: f64,
67    /// The gradient of the objective at `x`.
68    pub jac: Vec<f64>,
69    /// Multipliers of the equalities and (≥ 0) of the inequalities `g(x) ≤ 0`, from the last subproblem.
70    pub equality_multipliers: Vec<f64>,
71    pub inequality_multipliers: Vec<f64>,
72    /// The largest constraint violation (bounds are always respected).
73    pub maxcv: f64,
74    /// Evaluations of the objective and constraints, of their derivatives, and iterations.
75    pub nfev: usize,
76    pub njev: usize,
77    pub nit: usize,
78    pub success: bool,
79    pub status: SlsqpStatus,
80}
81
82fn dot(a: &[f64], b: &[f64]) -> f64 {
83    a.iter().zip(b).map(|(x, y)| x * y).sum()
84}
85
86/// Solves `min ½ zᵀBz + gᵀz` subject to `a·z + c = 0` for the rows `eq` and `a·z + c ≥ 0` for the rows
87/// `ineq`, through its dual (a QP in the multipliers with bounds). Returns `z` and the multipliers.
88fn qp(b: &M, g: &[f64], eq: &[(V, f64)], ineq: &[(V, f64)]) -> Option<(V, V, V)> {
89    let n = g.len();
90    let rows: Vec<&(V, f64)> = eq.iter().chain(ineq).collect();
91    let m = rows.len();
92    let solve_b = |v: &[f64]| solve_dense(b.clone(), v.to_vec());
93    let binv_g = solve_b(g)?;
94    let binv_a: Vec<V> = rows.iter().map(|r| solve_b(&r.0)).collect::<Option<_>>()?;
95    // Dual: min ½ yᵀ(A B⁻¹ Aᵀ)y + (c − A B⁻¹ g)ᵀy with y ≥ 0 on the inequalities; z = B⁻¹(Aᵀy − g).
96    let mm: M = (0..m).map(|i| (0..m).map(|j| dot(&rows[i].0, &binv_a[j])).collect()).collect();
97    let qq: V = (0..m).map(|i| rows[i].1 - dot(&rows[i].0, &binv_g)).collect();
98    let y = if m == 0 { Vec::new() } else { bound_constrained_qp(&mm, &qq, eq.len())? };
99    let z: V = (0..n).map(|k| -binv_g[k] + (0..m).map(|i| y[i] * binv_a[i][k]).sum::<f64>()).collect();
100    if z.iter().any(|v| !v.is_finite()) {
101        return None;
102    }
103    // A solution of the dual that does not satisfy the constraints means the primal is infeasible.
104    let scale = 1.0 + rows.iter().map(|r| r.1.abs()).fold(0.0f64, f64::max);
105    let ok = rows.iter().enumerate().all(|(i, r)| {
106        let v = dot(&r.0, &z) + r.1;
107        if i < eq.len() { v.abs() <= 1e-7 * scale } else { v >= -1e-7 * scale }
108    });
109    if !ok {
110        return None;
111    }
112    Some((z, y[..eq.len()].to_vec(), y[eq.len()..].to_vec()))
113}
114
115// ANCHOR: slsqp
116/// Minimises `problem.objective` subject to the bounds `lower ≤ x ≤ upper` (`None`: unbounded) and the
117/// problem's `inequalities(x) ≤ 0` and `equalities(x) = 0`, by SLSQP (SciPy's `minimize(method='SLSQP')`).
118/// The problem's `gradient` and Jacobians are used (central differences unless the problem provides them);
119/// `x0` is moved into the bounds first.
120pub fn slsqp<P: ConstrainedProblem>(problem: &P, x0: Vec<f64>, lower: Option<&[f64]>, upper: Option<&[f64]>, options: SlsqpOptions) -> Result<SlsqpResult, ErrorsJSL> {
121    let n = x0.len();
122    if n == 0 {
123        return Err(ErrorsJSL::Misconfiguration("Initial parameters must be a non-empty vector."));
124    }
125    if x0.iter().any(|v| !v.is_finite()) {
126        return Err(ErrorsJSL::InvalidInputRange("the initial point must be finite"));
127    }
128    let xl: V = lower.map_or(vec![f64::NEG_INFINITY; n], |l| l.iter().map(|v| if v.is_nan() { f64::NEG_INFINITY } else { *v }).collect());
129    let xu: V = upper.map_or(vec![f64::INFINITY; n], |u| u.iter().map(|v| if v.is_nan() { f64::INFINITY } else { *v }).collect());
130    if xl.len() != n || xu.len() != n {
131        return Err(ErrorsJSL::IncompatibleArraySizes((xl.len().min(xu.len()), n)));
132    }
133    if (0..n).any(|i| xl[i] > xu[i]) {
134        return Err(ErrorsJSL::InvalidInputRange("a lower bound exceeds its upper bound"));
135    }
136    if options.ftol.is_nan() || options.ftol < 0.0 || options.max_iterations == 0 {
137        return Err(ErrorsJSL::InvalidInputRange("need ftol ≥ 0 and at least one iteration"));
138    }
139    let acc = options.ftol;
140    let mut x: V = (0..n).map(|i| x0[i].max(xl[i]).min(xu[i])).collect();
141    // The constraints as c(x) ≥ 0 after the equalities: c = [h; −g], with the rows of their Jacobians.
142    let constraints = |x: &[f64]| -> (V, usize) {
143        let (h, g) = (problem.equalities(x), problem.inequalities(x));
144        let me = h.len();
145        (h.into_iter().chain(g.into_iter().map(|v| -v)).collect(), me)
146    };
147    let jacobian = |x: &[f64]| -> M {
148        let (je, ji) = (problem.equality_jacobian(x), problem.inequality_jacobian(x));
149        je.into_iter().chain(ji.into_iter().map(|r| r.into_iter().map(|v| -v).collect())).collect()
150    };
151    let violation = |c: &[f64], me: usize| -> f64 { c.iter().enumerate().map(|(j, v)| if j < me { v.abs() } else { (-v).max(0.0) }).sum() };
152    let (mut nfev, mut njev) = (0usize, 0usize);
153    let mut f = problem.objective(&x);
154    let (mut c, me) = constraints(&x);
155    nfev += 1;
156    if !f.is_finite() || c.iter().any(|v| !v.is_finite()) {
157        return Err(ErrorsJSL::InvalidInputRange("the objective and constraints must be finite at the initial point"));
158    }
159    let m = c.len();
160    let mut g = problem.gradient(&x);
161    let mut a = jacobian(&x);
162    njev += 1;
163    let identity = || -> M { (0..n).map(|i| (0..n).map(|j| if i == j { 1.0 } else { 0.0 }).collect()).collect() };
164    let mut b = identity();
165    let mut b_is_identity = true;
166    let mut mu = vec![0.0; m];
167    let (mut lam_eq, mut lam_in): (V, V) = (vec![0.0; me], vec![0.0; m - me]);
168    let mut status = SlsqpStatus::IterationLimit;
169    let mut nit = 0;
170    'outer: while nit < options.max_iterations {
171        nit += 1;
172        // --- The subproblem: min ½ dᵀBd + gᵀd, A d + c (= 0 | ≥ 0), xl − x ≤ d ≤ xu − x.
173        let bound_rows = |extra: usize| -> Vec<(V, f64)> {
174            let mut out = Vec::new();
175            for i in 0..n {
176                if xl[i] > f64::NEG_INFINITY {
177                    let mut r = vec![0.0; n + extra];
178                    r[i] = 1.0;
179                    out.push((r, x[i] - xl[i]));
180                }
181                if xu[i] < f64::INFINITY {
182                    let mut r = vec![0.0; n + extra];
183                    r[i] = -1.0;
184                    out.push((r, xu[i] - x[i]));
185                }
186            }
187            out
188        };
189        // `d + (x − xl) ≥ 0` is the same as `d ≥ xl − x`.
190        let eq_rows: Vec<(V, f64)> = (0..me).map(|j| (a[j].clone(), c[j])).collect();
191        let mut in_rows: Vec<(V, f64)> = (me..m).map(|j| (a[j].clone(), c[j])).collect();
192        let n_general_in = in_rows.len();
193        in_rows.extend(bound_rows(0));
194        let mut relaxed = false;
195        let sol = match qp(&b, &g, &eq_rows, &in_rows) {
196            Some(s) => s,
197            None => {
198                // Inconsistent linearised constraints: scale their constants by δ ∈ [0, 1] and penalise 1 − δ.
199                relaxed = true;
200                let trace: f64 = (0..n).map(|i| b[i][i]).sum::<f64>() / n as f64;
201                let rho = 1e4 * trace.max(1.0) * (1.0 + g.iter().fold(0.0f64, |s, v| s.max(v.abs())));
202                let mut b_ext: M = b.iter().map(|r| r.iter().copied().chain(std::iter::once(0.0)).collect()).collect();
203                b_ext.push(vec![0.0; n + 1]);
204                b_ext[n][n] = rho;
205                let g_ext: V = g.iter().copied().chain(std::iter::once(-rho)).collect();
206                let eq_ext: Vec<(V, f64)> = (0..me).map(|j| (a[j].iter().copied().chain(std::iter::once(c[j])).collect(), 0.0)).collect();
207                let mut in_ext: Vec<(V, f64)> = (me..m).map(|j| (a[j].iter().copied().chain(std::iter::once(c[j])).collect(), 0.0)).collect();
208                in_ext.extend(bound_rows(1));
209                let mut r0 = vec![0.0; n + 1];
210                r0[n] = 1.0;
211                in_ext.push((r0, 0.0));
212                let mut r1 = vec![0.0; n + 1];
213                r1[n] = -1.0;
214                in_ext.push((r1, 1.0));
215                match qp(&b_ext, &g_ext, &eq_ext, &in_ext) {
216                    Some((mut z, le, li)) => {
217                        z.truncate(n);
218                        (z, le, li)
219                    }
220                    None => {
221                        if !b_is_identity {
222                            b = identity();
223                            b_is_identity = true;
224                            continue 'outer;
225                        }
226                        status = SlsqpStatus::InconsistentConstraints;
227                        break 'outer;
228                    }
229                }
230            }
231        };
232        let (d, le, li) = sol;
233        lam_eq = le;
234        lam_in = li[..n_general_in].to_vec();
235        let lam: V = lam_eq.iter().chain(&lam_in).copied().collect();
236        // --- Convergence of the model: a negligible predicted decrease at a feasible point.
237        let gd = dot(&g, &d);
238        let viol0 = violation(&c, me);
239        if !relaxed && gd.abs() < acc && viol0 < acc {
240            status = SlsqpStatus::Converged;
241            break;
242        }
243        // --- The merit function f + Σ μ_j |violation_j| and its directional derivative along d.
244        for j in 0..m {
245            mu[j] = lam[j].abs().max(0.5 * (mu[j] + lam[j].abs()));
246        }
247        let merit = |f: f64, c: &[f64]| -> f64 { f + c.iter().enumerate().map(|(j, v)| mu[j] * if j < me { v.abs() } else { (-v).max(0.0) }).sum::<f64>() };
248        let t0 = merit(f, &c);
249        let dphi = gd - c.iter().enumerate().map(|(j, v)| mu[j] * if j < me { v.abs() } else { (-v).max(0.0) }).sum::<f64>();
250        if dphi >= 0.0 {
251            if !b_is_identity {
252                b = identity();
253                b_is_identity = true;
254                continue;
255            }
256            status = SlsqpStatus::PositiveDirectionalDerivative;
257            break;
258        }
259        // --- The line search: Armijo with safeguarded quadratic interpolation.
260        let mut alpha: f64 = 1.0;
261        let mut accepted = None;
262        for _ in 0..10 {
263            let xn: V = (0..n).map(|i| (x[i] + alpha * d[i]).max(xl[i]).min(xu[i])).collect();
264            let fn_ = problem.objective(&xn);
265            let (cn, _) = constraints(&xn);
266            nfev += 1;
267            if !fn_.is_finite() || cn.iter().any(|v| !v.is_finite()) {
268                alpha *= 0.5;
269                continue;
270            }
271            let t = merit(fn_, &cn);
272            if t - t0 <= 0.1 * alpha * dphi {
273                accepted = Some((xn, fn_, cn));
274                break;
275            }
276            let interp = -dphi * alpha * alpha / (2.0 * (t - t0 - dphi * alpha));
277            alpha = interp.max(0.1 * alpha).min(0.5 * alpha);
278        }
279        let Some((xn, fn_, cn)) = accepted else {
280            if !b_is_identity {
281                b = identity();
282                b_is_identity = true;
283                continue;
284            }
285            status = SlsqpStatus::LineSearchFailed;
286            break;
287        };
288        // --- The damped BFGS update of B with the change of the Lagrangian's gradient.
289        let g_new = problem.gradient(&xn);
290        let a_new = jacobian(&xn);
291        njev += 1;
292        let s: V = (0..n).map(|i| xn[i] - x[i]).collect();
293        let grad_l = |gr: &[f64], ar: &M| -> V { (0..n).map(|k| gr[k] - (0..m).map(|j| lam[j] * ar[j][k]).sum::<f64>()).collect() };
294        let gl_new = grad_l(&g_new, &a_new);
295        let gl_old = grad_l(&g, &a);
296        let mut y: V = (0..n).map(|k| gl_new[k] - gl_old[k]).collect();
297        let bs: V = b.iter().map(|r| dot(r, &s)).collect();
298        let sbs = dot(&s, &bs);
299        if sbs > 1e-300 {
300            let mut sy = dot(&s, &y);
301            if sy < 0.2 * sbs {
302                let theta = 0.8 * sbs / (sbs - sy);
303                y = (0..n).map(|k| theta * y[k] + (1.0 - theta) * bs[k]).collect();
304                sy = dot(&s, &y);
305            }
306            for i in 0..n {
307                for j in 0..n {
308                    b[i][j] += y[i] * y[j] / sy - bs[i] * bs[j] / sbs;
309                }
310            }
311            b_is_identity = false;
312        }
313        // --- Convergence: the objective or the point barely moved and the constraints hold.
314        let f_old = f;
315        x = xn;
316        f = fn_;
317        c = cn;
318        g = g_new;
319        a = a_new;
320        let step_norm = dot(&s, &s).sqrt();
321        if ((f - f_old).abs() < acc || step_norm < acc) && violation(&c, me) < acc {
322            status = SlsqpStatus::Converged;
323            break;
324        }
325    }
326    let (h_final, g_final) = (problem.equalities(&x), problem.inequalities(&x));
327    let maxcv = h_final.iter().map(|v| v.abs()).chain(g_final.iter().map(|v| v.max(0.0))).fold(0.0, f64::max);
328    Ok(SlsqpResult { jac: g, fun: f, maxcv, equality_multipliers: lam_eq, inequality_multipliers: lam_in, x, nfev, njev, nit, success: status == SlsqpStatus::Converged, status })
329}
330// ANCHOR_END: slsqp
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335
336    struct Rosen;
337    impl ConstrainedProblem for Rosen {
338        fn objective(&self, x: &[f64]) -> f64 {
339            100.0 * (x[1] - x[0] * x[0]).powi(2) + (1.0 - x[0]).powi(2)
340        }
341        fn gradient(&self, x: &[f64]) -> Vec<f64> {
342            vec![-400.0 * x[0] * (x[1] - x[0] * x[0]) - 2.0 * (1.0 - x[0]), 200.0 * (x[1] - x[0] * x[0])]
343        }
344    }
345
346    struct Disc;
347    impl ConstrainedProblem for Disc {
348        fn objective(&self, x: &[f64]) -> f64 {
349            Rosen.objective(x)
350        }
351        fn gradient(&self, x: &[f64]) -> Vec<f64> {
352            Rosen.gradient(x)
353        }
354        fn inequalities(&self, x: &[f64]) -> Vec<f64> {
355            vec![x[0] * x[0] + x[1] * x[1] - 1.5]
356        }
357        fn inequality_jacobian(&self, x: &[f64]) -> Vec<Vec<f64>> {
358            vec![vec![2.0 * x[0], 2.0 * x[1]]]
359        }
360    }
361
362    struct Tutorial;
363    impl ConstrainedProblem for Tutorial {
364        fn objective(&self, x: &[f64]) -> f64 {
365            x[0] * x[1]
366        }
367        fn gradient(&self, x: &[f64]) -> Vec<f64> {
368            vec![x[1], x[0]]
369        }
370        fn inequalities(&self, x: &[f64]) -> Vec<f64> {
371            vec![x[0] * x[0] + x[1] * x[1] - 1.0, -x[1]]
372        }
373        fn inequality_jacobian(&self, x: &[f64]) -> Vec<Vec<f64>> {
374            vec![vec![2.0 * x[0], 2.0 * x[1]], vec![0.0, -1.0]]
375        }
376    }
377
378    struct Hs071;
379    impl ConstrainedProblem for Hs071 {
380        fn objective(&self, x: &[f64]) -> f64 {
381            x[0] * x[3] * (x[0] + x[1] + x[2]) + x[2]
382        }
383        fn gradient(&self, x: &[f64]) -> Vec<f64> {
384            vec![x[3] * (2.0 * x[0] + x[1] + x[2]), x[0] * x[3], x[0] * x[3] + 1.0, x[0] * (x[0] + x[1] + x[2])]
385        }
386        fn inequalities(&self, x: &[f64]) -> Vec<f64> {
387            vec![25.0 - x[0] * x[1] * x[2] * x[3]]
388        }
389        fn inequality_jacobian(&self, x: &[f64]) -> Vec<Vec<f64>> {
390            vec![vec![-x[1] * x[2] * x[3], -x[0] * x[2] * x[3], -x[0] * x[1] * x[3], -x[0] * x[1] * x[2]]]
391        }
392        fn equalities(&self, x: &[f64]) -> Vec<f64> {
393            vec![x.iter().map(|v| v * v).sum::<f64>() - 40.0]
394        }
395        fn equality_jacobian(&self, x: &[f64]) -> Vec<Vec<f64>> {
396            vec![x.iter().map(|v| 2.0 * v).collect()]
397        }
398    }
399
400    struct BoxProblem;
401    impl ConstrainedProblem for BoxProblem {
402        fn objective(&self, x: &[f64]) -> f64 {
403            -x[0] * x[1] * x[2]
404        }
405        fn gradient(&self, x: &[f64]) -> Vec<f64> {
406            vec![-x[1] * x[2], -x[0] * x[2], -x[0] * x[1]]
407        }
408        fn equalities(&self, x: &[f64]) -> Vec<f64> {
409            vec![2.0 * (x[0] * x[1] + x[1] * x[2] + x[0] * x[2]) - 6.0]
410        }
411        fn equality_jacobian(&self, x: &[f64]) -> Vec<Vec<f64>> {
412            vec![vec![2.0 * (x[1] + x[2]), 2.0 * (x[0] + x[2]), 2.0 * (x[0] + x[1])]]
413        }
414    }
415
416    struct Inconsistent;
417    impl ConstrainedProblem for Inconsistent {
418        // min x + y inside the unit disc and outside the disc of radius ½: from the origin the second
419        // constraint's linearisation (−¼ ≥ 0) cannot hold.
420        fn objective(&self, x: &[f64]) -> f64 {
421            x[0] + x[1]
422        }
423        fn gradient(&self, _x: &[f64]) -> Vec<f64> {
424            vec![1.0, 1.0]
425        }
426        fn inequalities(&self, x: &[f64]) -> Vec<f64> {
427            vec![x[0] * x[0] + x[1] * x[1] - 1.0, 0.25 - x[0] * x[0] - x[1] * x[1]]
428        }
429        fn inequality_jacobian(&self, x: &[f64]) -> Vec<Vec<f64>> {
430            vec![vec![2.0 * x[0], 2.0 * x[1]], vec![-2.0 * x[0], -2.0 * x[1]]]
431        }
432    }
433
434    // SciPy 1.17's SLSQP with analytic derivatives takes 34 iterations (47 evaluations) on Rosenbrock, 27 (38)
435    // in the disc, 6 (7) on the tutorial from (−½, 1), 5 (5) on HS071, 11 (15) on the box of surface area 6 and
436    // 25 (35) on Rosenbrock with bounds: the library's counts are the same or within three.
437    #[test]
438    fn follows_scipys_slsqp_iteration_for_iteration() {
439        let o = SlsqpOptions::default();
440        let r = slsqp(&Rosen, vec![-1.2, 1.0], None, None, o).unwrap();
441        assert!(r.success && (r.x[0] - 0.999922).abs() < 1e-5 && (r.x[1] - 0.999851).abs() < 1e-5 && r.nit == 34 && r.nfev == 47, "{r:?}");
442        let r = slsqp(&Disc, vec![-1.0, 0.0], None, None, o).unwrap();
443        assert!(r.success && (r.x[0] - 0.907234).abs() < 1e-5 && (r.x[1] - 0.822755).abs() < 1e-5 && r.nit.abs_diff(27) <= 3 && r.maxcv < 1e-8, "{r:?}");
444        // From (1, 1) both methods stop at (0, 0), a stationary point of the problem.
445        let r = slsqp(&Tutorial, vec![1.0, 1.0], None, None, o).unwrap();
446        assert!(r.success && r.x[0].abs() < 1e-6 && r.x[1].abs() < 1e-6 && r.nit == 2, "{r:?}");
447        let r = slsqp(&Tutorial, vec![-0.5, 1.0], None, None, o).unwrap();
448        let s = 0.5f64.sqrt();
449        assert!(r.success && (r.x[0] + s).abs() < 1e-4 && (r.x[1] - s).abs() < 1e-4 && r.nit.abs_diff(6) <= 1, "{r:?}");
450        let r = slsqp(&Hs071, vec![1.0, 5.0, 5.0, 1.0], Some(&[1.0; 4]), Some(&[5.0; 4]), o).unwrap();
451        assert!(r.success && (r.fun - 17.014017).abs() < 1e-5 && (r.x[1] - 4.742996).abs() < 1e-4 && r.nit == 5 && r.maxcv < 1e-6, "{r:?}");
452        assert!(r.inequality_multipliers.len() == 1 && r.equality_multipliers.len() == 1);
453        let r = slsqp(&BoxProblem, vec![0.5, 1.0, 2.0], None, None, o).unwrap();
454        assert!(r.success && r.x.iter().all(|v| (v - 1.0).abs() < 1e-3) && r.nit.abs_diff(11) <= 1, "{r:?}");
455        let r = slsqp(&Rosen, vec![-1.2, 1.0], Some(&[-2.0, -2.0]), Some(&[0.5, 2.0]), o).unwrap();
456        assert!(r.success && r.x[0] == 0.5 && (r.x[1] - 0.250014).abs() < 1e-4 && r.nit == 25, "{r:?}");
457    }
458
459    #[test]
460    fn a_relaxed_subproblem_handles_inconsistent_linearisations() {
461        // SciPy: 6 iterations from the origin and 10 from (0.1, −0.05), both to (−0.7071, −0.7071).
462        let o = SlsqpOptions::default();
463        let r = slsqp(&Inconsistent, vec![0.0, 0.0], None, None, o).unwrap();
464        assert!(r.success && (r.x[0] + std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-4 && (r.x[1] + std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-4 && r.nit.abs_diff(6) <= 1, "{r:?}");
465        let r = slsqp(&Inconsistent, vec![0.1, -0.05], None, None, o).unwrap();
466        assert!(r.success && (r.x[0] + std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-5 && r.nit.abs_diff(10) <= 1, "{r:?}");
467    }
468
469    #[test]
470    fn tolerances_limits_and_errors() {
471        // A tighter ftol gives a more accurate point.
472        let loose = slsqp(&Rosen, vec![-1.2, 1.0], None, None, SlsqpOptions::default()).unwrap();
473        let tight = slsqp(&Rosen, vec![-1.2, 1.0], None, None, SlsqpOptions::new(1e-12, 200)).unwrap();
474        assert!(tight.success && (tight.x[0] - 1.0).abs() < (loose.x[0] - 1.0).abs() && (tight.x[0] - 1.0).abs() < 1e-6, "{tight:?}");
475        let r = slsqp(&Rosen, vec![-1.2, 1.0], None, None, SlsqpOptions::new(1e-6, 5)).unwrap();
476        assert!(!r.success && r.status == SlsqpStatus::IterationLimit && r.nit == 5);
477        // The start is moved into the bounds, and the result respects them.
478        let r = slsqp(&Rosen, vec![5.0, 5.0], Some(&[-1.0, -1.0]), Some(&[1.0, 1.0]), SlsqpOptions::default()).unwrap();
479        assert!(r.x.iter().all(|v| (-1.0..=1.0).contains(v)) && (r.x[0] - 1.0).abs() < 1e-3);
480        assert!(slsqp(&Rosen, vec![], None, None, SlsqpOptions::default()).is_err());
481        assert!(slsqp(&Rosen, vec![0.0, 0.0], Some(&[1.0, 0.0]), Some(&[0.0, 1.0]), SlsqpOptions::default()).is_err());
482        assert!(slsqp(&Rosen, vec![0.0, 0.0], None, None, SlsqpOptions::new(-1.0, 10)).is_err());
483        assert!(slsqp(&Rosen, vec![0.0, 0.0], Some(&[0.0]), None, SlsqpOptions::default()).is_err());
484    }
485}