1use crate::optimization_traits::{GradientBasedMinimizationEngine, GradientFunction, MinimizationControls, ObjectiveFunction};
20use crate::quasi_newton::Lbfgs;
21use lib_jsl_core::ErrorsJSL;
22
23fn central_gradient(f: &dyn Fn(&[f64]) -> f64, x: &[f64]) -> Vec<f64> {
24 let mut z = x.to_vec();
25 (0..x.len())
26 .map(|k| {
27 let h = 1e-6 * x[k].abs().max(1.0);
28 z[k] = x[k] + h;
29 let up = f(&z);
30 z[k] = x[k] - h;
31 let down = f(&z);
32 z[k] = x[k];
33 (up - down) / (2.0 * h)
34 })
35 .collect()
36}
37
38fn central_jacobian(c: &dyn Fn(&[f64]) -> Vec<f64>, x: &[f64], m: usize) -> Vec<Vec<f64>> {
39 let mut jac = vec![vec![0.0; x.len()]; m];
40 let mut z = x.to_vec();
41 for k in 0..x.len() {
42 let h = 1e-6 * x[k].abs().max(1.0);
43 z[k] = x[k] + h;
44 let up = c(&z);
45 z[k] = x[k] - h;
46 let down = c(&z);
47 z[k] = x[k];
48 for i in 0..m {
49 jac[i][k] = (up[i] - down[i]) / (2.0 * h);
50 }
51 }
52 jac
53}
54
55pub trait ConstrainedProblem {
58 fn objective(&self, x: &[f64]) -> f64;
59 fn gradient(&self, x: &[f64]) -> Vec<f64> {
60 central_gradient(&|z| self.objective(z), x)
61 }
62 fn equalities(&self, _x: &[f64]) -> Vec<f64> {
64 Vec::new()
65 }
66 fn equality_jacobian(&self, x: &[f64]) -> Vec<Vec<f64>> {
68 let m = self.equalities(x).len();
69 central_jacobian(&|z| self.equalities(z), x, m)
70 }
71 fn inequalities(&self, _x: &[f64]) -> Vec<f64> {
73 Vec::new()
74 }
75 fn inequality_jacobian(&self, x: &[f64]) -> Vec<Vec<f64>> {
77 let m = self.inequalities(x).len();
78 central_jacobian(&|z| self.inequalities(z), x, m)
79 }
80 fn lagrangian_hessian(&self, _x: &[f64], _equality_multipliers: &[f64], _inequality_multipliers: &[f64]) -> Option<Vec<Vec<f64>>> {
84 None
85 }
86 fn lagrangian_hessian_vector(&self, _x: &[f64], _equality_multipliers: &[f64], _inequality_multipliers: &[f64], _v: &[f64]) -> Option<Vec<f64>> {
91 None
92 }
93}
94
95#[derive(Debug, Clone, Copy)]
97pub struct ConstrainedOptions {
98 pub tolerance: f64,
100 pub max_iterations: usize,
101}
102
103impl Default for ConstrainedOptions {
104 fn default() -> Self {
105 ConstrainedOptions { tolerance: 1e-8, max_iterations: 200 }
106 }
107}
108
109#[derive(Debug, Clone)]
111#[non_exhaustive]
112pub struct ConstrainedResult {
113 pub parameters: Vec<f64>,
114 pub objective_value: f64,
115 pub equality_multipliers: Vec<f64>,
117 pub inequality_multipliers: Vec<f64>,
119 pub constraint_violation: f64,
121 pub iterations: usize,
122 pub converged: bool,
123}
124
125fn violation(h: &[f64], g: &[f64]) -> f64 {
126 h.iter().map(|v| v.abs()).chain(g.iter().map(|v| v.max(0.0))).fold(0.0, f64::max)
127}
128
129fn dot(a: &[f64], b: &[f64]) -> f64 {
130 a.iter().zip(b).map(|(p, q)| p * q).sum()
131}
132
133pub(crate) fn solve_dense(mut a: Vec<Vec<f64>>, mut b: Vec<f64>) -> Option<Vec<f64>> {
135 let n = b.len();
136 for k in 0..n {
137 let p = (k..n).max_by(|&i, &j| a[i][k].abs().total_cmp(&a[j][k].abs()))?;
138 if a[p][k].abs() < 1e-300 || !a[p][k].is_finite() {
139 return None;
140 }
141 a.swap(k, p);
142 b.swap(k, p);
143 for i in k + 1..n {
144 let m = a[i][k] / a[k][k];
145 let (top, rest) = a.split_at_mut(i);
146 rest[0][k..].iter_mut().zip(&top[k][k..]).for_each(|(x, y)| *x -= m * y);
147 b[i] -= m * b[k];
148 }
149 }
150 for i in (0..n).rev() {
151 let s: f64 = (i + 1..n).map(|j| a[i][j] * b[j]).sum();
152 b[i] = (b[i] - s) / a[i][i];
153 }
154 Some(b)
155}
156
157pub(crate) fn bound_constrained_qp(m: &[Vec<f64>], q: &[f64], first_bounded: usize) -> Option<Vec<f64>> {
160 let n = q.len();
161 let trace: f64 = (0..n).map(|i| m[i][i]).sum::<f64>().max(1.0);
162 let regularisation = 1e-12 * trace; let mut y = vec![0.0; n];
164 let mut active: Vec<bool> = (0..n).map(|i| i >= first_bounded).collect();
165 for _ in 0..(10 * n + 50) {
166 let free: Vec<usize> = (0..n).filter(|&i| !active[i]).collect();
168 let sub: Vec<Vec<f64>> = free.iter().map(|&i| free.iter().map(|&j| m[i][j] + if i == j { regularisation } else { 0.0 }).collect()).collect();
169 let rhs: Vec<f64> = free.iter().map(|&i| -q[i]).collect();
170 let z = if free.is_empty() { Vec::new() } else { solve_dense(sub, rhs)? };
171 let mut target = vec![0.0; n];
172 free.iter().zip(&z).for_each(|(&i, &v)| target[i] = v);
173 let mut alpha: f64 = 1.0;
175 let mut blocking = None;
176 for &i in &free {
177 if i >= first_bounded && target[i] < 0.0 {
178 let a = y[i] / (y[i] - target[i]);
179 if a < alpha {
180 alpha = a;
181 blocking = Some(i);
182 }
183 }
184 }
185 for i in 0..n {
186 y[i] += alpha * (target[i] - y[i]);
187 }
188 if let Some(i) = blocking {
189 y[i] = 0.0;
190 active[i] = true;
191 continue;
192 }
193 let gradient: Vec<f64> = (0..n).map(|i| dot(&m[i], &y) + q[i]).collect();
195 let release = (first_bounded..n).filter(|&i| active[i] && gradient[i] < -1e-12 * trace).min_by(|&a, &b| gradient[a].total_cmp(&gradient[b]));
196 match release {
197 Some(i) => active[i] = false,
198 None => return Some(y),
199 }
200 }
201 None
202}
203
204pub fn sqp<P: ConstrainedProblem>(problem: &P, x0: Vec<f64>, options: ConstrainedOptions) -> Result<ConstrainedResult, ErrorsJSL> {
206 let n = x0.len();
207 if n == 0 {
208 return Err(ErrorsJSL::Misconfiguration("Initial parameters must be a non-empty vector."));
209 }
210 let mut x = x0;
211 let mut b: Vec<Vec<f64>> = (0..n).map(|i| (0..n).map(|j| if i == j { 1.0 } else { 0.0 }).collect()).collect();
212 let mut penalty: f64 = 1.0;
213 let (mut lambda, mut mu) = (Vec::new(), Vec::new());
214 let mut converged = false;
215 let mut iterations = 0;
216 while iterations < options.max_iterations {
217 iterations += 1;
218 let (f, grad) = (problem.objective(&x), problem.gradient(&x));
219 let (h, g) = (problem.equalities(&x), problem.inequalities(&x));
220 let (je, ji) = (problem.equality_jacobian(&x), problem.inequality_jacobian(&x));
221 let (me, mi) = (h.len(), g.len());
222 let a: Vec<&Vec<f64>> = je.iter().chain(ji.iter()).collect();
224 let c: Vec<f64> = h.iter().chain(g.iter()).copied().collect();
225 let m = me + mi;
226 let solve_b = |v: &[f64]| solve_dense(b.clone(), v.to_vec());
228 let binv_g = solve_b(&grad).ok_or(ErrorsJSL::RuntimeError("The Hessian approximation became singular."))?;
229 let binv_a: Vec<Vec<f64>> = a.iter().map(|row| solve_b(row)).collect::<Option<_>>().ok_or(ErrorsJSL::RuntimeError("The Hessian approximation became singular."))?;
230 let dual_m: Vec<Vec<f64>> = (0..m).map(|i| (0..m).map(|j| dot(a[i], &binv_a[j])).collect()).collect();
233 let dual_q: Vec<f64> = (0..m).map(|i| dot(a[i], &binv_g) - c[i]).collect();
234 let y = bound_constrained_qp(&dual_m, &dual_q, me).ok_or(ErrorsJSL::RuntimeError("The QP subproblem failed (inconsistent linearised constraints?)."))?;
235 let d: Vec<f64> = (0..n).map(|k| -(binv_g[k] + (0..m).map(|i| y[i] * binv_a[i][k]).sum::<f64>())).collect();
237 lambda = y[..me].to_vec();
239 mu = y[me..].to_vec();
240 let gl_old: Vec<f64> = (0..n).map(|k| grad[k] + (0..m).map(|i| y[i] * a[i][k]).sum::<f64>()).collect();
241 let step_norm = d.iter().fold(0.0f64, |s, v| s.max(v.abs()));
242 let kkt = gl_old.iter().fold(0.0f64, |s, v| s.max(v.abs()));
243 if violation(&h, &g) <= options.tolerance && (step_norm <= options.tolerance * (1.0 + x.iter().fold(0.0f64, |s, v| s.max(v.abs()))) || kkt <= options.tolerance) {
244 converged = true;
245 break;
246 }
247 penalty = penalty.max(1.5 * y.iter().fold(0.0f64, |s, v| s.max(v.abs()))).max(1e-3);
249 let infeasibility = |h: &[f64], g: &[f64]| h.iter().map(|v| v.abs()).sum::<f64>() + g.iter().map(|v| v.max(0.0)).sum::<f64>();
250 let phi0 = f + penalty * infeasibility(&h, &g);
251 let derivative = dot(&grad, &d) - penalty * infeasibility(&h, &g);
252 let mut t = 1.0;
253 let mut x_new;
254 loop {
255 x_new = x.iter().zip(&d).map(|(a, b)| a + t * b).collect::<Vec<f64>>();
256 let phi = problem.objective(&x_new) + penalty * infeasibility(&problem.equalities(&x_new), &problem.inequalities(&x_new));
257 if phi.is_finite() && phi <= phi0 + 1e-4 * t * derivative.min(0.0) || t < 1e-10 {
258 break;
259 }
260 t *= 0.5;
261 }
262 let grad_new = problem.gradient(&x_new);
264 let (je_new, ji_new) = (problem.equality_jacobian(&x_new), problem.inequality_jacobian(&x_new));
265 let a_new: Vec<&Vec<f64>> = je_new.iter().chain(ji_new.iter()).collect();
266 let gl_new: Vec<f64> = (0..n).map(|k| grad_new[k] + (0..m).map(|i| y[i] * a_new[i][k]).sum::<f64>()).collect();
267 let s: Vec<f64> = x_new.iter().zip(&x).map(|(p, q)| p - q).collect();
268 let mut yv: Vec<f64> = gl_new.iter().zip(&gl_old).map(|(p, q)| p - q).collect();
269 let bs: Vec<f64> = b.iter().map(|row| dot(row, &s)).collect();
270 let sbs = dot(&s, &bs);
271 let sy = dot(&s, &yv);
272 if sbs > 1e-300 {
273 if sy < 0.2 * sbs {
274 let theta = 0.8 * sbs / (sbs - sy);
275 yv = yv.iter().zip(&bs).map(|(p, q)| theta * p + (1.0 - theta) * q).collect();
276 }
277 let sy = dot(&s, &yv);
278 for i in 0..n {
279 for j in 0..n {
280 b[i][j] += yv[i] * yv[j] / sy - bs[i] * bs[j] / sbs;
281 }
282 }
283 }
284 x = x_new;
285 }
286 let (h, g) = (problem.equalities(&x), problem.inequalities(&x));
287 Ok(ConstrainedResult {
288 objective_value: problem.objective(&x),
289 constraint_violation: violation(&h, &g),
290 parameters: x,
291 equality_multipliers: lambda,
292 inequality_multipliers: mu,
293 iterations,
294 converged,
295 })
296}
297
298struct AugmentedLagrangian<'a, P> {
301 problem: &'a P,
302 lambda: &'a [f64],
303 mu: &'a [f64],
304 rho: f64,
305}
306
307impl<P: ConstrainedProblem> ObjectiveFunction for AugmentedLagrangian<'_, P> {
308 fn evaluate(&self, x: &[f64]) -> f64 {
309 let (h, g) = (self.problem.equalities(x), self.problem.inequalities(x));
310 let eq: f64 = h.iter().zip(self.lambda).map(|(hi, li)| li * hi + 0.5 * self.rho * hi * hi).sum();
311 let ineq: f64 = g.iter().zip(self.mu).map(|(gj, mj)| ((mj + self.rho * gj).max(0.0).powi(2) - mj * mj) / (2.0 * self.rho)).sum();
312 self.problem.objective(x) + eq + ineq
313 }
314}
315
316impl<P: ConstrainedProblem> GradientFunction for AugmentedLagrangian<'_, P> {
317 fn evaluate(&self, x: &[f64]) -> Vec<f64> {
318 let mut grad = self.problem.gradient(x);
319 let (h, g) = (self.problem.equalities(x), self.problem.inequalities(x));
320 for (row, (hi, li)) in self.problem.equality_jacobian(x).iter().zip(h.iter().zip(self.lambda)) {
321 let w = li + self.rho * hi;
322 grad.iter_mut().zip(row).for_each(|(gk, r)| *gk += w * r);
323 }
324 for (row, (gj, mj)) in self.problem.inequality_jacobian(x).iter().zip(g.iter().zip(self.mu)) {
325 let w = (mj + self.rho * gj).max(0.0);
326 grad.iter_mut().zip(row).for_each(|(gk, r)| *gk += w * r);
327 }
328 grad
329 }
330}
331
332pub fn augmented_lagrangian<P: ConstrainedProblem>(problem: &P, x0: Vec<f64>, options: ConstrainedOptions) -> Result<ConstrainedResult, ErrorsJSL> {
334 if x0.is_empty() {
335 return Err(ErrorsJSL::Misconfiguration("Initial parameters must be a non-empty vector."));
336 }
337 let mut x = x0;
338 let mut lambda = vec![0.0; problem.equalities(&x).len()];
339 let mut mu = vec![0.0; problem.inequalities(&x).len()];
340 let mut rho = 10.0;
341 let mut previous_violation = f64::INFINITY;
342 let mut converged = false;
343 let mut iterations = 0;
344 let mut inner = Lbfgs::default();
345 inner.set_max_iterations(Some(2000));
346 while iterations < options.max_iterations {
347 iterations += 1;
348 inner.set_tolerance(Some((options.tolerance * 0.1).max(1e-12)));
349 let al = AugmentedLagrangian { problem, lambda: &lambda, mu: &mu, rho };
351 x = inner.gradient_based_minimize(&al, &al, x.clone())?.parameters;
352 let (h, g) = (problem.equalities(&x), problem.inequalities(&x));
353 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);
355 lambda.iter_mut().zip(&h).for_each(|(l, hi)| *l += rho * hi);
356 mu.iter_mut().zip(&g).for_each(|(m, gj)| *m = (*m + rho * gj).max(0.0));
357 if v <= options.tolerance {
359 converged = true;
360 break;
361 }
362 if v > 0.25 * previous_violation {
363 rho = (rho * 10.0).min(1e10);
364 }
365 previous_violation = v;
366 }
367 let (h, g) = (problem.equalities(&x), problem.inequalities(&x));
368 Ok(ConstrainedResult {
369 objective_value: problem.objective(&x),
370 constraint_violation: violation(&h, &g),
371 parameters: x,
372 equality_multipliers: lambda,
373 inequality_multipliers: mu,
374 iterations,
375 converged,
376 })
377}
378
379#[cfg(test)]
380mod tests {
381 use super::*;
382
383 struct Hs071;
385 impl ConstrainedProblem for Hs071 {
386 fn objective(&self, x: &[f64]) -> f64 {
387 x[0] * x[3] * (x[0] + x[1] + x[2]) + x[2]
388 }
389 fn gradient(&self, x: &[f64]) -> Vec<f64> {
390 vec![x[3] * (2.0 * x[0] + x[1] + x[2]), x[0] * x[3], x[0] * x[3] + 1.0, x[0] * (x[0] + x[1] + x[2])]
391 }
392 fn equalities(&self, x: &[f64]) -> Vec<f64> {
393 vec![x.iter().map(|v| v * v).sum::<f64>() - 40.0]
394 }
395 fn inequalities(&self, x: &[f64]) -> Vec<f64> {
396 let mut g = vec![25.0 - x.iter().product::<f64>()];
397 g.extend(x.iter().map(|v| 1.0 - v));
398 g.extend(x.iter().map(|v| v - 5.0));
399 g
400 }
401 }
402 const HS071_X: [f64; 4] = [1.0, 4.742_999_63, 3.821_149_98, 1.379_408_29];
403 const HS071_F: f64 = 17.014_017_3;
404
405 struct Tutorial;
407 impl ConstrainedProblem for Tutorial {
408 fn objective(&self, x: &[f64]) -> f64 {
409 (x[0] - 1.0).powi(2) + (x[1] - 2.5).powi(2)
410 }
411 fn inequalities(&self, x: &[f64]) -> Vec<f64> {
412 vec![-(x[0] - 2.0 * x[1] + 2.0), -(-x[0] - 2.0 * x[1] + 6.0), -(-x[0] + 2.0 * x[1] + 2.0), -x[0], -x[1]]
413 }
414 }
415
416 struct Circle;
418 impl ConstrainedProblem for Circle {
419 fn objective(&self, x: &[f64]) -> f64 {
420 x[0] + x[1]
421 }
422 fn equalities(&self, x: &[f64]) -> Vec<f64> {
423 vec![x[0] * x[0] + x[1] * x[1] - 2.0]
424 }
425 }
426
427 fn check(r: &ConstrainedResult, x: &[f64], f: f64, tol: f64, name: &str) {
428 assert!(r.converged, "{name}: {r:?}");
429 assert!(r.parameters.iter().zip(x).all(|(a, b)| (a - b).abs() < tol), "{name}: {r:?}");
430 assert!((r.objective_value - f).abs() < tol && r.constraint_violation < 1e-6, "{name}: {r:?}");
431 }
432
433 #[test]
434 fn sqp_solves_hs071_a_linear_qp_and_an_equality_problem() {
435 let r = sqp(&Hs071, vec![1.0, 5.0, 5.0, 1.0], ConstrainedOptions::default()).unwrap();
436 check(&r, &HS071_X, HS071_F, 1e-6, "hs071");
437 assert!(r.iterations < 50, "{}", r.iterations);
438 assert!(r.inequality_multipliers[0] > 0.0 && r.inequality_multipliers[1] > 0.0 && r.inequality_multipliers[2..].iter().filter(|&&m| m > 1e-8).count() == 0, "{:?}", r.inequality_multipliers);
440 let r = sqp(&Tutorial, vec![2.0, 0.0], ConstrainedOptions::default()).unwrap();
441 check(&r, &[1.4, 1.7], 0.8, 1e-7, "tutorial");
442 let r = sqp(&Circle, vec![0.5, -1.5], ConstrainedOptions::default()).unwrap();
443 check(&r, &[-1.0, -1.0], -2.0, 1e-7, "circle");
444 assert!((r.equality_multipliers[0] - 0.5).abs() < 1e-6);
445 }
446
447 #[test]
448 fn augmented_lagrangian_agrees_with_sqp() {
449 let options = ConstrainedOptions { tolerance: 1e-8, ..Default::default() };
450 let r = augmented_lagrangian(&Hs071, vec![1.0, 5.0, 5.0, 1.0], options).unwrap();
451 check(&r, &HS071_X, HS071_F, 1e-5, "hs071");
452 let r = augmented_lagrangian(&Tutorial, vec![2.0, 0.0], options).unwrap();
453 check(&r, &[1.4, 1.7], 0.8, 1e-6, "tutorial");
454 let r = augmented_lagrangian(&Circle, vec![0.5, -1.5], options).unwrap();
455 check(&r, &[-1.0, -1.0], -2.0, 1e-6, "circle");
456 assert!((r.equality_multipliers[0] - 0.5).abs() < 1e-5);
457 assert!(sqp(&Circle, vec![], options).is_err() && augmented_lagrangian(&Circle, vec![], options).is_err());
458 }
459}