Skip to main content

ctrl_freeq/
run.rs

1//! One call from a configuration to an optimised pulse.
2
3use 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/// What a run produced.
13#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
14pub struct RunResult {
15    /// The seed every random quantity was drawn from; put it in the configuration to repeat the run exactly.
16    pub seed: u64,
17    /// The optimiser used.
18    pub algorithm: String,
19    /// The optimised parameters.
20    pub solution: Vec<f64>,
21    /// Mean fidelity at the solution.
22    pub fidelity: f64,
23    /// Amplitude penalty at the solution.
24    pub penalty: f64,
25    /// Fidelity at each reported iteration.
26    pub fidelity_history: Vec<f64>,
27    /// Iterations completed.
28    pub iterations: usize,
29    /// Objective evaluations.
30    pub evaluations: usize,
31    /// Why the run ended.
32    pub exit: Exit,
33    /// Wall-clock seconds.
34    pub elapsed_s: f64,
35    /// Things the user should know, such as a request for a GPU this version cannot honour.
36    pub notices: Vec<String>,
37}
38
39/// Number of threads a run uses when the configuration does not set `cpu_cores`.
40pub fn available_threads() -> usize {
41    crate::parallel::available_threads()
42}
43
44/// Passes reports on and keeps the fidelity history.
45struct 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
60/// Optimise the pulse `cfg` describes, reporting each iteration to `sink`.
61///
62/// The configuration's seed is used if it has one; otherwise one is drawn and returned in the result.
63pub 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}