Skip to main content

lib_jsl_optimization/
gradient_descent.rs

1//! This file contains the implementation of the gradient descent algorithm for optimization.
2//! Gradient descent is an iterative optimization algorithm used to find the minimum of a function.
3//! The algorithm works by taking steps proportional to the negative of the gradient of the function at the current point. The size of the steps is determined by a learning rate, which is a hyperparameter that controls how quickly the algorithm converges to the minimum. 
4//! It stops when the objective changes by less than the tolerance (default 1e-5) in one step, or
5//! after `max_iterations` (default 1000). That test does not measure the gradient: with a small
6//! learning rate the objective changes little per step even far from a minimum, so check the
7//! result. Too large a learning rate (above `2/L` for an `L`-smooth function) diverges. With
8//! bounds, each step is projected onto the box (projected gradient descent).
9//!
10//! See the book entry [Gradient descent and nonlinear conjugate gradients](https://jwkunz.github.io/lib_jsl/book/optimization/gradient-methods.html#gradient-descent).
11
12use crate::optimization_traits::{
13    GradientBasedMinimizationEngine, GradientFunction, MinimizationControls, ObjectiveFunction,
14    OptimizationResult,
15};
16use lib_jsl_core::ErrorsJSL;
17
18pub struct GradientDescent {
19    learning_rate: f64,
20    max_iterations: Option<usize>,
21    tolerance: Option<f64>,
22    bounds: Option<Vec<(f64, f64)>>,
23}
24
25impl GradientDescent {
26    pub fn new(learning_rate: f64) -> Self {
27        GradientDescent {
28            learning_rate,
29            max_iterations: None,
30            tolerance: None,
31            bounds: None,
32        }
33    }
34}
35
36impl MinimizationControls for GradientDescent {
37    fn set_max_iterations(&mut self, max_iterations: Option<usize>) {
38        self.max_iterations = max_iterations;
39    }
40    fn get_max_iterations(&self) -> Option<usize> {
41        self.max_iterations
42    }
43    fn set_tolerance(&mut self, tolerance: Option<f64>) {
44        self.tolerance = tolerance;
45    }
46    fn get_tolerance(&self) -> Option<f64> {
47        self.tolerance
48    }
49    fn set_bounds(&mut self, bounds: Option<Vec<(f64, f64)>>) {
50        self.bounds = bounds;
51    }
52    fn get_bounds(&self) -> Option<Vec<(f64, f64)>> {
53        self.bounds.clone()
54    }
55}
56
57impl<T, U> GradientBasedMinimizationEngine<T, U> for GradientDescent 
58where T: ObjectiveFunction, U: GradientFunction {
59    fn gradient_based_minimize(
60            &self,
61            objective_function: &T,
62            gradient_function: &U,
63            initial_parameters: Vec<f64>,
64        ) -> Result<OptimizationResult, ErrorsJSL> {
65        if initial_parameters.is_empty() {
66            return Err(ErrorsJSL::Misconfiguration("Initial parameters must be a non-empty vector."));
67        }
68
69        let bounds = self.get_bounds();
70        if let Some(bounds) = bounds.as_ref() {
71            if bounds.len() != initial_parameters.len() {
72                return Err(ErrorsJSL::Misconfiguration(
73                    "Bounds length must match the number of parameters.",
74                ));
75            }            
76            if bounds.iter().any(|(lower, upper)| lower > upper) {
77                return Err(ErrorsJSL::Misconfiguration(
78                    "Lower bound must be less than or equal to upper bound.",
79                ));
80            }
81        }
82
83        // Here is the implementation of the gradient descent algorithm. It assumes that the objective function is differentiable and that the initial parameters are a valid starting point for the optimization.
84        let mut result = OptimizationResult {
85            parameters: initial_parameters.clone(),
86            objective_value: objective_function.evaluate(&initial_parameters),
87            iterations: 0,
88            converged: false,
89        };
90        let max_iterations = self.max_iterations.unwrap_or(1000);
91        let tolerance = self.tolerance.unwrap_or(1e-5);
92        // The main loop of the gradient descent algorithm. It continues until the desired level of precision is achieved or the maximum number of iterations is reached.
93        while result.iterations < max_iterations {
94            // The gradient of the objective function at the current parameters is evaluated, and the parameters are updated by taking a step in the direction of the negative gradient, scaled by the learning rate. If bounds are set, the updated parameters are projected back into the feasible region defined by the bounds.
95            let gradient = gradient_function.evaluate(&result.parameters);
96            if gradient.len() != result.parameters.len() {
97                return Err(ErrorsJSL::Misconfiguration(
98                    "Gradient length must match the number of parameters.",
99                ));
100            }
101            // ANCHOR: gradient_step
102            let mut new_parameters: Vec<f64> = result.parameters.iter().zip(gradient.iter()).map(|(p, g)| p - self.learning_rate * g).collect();
103            if let Some(bounds) = bounds.as_ref() {
104                new_parameters = new_parameters.iter().enumerate().map(|(i, p)| {
105                    let (lower_bound, upper_bound) = bounds[i];
106                    p.max(lower_bound).min(upper_bound)
107                }).collect();
108            }
109            // ANCHOR_END: gradient_step
110            // The objective value at the new parameters is evaluated, and the convergence status is determined based on whether the change in objective value is smaller than the specified tolerance.
111            let new_objective_value = objective_function.evaluate(&new_parameters);
112            result.iterations += 1;
113            if (result.objective_value - new_objective_value).abs() < tolerance {
114                result.converged = true;
115                result.parameters = new_parameters;
116                result.objective_value = new_objective_value;
117                break;
118            }
119            result.parameters = new_parameters;
120            result.objective_value = new_objective_value;
121        }
122        Ok(result)
123    }
124}       
125
126#[cfg(test)]
127mod tests {
128    use crate::optimization_traits::ObjectiveFunctionWithGradient;
129
130    use super::*;
131    #[test]
132    fn test_gradient_descent() {
133        // This is a simple test case for the gradient descent algorithm. It uses a simple quadratic function with a minimum at x = 2.0 and a minimum value of 1.0. The algorithm should be able to find the minimum within a reasonable number of iterations.
134        struct TestObjectiveFunction;
135        impl ObjectiveFunction for TestObjectiveFunction {
136            fn evaluate(&self, parameters: &[f64]) -> f64 {
137                let x = parameters[0];
138                (x - 2.0).powi(2) + 1.0
139            }
140        }
141        impl GradientFunction for TestObjectiveFunction {
142            fn evaluate(&self, parameters: &[f64]) -> Vec<f64> {
143                let x = parameters[0];
144                vec![2.0 * (x - 2.0)]
145            }
146        }
147        impl ObjectiveFunctionWithGradient for TestObjectiveFunction {}
148        let objective_function = TestObjectiveFunction;
149        let mut optimizer = GradientDescent::new(1E-2);
150        optimizer.set_max_iterations(Some(10000));
151        optimizer.set_tolerance(Some(1e-6));
152        let initial_parameters = vec![0.0];
153        let result = optimizer.gradient_based_minimize(&objective_function, &objective_function, initial_parameters).unwrap();
154        //dbg!("Result: {:?}", &result);
155        assert!(result.converged);
156        assert!((result.parameters[0] - 2.0).abs() < 1e-1);
157        assert!((result.objective_value - 1.0).abs() < 1e-1);
158    }
159
160    #[test]
161    fn test_gradient_descent_rejects_empty_initial_parameters() {
162        struct PanickingObjective;
163        impl ObjectiveFunction for PanickingObjective {
164            fn evaluate(&self, _: &[f64]) -> f64 {
165                panic!("objective should not be evaluated when initial parameters are empty");
166            }
167        }
168        impl GradientFunction for PanickingObjective {
169            fn evaluate(&self, _: &[f64]) -> Vec<f64> {
170                vec![]
171            }
172        }
173        impl ObjectiveFunctionWithGradient for PanickingObjective {}
174
175        let optimizer = GradientDescent::new(1e-2);
176        let result = optimizer.gradient_based_minimize(&PanickingObjective, &PanickingObjective, vec![]);
177        assert!(matches!(result, Err(ErrorsJSL::Misconfiguration(_))));
178    }
179
180    #[test]
181    fn test_gradient_descent_rejects_bounds_dimension_mismatch() {
182        struct Objective;
183        impl ObjectiveFunction for Objective {
184            fn evaluate(&self, parameters: &[f64]) -> f64 {
185                parameters.iter().map(|x| x * x).sum()
186            }
187        }
188        impl GradientFunction for Objective {
189            fn evaluate(&self, parameters: &[f64]) -> Vec<f64> {
190                parameters.iter().map(|x| 2.0 * x).collect()
191            }
192        }
193        impl ObjectiveFunctionWithGradient for Objective {}
194
195        let mut optimizer = GradientDescent::new(1e-2);
196        optimizer.set_bounds(Some(vec![(-1.0, 1.0)]));
197        let result = optimizer.gradient_based_minimize(&Objective, &Objective, vec![1.0, 2.0]);
198        assert!(matches!(result, Err(ErrorsJSL::Misconfiguration(_))));
199    }
200
201    #[test]
202    fn test_gradient_descent_rejects_gradient_dimension_mismatch() {
203        struct Objective;
204        impl ObjectiveFunction for Objective {
205            fn evaluate(&self, parameters: &[f64]) -> f64 {
206                parameters.iter().map(|x| x * x).sum()
207            }
208        }
209        struct BadGradient;
210        impl GradientFunction for BadGradient {
211            fn evaluate(&self, _: &[f64]) -> Vec<f64> {
212                vec![1.0]
213            }
214        }
215
216        let optimizer = GradientDescent::new(1e-2);
217        let result = optimizer.gradient_based_minimize(&Objective, &BadGradient, vec![1.0, 2.0]);
218        assert!(matches!(result, Err(ErrorsJSL::Misconfiguration(_))));
219    }
220}