use crate::buffer::take;
use crate::math::dot;
#[derive(Debug, Clone, Copy)]
pub(crate) struct Options {
pub(crate) max_iterations: usize,
pub(crate) gradient_tolerance: f64,
pub(crate) value_tolerance: f64,
}
impl Options {
pub(crate) const DEFAULT_MAX_ITERATIONS: usize = 200;
}
impl Default for Options {
fn default() -> Self {
Self {
max_iterations: Self::DEFAULT_MAX_ITERATIONS,
gradient_tolerance: 1e-7,
value_tolerance: 1e-13,
}
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Minimum {
pub(crate) iterations: usize,
pub(crate) converged: bool,
}
const STEP: f64 = 6.055_454_452_393_343e-6;
const ARMIJO: f64 = 1e-4;
const MAX_HALVINGS: usize = 50;
pub(crate) const fn scratch_len(n: usize) -> usize {
n * n + 8 * n
}
struct Buffers<'a> {
inverse_hessian: &'a mut [f64],
gradient: &'a mut [f64],
direction: &'a mut [f64],
candidate: &'a mut [f64],
next_gradient: &'a mut [f64],
s: &'a mut [f64],
y: &'a mut [f64],
hy: &'a mut [f64],
point: &'a mut [f64],
}
impl<'a> Buffers<'a> {
fn new(mut scratch: &'a mut [f64], n: usize) -> Self {
Self {
inverse_hessian: take(&mut scratch, n * n),
gradient: take(&mut scratch, n),
direction: take(&mut scratch, n),
candidate: take(&mut scratch, n),
next_gradient: take(&mut scratch, n),
s: take(&mut scratch, n),
y: take(&mut scratch, n),
hy: take(&mut scratch, n),
point: take(&mut scratch, n),
}
}
}
pub(crate) fn minimize(
mut f: impl FnMut(&[f64]) -> f64,
x: &mut [f64],
scratch: &mut [f64],
options: Options,
) -> Minimum {
let n = x.len();
let mut value = f(x);
if n == 0 || !value.is_finite() {
let converged = n == 0 && value.is_finite();
return Minimum {
iterations: 0,
converged,
};
}
let b = Buffers::new(scratch, n);
gradient_at(&mut f, x, value, b.point, b.gradient);
identity(b.inverse_hessian, n);
let mut fresh = true;
for iteration in 0..options.max_iterations {
if max_abs(b.gradient) <= options.gradient_tolerance {
return Minimum {
iterations: iteration,
converged: true,
};
}
descent_direction(b.inverse_hessian, b.gradient, b.direction);
if dot(b.gradient, b.direction) >= 0.0 {
identity(b.inverse_hessian, n);
fresh = true;
for (d, g) in b.direction.iter_mut().zip(b.gradient.iter()) {
*d = -g;
}
}
let Some(next_value) = line_search(&mut f, x, value, b.gradient, b.direction, b.candidate)
else {
if fresh {
return Minimum {
iterations: iteration,
converged: false,
};
}
identity(b.inverse_hessian, n);
fresh = true;
continue;
};
gradient_at(&mut f, b.candidate, next_value, b.point, b.next_gradient);
difference_into(b.s, b.candidate, x);
difference_into(b.y, b.next_gradient, b.gradient);
let improvement = value - next_value;
if fresh {
scale_initial(b.inverse_hessian, n, b.s, b.y);
}
fresh = !bfgs_update(b.inverse_hessian, b.s, b.y, b.hy) && fresh;
x.copy_from_slice(b.candidate);
value = next_value;
b.gradient.copy_from_slice(b.next_gradient);
if improvement <= options.value_tolerance * value.abs().max(1.0) {
return Minimum {
iterations: iteration + 1,
converged: true,
};
}
}
let converged = max_abs(b.gradient) <= options.gradient_tolerance;
Minimum {
iterations: options.max_iterations,
converged,
}
}
fn gradient_at(
f: &mut impl FnMut(&[f64]) -> f64,
x: &[f64],
value: f64,
point: &mut [f64],
gradient: &mut [f64],
) {
point.copy_from_slice(x);
for (i, g) in gradient.iter_mut().enumerate() {
let h = STEP * x[i].abs().max(1.0);
point[i] = x[i] + h;
let up = f(point);
point[i] = x[i] - h;
let down = f(point);
point[i] = x[i];
*g = match (up.is_finite(), down.is_finite()) {
(true, true) => (up - down) / (2.0 * h),
(true, false) => (up - value) / h,
(false, true) => (value - down) / h,
(false, false) => 0.0,
};
}
}
fn line_search(
f: &mut impl FnMut(&[f64]) -> f64,
x: &[f64],
value: f64,
gradient: &[f64],
direction: &[f64],
candidate: &mut [f64],
) -> Option<f64> {
let slope = dot(gradient, direction);
let mut step = 1.0;
for _ in 0..MAX_HALVINGS {
for ((c, a), d) in candidate.iter_mut().zip(x).zip(direction) {
*c = a + step * d;
}
let candidate_value = f(candidate);
if candidate_value.is_finite() && candidate_value <= value + ARMIJO * step * slope {
return Some(candidate_value);
}
step *= 0.5;
}
None
}
fn descent_direction(inverse_hessian: &[f64], gradient: &[f64], direction: &mut [f64]) {
let n = gradient.len();
for (d, row) in direction.iter_mut().zip(inverse_hessian.chunks_exact(n)) {
*d = -dot(row, gradient);
}
}
fn difference_into(out: &mut [f64], a: &[f64], b: &[f64]) {
for ((o, a), b) in out.iter_mut().zip(a).zip(b) {
*o = a - b;
}
}
fn scale_initial(inverse_hessian: &mut [f64], n: usize, s: &[f64], y: &[f64]) {
let (sy, yy) = (dot(s, y), dot(y, y));
if sy > 0.0 && yy > 0.0 {
for (i, row) in inverse_hessian.chunks_exact_mut(n).enumerate() {
row.fill(0.0);
row[i] = sy / yy;
}
}
}
fn bfgs_update(inverse_hessian: &mut [f64], s: &[f64], y: &[f64], hy: &mut [f64]) -> bool {
let sy = dot(s, y);
if sy <= 1e-12 * crate::math::sqrt(dot(s, s) * dot(y, y)) {
return false;
}
let n = s.len();
let rho = 1.0 / sy;
for (h, row) in hy.iter_mut().zip(inverse_hessian.chunks_exact(n)) {
*h = dot(row, y);
}
let yhy = dot(y, hy);
for (i, row) in inverse_hessian.chunks_exact_mut(n).enumerate() {
for (j, h) in row.iter_mut().enumerate() {
*h += -rho * (hy[i] * s[j] + s[i] * hy[j]) + (rho * rho * yhy + rho) * s[i] * s[j];
}
}
true
}
fn identity(matrix: &mut [f64], n: usize) {
matrix.fill(0.0);
for i in 0..n {
matrix[i * n + i] = 1.0;
}
}
fn max_abs(v: &[f64]) -> f64 {
v.iter().fold(0.0, |m, x| m.max(x.abs()))
}
#[cfg(test)]
mod tests {
use super::*;
use std::vec;
fn run(f: impl FnMut(&[f64]) -> f64, x0: &[f64]) -> (std::vec::Vec<f64>, Minimum) {
let mut x = x0.to_vec();
let mut scratch = vec![0.0; scratch_len(x.len())];
let minimum = minimize(f, &mut x, &mut scratch, Options::default());
(x, minimum)
}
#[test]
fn minimises_rosenbrock() {
let rosenbrock = |x: &[f64]| (1.0 - x[0]).powi(2) + 100.0 * (x[1] - x[0] * x[0]).powi(2);
let (x, minimum) = run(rosenbrock, &[-1.2, 1.0]);
assert!(minimum.converged, "{minimum:?}");
assert!(
(x[0] - 1.0).abs() < 1e-5 && (x[1] - 1.0).abs() < 1e-5,
"{x:?}"
);
}
#[test]
fn steps_back_from_infinite_regions() {
let f = |x: &[f64]| {
if x[0] > 3.0 {
f64::INFINITY
} else {
(x[0] - 2.0).powi(2)
}
};
let (x, _) = run(f, &[0.0]);
assert!((x[0] - 2.0).abs() < 1e-6, "{x:?}");
}
#[test]
fn no_parameters() {
let (x, minimum) = run(|_| 4.0, &[]);
assert!(minimum.converged);
assert!(x.is_empty());
}
}