use std::time::Instant;
use crate::{
fitness::{allow_objective_func, FitnessEvaluator, SquareAndSum},
CmaesAlgo, CmaesAlgoOptimizer, CmaesParams, CmaesState, CmaesStateLogic,
};
use anyhow::Result;
pub fn example() -> Result<()> {
let start = Instant::now();
let obj = allow_objective_func(SquareAndSum)?;
let params = CmaesParams {
popsize: 50,
xstart: vec![0.0; 50],
sigma: 0.75,
tol: Some(0.0001),
obj_value: Some(0.0), zs: Some(0.01),
};
let cmaes = CmaesAlgo::new(params)?;
let mut state = CmaesState::init_state(&cmaes.validated_params)?;
let mut step = 0;
loop {
let mut pop = cmaes.ask(&mut state)?;
let mut fitness = obj.evaluate(&pop)?;
state = cmaes.tell(state, &mut pop, &mut fitness)?;
let obj_value = cmaes.validated_params.obj_value.as_ref();
let tol = cmaes.validated_params.tol.as_ref();
if let (Some(obj_value), Some(tol)) = (obj_value, tol) {
let curr = state.best_y.first().unwrap();
if (curr - obj_value).abs() < *tol {
break;
}
}
step += 1;
}
println!(
"Step {} | Fitness: {:+.4?} | Duration p/step: {:.4} secs",
step,
&state.best_y.first().unwrap(),
(start.elapsed().as_micros() as f32) / 1000000.0 / (step as f32)
);
Ok(())
}