use serde::{Deserialize, Serialize};
use crate::config::Config;
use crate::error::Result;
use crate::objective::CostModel;
use crate::optim::{Exit, IterationReport, ProgressSink, RunControl, optimizer};
use crate::setup::{Problem, resolve_seed};
use crate::time::Instant;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RunResult {
pub seed: u64,
pub algorithm: String,
pub solution: Vec<f64>,
pub fidelity: f64,
pub penalty: f64,
pub fidelity_history: Vec<f64>,
pub iterations: usize,
pub evaluations: usize,
pub exit: Exit,
pub elapsed_s: f64,
pub notices: Vec<String>,
}
pub fn available_threads() -> usize {
crate::parallel::available_threads()
}
struct History<'a> {
inner: &'a mut dyn ProgressSink,
fidelities: Vec<f64>,
}
impl ProgressSink for History<'_> {
fn on_iteration(&mut self, r: &IterationReport) {
self.fidelities.push(r.fidelity);
self.inner.on_iteration(r);
}
fn should_cancel(&self) -> bool {
self.inner.should_cancel()
}
}
pub fn run(cfg: &Config, sink: &mut dyn ProgressSink) -> Result<RunResult> {
let started = Instant::now();
let seed = resolve_seed(cfg);
let problem = Problem::build_with_seed(cfg, seed)?;
let x0 = problem.x0.clone();
let mut model = CostModel::new(problem);
if let Some(threads) = cfg.cpu_cores {
model = model.with_threads(threads)?;
}
let opt = optimizer(&cfg.optimization.algorithm)?;
let mut notices = Vec::new();
if cfg.compute_resource.as_deref() == Some("gpu") {
notices.push("GPU is not supported; running on CPU.".to_string());
}
let mut history = History {
inner: sink,
fidelities: Vec::new(),
};
let mut ctl = RunControl {
max_iter: cfg.optimization.max_iter,
target_fidelity: cfg.optimization.targ_fid,
sink: &mut history,
};
let result = opt.minimize(&model, &x0, &mut ctl)?;
Ok(RunResult {
seed,
algorithm: opt.name().to_string(),
solution: result.x,
fidelity: result.eval.fidelity,
penalty: result.eval.penalty,
fidelity_history: history.fidelities,
iterations: result.iterations,
evaluations: result.evaluations,
exit: result.exit,
elapsed_s: started.elapsed().as_secs_f64(),
notices,
})
}