1use crate::constrained::{ConstrainedProblem, ConstrainedResult, bound_constrained_qp, solve_dense};
8use lib_jsl_core::ErrorsJSL;
9
10#[derive(Clone, Copy, Debug)]
12#[non_exhaustive]
13pub struct CobylaOptions {
14 pub rhobeg: f64,
16 pub rhoend: f64,
18 pub max_evaluations: usize,
20 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 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
45fn 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 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 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
80fn subproblem(g: &[f64], c: &[f64], a: &[Vec<f64>], delta: f64) -> Vec<f64> {
86 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 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
128fn 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
135const ALPHA: f64 = 0.25;
137const BETA: f64 = 2.1;
138const GAMMA: f64 = 0.5;
139const DELTA: f64 = 1.1;
140
141pub 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 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 let mut delta = rho;
177 let mut mu = 0.0f64;
178 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 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 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 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 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 let step = subproblem(&g, &vals[0].1, &a, delta);
229 let short = norm(&step) < 0.5 * delta;
230 if !short {
231 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 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 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 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 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 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#[cfg(test)]
377mod tests {
378 use super::*;
379
380 struct Tutorial;
381 impl ConstrainedProblem for Tutorial {
382 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 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 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 assert!(r.iterations < 2000, "{} evaluations", r.iterations);
417 }
418}