Constrained optimisation: SQP and the augmented Lagrangian method
| Problem | Minimise a smooth subject to nonlinear equality constraints and inequality constraints |
| Devised by | Optimality conditions: Joseph-Louis Lagrange (1788, equalities), William Karush (1939), Harold Kuhn and Albert Tucker (1951). SQP: Robert Wilson (1963), Shih-Ping Han (1977), Michael Powell (1978). Augmented Lagrangian: Magnus Hestenes and Michael Powell (1969), extended to inequalities by R. Tyrrell Rockafellar (1973) |
| Accuracy | To the tolerance on the constraint violation and the optimality conditions; SQP converges superlinearly, the augmented Lagrangian method linearly in its outer iterations |
| Cost | SQP: per iteration, gradients of and all constraints, a dense quadratic program and an factorisation. Augmented Lagrangian: an unconstrained minimisation (L-BFGS) per outer iteration |
| Read first | Background: what a minimum looks like, Newton and quasi-Newton methods: Newton, BFGS and L-BFGS |
| API | sqp, augmented_lagrangian, ConstrainedProblem, ConstrainedResult; cobyla, slsqp, SlsqpOptions, cobyqa, CobyqaOptions, trust_constr, minimize_trust_krylov, least_squares_lsmr, lsmr |
Overview
Real problems come with constraints: a design must meet its specifications, a portfolio must be fully invested, concentrations cannot be negative. At a constrained minimum the gradient of need not vanish: it is balanced by the gradients of the constraints that are active (holding with equality), weighted by Lagrange multipliers that measure how much the optimum would improve if each constraint were relaxed.
Sequential quadratic programming (SQP) applies Newton’s method to these optimality conditions: each iteration minimises a quadratic model of the Lagrangian subject to linearised constraints. It is the most effective general method for small and medium problems. The augmented Lagrangian method converts the constrained problem into a sequence of unconstrained ones, each solved by any unconstrained method, and updates multiplier estimates between them. It is simpler and more forgiving, at the price of more function evaluations.
Where it is used
Most engineering design is optimisation under constraints.
- Design. Minimising weight or cost of a structure subject to stress and deflection limits; maximising the volume of a box for a fixed surface area.
- Process and power systems. Optimal power flow in electricity grids, and chemical process operation within safety and quality limits.
- Control. Model predictive control solves a constrained optimisation at every step.
- Finance and statistics. Portfolio optimisation with budget constraints, and maximum-likelihood estimation with parameter constraints.
- Derivative-free methods. COBYLA and COBYQA handle black-box simulators without gradients.
History
Lagrange introduced his multipliers in the Mécanique analytique (1788) for mechanical systems with equality constraints. The conditions for inequalities were found by William Karush in his 1939 master’s thesis at the University of Chicago, which was not published, and again by Harold Kuhn and Albert Tucker in 1951; they are now the KKT conditions.
Robert Wilson’s 1963 Harvard thesis proposed solving a sequence of quadratic programs, and Shih-Ping
Han (1977) and Michael Powell (1978) made SQP practical with quasi-Newton approximations and merit
functions, establishing the method that underlies codes such as SNOPT and MATLAB’s fmincon.
Penalty methods, adding to and letting , were older (Courant, 1943) but become
badly conditioned as grows. Magnus Hestenes and Michael Powell (1969) independently showed that
adding the multiplier term avoids this: the method of multipliers, later analysed by Rockafellar
and Dimitri Bertsekas, and the basis of codes such as LANCELOT.
The idea
Optimality conditions
The problem is
with equality constraints and inequality constraints . A point satisfying all of them is feasible. Before designing an algorithm we need to know how to recognise a solution. Without constraints the test is . With constraints it is more subtle, and is best built up in three steps.
One equality constraint. The feasible points lie on the surface , and the gradient is perpendicular to that surface. At a constrained minimum, must not decrease in any direction along the surface. That does not require ; it requires only that have no component along the surface, that is, that be perpendicular to it too. Two vectors perpendicular to the same surface are parallel:
for some number , the Lagrange multiplier. If this failed, sliding along the surface in the direction of the leftover component of would reduce .
One inequality constraint. There are two cases. If the minimum lies strictly inside the region, , the constraint plays no part (it is inactive) and as usual. If the minimum lies on the boundary, , the constraint is active and behaves like an equality, , with one extra requirement. Moving into the interior (against ) must not decrease either, so must point out of the region, the same way as . That forces . Both cases are covered by a single statement: with and , where the last equation says that either the multiplier or the constraint is zero.
The general case. With several constraints the gradient of is balanced by a combination of the constraint gradients. It is convenient to collect everything into the Lagrangian
Under mild conditions on the constraints, a local minimum has multipliers satisfying the Karush-Kuhn-Tucker (KKT) conditions
The first equation says that the gradient of with respect to vanishes (stationarity). The next two are feasibility. The last, complementarity, says that an inactive constraint () has : only active constraints exert a “force” on the solution.
The multipliers are not just bookkeeping. is the rate at which the optimal value would fall if the constraint were relaxed to : it is the price of that constraint. A large multiplier marks a constraint that is costing a great deal.
Sequential quadratic programming
The KKT conditions are a system of nonlinear equations (and inequalities) in and the multipliers. SQP solves them by a Newton-like iteration, in which each step is itself a simpler optimisation problem.
The subproblem. At the current point, replace by a quadratic model and each constraint by its linearisation, and solve for the step :
A problem with a quadratic objective and linear constraints is a quadratic program (QP), and it can be solved exactly in a finite number of steps. Its solution gives the step , and its own multipliers are the new estimates of and . The matrix approximates the Hessian of the Lagrangian, not of alone, because the curvature of the constraints matters as much as that of the objective. With the exact Hessian, the iteration is Newton’s method applied to the KKT conditions.
The library’s implementation makes three further choices.
- The Hessian approximation. is maintained by a BFGS update, so no second derivatives are needed. The Lagrangian can have negative curvature in some directions even at a solution, which would break the ordinary BFGS update; Powell’s damping modifies the update so that stays positive definite regardless.
- Solving the QP. With positive definite the QP is solved through its dual. The step can be written , where the rows of are the constraint gradients and holds the multipliers. The multipliers minimise a convex quadratic subject only to the simple bounds for the inequalities, a much easier problem, which an active-set method solves.
- Accepting the step. A step may reduce while violating the constraints more, or the reverse, so progress is measured by the merit function
which adds to a penalty times the total constraint violation. A line search along reduces this function. With larger than the largest multiplier, its minimum is the constrained minimum. Because violations are penalised and not forbidden, SQP can start from an infeasible point.
The augmented Lagrangian method
The second method reduces the constrained problem to a sequence of unconstrained ones. Consider equality constraints first.
The penalty idea, and its flaw. The simplest approach adds a penalty for violating the constraints and minimises without constraints. The minimiser of this function always violates the constraints slightly, by an amount proportional to , because a small violation costs little and can buy a reduction in . Exact feasibility needs , and the penalised function then has a valley with extremely steep walls, which is ill-conditioned and hard to minimise.
Adding the multiplier term. The augmented Lagrangian adds the penalty to the Lagrangian instead of to :
If were the exact multiplier vector, the minimiser of over would be the constrained solution itself, for any sufficiently large finite . The multiplier term supplies the force that holds the solution on the constraints, so the penalty no longer has to.
Estimating the multipliers. The exact multipliers are unknown, but each minimisation improves the estimate. At the minimiser of its gradient vanishes:
Compare this with the KKT stationarity condition: the quantity stands exactly where the true multiplier should. This suggests the update .
The method. Each outer iteration minimises over with an unconstrained method (here L-BFGS) and then updates the multipliers by the rule above. The penalty is increased tenfold whenever the violation fails to fall by a factor of four.
Inequalities are handled by Rockafellar’s form of the augmented Lagrangian, which adds and updates . The implements the two cases of the optimality conditions: a constraint that is comfortably satisfied gets a zero multiplier and drops out, while an active one is treated like an equality.
An example
Minimise subject to and , from the infeasible point . The objective is the squared distance from , so the unconstrained minimum is , which violates both constraints. The solution is , where both are active, with multipliers :
Figure 5.8. A constrained problem.
The KKT conditions can be checked by hand. In the standard form the constraints are and . At the gradients are , and , and indeed
Table 5.7. Constrained optimisers on test problems.
| problem | method | iterations | evaluations of | constraint violation | multipliers (inequalities) | |
|---|---|---|---|---|---|---|
| the problem above | SQP | 6 | 13 | 1.00000000 | 2e-12 | 0.667, 0.667 |
| the problem above | augmented Lagrangian | 9 | 205 | 1.00000000 | 1e-9 | 0.667, 0.667 |
| Hock-Schittkowski 71 | SQP | 6 | 100 | 17.01401728 | 3e-9 | : 0.552, : 1.088 |
| Hock-Schittkowski 71 | augmented Lagrangian | 11 | 9910 | 17.01401730 | 8e-9 | : 0.552, : 1.088 |
SQP reaches the solution in a few iterations; the augmented Lagrangian method needs more outer iterations and many more evaluations, each outer iteration being a full minimisation. On Hock and Schittkowski’s problem 71, a standard test with four variables, one equality, one nonlinear inequality and eight bounds, the derivatives are computed by central differences, which dominate the evaluation counts. Both methods find and the active constraints, the product constraint and the bound , with the published multipliers.
Algorithm
Sequential quadratic programming (sqp). Input: the objective, the constraints and a
starting point , which need not be feasible. Start with . Repeat:
- Evaluate , the constraints, and the gradients of all of them at .
- Solve the quadratic program for the step and the multiplier estimates , through its dual.
- Test. Stop if the constraint violation is below the tolerance and either the step or the KKT residual (the gradient of the Lagrangian) is too.
- Update the penalty. Raise if necessary so that it exceeds the largest multiplier in magnitude; this keeps a descent direction for the merit function.
- Line search. Starting from a full step, shorten the step along until the merit function decreases sufficiently, and move there.
- Update by the damped BFGS formula, using the step and the change in the gradient of the Lagrangian.
Each iteration costs one evaluation of all the gradients and the solution of one dense QP.
Augmented Lagrangian (augmented_lagrangian). Input as above. Start with all multipliers
zero and . Repeat:
- Inner minimisation. Minimise over with L-BFGS, starting from the previous solution.
- Update the multipliers: and .
- Test. Measure the violation: for the equalities, and for each inequality either the amount by which it is violated or, if it is satisfied with a nonzero multiplier, the failure of complementarity. Stop if the largest is below the tolerance.
- Update the penalty. If the violation did not fall by a factor of four since the last outer iteration, multiply by 10.
Each outer iteration is a complete unconstrained minimisation, which is why the method needs many more evaluations than SQP.
Implementation
The SQP subproblem through its dual:
// Dual QP: min ½ yᵀ(A B⁻¹ Aᵀ)y + (A B⁻¹ ∇f − c)ᵀ y, inequality multipliers ≥ 0.
let dual_m: Vec<Vec<f64>> = (0..m).map(|i| (0..m).map(|j| dot(a[i], &binv_a[j])).collect()).collect();
let dual_q: Vec<f64> = (0..m).map(|i| dot(a[i], &binv_g) - c[i]).collect();
let y = bound_constrained_qp(&dual_m, &dual_q, me).ok_or(ErrorsJSL::RuntimeError("The QP subproblem failed (inconsistent linearised constraints?)."))?;
// d = −B⁻¹(∇f + Aᵀy).
let d: Vec<f64> = (0..n).map(|k| -(binv_g[k] + (0..m).map(|i| y[i] * binv_a[i][k]).sum::<f64>())).collect();
The augmented Lagrangian outer iteration:
let al = AugmentedLagrangian { problem, lambda: &lambda, mu: &mu, rho };
x = inner.gradient_based_minimize(&al, &al, x.clone())?.parameters;
let (h, g) = (problem.equalities(&x), problem.inequalities(&x));
// Inequality violation measured by the complementarity-aware min(−g, μ/ρ).
let v = h.iter().map(|v| v.abs()).chain(g.iter().zip(&mu).map(|(gj, mj)| gj.max(-mj / rho).abs())).fold(0.0, f64::max);
lambda.iter_mut().zip(&h).for_each(|(l, hi)| *l += rho * hi);
mu.iter_mut().zip(&g).for_each(|(m, gj)| *m = (*m + rho * gj).max(0.0));
- Problems implement the
ConstrainedProblemtrait: only the objective is required; constraints default to none and all derivatives to central differences. - The QP is dense and solved by Gaussian elimination: suitable for tens to a few hundred variables and constraints.
- The result reports the multipliers; positive inequality multipliers identify the active constraints.
In practice
//! Constrained minimisation by SQP and the augmented Lagrangian method.
//!
//! Run with `cargo run -p lib_jsl_optimization --example optimization_constrained`.
use lib_jsl_optimization::constrained::{ConstrainedOptions, ConstrainedProblem, augmented_lagrangian, sqp};
/// The box of largest volume with surface area 6 (no lid constraint): maximise xyz subject to
/// 2(xy + yz + zx) = 6 and x, y, z ≥ 0. The answer is the unit cube.
struct Box3;
impl ConstrainedProblem for Box3 {
fn objective(&self, x: &[f64]) -> f64 {
-x[0] * x[1] * x[2]
}
fn equalities(&self, x: &[f64]) -> Vec<f64> {
vec![2.0 * (x[0] * x[1] + x[1] * x[2] + x[2] * x[0]) - 6.0]
}
fn inequalities(&self, x: &[f64]) -> Vec<f64> {
x.iter().map(|v| -v).collect()
}
}
fn main() {
let options = ConstrainedOptions::default();
let r = sqp(&Box3, vec![0.5, 1.0, 2.0], options).unwrap();
println!("SQP: {:?}, volume {:.8}, λ = {:?}, {} iterations", r.parameters, -r.objective_value, r.equality_multipliers, r.iterations);
let r = augmented_lagrangian(&Box3, vec![0.5, 1.0, 2.0], options).unwrap();
println!("augmented Lagrangian: {:?}, volume {:.8}, {} outer iterations", r.parameters, -r.objective_value, r.iterations);
}
COBYLA and trust-constr
SciPy offers two further constrained methods, and the library now has both.
COBYLA (Powell, 1994) needs no derivatives. It keeps a simplex of points and the linear functions that interpolate the objective and each constraint on it. Each step minimises the linear objective subject to the linear constraints within a ball of radius . If the linearised constraints cannot all be met in the ball, it first minimises their largest violation. Points are compared by the merit , with raised whenever a step would not reduce it. Geometry steps keep the simplex well shaped (no vertex farther than from the base, none closer than to the opposite face), and the vertex that a new point replaces is the one with the largest barycentric weight of the new point, the farthest among the well-weighted ones. The trust-region radius is separate from the accuracy radius : it doubles the length of a successful step and halves after a poor one, and only when it is down at , with a well-shaped simplex, is halved, down to rhoend. is lowered with so that it does not stay large after the constraints have been met.
The library solves the linear ball-constrained subproblem as the limit of the strictly convex QP , with found by bisection so that . Powell instead uses a purpose-built active-set method.
trust-constr (Byrd, Hribar and Nocedal, 1999) is an interior-point method.
- Inequalities get slacks, , and the barrier problem is solved for .
- Each barrier problem is solved by Byrd and Omojokun’s trust-region SQP, which splits every step in two. A normal step reduces the linearised constraint violation within . A tangential step then improves the quadratic model inside the null space of the constraint Jacobian, by projected conjugate gradients.
- The slacks are scaled and kept a fraction 0.995 from zero. The Hessian is a damped BFGS approximation by default, as SciPy’s
hess=BFGS().trust_constr_withchoosesHessianUpdate::Sr1(symmetric rank one, possibly indefinite, asSR1()) orHessianUpdate::Exact(the problem’slagrangian_hessian, evaluated with the current multiplier estimates), and takes a callback that sees the point, the objective, the iteration count and the trust-region radius after every iteration and can stop the solve by returningtrue.ConstrainedProblem::lagrangian_hessian_vectorgivesHessianUpdate::Exactthe product with a vector (SciPy’shessp) when the matrix is too costly to form, andTrustConstrStateprints as SciPy’sverbose=2line, so a callback that prints it is the verbosity option. Sparse Jacobians are not supported.
const ALPHA: f64 = 0.25;
const BETA: f64 = 2.1;
const GAMMA: f64 = 0.5;
const DELTA: f64 = 1.1;
/// Minimises `f` subject to `g(x) ≤ 0` and `h(x) = 0` without derivatives, by Powell's COBYLA
/// (SciPy's `minimize(method='COBYLA')`; equalities become pairs of inequalities).
///
/// The method keeps a simplex of `n + 1` points and the linear functions that interpolate the
/// objective and every constraint on it. Each iteration minimises the linear objective subject
/// to the linear constraints within a ball of radius `ρ` around the best vertex (best by the
/// merit `f + μ·max violation`, with `μ` raised whenever a step would not decrease it), and
/// replaces a vertex by the new point. Steps that would spoil the simplex's shape are replaced
/// by geometry steps, and `ρ` is halved when the trust-region steps become short, until it
/// reaches `rhoend`. The derivatives defaulted by [`ConstrainedProblem`] are never called.
pub fn cobyla<P: ConstrainedProblem>(problem: &P, x0: Vec<f64>, options: CobylaOptions) -> Result<ConstrainedResult, ErrorsJSL> {
let n = x0.len();
if n == 0 {
return Err(ErrorsJSL::Misconfiguration("Initial parameters must be a non-empty vector."));
}
if !(options.rhobeg > 0.0 && options.rhoend > 0.0 && options.rhoend <= options.rhobeg) {
return Err(ErrorsJSL::InvalidInputRange("need 0 < rhoend ≤ rhobeg"));
}
// Constraints as c(x) ≥ 0.
let cons = |x: &[f64]| -> Vec<f64> {
let mut c: Vec<f64> = problem.inequalities(x).iter().map(|v| -v).collect();
for h in problem.equalities(x) {
c.push(h);
c.push(-h);
}
c
};
let nfev = std::cell::Cell::new(0usize);
let eval = |x: &[f64]| -> (f64, Vec<f64>) {
nfev.set(nfev.get() + 1);
(problem.objective(x), cons(x))
};
let resmax = |c: &[f64]| c.iter().map(|v| -v).fold(0.0f64, f64::max);
let mut rho = options.rhobeg;
// The trust-region radius, between ρ (the accuracy still wanted) and what the steps have earned.
let mut delta = rho;
let mut mu = 0.0f64;
// Vertex 0 is x0; vertex j is x0 + ρ e_j.
let mut pts: Vec<Vec<f64>> = vec![x0.clone()];
let mut vals: Vec<(f64, Vec<f64>)> = vec![eval(&x0)];
for j in 0..n {
let mut p = x0.clone();
p[j] += rho;
vals.push(eval(&p));
pts.push(p);
}
let phi = |v: &(f64, Vec<f64>), mu: f64| v.0 + mu * resmax(&v.1);
loop {
// Make vertex 0 the best by the merit (ties: the smaller violation).
let best = (0..=n)
.min_by(|&a, &b| {
let (pa, pb) = (phi(&vals[a], mu), phi(&vals[b], mu));
pa.total_cmp(&pb).then(resmax(&vals[a].1).total_cmp(&resmax(&vals[b].1)))
})
.unwrap();
pts.swap(0, best);
vals.swap(0, best);
if nfev.get() >= options.max_evaluations {
break;
}
// Linear models: rows of D are the displacements x_j − x_0; gradients solve D ∇ = Δ.
let d: Vec<Vec<f64>> = (1..=n).map(|j| pts[j].iter().zip(&pts[0]).map(|(a, b)| a - b).collect()).collect();
let Some(dinv) = invert(&d) else {
// A degenerate simplex: rebuild it around the best point.
for j in 0..n {
let mut p = pts[0].clone();
p[j] += rho;
vals[j + 1] = eval(&p);
pts[j + 1] = p;
}
continue;
};
let grad_of = |k: Option<usize>| -> Vec<f64> {
let diffs: Vec<f64> = (1..=n).map(|j| match k {
None => vals[j].0 - vals[0].0,
Some(i) => vals[j].1[i] - vals[0].1[i],
}).collect();
(0..n).map(|r| (0..n).map(|j| dinv[r][j] * diffs[j]).sum()).collect()
};
let g = grad_of(None);
let mc = vals[0].1.len();
let a: Vec<Vec<f64>> = (0..mc).map(|i| grad_of(Some(i))).collect();
// Simplex geometry: Powell's acceptability test with factors 1.1 (lengths) and 0.25
// (distances of each vertex from the opposite face).
let lengths: Vec<f64> = d.iter().map(|r| norm(r)).collect();
let face: Vec<f64> = (0..n).map(|j| 1.0 / norm(&(0..n).map(|r| dinv[r][j]).collect::<Vec<_>>())).collect();
// The trust-region step.
let step = subproblem(&g, &vals[0].1, &a, delta);
let short = norm(&step) < 0.5 * delta;
if !short {
// Raise μ until the step decreases the linearised merit.
let r0 = resmax(&vals[0].1);
let r_lin = vals[0].1.iter().zip(&a).map(|(c, r)| -(c + dot(r, &step))).fold(0.0f64, f64::max);
let fdec = -dot(&g, &step);
if r_lin < r0 {
let needed = -fdec / (r0 - r_lin);
if mu < 1.5 * needed {
mu = 2.0 * needed;
}
}
let predicted = fdec + mu * (r0 - r_lin);
let p: Vec<f64> = pts[0].iter().zip(&step).map(|(a, b)| a + b).collect();
let v = eval(&p);
let actual = phi(&vals[0], mu) - phi(&v, mu);
// Powell's choice of the vertex to replace: the one with the largest barycentric weight of
// the new point (above 1 when the step failed), and among the well-weighted ones the
// farthest (from the new point after a success, from the base after a failure).
let sigma: Vec<f64> = (0..n).map(|j| (0..n).map(|r| dinv[r][j] * step[r]).sum::<f64>().abs()).collect();
let mut ratio = if actual <= 0.0 { 1.0 } else { 0.0 };
let mut jdrop = None;
for (j, &sj) in sigma.iter().enumerate() {
if sj > ratio {
jdrop = Some(j);
ratio = sj;
}
}
let mut edgmax = DELTA * delta;
for j in 0..n {
if sigma[j] * face[j] >= ALPHA * delta || sigma[j] * face[j] >= face[j] {
let dist = if actual > 0.0 { norm(&d[j].iter().zip(&step).map(|(x, y)| x - y).collect::<Vec<_>>()) } else { lengths[j] };
if dist > edgmax {
jdrop = Some(j);
edgmax = dist;
}
}
}
if let Some(j) = jdrop {
vals[j + 1] = v;
pts[j + 1] = p;
}
let ratio = if predicted > 0.0 { actual / predicted } else { -1.0 };
let len = norm(&step);
delta = if ratio <= 0.1 { 0.5 * delta } else if ratio <= 0.7 { (0.5 * delta).max(len) } else { (0.5 * delta).max(2.0 * len) };
if delta <= 1.5 * rho {
delta = rho;
}
if actual > 0.0 && ratio > 0.1 {
continue;
}
if delta > rho {
continue;
}
}
// The step was short or poor at the smallest radius: improve the simplex if it is badly shaped, else shrink ρ.
if short && delta > rho {
delta = (0.5 * delta).max(rho);
if delta <= 1.5 * rho {
delta = rho;
}
continue;
}
let acceptable = {
let d: Vec<Vec<f64>> = (1..=n).map(|j| pts[j].iter().zip(&pts[0]).map(|(a, b)| a - b).collect()).collect();
invert(&d).map(|di| {
let lengths: Vec<f64> = d.iter().map(|r| norm(r)).collect();
let face: Vec<f64> = (0..n).map(|j| 1.0 / norm(&(0..n).map(|r| di[r][j]).collect::<Vec<_>>())).collect();
(lengths, face, di)
})
};
if let Some((lengths, face, di)) = acceptable {
let jl = (0..n).max_by(|&a, &b| lengths[a].total_cmp(&lengths[b])).unwrap();
let jf = (0..n).min_by(|&a, &b| face[a].total_cmp(&face[b])).unwrap();
// At the smallest radius the simplex is tightened before ρ is allowed to fall.
let beta = if delta <= rho { DELTA } else { BETA };
let j = if lengths[jl] > beta * delta {
Some(jl)
} else if face[jf] < ALPHA * delta {
Some(jf)
} else {
None
};
if let Some(j) = j {
// Geometry step: move vertex j to x0 ± ½ρ along the normal of its opposite face, on the
// side where the linear merit is lower.
let v: Vec<f64> = (0..n).map(|r| di[r][j]).collect();
let vn = norm(&v);
let mut dir: Vec<f64> = v.iter().map(|x| GAMMA * delta * x / vn).collect();
let lin_merit = |s: &[f64]| dot(&g, s) + mu * vals[0].1.iter().zip(&a).map(|(c, r)| -(c + dot(r, s))).fold(0.0f64, f64::max);
let neg: Vec<f64> = dir.iter().map(|x| -x).collect();
if lin_merit(&neg) < lin_merit(&dir) {
dir = neg;
}
let p: Vec<f64> = pts[0].iter().zip(&dir).map(|(a, b)| a + b).collect();
vals[j + 1] = eval(&p);
pts[j + 1] = p;
continue;
}
} else {
continue;
}
if rho <= options.rhoend {
break;
}
rho = (0.5 * rho).max(options.rhoend);
if rho <= 1.5 * options.rhoend {
rho = options.rhoend;
}
delta = rho;
// Powell's reduction of μ with ρ: keep it no larger than the range of f over the range of
// the constraints that have a vertex far below their maximum.
if mu > 0.0 {
let mut denom = 0.0f64;
let (fmin, fmax) = vals.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(v.0), hi.max(v.0)));
for k in 0..vals[0].1.len() {
let (cmin, cmax) = vals.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(v.1[k]), hi.max(v.1[k])));
if cmin < 0.5 * cmax {
let t = cmax.max(0.0) - cmin;
denom = if denom <= 0.0 { t } else { denom.min(t) };
}
}
if denom == 0.0 {
mu = 0.0;
} else if fmax - fmin < mu * denom {
mu = (fmax - fmin) / denom;
}
}
}
let best = (0..=n)
.min_by(|&a, &b| phi(&vals[a], mu).total_cmp(&phi(&vals[b], mu)).then(resmax(&vals[a].1).total_cmp(&resmax(&vals[b].1))))
.unwrap();
let x = pts[best].clone();
let (fx, c) = vals[best].clone();
let violation = resmax(&c);
Ok(ConstrainedResult {
parameters: x,
objective_value: fx,
equality_multipliers: Vec::new(),
inequality_multipliers: Vec::new(),
constraint_violation: violation,
iterations: nfev.get(),
converged: rho <= options.rhoend && violation <= options.catol && nfev.get() < options.max_evaluations,
})
}
/// Minimises `f(x)` subject to `h(x) = 0` and `g(x) ≤ 0` by a trust-region interior-point
/// method (SciPy's `minimize(method='trust-constr')` with a BFGS Hessian).
///
/// Inequalities get slacks, `g(x) + s = 0`, `s > 0`, and the barrier problem
/// `min f(x) − μ Σ ln sᵢ` subject to the equalities is solved by Byrd and Omojokun's
/// trust-region SQP for a decreasing sequence of `μ` (0.1, then a factor 0.2 each time the
/// barrier problem is solved to a tolerance that falls with it). Each SQP step is the sum of a
/// normal step, which reduces the linearised constraint violation within 0.8 of the trust
/// region, and a tangential step, projected conjugate gradients on the quadratic model in the
/// null space of the constraint Jacobian. Slack steps are scaled by `S` and kept a fraction
/// 0.995 from the boundary. Steps are accepted by the ℓ₂ merit function `φ + ν‖c‖`, the
/// Lagrangian Hessian is a damped BFGS approximation, and the multipliers are least-squares
/// estimates. `max_iterations` counts SQP iterations over all barrier problems.
pub fn trust_constr<P: ConstrainedProblem>(problem: &P, x0: Vec<f64>, options: ConstrainedOptions) -> Result<ConstrainedResult, ErrorsJSL> {
trust_constr_with(problem, x0, options, HessianUpdate::Bfgs, None)
}
/// How the Hessian of the Lagrangian is obtained (SciPy's `hess` argument).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum HessianUpdate {
/// Damped BFGS: always positive definite (SciPy's `BFGS()`).
Bfgs,
/// Symmetric rank-one: may be indefinite, which the trust region and the conjugate-gradient
/// iteration handle through negative curvature (SciPy's `SR1()`).
Sr1,
/// The exact Hessian from [`ConstrainedProblem::lagrangian_hessian`], evaluated at the current
/// point with the current multiplier estimates.
Exact,
}
/// What the callback of [`trust_constr_with`] sees after each iteration. `Display` gives the line
/// that SciPy prints with `verbose=2`, so a callback that prints it is the verbosity option:
/// `Some(&mut |s| { println!("{s}"); false })`.
#[derive(Clone, Copy, Debug)]
pub struct TrustConstrState<'a> {
pub x: &'a [f64],
pub objective_value: f64,
pub iterations: usize,
/// The trust-region radius.
pub radius: f64,
}
impl std::fmt::Display for TrustConstrState<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "iter {:4} f = {:+.8e} radius = {:.2e}", self.iterations, self.objective_value, self.radius)
}
}
/// [`trust_constr`] with a choice of the Hessian and a callback. The callback is called after every
/// iteration and stops the solve by returning `true` (the result then has `converged = false`).
/// `HessianUpdate::Exact` needs [`ConstrainedProblem::lagrangian_hessian`] to return the matrix.
pub 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> {
let n = x0.len();
if n == 0 {
return Err(ErrorsJSL::Misconfiguration("Initial parameters must be a non-empty vector."));
}
let mut x = x0;
let ng = problem.inequalities(&x).len();
let mut s: Vec<f64> = problem.inequalities(&x).iter().map(|g| (-1.5 * g).max(1.0)).collect();
let mut mu = if ng > 0 { 0.1 } else { 0.0 };
let mut barrier_tol = if ng > 0 { 0.1f64.max(options.tolerance) } else { options.tolerance };
let mut bfgs: Vec<Vec<f64>> = (0..n).map(|i| (0..n).map(|j| if i == j { 1.0 } else { 0.0 }).collect()).collect();
let mut delta: f64 = 1.0;
let mut nu: f64 = 1.0;
let mut iterations = 0;
// Constraint values c(z) = [h(x); g(x) + s] and the scaled Jacobian [Jh 0; Jg S].
let eval = |x: &[f64], s: &[f64]| -> (Vec<f64>, Vec<Vec<f64>>) {
let h = problem.equalities(x);
let g = problem.inequalities(x);
let (jh, jg) = (problem.equality_jacobian(x), problem.inequality_jacobian(x));
let mut c = h;
c.extend(g.iter().zip(s).map(|(a, b)| a + b));
let mut a: Vec<Vec<f64>> = jh.into_iter().map(|mut r| {
r.extend(std::iter::repeat_n(0.0, s.len()));
r
}).collect();
for (i, mut r) in jg.into_iter().enumerate() {
r.extend((0..s.len()).map(|k| if k == i { s[i] } else { 0.0 }));
a.push(r);
}
(c, a)
};
let converged;
let mut stopped = false;
let mut lambda: Vec<f64>;
loop {
// Solve the barrier problem for this μ.
loop {
let fx = problem.objective(&x);
let gx = problem.gradient(&x);
let (c, a) = eval(&x, &s);
let mut grad = gx.clone();
grad.extend(std::iter::repeat_n(-mu, ng));
// Least-squares multipliers and the optimality of the barrier problem.
lambda = if a.is_empty() { Vec::new() } else { aat_solve(&a, &matvec(&a, &grad)).iter().map(|t| -t).collect() };
let lag: Vec<f64> = grad.iter().zip(rmatvec(&a, &lambda, n + ng)).map(|(p, q)| p + q).collect();
let opt = lag.iter().fold(0.0f64, |m, v| m.max(v.abs()));
let viol = c.iter().fold(0.0f64, |m, v| m.max(v.abs()));
if (opt <= barrier_tol && viol <= barrier_tol) || iterations >= options.max_iterations {
break;
}
iterations += 1;
// The exact Hessian: as a matrix if the problem has one, else through products.
let mut exact_hv: Option<(Vec<f64>, Vec<f64>)> = None;
if hessian == HessianUpdate::Exact {
let (ne, ni) = (problem.equalities(&x).len(), ng);
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]) };
match problem.lagrangian_hessian(&x, &eq, &ineq) {
Some(h) => bfgs = h,
None => {
if problem.lagrangian_hessian_vector(&x, &eq, &ineq, &vec![0.0; n]).is_none() {
return Err(ErrorsJSL::Misconfiguration("HessianUpdate::Exact needs the problem's lagrangian_hessian or lagrangian_hessian_vector"));
}
exact_hv = Some((eq, ineq));
}
}
}
let hmul = |d: &[f64]| -> Vec<f64> {
let mut out = match &exact_hv {
Some((eq, ineq)) => problem.lagrangian_hessian_vector(&x, eq, ineq, &d[..n]).unwrap_or_else(|| vec![0.0; n]),
None => matvec(&bfgs, &d[..n]),
};
out.extend(d[n..].iter().map(|t| mu * t));
out
};
let d = byrd_omojokun_step(&hmul, &grad, &a, &c, delta, n);
// Merit: barrier objective plus ν‖c‖, with ν raised to make the step a descent.
let ad: Vec<f64> = matvec(&a, &d).iter().zip(&c).map(|(p, q)| p + q).collect();
let quad = dot(&grad, &d) + 0.5 * dot(&d, &hmul(&d));
let vpred = norm(&c) - norm(&ad);
if vpred > 1e-14 {
nu = nu.max(quad / (0.9 * vpred) + 1e-8);
}
let predicted = -quad + nu * vpred;
let barrier = |fx: f64, s: &[f64]| fx - mu * s.iter().map(|v| v.ln()).sum::<f64>();
let x_new: Vec<f64> = x.iter().zip(&d[..n]).map(|(p, q)| p + q).collect();
let s_new: Vec<f64> = s.iter().zip(&d[n..]).map(|(p, q)| p * (1.0 + q)).collect();
let (c_new, _) = eval(&x_new, &s_new);
let f_new = problem.objective(&x_new);
let actual = barrier(fx, &s) + nu * norm(&c) - barrier(f_new, &s_new) - nu * norm(&c_new);
let ratio = if predicted > 0.0 { actual / predicted } else { -1.0 };
let dn = norm(&d);
if ratio >= 0.75 {
delta = delta.max(7.0 * dn);
} else if ratio >= 0.3 {
delta = delta.max(2.0 * dn);
} else if ratio < 0.1 {
delta = 0.25 * dn.max(1e-16);
}
if delta < 1e-14 {
break;
}
if ratio > 1e-4 && f_new.is_finite() && s_new.iter().all(|v| *v > 0.0) {
// Damped BFGS on the Lagrangian's x-part, with the current multipliers.
let lag_x = |x: &[f64]| -> Vec<f64> {
let mut l = problem.gradient(x);
let mut jac = problem.equality_jacobian(x);
jac.extend(problem.inequality_jacobian(x));
for (row, lm) in jac.iter().zip(&lambda) {
l.iter_mut().zip(row).for_each(|(o, r)| *o += lm * r);
}
l
};
let (l0, l1) = (lag_x(&x), lag_x(&x_new));
let sv: Vec<f64> = d[..n].to_vec();
let mut yv: Vec<f64> = l1.iter().zip(&l0).map(|(p, q)| p - q).collect();
let bs = matvec(&bfgs, &sv);
let sbs = dot(&sv, &bs);
let sy = dot(&sv, &yv);
if hessian == HessianUpdate::Sr1 {
// B += (y − Bs)(y − Bs)ᵀ / ((y − Bs)ᵀ s), skipped when the denominator is small.
let r: Vec<f64> = yv.iter().zip(&bs).map(|(y, b)| y - b).collect();
let den = dot(&r, &sv);
if den.abs() > 1e-8 * norm(&r) * norm(&sv) && den.abs() > 1e-300 {
for i in 0..n {
for j in 0..n {
bfgs[i][j] += r[i] * r[j] / den;
}
}
}
} else if hessian == HessianUpdate::Bfgs && sbs > 1e-300 {
if sy < 0.2 * sbs {
let theta = 0.8 * sbs / (sbs - sy);
yv = yv.iter().zip(&bs).map(|(y, b)| theta * y + (1.0 - theta) * b).collect();
}
let sy = dot(&sv, &yv);
if sy > 1e-300 {
for i in 0..n {
for j in 0..n {
bfgs[i][j] += yv[i] * yv[j] / sy - bs[i] * bs[j] / sbs;
}
}
}
}
x = x_new;
s = s_new;
}
if let Some(cb) = callback.as_deref_mut() {
let state = TrustConstrState { x: &x, objective_value: problem.objective(&x), iterations, radius: delta };
if cb(&state) {
stopped = true;
break;
}
}
}
if stopped {
converged = false;
break;
}
if ng == 0 || iterations >= options.max_iterations {
converged = iterations < options.max_iterations;
break;
}
if barrier_tol <= options.tolerance {
converged = true;
break;
}
mu *= 0.2;
barrier_tol = (0.2 * barrier_tol).max(options.tolerance);
delta = delta.max(1.0);
}
let h = problem.equalities(&x);
let g = problem.inequalities(&x);
let violation = h.iter().map(|v| v.abs()).chain(g.iter().map(|v| v.max(0.0))).fold(0.0, f64::max);
let ne = h.len();
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]) };
Ok(ConstrainedResult {
objective_value: problem.objective(&x),
parameters: x,
equality_multipliers: eq,
inequality_multipliers: ineq,
constraint_violation: violation,
iterations,
converged: converged && violation <= options.tolerance.max(1e-6),
})
}
The references are from SciPy 1.17.1, written by book/generator/data/make_opt216_refs.py. The optima come from SLSQP at tolerance ; for the first problem the minimum is known exactly:
Table 5.8. COBYLA, COBYQA, SLSQP and trust-constr against SciPy.
| Method and problem | Library: distance from the optimum | SciPy: distance from the optimum |
|---|---|---|
| COBYLA: x₀x₁ on the half disc, from (1, 1) | 8e-1 (85 evaluations) | 1e0 (21 evaluations) |
| COBYQA: x₀x₁ on the half disc, from (1, 1) | 6e-9 (37 evaluations) | 8e-9 (37 evaluations) |
| SLSQP: x₀x₁ on the half disc, from (1, 1) | 7e-1 (2 iterations) | 7e-1 (2 iterations) |
| trust-constr: x₀x₁ on the half disc, from (1, 1) | 6e-8 (234 iterations) | 1e-8 (36 iterations) |
| COBYLA: Rosenbrock in the disc x² + y² ≤ 1.5 | 5e-2 (1000 evaluations) | 5e-2 (1000 evaluations) |
| … with up to 10 000 evaluations | 1e-9 (1367 evaluations) | 2e-9 (1304 evaluations) |
| COBYQA: Rosenbrock in the disc x² + y² ≤ 1.5 | 6e-9 (104 evaluations) | 9e-9 (110 evaluations) |
| SLSQP: Rosenbrock in the disc x² + y² ≤ 1.5 | 2e-9 (25 iterations) | 2e-9 (29 iterations) |
| trust-constr: Rosenbrock in the disc x² + y² ≤ 1.5 | 4e-7 (254 iterations) | 5e-7 (137 iterations) |
| COBYQA: HS071 (4 variables, 1 equality, 9 inequalities) | 1e-5 (2000 evaluations) | 5e-9 (53 evaluations) |
| SLSQP: HS071 (4 variables, 1 equality, 9 inequalities) | 5e-6 (6 iterations) | 3e-8 (17 iterations) |
| trust-constr: HS071 (4 variables, 1 equality, 9 inequalities) | 2e-6 (228 iterations) | 4e-7 (301 iterations) |
- On the first problem, from , SciPy’s COBYLA stops at with . Every point with satisfies the optimality conditions (the gradient is a multiple of the constraint’s), and neither method is led away from the line; the library stops at . The minimum, at , is found from other starts (the test uses ).
- On the Rosenbrock problem, both COBYLAs use up SciPy’s default budget of 1000 evaluations before converging. With more room, SciPy’s needs 1304 evaluations in the table’s reference (about 1160 with SciPy 1.17’s current COBYLA) and the library’s 1367; before 2.42 it needed 4905, because the radius only ever shrank, so the creep along the curved valley took thousands of steps of a millimetre. The test checks that it stays under 2000. PRIMA lowers by a factor of ten while it is far above
rhoendand then by the geometric mean with it; trying that schedule in place of halving cut the first example’s count from 85 to 47 and the Rosenbrock count at from 1367 to 1321, but at it stopped in the valley at against the optimum’s , so the halving stays. Matching SciPy’s evaluation counts and its stopping point on the first problem would need PRIMA’s own trust-region subproblem solver and its rules for choosing which point to drop, which are not reproducible from SciPy’s compiled library. - trust-constr reaches the optima to or better in both libraries.
Figure 5.9. Where COBYLA and trust-constr evaluate the objective on the Rosenbrock problem in a disc. Both creep along the curved valley toward the boundary, where the minimum lies.
SLSQP
SLSQP (Kraft, 1988; SciPy’s default method for constrained problems) is the sequential quadratic programming method of this chapter in the form that SciPy uses, and shgo’s local solver. slsqp takes the bounds as slices (or None) and the constraints from the problem’s inequalities () and equalities, with the problem’s gradient and Jacobians (central differences when it gives none).
- Each iteration solves the quadratic program subject to the linearised constraints and to , where is a positive definite BFGS approximation of the Hessian of the Lagrangian, started at the identity. The update uses the change of the Lagrangian’s gradient with the multipliers of the last subproblem (the bounds’ are left out) and Powell’s damping, which mixes with when .
- The step is chosen on the merit function (violations of the equalities and the inequalities), with weights that follow the multipliers. The line search accepts a decrease of 0.1 of the predicted one and otherwise interpolates a quadratic, in at most ten tries.
- When the linearised constraints cannot all hold, the constants of the constraints are scaled by a variable whose shortfall is penalised heavily in the subproblem, so that the step goes as far toward feasibility as the linearisation allows. If the direction is not a descent direction of the merit function, or the line search fails, is reset to the identity once.
- The run stops when the model predicts a decrease and a violation below
ftol(default ), or when the objective, or the point, changes by less thanftolwith the violation below it;maxiteris 100.
/// Minimises `problem.objective` subject to the bounds `lower ≤ x ≤ upper` (`None`: unbounded) and the
/// problem's `inequalities(x) ≤ 0` and `equalities(x) = 0`, by SLSQP (SciPy's `minimize(method='SLSQP')`).
/// The problem's `gradient` and Jacobians are used (central differences unless the problem provides them);
/// `x0` is moved into the bounds first.
pub fn slsqp<P: ConstrainedProblem>(problem: &P, x0: Vec<f64>, lower: Option<&[f64]>, upper: Option<&[f64]>, options: SlsqpOptions) -> Result<SlsqpResult, ErrorsJSL> {
let n = x0.len();
if n == 0 {
return Err(ErrorsJSL::Misconfiguration("Initial parameters must be a non-empty vector."));
}
if x0.iter().any(|v| !v.is_finite()) {
return Err(ErrorsJSL::InvalidInputRange("the initial point must be finite"));
}
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());
let xu: V = upper.map_or(vec![f64::INFINITY; n], |u| u.iter().map(|v| if v.is_nan() { f64::INFINITY } else { *v }).collect());
if xl.len() != n || xu.len() != n {
return Err(ErrorsJSL::IncompatibleArraySizes((xl.len().min(xu.len()), n)));
}
if (0..n).any(|i| xl[i] > xu[i]) {
return Err(ErrorsJSL::InvalidInputRange("a lower bound exceeds its upper bound"));
}
if options.ftol.is_nan() || options.ftol < 0.0 || options.max_iterations == 0 {
return Err(ErrorsJSL::InvalidInputRange("need ftol ≥ 0 and at least one iteration"));
}
let acc = options.ftol;
let mut x: V = (0..n).map(|i| x0[i].max(xl[i]).min(xu[i])).collect();
// The constraints as c(x) ≥ 0 after the equalities: c = [h; −g], with the rows of their Jacobians.
let constraints = |x: &[f64]| -> (V, usize) {
let (h, g) = (problem.equalities(x), problem.inequalities(x));
let me = h.len();
(h.into_iter().chain(g.into_iter().map(|v| -v)).collect(), me)
};
let jacobian = |x: &[f64]| -> M {
let (je, ji) = (problem.equality_jacobian(x), problem.inequality_jacobian(x));
je.into_iter().chain(ji.into_iter().map(|r| r.into_iter().map(|v| -v).collect())).collect()
};
let violation = |c: &[f64], me: usize| -> f64 { c.iter().enumerate().map(|(j, v)| if j < me { v.abs() } else { (-v).max(0.0) }).sum() };
let (mut nfev, mut njev) = (0usize, 0usize);
let mut f = problem.objective(&x);
let (mut c, me) = constraints(&x);
nfev += 1;
if !f.is_finite() || c.iter().any(|v| !v.is_finite()) {
return Err(ErrorsJSL::InvalidInputRange("the objective and constraints must be finite at the initial point"));
}
let m = c.len();
let mut g = problem.gradient(&x);
let mut a = jacobian(&x);
njev += 1;
let identity = || -> M { (0..n).map(|i| (0..n).map(|j| if i == j { 1.0 } else { 0.0 }).collect()).collect() };
let mut b = identity();
let mut b_is_identity = true;
let mut mu = vec![0.0; m];
let (mut lam_eq, mut lam_in): (V, V) = (vec![0.0; me], vec![0.0; m - me]);
let mut status = SlsqpStatus::IterationLimit;
let mut nit = 0;
'outer: while nit < options.max_iterations {
nit += 1;
// --- The subproblem: min ½ dᵀBd + gᵀd, A d + c (= 0 | ≥ 0), xl − x ≤ d ≤ xu − x.
let bound_rows = |extra: usize| -> Vec<(V, f64)> {
let mut out = Vec::new();
for i in 0..n {
if xl[i] > f64::NEG_INFINITY {
let mut r = vec![0.0; n + extra];
r[i] = 1.0;
out.push((r, x[i] - xl[i]));
}
if xu[i] < f64::INFINITY {
let mut r = vec![0.0; n + extra];
r[i] = -1.0;
out.push((r, xu[i] - x[i]));
}
}
out
};
// `d + (x − xl) ≥ 0` is the same as `d ≥ xl − x`.
let eq_rows: Vec<(V, f64)> = (0..me).map(|j| (a[j].clone(), c[j])).collect();
let mut in_rows: Vec<(V, f64)> = (me..m).map(|j| (a[j].clone(), c[j])).collect();
let n_general_in = in_rows.len();
in_rows.extend(bound_rows(0));
let mut relaxed = false;
let sol = match qp(&b, &g, &eq_rows, &in_rows) {
Some(s) => s,
None => {
// Inconsistent linearised constraints: scale their constants by δ ∈ [0, 1] and penalise 1 − δ.
relaxed = true;
let trace: f64 = (0..n).map(|i| b[i][i]).sum::<f64>() / n as f64;
let rho = 1e4 * trace.max(1.0) * (1.0 + g.iter().fold(0.0f64, |s, v| s.max(v.abs())));
let mut b_ext: M = b.iter().map(|r| r.iter().copied().chain(std::iter::once(0.0)).collect()).collect();
b_ext.push(vec![0.0; n + 1]);
b_ext[n][n] = rho;
let g_ext: V = g.iter().copied().chain(std::iter::once(-rho)).collect();
let eq_ext: Vec<(V, f64)> = (0..me).map(|j| (a[j].iter().copied().chain(std::iter::once(c[j])).collect(), 0.0)).collect();
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();
in_ext.extend(bound_rows(1));
let mut r0 = vec![0.0; n + 1];
r0[n] = 1.0;
in_ext.push((r0, 0.0));
let mut r1 = vec![0.0; n + 1];
r1[n] = -1.0;
in_ext.push((r1, 1.0));
match qp(&b_ext, &g_ext, &eq_ext, &in_ext) {
Some((mut z, le, li)) => {
z.truncate(n);
(z, le, li)
}
None => {
if !b_is_identity {
b = identity();
b_is_identity = true;
continue 'outer;
}
status = SlsqpStatus::InconsistentConstraints;
break 'outer;
}
}
}
};
let (d, le, li) = sol;
lam_eq = le;
lam_in = li[..n_general_in].to_vec();
let lam: V = lam_eq.iter().chain(&lam_in).copied().collect();
// --- Convergence of the model: a negligible predicted decrease at a feasible point.
let gd = dot(&g, &d);
let viol0 = violation(&c, me);
if !relaxed && gd.abs() < acc && viol0 < acc {
status = SlsqpStatus::Converged;
break;
}
// --- The merit function f + Σ μ_j |violation_j| and its directional derivative along d.
for j in 0..m {
mu[j] = lam[j].abs().max(0.5 * (mu[j] + lam[j].abs()));
}
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>() };
let t0 = merit(f, &c);
let dphi = gd - c.iter().enumerate().map(|(j, v)| mu[j] * if j < me { v.abs() } else { (-v).max(0.0) }).sum::<f64>();
if dphi >= 0.0 {
if !b_is_identity {
b = identity();
b_is_identity = true;
continue;
}
status = SlsqpStatus::PositiveDirectionalDerivative;
break;
}
// --- The line search: Armijo with safeguarded quadratic interpolation.
let mut alpha: f64 = 1.0;
let mut accepted = None;
for _ in 0..10 {
let xn: V = (0..n).map(|i| (x[i] + alpha * d[i]).max(xl[i]).min(xu[i])).collect();
let fn_ = problem.objective(&xn);
let (cn, _) = constraints(&xn);
nfev += 1;
if !fn_.is_finite() || cn.iter().any(|v| !v.is_finite()) {
alpha *= 0.5;
continue;
}
let t = merit(fn_, &cn);
if t - t0 <= 0.1 * alpha * dphi {
accepted = Some((xn, fn_, cn));
break;
}
let interp = -dphi * alpha * alpha / (2.0 * (t - t0 - dphi * alpha));
alpha = interp.max(0.1 * alpha).min(0.5 * alpha);
}
let Some((xn, fn_, cn)) = accepted else {
if !b_is_identity {
b = identity();
b_is_identity = true;
continue;
}
status = SlsqpStatus::LineSearchFailed;
break;
};
// --- The damped BFGS update of B with the change of the Lagrangian's gradient.
let g_new = problem.gradient(&xn);
let a_new = jacobian(&xn);
njev += 1;
let s: V = (0..n).map(|i| xn[i] - x[i]).collect();
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() };
let gl_new = grad_l(&g_new, &a_new);
let gl_old = grad_l(&g, &a);
let mut y: V = (0..n).map(|k| gl_new[k] - gl_old[k]).collect();
let bs: V = b.iter().map(|r| dot(r, &s)).collect();
let sbs = dot(&s, &bs);
if sbs > 1e-300 {
let mut sy = dot(&s, &y);
if sy < 0.2 * sbs {
let theta = 0.8 * sbs / (sbs - sy);
y = (0..n).map(|k| theta * y[k] + (1.0 - theta) * bs[k]).collect();
sy = dot(&s, &y);
}
for i in 0..n {
for j in 0..n {
b[i][j] += y[i] * y[j] / sy - bs[i] * bs[j] / sbs;
}
}
b_is_identity = false;
}
// --- Convergence: the objective or the point barely moved and the constraints hold.
let f_old = f;
x = xn;
f = fn_;
c = cn;
g = g_new;
a = a_new;
let step_norm = dot(&s, &s).sqrt();
if ((f - f_old).abs() < acc || step_norm < acc) && violation(&c, me) < acc {
status = SlsqpStatus::Converged;
break;
}
}
let (h_final, g_final) = (problem.equalities(&x), problem.inequalities(&x));
let maxcv = h_final.iter().map(|v| v.abs()).chain(g_final.iter().map(|v| v.max(0.0))).fold(0.0, f64::max);
Ok(SlsqpResult { jac: g, fun: f, maxcv, equality_multipliers: lam_eq, inequality_multipliers: lam_in, x, nfev, njev, nit, success: status == SlsqpStatus::Converged, status })
}
Against SciPy 1.17 with analytic derivatives the library follows the same iterations: 34 iterations and 47 evaluations on Rosenbrock from in both (the same point to six digits); 5 and 5 on Hock and Schittkowski’s no. 71; 11 and 11 on the largest box of surface area 6 (15 evaluations in both); 25 and 25 on Rosenbrock with bounds; 2 and 2 from on the tutorial problem, which both end at its stationary point (from the library needs 5 iterations and SciPy 6). In the disc the library takes 24 against 27. A case built so that the linearisation is inconsistent (min between two circles, started at their common centre) takes 6 iterations from the origin and 10 from in both. Table 5.8’s SLSQP rows differ in the derivatives: the library’s problems have none for the constraints, so both use finite differences.
COBYQA
COBYQA (Ragonneau, 2022; SciPy’s minimize(method='COBYQA')) is Powell’s successor to COBYLA with quadratic instead of linear models, for problems with bounds and nonlinear equality and inequality constraints, and no derivatives.
- The objective and every constraint get a quadratic model that interpolates their values at points (up to with
npt). Among the models that do, the one is taken whose Hessian differs least in the Frobenius norm from the previous model. That is the solution of one symmetric linear system of order for each function, with the same matrix, which the code factors by its eigendecomposition and reuses. A new point replaces the one that keeps the system best conditioned (the largest weighted Lagrange-polynomial determinant), and the base point of the models is moved to the best point when the two drift apart. - A step is Byrd and Omojokun’s, as in trust-constr but with the models: a normal step of at most reduces the violation of the linearised constraints within the bounds (by a truncated conjugate-gradient method on the slack form, with an improving search along the boundary), and a tangential step in the null space of the active linearisations reduces the model of the Lagrangian within what is left of the radius. A second-order correction follows a normal step that raised the merit function.
- Points are compared by the merit with the penalty raised to twice a multiplier-based threshold when it is below times that threshold, and lowered when the resolution falls. The multipliers come from a bound-constrained least-squares fit to the model gradient.
- When a step is short or fails, geometry steps replace the point farthest from the best by one that maximises its Lagrange polynomial (a Cauchy-type step and a search along the lines to the other points), so that the models stay valid. falls from
rhobegtorhoend, first by factors of ten and then, near the end, by square roots.
cobyqa takes the variables’ bounds as slices (or None) and the constraints from the problem’s inequalities () and equalities; variables with equal bounds are removed.
cobyqa_withadds linear constraints (LinearConstraints:a_ub x ≤ b_ub,a_eq x = b_eq), which are kept exact. Their linearisation is the constraint itself, so the normal and tangential steps see them as they are, and they enter the merit function, the multiplier estimates and the penalty bound; only the nonlinear constraints are modelled. It also takes a callback that sees the best point after every evaluation and stops the run by returningtrue.CobyqaOptionshas SciPy’sscale(the variables mapped to when all bounds are finite, with the linear constraints transformed to match),filter_size, and the history of the objective and the violation (with_history);CobyqaConstantsholds the 19 constants of the method and a flag for the improving search (improve_tcg), checked as SciPy checks them.
/// Minimises `problem.objective` subject to the bounds `lower ≤ x ≤ upper` (`None`: unbounded) and to the
/// problem's `inequalities(x) ≤ 0` and `equalities(x) = 0`, without derivatives, by COBYQA (SciPy's
/// `minimize(method='COBYQA')`). The gradient and Jacobian methods of [`ConstrainedProblem`] are never
/// called. See [`cobyqa_with`] for linear constraints and a callback.
pub fn cobyqa<P: ConstrainedProblem>(problem: &P, x0: Vec<f64>, lower: Option<&[f64]>, upper: Option<&[f64]>, options: CobyqaOptions) -> Result<CobyqaResult, ErrorsJSL> {
cobyqa_with(problem, x0, lower, upper, None, options, None)
}
/// [`cobyqa`] with linear constraints, which are kept exact (their linearisations are the constraints
/// themselves, and they count in the merit function and the multipliers) instead of being modelled, and a
/// callback that receives the best point after every evaluation and stops the run by returning `true`
/// (status [`CobyqaStatus::CallbackStop`], a success).
pub fn cobyqa_with<P: ConstrainedProblem>(
problem: &P,
x0: Vec<f64>,
lower: Option<&[f64]>,
upper: Option<&[f64]>,
linear: Option<&LinearConstraints>,
options: CobyqaOptions,
callback: Option<StopCallback<'_>>,
) -> Result<CobyqaResult, ErrorsJSL> {
let n_orig = x0.len();
if n_orig == 0 {
return Err(ErrorsJSL::Misconfiguration("Initial parameters must be a non-empty vector."));
}
if x0.iter().any(|v| !v.is_finite()) {
return Err(ErrorsJSL::InvalidInputRange("the initial point must be finite"));
}
options.constants.validate()?;
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());
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());
if xl_full.len() != n_orig || xu_full.len() != n_orig {
return Err(ErrorsJSL::IncompatibleArraySizes((xl_full.len().min(xu_full.len()), n_orig)));
}
if !(options.rhobeg > 0.0 && options.rhoend >= 0.0 && options.rhobeg >= options.rhoend) {
return Err(ErrorsJSL::InvalidInputRange("need rhobeg > 0 and 0 ≤ rhoend ≤ rhobeg"));
}
let lin_in = linear.cloned().unwrap_or_default();
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) {
return Err(ErrorsJSL::InvalidInputRange("linear constraints need rows of the problem's dimension and one bound per row"));
}
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);
// Fixed variables are removed.
let tol = get_arrays_tol(&[&xl_full, &xu_full]);
let fixed: Vec<bool> = (0..n_orig).map(|i| xl_full[i] <= xu_full[i] && (xl_full[i] - xu_full[i]).abs() < tol).collect();
let free: Vec<usize> = (0..n_orig).filter(|&i| !fixed[i]).collect();
let mut full = x0.clone();
for i in 0..n_orig {
if fixed[i] {
full[i] = (0.5 * (xl_full[i] + xu_full[i])).clamp(xl_full[i], xu_full[i]);
}
}
let n = free.len();
let mut xl: V = free.iter().map(|&i| xl_full[i]).collect();
let mut xu: V = free.iter().map(|&i| xu_full[i]).collect();
let mut x0r: V = free.iter().map(|&i| x0[i]).collect();
if bounds_feasible {
x0r = clip(&x0r, &xl, &xu);
}
// The linear constraints in the free variables (the fixed ones move to the right-hand side), then scaled.
let reduce = |rows: &[V], rhs: &[f64]| -> (Vec<V>, V) {
let a: Vec<V> = rows.iter().map(|r| free.iter().map(|&i| r[i]).collect()).collect();
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();
(a, b)
};
let (mut a_ub, mut b_ub) = reduce(&lin_in.a_ub, &lin_in.b_ub);
let (mut a_eq, mut b_eq) = reduce(&lin_in.a_eq, &lin_in.b_eq);
let scale = options.scale && bounds_feasible && n > 0 && xl.iter().chain(&xu).all(|v| v.is_finite());
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]) };
if scale {
for (rows, rhs) in [(&mut a_ub, &mut b_ub), (&mut a_eq, &mut b_eq)] {
for (r, b) in rows.iter_mut().zip(rhs.iter_mut()) {
*b -= dot(r, &shift);
for (v, f) in r.iter_mut().zip(&factor) {
*v *= f;
}
}
}
x0r = (0..n).map(|i| (x0r[i] - shift[i]) / factor[i]).collect();
xl = vec![-1.0; n];
xu = vec![1.0; n];
}
let lin = Lin { a_ub, b_ub, a_eq, b_eq };
let reduced = Reduced { p: problem, free: free.clone(), full: full.clone(), shift, factor };
let expand = |x: &[f64]| reduced.expand(x);
let probe_x0 = if n == 0 { vec![] } else { x0r.clone() };
let (m_ub, m_eq) = (problem.inequalities(&expand(&probe_x0)).len(), problem.equalities(&expand(&probe_x0)).len());
let reduced_ref = &reduced;
let cb = callback.map(|f| Box::new(move |xr: &[f64]| f(&reduced_ref.expand(xr))) as Callback<'_>);
let mut pb = Pb {
p: &reduced,
lin: &lin,
x0: x0r.clone(),
n_eval: 0,
feasibility_tol: options.feasibility_tol,
fun_filter: Vec::new(),
maxcv_filter: Vec::new(),
x_filter: Vec::new(),
filter_size: options.filter_size.unwrap_or(usize::MAX).max(1),
store_history: options.store_history,
history_size: options.history_size.unwrap_or(usize::MAX).max(1),
fun_history: Vec::new(),
maxcv_history: Vec::new(),
callback: cb,
};
if !bounds_feasible {
return Ok(build_result(&mut pb, 0.0, false, CobyqaStatus::InfeasibleBounds, 0, options.feasibility_tol, &expand));
}
if n == 0 {
let _ = pb.eval(&[], 0.0);
return Ok(build_result(&mut pb, 0.0, true, CobyqaStatus::AllFixed, 0, options.feasibility_tol, &expand));
}
let npt = options.npt.unwrap_or(2 * n + 1);
if npt == 0 || npt > (n + 1) * (n + 2) / 2 || npt < n + 1 {
return Err(ErrorsJSL::InvalidInputRange("npt must be between n + 1 and (n + 1)(n + 2)/2"));
}
let max_eval = options.max_evaluations.unwrap_or((500 * n).max(npt + 1));
let max_iter = options.max_iterations.unwrap_or(1000 * n);
let (mut rhobeg, mut rhoend) = (options.rhobeg, options.rhoend);
// The interpolation set.
let max_radius = 0.5 * (0..n).map(|i| xu[i] - xl[i]).fold(f64::INFINITY, f64::min);
if rhobeg > max_radius {
rhobeg = max_radius;
rhoend = rhoend.min(max_radius);
}
let mut x_base = x0r.clone();
let very_close_xl: Vec<bool> = (0..n).map(|i| x_base[i] <= xl[i] + 0.5 * rhobeg).collect();
for i in 0..n {
if very_close_xl[i] {
x_base[i] = xl[i];
}
}
for i in 0..n {
if xl[i] + 0.5 * rhobeg < x_base[i] && x_base[i] <= xl[i] + rhobeg {
x_base[i] = (xl[i] + rhobeg).min(xu[i]);
}
}
let very_close_xu: Vec<bool> = (0..n).map(|i| x_base[i] >= xu[i] - 0.5 * rhobeg).collect();
for i in 0..n {
if very_close_xu[i] {
x_base[i] = xu[i];
}
}
for i in 0..n {
if x_base[i] < xu[i] - 0.5 * rhobeg && xu[i] - rhobeg <= x_base[i] {
x_base[i] = (xu[i] - rhobeg).max(xl[i]);
}
}
let mut xpt: Vec<V> = vec![vec![0.0; n]; npt];
for k in 1..npt {
if k <= n {
xpt[k][k - 1] = if very_close_xu[k - 1] { -rhobeg } else { rhobeg };
} else if k <= 2 * n {
let i = k - n - 1;
xpt[k][i] = if very_close_xl[i] {
2.0 * rhobeg
} else if very_close_xu[i] {
-2.0 * rhobeg
} else {
-rhobeg
};
} else {
let spread = (k - n - 1) / n;
let k1 = k - (1 + spread) * n - 1;
let k2 = (k1 + spread) % n;
xpt[k][k1] = xpt[k1 + 1][k1];
xpt[k][k2] = xpt[k2 + 1][k2];
}
}
let ip = Interp { n, x_base, xpt, cache: RefCell::new(None) };
// Evaluate the interpolation points.
let mut fun_val = vec![f64::NAN; npt];
let mut cub_val: Vec<V> = vec![vec![]; npt];
let mut ceq_val: Vec<V> = vec![vec![]; npt];
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);
let c = options.constants;
for k in 0..npt {
if pb.n_eval >= max_eval {
return Ok(finish(&mut pb, false, CobyqaStatus::MaxIterations, 0, 0.0));
}
let x = ip.point(k);
let (f, cub, ceq) = match pb.eval(&x, 0.0) {
Ok(v) => v,
Err(_) => return Ok(finish(&mut pb, true, CobyqaStatus::CallbackStop, 0, 0.0)),
};
fun_val[k] = f;
cub_val[k] = cub;
ceq_val[k] = ceq;
if f <= options.target && maxcv_of(&lin, &x, &cub_val[k], &ceq_val[k]) <= options.feasibility_tol {
return Ok(finish(&mut pb, true, CobyqaStatus::TargetReached, 0, 0.0));
}
}
let build = || -> Result<Models, Stop> {
let fun = Quad::from_values(&ip, &fun_val)?;
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();
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();
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? })
};
let models = match build() {
Ok(m) => m,
Err(_) => return Ok(finish(&mut pb, false, CobyqaStatus::LinearAlgebra, 0, 0.0)),
};
let nonlinear = m_ub + m_eq > 0;
let constrained = nonlinear || !lin.a_ub.is_empty() || !lin.a_eq.is_empty();
let (l_ub, l_eq) = (lin.a_ub.len(), lin.a_eq.len());
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 };
tr.set_best_index();
let xb = tr.x_best();
tr.set_multipliers(&xb);
let eval_step = |pb: &mut Pb<Reduced<P>>, tr: &Tr, step: &[f64]| -> Result<(f64, V, V), Stop> {
if pb.n_eval >= max_eval {
return Err(Stop::MaxEval);
}
let x_eval = add(&tr.x_best(), step);
let (f, cub, ceq) = pb.eval(&x_eval, tr.penalty)?;
if f <= options.target && maxcv_of(&tr.lin, &x_eval, &cub, &ceq) <= options.feasibility_tol {
return Err(Stop::Target);
}
Ok((f, cub, ceq))
};
let stop_status = |s: &Stop| match s {
Stop::Target => (true, CobyqaStatus::TargetReached),
Stop::Callback => (true, CobyqaStatus::CallbackStop),
Stop::MaxEval => (false, CobyqaStatus::MaxEvaluations),
Stop::LinAlg => (false, CobyqaStatus::LinearAlgebra),
};
let mut n_iter = 0;
let mut n_short = 0;
let mut n_very_short = 0;
let mut n_alt = 0;
let (success, status);
'main: loop {
if n_iter >= max_iter {
status = CobyqaStatus::MaxIterations;
success = false;
break;
}
n_iter += 1;
if norm(&sub(&tr.x_best(), &tr.models.ip.x_base)) >= tr.c.large_shift_factor * tr.radius {
let xb = tr.x_best();
tr.models.shift_x_base(&xb);
}
let radius_save = tr.radius;
let (ns, ts) = tr.trust_region_step();
let mut step = add(&ns, &ts);
let s_norm = norm(&step);
let mut k_new = 0usize;
let (enhance, improve);
if s_norm <= tr.c.short_step_threshold * tr.resolution {
let r = tr.radius * tr.c.decrease_resolution_factor;
tr.set_radius(r);
if radius_save > tr.resolution {
n_short = 0;
n_very_short = 0;
} else {
n_short += 1;
n_very_short += 1;
if s_norm > 0.1 * tr.resolution {
n_very_short = 0;
}
}
enhance = n_short >= 5 || n_very_short >= 3;
if enhance {
n_short = 0;
n_very_short = 0;
improve = false;
} else {
match tr.index_to_remove(None) {
Ok((k, dist)) => {
k_new = k;
improve = dist > tr.radius.max(tr.c.resolution_factor * tr.resolution);
}
Err(s) => {
(success, status) = stop_status(&s);
break 'main;
}
}
}
} else {
let same_best = tr.increase_penalty(&step);
if same_best {
let (mut f, mut cub, mut ceq) = match eval_step(&mut pb, &tr, &step) {
Ok(v) => v,
Err(s) => {
(success, status) = stop_status(&s);
break 'main;
}
};
let merit_old = tr.merit_vals(&tr.x_best(), tr.fun_best(), tr.cub_best(), tr.ceq_best());
let merit_new = tr.merit_vals(&add(&tr.x_best(), &step), f, &cub, &ceq);
if tr.nonlinear && merit_new > merit_old && norm(&ns) > tr.c.byrd_omojokun_factor * tr.c.byrd_omojokun_factor * tr.radius {
let soc = tr.second_order_correction(&step);
if norm(&soc) > 0.0 {
axpy(&mut step, 1.0, &soc);
match eval_step(&mut pb, &tr, &step) {
Ok(v) => (f, cub, ceq) = v,
Err(s) => {
(success, status) = stop_status(&s);
break 'main;
}
}
}
}
let ratio = tr.reduction_ratio(&step, f, &cub, &ceq);
let x_new = add(&tr.x_best(), &step);
let k = match tr.index_to_remove(Some(&x_new)) {
Ok((k, _)) => k,
Err(s) => {
(success, status) = stop_status(&s);
break 'main;
}
};
let ill = match tr.models.update_interpolation(k, &x_new, f, &cub, &ceq) {
Ok(v) => v,
Err(s) => {
(success, status) = stop_status(&s);
break 'main;
}
};
tr.set_best_index();
tr.update_radius(&step, ratio);
if tr.radius <= tr.resolution {
if ratio >= tr.c.very_low_ratio {
n_alt = 0;
} else {
n_alt += 1;
let xb = tr.x_best();
let grad = tr.models.fun.grad(&xb, &tr.models.ip);
let alt = match Quad::from_values(&tr.models.ip, &tr.models.fun_val) {
Ok(q) => q.grad(&xb, &tr.models.ip),
Err(s) => {
(success, status) = stop_status(&s);
break 'main;
}
};
if norm(&grad) < tr.c.large_gradient_factor * norm(&alt) {
n_alt = 0;
}
if n_alt >= 3 {
if let Err(s) = tr.models.reset() {
(success, status) = stop_status(&s);
break 'main;
}
n_alt = 0;
}
}
}
tr.set_multipliers(&x_new);
match tr.index_to_remove(None) {
Ok((k2, dist)) => {
k_new = k2;
improve = ill || (ratio <= tr.c.low_ratio && dist > tr.radius.max(tr.c.resolution_factor * tr.resolution));
}
Err(s) => {
(success, status) = stop_status(&s);
break 'main;
}
}
enhance = radius_save <= tr.resolution && ratio <= tr.c.low_ratio && !improve;
} else {
enhance = false;
improve = false;
}
}
if enhance {
if tr.resolution <= rhoend {
success = true;
status = CobyqaStatus::RadiusReached;
break;
}
tr.enhance_resolution(rhoend);
tr.decrease_penalty();
}
if improve {
let step = match tr.geometry_step(k_new) {
Ok(s) => s,
Err(s) => {
(success, status) = stop_status(&s);
break 'main;
}
};
let (f, cub, ceq) = match eval_step(&mut pb, &tr, &step) {
Ok(v) => v,
Err(s) => {
(success, status) = stop_status(&s);
break 'main;
}
};
let x_new = add(&tr.x_best(), &step);
if let Err(s) = tr.models.update_interpolation(k_new, &x_new, f, &cub, &ceq) {
(success, status) = stop_status(&s);
break 'main;
}
tr.set_best_index();
}
}
Ok(finish(&mut pb, success, status, n_iter, tr.penalty))
}
Against SciPy 1.17’s COBYQA (the rows of Table 5.8 that start with COBYQA, run to ), the library reaches the same optimum to with 37, 100 and 58 evaluations, SciPy with 37, 110 and 53. On the unconstrained Rosenbrock function from the library needs 150 against SciPy’s 144, and on a bounded weighted sphere both need 29. With a linear constraint on Rosenbrock the counts are 89 and 88, with 33 and 33 (the same point to six digits), on the linearly constrained example of the Wikipedia entry on constrained optimisation 25 and 30, and a callback that stops at the 20th evaluation gives the same point, value and iteration count in both. With scaling to the unit box on Rosenbrock in the library needs 106 evaluations and SciPy 177. The counts are close, not equal: the eigendecomposition and the pivoted QR of the active constraints are computed by different routines, and where two choices tie (a point to drop, an active constraint to release) rounding picks differently. On Hock and Schittkowski’s no. 71 at SciPy’s default tolerance, SciPy stops with a constraint violation of (success = False), the library at .
Large problems: trust-krylov and LSMR
Two further methods suit problems too large for dense factorisations.
minimize_trust_krylov(SciPy’strust-krylov) solves each trust-region subproblem on a growing Krylov subspace , the GLTR method of Gould, Lucidi, Roma and Toint. The Lanczos process makes tridiagonal on the subspace, and the small problem is solved exactly. It needs only Hessian-vector products. Unlike Steihaug’s truncated conjugate gradients, it keeps improving the step after reaching the boundary.least_squares_lsmr(SciPy’sleast_squares(tr_solver='lsmr')) takes the Jacobian as any linear operator, such as a sparse matrix. It finds an approximate regularised Gauss-Newton step withlsmr(Fong and Saunders’ variant of LSQR, now inlinalg::sparse) and solves the trust-region problem exactly in the plane of that step and the gradient.
/// The trust-region subproblem `min gᵀp + ½ pᵀHp`, `‖p‖ ≤ Δ`, on growing Krylov subspaces
/// `span{g, Hg, H²g, …}` (Gould, Lucidi, Roma and Toint's GLTR, as in SciPy's `trust-krylov`).
/// The Lanczos process gives an orthonormal basis `Q` in which `H` is tridiagonal, `QᵀHQ = T`;
/// the small problem `min ‖g‖ e₁ᵀy + ½ yᵀTy`, `‖y‖ ≤ Δ` is solved exactly (Moré-Sorensen),
/// and the subspace grows until `‖(H + λI)p + g‖ = β_{k+1} |y_k|` is small. Unlike Steihaug's
/// truncated CG it keeps improving the step after reaching the boundary, so it also handles
/// negative curvature well. Returns the step, whether it is on the boundary, and the number of
/// Hessian-vector products.
fn krylov_step(g: &[f64], mut hessp: impl FnMut(&[f64]) -> Vec<f64>, radius: f64) -> (Vec<f64>, bool, usize) {
let n = g.len();
let gnorm = norm(g);
let tol = gnorm * 0.5f64.min(gnorm.sqrt());
let mut q: Vec<Vec<f64>> = vec![g.iter().map(|v| v / gnorm).collect()];
let (mut alpha, mut beta): (Vec<f64>, Vec<f64>) = (Vec::new(), Vec::new());
let mut products = 0;
loop {
let k = q.len() - 1;
let mut w = hessp(&q[k]);
products += 1;
let a = dot(&w, &q[k]);
alpha.push(a);
// Full reorthogonalisation keeps Q orthonormal for the modest sizes this targets.
for _ in 0..2 {
for qi in &q {
let c = dot(&w, qi);
w.iter_mut().zip(qi).for_each(|(x, y)| *x -= c * y);
}
}
let b = norm(&w);
// The projected problem.
let dim = k + 1;
let t = Array2::from_shape_fn((dim, dim), |(i, j)| {
if i == j {
alpha[i]
} else if i + 1 == j || j + 1 == i {
beta[i.min(j)]
} else {
0.0
}
});
let mut e1 = vec![0.0; dim];
e1[0] = gnorm;
let mut small = Model { fun: 0.0, jac: e1, hess: t, jac_mag: gnorm, lambda_lb: 0.0, previous_radius: -1.0 };
let (y, hits) = small.solve_exact(radius);
let done = dim == n || b <= 1e-12 * gnorm.max(1.0) || b * y[k].abs() <= tol;
if done {
let mut p = vec![0.0; n];
for (qi, yi) in q.iter().zip(&y) {
p.iter_mut().zip(qi).for_each(|(x, v)| *x += yi * v);
}
return (p, hits, products);
}
beta.push(b);
q.push(w.iter().map(|v| v / b).collect());
}
}
/// Minimises `f` by a trust-region Newton method whose subproblems are solved on Krylov
/// subspaces with Hessian-vector products only (SciPy's `minimize(method='trust-krylov')`).
/// The outer iteration is that of [`minimize_trust_region`]; `nhev` counts Hessian-vector
/// products.
pub fn minimize_trust_krylov(
mut f: impl FnMut(&[f64]) -> f64,
mut grad: impl FnMut(&[f64]) -> Vec<f64>,
mut hessp: impl FnMut(&[f64], &[f64]) -> Vec<f64>,
x0: &[f64],
options: TrustRegionOptions,
) -> Result<TrustRegionResult, ErrorsJSL> {
let o = options;
if !(0.0..0.25).contains(&o.eta) || o.max_trust_radius <= 0.0 || o.initial_trust_radius <= 0.0 || o.initial_trust_radius >= o.max_trust_radius {
return Err(ErrorsJSL::InvalidInputRange("need 0 ≤ η < ¼ and 0 < initial radius < maximum radius"));
}
let max_it = o.max_iterations.unwrap_or(200 * x0.len());
let mut x = x0.to_vec();
let (mut fx, mut gx) = (f(&x), grad(&x));
let (mut nfev, mut njev, mut nhev) = (1, 1, 0);
let mut radius = o.initial_trust_radius;
let (mut k, mut status) = (0, 0);
while norm(&gx) >= o.gtol {
let (p, hits, used) = krylov_step(&gx, |v| hessp(&x, v), radius);
let hp = hessp(&x, &p);
nhev += used + 1;
let predicted = fx + dot(&gx, &p) + 0.5 * dot(&p, &hp);
let xp: Vec<f64> = x.iter().zip(&p).map(|(a, b)| a + b).collect();
let fp = f(&xp);
nfev += 1;
let actual_reduction = fx - fp;
let predicted_reduction = fx - predicted;
if predicted_reduction <= 0.0 {
status = 2;
break;
}
let rho = actual_reduction / predicted_reduction;
if rho < 0.25 {
radius *= 0.25;
} else if rho > 0.75 && hits {
radius = (2.0 * radius).min(o.max_trust_radius);
}
if rho > o.eta {
x = xp;
fx = fp;
gx = grad(&x);
njev += 1;
}
k += 1;
if norm(&gx) < o.gtol {
break;
}
if k >= max_it {
status = 1;
break;
}
}
Ok(TrustRegionResult { x, fun: fx, jac: gx, iterations: k, nfev, njev, nhev, status })
}
Table 5.9. trust-krylov, least squares with LSMR, and LSMR against SciPy.
| Function and problem | Library against SciPy |
|---|---|
minimize_trust_krylov: 4-D Rosenbrock from (−1.2, 1, −0.5, 0.8) | x differs by 2e-11; iterations 48 vs 46, Hessian-vector products 163 vs 146 |
minimize_trust_krylov: 30-D Rosenbrock from (−1.2, 1, …) | x differs by 1e-11; iterations 133 vs 119, Hessian-vector products 1018 vs 714 |
least_squares_lsmr: Broyden tridiagonal system, n = 100, sparse Jacobian | x differs by 1e-16; cost 6.3e-19 vs 6.3e-19; evaluations 5 vs 5 |
least_squares_lsmr: exponential fit, free | x differs by 4e-16; evaluations 7 vs 7 |
least_squares_lsmr: exponential fit, rate bounded by 0.5 | x differs by 0; evaluations 8 vs 8 |
least_squares_lsmr: exponential fit, soft-L1 loss | x differs by 0; evaluations 6 vs 6 |
lsmr, 60 × 20 sparse, damping 0 | x differs by 5e-16; istop 7 vs 7; iterations 20 vs 20 |
lsmr, 60 × 20 sparse, damping 0.5 | x differs by 4e-16; istop 7 vs 7; iterations 20 vs 20 |
LSMR and the LSMR trust-region solver repeat SciPy’s iterations, with the same counts and the same solutions to rounding. trust-krylov reaches the same minima. Its subproblems are solved to a slightly different accuracy from SciPy’s trlib, so it takes a few more iterations and Hessian-vector products.
Strengths
- SQP: superlinear convergence, few evaluations, starts from infeasible points.
- Augmented Lagrangian: simple, reuses any unconstrained solver, tolerant of degenerate constraints.
- Both return Lagrange multipliers, which are sensitivities of the optimum to the constraints.
Weaknesses
- Local methods: with non-convex constraints they may find a local solution, or report infeasibility for a feasible problem.
- SQP’s dense QP limits it to moderate sizes; inconsistent linearised constraints make the QP fail.
- The augmented Lagrangian method needs many evaluations.
Exercises
- Verify the KKT conditions at for the example, and show that .
- Solve subject to by Lagrange multipliers. What is the sign of , and what does it mean?
- Show that the quadratic penalty method has a solution that violates the constraint by , and that the Hessian has condition number .
- Derive the dual of the equality-constrained QP subject to .
- Solve the box problem of the example program with the constraint added. Which constraints are active?
Hints and answers
- At : gives and , so . Both constraints are active (), so complementarity holds.
- With , stationarity gives and , so . The minimum is with and . With this sign convention for the constraint : the rate at which the optimal value falls as the circle is enlarged (, so at ).
- At the penalty minimiser , so , where is the multiplier: the violation is . The Hessian is : it has eigenvalues of size along the constraint normals and of size in the tangent directions, so its condition number is .
- With , stationarity gives . Substituting, the dual is , an unconstrained concave quadratic.
- The problem as stated is infeasible: since , the surface-area constraint forces , and the unit cube (sum 3) is already the smallest. Try a bound above 3 (say ) to see an active inequality, or a bound on a single side such as .
Further reading
- J. Nocedal and S. J. Wright, Numerical Optimization, 2nd ed., Springer, 2006, chapters 12, 17 and 18.
- M. J. D. Powell, “A fast algorithm for nonlinearly constrained optimization calculations”, in Numerical Analysis, Lecture Notes in Mathematics 630, Springer, 1978, 144–157.
- D. P. Bertsekas, Constrained Optimization and Lagrange Multiplier Methods, Academic Press, 1982.
- W. Hock and K. Schittkowski, Test Examples for Nonlinear Programming Codes, Lecture Notes in Economics and Mathematical Systems 187, Springer, 1981.
- H. W. Kuhn, “Nonlinear programming: a historical view”, SIAM-AMS Proceedings 9 (1976) 1–26.
- M. J. D. Powell, “A direct search optimization method that models the objective and constraint functions by linear interpolation”, in Advances in Optimization and Numerical Analysis, Kluwer, 1994, 51–67.
- R. H. Byrd, M. E. Hribar and J. Nocedal, “An interior point algorithm for large-scale nonlinear programming”, SIAM Journal on Optimization 9 (1999) 877–900.
- N. I. M. Gould, S. Lucidi, M. Roma and Ph. L. Toint, “Solving the trust-region subproblem using the Lanczos method”, SIAM Journal on Optimization 9 (1999) 504–525.
- D. C.-L. Fong and M. A. Saunders, “LSMR: an iterative algorithm for sparse least-squares problems”, SIAM Journal on Scientific Computing 33 (2011) 2950–2971.