lib_jsl_derivatives/
adaptive.rs1#![allow(clippy::neg_cmp_op_on_partial_ord)]
13#![allow(clippy::needless_range_loop)]
14
15use lib_jsl_core::ErrorsJSL;
16
17#[derive(Clone, Copy, Debug)]
19pub struct DerivativeOptions {
20 pub initial_step: f64,
22 pub step_factor: f64,
24 pub max_iterations: usize,
26 pub atol: f64,
28 pub rtol: f64,
29}
30
31impl Default for DerivativeOptions {
32 fn default() -> Self {
34 DerivativeOptions { initial_step: 0.5, step_factor: 2.0, max_iterations: 10, atol: 0.0, rtol: f64::EPSILON.sqrt() * 1e-3 }
35 }
36}
37
38#[derive(Clone, Copy, Debug)]
40#[non_exhaustive]
41pub struct DerivativeResult {
42 pub df: f64,
43 pub error: f64,
45 pub nfev: usize,
47 pub converged: bool,
49}
50
51pub fn derivative(f: impl Fn(f64) -> f64, x: f64, options: DerivativeOptions) -> Result<DerivativeResult, ErrorsJSL> {
60 if !x.is_finite() || !(options.initial_step > 0.0) || !(options.step_factor > 1.0) || options.max_iterations == 0 {
61 return Err(ErrorsJSL::InvalidInputRange("need a finite point, a positive step and a step factor above 1"));
62 }
63 let c2 = options.step_factor * options.step_factor;
64 let mut h = options.initial_step;
65 let mut nfev = 0;
66 let mut central = |h: f64| {
67 nfev += 2;
68 (f(x + h) - f(x - h)) / (2.0 * h)
69 };
70 let mut prev_row = vec![central(h)];
71 let (mut best, mut err) = (prev_row[0], f64::INFINITY);
72 for iteration in 1..options.max_iterations {
73 h /= options.step_factor;
74 let mut row = vec![central(h)];
75 let mut fac = c2;
76 for j in 1..=prev_row.len() {
77 let t = (row[j - 1] * fac - prev_row[j - 1]) / (fac - 1.0);
78 fac *= c2;
79 let errt = (t - row[j - 1]).abs().max((t - prev_row[j - 1]).abs());
80 if errt <= err {
81 err = errt;
82 best = t;
83 }
84 row.push(t);
85 }
86 let diverging = iteration >= 3 && err <= f64::EPSILON.sqrt() * best.abs().max(1e-300) && (row[row.len() - 1] - prev_row[prev_row.len() - 1]).abs() >= 2.0 * err;
91 prev_row = row;
92 if err <= options.atol + options.rtol * best.abs() || diverging {
93 break;
94 }
95 }
96 Ok(DerivativeResult { df: best, error: err, nfev, converged: err <= options.atol + options.rtol * best.abs() || err.is_finite() && err <= 1e-8 * best.abs().max(1.0) })
97}
98pub fn jacobian(f: impl Fn(&[f64]) -> Vec<f64>, x: &[f64], options: DerivativeOptions) -> Result<(Vec<Vec<f64>>, f64), ErrorsJSL> {
103 let m = f(x).len();
104 let n = x.len();
105 let mut jac = vec![vec![0.0; n]; m];
106 let mut worst: f64 = 0.0;
107 for j in 0..n {
108 for (i, row) in jac.iter_mut().enumerate() {
109 let g = |t: f64| {
110 let mut z = x.to_vec();
111 z[j] = t;
112 f(&z)[i]
113 };
114 let r = derivative(g, x[j], options)?;
115 row[j] = r.df;
116 worst = worst.max(r.error);
117 }
118 }
119 Ok((jac, worst))
120}
121
122pub fn hessian(f: impl Fn(&[f64]) -> f64, x: &[f64], options: DerivativeOptions) -> Result<Vec<Vec<f64>>, ErrorsJSL> {
125 let n = x.len();
126 let inner = DerivativeOptions { initial_step: options.initial_step / 4.0, ..options };
127 let grad = |z: &[f64]| -> Vec<f64> {
128 (0..n)
129 .map(|i| {
130 derivative(
131 |t| {
132 let mut w = z.to_vec();
133 w[i] = t;
134 f(&w)
135 },
136 z[i],
137 inner,
138 )
139 .map(|r| r.df)
140 .unwrap_or(f64::NAN)
141 })
142 .collect()
143 };
144 let (mut h, _) = jacobian(grad, x, options)?;
145 for i in 0..n {
146 for j in 0..i {
147 let s = 0.5 * (h[i][j] + h[j][i]);
148 h[i][j] = s;
149 h[j][i] = s;
150 }
151 }
152 Ok(h)
153}
154
155#[cfg(test)]
156mod tests {
157 use super::*;
158
159 #[test]
160 fn derivatives_of_smooth_functions_are_near_machine_precision() {
161 for &x in &[0.3, 1.0, 2.7] {
162 let r = derivative(f64::exp, x, DerivativeOptions::default()).unwrap();
163 assert!((r.df - x.exp()).abs() < 1e-12 * x.exp(), "{x}: {:?}", r);
164 assert!(r.error < 1e-9 * x.exp());
165 let r = derivative(|t| (3.0 * t).sin(), x, DerivativeOptions::default()).unwrap();
166 assert!((r.df - 3.0 * (3.0 * x).cos()).abs() < 1e-11);
167 }
168 }
169
170 #[test]
171 fn jacobian_and_hessian_of_simple_maps() {
172 let f = |v: &[f64]| vec![v[0] * v[1], v[0].sin() + v[1] * v[1]];
173 let (j, _) = jacobian(f, &[0.5, 2.0], DerivativeOptions::default()).unwrap();
174 let want = [[2.0, 0.5], [0.5f64.cos(), 4.0]];
175 for i in 0..2 {
176 for k in 0..2 {
177 assert!((j[i][k] - want[i][k]).abs() < 1e-11);
178 }
179 }
180 let h = hessian(|v: &[f64]| v[0] * v[0] * v[1] + v[1].exp(), &[1.5, 0.5], DerivativeOptions::default()).unwrap();
181 let want = [[2.0 * 0.5, 2.0 * 1.5], [2.0 * 1.5, 0.5f64.exp()]];
182 for i in 0..2 {
183 for k in 0..2 {
184 assert!((h[i][k] - want[i][k]).abs() < 1e-8, "{h:?}");
185 }
186 }
187 }
188}