#![allow(clippy::needless_range_loop)]
pub(crate) mod driver;
pub(crate) mod geometry;
pub(crate) mod init;
pub(crate) mod rescue;
pub(crate) mod trsbox;
#[cfg(test)]
mod parity;
use std::marker::PhantomData;
use crate::core::constraint::evaluation::BoxProblem;
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::{PointState, State};
use crate::core::termination::Termination;
use driver::{BobyqaWork, Transition};
pub struct Bounded;
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "serde",
serde(bound(
serialize = "F: serde::Serialize",
deserialize = "F: serde::Deserialize<'de>"
))
)]
pub struct Bobyqa<Mode = Bounded, F: Scalar = f64> {
radius_tolerance: Option<F>,
rho_beg: F,
rho_end: F,
npt: Option<usize>,
work: Option<BobyqaWork<F>>,
_mode: PhantomData<fn() -> Mode>,
}
impl<F: Scalar> Bobyqa<Bounded, F> {
pub fn rho(&self) -> Option<F> {
self.work.as_ref().map(|work| work.rho())
}
#[allow(clippy::type_complexity)]
pub fn geometry_diagnostics(
&self,
) -> Option<(F, F, Vec<Vec<F>>, Vec<F>, Vec<F>)> {
self.work.as_ref().map(|work| work.geometry_diagnostics())
}
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,
_mode: PhantomData,
}
}
pub fn with_initial_radius(mut self, rho_beg: F) -> Self {
self.rho_beg = rho_beg;
self
}
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 Bobyqa<Bounded, 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
}
fn to_vec<V, F>(v: &V, n: usize) -> Vec<F>
where
V: std::ops::Index<usize, Output = F>,
F: Copy,
{
(0..n).map(|i| v[i]).collect()
}
impl<V, F> InitialState<V> for Bobyqa<Bounded, F>
where
F: Scalar,
V: Clone,
{
type State = PointState<V, F>;
fn seed(&self, x: &V) -> Self::State {
PointState::new(x.clone())
}
}
impl<P, V, F> Solver<P, PointState<V, F>> for Bobyqa<Bounded, F>
where
F: Scalar,
P: CostFunction<Param = V, Output = F> + BoxProblem<Param = V>,
V: Clone
+ VectorLen
+ std::ops::Index<usize, Output = F>
+ std::ops::IndexMut<usize, Output = F>,
V: crate::VectorLen + std::ops::Index<usize, Output = F>,
{
type Error = crate::ConstraintSolveError<P::Error>;
fn init(
&mut self,
problem: &mut Problem<P>,
mut state: PointState<V, F>,
) -> Result<PointState<V, F>, Self::Error> {
crate::core::constraint::evaluation::validate_box_problem(
problem.inner(),
Some(state.param().vec_len()),
false,
)
.map_err(crate::core::constraint::evaluation::invalid)?;
state.reset();
self.work = None;
let n = state.param().vec_len();
assert!(n >= 1, "Bobyqa requires a non-empty start point");
let npt = self.npt.unwrap_or(2 * n + 1);
let x0 = to_vec(state.param(), n);
let lower = to_vec(problem.inner().lower(), n);
let upper = to_vec(problem.inner().upper(), n);
let template = state.param().clone();
let (work, best_x, best_f) = {
let mut eval = |slice: &[F]| -> Result<
F,
crate::ConstraintSolveError<P::Error>,
> {
Ok(problem.cost(&fill_from(&template, slice))?)
};
BobyqaWork::try_init(
x0,
&lower,
&upper,
self.rho_beg,
self.rho_end,
npt,
&mut eval,
)?
};
state.replace(fill_from(&template, &best_x), best_f);
self.work = Some(work);
Ok(state)
}
fn next_iter(
&mut self,
problem: &mut Problem<P>,
mut state: PointState<V, F>,
) -> Result<crate::SolverStep<PointState<V, F>>, Self::Error> {
let template = state.param().clone();
let work = self
.work
.as_mut()
.expect("Bobyqa::init must run before next_iter");
let out = {
let mut eval = |slice: &[F]| -> Result<
F,
crate::ConstraintSolveError<P::Error>,
> {
Ok(problem.cost(&fill_from(&template, slice))?)
};
work.step(&mut eval)?
};
let mut best_f = state.cost();
for (xabs, f_new) in &out.evaluated {
if *f_new < best_f {
best_f = *f_new;
state.replace(fill_from(&template, xabs), best_f);
}
}
let reason = match out.transition {
Transition::Converged => Some(Termination::custom(
"bobyqa.final_radius",
"The algorithm completed its final trust-radius stage; this does not certify feasibility or global optimality.",
vec![crate::Measurement {
name: "final_radius".into(),
value: self.rho_end,
}],
)),
Transition::Continue | Transition::RhoReduced => None,
};
Ok(crate::SolverStep::from((state, reason)))
}
fn terminate(&self, _state: &PointState<V, F>) -> Option<Termination<F>> {
let tolerance = self.radius_tolerance?;
let metric = self.rho()?;
(metric.is_finite() && metric <= tolerance).then(|| {
Termination::upper_bound(
crate::ConvergenceTest::Radius,
metric,
tolerance,
tolerance,
None,
)
})
}
}
#[cfg(test)]
mod tests {
use crate::core::problem::CostFunction;
use crate::{Bobyqa, Executor, PointState};
struct Quad {
lower: Vec<f64>,
upper: Vec<f64>,
}
impl crate::Constraints for Quad {
type Set = crate::ConstraintSet<crate::BoxBounds<Vec<f64>>>;
fn constraints(
&self,
) -> <Self::Set as crate::ConstraintDescription>::Borrowed<'_> {
crate::ConstraintSet::new().with_bounds(crate::BoxBounds::new(
Some(&self.lower),
Some(&self.upper),
))
}
}
impl CostFunction for Quad {
type Param = Vec<f64>;
type Output = f64;
type Error = std::convert::Infallible;
fn cost(&self, x: &Vec<f64>) -> Result<f64, std::convert::Infallible> {
Ok((x[0] - 1.0).powi(2) + 2.0 * (x[1] + 2.0).powi(2))
}
}
#[test]
fn converges_interior_minimum() {
let problem = Quad {
lower: vec![-5.0, -5.0],
upper: vec![5.0, 5.0],
};
let result = Executor::new(
problem,
Bobyqa::new()
.with_initial_radius(0.5)
.with_final_radius(1e-8),
PointState::new(vec![0.0, 0.0]),
)
.max_cost_evals(500)
.run()
.unwrap();
let x = result.best_param();
assert!((x[0] - 1.0).abs() < 1e-5, "x0 = {}", x[0]);
assert!((x[1] + 2.0).abs() < 1e-5, "x1 = {}", x[1]);
assert!(result.best_cost() < 1e-9, "cost = {}", result.best_cost());
}
#[test]
fn converges_with_unbounded_sides() {
for (lower, upper) in [
(vec![0.0, -3.0], vec![f64::INFINITY; 2]),
(vec![f64::NEG_INFINITY; 2], vec![2.0, 0.0]),
(vec![0.0, f64::NEG_INFINITY], vec![f64::INFINITY, 0.0]),
(vec![f64::NEG_INFINITY; 2], vec![f64::INFINITY; 2]),
] {
let result = Executor::from_start(
Quad { lower, upper },
Bobyqa::new()
.with_initial_radius(0.5)
.with_final_radius(1e-8),
vec![0.0, 0.0],
)
.max_cost_evals(500)
.run()
.unwrap();
assert!((result.best_param()[0] - 1.0).abs() < 1e-5);
assert!((result.best_param()[1] + 2.0).abs() < 1e-5);
assert!(result.best_cost() < 1e-9);
}
}
#[test]
fn narrow_box_revises_rho_beg() {
let problem = Quad {
lower: vec![0.9, -2.2],
upper: vec![1.1, -1.8],
};
let result = Executor::new(
problem,
Bobyqa::new(),
PointState::new(vec![1.0, -2.0]),
)
.max_cost_evals(500)
.run()
.unwrap();
let x = result.best_param();
assert!((x[0] - 1.0).abs() < 1e-3, "x0 = {}", x[0]);
assert!((x[1] + 2.0).abs() < 1e-3, "x1 = {}", x[1]);
}
#[test]
fn infeasible_start_converges() {
let problem = Quad {
lower: vec![-3.0, -3.0],
upper: vec![3.0, 3.0],
};
let result = Executor::new(
problem,
Bobyqa::new()
.with_initial_radius(0.5)
.with_final_radius(1e-8),
PointState::new(vec![100.0, -100.0]),
)
.max_cost_evals(500)
.run()
.unwrap();
let x = result.best_param();
assert!((x[0] - 1.0).abs() < 1e-5, "x0 = {}", x[0]);
assert!((x[1] + 2.0).abs() < 1e-5, "x1 = {}", x[1]);
}
#[test]
fn converges_to_active_bound() {
struct Bowl {
lower: Vec<f64>,
upper: Vec<f64>,
}
impl crate::Constraints for Bowl {
type Set = crate::ConstraintSet<crate::BoxBounds<Vec<f64>>>;
fn constraints(
&self,
) -> <Self::Set as crate::ConstraintDescription>::Borrowed<'_>
{
crate::ConstraintSet::new().with_bounds(crate::BoxBounds::new(
Some(&self.lower),
Some(&self.upper),
))
}
}
impl CostFunction for Bowl {
type Param = Vec<f64>;
type Output = f64;
type Error = std::convert::Infallible;
fn cost(
&self,
x: &Vec<f64>,
) -> Result<f64, std::convert::Infallible> {
Ok((x[0] - 5.0).powi(2) + (x[1] - 5.0).powi(2))
}
}
let problem = Bowl {
lower: vec![-2.0, -2.0],
upper: vec![2.0, 2.0],
};
let result = Executor::new(
problem,
Bobyqa::new()
.with_initial_radius(0.5)
.with_final_radius(1e-8),
PointState::new(vec![0.0, 0.0]),
)
.max_cost_evals(500)
.run()
.unwrap();
let x = result.best_param();
assert!((x[0] - 2.0).abs() < 1e-5, "x0 = {}", x[0]);
assert!((x[1] - 2.0).abs() < 1e-5, "x1 = {}", x[1]);
}
#[test]
fn converges_rosenbrock_box() {
struct Rosen {
lower: Vec<f64>,
upper: Vec<f64>,
}
impl crate::Constraints for Rosen {
type Set = crate::ConstraintSet<crate::BoxBounds<Vec<f64>>>;
fn constraints(
&self,
) -> <Self::Set as crate::ConstraintDescription>::Borrowed<'_>
{
crate::ConstraintSet::new().with_bounds(crate::BoxBounds::new(
Some(&self.lower),
Some(&self.upper),
))
}
}
impl CostFunction for Rosen {
type Param = Vec<f64>;
type Output = f64;
type Error = std::convert::Infallible;
fn cost(
&self,
x: &Vec<f64>,
) -> Result<f64, std::convert::Infallible> {
Ok(100.0 * (x[1] - x[0] * x[0]).powi(2) + (1.0 - x[0]).powi(2))
}
}
let problem = Rosen {
lower: vec![-5.0, -5.0],
upper: vec![5.0, 5.0],
};
let result = Executor::new(
problem,
Bobyqa::new()
.with_initial_radius(0.5)
.with_final_radius(1e-6),
PointState::new(vec![-1.2, 1.0]),
)
.max_cost_evals(2000)
.run()
.unwrap();
let x = result.best_param();
assert!((x[0] - 1.0).abs() < 1e-3, "x0 = {}", x[0]);
assert!((x[1] - 1.0).abs() < 1e-3, "x1 = {}", x[1]);
assert!(result.best_cost() < 1e-6, "cost = {}", result.best_cost());
}
}