///|
/// Algorithm for unconstrained minimization.
#derive(Debug, Eq)
pub(all) enum Algorithm {
SteepestDescent
NormalizedGradient
FletcherReeves
Bfgs
Lbfgs(Int32)
Dfp
Sr1
Broyden(Double)
}
///|
fn bfgs_update(
inverse : Array[Array[Double]],
x : ArrayView[Double],
gradient : ArrayView[Double],
next_x : ArrayView[Double],
next_gradient : ArrayView[Double],
) -> Array[Array[Double]] {
let s = x.mapi((i, value) => next_x[i] - value)
let y = gradient.mapi((i, value) => next_gradient[i] - value)
let ys = dot(y[:], s[:])
let scale = gradient_norm(y[:]) * gradient_norm(s[:])
if !ys.is_finite() || !scale.is_finite() || ys <= 1.0e-10 * scale || ys <= 0.0 {
return identity_matrix(x.length())
}
let hy = matrix_vector(inverse, y[:])
let yhy = dot(y[:], hy[:])
let coefficient = (1.0 + yhy / ys) / ys
let updated = inverse.mapi((i, row) => {
row.mapi((j, element) => {
element + coefficient * s[i] * s[j] - (s[i] * hy[j] + hy[i] * s[j]) / ys
})
})
if !yhy.is_finite() ||
updated.any(row => row.any(value => !value.is_finite())) {
identity_matrix(x.length())
} else {
updated
}
}