1use crate::constrained::{ConstrainedOptions, ConstrainedProblem, ConstrainedResult, solve_dense};
7use lib_jsl_core::ErrorsJSL;
8
9fn dot(a: &[f64], b: &[f64]) -> f64 {
10 a.iter().zip(b).map(|(x, y)| x * y).sum()
11}
12
13fn norm(a: &[f64]) -> f64 {
14 dot(a, a).sqrt()
15}
16
17fn matvec(m: &[Vec<f64>], v: &[f64]) -> Vec<f64> {
18 m.iter().map(|r| dot(r, v)).collect()
19}
20
21fn rmatvec(m: &[Vec<f64>], v: &[f64], n: usize) -> Vec<f64> {
22 let mut out = vec![0.0; n];
23 for (r, vi) in m.iter().zip(v) {
24 out.iter_mut().zip(r).for_each(|(o, a)| *o += vi * a);
25 }
26 out
27}
28
29fn aat_solve(a: &[Vec<f64>], r: &[f64]) -> Vec<f64> {
31 let m = a.len();
32 let trace: f64 = a.iter().map(|row| dot(row, row)).sum::<f64>().max(1.0);
33 let k: Vec<Vec<f64>> = (0..m).map(|i| (0..m).map(|j| dot(&a[i], &a[j]) + if i == j { 1e-14 * trace } else { 0.0 }).collect()).collect();
34 solve_dense(k, r.to_vec()).unwrap_or_else(|| vec![0.0; m])
35}
36
37fn project(a: &[Vec<f64>], v: &[f64]) -> Vec<f64> {
39 if a.is_empty() {
40 return v.to_vec();
41 }
42 let y = aat_solve(a, &matvec(a, v));
43 let aty = rmatvec(a, &y, v.len());
44 v.iter().zip(&aty).map(|(p, q)| p - q).collect()
45}
46
47fn to_boundary(z: &[f64], d: &[f64], delta: f64) -> f64 {
49 let (a, b, c) = (dot(d, d), 2.0 * dot(z, d), dot(z, z) - delta * delta);
50 (-b + (b * b - 4.0 * a * c).max(0.0).sqrt()) / (2.0 * a)
51}
52
53fn byrd_omojokun_step(h: &dyn Fn(&[f64]) -> Vec<f64>, g: &[f64], a: &[Vec<f64>], c: &[f64], delta: f64, n_x: usize) -> Vec<f64> {
56 let nz = g.len();
57 let tau = 0.995;
58 let mut v = vec![0.0; nz];
60 if !a.is_empty() && norm(c) > 0.0 {
61 let gn = rmatvec(a, &aat_solve(a, c), nz).iter().map(|t| -t).collect::<Vec<_>>();
62 let r = 0.8 * delta;
63 v = if norm(&gn) <= r {
64 gn
65 } else {
66 let grad = rmatvec(a, c, nz);
67 let ag = matvec(a, &grad);
68 let alpha = dot(&grad, &grad) / dot(&ag, &ag).max(f64::MIN_POSITIVE);
69 let cauchy: Vec<f64> = grad.iter().map(|t| -alpha * t).collect();
70 if norm(&cauchy) >= r {
71 cauchy.iter().map(|t| t * r / norm(&cauchy)).collect()
72 } else {
73 let dir: Vec<f64> = gn.iter().zip(&cauchy).map(|(p, q)| p - q).collect();
74 let t = to_boundary(&cauchy, &dir, r);
75 cauchy.iter().zip(&dir).map(|(p, q)| p + t * q).collect()
76 }
77 };
78 let scale = v[n_x..].iter().filter(|t| **t < -0.5 * tau).fold(1.0f64, |m, t| m.min(-0.5 * tau / t));
79 v.iter_mut().for_each(|t| *t *= scale);
80 }
81 let hv = h(&v);
83 let mut r: Vec<f64> = g.iter().zip(&hv).map(|(p, q)| p + q).collect();
84 let mut d = v.clone();
85 let mut pr = project(a, &r);
86 let mut p: Vec<f64> = pr.iter().map(|t| -t).collect();
87 let tol = 0.01 * norm(&pr).min(1.0) * norm(&pr);
88 let mut rpr = dot(&r, &pr);
89 for _ in 0..2 * nz + 5 {
90 if norm(&pr) <= tol || rpr <= 0.0 {
91 break;
92 }
93 let hp = h(&p);
94 let curv = dot(&p, &hp);
95 if curv <= 0.0 {
96 let t = to_boundary(&d, &p, delta);
97 d.iter_mut().zip(&p).for_each(|(x, y)| *x += t * y);
98 break;
99 }
100 let alpha = rpr / curv;
101 let trial: Vec<f64> = d.iter().zip(&p).map(|(x, y)| x + alpha * y).collect();
102 if norm(&trial) >= delta {
103 let t = to_boundary(&d, &p, delta);
104 d.iter_mut().zip(&p).for_each(|(x, y)| *x += t * y);
105 break;
106 }
107 d = trial;
108 r.iter_mut().zip(&hp).for_each(|(x, y)| *x += alpha * y);
109 pr = project(a, &r);
110 let rpr_new = dot(&r, &pr);
111 let beta = rpr_new / rpr;
112 rpr = rpr_new;
113 p = p.iter().zip(&pr).map(|(x, y)| -y + beta * x).collect();
114 }
115 let scale = d[n_x..].iter().filter(|t| **t < -tau).fold(1.0f64, |m, t| m.min(-tau / t));
117 d.iter_mut().for_each(|t| *t *= scale);
118 d
119}
120
121pub fn trust_constr<P: ConstrainedProblem>(problem: &P, x0: Vec<f64>, options: ConstrainedOptions) -> Result<ConstrainedResult, ErrorsJSL> {
136 trust_constr_with(problem, x0, options, HessianUpdate::Bfgs, None)
137}
138
139#[derive(Clone, Copy, Debug, PartialEq, Eq)]
141#[non_exhaustive]
142pub enum HessianUpdate {
143 Bfgs,
145 Sr1,
148 Exact,
151}
152
153#[derive(Clone, Copy, Debug)]
157pub struct TrustConstrState<'a> {
158 pub x: &'a [f64],
159 pub objective_value: f64,
160 pub iterations: usize,
161 pub radius: f64,
163}
164
165impl std::fmt::Display for TrustConstrState<'_> {
166 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
167 write!(f, "iter {:4} f = {:+.8e} radius = {:.2e}", self.iterations, self.objective_value, self.radius)
168 }
169}
170
171pub 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> {
175 let n = x0.len();
176 if n == 0 {
177 return Err(ErrorsJSL::Misconfiguration("Initial parameters must be a non-empty vector."));
178 }
179 let mut x = x0;
180 let ng = problem.inequalities(&x).len();
181 let mut s: Vec<f64> = problem.inequalities(&x).iter().map(|g| (-1.5 * g).max(1.0)).collect();
182 let mut mu = if ng > 0 { 0.1 } else { 0.0 };
183 let mut barrier_tol = if ng > 0 { 0.1f64.max(options.tolerance) } else { options.tolerance };
184 let mut bfgs: Vec<Vec<f64>> = (0..n).map(|i| (0..n).map(|j| if i == j { 1.0 } else { 0.0 }).collect()).collect();
185 let mut delta: f64 = 1.0;
186 let mut nu: f64 = 1.0;
187 let mut iterations = 0;
188 let eval = |x: &[f64], s: &[f64]| -> (Vec<f64>, Vec<Vec<f64>>) {
190 let h = problem.equalities(x);
191 let g = problem.inequalities(x);
192 let (jh, jg) = (problem.equality_jacobian(x), problem.inequality_jacobian(x));
193 let mut c = h;
194 c.extend(g.iter().zip(s).map(|(a, b)| a + b));
195 let mut a: Vec<Vec<f64>> = jh.into_iter().map(|mut r| {
196 r.extend(std::iter::repeat_n(0.0, s.len()));
197 r
198 }).collect();
199 for (i, mut r) in jg.into_iter().enumerate() {
200 r.extend((0..s.len()).map(|k| if k == i { s[i] } else { 0.0 }));
201 a.push(r);
202 }
203 (c, a)
204 };
205 let converged;
206 let mut stopped = false;
207 let mut lambda: Vec<f64>;
208 loop {
209 loop {
211 let fx = problem.objective(&x);
212 let gx = problem.gradient(&x);
213 let (c, a) = eval(&x, &s);
214 let mut grad = gx.clone();
215 grad.extend(std::iter::repeat_n(-mu, ng));
216 lambda = if a.is_empty() { Vec::new() } else { aat_solve(&a, &matvec(&a, &grad)).iter().map(|t| -t).collect() };
218 let lag: Vec<f64> = grad.iter().zip(rmatvec(&a, &lambda, n + ng)).map(|(p, q)| p + q).collect();
219 let opt = lag.iter().fold(0.0f64, |m, v| m.max(v.abs()));
220 let viol = c.iter().fold(0.0f64, |m, v| m.max(v.abs()));
221 if (opt <= barrier_tol && viol <= barrier_tol) || iterations >= options.max_iterations {
222 break;
223 }
224 iterations += 1;
225 let mut exact_hv: Option<(Vec<f64>, Vec<f64>)> = None;
227 if hessian == HessianUpdate::Exact {
228 let (ne, ni) = (problem.equalities(&x).len(), ng);
229 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]) };
230 match problem.lagrangian_hessian(&x, &eq, &ineq) {
231 Some(h) => bfgs = h,
232 None => {
233 if problem.lagrangian_hessian_vector(&x, &eq, &ineq, &vec![0.0; n]).is_none() {
234 return Err(ErrorsJSL::Misconfiguration("HessianUpdate::Exact needs the problem's lagrangian_hessian or lagrangian_hessian_vector"));
235 }
236 exact_hv = Some((eq, ineq));
237 }
238 }
239 }
240 let hmul = |d: &[f64]| -> Vec<f64> {
241 let mut out = match &exact_hv {
242 Some((eq, ineq)) => problem.lagrangian_hessian_vector(&x, eq, ineq, &d[..n]).unwrap_or_else(|| vec![0.0; n]),
243 None => matvec(&bfgs, &d[..n]),
244 };
245 out.extend(d[n..].iter().map(|t| mu * t));
246 out
247 };
248 let d = byrd_omojokun_step(&hmul, &grad, &a, &c, delta, n);
249 let ad: Vec<f64> = matvec(&a, &d).iter().zip(&c).map(|(p, q)| p + q).collect();
251 let quad = dot(&grad, &d) + 0.5 * dot(&d, &hmul(&d));
252 let vpred = norm(&c) - norm(&ad);
253 if vpred > 1e-14 {
254 nu = nu.max(quad / (0.9 * vpred) + 1e-8);
255 }
256 let predicted = -quad + nu * vpred;
257 let barrier = |fx: f64, s: &[f64]| fx - mu * s.iter().map(|v| v.ln()).sum::<f64>();
258 let x_new: Vec<f64> = x.iter().zip(&d[..n]).map(|(p, q)| p + q).collect();
259 let s_new: Vec<f64> = s.iter().zip(&d[n..]).map(|(p, q)| p * (1.0 + q)).collect();
260 let (c_new, _) = eval(&x_new, &s_new);
261 let f_new = problem.objective(&x_new);
262 let actual = barrier(fx, &s) + nu * norm(&c) - barrier(f_new, &s_new) - nu * norm(&c_new);
263 let ratio = if predicted > 0.0 { actual / predicted } else { -1.0 };
264 let dn = norm(&d);
265 if ratio >= 0.75 {
266 delta = delta.max(7.0 * dn);
267 } else if ratio >= 0.3 {
268 delta = delta.max(2.0 * dn);
269 } else if ratio < 0.1 {
270 delta = 0.25 * dn.max(1e-16);
271 }
272 if delta < 1e-14 {
273 break;
274 }
275 if ratio > 1e-4 && f_new.is_finite() && s_new.iter().all(|v| *v > 0.0) {
276 let lag_x = |x: &[f64]| -> Vec<f64> {
278 let mut l = problem.gradient(x);
279 let mut jac = problem.equality_jacobian(x);
280 jac.extend(problem.inequality_jacobian(x));
281 for (row, lm) in jac.iter().zip(&lambda) {
282 l.iter_mut().zip(row).for_each(|(o, r)| *o += lm * r);
283 }
284 l
285 };
286 let (l0, l1) = (lag_x(&x), lag_x(&x_new));
287 let sv: Vec<f64> = d[..n].to_vec();
288 let mut yv: Vec<f64> = l1.iter().zip(&l0).map(|(p, q)| p - q).collect();
289 let bs = matvec(&bfgs, &sv);
290 let sbs = dot(&sv, &bs);
291 let sy = dot(&sv, &yv);
292 if hessian == HessianUpdate::Sr1 {
293 let r: Vec<f64> = yv.iter().zip(&bs).map(|(y, b)| y - b).collect();
295 let den = dot(&r, &sv);
296 if den.abs() > 1e-8 * norm(&r) * norm(&sv) && den.abs() > 1e-300 {
297 for i in 0..n {
298 for j in 0..n {
299 bfgs[i][j] += r[i] * r[j] / den;
300 }
301 }
302 }
303 } else if hessian == HessianUpdate::Bfgs && sbs > 1e-300 {
304 if sy < 0.2 * sbs {
305 let theta = 0.8 * sbs / (sbs - sy);
306 yv = yv.iter().zip(&bs).map(|(y, b)| theta * y + (1.0 - theta) * b).collect();
307 }
308 let sy = dot(&sv, &yv);
309 if sy > 1e-300 {
310 for i in 0..n {
311 for j in 0..n {
312 bfgs[i][j] += yv[i] * yv[j] / sy - bs[i] * bs[j] / sbs;
313 }
314 }
315 }
316 }
317 x = x_new;
318 s = s_new;
319 }
320 if let Some(cb) = callback.as_deref_mut() {
321 let state = TrustConstrState { x: &x, objective_value: problem.objective(&x), iterations, radius: delta };
322 if cb(&state) {
323 stopped = true;
324 break;
325 }
326 }
327 }
328 if stopped {
329 converged = false;
330 break;
331 }
332 if ng == 0 || iterations >= options.max_iterations {
333 converged = iterations < options.max_iterations;
334 break;
335 }
336 if barrier_tol <= options.tolerance {
337 converged = true;
338 break;
339 }
340 mu *= 0.2;
341 barrier_tol = (0.2 * barrier_tol).max(options.tolerance);
342 delta = delta.max(1.0);
343 }
344 let h = problem.equalities(&x);
345 let g = problem.inequalities(&x);
346 let violation = h.iter().map(|v| v.abs()).chain(g.iter().map(|v| v.max(0.0))).fold(0.0, f64::max);
347 let ne = h.len();
348 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]) };
349 Ok(ConstrainedResult {
350 objective_value: problem.objective(&x),
351 parameters: x,
352 equality_multipliers: eq,
353 inequality_multipliers: ineq,
354 constraint_violation: violation,
355 iterations,
356 converged: converged && violation <= options.tolerance.max(1e-6),
357 })
358}
359#[cfg(test)]
362mod tests {
363 use super::*;
364
365 struct Hs071;
366 impl ConstrainedProblem for Hs071 {
367 fn objective(&self, x: &[f64]) -> f64 {
368 x[0] * x[3] * (x[0] + x[1] + x[2]) + x[2]
369 }
370 fn equalities(&self, x: &[f64]) -> Vec<f64> {
371 vec![x.iter().map(|v| v * v).sum::<f64>() - 40.0]
372 }
373 fn inequalities(&self, x: &[f64]) -> Vec<f64> {
374 let mut g = vec![25.0 - x.iter().product::<f64>()];
375 for &v in x {
376 g.push(1.0 - v);
377 g.push(v - 5.0);
378 }
379 g
380 }
381 }
382
383 struct Circle;
384 impl ConstrainedProblem for Circle {
385 fn objective(&self, x: &[f64]) -> f64 {
387 x[0] + x[1]
388 }
389 fn equalities(&self, x: &[f64]) -> Vec<f64> {
390 vec![x[0] * x[0] + x[1] * x[1] - 1.0]
391 }
392 }
393
394 struct ExactCircle;
396 impl ConstrainedProblem for ExactCircle {
397 fn objective(&self, x: &[f64]) -> f64 {
398 x[0] + x[1]
399 }
400 fn gradient(&self, _x: &[f64]) -> Vec<f64> {
401 vec![1.0, 1.0]
402 }
403 fn equalities(&self, x: &[f64]) -> Vec<f64> {
404 vec![x[0] * x[0] + x[1] * x[1] - 1.0]
405 }
406 fn equality_jacobian(&self, x: &[f64]) -> Vec<Vec<f64>> {
407 vec![vec![2.0 * x[0], 2.0 * x[1]]]
408 }
409 fn lagrangian_hessian(&self, _x: &[f64], eq: &[f64], _ineq: &[f64]) -> Option<Vec<Vec<f64>>> {
410 Some(vec![vec![2.0 * eq[0], 0.0], vec![0.0, 2.0 * eq[0]]])
411 }
412 }
413
414 struct HessianVectorCircle;
416 impl ConstrainedProblem for HessianVectorCircle {
417 fn objective(&self, x: &[f64]) -> f64 {
418 x[0] + x[1]
419 }
420 fn gradient(&self, _x: &[f64]) -> Vec<f64> {
421 vec![1.0, 1.0]
422 }
423 fn equalities(&self, x: &[f64]) -> Vec<f64> {
424 vec![x[0] * x[0] + x[1] * x[1] - 1.0]
425 }
426 fn equality_jacobian(&self, x: &[f64]) -> Vec<Vec<f64>> {
427 vec![vec![2.0 * x[0], 2.0 * x[1]]]
428 }
429 fn lagrangian_hessian_vector(&self, _x: &[f64], eq: &[f64], _ineq: &[f64], v: &[f64]) -> Option<Vec<f64>> {
430 Some(v.iter().map(|t| 2.0 * eq[0] * t).collect())
431 }
432 }
433
434 #[test]
435 fn hessian_vector_products_and_the_printing_callback() {
436 let o = ConstrainedOptions { tolerance: 1e-8, max_iterations: 1000 };
437 let s = 0.5f64.sqrt();
438 let r = trust_constr_with(&HessianVectorCircle, vec![2.0, 0.5], o, HessianUpdate::Exact, None).unwrap();
439 assert!(r.converged && (r.parameters[0] + s).abs() < 1e-7 && (r.parameters[1] + s).abs() < 1e-7);
440 let mut lines = Vec::new();
441 let mut cb = |st: &TrustConstrState| {
442 lines.push(st.to_string());
443 false
444 };
445 trust_constr_with(&Circle, vec![2.0, 0.5], o, HessianUpdate::Bfgs, Some(&mut cb)).unwrap();
446 assert!(lines.len() > 3 && lines[0].starts_with("iter 1 f = "), "{:?}", lines.first());
447 }
448
449 #[test]
450 fn exact_and_sr1_hessians_and_the_callback() {
451 let o = ConstrainedOptions { tolerance: 1e-8, max_iterations: 1000 };
452 let s = 0.5f64.sqrt();
453 let exact = trust_constr_with(&ExactCircle, vec![2.0, 0.5], o, HessianUpdate::Exact, None).unwrap();
454 assert!(exact.converged && (exact.parameters[0] + s).abs() < 1e-7 && (exact.parameters[1] + s).abs() < 1e-7);
455 let sr1 = trust_constr_with(&Circle, vec![2.0, 0.5], o, HessianUpdate::Sr1, None).unwrap();
456 assert!(sr1.converged && (sr1.parameters[0] + s).abs() < 1e-6, "{:?}", sr1.parameters);
457 assert!(trust_constr_with(&Circle, vec![2.0, 0.5], o, HessianUpdate::Exact, None).is_err());
459 let mut seen = 0;
460 let mut cb = |st: &TrustConstrState| {
461 seen += 1;
462 st.iterations >= 3
463 };
464 let stopped = trust_constr_with(&Circle, vec![2.0, 0.5], o, HessianUpdate::Bfgs, Some(&mut cb)).unwrap();
465 assert!(!stopped.converged && stopped.iterations == 3 && seen == 3);
466 }
467
468 #[test]
469 fn solves_equality_and_mixed_problems() {
470 let o = ConstrainedOptions { tolerance: 1e-8, max_iterations: 1000 };
471 let r = trust_constr(&Circle, vec![2.0, 0.5], o).unwrap();
472 let s = 0.5f64.sqrt();
473 assert!(r.converged && (r.parameters[0] + s).abs() < 1e-7 && (r.parameters[1] + s).abs() < 1e-7, "{:?}", r.parameters);
474 assert!((r.equality_multipliers[0] - s).abs() < 1e-6, "{:?}", r.equality_multipliers);
475 let r = trust_constr(&Hs071, vec![1.0, 5.0, 5.0, 1.0], o).unwrap();
477 assert!(r.converged && (r.objective_value - 17.0140173).abs() < 1e-5, "{:?} {} {}", r.parameters, r.objective_value, r.iterations);
478 assert!((r.parameters[1] - 4.743).abs() < 1e-3, "{:?}", r.parameters);
479 }
480}