Skip to main content

lib_jsl_optimization/
tnc.rs

1//! Bound-constrained minimisation by a truncated Newton method (the method of SciPy's
2//! `minimize(method="TNC")`, Nash's truncated Newton with bounds).
3//!
4//! See the book entry [Levenberg-Marquardt for systems, mixed-integer programming and truncated Newton](https://jwkunz.github.io/lib_jsl/book/optimization/milp-tnc.html#truncated-newton-with-bounds).
5
6use crate::bounded::BoundedResult;
7use lib_jsl_core::ErrorsJSL;
8
9/// Options for [`minimize_tnc`].
10#[derive(Clone, Copy, Debug)]
11pub struct TncOptions {
12    /// Stop when the largest component of the projected gradient is at most this.
13    pub pgtol: f64,
14    /// Also stop when the decrease of `f` in an iteration is at most this times `|f|` (default 0:
15    /// only the gradient test and the evaluation limit stop the iteration).
16    pub ftol: f64,
17    /// The largest number of evaluations of `(f, ∇f)`, including those for Hessian-vector
18    /// products; `None` for `max(1000, 100 n)` (SciPy's TNC allows `max(100, 10 n)`, but stops on
19    /// a much looser test).
20    pub maxfun: Option<usize>,
21    /// The largest number of conjugate-gradient iterations per Newton step (default
22    /// `min(50, n)`; SciPy's `maxCGit` defaults to `n/2`, which its preconditioner makes up for).
23    pub max_cg: Option<usize>,
24}
25
26impl Default for TncOptions {
27    fn default() -> Self {
28        TncOptions { pgtol: 1e-8, ftol: 0.0, maxfun: None, max_cg: None }
29    }
30}
31
32type DynFg<'a> = &'a mut dyn FnMut(&[f64]) -> (f64, Vec<f64>);
33
34fn dot(a: &[f64], b: &[f64]) -> f64 {
35    a.iter().zip(b).map(|(x, y)| x * y).sum()
36}
37
38// ANCHOR: tnc
39/// Minimises `f` subject to `lb ≤ x ≤ ub` by a truncated Newton method; `fg` returns `f` and its
40/// gradient. Each iteration fixes the variables on a bound whose gradient points outwards, and
41/// solves the Newton equations `H p = −g` for the others only approximately, by conjugate
42/// gradients stopped at a relative residual `min(½, √‖g‖)` or at negative curvature; the
43/// Hessian-vector products are forward differences of the gradient, so no Hessian is needed.
44/// A projected backtracking line search along `p` keeps the iterates in the box.
45pub fn minimize_tnc(mut fg: impl FnMut(&[f64]) -> (f64, Vec<f64>), x0: &[f64], lb: &[f64], ub: &[f64], options: TncOptions) -> Result<BoundedResult, ErrorsJSL> {
46    let n = x0.len();
47    if n == 0 || lb.len() != n || ub.len() != n {
48        return Err(ErrorsJSL::IncompatibleArraySizes((lb.len(), n)));
49    }
50    if (0..n).any(|i| lb[i].is_nan() || ub[i].is_nan() || lb[i] > ub[i]) {
51        return Err(ErrorsJSL::InvalidInputRange("minimize_tnc: need lb ≤ ub"));
52    }
53    let maxfun = options.maxfun.unwrap_or((100 * n).max(1000));
54    let max_cg = options.max_cg.unwrap_or(n.clamp(1, 50));
55    let mut x: Vec<f64> = (0..n).map(|i| x0[i].clamp(lb[i], ub[i])).collect();
56    let (mut f, mut g) = fg(&x);
57    let mut nfev = 1;
58    let mut iterations = 0;
59    let free_of = |x: &[f64], g: &[f64]| -> Vec<bool> { (0..n).map(|i| !((x[i] <= lb[i] && g[i] > 0.0) || (x[i] >= ub[i] && g[i] < 0.0))).collect() };
60    let pg_norm = |x: &[f64], g: &[f64]| -> f64 { (0..n).map(|i| ((x[i] - g[i]).clamp(lb[i], ub[i]) - x[i]).abs()).fold(0.0, f64::max) };
61    let mut converged = false;
62    while nfev < maxfun {
63        if pg_norm(&x, &g) <= options.pgtol {
64            converged = true;
65            break;
66        }
67        let free = free_of(&x, &g);
68        let gf: Vec<f64> = (0..n).map(|i| if free[i] { g[i] } else { 0.0 }).collect();
69        let gnorm = dot(&gf, &gf).sqrt();
70        // Truncated conjugate gradients on H p = −g over the free variables.
71        let hv = |v: &[f64], fg: DynFg<'_>, x: &[f64], g: &[f64]| -> Vec<f64> {
72            let vn = dot(v, v).sqrt();
73            let xn = dot(x, x).sqrt();
74            let h = f64::EPSILON.sqrt() * (1.0 + xn) / vn.max(1e-300);
75            let xh: Vec<f64> = (0..n).map(|i| x[i] + h * v[i]).collect();
76            let (_, gh) = fg(&xh);
77            (0..n).map(|i| if free[i] { (gh[i] - g[i]) / h } else { 0.0 }).collect()
78        };
79        let mut p = vec![0.0; n];
80        let mut r: Vec<f64> = gf.iter().map(|v| -v).collect();
81        let mut d = r.clone();
82        let mut rr = dot(&r, &r);
83        let eta = 0.5f64.min(gnorm.sqrt());
84        for k in 0..max_cg {
85            let hd = hv(&d, &mut fg, &x, &g);
86            nfev += 1;
87            let curv = dot(&d, &hd);
88            if curv <= 1e-16 * dot(&d, &d) {
89                if k == 0 {
90                    p.clone_from(&d);
91                }
92                break;
93            }
94            let alpha = rr / curv;
95            for i in 0..n {
96                p[i] += alpha * d[i];
97                r[i] -= alpha * hd[i];
98            }
99            let rr_new = dot(&r, &r);
100            if rr_new.sqrt() <= eta * gnorm {
101                break;
102            }
103            let beta = rr_new / rr;
104            rr = rr_new;
105            for i in 0..n {
106                d[i] = r[i] + beta * d[i];
107            }
108        }
109        if dot(&p, &gf) >= 0.0 {
110            p = gf.iter().map(|v| -v).collect();
111        }
112        // Projected backtracking (Armijo) line search.
113        let mut step = 1.0;
114        let mut accepted = None;
115        for _ in 0..40 {
116            let xt: Vec<f64> = (0..n).map(|i| (x[i] + step * p[i]).clamp(lb[i], ub[i])).collect();
117            let (ft, gt) = fg(&xt);
118            nfev += 1;
119            let decrease: f64 = (0..n).map(|i| g[i] * (xt[i] - x[i])).sum();
120            if ft.is_finite() && ft <= f + 1e-4 * decrease {
121                accepted = Some((xt, ft, gt));
122                break;
123            }
124            step *= 0.5;
125        }
126        iterations += 1;
127        let Some((xt, ft, gt)) = accepted else { break };
128        let decrease = f - ft;
129        let scale = f.abs().max(ft.abs());
130        x = xt;
131        f = ft;
132        g = gt;
133        if decrease <= options.ftol * scale {
134            converged = pg_norm(&x, &g) <= options.pgtol;
135            break;
136        }
137    }
138    let active = (0..n).map(|i| if x[i] <= lb[i] { -1 } else if x[i] >= ub[i] { 1 } else { 0 }).collect();
139    Ok(BoundedResult { x, fun: f, gradient: g, iterations, nfev, converged, active })
140}
141// ANCHOR_END: tnc
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    #[test]
148    fn rosenbrock_with_and_without_bounds() {
149        let fg = |x: &[f64]| {
150            let n = x.len();
151            let mut f = 0.0;
152            let mut g = vec![0.0; n];
153            for i in 0..n - 1 {
154                let a = x[i + 1] - x[i] * x[i];
155                let b = 1.0 - x[i];
156                f += 100.0 * a * a + b * b;
157                g[i] += -400.0 * x[i] * a - 2.0 * b;
158                g[i + 1] += 200.0 * a;
159            }
160            (f, g)
161        };
162        let n = 6;
163        let x0 = vec![-1.2; n];
164        let inf = vec![f64::INFINITY; n];
165        let opts = TncOptions::default();
166        let r = minimize_tnc(fg, &x0, &vec![f64::NEG_INFINITY; n], &inf, opts).unwrap();
167        assert!(r.converged && r.x.iter().all(|v| (v - 1.0).abs() < 1e-6), "{:?}", r.x);
168        // With x₀ ≤ 0.5 the first variable sits on its bound; L-BFGS-B agrees on the rest.
169        let mut ub = inf.clone();
170        ub[0] = 0.5;
171        let lb = vec![f64::NEG_INFINITY; n];
172        let r = minimize_tnc(fg, &x0, &lb, &ub, opts).unwrap();
173        assert_eq!(r.active[0], 1);
174        let l = crate::bounded::minimize_lbfgsb(fg, &x0, &lb, &ub, crate::bounded::LbfgsbOptions { gtol: 1e-10, ftol: 1e-15, ..Default::default() }).unwrap();
175        assert!(r.x.iter().zip(&l.x).all(|(a, b)| (a - b).abs() < 1e-5), "{:?} vs {:?}", r.x, l.x);
176    }
177}