#![allow(clippy::needless_range_loop)]
#![allow(dead_code)]
pub(crate) mod bigden;
pub(crate) mod biglag;
pub(crate) mod driver;
pub(crate) mod init;
pub(crate) mod trsapp;
#[cfg(test)]
mod parity;
use crate::core::inner::InitialState;
use crate::core::math::{Scalar, VectorLen};
use crate::core::problem::{CostFunction, Problem};
use crate::core::solver::Solver;
use crate::core::state::NewuoaState;
use crate::core::termination::TerminationReason;
use driver::{NewuoaWork, Transition};
pub struct Newuoa<F = f64> {
radius_tolerance: Option<F>,
rho_beg: F,
rho_end: F,
npt: Option<usize>,
work: Option<NewuoaWork<F>>,
}
impl<F: Scalar> Newuoa<F> {
pub fn with_absolute_radius_tolerance(
mut self,
value: impl Into<Option<F>>,
) -> Self {
self.radius_tolerance =
crate::core::convergence::optional_tolerance(value);
self
}
pub fn new() -> Self {
Self {
rho_beg: F::from_f64(1.0).expect("1.0 representable"),
radius_tolerance: None,
rho_end: F::from_f64(1e-6).expect("1e-6 representable"),
npt: None,
work: None,
}
}
#[deprecated(
note = "use `with_initial_radius`; removal scheduled for Basin 2.0"
)]
pub fn with_rho_beg(self, rho_beg: F) -> Self {
self.with_initial_radius(rho_beg)
}
pub fn with_initial_radius(mut self, rho_beg: F) -> Self {
self.rho_beg = rho_beg;
self
}
#[deprecated(
note = "use `with_final_radius`; removal scheduled for Basin 2.0"
)]
pub fn with_rho_end(self, rho_end: F) -> Self {
self.with_final_radius(rho_end)
}
pub fn with_final_radius(mut self, rho_end: F) -> Self {
self.rho_end = rho_end;
self
}
pub fn with_npt(mut self, npt: usize) -> Self {
self.npt = Some(npt);
self
}
}
impl<F: Scalar> Default for Newuoa<F> {
fn default() -> Self {
Self::new()
}
}
fn fill_from<V, F>(template: &V, slice: &[F]) -> V
where
V: Clone + std::ops::IndexMut<usize, Output = F>,
F: Copy,
{
let mut v = template.clone();
for (i, &x) in slice.iter().enumerate() {
v[i] = x;
}
v
}
impl<V, F> InitialState<V> for Newuoa<F>
where
F: Scalar,
V: Clone,
{
type State = NewuoaState<V, F>;
fn seed(&self, x: &V) -> Self::State {
NewuoaState::new(x.clone())
}
}
impl<P, V, F> Solver<P, NewuoaState<V, F>> for Newuoa<F>
where
F: Scalar,
P: CostFunction<Param = V, Output = F>,
V: Clone
+ VectorLen
+ std::ops::Index<usize, Output = F>
+ std::ops::IndexMut<usize, Output = F>,
{
type Error = P::Error;
fn init(
&mut self,
problem: &mut Problem<P>,
mut state: NewuoaState<V, F>,
) -> Result<NewuoaState<V, F>, Self::Error> {
let n = state.param.vec_len();
assert!(n >= 1, "Newuoa requires a non-empty start point");
let npt = self.npt.unwrap_or(2 * n + 1);
let x0: Vec<F> = (0..n).map(|i| state.param[i]).collect();
let template = state.param.clone();
let (work, best_x, best_f) = {
let mut eval = |slice: &[F]| -> Result<F, P::Error> {
problem.cost(&fill_from(&template, slice))
};
NewuoaWork::try_init(
x0,
self.rho_beg,
self.rho_end,
npt,
&mut eval,
)?
};
state.param = fill_from(&template, &best_x);
state.cost = Some(best_f);
state.rho = work.rho();
self.work = Some(work);
Ok(state)
}
fn next_iter(
&mut self,
problem: &mut Problem<P>,
mut state: NewuoaState<V, F>,
) -> Result<(NewuoaState<V, F>, Option<TerminationReason>), Self::Error>
{
let template = state.param.clone();
let work = self
.work
.as_mut()
.expect("Newuoa::init must run before next_iter");
let out = {
let mut eval = |slice: &[F]| -> Result<F, P::Error> {
problem.cost(&fill_from(&template, slice))
};
work.step(&mut eval)?
};
state.rho = work.rho();
let mut best_f = state.cost.expect("Newuoa::init seeds the cost");
for (xabs, f_new) in &out.evaluated {
if *f_new < best_f {
best_f = *f_new;
state.param = fill_from(&template, xabs);
state.cost = Some(best_f);
}
}
let reason = match out.transition {
Transition::Converged => Some(TerminationReason::SolverConverged),
Transition::Continue | Transition::RhoReduced => None,
};
Ok((state, reason))
}
fn terminate(
&self,
state: &NewuoaState<V, F>,
) -> Option<TerminationReason> {
let tolerance = self.radius_tolerance?;
let metric = crate::RhoState::rho(state);
(metric.is_finite() && metric <= tolerance)
.then_some(TerminationReason::RhoTolerance)
}
}