1use serde::{Deserialize, Serialize};
4
5use crate::config::Config;
6use crate::error::Result;
7use crate::objective::CostModel;
8use crate::optim::{Exit, IterationReport, ProgressSink, RunControl, optimizer};
9use crate::setup::{Problem, resolve_seed};
10use crate::time::Instant;
11
12#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
14pub struct RunResult {
15 pub seed: u64,
17 pub algorithm: String,
19 pub solution: Vec<f64>,
21 pub fidelity: f64,
23 pub penalty: f64,
25 pub fidelity_history: Vec<f64>,
27 pub iterations: usize,
29 pub evaluations: usize,
31 pub exit: Exit,
33 pub elapsed_s: f64,
35 pub notices: Vec<String>,
37}
38
39pub fn available_threads() -> usize {
41 crate::parallel::available_threads()
42}
43
44struct History<'a> {
46 inner: &'a mut dyn ProgressSink,
47 fidelities: Vec<f64>,
48}
49
50impl ProgressSink for History<'_> {
51 fn on_iteration(&mut self, r: &IterationReport) {
52 self.fidelities.push(r.fidelity);
53 self.inner.on_iteration(r);
54 }
55 fn should_cancel(&self) -> bool {
56 self.inner.should_cancel()
57 }
58}
59
60pub fn run(cfg: &Config, sink: &mut dyn ProgressSink) -> Result<RunResult> {
64 let started = Instant::now();
65 let seed = resolve_seed(cfg);
66 let problem = Problem::build_with_seed(cfg, seed)?;
67 let x0 = problem.x0.clone();
68 let mut model = CostModel::new(problem);
69 if let Some(threads) = cfg.cpu_cores {
70 model = model.with_threads(threads)?;
71 }
72 let opt = optimizer(&cfg.optimization.algorithm)?;
73 let mut notices = Vec::new();
74 if cfg.compute_resource.as_deref() == Some("gpu") {
75 notices.push("GPU is not supported; running on CPU.".to_string());
76 }
77 let mut history = History {
78 inner: sink,
79 fidelities: Vec::new(),
80 };
81 let mut ctl = RunControl {
82 max_iter: cfg.optimization.max_iter,
83 target_fidelity: cfg.optimization.targ_fid,
84 sink: &mut history,
85 };
86 let result = opt.minimize(&model, &x0, &mut ctl)?;
87 Ok(RunResult {
88 seed,
89 algorithm: opt.name().to_string(),
90 solution: result.x,
91 fidelity: result.eval.fidelity,
92 penalty: result.eval.penalty,
93 fidelity_history: history.fidelities,
94 iterations: result.iterations,
95 evaluations: result.evaluations,
96 exit: result.exit,
97 elapsed_s: started.elapsed().as_secs_f64(),
98 notices,
99 })
100}