use crate::fitness::{FitnessEvaluator, MinOrMax};
use crate::objectives::SquareAndSum;
use crate::params::{CmaesParams, CmaesParamsValidator};
use crate::state::{CmaesState, CmaesStateLogic};
use crate::strategy::{CmaesAlgo, CmaesAlgoOptimizer};
use anyhow::Result;
use std::env::var;
#[allow(unused_imports)]
use std::io::{self, Write};
use std::time::Instant;
pub fn example() -> Result<()> {
let verbose = var("VERBOSE").unwrap_or("No".to_string());
let start = Instant::now();
let obj_func = SquareAndSum {
obj_dim: 50,
dir: MinOrMax::Min,
};
let params = CmaesParams::new()?
.set_popsize(50)?
.set_xstart(vec![0.5; obj_func.evaluator_dim()?])?
.set_sigma(0.5)?;
let cmaes = CmaesAlgo::new(params)?;
let mut state = CmaesState::init_state(&cmaes.params)?;
let mut step = 0;
loop {
let mut pop = cmaes.ask(&mut state)?;
let mut fitness = obj_func.evaluate(&pop)?;
state = cmaes.tell(state, &mut pop, &mut fitness)?;
if let Ok(true) = cmaes.is_done(&state, step) {
break;
}
if verbose != "No" {
print!("{:+.5?} ", &state.best_y_fit.row(0)[0]);
io::stdout().flush().unwrap()
}
step += 1;
}
if verbose != "No" {
println!(
"Step {} | Fitness: {:+.5?} | Duration p/step: {:.5} secs",
step,
&state.best_y_fit.row(0)[0],
(start.elapsed().as_micros() as f32) / 1000000.0 / (step as f32)
);
println!("{:+.5?}", &state.best_y);
}
Ok(())
}