lib_jsl_optimization/
newton_raphson_method.rs1use crate::{
9 optimization_traits::{
10 GradientFunction, HessianBasedMinimizationEngine, HessianFunction, MinimizationControls,
11 ObjectiveFunction, OptimizationResult,
12 },
13};
14use lib_jsl_core::ErrorsJSL;
15use lib_jsl_linalg::Solve;
16
17#[derive(Debug, Clone, Default)]
20pub struct NewtonRaphsonMethod {
21 max_iterations: Option<usize>,
22 tolerance: Option<f64>,
23 bounds: Option<Vec<(f64, f64)>>,
24}
25
26impl NewtonRaphsonMethod {
27 pub fn new() -> Self {
28 Self::default()
29 }
30}
31
32impl MinimizationControls for NewtonRaphsonMethod {
33 fn set_max_iterations(&mut self, max_iterations: Option<usize>) {
34 self.max_iterations = max_iterations;
35 }
36 fn get_max_iterations(&self) -> Option<usize> {
37 self.max_iterations
38 }
39 fn set_tolerance(&mut self, tolerance: Option<f64>) {
40 self.tolerance = tolerance;
41 }
42 fn get_tolerance(&self) -> Option<f64> {
43 self.tolerance
44 }
45 fn set_bounds(&mut self, bounds: Option<Vec<(f64, f64)>>) {
46 self.bounds = bounds;
47 }
48 fn get_bounds(&self) -> Option<Vec<(f64, f64)>> {
49 self.bounds.clone()
50 }
51}
52
53impl<T, U, V> HessianBasedMinimizationEngine<T, U, V> for NewtonRaphsonMethod
54where T: ObjectiveFunction, U: GradientFunction, V: HessianFunction {
55 fn hessian_based_minimize(
56 &self,
57 objective_function: &T,
58 gradient_function: &U,
59 hessian_function: &V,
60 initial_parameters: Vec<f64>,
61 ) -> Result<OptimizationResult, ErrorsJSL> {
62 let n = initial_parameters.len();
63 if n == 0 {
64 return Err(ErrorsJSL::Misconfiguration("Initial parameters must be a non-empty vector."));
65 }
66 let mut result = OptimizationResult {
67 parameters: initial_parameters.clone(),
68 objective_value: objective_function.evaluate(&initial_parameters),
69 iterations: 0,
70 converged: false,
71 };
72 let bounds = self.get_bounds();
73 if let Some(bounds) = bounds.as_ref() {
74 if bounds.len() != n {
75 return Err(ErrorsJSL::Misconfiguration(
76 "Bounds length must match the number of parameters.",
77 ));
78 }
79 if bounds.iter().any(|(lower, upper)| lower > upper) {
80 return Err(ErrorsJSL::Misconfiguration(
81 "Lower bound must be less than or equal to upper bound.",
82 ));
83 }
84 }
85 let max_iterations = self.get_max_iterations().unwrap_or(100);
87 while result.iterations < max_iterations {
88 let gradient = gradient_function.evaluate(&result.parameters);
90 let hessian = hessian_function.evaluate(&result.parameters);
91 if gradient.len() != n || hessian.len() != n || hessian.iter().any(|row| row.len() != n) {
92 return Err(ErrorsJSL::Misconfiguration("The gradient and Hessian must match the number of parameters."));
93 }
94 let hessian_matrix = ndarray::Array2::from_shape_vec((n, n), hessian.into_iter().flatten().collect())
95 .expect("n × n entries");
96 let step = hessian_matrix
98 .solve(&ndarray::Array1::from_vec(gradient))
99 .map_err(|_| ErrorsJSL::RuntimeError("The Hessian is singular."))?
100 .mapv(|x| -x);
101 let mut new_parameters = result
103 .parameters
104 .iter()
105 .zip(step.iter())
106 .map(|(p, s)| p + s)
107 .collect::<Vec<f64>>();
108 if let Some(bounds) = bounds.as_ref() {
109 new_parameters = new_parameters
110 .iter()
111 .enumerate()
112 .map(|(i, p)| {
113 let (lower, upper) = bounds[i];
114 if *p < lower {
115 lower
116 } else if *p > upper {
117 upper
118 } else {
119 *p
120 }
121 })
122 .collect();
123 }
124 let new_objective_value = objective_function.evaluate(&new_parameters);
125 result.iterations += 1;
126 if (result.objective_value - new_objective_value).abs()
127 < self.get_tolerance().unwrap_or(1e-6)
128 {
129 result.converged = true;
130 result.parameters = new_parameters;
131 result.objective_value = new_objective_value;
132 break;
133 }
134 result.parameters = new_parameters;
135 result.objective_value = new_objective_value;
136 }
137 Ok(result)
138 }
139}
140#[cfg(test)]
141mod tests {
142 use super::*;
143 use crate::optimization_traits::ObjectiveFunctionWithGradient;
144 #[test]
145 fn test_newton_raphson_method() {
146 struct TestObjectiveFunction;
148 impl ObjectiveFunction for TestObjectiveFunction {
149 fn evaluate(&self, parameters: &[f64]) -> f64 {
150 let x = parameters[0];
151 (x - 2.0).powi(2) + 1.0
152 }
153 }
154 impl GradientFunction for TestObjectiveFunction {
155 fn evaluate(&self, parameters: &[f64]) -> Vec<f64> {
156 let x = parameters[0];
157 vec![2.0 * (x - 2.0)]
158 }
159 }
160 impl HessianFunction for TestObjectiveFunction {
161 fn evaluate(&self, _: &[f64]) -> Vec<Vec<f64>> {
162 vec![vec![2.0]]
163 }
164 }
165 impl ObjectiveFunctionWithGradient for TestObjectiveFunction {}
166 let objective_function = TestObjectiveFunction;
167 let mut optimizer = NewtonRaphsonMethod::new();
168 optimizer.set_tolerance(Some(1e-6));
169 optimizer.set_bounds(Some(vec![(0.0, 4.0)]));
170 let initial_parameters = vec![0.0];
171 let result = optimizer
172 .hessian_based_minimize(
173 &objective_function,
174 &objective_function,
175 &objective_function,
176 initial_parameters,
177 )
178 .unwrap();
179 assert!(result.converged);
181 assert!((result.parameters[0] - 2.0).abs() < 1e-3);
182 assert!((result.objective_value - 1.0).abs() < 1e-3);
183 }
184
185 struct Flat;
186 impl ObjectiveFunction for Flat {
187 fn evaluate(&self, p: &[f64]) -> f64 {
188 p[0]
189 }
190 }
191 impl GradientFunction for Flat {
192 fn evaluate(&self, _: &[f64]) -> Vec<f64> {
193 vec![1.0]
194 }
195 }
196 impl HessianFunction for Flat {
197 fn evaluate(&self, _: &[f64]) -> Vec<Vec<f64>> {
198 vec![vec![0.0]]
199 }
200 }
201
202 #[test]
203 fn singular_hessians_and_empty_input_are_errors_not_panics() {
204 let newton = NewtonRaphsonMethod::new();
206 assert!(newton.hessian_based_minimize(&Flat, &Flat, &Flat, vec![1.0]).is_err());
207 assert!(newton.hessian_based_minimize(&Flat, &Flat, &Flat, vec![]).is_err());
208 }
209
210 #[test]
211 fn quadratic_convergence_on_a_smooth_convex_function() {
212 struct ExpMinusX;
214 impl ObjectiveFunction for ExpMinusX {
215 fn evaluate(&self, p: &[f64]) -> f64 {
216 p.iter().map(|x| x.exp() - x).sum()
217 }
218 }
219 impl GradientFunction for ExpMinusX {
220 fn evaluate(&self, p: &[f64]) -> Vec<f64> {
221 p.iter().map(|x| x.exp() - 1.0).collect()
222 }
223 }
224 impl HessianFunction for ExpMinusX {
225 fn evaluate(&self, p: &[f64]) -> Vec<Vec<f64>> {
226 (0..p.len()).map(|i| (0..p.len()).map(|j| if i == j { p[i].exp() } else { 0.0 }).collect()).collect()
227 }
228 }
229 let mut newton = NewtonRaphsonMethod::new();
230 newton.set_tolerance(Some(1e-15));
231 let r = newton.hessian_based_minimize(&ExpMinusX, &ExpMinusX, &ExpMinusX, vec![1.0, -1.0]).unwrap();
232 assert!(r.converged && r.parameters.iter().all(|x| x.abs() < 1e-7) && r.iterations < 10, "{r:?}");
233 }
234}