Skip to main content

lib_jsl_optimization/
cobyla.rs

1//! COBYLA: constrained optimisation by linear approximations (Powell, 1994; SciPy's
2//! `minimize(method='COBYLA')`), a derivative-free method for problems with nonlinear
3//! inequality constraints.
4//!
5//! See the book entry [Constrained optimisation](https://jwkunz.github.io/lib_jsl/book/optimization/constrained.html#cobyla-and-trust-constr).
6
7use crate::constrained::{ConstrainedProblem, ConstrainedResult, bound_constrained_qp, solve_dense};
8use lib_jsl_core::ErrorsJSL;
9
10/// Options for [`cobyla`], with SciPy's defaults.
11#[derive(Clone, Copy, Debug)]
12#[non_exhaustive]
13pub struct CobylaOptions {
14    /// The initial trust-region radius (the size of the first simplex).
15    pub rhobeg: f64,
16    /// The final radius, which sets the accuracy (SciPy's `tol`).
17    pub rhoend: f64,
18    /// The largest number of function evaluations.
19    pub max_evaluations: usize,
20    /// The constraint violation accepted at the end (SciPy's `catol`).
21    pub catol: f64,
22}
23
24impl Default for CobylaOptions {
25    fn default() -> Self {
26        CobylaOptions { rhobeg: 1.0, rhoend: 1e-4, max_evaluations: 1000, catol: 2e-4 }
27    }
28}
29
30impl CobylaOptions {
31    /// The defaults with the given initial and final radii.
32    pub fn with_radii(rhobeg: f64, rhoend: f64) -> Self {
33        CobylaOptions { rhobeg, rhoend, ..Default::default() }
34    }
35}
36
37fn dot(a: &[f64], b: &[f64]) -> f64 {
38    a.iter().zip(b).map(|(x, y)| x * y).sum()
39}
40
41fn norm(a: &[f64]) -> f64 {
42    dot(a, a).sqrt()
43}
44
45/// `min qᵀd + (μ/2)(‖d‖² + w t²) + t·[stage 1]` subject to `A d − [stage 1] t ≤ b`: the minimiser
46/// for one μ through the dual (a bound-constrained QP in the multipliers). In stage 1 the extra
47/// variable `t ≥ 0` is the largest violation.
48fn regularised_lp(q: &[f64], a: &[Vec<f64>], b: &[f64], mu: f64, stage1: bool) -> Option<(Vec<f64>, f64)> {
49    let n = q.len();
50    let m = a.len();
51    // Variables z = (d, t) in stage 1, d otherwise; constraints rows r with r·z ≤ b (plus −t ≤ 0).
52    let nz = if stage1 { n + 1 } else { n };
53    let mut rows: Vec<Vec<f64>> = a.iter().map(|r| if stage1 { let mut r = r.clone(); r.push(-1.0); r } else { r.clone() }).collect();
54    let mut rhs = b.to_vec();
55    if stage1 {
56        let mut r = vec![0.0; nz];
57        r[n] = -1.0;
58        rows.push(r);
59        rhs.push(0.0);
60    }
61    let mut c = q.to_vec();
62    if stage1 {
63        c.push(1.0);
64    }
65    // Primal: min cᵀz + (μ/2)‖z‖² s.t. R z ≤ rhs. Dual: min ½ λᵀ(R Rᵀ/μ)λ + (R c/μ + rhs)ᵀλ, λ ≥ 0.
66    let k = rows.len();
67    let mm: Vec<Vec<f64>> = (0..k).map(|i| (0..k).map(|j| dot(&rows[i], &rows[j]) / mu).collect()).collect();
68    let qq: Vec<f64> = (0..k).map(|i| dot(&rows[i], &c) / mu + rhs[i]).collect();
69    let lambda = bound_constrained_qp(&mm, &qq, 0)?;
70    let mut z: Vec<f64> = c.iter().map(|v| -v / mu).collect();
71    for (r, l) in rows.iter().zip(&lambda) {
72        z.iter_mut().zip(r).for_each(|(zi, ri)| *zi -= l * ri / mu);
73    }
74    let _ = m;
75    let t = if stage1 { z[n].max(0.0) } else { 0.0 };
76    z.truncate(n);
77    Some((z, t))
78}
79
80/// The linear trust-region subproblem: minimise `gᵀd` subject to `c + A d ≥ 0` and `‖d‖ ≤ Δ`,
81/// or, if the linearised constraints cannot all hold in the ball, first minimise their largest
82/// violation and then `gᵀd` without letting it grow (Powell's two stages). Each stage is the
83/// limit of `min gᵀd + (μ/2)‖d‖²` as `μ` falls to the value where `‖d‖ = Δ`, found by bisection
84/// on `log μ`.
85fn subproblem(g: &[f64], c: &[f64], a: &[Vec<f64>], delta: f64) -> Vec<f64> {
86    // Constraints −A d ≤ c.
87    let neg: Vec<Vec<f64>> = a.iter().map(|r| r.iter().map(|v| -v).collect()).collect();
88    let solve = |q: &[f64], b: &[f64], stage1: bool| -> Vec<f64> {
89        let scale = (norm(q) + 1.0) / delta;
90        let (mut lo, mut hi) = ((scale * 1e-10).ln(), (scale * 1e10).ln());
91        let at = |l: f64| regularised_lp(q, &neg, b, l.exp(), stage1).map(|r| r.0);
92        match at(lo) {
93            Some(d) if norm(&d) <= delta => return d,
94            _ => {}
95        }
96        let mut best = at(hi).unwrap_or_else(|| vec![0.0; q.len()]);
97        for _ in 0..60 {
98            let mid = 0.5 * (lo + hi);
99            match at(mid) {
100                Some(d) if norm(&d) <= delta => {
101                    best = d;
102                    hi = mid;
103                }
104                _ => lo = mid,
105            }
106            if hi - lo < 1e-9 {
107                break;
108            }
109        }
110        best
111    };
112    let n = g.len();
113    if c.iter().all(|&v| v >= 0.0) {
114        return solve(g, c, false);
115    }
116    // Stage 1: the smallest largest violation within the ball.
117    let d1 = solve(&vec![0.0; n], c, true);
118    let viol = c.iter().zip(a).map(|(ci, r)| -(ci + dot(r, &d1))).fold(0.0f64, f64::max);
119    if viol <= 0.0 {
120        return solve(g, c, false);
121    }
122    let relaxed: Vec<f64> = c.iter().map(|v| v + viol * (1.0 + 1e-9)).collect();
123    let d2 = solve(g, &relaxed, false);
124    let v2 = c.iter().zip(a).map(|(ci, r)| -(ci + dot(r, &d2))).fold(0.0f64, f64::max);
125    if v2 <= viol * (1.0 + 1e-6) + 1e-14 { d2 } else { d1 }
126}
127
128/// Inverts the `n × n` matrix whose rows are `rows`.
129fn invert(rows: &[Vec<f64>]) -> Option<Vec<Vec<f64>>> {
130    let n = rows.len();
131    let cols: Vec<Vec<f64>> = (0..n).map(|j| solve_dense(rows.to_vec(), (0..n).map(|i| if i == j { 1.0 } else { 0.0 }).collect())).collect::<Option<_>>()?;
132    Some((0..n).map(|i| (0..n).map(|j| cols[j][i]).collect()).collect())
133}
134
135// ANCHOR: cobyla
136const ALPHA: f64 = 0.25;
137const BETA: f64 = 2.1;
138const GAMMA: f64 = 0.5;
139const DELTA: f64 = 1.1;
140
141/// Minimises `f` subject to `g(x) ≤ 0` and `h(x) = 0` without derivatives, by Powell's COBYLA
142/// (SciPy's `minimize(method='COBYLA')`; equalities become pairs of inequalities).
143///
144/// The method keeps a simplex of `n + 1` points and the linear functions that interpolate the
145/// objective and every constraint on it. Each iteration minimises the linear objective subject
146/// to the linear constraints within a ball of radius `ρ` around the best vertex (best by the
147/// merit `f + μ·max violation`, with `μ` raised whenever a step would not decrease it), and
148/// replaces a vertex by the new point. Steps that would spoil the simplex's shape are replaced
149/// by geometry steps, and `ρ` is halved when the trust-region steps become short, until it
150/// reaches `rhoend`. The derivatives defaulted by [`ConstrainedProblem`] are never called.
151pub fn cobyla<P: ConstrainedProblem>(problem: &P, x0: Vec<f64>, options: CobylaOptions) -> Result<ConstrainedResult, ErrorsJSL> {
152    let n = x0.len();
153    if n == 0 {
154        return Err(ErrorsJSL::Misconfiguration("Initial parameters must be a non-empty vector."));
155    }
156    if !(options.rhobeg > 0.0 && options.rhoend > 0.0 && options.rhoend <= options.rhobeg) {
157        return Err(ErrorsJSL::InvalidInputRange("need 0 < rhoend ≤ rhobeg"));
158    }
159    // Constraints as c(x) ≥ 0.
160    let cons = |x: &[f64]| -> Vec<f64> {
161        let mut c: Vec<f64> = problem.inequalities(x).iter().map(|v| -v).collect();
162        for h in problem.equalities(x) {
163            c.push(h);
164            c.push(-h);
165        }
166        c
167    };
168    let nfev = std::cell::Cell::new(0usize);
169    let eval = |x: &[f64]| -> (f64, Vec<f64>) {
170        nfev.set(nfev.get() + 1);
171        (problem.objective(x), cons(x))
172    };
173    let resmax = |c: &[f64]| c.iter().map(|v| -v).fold(0.0f64, f64::max);
174    let mut rho = options.rhobeg;
175    // The trust-region radius, between ρ (the accuracy still wanted) and what the steps have earned.
176    let mut delta = rho;
177    let mut mu = 0.0f64;
178    // Vertex 0 is x0; vertex j is x0 + ρ e_j.
179    let mut pts: Vec<Vec<f64>> = vec![x0.clone()];
180    let mut vals: Vec<(f64, Vec<f64>)> = vec![eval(&x0)];
181    for j in 0..n {
182        let mut p = x0.clone();
183        p[j] += rho;
184        vals.push(eval(&p));
185        pts.push(p);
186    }
187    let phi = |v: &(f64, Vec<f64>), mu: f64| v.0 + mu * resmax(&v.1);
188    loop {
189        // Make vertex 0 the best by the merit (ties: the smaller violation).
190        let best = (0..=n)
191            .min_by(|&a, &b| {
192                let (pa, pb) = (phi(&vals[a], mu), phi(&vals[b], mu));
193                pa.total_cmp(&pb).then(resmax(&vals[a].1).total_cmp(&resmax(&vals[b].1)))
194            })
195            .unwrap();
196        pts.swap(0, best);
197        vals.swap(0, best);
198        if nfev.get() >= options.max_evaluations {
199            break;
200        }
201        // Linear models: rows of D are the displacements x_j − x_0; gradients solve D ∇ = Δ.
202        let d: Vec<Vec<f64>> = (1..=n).map(|j| pts[j].iter().zip(&pts[0]).map(|(a, b)| a - b).collect()).collect();
203        let Some(dinv) = invert(&d) else {
204            // A degenerate simplex: rebuild it around the best point.
205            for j in 0..n {
206                let mut p = pts[0].clone();
207                p[j] += rho;
208                vals[j + 1] = eval(&p);
209                pts[j + 1] = p;
210            }
211            continue;
212        };
213        let grad_of = |k: Option<usize>| -> Vec<f64> {
214            let diffs: Vec<f64> = (1..=n).map(|j| match k {
215                None => vals[j].0 - vals[0].0,
216                Some(i) => vals[j].1[i] - vals[0].1[i],
217            }).collect();
218            (0..n).map(|r| (0..n).map(|j| dinv[r][j] * diffs[j]).sum()).collect()
219        };
220        let g = grad_of(None);
221        let mc = vals[0].1.len();
222        let a: Vec<Vec<f64>> = (0..mc).map(|i| grad_of(Some(i))).collect();
223        // Simplex geometry: Powell's acceptability test with factors 1.1 (lengths) and 0.25
224        // (distances of each vertex from the opposite face).
225        let lengths: Vec<f64> = d.iter().map(|r| norm(r)).collect();
226        let face: Vec<f64> = (0..n).map(|j| 1.0 / norm(&(0..n).map(|r| dinv[r][j]).collect::<Vec<_>>())).collect();
227        // The trust-region step.
228        let step = subproblem(&g, &vals[0].1, &a, delta);
229        let short = norm(&step) < 0.5 * delta;
230        if !short {
231            // Raise μ until the step decreases the linearised merit.
232            let r0 = resmax(&vals[0].1);
233            let r_lin = vals[0].1.iter().zip(&a).map(|(c, r)| -(c + dot(r, &step))).fold(0.0f64, f64::max);
234            let fdec = -dot(&g, &step);
235            if r_lin < r0 {
236                let needed = -fdec / (r0 - r_lin);
237                if mu < 1.5 * needed {
238                    mu = 2.0 * needed;
239                }
240            }
241            let predicted = fdec + mu * (r0 - r_lin);
242            let p: Vec<f64> = pts[0].iter().zip(&step).map(|(a, b)| a + b).collect();
243            let v = eval(&p);
244            let actual = phi(&vals[0], mu) - phi(&v, mu);
245            // Powell's choice of the vertex to replace: the one with the largest barycentric weight of
246            // the new point (above 1 when the step failed), and among the well-weighted ones the
247            // farthest (from the new point after a success, from the base after a failure).
248            let sigma: Vec<f64> = (0..n).map(|j| (0..n).map(|r| dinv[r][j] * step[r]).sum::<f64>().abs()).collect();
249            let mut ratio = if actual <= 0.0 { 1.0 } else { 0.0 };
250            let mut jdrop = None;
251            for (j, &sj) in sigma.iter().enumerate() {
252                if sj > ratio {
253                    jdrop = Some(j);
254                    ratio = sj;
255                }
256            }
257            let mut edgmax = DELTA * delta;
258            for j in 0..n {
259                if sigma[j] * face[j] >= ALPHA * delta || sigma[j] * face[j] >= face[j] {
260                    let dist = if actual > 0.0 { norm(&d[j].iter().zip(&step).map(|(x, y)| x - y).collect::<Vec<_>>()) } else { lengths[j] };
261                    if dist > edgmax {
262                        jdrop = Some(j);
263                        edgmax = dist;
264                    }
265                }
266            }
267            if let Some(j) = jdrop {
268                vals[j + 1] = v;
269                pts[j + 1] = p;
270            }
271            let ratio = if predicted > 0.0 { actual / predicted } else { -1.0 };
272            let len = norm(&step);
273            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) };
274            if delta <= 1.5 * rho {
275                delta = rho;
276            }
277            if actual > 0.0 && ratio > 0.1 {
278                continue;
279            }
280            if delta > rho {
281                continue;
282            }
283        }
284        // The step was short or poor at the smallest radius: improve the simplex if it is badly shaped, else shrink ρ.
285        if short && delta > rho {
286            delta = (0.5 * delta).max(rho);
287            if delta <= 1.5 * rho {
288                delta = rho;
289            }
290            continue;
291        }
292        let acceptable = {
293            let d: Vec<Vec<f64>> = (1..=n).map(|j| pts[j].iter().zip(&pts[0]).map(|(a, b)| a - b).collect()).collect();
294            invert(&d).map(|di| {
295                let lengths: Vec<f64> = d.iter().map(|r| norm(r)).collect();
296                let face: Vec<f64> = (0..n).map(|j| 1.0 / norm(&(0..n).map(|r| di[r][j]).collect::<Vec<_>>())).collect();
297                (lengths, face, di)
298            })
299        };
300        if let Some((lengths, face, di)) = acceptable {
301            let jl = (0..n).max_by(|&a, &b| lengths[a].total_cmp(&lengths[b])).unwrap();
302            let jf = (0..n).min_by(|&a, &b| face[a].total_cmp(&face[b])).unwrap();
303            // At the smallest radius the simplex is tightened before ρ is allowed to fall.
304            let beta = if delta <= rho { DELTA } else { BETA };
305            let j = if lengths[jl] > beta * delta {
306                Some(jl)
307            } else if face[jf] < ALPHA * delta {
308                Some(jf)
309            } else {
310                None
311            };
312            if let Some(j) = j {
313                // Geometry step: move vertex j to x0 ± ½ρ along the normal of its opposite face, on the
314                // side where the linear merit is lower.
315                let v: Vec<f64> = (0..n).map(|r| di[r][j]).collect();
316                let vn = norm(&v);
317                let mut dir: Vec<f64> = v.iter().map(|x| GAMMA * delta * x / vn).collect();
318                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);
319                let neg: Vec<f64> = dir.iter().map(|x| -x).collect();
320                if lin_merit(&neg) < lin_merit(&dir) {
321                    dir = neg;
322                }
323                let p: Vec<f64> = pts[0].iter().zip(&dir).map(|(a, b)| a + b).collect();
324                vals[j + 1] = eval(&p);
325                pts[j + 1] = p;
326                continue;
327            }
328        } else {
329            continue;
330        }
331        if rho <= options.rhoend {
332            break;
333        }
334        rho = (0.5 * rho).max(options.rhoend);
335        if rho <= 1.5 * options.rhoend {
336            rho = options.rhoend;
337        }
338        delta = rho;
339        // Powell's reduction of μ with ρ: keep it no larger than the range of f over the range of
340        // the constraints that have a vertex far below their maximum.
341        if mu > 0.0 {
342            let mut denom = 0.0f64;
343            let (fmin, fmax) = vals.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(v.0), hi.max(v.0)));
344            for k in 0..vals[0].1.len() {
345                let (cmin, cmax) = vals.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(v.1[k]), hi.max(v.1[k])));
346                if cmin < 0.5 * cmax {
347                    let t = cmax.max(0.0) - cmin;
348                    denom = if denom <= 0.0 { t } else { denom.min(t) };
349                }
350            }
351            if denom == 0.0 {
352                mu = 0.0;
353            } else if fmax - fmin < mu * denom {
354                mu = (fmax - fmin) / denom;
355            }
356        }
357    }
358    let best = (0..=n)
359        .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))))
360        .unwrap();
361    let x = pts[best].clone();
362    let (fx, c) = vals[best].clone();
363    let violation = resmax(&c);
364    Ok(ConstrainedResult {
365        parameters: x,
366        objective_value: fx,
367        equality_multipliers: Vec::new(),
368        inequality_multipliers: Vec::new(),
369        constraint_violation: violation,
370        iterations: nfev.get(),
371        converged: rho <= options.rhoend && violation <= options.catol && nfev.get() < options.max_evaluations,
372    })
373}
374// ANCHOR_END: cobyla
375
376#[cfg(test)]
377mod tests {
378    use super::*;
379
380    struct Tutorial;
381    impl ConstrainedProblem for Tutorial {
382        // SciPy's COBYLA example: min x0 x1 s.t. 1 − x0² − x1² ≥ 0, x1 ≥ 0.
383        fn objective(&self, x: &[f64]) -> f64 {
384            x[0] * x[1]
385        }
386        fn inequalities(&self, x: &[f64]) -> Vec<f64> {
387            vec![x[0] * x[0] + x[1] * x[1] - 1.0, -x[1]]
388        }
389    }
390
391    struct Rosen;
392    impl ConstrainedProblem for Rosen {
393        fn objective(&self, x: &[f64]) -> f64 {
394            100.0 * (x[1] - x[0] * x[0]).powi(2) + (1.0 - x[0]).powi(2)
395        }
396        // A disc that excludes the unconstrained minimum (1, 1).
397        fn inequalities(&self, x: &[f64]) -> Vec<f64> {
398            vec![x[0] * x[0] + x[1] * x[1] - 1.5]
399        }
400        fn equalities(&self, _x: &[f64]) -> Vec<f64> {
401            Vec::new()
402        }
403    }
404
405    #[test]
406    fn solves_the_scipy_example_and_a_constrained_rosenbrock() {
407        let r = cobyla(&Tutorial, vec![-0.5, 1.0], CobylaOptions::with_radii(1.0, 1e-8)).unwrap();
408        let s = 0.5f64.sqrt();
409        assert!(r.converged && (r.parameters[0] + s).abs() < 1e-6 && (r.parameters[1] - s).abs() < 1e-6, "{:?}", r.parameters);
410        let r = cobyla(&Rosen, vec![-1.0, 0.0], CobylaOptions { rhoend: 1e-8, max_evaluations: 5000, ..Default::default() }).unwrap();
411        // The minimum lies on the circle x² + y² = 1.5.
412        let x = &r.parameters;
413        assert!(r.converged && (x[0] * x[0] + x[1] * x[1] - 1.5).abs() < 1e-6, "{x:?} {}", r.iterations);
414        assert!((x[0] - 0.9072).abs() < 1e-3 && (x[1] - 0.8228).abs() < 1e-3, "{x:?}");
415        // SciPy needs about 1160 evaluations here (the vertex-replacement and radius rules matter).
416        assert!(r.iterations < 2000, "{} evaluations", r.iterations);
417    }
418}