use crate::core::constraint::BoxConstraints;
use crate::core::inner::InitialState;
use crate::core::least_squares::evaluation::{BoundedEvaluation, NllsStep};
use crate::core::math::{
AddDiagonalVectorInPlace, BoxAffineScaling, Dot, GramMatrix,
LinearSolveSpd, MatTransposeVec, MaxDiagonal, NegInPlace, NormSquared,
Scalar, ScaledAdd,
};
use crate::core::problem::{Jacobian, Problem, Residual};
use crate::core::solver::Solver;
use crate::core::state::NllsState;
use crate::core::termination::TerminationReason;
use crate::{
LossFunction, RobustLeastSquares, ScaleRowsInPlace, VectorIndex, VectorLen,
};
pub struct Trf<V, M, F = f64> {
tol_grad: Option<F>,
tau: F,
rstep: F,
theta: F,
max_inner_attempts: u32,
mu: Option<F>,
nu: F,
rejected_step: bool,
r_cache: Option<V>,
j_cache: Option<M>,
model_r_cache: Option<V>,
failed: bool,
}
impl<V, M, F: Scalar> Default for Trf<V, M, F> {
fn default() -> Self {
Self {
tol_grad: Some(F::from_f64(1e-8).unwrap()),
tau: F::from_f64(1e-3).unwrap(),
rstep: F::from_f64(1e-10).unwrap(),
theta: F::from_f64(0.99995).unwrap(),
max_inner_attempts: 50,
mu: None,
nu: F::from_f64(2.0).unwrap(),
rejected_step: false,
r_cache: None,
j_cache: None,
model_r_cache: None,
failed: false,
}
}
}
impl<V, M> Trf<V, M> {
pub fn new() -> Self {
Self::default()
}
}
impl<V, M, F: Scalar> Trf<V, M, F> {
#[deprecated(
note = "use `with_absolute_scaled_gradient_tolerance`; removal scheduled for Basin 2.0"
)]
pub fn with_tol_grad(mut self, tol: F) -> Self {
assert!(tol >= F::zero(), "tol_grad must be ≥ 0");
self.tol_grad = (tol > F::zero()).then_some(tol);
self
}
pub fn with_absolute_scaled_gradient_tolerance(
mut self,
value: impl Into<Option<F>>,
) -> Self {
self.tol_grad = crate::core::convergence::optional_tolerance(value);
self
}
pub fn with_tau(mut self, tau: F) -> Self {
assert!(tau > F::zero(), "tau must be > 0");
self.tau = tau;
self
}
pub fn with_rstep(mut self, rstep: F) -> Self {
assert!(rstep > F::zero(), "rstep must be > 0");
self.rstep = rstep;
self
}
pub fn with_theta(mut self, theta: F) -> Self {
assert!(
theta > F::zero() && theta < F::one(),
"theta must be in (0, 1), got {:?}",
theta
);
self.theta = theta;
self
}
pub fn with_max_inner_attempts(mut self, n: u32) -> Self {
assert!(n > 0, "max_inner_attempts must be > 0");
self.max_inner_attempts = n;
self
}
}
impl<V, M, F> InitialState<V> for Trf<V, M, F>
where
F: Scalar,
V: Clone,
{
type State = NllsState<V, F>;
fn seed(&self, x: &V) -> Self::State {
NllsState::new(x.clone())
}
}
impl<P, V, M, F> Solver<P, NllsState<V, F>> for Trf<V, M, F>
where
F: Scalar,
P: Residual<Param = V, Output = V>
+ Jacobian<Jacobian = M>
+ BoxConstraints<Param = V>,
V: ScaledAdd<F>
+ NormSquared<F>
+ NegInPlace
+ Dot<F>
+ BoxAffineScaling<F>
+ Clone,
M: GramMatrix
+ MatTransposeVec<V>
+ LinearSolveSpd<V>
+ AddDiagonalVectorInPlace<V>
+ MaxDiagonal<F>
+ Clone,
{
type Error = <P as Residual>::Error;
fn should_check_iterate_change(&self) -> bool {
!self.rejected_step
}
fn init(
&mut self,
problem: &mut Problem<P>,
state: NllsState<V, F>,
) -> Result<NllsState<V, F>, Self::Error> {
self.init_evaluated(problem, state)
}
fn next_iter(
&mut self,
problem: &mut Problem<P>,
state: NllsState<V, F>,
) -> Result<(NllsState<V, F>, Option<TerminationReason>), Self::Error> {
self.next_evaluated(problem, state)
}
}
impl<P, L, V, M, F> Solver<RobustLeastSquares<P, L, F>, NllsState<V, F>>
for Trf<V, M, F>
where
F: Scalar,
P: Residual<Param = V, Output = V>
+ Jacobian<Jacobian = M>
+ BoxConstraints<Param = V>,
V: ScaledAdd<F>
+ NormSquared<F>
+ NegInPlace
+ Dot<F>
+ BoxAffineScaling<F>
+ Clone,
M: GramMatrix
+ MatTransposeVec<V>
+ LinearSolveSpd<V>
+ AddDiagonalVectorInPlace<V>
+ MaxDiagonal<F>
+ Clone,
L: LossFunction<F>,
V: VectorLen + VectorIndex<F>,
M: ScaleRowsInPlace<F>,
{
type Error = <P as Residual>::Error;
fn should_check_iterate_change(&self) -> bool {
!self.rejected_step
}
fn init(
&mut self,
problem: &mut Problem<RobustLeastSquares<P, L, F>>,
state: NllsState<V, F>,
) -> Result<NllsState<V, F>, Self::Error> {
self.init_evaluated(problem, state)
}
fn next_iter(
&mut self,
problem: &mut Problem<RobustLeastSquares<P, L, F>>,
state: NllsState<V, F>,
) -> Result<(NllsState<V, F>, Option<TerminationReason>), Self::Error> {
self.next_evaluated(problem, state)
}
}
impl<V, M, F: Scalar> Trf<V, M, F>
where
V: ScaledAdd<F>
+ NormSquared<F>
+ NegInPlace
+ Dot<F>
+ BoxAffineScaling<F>
+ Clone,
M: GramMatrix
+ MatTransposeVec<V>
+ LinearSolveSpd<V>
+ AddDiagonalVectorInPlace<V>
+ MaxDiagonal<F>
+ Clone,
{
fn init_evaluated<E: BoundedEvaluation<V, M, F>>(
&mut self,
problem: &mut E,
mut state: NllsState<V, F>,
) -> Result<NllsState<V, F>, E::Error> {
state.param.project_strictly_inside(
problem.lower(),
problem.upper(),
self.rstep,
);
self.failed = false;
self.rejected_step = false;
self.r_cache = None;
self.j_cache = None;
self.model_r_cache = None;
let (r, j) = problem.residual_and_jacobian(&state.param)?;
state.cost = Some(
problem.cost(&r, |r| F::from_f64(0.5).unwrap() * r.norm_squared()),
);
let Some((model_r, j)) = problem.model(&r, j) else {
self.failed = true;
return Ok(state);
};
let g = j.mat_transpose_vec(model_r.as_ref().unwrap_or(&r));
if !problem.valid_vector(&g) {
self.failed = true;
return Ok(state);
}
let mut d_sq = state.param.clone();
let mut c_diag = state.param.clone();
state.param.compute_cl_scaling(
&g,
problem.lower(),
problem.upper(),
&mut d_sq,
&mut c_diag,
);
let mut a = j.gram();
a.add_diagonal_vector_in_place(&c_diag);
let max_diag = a.max_diagonal().max(F::one());
self.mu = Some(self.tau * max_diag);
self.nu = F::from_f64(2.0).unwrap();
self.r_cache = Some(r);
self.j_cache = Some(j);
self.model_r_cache = model_r;
Ok(state)
}
fn next_evaluated<E: BoundedEvaluation<V, M, F>>(
&mut self,
problem: &mut E,
mut state: NllsState<V, F>,
) -> NllsStep<V, F, E::Error> {
if self.failed {
return Ok((state, Some(TerminationReason::SolverFailed)));
}
let r = match self.r_cache.take() {
Some(r) => r,
None => problem.residual(&state.param)?,
};
let (model_r, j) = match self.j_cache.take() {
Some(j) => (self.model_r_cache.take(), j),
None => {
let j = problem.jacobian(&state.param)?;
let Some(model) = problem.model(&r, j) else {
self.failed = true;
return Ok((state, Some(TerminationReason::SolverFailed)));
};
model
}
};
let g = j.mat_transpose_vec(model_r.as_ref().unwrap_or(&r));
if !problem.valid_vector(&g) {
self.failed = true;
return Ok((state, Some(TerminationReason::SolverFailed)));
}
let mut d_sq = state.param.clone();
let mut c_diag = state.param.clone();
state.param.compute_cl_scaling(
&g,
problem.lower(),
problem.upper(),
&mut d_sq,
&mut c_diag,
);
if self
.tol_grad
.is_some_and(|tol| g.cl_kkt_inf_norm(&d_sq) <= tol)
{
self.r_cache = Some(r);
self.j_cache = Some(j);
self.model_r_cache = model_r;
return Ok((state, Some(TerminationReason::SolverConverged)));
}
let mut neg_g = g.clone();
neg_g.neg_in_place();
let m = j.gram();
let mut mu = self
.mu
.expect("mu not set: Solver::init must run before next_iter");
let mut nu = self.nu;
let two = F::from_f64(2.0).unwrap();
let half = F::from_f64(0.5).unwrap();
let one_third = F::from_f64(1.0 / 3.0).unwrap();
let h;
let mut attempts: u32 = 0;
loop {
let mut a_damped = m.clone();
let mut damping_vec = c_diag.clone();
damping_vec.scaled_add(mu, &d_sq);
a_damped.add_diagonal_vector_in_place(&damping_vec);
match a_damped.solve_spd(&neg_g) {
Ok(step) => {
h = step;
break;
}
Err(_) => {
attempts += 1;
if attempts >= self.max_inner_attempts || !mu.is_finite() {
self.mu = Some(mu);
self.nu = nu;
self.r_cache = Some(r);
self.j_cache = Some(j);
self.model_r_cache = model_r;
return Ok((
state,
Some(TerminationReason::SolverFailed),
));
}
mu = mu * nu;
nu = nu * two;
}
}
}
let tau_max =
state
.param
.max_feasible_step(&h, problem.lower(), problem.upper());
let alpha = if tau_max >= F::one() {
F::one()
} else {
self.theta * tau_max
};
let mut x_trial = state.param.clone();
x_trial.scaled_add(alpha, &h);
let r_trial = problem.residual(&x_trial)?;
let f_trial = problem.cost(&r_trial, |r| half * r.norm_squared());
let prev_cost = state
.cost
.expect("cost not set: Solver::init must run before next_iter");
let h_t_g = h.dot(&g);
let dh_norm_sq = h.weighted_norm_squared(&d_sq);
let predicted = -alpha * (F::one() - half * alpha) * h_t_g
+ half * alpha * alpha * mu * dh_norm_sq;
let half_s_t_c_s =
half * alpha * alpha * h.weighted_norm_squared(&c_diag);
let actual = prev_cost - f_trial - half_s_t_c_s;
let rho = if predicted > F::zero() {
actual / predicted
} else {
F::zero()
};
if rho > F::zero() {
self.rejected_step = false;
state.param = x_trial;
state.cost = Some(f_trial);
let factor = F::one() - (two * rho - F::one()).powi(3);
mu = mu * factor.max(one_third);
nu = two;
self.r_cache = Some(r_trial);
self.j_cache = None;
} else {
self.rejected_step = true;
mu = mu * nu;
nu = nu * two;
self.r_cache = Some(r);
self.j_cache = Some(j);
self.model_r_cache = model_r;
}
self.mu = Some(mu);
self.nu = nu;
Ok((state, None))
}
}