1use lib_jsl_core::ErrorsJSL;
15#[derive(Debug, Clone, Copy)]
17pub struct SystemOptions {
18 pub function_tolerance: f64,
20 pub step_tolerance: f64,
25 pub max_iterations: usize,
27}
28
29impl Default for SystemOptions {
30 fn default() -> Self {
31 SystemOptions { function_tolerance: 1e-12, step_tolerance: 1e-14, max_iterations: 200 }
32 }
33}
34
35#[derive(Debug, Clone)]
37#[non_exhaustive]
38pub struct SystemRootResult {
39 pub x: Vec<f64>,
41 pub residual: f64,
43 pub iterations: usize,
45 pub nfev: usize,
47 pub converged: bool,
49}
50
51impl SystemRootResult {
52 pub(crate) fn new(x: Vec<f64>, residual: f64, iterations: usize, nfev: usize, converged: bool) -> Self {
53 SystemRootResult { x, residual, iterations, nfev, converged }
54 }
55}
56
57fn inf_norm(v: &[f64]) -> f64 {
58 v.iter().fold(0.0, |m, a| m.max(a.abs()))
59}
60
61fn half_norm_squared(v: &[f64]) -> f64 {
62 0.5 * v.iter().map(|a| a * a).sum::<f64>()
63}
64
65fn solve_dense(mut a: Vec<Vec<f64>>, mut b: Vec<f64>) -> Option<Vec<f64>> {
67 let n = b.len();
68 for k in 0..n {
69 let p = (k..n).max_by(|&i, &j| a[i][k].abs().total_cmp(&a[j][k].abs()))?;
70 if a[p][k] == 0.0 || !a[p][k].is_finite() {
71 return None;
72 }
73 a.swap(k, p);
74 b.swap(k, p);
75 for i in k + 1..n {
76 let m = a[i][k] / a[k][k];
77 let (top, rest) = a.split_at_mut(i);
78 rest[0][k..].iter_mut().zip(&top[k][k..]).for_each(|(x, y)| *x -= m * y);
79 b[i] -= m * b[k];
80 }
81 }
82 for i in (0..n).rev() {
83 let s: f64 = (i + 1..n).map(|j| a[i][j] * b[j]).sum();
84 b[i] = (b[i] - s) / a[i][i];
85 }
86 Some(b)
87}
88
89struct Counted<'a, F> {
90 f: &'a F,
91 evaluations: usize,
92}
93
94impl<F: Fn(&[f64]) -> Vec<f64>> Counted<'_, F> {
95 fn eval(&mut self, x: &[f64]) -> Vec<f64> {
96 self.evaluations += 1;
97 (self.f)(x)
98 }
99
100 fn jacobian(&mut self, x: &[f64], fx: &[f64]) -> Vec<Vec<f64>> {
101 let n = x.len();
102 let mut jac = vec![vec![0.0; n]; n];
103 let mut z = x.to_vec();
104 for k in 0..n {
105 let h = f64::EPSILON.sqrt() * x[k].abs().max(1.0);
106 z[k] = x[k] + h;
107 let fz = self.eval(&z);
108 z[k] = x[k];
109 for i in 0..n {
110 jac[i][k] = (fz[i] - fx[i]) / h;
111 }
112 }
113 jac
114 }
115}
116
117fn line_search<F: Fn(&[f64]) -> Vec<f64>>(sys: &mut Counted<F>, x: &[f64], f0: f64, slope: f64, p: &[f64]) -> (Vec<f64>, Vec<f64>, bool) {
121 let max_step = 100.0 * x.iter().map(|v| v * v).sum::<f64>().sqrt().max(x.len() as f64);
122 let norm_p = p.iter().map(|v| v * v).sum::<f64>().sqrt();
123 let scale = if norm_p > max_step { max_step / norm_p } else { 1.0 };
124 let p: Vec<f64> = p.iter().map(|v| v * scale).collect();
125 let slope = slope * scale;
126 let (mut lambda, mut previous_lambda, mut previous_f) = (1.0, 1.0, f0);
127 let min_lambda = 1e-12 / p.iter().zip(x).map(|(pi, xi)| pi.abs() / xi.abs().max(1.0)).fold(1e-300, f64::max);
128 loop {
129 let trial: Vec<f64> = x.iter().zip(&p).map(|(a, b)| a + lambda * b).collect();
130 let ft = sys.eval(&trial);
131 let value = half_norm_squared(&ft);
132 if value.is_finite() && value <= f0 + 1e-4 * lambda * slope {
133 return (trial, ft, true);
134 }
135 if lambda < min_lambda {
136 return (trial, ft, false);
137 }
138 let next = if !value.is_finite() {
139 0.1 * lambda
140 } else if lambda == 1.0 {
141 -slope / (2.0 * (value - f0 - slope))
142 } else {
143 let r1 = value - f0 - lambda * slope;
144 let r2 = previous_f - f0 - previous_lambda * slope;
145 let a = (r1 / (lambda * lambda) - r2 / (previous_lambda * previous_lambda)) / (lambda - previous_lambda);
146 let b = (-previous_lambda * r1 / (lambda * lambda) + lambda * r2 / (previous_lambda * previous_lambda)) / (lambda - previous_lambda);
147 let t = if a == 0.0 {
148 -slope / (2.0 * b)
149 } else {
150 let disc = b * b - 3.0 * a * slope;
151 if disc < 0.0 { 0.5 * lambda } else if b <= 0.0 { (-b + disc.sqrt()) / (3.0 * a) } else { -slope / (b + disc.sqrt()) }
152 };
153 t.min(0.5 * lambda)
154 };
155 previous_lambda = lambda;
156 previous_f = value;
157 lambda = if next.is_finite() { next.max(0.1 * lambda) } else { 0.1 * lambda };
158 }
159}
160
161fn finish(x: Vec<f64>, fx: &[f64], iterations: usize, evaluations: usize, converged: bool) -> SystemRootResult {
162 SystemRootResult { residual: inf_norm(fx), x, iterations, nfev: evaluations, converged }
163}
164
165pub fn newton_system<F, J>(f: F, jacobian: Option<J>, x0: Vec<f64>, options: SystemOptions) -> Result<SystemRootResult, ErrorsJSL>
169where
170 F: Fn(&[f64]) -> Vec<f64>,
171 J: Fn(&[f64]) -> Vec<Vec<f64>>,
172{
173 let n = x0.len();
174 let mut sys = Counted { f: &f, evaluations: 0 };
175 if n == 0 {
176 return Err(ErrorsJSL::InvalidInputRange("newton_system: the starting point must not be empty"));
177 }
178 let mut x = x0;
179 let mut fx = sys.eval(&x);
180 if fx.len() != n {
181 return Err(ErrorsJSL::InvalidInputRange("newton_system: F must map ℝⁿ to ℝⁿ"));
182 }
183 for iteration in 0..options.max_iterations {
184 if inf_norm(&fx) <= options.function_tolerance {
185 return Ok(finish(x, &fx, iteration, sys.evaluations, true));
186 }
187 let jac = match &jacobian {
188 Some(j) => j(&x),
189 None => sys.jacobian(&x, &fx),
190 };
191 if jac.len() != n || jac.iter().any(|row| row.len() != n) {
192 return Err(ErrorsJSL::InvalidInputRange("newton_system: the Jacobian must be n × n"));
193 }
194 let Some(step) = solve_dense(jac, fx.iter().map(|v| -v).collect()) else {
196 return Ok(finish(x, &fx, iteration, sys.evaluations, false));
197 };
198 let f0 = half_norm_squared(&fx);
199 let (x_new, f_new, ok) = line_search(&mut sys, &x, f0, -2.0 * f0, &step);
200 let relative_step = x_new.iter().zip(&x).map(|(a, b)| (a - b).abs() / a.abs().max(1.0)).fold(0.0, f64::max);
202 x = x_new;
203 fx = f_new;
204 if !ok || relative_step < options.step_tolerance {
205 let converged = inf_norm(&fx) <= options.function_tolerance.max(1e-8);
206 return Ok(finish(x, &fx, iteration + 1, sys.evaluations, converged));
207 }
208 }
209 let converged = inf_norm(&fx) <= options.function_tolerance;
210 Ok(finish(x, &fx, options.max_iterations, sys.evaluations, converged))
211}
212
213pub fn broyden_system<F>(f: F, x0: Vec<f64>, options: SystemOptions) -> Result<SystemRootResult, ErrorsJSL>
216where
217 F: Fn(&[f64]) -> Vec<f64>,
218{
219 let n = x0.len();
220 let mut sys = Counted { f: &f, evaluations: 0 };
221 if n == 0 {
222 return Err(ErrorsJSL::InvalidInputRange("broyden_system: the starting point must not be empty"));
223 }
224 let mut x = x0;
225 let mut fx = sys.eval(&x);
226 if fx.len() != n {
227 return Err(ErrorsJSL::InvalidInputRange("broyden_system: F must map ℝⁿ to ℝⁿ"));
228 }
229 let mut b = sys.jacobian(&x, &fx);
230 let mut fresh = true;
231 for iteration in 0..options.max_iterations {
232 if inf_norm(&fx) <= options.function_tolerance {
233 return Ok(finish(x, &fx, iteration, sys.evaluations, true));
234 }
235 let step = solve_dense(b.clone(), fx.iter().map(|v| -v).collect());
236 let f0 = half_norm_squared(&fx);
237 let result = step.map(|p| {
238 line_search(&mut sys, &x, f0, -2.0 * f0, &p)
240 });
241 match result {
242 Some((x_new, f_new, true)) => {
243 let s: Vec<f64> = x_new.iter().zip(&x).map(|(a, c)| a - c).collect();
244 let ss: f64 = s.iter().map(|v| v * v).sum();
245 let relative_step = s.iter().zip(&x_new).map(|(d, a)| d.abs() / a.abs().max(1.0)).fold(0.0, f64::max);
246 if ss > 0.0 {
248 let bs: Vec<f64> = b.iter().map(|row| row.iter().zip(&s).map(|(a, c)| a * c).sum()).collect();
249 for i in 0..n {
250 let u = (f_new[i] - fx[i] - bs[i]) / ss;
251 b[i].iter_mut().zip(&s).for_each(|(bij, sj)| *bij += u * sj);
252 }
253 }
254 x = x_new;
256 fx = f_new;
257 fresh = false;
258 if relative_step < options.step_tolerance {
259 let converged = inf_norm(&fx) <= options.function_tolerance.max(1e-8);
260 return Ok(finish(x, &fx, iteration + 1, sys.evaluations, converged));
261 }
262 }
263 _ if !fresh => {
264 b = sys.jacobian(&x, &fx);
266 fresh = true;
267 }
268 _ => return Ok(finish(x, &fx, iteration, sys.evaluations, false)),
269 }
270 }
271 let converged = inf_norm(&fx) <= options.function_tolerance;
272 Ok(finish(x, &fx, options.max_iterations, sys.evaluations, converged))
273}
274
275#[cfg(test)]
276mod tests {
277 use super::*;
278
279 type NoJacobian = fn(&[f64]) -> Vec<Vec<f64>>;
280
281 fn rosenbrock(x: &[f64]) -> Vec<f64> {
282 vec![10.0 * (x[1] - x[0] * x[0]), 1.0 - x[0]]
283 }
284
285 fn three(x: &[f64]) -> Vec<f64> {
287 vec![x[0] * x[0] + x[1] * x[1] + x[2] * x[2] - 14.0, x[0] + x[1] + x[2] - 6.0, x[0] * x[1] * x[2] - 6.0]
288 }
289
290 fn bratu(u: &[f64]) -> Vec<f64> {
292 let n = u.len();
293 let h = 1.0 / (n + 1) as f64;
294 (0..n)
295 .map(|i| {
296 let left = if i == 0 { 0.0 } else { u[i - 1] };
297 let right = if i + 1 == n { 0.0 } else { u[i + 1] };
298 left - 2.0 * u[i] + right + h * h * u[i].exp()
299 })
300 .collect()
301 }
302
303 #[test]
304 fn newton_converges_quadratically_with_and_without_a_jacobian() {
305 let jac = |x: &[f64]| vec![vec![-20.0 * x[0], 10.0], vec![-1.0, 0.0]];
306 let r = newton_system(rosenbrock, Some(jac), vec![-1.2, 1.0], SystemOptions::default()).unwrap();
307 assert!(r.converged && (r.x[0] - 1.0).abs() < 1e-12 && (r.x[1] - 1.0).abs() < 1e-12, "{r:?}");
308 assert!(r.iterations <= 20, "{}", r.iterations);
311 let r = newton_system(three, None::<NoJacobian>, vec![0.7, 2.4, 2.6], SystemOptions::default()).unwrap();
312 assert!(r.converged && r.x.iter().zip([1.0, 2.0, 3.0]).all(|(v, w)| (v - w).abs() < 1e-10), "{r:?}");
313 let r = newton_system(bratu, None::<NoJacobian>, vec![0.0; 40], SystemOptions::default()).unwrap();
314 assert!(r.converged && r.residual < 1e-12 && r.iterations < 10);
315 }
316
317 #[test]
318 fn broyden_uses_fewer_evaluations_on_a_large_system() {
319 let n = 40;
320 let newton = newton_system(bratu, None::<NoJacobian>, vec![0.0; n], SystemOptions::default()).unwrap();
321 let broyden = broyden_system(bratu, vec![0.0; n], SystemOptions::default()).unwrap();
322 assert!(broyden.converged && broyden.residual < 1e-12, "{broyden:?}");
323 assert!(newton.x.iter().zip(&broyden.x).all(|(a, b)| (a - b).abs() < 1e-9));
324 assert!(broyden.nfev < newton.nfev, "{} vs {}", broyden.nfev, newton.nfev);
325 let r = broyden_system(rosenbrock, vec![-1.2, 1.0], SystemOptions::default()).unwrap();
326 assert!(r.converged && (r.x[0] - 1.0).abs() < 1e-10, "{r:?}");
327 }
328
329 #[test]
330 fn line_search_rescues_a_far_start_and_validation() {
331 let r = newton_system(|x: &[f64]| vec![x[0].atan()], None::<NoJacobian>, vec![10.0], SystemOptions::default()).unwrap();
333 assert!(r.converged && r.x[0].abs() < 1e-12, "{r:?}");
334 assert!(newton_system(|x: &[f64]| vec![x[0]], None::<NoJacobian>, vec![], SystemOptions::default()).is_err());
335 assert!(broyden_system(|x: &[f64]| vec![x[0], 1.0], vec![1.0], SystemOptions::default()).is_err());
336 assert!(newton_system(|x: &[f64]| vec![x[0] - 1.0], Some(|_: &[f64]| vec![vec![1.0, 0.0]]), vec![0.0], SystemOptions::default()).is_err());
337 assert!(!newton_system(|x: &[f64]| vec![x[0] * x[0] + 1.0], None::<NoJacobian>, vec![0.5], SystemOptions::default()).unwrap().converged);
339 }
340}