use crate::core::math::{
GramMatrix, LinearSolveSpd, MatTransposeVec, NegInPlace, NormInfinity, NormSquared, ScaledAdd,
};
use crate::core::problem::{Jacobian, Residual};
use crate::core::solver::Solver;
use crate::core::state::BasicState;
use crate::core::termination::TerminationReason;
pub struct GaussNewton<V, M> {
tol_grad: f64,
r_cache: Option<V>,
j_cache: Option<M>,
}
impl<V, M> Default for GaussNewton<V, M> {
fn default() -> Self {
Self::new()
}
}
impl<V, M> GaussNewton<V, M> {
pub fn new() -> Self {
Self {
tol_grad: 1e-8,
r_cache: None,
j_cache: None,
}
}
pub fn tol_grad(mut self, tol: f64) -> Self {
assert!(tol >= 0.0, "tol_grad must be ≥ 0");
self.tol_grad = tol;
self
}
}
impl<P, V, M> Solver<P, BasicState<V>> for GaussNewton<V, M>
where
P: Residual<Param = V, Output = V> + Jacobian<Param = V, Output = M>,
V: ScaledAdd<f64> + NormSquared + NormInfinity + NegInPlace + Clone,
M: GramMatrix + MatTransposeVec<V> + LinearSolveSpd<V>,
{
fn init(&mut self, problem: &P, mut state: BasicState<V>) -> BasicState<V> {
let r = problem.residual(&state.param);
let j = problem.jacobian(&state.param);
state.cost = Some(0.5 * r.norm_squared());
state.cost_evals += 1;
state.gradient_evals += 1;
self.r_cache = Some(r);
self.j_cache = Some(j);
state
}
fn next_iter(
&mut self,
problem: &P,
mut state: BasicState<V>,
) -> (BasicState<V>, Option<TerminationReason>) {
let r = match self.r_cache.take() {
Some(r) => r,
None => {
state.cost_evals += 1;
problem.residual(&state.param)
}
};
let j = match self.j_cache.take() {
Some(j) => j,
None => {
state.gradient_evals += 1;
problem.jacobian(&state.param)
}
};
let g = j.mat_transpose_vec(&r);
if self.tol_grad > 0.0 && g.norm_infinity() <= self.tol_grad {
self.r_cache = Some(r);
self.j_cache = Some(j);
return (state, Some(TerminationReason::SolverConverged));
}
let gram = j.gram();
let mut neg_g = g;
neg_g.neg_in_place();
let delta = match gram.solve_spd(&neg_g) {
Ok(d) => d,
Err(_) => {
self.r_cache = Some(r);
self.j_cache = Some(j);
return (state, Some(TerminationReason::SolverFailed));
}
};
state.param.scaled_add(1.0, &delta);
let r_new = problem.residual(&state.param);
state.cost = Some(0.5 * r_new.norm_squared());
state.cost_evals += 1;
self.r_cache = Some(r_new);
self.j_cache = None;
(state, None)
}
}