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 #[serde(default)]
41 pub peak_amplitude: Vec<f64>,
42}
43
44fn 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
58pub fn available_threads() -> usize {
60 crate::parallel::available_threads()
61}
62
63struct 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
79pub 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 #[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}