Skip to main content

lib_jsl_optimization/
optimization_traits.rs

1//! Here are traits that are used in optimization algorithms. They are defined
2//! here to avoid circular dependencies between the optimization algorithms and
3//! the traits they use.
4//!
5//! See the book entry [Optimisation](https://jwkunz.github.io/lib_jsl/book/optimization/index.html#in-the-library).
6use lib_jsl_core::ErrorsJSL;
7
8/// - `ObjectiveFunction`: A trait for objective functions that can be optimized. It has a method `evaluate` that takes a vector of parameters and returns a single scalar value of the objective function at those parameters.
9pub trait ObjectiveFunction {
10    fn evaluate(&self, parameters: &[f64]) -> f64;
11}
12
13/// - `GradientFunction`: A trait for gradient functions that can be used in optimization algorithms. It has a method `evaluate` that takes a vector of parameters and returns a vector of the same length representing the gradient of the objective function at those parameters.
14pub trait GradientFunction {
15    fn evaluate(&self, parameters: &[f64]) -> Vec<f64>;
16}
17
18/// `HessianFunction`: the Hessian `∂²f/∂xᵢ∂xⱼ` of the objective at the given parameters, as
19/// rows of a symmetric matrix. Used by [`NewtonRaphsonMethod`](crate::newton_raphson_method::NewtonRaphsonMethod).
20pub trait HessianFunction {
21    fn evaluate(&self, parameters: &[f64]) -> Vec<Vec<f64>>;
22}
23
24/// - `ObjectiveFunctionWithGradient`: A trait for objective functions that also have a gradient. It is a marker trait that indicates that the objective function implements both `ObjectiveFunction` and `GradientFunction`.
25pub trait ObjectiveFunctionWithGradient: ObjectiveFunction + GradientFunction {}
26
27/// `OptimizationResult`: the best parameters found, the objective there, the iterations taken
28/// and whether the method's convergence test was met. What counts as an iteration, and what the
29/// test is, differ between methods; see each method's documentation.
30#[derive(Debug, Clone)]
31#[non_exhaustive]
32pub struct OptimizationResult {
33    pub parameters: Vec<f64>,
34    pub objective_value: f64,
35    pub iterations: usize,
36    pub converged: bool,
37}
38/// - 'MinimizationControls': A trait that defines methods for setting and getting the convergence criteria for optimization algorithms, including maximum iterations, tolerance, and optional bounds for the optimization.
39pub trait MinimizationControls {
40    /// These traits use options to allow for algorithms to set and get the convergence criteria.
41    /// If the algorithm does not have a maximum number of iterations, this can be set to None.
42    fn set_max_iterations(&mut self, max_iterations: Option<usize>);
43    fn get_max_iterations(&self) -> Option<usize>;
44    /// If the algorithm does not have a tolerance for convergence, this can be set to None.
45    fn set_tolerance(&mut self, tolerance: Option<f64>);
46    fn get_tolerance(&self) -> Option<f64>;
47    /// This function can be used to set and get the optional bounds for the optimization. If the algorithm does not support bounds, this can be set to None.
48    /// The bounds are represented as a vector of tuples, where each tuple contains the lower and upper bound for the corresponding parameter. If a parameter is unbounded, its corresponding tuple can be set to (f64::NEG_INFINITY, f64::INFINITY).
49    fn set_bounds(&mut self, bounds: Option<Vec<(f64, f64)>>);
50    fn get_bounds(&self) -> Option<Vec<(f64, f64)>>;
51}
52
53/// Gradient Free Minimization Engine trait that extends the MinimizationControls trait and has a method `gradient_free_minimize` that takes an objective function and an initial guess for the parameters, and returns the parameters that minimize the objective function.
54pub trait GradientFreeMinimizationEngine<T>: MinimizationControls {
55    fn gradient_free_minimize(
56        &self,
57        objective_function: &T,
58        initial_parameters: Vec<f64>,
59    ) -> Result<OptimizationResult, ErrorsJSL>
60    where
61        T: ObjectiveFunction;
62}       
63
64/// Gradient Based Minimization Engine trait that extends the MinimizationControls trait and has a method `gradient_based_minimize` that takes an objective function, an initial guess for the parameters, and returns the parameters that minimize the objective function.  
65/// This trait is intended for optimization algorithms that require the use of gradients, such as gradient descent or Newton's method.
66/// The method takes an additional argument for the gradient function, which is used to compute the gradient of the objective function at the current parameters.  The optimization algorithm can then use this gradient information to update the parameters in the direction of steepest descent, or to compute a search direction for more advanced optimization methods.    
67pub trait GradientBasedMinimizationEngine<T,U>: MinimizationControls {
68    fn gradient_based_minimize(
69        &self,
70        objective_function: &T ,
71        gradient_function: &U,
72        initial_parameters: Vec<f64>,
73    ) -> Result<OptimizationResult, ErrorsJSL>
74    where
75        T: ObjectiveFunction,
76        U: GradientFunction;
77}   
78
79/// Hessian Based Minimization Engine trait that extends the MinimizationControls trait and has a method `hessian_based_minimize` that takes an objective function, an initial guess for the parameters, and returns the parameters that minimize the objective function.
80/// This trait is intended for optimization algorithms that require the use of second-order information, such as Newton's method or quasi-Newton methods. The method takes additional arguments for the gradient function and the
81/// Hessian function, which are used to compute the gradient and Hessian of the objective function at the current parameters. The optimization algorithm can then use this information to update the parameters in a more informed way, potentially leading to faster convergence to the minimum.
82pub trait HessianBasedMinimizationEngine<T,U,V>: MinimizationControls {
83    fn hessian_based_minimize(
84        &self,
85        objective_function: &T,
86        gradient_function: &U,
87        hessian_function: &V, 
88        initial_parameters: Vec<f64>,
89    ) -> Result<OptimizationResult, ErrorsJSL>
90    where
91        T: ObjectiveFunction,
92        U: GradientFunction,
93        V: HessianFunction;
94}