Skip to main content

argmin/solver/linesearch/condition/
goldstein.rs

1// Copyright 2018-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 super::LineSearchCondition;
9use crate::core::{ArgminFloat, Error};
10use argmin_math::ArgminDot;
11#[cfg(feature = "serde1")]
12use serde::{Deserialize, Serialize};
13
14/// # Goldstein conditions
15///
16/// Ensures sufficient decrease of the cost function value and also bounds the step length from
17/// below.
18#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
19#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
20pub struct GoldsteinCondition<F> {
21    c: F,
22}
23
24impl<F> GoldsteinCondition<F>
25where
26    F: ArgminFloat,
27{
28    /// Construct a new instance of [`GoldsteinCondition`].
29    ///
30    /// # Example
31    ///
32    /// ```
33    /// # use argmin::solver::linesearch::condition::GoldsteinCondition;
34    /// let goldstein = GoldsteinCondition::new(0.1f64);
35    /// ```
36    pub fn new(c: F) -> Result<Self, Error> {
37        if c <= float!(0.0) || c >= float!(0.5) {
38            return Err(argmin_error!(
39                InvalidParameter,
40                "GoldsteinCondition: Parameter c must be in (0, 0.5)"
41            ));
42        }
43        Ok(GoldsteinCondition { c })
44    }
45}
46
47impl<T, G, F> LineSearchCondition<T, G, F> for GoldsteinCondition<F>
48where
49    G: ArgminDot<T, F>,
50    F: ArgminFloat,
51{
52    fn evaluate_condition(
53        &self,
54        current_cost: F,
55        _current_gradient: Option<&G>,
56        initial_cost: F,
57        initial_gradient: &G,
58        search_direction: &T,
59        step_length: F,
60    ) -> bool {
61        let tmp = step_length * initial_gradient.dot(search_direction);
62        initial_cost + (float!(1.0) - self.c) * tmp <= current_cost
63            && current_cost <= initial_cost + self.c * tmp
64    }
65
66    fn requires_current_gradient(&self) -> bool {
67        false
68    }
69}
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74    use crate::core::ArgminError;
75
76    test_trait_impl!(goldstein, GoldsteinCondition<f64>);
77
78    #[test]
79    fn test_goldstein_new() {
80        let c: f64 = 0.01;
81        let GoldsteinCondition { c: c_arm } = GoldsteinCondition::new(c).unwrap();
82        assert_eq!(c.to_ne_bytes(), c_arm.to_ne_bytes());
83
84        assert_error!(
85            GoldsteinCondition::new(0.5f64),
86            ArgminError,
87            "Invalid parameter: \"GoldsteinCondition: Parameter c must be in (0, 0.5)\""
88        );
89
90        assert_error!(
91            GoldsteinCondition::new(1.0f64),
92            ArgminError,
93            "Invalid parameter: \"GoldsteinCondition: Parameter c must be in (0, 0.5)\""
94        );
95
96        assert_error!(
97            GoldsteinCondition::new(0.0f64),
98            ArgminError,
99            "Invalid parameter: \"GoldsteinCondition: Parameter c must be in (0, 0.5)\""
100        );
101
102        assert_error!(
103            GoldsteinCondition::new(-1.0f64),
104            ArgminError,
105            "Invalid parameter: \"GoldsteinCondition: Parameter c must be in (0, 0.5)\""
106        );
107    }
108
109    #[test]
110    fn test_goldstein() {
111        let c: f64 = 0.1;
112        let cond = GoldsteinCondition::new(c).unwrap();
113        let f = |x: f64, y: f64| x.powf(2.0) + y.powf(2.0);
114        let g = |x: f64, y: f64| vec![2.0 * x, 2.0 * y];
115        let initial_x = -1.0;
116        let initial_y = -0.0;
117        let search_direction = vec![1.0, 0.0];
118        // Need a larger epsilon here, I suppose because of more severe round off errors.
119        for (alpha, acc) in [
120            (0.001, false),
121            (0.03, false),
122            (0.2 - 6.0 * f64::EPSILON, false),
123            (0.2, true),
124            (0.2, true),
125            (0.5, true),
126            (0.9, true),
127            (0.99, true),
128            (1.0, true),
129            (1.5, true),
130            (1.8 - f64::EPSILON, true),
131            (1.8, false),
132            (2.0, false),
133            (2.3, false),
134        ] {
135            assert_eq!(
136                cond.evaluate_condition(
137                    f(initial_x + alpha, initial_y),
138                    Some(&g(initial_x + alpha, initial_y)),
139                    f(initial_x, initial_y),
140                    &g(initial_x, initial_y),
141                    &search_direction,
142                    alpha,
143                ),
144                acc
145            );
146        }
147    }
148}