extern crate ndarray;
use argmin::core::{CostFunction, Executor};
use argmin::solver::neldermead::NelderMead;
struct Cost1d<F>
where
F: Fn(f64) -> f64,
{
func: F,
min: f64,
max: f64,
}
impl<F> CostFunction for Cost1d<F>
where
F: Fn(f64) -> f64,
{
type Param = f64;
type Output = f64;
fn cost(&self, x: &Self::Param) -> Result<Self::Output, argmin::core::Error> {
if x > &self.max || x < &self.min {
Ok(f64::INFINITY)
} else {
let f = &self.func;
Ok(f(*x))
}
}
}
pub fn nelder_mead_1d<F>(
func: F,
guess: (f64, f64),
max_iter: u64,
min: f64,
max: f64,
tolerance: f64,
) -> f64
where
F: Fn(f64) -> f64,
{
let cost = Cost1d { func, min, max };
let solver = NelderMead::new(vec![guess.0, guess.1])
.with_sd_tolerance(tolerance)
.unwrap();
let res = Executor::new(cost, solver)
.configure(|state| state.max_iters(max_iter))
.run()
.unwrap();
use argmin::core::State;
*res.state().get_best_param().unwrap()
}