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    /// Per qubit, the largest amplitude of the optimised pulse as a fraction of that qubit's `Omega_R_max`.
38    /// Anything above 1 asks for more than the configured maximum Rabi frequency: the limit is penalised in the
39    /// cost, not enforced, so a result can exceed it.
40    #[serde(default)]
41    pub peak_amplitude: Vec<f64>,
42}
43
44/// What to tell the user when a pulse asks for more than the maximum Rabi frequency it was given.
45fn amplitude_notice(peaks: &[f64]) -> Option<String> {
46    let (q, &peak) = peaks
47        .iter()
48        .enumerate()
49        .max_by(|a, b| a.1.total_cmp(b.1))
50        .filter(|&(_, &p)| p > 1.0)?;
51    Some(format!(
52        "The pulse exceeds the maximum Rabi frequency: qubit {}'s amplitude peaks at {peak:.2} of it.  The limit \
53         is penalised in the cost, not enforced.",
54        q + 1
55    ))
56}
57
58/// Number of threads a run uses when the configuration does not set `cpu_cores`.
59pub fn available_threads() -> usize {
60    crate::parallel::available_threads()
61}
62
63/// Passes reports on and keeps the fidelity history.
64struct History<'a> {
65    inner: &'a mut dyn ProgressSink,
66    fidelities: Vec<f64>,
67}
68
69impl ProgressSink for History<'_> {
70    fn on_iteration(&mut self, r: &IterationReport) {
71        self.fidelities.push(r.fidelity);
72        self.inner.on_iteration(r);
73    }
74    fn should_cancel(&self) -> bool {
75        self.inner.should_cancel()
76    }
77}
78
79/// Optimise the pulse `cfg` describes, reporting each iteration to `sink`.
80///
81/// The configuration's seed is used if it has one; otherwise one is drawn and returned in the result.
82pub fn run(cfg: &Config, sink: &mut dyn ProgressSink) -> Result<RunResult> {
83    let started = Instant::now();
84    let seed = resolve_seed(cfg);
85    let problem = Problem::build_with_seed(cfg, seed)?;
86    let x0 = problem.x0.clone();
87    let mut model = CostModel::new(problem);
88    if let Some(threads) = cfg.cpu_cores {
89        model = model.with_threads(threads)?;
90    }
91    let opt = optimizer(&cfg.optimization.algorithm)?;
92    let mut notices = Vec::new();
93    if cfg.compute_resource.as_deref() == Some("gpu") {
94        notices.push("GPU is not supported; running on CPU.".to_string());
95    }
96    if let Some(gate) = cfg.target_states.single_gate() {
97        notices.push(format!(
98            "The fidelity is the {gate} gate's average gate fidelity over the computational basis; the initial \
99             states only set what the dynamics plots show."
100        ));
101    }
102    let mut history = History {
103        inner: sink,
104        fidelities: Vec::new(),
105    };
106    let mut ctl = RunControl {
107        max_iter: cfg.optimization.max_iter,
108        target_fidelity: cfg.optimization.targ_fid,
109        sink: &mut history,
110    };
111    let result = opt.minimize(&model, &x0, &mut ctl)?;
112    let amp = model.waveforms(&result.x)?.amp;
113    let peak_amplitude: Vec<f64> = (0..amp.cols)
114        .map(|q| (0..amp.rows).fold(0.0f64, |m, t| m.max(amp.get(t, q))))
115        .collect();
116    notices.extend(amplitude_notice(&peak_amplitude));
117    Ok(RunResult {
118        seed,
119        algorithm: opt.name().to_string(),
120        solution: result.x,
121        fidelity: result.eval.fidelity,
122        penalty: result.eval.penalty,
123        fidelity_history: history.fidelities,
124        iterations: result.iterations,
125        evaluations: result.evaluations,
126        exit: result.exit,
127        elapsed_s: started.elapsed().as_secs_f64(),
128        notices,
129        peak_amplitude,
130    })
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136    use crate::config::examples;
137    use crate::optim::NoProgress;
138
139    #[test]
140    fn a_run_reports_the_peak_amplitude_of_its_pulse() {
141        let mut cfg = Config::from_json(examples()[0].1).unwrap();
142        cfg.seed = Some(5);
143        cfg.optimization.max_iter = 3;
144        let r = run(&cfg, &mut NoProgress).unwrap();
145        let model = CostModel::new(Problem::build_with_seed(&cfg, r.seed).unwrap());
146        let amp = model.waveforms(&r.solution).unwrap().amp;
147        let want = (0..amp.rows).fold(0.0f64, |m, t| m.max(amp.get(t, 0)));
148        assert_eq!(r.peak_amplitude, vec![want]);
149    }
150
151    /// The amplitude limit is penalised, not enforced, so a pulse that exceeds it says so.
152    #[test]
153    fn exceeding_the_maximum_rabi_frequency_is_reported() {
154        assert_eq!(amplitude_notice(&[0.5, 1.0]), None);
155        let notice = amplitude_notice(&[0.5, 1.07]).expect("a notice");
156        assert!(notice.contains("qubit 2") && notice.contains("1.07"), "{notice}");
157    }
158}