Skip to main content

argmin/solver/quasinewton/
sr1_trustregion.rs

1// Copyright 2019-2024 argmin developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8use crate::core::{
9    ArgminFloat, CostFunction, Error, Executor, Gradient, Hessian, IterState, OptimizationResult,
10    Problem, Solver, TerminationReason, TerminationStatus, TrustRegionRadius, KV,
11};
12use argmin_math::{
13    ArgminAdd, ArgminDot, ArgminL2Norm, ArgminMul, ArgminSub, ArgminWeightedDot, ArgminZeroLike,
14};
15#[cfg(feature = "serde1")]
16use serde::{Deserialize, Serialize};
17
18/// # SR1 Trust region method
19///
20/// A Quasi-Newton method which uses symmetric rank 1 (SR1) updating of the Hessian in a trust
21/// region framework. An initial parameter vector must be provided, initial cost, gradient and
22/// Hessian are optional and will be computed if not provided.
23/// Requires a [trust region sub problem](`crate::solver::trustregion`).
24///
25/// ## Requirements on the optimization problem
26///
27/// The optimization problem is required to implement [`CostFunction`], [`Gradient`] and
28/// [`Hessian`].
29///
30/// ## Reference
31///
32/// Jorge Nocedal and Stephen J. Wright (2006). Numerical Optimization.
33/// Springer. ISBN 0-387-30303-0.
34#[derive(Clone)]
35#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
36pub struct SR1TrustRegion<R, F> {
37    /// parameter for skipping rule
38    denominator_factor: F,
39    /// subproblem
40    subproblem: R,
41    /// Radius
42    radius: F,
43    /// eta \in (0, 10^-3)
44    eta: F,
45    /// Tolerance for the stopping criterion based on the change of the norm on the gradient
46    tol_grad: F,
47}
48
49impl<R, F> SR1TrustRegion<R, F>
50where
51    F: ArgminFloat,
52{
53    /// Construct a new instance of [`SR1TrustRegion`]
54    ///
55    /// # Example
56    ///
57    /// ```
58    /// # use argmin::solver::quasinewton::SR1TrustRegion;
59    /// # let subproblem = ();
60    /// let subproblem = argmin::solver::trustregion::Steihaug::new().with_max_iters(20);
61    /// # // The next line defines the type of `subproblem`. This is done here hidden in order to
62    /// # // not litter the docs. When all of this is fed into an Executor, the compiler will
63    /// # // figure out the types.
64    /// # let subproblem: argmin::solver::trustregion::Steihaug<Vec<f64>, f64> = subproblem;
65    /// let sr1: SR1TrustRegion<_, f64> = SR1TrustRegion::new(subproblem);
66    /// ```
67    pub fn new(subproblem: R) -> Self {
68        SR1TrustRegion {
69            denominator_factor: float!(1e-8),
70            subproblem,
71            radius: float!(1.0),
72            eta: float!(0.5 * 1e-3),
73            tol_grad: float!(1e-3),
74        }
75    }
76
77    /// Set denominator factor
78    ///
79    /// If the denominator of the update is below the `denominator_factor` (scaled with other
80    /// factors derived from the parameter vectors and the gradients), then the update of the
81    /// inverse Hessian will be skipped.
82    ///
83    /// Must be in `(0, 1)` and defaults to `1e-8`.
84    ///
85    /// # Example
86    ///
87    /// ```
88    /// # use argmin::solver::quasinewton::SR1TrustRegion;
89    /// # use argmin::core::Error;
90    /// # fn main() -> Result<(), Error> {
91    /// # let subproblem = ();
92    /// let sr1: SR1TrustRegion<_, f64> = SR1TrustRegion::new(subproblem).with_denominator_factor(1e-7)?;
93    /// # Ok(())
94    /// # }
95    /// ```
96    pub fn with_denominator_factor(mut self, denominator_factor: F) -> Result<Self, Error> {
97        if denominator_factor <= float!(0.0) || denominator_factor >= float!(1.0) {
98            return Err(argmin_error!(
99                InvalidParameter,
100                "`SR1TrustRegion`: denominator_factor must be in (0, 1)."
101            ));
102        }
103        self.denominator_factor = denominator_factor;
104        Ok(self)
105    }
106
107    /// Set initial radius
108    ///
109    /// Defaults to 1.0.
110    ///
111    /// # Example
112    ///
113    /// ```
114    /// # use argmin::solver::quasinewton::SR1TrustRegion;
115    /// # use argmin::core::Error;
116    /// # fn main() -> Result<(), Error> {
117    /// # let subproblem = ();
118    /// let sr1: SR1TrustRegion<_, f64> = SR1TrustRegion::new(subproblem).with_radius(2.0);
119    /// # Ok(())
120    /// # }
121    /// ```
122    #[must_use]
123    pub fn with_radius(mut self, radius: F) -> Self {
124        self.radius = radius.abs();
125        self
126    }
127
128    /// Set eta
129    ///
130    /// A step is taken if the actual reduction over the predicted reduction exceeds eta.
131    /// Must be in (0, 10^-3) and defaults to 0.5 * 10^-3.
132    ///
133    /// # Example
134    ///
135    /// ```
136    /// # use argmin::solver::quasinewton::SR1TrustRegion;
137    /// # use argmin::core::Error;
138    /// # fn main() -> Result<(), Error> {
139    /// # let subproblem = ();
140    /// let sr1: SR1TrustRegion<_, f64> = SR1TrustRegion::new(subproblem).with_eta(10e-4)?;
141    /// # Ok(())
142    /// # }
143    /// ```
144    pub fn with_eta(mut self, eta: F) -> Result<Self, Error> {
145        if eta >= float!(10e-3) || eta <= float!(0.0) {
146            return Err(argmin_error!(
147                InvalidParameter,
148                "SR1TrustRegion: eta must be in (0, 10^-3)."
149            ));
150        }
151        self.eta = eta;
152        Ok(self)
153    }
154
155    /// The algorithm stops if the norm of the gradient is below `tol_grad`.
156    ///
157    /// The provided value must be non-negative. Defaults to `10^-3`.
158    ///
159    /// # Example
160    ///
161    /// ```
162    /// # use argmin::solver::quasinewton::SR1TrustRegion;
163    /// # use argmin::core::Error;
164    /// # fn main() -> Result<(), Error> {
165    /// # let subproblem = ();
166    /// let sr1: SR1TrustRegion<_, f64> = SR1TrustRegion::new(subproblem).with_tolerance_grad(1e-6)?;
167    /// # Ok(())
168    /// # }
169    /// ```
170    pub fn with_tolerance_grad(mut self, tol_grad: F) -> Result<Self, Error> {
171        if tol_grad < float!(0.0) {
172            return Err(argmin_error!(
173                InvalidParameter,
174                "`SR1TrustRegion`: gradient tolerance must be >= 0."
175            ));
176        }
177        self.tol_grad = tol_grad;
178        Ok(self)
179    }
180}
181
182impl<O, R, P, G, B, F> Solver<O, IterState<P, G, (), B, (), F>> for SR1TrustRegion<R, F>
183where
184    O: CostFunction<Param = P, Output = F>
185        + Gradient<Param = P, Gradient = G>
186        + Hessian<Param = P, Hessian = B>,
187    P: Clone
188        + ArgminSub<P, P>
189        + ArgminAdd<P, P>
190        + ArgminDot<P, F>
191        + ArgminDot<P, B>
192        + ArgminL2Norm<F>
193        + ArgminZeroLike,
194    G: Clone + ArgminL2Norm<F> + ArgminDot<P, F> + ArgminSub<G, P>,
195    B: Clone + ArgminDot<P, P> + ArgminAdd<B, B> + ArgminMul<F, B>,
196    R: Clone + TrustRegionRadius<F> + Solver<O, IterState<P, G, (), B, (), F>>,
197    F: ArgminFloat + ArgminL2Norm<F>,
198{
199    fn name(&self) -> &str {
200        "SR1 trust region"
201    }
202
203    fn init(
204        &mut self,
205        problem: &mut Problem<O>,
206        mut state: IterState<P, G, (), B, (), F>,
207    ) -> Result<(IterState<P, G, (), B, (), F>, Option<KV>), Error> {
208        let param = state.take_param().ok_or_else(argmin_error_closure!(
209            NotInitialized,
210            concat!(
211                "`SR1TrustRegion` requires an initial parameter vector. ",
212                "Please provide an initial guess via `Executor`s `configure` method."
213            )
214        ))?;
215
216        let cost = state.get_cost();
217        let cost = if cost.is_infinite() {
218            problem.cost(&param)?
219        } else {
220            cost
221        };
222
223        let grad = state
224            .take_gradient()
225            .map(Result::Ok)
226            .unwrap_or_else(|| problem.gradient(&param))?;
227
228        let hessian = state
229            .take_hessian()
230            .map(Result::Ok)
231            .unwrap_or_else(|| problem.hessian(&param))?;
232
233        Ok((
234            state
235                .param(param)
236                .cost(cost)
237                .gradient(grad)
238                .hessian(hessian),
239            None,
240        ))
241    }
242
243    fn next_iter(
244        &mut self,
245        problem: &mut Problem<O>,
246        mut state: IterState<P, G, (), B, (), F>,
247    ) -> Result<(IterState<P, G, (), B, (), F>, Option<KV>), Error> {
248        let xk = state.take_param().ok_or_else(argmin_error_closure!(
249            PotentialBug,
250            "`SR1TrustRegion`: Parameter vector in state not set."
251        ))?;
252
253        let cost = state.get_cost();
254
255        let prev_grad = state.take_gradient().ok_or_else(argmin_error_closure!(
256            PotentialBug,
257            "`SR1TrustRegion`: Gradient in state not set."
258        ))?;
259
260        let hessian = state.take_hessian().ok_or_else(argmin_error_closure!(
261            PotentialBug,
262            "`SR1TrustRegion`: Hessian in state not set."
263        ))?;
264
265        self.subproblem.set_radius(self.radius);
266
267        let OptimizationResult {
268            problem: sub_problem,
269            state: mut sub_state,
270            ..
271        } = Executor::new(problem.take_problem().unwrap(), self.subproblem.clone())
272            .configure(|config| {
273                config
274                    .param(xk.zero_like())
275                    .hessian(hessian.clone())
276                    .gradient(prev_grad.clone())
277                    .cost(cost)
278            })
279            .ctrlc(false)
280            .run()?;
281
282        let sk = sub_state.take_param().ok_or_else(argmin_error_closure!(
283            PotentialBug,
284            "`SR1TrustRegion`: No parameters returned by line search."
285        ))?;
286
287        problem.consume_problem(sub_problem);
288
289        let xksk = xk.add(&sk);
290        let dfk1 = problem.gradient(&xksk)?;
291        let yk = dfk1.sub(&prev_grad);
292        let fk1 = problem.cost(&xksk)?;
293
294        let ared = cost - fk1;
295        let tmp1: F = prev_grad.dot(&sk);
296        let tmp2: F = sk.weighted_dot(&hessian, &sk);
297        let tmp2: F = tmp2.mul(float!(0.5));
298        let pred = -tmp1 - tmp2;
299        let ap = ared / pred;
300
301        let (xk1, fk1, dfk1) = if ap > self.eta {
302            (xksk, fk1, dfk1)
303        } else {
304            (xk, cost, prev_grad)
305        };
306
307        self.radius = if ap > float!(0.75) {
308            if sk.l2_norm() <= float!(0.8) * self.radius {
309                self.radius
310            } else {
311                float!(2.0) * self.radius
312            }
313        } else if ap <= float!(0.75) && ap >= float!(0.1) {
314            self.radius
315        } else {
316            float!(0.5) * self.radius
317        };
318
319        let bksk = hessian.dot(&sk);
320        let ykbksk = yk.sub(&bksk);
321        let skykbksk: F = sk.dot(&ykbksk);
322
323        let hessian_update =
324            skykbksk.abs() >= self.denominator_factor * sk.l2_norm() * skykbksk.l2_norm();
325        let hessian = if hessian_update {
326            let a: B = ykbksk.dot(&ykbksk);
327            let b: F = sk.dot(&ykbksk);
328            hessian.add(&a.mul(&(float!(1.0) / b)))
329        } else {
330            hessian
331        };
332
333        Ok((
334            state.param(xk1).cost(fk1).gradient(dfk1).hessian(hessian),
335            Some(kv!["ared" => ared;
336                         "pred" => pred;
337                         "ap" => ap;
338                         "radius" => self.radius;
339                         "hessian_update" => hessian_update;]),
340        ))
341    }
342
343    fn terminate(&mut self, state: &IterState<P, G, (), B, (), F>) -> TerminationStatus {
344        if state.get_gradient().unwrap().l2_norm() < self.tol_grad {
345            return TerminationStatus::Terminated(TerminationReason::SolverConverged);
346        }
347        TerminationStatus::NotTerminated
348    }
349}
350
351#[cfg(test)]
352mod tests {
353    use super::*;
354    use crate::core::{test_utils::TestProblem, ArgminError, State};
355    use crate::solver::trustregion::CauchyPoint;
356
357    test_trait_impl!(sr1, SR1TrustRegion<CauchyPoint<f64>, f64>);
358
359    #[test]
360    fn test_new() {
361        #[derive(Eq, PartialEq, Debug)]
362        struct MyFakeSubProblem {}
363
364        let sr1: SR1TrustRegion<_, f64> = SR1TrustRegion::new(MyFakeSubProblem {});
365        let SR1TrustRegion {
366            denominator_factor,
367            subproblem,
368            radius,
369            eta,
370            tol_grad,
371        } = sr1;
372
373        assert_eq!(denominator_factor.to_ne_bytes(), 1e-8f64.to_ne_bytes());
374        assert_eq!(subproblem, MyFakeSubProblem {});
375        assert_eq!(radius.to_ne_bytes(), 1.0f64.to_ne_bytes());
376        assert_eq!(eta.to_ne_bytes(), (0.5f64 * 1e-3f64).to_ne_bytes());
377        assert_eq!(tol_grad.to_ne_bytes(), 1e-3f64.to_ne_bytes());
378    }
379
380    #[test]
381    fn test_with_denominator_factor() {
382        #[derive(Eq, PartialEq, Debug, Clone, Copy)]
383        struct MyFakeSubProblem {}
384
385        // correct parameters
386        for tol in [f64::EPSILON, 1e-8, 1e-6, 1e-2, 1.0 - f64::EPSILON] {
387            let sr1: SR1TrustRegion<_, f64> = SR1TrustRegion::new(MyFakeSubProblem {});
388            let res = sr1.with_denominator_factor(tol);
389            assert!(res.is_ok());
390
391            let nm = res.unwrap();
392            assert_eq!(nm.denominator_factor.to_ne_bytes(), tol.to_ne_bytes());
393        }
394
395        // incorrect parameters
396        for tol in [-f64::EPSILON, 0.0, -1.0, 1.0] {
397            let sr1: SR1TrustRegion<_, f64> = SR1TrustRegion::new(MyFakeSubProblem {});
398            let res = sr1.with_denominator_factor(tol);
399            assert_error!(
400                res,
401                ArgminError,
402                "Invalid parameter: \"`SR1TrustRegion`: denominator_factor must be in (0, 1).\""
403            );
404        }
405    }
406
407    #[test]
408    fn test_with_tolerance_grad() {
409        #[derive(Eq, PartialEq, Debug, Clone, Copy)]
410        struct MyFakeSubProblem {}
411
412        // correct parameters
413        for tol in [1e-6, 0.0, 1e-2, 1.0, 2.0] {
414            let sr1: SR1TrustRegion<_, f64> = SR1TrustRegion::new(MyFakeSubProblem {});
415            let res = sr1.with_tolerance_grad(tol);
416            assert!(res.is_ok());
417
418            let nm = res.unwrap();
419            assert_eq!(nm.tol_grad.to_ne_bytes(), tol.to_ne_bytes());
420        }
421
422        // incorrect parameters
423        for tol in [-f64::EPSILON, -1.0, -100.0, -42.0] {
424            let sr1: SR1TrustRegion<_, f64> = SR1TrustRegion::new(MyFakeSubProblem {});
425            let res = sr1.with_tolerance_grad(tol);
426            assert_error!(
427                res,
428                ArgminError,
429                "Invalid parameter: \"`SR1TrustRegion`: gradient tolerance must be >= 0.\""
430            );
431        }
432    }
433
434    #[test]
435    fn test_init() {
436        let subproblem = CauchyPoint::new();
437
438        let param: Vec<f64> = vec![-1.0, 1.0];
439
440        let mut sr1: SR1TrustRegion<_, f64> = SR1TrustRegion::new(subproblem);
441
442        // Forgot to initialize the parameter vector
443        let state: IterState<Vec<f64>, Vec<f64>, (), Vec<Vec<f64>>, (), f64> = IterState::new();
444        let problem = TestProblem::new();
445        let res = sr1.init(&mut Problem::new(problem), state);
446        assert_error!(
447            res,
448            ArgminError,
449            concat!(
450                "Not initialized: \"`SR1TrustRegion` requires an initial parameter vector. Please ",
451                "provide an initial guess via `Executor`s `configure` method.\""
452            )
453        );
454
455        // All good.
456        let state: IterState<Vec<f64>, Vec<f64>, (), Vec<Vec<f64>>, (), f64> =
457            IterState::new().param(param.clone());
458        let problem = TestProblem::new();
459        let (mut state_out, kv) = sr1.init(&mut Problem::new(problem), state).unwrap();
460
461        assert!(kv.is_none());
462
463        let s_param = state_out.take_param().unwrap();
464
465        for (s, p) in s_param.iter().zip(param.iter()) {
466            assert_eq!(s.to_ne_bytes(), p.to_ne_bytes());
467        }
468
469        let s_grad = state_out.take_gradient().unwrap();
470
471        for (s, p) in s_grad.iter().zip(param.iter()) {
472            assert_eq!(s.to_ne_bytes(), p.to_ne_bytes());
473        }
474
475        assert_eq!(state_out.get_cost().to_ne_bytes(), 1.0f64.to_ne_bytes())
476    }
477
478    #[test]
479    fn test_init_provided_cost() {
480        let subproblem = CauchyPoint::new();
481
482        let param: Vec<f64> = vec![-1.0, 1.0];
483
484        let mut sr1: SR1TrustRegion<_, f64> = SR1TrustRegion::new(subproblem);
485
486        let state: IterState<Vec<f64>, Vec<f64>, (), Vec<Vec<f64>>, (), f64> =
487            IterState::new().param(param).cost(1234.0);
488
489        let problem = TestProblem::new();
490        let (state_out, kv) = sr1.init(&mut Problem::new(problem), state).unwrap();
491
492        assert!(kv.is_none());
493
494        assert_eq!(state_out.get_cost().to_ne_bytes(), 1234.0f64.to_ne_bytes())
495    }
496
497    #[test]
498    fn test_init_provided_grad() {
499        let subproblem = CauchyPoint::new();
500
501        let param: Vec<f64> = vec![-1.0, 1.0];
502        let gradient: Vec<f64> = vec![4.0, 9.0];
503
504        let mut sr1: SR1TrustRegion<_, f64> = SR1TrustRegion::new(subproblem);
505
506        let state: IterState<Vec<f64>, Vec<f64>, (), Vec<Vec<f64>>, (), f64> =
507            IterState::new().param(param).gradient(gradient.clone());
508
509        let problem = TestProblem::new();
510        let (mut state_out, kv) = sr1.init(&mut Problem::new(problem), state).unwrap();
511
512        assert!(kv.is_none());
513
514        let s_grad = state_out.take_gradient().unwrap();
515
516        for (s, g) in s_grad.iter().zip(gradient.iter()) {
517            assert_eq!(s.to_ne_bytes(), g.to_ne_bytes());
518        }
519    }
520
521    #[test]
522    fn test_init_provided_hessian() {
523        let subproblem = CauchyPoint::new();
524
525        let param: Vec<f64> = vec![-1.0, 1.0];
526        let gradient: Vec<f64> = vec![4.0, 9.0];
527        let hessian: Vec<Vec<f64>> = vec![vec![1.0, 2.0], vec![3.0, 4.0]];
528
529        let mut sr1: SR1TrustRegion<_, f64> = SR1TrustRegion::new(subproblem);
530
531        let state: IterState<Vec<f64>, Vec<f64>, (), Vec<Vec<f64>>, (), f64> = IterState::new()
532            .param(param)
533            .gradient(gradient)
534            .hessian(hessian.clone());
535
536        let problem = TestProblem::new();
537        let (mut state_out, kv) = sr1.init(&mut Problem::new(problem), state).unwrap();
538
539        assert!(kv.is_none());
540
541        let s_hessian = state_out.take_hessian().unwrap();
542
543        for (s1, g1) in s_hessian.iter().zip(hessian.iter()) {
544            for (s, g) in s1.iter().zip(g1.iter()) {
545                assert_eq!(s.to_ne_bytes(), g.to_ne_bytes());
546            }
547        }
548    }
549}