Skip to main content

ctrl_freeq/
analysis.rs

1//! What the plots need after a run: the pulses, the state dynamics, and the excitation profile.
2//!
3//! Everything here is plain `f64` propagation of the optimised pulse, with the same Hamiltonians, time step and
4//! evolution as the objective.
5
6use serde::{Deserialize, Serialize};
7
8use crate::autodiff::C;
9use crate::config::{Config, Space};
10use crate::error::Result;
11use crate::hamiltonian::Source;
12use crate::linalg::{CMat, expm_mi_dt};
13use crate::objective::{CostModel, Waveforms};
14use crate::run::RunResult;
15use crate::setup::{Evolution, Problem};
16
17/// Batch snapshots whose trajectories are kept for plotting.
18const MAX_SNAPSHOTS: usize = 20;
19/// Largest dimension whose full density matrix is kept; larger ones keep the populations only.
20const MAX_FULL_DENSITY: usize = 4;
21/// Offsets in the excitation profile.
22#[cfg(not(target_arch = "wasm32"))]
23const PROFILE_POINTS: usize = 1000;
24#[cfg(target_arch = "wasm32")]
25const PROFILE_POINTS: usize = 400;
26
27/// Plot data for a finished run.
28#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
29pub struct Analysis {
30    /// Time grid in nanoseconds.
31    pub times_ns: Vec<f64>,
32    /// One trace per qubit.
33    pub pulses: Vec<PulseTrace>,
34    /// One per initial state.
35    pub dynamics: Vec<Dynamics>,
36    /// One per initial state.
37    pub profiles: Vec<ExcitationProfile>,
38}
39
40/// A qubit's modulated waveform, as a fraction of its maximum Rabi frequency.
41#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
42pub struct PulseTrace {
43    /// Qubit index.
44    pub qubit: usize,
45    /// In-phase quadrature.
46    pub cx: Vec<f64>,
47    /// Quadrature.
48    pub cy: Vec<f64>,
49    /// Amplitude.
50    pub amp: Vec<f64>,
51    /// Phase in radians.
52    pub phase: Vec<f64>,
53}
54
55/// The evolution of one initial state under the pulse.
56#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
57pub struct Dynamics {
58    /// Which initial state.
59    pub initial_state: usize,
60    /// A label per component: `ψ1…` for state vectors, `ρ11…` for density matrices.
61    pub labels: Vec<String>,
62    /// `[component][t]` as `(re, im)`, under the mean drift (configured offsets and couplings) and maximum Rabi
63    /// frequencies.
64    pub mean: Vec<Vec<[f64; 2]>>,
65    /// `[snapshot][component][t]` for up to twenty batch snapshots.
66    pub snapshots: Vec<Vec<Vec<[f64; 2]>>>,
67    /// Per qubit, `⟨σx⟩, ⟨σy⟩, ⟨σz⟩` over time under the mean drift.
68    pub observables: Vec<[Vec<f64>; 3]>,
69    /// Per qubit, the smallest value of each observable over the batch snapshots, over time.
70    pub observables_min: Vec<[Vec<f64>; 3]>,
71    /// Per qubit, the largest value of each observable over the batch snapshots, over time.
72    pub observables_max: Vec<[Vec<f64>; 3]>,
73}
74
75/// Where the pulse acts: the final state's observables as the offsets are swept.
76#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
77pub struct ExcitationProfile {
78    /// Which initial state.
79    pub initial_state: usize,
80    /// Per qubit, the offsets swept, in Hz, across 1.5 sweep widths about the configured offset.
81    pub offsets_hz: Vec<Vec<f64>>,
82    /// Per qubit, `⟨σx⟩, ⟨σy⟩, ⟨σz⟩` at the end of the pulse at each offset.
83    pub xyz: Vec<[Vec<f64>; 3]>,
84}
85
86/// Plot data for `result`, a run of `cfg`.
87pub fn analyse(cfg: &Config, result: &RunResult) -> Result<Analysis> {
88    let problem = Problem::build_with_seed(cfg, result.seed)?;
89    let model = CostModel::new(problem);
90    let w = model.waveforms(&result.solution)?;
91    let p = model.problem();
92
93    let pulses = (0..p.n_qubits)
94        .map(|q| PulseTrace {
95            qubit: q,
96            cx: w.cx.col(q),
97            cy: w.cy.col(q),
98            amp: w.amp.col(q),
99            phase: w.phase.col(q),
100        })
101        .collect();
102
103    let mean_drift = p.model.drift(&p.delta, p.coupling.as_ref())?;
104    let dynamics = (0..p.initial_states.len())
105        .map(|i| dynamics(p, &w, &mean_drift, i))
106        .collect::<Result<Vec<_>>>()?;
107    let profiles = (0..p.initial_states.len())
108        .map(|i| profile(p, &w, i))
109        .collect::<Result<Vec<_>>>()?;
110
111    Ok(Analysis {
112        times_ns: p.times.iter().map(|t| t * 1e9).collect(),
113        pulses,
114        dynamics,
115        profiles,
116    })
117}
118
119/// The control amplitudes at every step for Rabi frequencies `rabi`: `u[t][k]`.
120fn controls(p: &Problem, w: &Waveforms, rabi: &[f64]) -> Vec<Vec<f64>> {
121    (0..p.n_pulse)
122        .map(|t| {
123            p.channels
124                .iter()
125                .map(|ch| {
126                    let (x, y) = (w.cx.get(t, ch.qubit), w.cy.get(t, ch.qubit));
127                    let s = match ch.source {
128                        Source::Cx => x,
129                        Source::Cy => y,
130                        Source::Power => x * x + y * y,
131                    };
132                    ch.coeff * rabi[ch.qubit].powi(ch.rabi_power) * s
133                })
134                .collect()
135        })
136        .collect()
137}
138
139/// The state after every step from `initial` under drift `h0` and controls `u`.
140fn trajectory(p: &Problem, h0: &CMat<f64>, u: &[Vec<f64>], initial: &CMat<f64>) -> Result<Vec<CMat<f64>>> {
141    let mut state = initial.clone();
142    let mut out = Vec::with_capacity(p.n_pulse);
143    for ut in u {
144        let mut h = h0.clone();
145        for (k, op) in p.control_ops.iter().enumerate() {
146            h.axpy_re(ut[k], op);
147        }
148        let step = expm_mi_dt(&h, p.dt)?;
149        state = match &p.evolution {
150            Evolution::Hilbert => step.matmul(&state)?,
151            Evolution::Liouville => step.matmul(&state)?.matmul(&step.adjoint())?,
152            Evolution::Lindblad(ops) => {
153                let rho = step.matmul(&state)?.matmul(&step.adjoint())?;
154                let mut next = rho.clone();
155                next.axpy_re(p.dt, &ops.dissipator(&rho, false)?);
156                next
157            }
158        };
159        out.push(state.clone());
160    }
161    Ok(out)
162}
163
164/// `Re⟨ψ|O|ψ⟩` or `Re Tr(O·ρ)`.
165fn expectation(o: &CMat<f64>, state: &CMat<f64>) -> f64 {
166    if state.cols == 1 {
167        let o_psi = o.matmul(state).expect("shapes match");
168        state.inner(&o_psi).re
169    } else {
170        o.matmul(state).expect("shapes match").trace().re
171    }
172}
173
174/// Which components of a state are plotted, and their labels.
175fn components(p: &Problem) -> (Vec<(usize, usize)>, Vec<String>) {
176    let d = p.dim;
177    match p.space {
178        Space::Hilbert => (
179            (0..d).map(|i| (i, 0)).collect(),
180            (1..=d).map(|i| format!("ψ{i}")).collect(),
181        ),
182        Space::Liouville if d <= MAX_FULL_DENSITY => {
183            let idx: Vec<(usize, usize)> = (0..d).flat_map(|r| (0..d).map(move |c| (r, c))).collect();
184            let labels = idx.iter().map(|(r, c)| format!("ρ{}{}", r + 1, c + 1)).collect();
185            (idx, labels)
186        }
187        Space::Liouville => (
188            (0..d).map(|i| (i, i)).collect(),
189            (1..=d).map(|i| format!("ρ{i}{i}")).collect(),
190        ),
191    }
192}
193
194fn pick(traj: &[CMat<f64>], idx: &[(usize, usize)]) -> Vec<Vec<[f64; 2]>> {
195    idx.iter()
196        .map(|&(r, c)| {
197            traj.iter()
198                .map(|s| {
199                    let z: C<f64> = s.get(r, c);
200                    [z.re, z.im]
201                })
202                .collect()
203        })
204        .collect()
205}
206
207fn observables_over(p: &Problem, traj: &[CMat<f64>]) -> Vec<[Vec<f64>; 3]> {
208    p.observables
209        .iter()
210        .map(|ops| [0, 1, 2].map(|k| traj.iter().map(|s| expectation(&ops[k], s)).collect()))
211        .collect()
212}
213
214fn dynamics(p: &Problem, w: &Waveforms, mean_drift: &CMat<f64>, i: usize) -> Result<Dynamics> {
215    let (idx, labels) = components(p);
216    let initial = &p.initial_states[i];
217    let mean_traj = trajectory(p, mean_drift, &controls(p, w, &p.rabi_max), initial)?;
218
219    let elements: Vec<usize> = (0..p.batch.len()).filter(|&b| p.batch[b].initial_index == i).collect();
220    let trajectories = crate::parallel::map(elements.len(), |j| {
221        let e = &p.batch[elements[j]];
222        trajectory(p, &e.h0, &controls(p, w, &e.rabi), &e.initial)
223    })
224    .into_iter()
225    .collect::<Result<Vec<_>>>()?;
226
227    let per_snapshot: Vec<Vec<[Vec<f64>; 3]>> = trajectories.iter().map(|t| observables_over(p, t)).collect();
228    let fold = |pick_min: bool| -> Vec<[Vec<f64>; 3]> {
229        (0..p.n_qubits)
230            .map(|q| {
231                [0, 1, 2].map(|k| {
232                    (0..p.n_pulse)
233                        .map(|t| {
234                            let vals = per_snapshot.iter().map(|s| s[q][k][t]);
235                            if pick_min {
236                                vals.fold(f64::INFINITY, f64::min)
237                            } else {
238                                vals.fold(f64::NEG_INFINITY, f64::max)
239                            }
240                        })
241                        .collect()
242                })
243            })
244            .collect()
245    };
246
247    Ok(Dynamics {
248        initial_state: i,
249        labels,
250        mean: pick(&mean_traj, &idx),
251        snapshots: trajectories.iter().take(MAX_SNAPSHOTS).map(|t| pick(t, &idx)).collect(),
252        observables: observables_over(p, &mean_traj),
253        observables_min: fold(true),
254        observables_max: fold(false),
255    })
256}
257
258fn profile(p: &Problem, w: &Waveforms, i: usize) -> Result<ExcitationProfile> {
259    let two_pi = 2.0 * std::f64::consts::PI;
260    let n = PROFILE_POINTS;
261    let offsets: Vec<Vec<f64>> = (0..p.n_qubits)
262        .map(|q| crate::basis::linspace(p.delta[q] - 0.75 * p.sw[q], p.delta[q] + 0.75 * p.sw[q], n))
263        .collect();
264    let u = controls(p, w, &p.rabi_max);
265    let initial = &p.initial_states[i];
266    let finals = crate::parallel::map(n, |j| -> Result<Vec<[f64; 3]>> {
267        let at: Vec<f64> = offsets.iter().map(|o| o[j]).collect();
268        let h0 = p.model.drift(&at, p.coupling.as_ref())?;
269        let last = trajectory(p, &h0, &u, initial)?
270            .pop()
271            .unwrap_or_else(|| initial.clone());
272        Ok(p.observables
273            .iter()
274            .map(|ops| [0, 1, 2].map(|k| expectation(&ops[k], &last)))
275            .collect())
276    })
277    .into_iter()
278    .collect::<Result<Vec<_>>>()?;
279    let xyz = (0..p.n_qubits)
280        .map(|q| [0, 1, 2].map(|k| finals.iter().map(|f| f[q][k]).collect()))
281        .collect();
282    Ok(ExcitationProfile {
283        initial_state: i,
284        offsets_hz: offsets.iter().map(|o| o.iter().map(|v| v / two_pi).collect()).collect(),
285        xyz,
286    })
287}
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292    use crate::config::examples;
293    use crate::optim::Exit;
294
295    fn result_for(solution: Vec<f64>) -> RunResult {
296        RunResult {
297            seed: 3,
298            algorithm: "l-bfgs".into(),
299            solution,
300            fidelity: 0.0,
301            penalty: 0.0,
302            fidelity_history: vec![],
303            iterations: 0,
304            evaluations: 0,
305            exit: Exit::Converged,
306            elapsed_s: 0.0,
307            notices: vec![],
308        }
309    }
310
311    fn single() -> Config {
312        let mut c = Config::from_json(examples()[0].1).unwrap();
313        c.optimization.h0_snapshots = 5;
314        c
315    }
316
317    #[test]
318    fn a_zero_pulse_leaves_populations_alone() {
319        let cfg = single();
320        let n = Problem::build_with_seed(&cfg, 3).unwrap().n_params();
321        let a = analyse(&cfg, &result_for(vec![0.0; n])).unwrap();
322        let d = &a.dynamics[0];
323        assert_eq!(d.labels, vec!["ψ1", "ψ2"]);
324        for t in 0..a.times_ns.len() {
325            let pop0 = d.mean[0][t][0].powi(2) + d.mean[0][t][1].powi(2);
326            assert!((pop0 - 1.0).abs() < 1e-12);
327            assert!((d.observables[0][2][t] - 1.0).abs() < 1e-12);
328        }
329        assert!(a.pulses[0].amp.iter().all(|&v| v == 0.0));
330    }
331
332    /// The mean trajectory's last point is the pulse applied to the initial state, as the objective sees it.
333    #[test]
334    fn the_last_state_matches_an_independent_propagation() {
335        let mut cfg = single();
336        cfg.parameters.coverage = vec![crate::config::Coverage::Single];
337        let problem = Problem::build_with_seed(&cfg, 3).unwrap();
338        let x: Vec<f64> = problem.x0.clone();
339        let target = problem.batch[0].target.clone();
340        let model = CostModel::new(problem);
341        let fid = model.value(&x).unwrap().fidelity;
342        let a = analyse(&cfg, &result_for(x)).unwrap();
343        let last: Vec<C<f64>> = a.dynamics[0]
344            .mean
345            .iter()
346            .map(|c| C::new(c.last().unwrap()[0], c.last().unwrap()[1]))
347            .collect();
348        let psi = CMat::column(last);
349        let overlap = target.inner(&psi).norm_sqr();
350        assert!((overlap - fid).abs() < 1e-12, "{overlap} vs {fid}");
351    }
352
353    #[test]
354    fn the_profile_spans_one_and_a_half_sweep_widths() {
355        let cfg = single();
356        let n = Problem::build_with_seed(&cfg, 3).unwrap().n_params();
357        let a = analyse(&cfg, &result_for(vec![0.0; n])).unwrap();
358        let o = &a.profiles[0].offsets_hz[0];
359        assert_eq!(o.len(), PROFILE_POINTS);
360        assert!((o[0] - (10e6 - 3.75e6)).abs() < 1e-3 && (o[o.len() - 1] - (10e6 + 3.75e6)).abs() < 1e-3);
361        // No pulse: every offset leaves Z at +1.
362        assert!(a.profiles[0].xyz[0][2].iter().all(|&z| (z - 1.0).abs() < 1e-12));
363    }
364}