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, Step};
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    /// Pulse sample times in nanoseconds: the middle of each time step.
31    pub times_ns: Vec<f64>,
32    /// State times in nanoseconds: the step boundaries from 0 to the pulse duration, one more than the samples.
33    pub state_times_ns: Vec<f64>,
34    /// One trace per qubit.
35    pub pulses: Vec<PulseTrace>,
36    /// One per initial state.
37    pub dynamics: Vec<Dynamics>,
38    /// One per initial state.
39    pub profiles: Vec<ExcitationProfile>,
40}
41
42/// A qubit's modulated waveform, as a fraction of its maximum Rabi frequency.
43#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
44pub struct PulseTrace {
45    /// Qubit index.
46    pub qubit: usize,
47    /// In-phase quadrature.
48    pub cx: Vec<f64>,
49    /// Quadrature.
50    pub cy: Vec<f64>,
51    /// Amplitude.
52    pub amp: Vec<f64>,
53    /// Phase in radians.
54    pub phase: Vec<f64>,
55}
56
57/// The evolution of one initial state under the pulse.
58#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
59pub struct Dynamics {
60    /// Which initial state.
61    pub initial_state: usize,
62    /// A label per component: `ψ1…` for state vectors, `ρ11…` for density matrices.
63    pub labels: Vec<String>,
64    /// `[component][t]` as `(re, im)` at the state times, under the mean drift (configured offsets and couplings) and maximum Rabi
65    /// frequencies.
66    pub mean: Vec<Vec<[f64; 2]>>,
67    /// `[snapshot][component][t]` for up to twenty batch snapshots.
68    pub snapshots: Vec<Vec<Vec<[f64; 2]>>>,
69    /// Per qubit, `⟨σx⟩, ⟨σy⟩, ⟨σz⟩` over time under the mean drift.
70    pub observables: Vec<[Vec<f64>; 3]>,
71    /// Per qubit, the smallest value of each observable over the batch snapshots, over time.
72    pub observables_min: Vec<[Vec<f64>; 3]>,
73    /// Per qubit, the largest value of each observable over the batch snapshots, over time.
74    pub observables_max: Vec<[Vec<f64>; 3]>,
75    /// Population outside the computational subspace over time, under the mean drift: `1 − Tr(P·ρ)`.  Zero
76    /// throughout for models without room to leak.  Total, not a sum over qubits, which would count leakage from
77    /// two qubits at once twice.
78    pub leakage: Vec<f64>,
79    /// The smallest leakage over the batch snapshots, over time.
80    pub leakage_min: Vec<f64>,
81    /// The largest leakage over the batch snapshots, over time.
82    pub leakage_max: Vec<f64>,
83}
84
85/// Where the pulse acts: the final state's observables as the offsets are swept.
86#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
87pub struct ExcitationProfile {
88    /// Which initial state.
89    pub initial_state: usize,
90    /// Per qubit, the offsets swept, in Hz, across 1.5 sweep widths about the configured offset.
91    pub offsets_hz: Vec<Vec<f64>>,
92    /// Per qubit, `⟨σx⟩, ⟨σy⟩, ⟨σz⟩` at the end of the pulse at each offset.
93    pub xyz: Vec<[Vec<f64>; 3]>,
94}
95
96/// Plot data for `result`, a run of `cfg`.
97pub fn analyse(cfg: &Config, result: &RunResult) -> Result<Analysis> {
98    let problem = Problem::build_with_seed(cfg, result.seed)?;
99    let model = CostModel::new(problem);
100    let w = model.waveforms(&result.solution)?;
101    let p = model.problem();
102
103    let pulses = (0..p.n_qubits)
104        .map(|q| PulseTrace {
105            qubit: q,
106            cx: w.cx.col(q),
107            cy: w.cy.col(q),
108            amp: w.amp.col(q),
109            phase: w.phase.col(q),
110        })
111        .collect();
112
113    let mean_drift = p.model.drift(&p.delta, p.coupling.as_ref())?;
114    let dynamics = (0..p.initial_states.len())
115        .map(|i| dynamics(p, &w, &mean_drift, i))
116        .collect::<Result<Vec<_>>>()?;
117    let profiles = (0..p.initial_states.len())
118        .map(|i| profile(p, &w, i))
119        .collect::<Result<Vec<_>>>()?;
120
121    Ok(Analysis {
122        times_ns: p.times.iter().map(|t| t * 1e9).collect(),
123        state_times_ns: (0..=p.n_pulse).map(|t| t as f64 * p.dt * 1e9).collect(),
124        pulses,
125        dynamics,
126        profiles,
127    })
128}
129
130/// The control amplitudes at every step for Rabi frequencies `rabi`: `u[t][k]`.
131fn controls(p: &Problem, w: &Waveforms, rabi: &[f64]) -> Vec<Vec<f64>> {
132    (0..p.n_pulse)
133        .map(|t| {
134            p.channels
135                .iter()
136                .map(|ch| {
137                    let (x, y) = (w.cx.get(t, ch.qubit), w.cy.get(t, ch.qubit));
138                    let s = match ch.source {
139                        Source::Cx => x,
140                        Source::Cy => y,
141                        Source::Power => x * x + y * y,
142                    };
143                    ch.coeff * rabi[ch.qubit].powi(ch.rabi_power) * s
144                })
145                .collect()
146        })
147        .collect()
148}
149
150/// `initial` and the state after every step under drift `h0` and controls `u`.
151fn trajectory(p: &Problem, h0: &CMat<f64>, u: &[Vec<f64>], initial: &CMat<f64>) -> Result<Vec<CMat<f64>>> {
152    let mut state = initial.clone();
153    let mut out = Vec::with_capacity(p.n_pulse + 1);
154    out.push(state.clone());
155    for ut in u {
156        let mut h = h0.clone();
157        for (k, op) in p.control_ops.iter().enumerate() {
158            h.axpy_re(ut[k], op);
159        }
160        let step = expm_mi_dt(&h, p.dt)?;
161        state = match &p.evolution {
162            Evolution::Hilbert => step.matmul(&state)?,
163            Evolution::Liouville => step.matmul(&state)?.matmul(&step.adjoint())?,
164            // Strang splitting, as the objective propagates: half a dissipation step at each end of the step,
165            // which is the same sequence once the halves between steps meet.
166            Evolution::Lindblad(ops) => {
167                let entering = ops.apply(&state, Step::Half, false)?;
168                let turned = step.matmul(&entering)?.matmul(&step.adjoint())?;
169                ops.apply(&turned, Step::Half, false)?
170            }
171        };
172        out.push(state.clone());
173    }
174    Ok(out)
175}
176
177/// `Re⟨ψ|O|ψ⟩` or `Re Tr(O·ρ)`.
178fn expectation(o: &CMat<f64>, state: &CMat<f64>) -> f64 {
179    if state.cols == 1 {
180        let o_psi = o.matmul(state).expect("shapes match");
181        state.inner(&o_psi).re
182    } else {
183        o.matmul(state).expect("shapes match").trace().re
184    }
185}
186
187/// Which components of a state are plotted, and their labels.
188fn components(p: &Problem) -> (Vec<(usize, usize)>, Vec<String>) {
189    let d = p.dim;
190    match p.space {
191        Space::Hilbert => (
192            (0..d).map(|i| (i, 0)).collect(),
193            (1..=d).map(|i| format!("ψ{i}")).collect(),
194        ),
195        Space::Liouville if d <= MAX_FULL_DENSITY => {
196            let idx: Vec<(usize, usize)> = (0..d).flat_map(|r| (0..d).map(move |c| (r, c))).collect();
197            let labels = idx.iter().map(|(r, c)| format!("ρ{}{}", r + 1, c + 1)).collect();
198            (idx, labels)
199        }
200        Space::Liouville => (
201            (0..d).map(|i| (i, i)).collect(),
202            (1..=d).map(|i| format!("ρ{i}{i}")).collect(),
203        ),
204    }
205}
206
207fn pick(traj: &[CMat<f64>], idx: &[(usize, usize)]) -> Vec<Vec<[f64; 2]>> {
208    idx.iter()
209        .map(|&(r, c)| {
210            traj.iter()
211                .map(|s| {
212                    let z: C<f64> = s.get(r, c);
213                    [z.re, z.im]
214                })
215                .collect()
216        })
217        .collect()
218}
219
220/// Population outside the computational subspace at each step: `1 − Tr(P·ρ)`, or `1 − ‖P·ψ‖²`.
221fn leakage_over(projector: &CMat<f64>, traj: &[CMat<f64>]) -> Vec<f64> {
222    traj.iter().map(|s| 1.0 - expectation(projector, s)).collect()
223}
224
225fn observables_over(p: &Problem, traj: &[CMat<f64>]) -> Vec<[Vec<f64>; 3]> {
226    p.observables
227        .iter()
228        .map(|ops| [0, 1, 2].map(|k| traj.iter().map(|s| expectation(&ops[k], s)).collect()))
229        .collect()
230}
231
232fn dynamics(p: &Problem, w: &Waveforms, mean_drift: &CMat<f64>, i: usize) -> Result<Dynamics> {
233    let (idx, labels) = components(p);
234    let initial = &p.initial_states[i];
235    let mean_traj = trajectory(p, mean_drift, &controls(p, w, &p.rabi_max), initial)?;
236
237    // One trajectory from this initial state per drift and Rabi snapshot.  Batch elements do not always start from
238    // it: a gate target evolves the whole computational basis.
239    let mut seen = std::collections::HashSet::new();
240    let snapshots: Vec<_> = p
241        .batch
242        .iter()
243        .filter(|e| seen.insert((e.snapshot, e.rabi_index)))
244        .collect();
245    let trajectories = crate::parallel::map(snapshots.len(), |j| {
246        let e = snapshots[j];
247        trajectory(p, &e.h0, &controls(p, w, &e.rabi), initial)
248    })
249    .into_iter()
250    .collect::<Result<Vec<_>>>()?;
251
252    let per_snapshot: Vec<Vec<[Vec<f64>; 3]>> = trajectories.iter().map(|t| observables_over(p, t)).collect();
253    // The computational subspace's projector, `P·P†`, which is the identity where there is nowhere to leak.
254    let projector = p.model.embed_density(&CMat::identity(1 << p.n_qubits))?;
255    let leaks: Vec<Vec<f64>> = trajectories.iter().map(|t| leakage_over(&projector, t)).collect();
256    let leak_fold = |pick_min: bool| -> Vec<f64> {
257        (0..=p.n_pulse)
258            .map(|t| {
259                let vals = leaks.iter().map(|l| l[t]);
260                if pick_min {
261                    vals.fold(f64::INFINITY, f64::min)
262                } else {
263                    vals.fold(f64::NEG_INFINITY, f64::max)
264                }
265            })
266            .collect()
267    };
268    let fold = |pick_min: bool| -> Vec<[Vec<f64>; 3]> {
269        (0..p.n_qubits)
270            .map(|q| {
271                [0, 1, 2].map(|k| {
272                    (0..=p.n_pulse)
273                        .map(|t| {
274                            let vals = per_snapshot.iter().map(|s| s[q][k][t]);
275                            if pick_min {
276                                vals.fold(f64::INFINITY, f64::min)
277                            } else {
278                                vals.fold(f64::NEG_INFINITY, f64::max)
279                            }
280                        })
281                        .collect()
282                })
283            })
284            .collect()
285    };
286
287    Ok(Dynamics {
288        initial_state: i,
289        labels,
290        mean: pick(&mean_traj, &idx),
291        snapshots: trajectories.iter().take(MAX_SNAPSHOTS).map(|t| pick(t, &idx)).collect(),
292        observables: observables_over(p, &mean_traj),
293        observables_min: fold(true),
294        observables_max: fold(false),
295        leakage: leakage_over(&projector, &mean_traj),
296        leakage_min: leak_fold(true),
297        leakage_max: leak_fold(false),
298    })
299}
300
301fn profile(p: &Problem, w: &Waveforms, i: usize) -> Result<ExcitationProfile> {
302    let two_pi = 2.0 * std::f64::consts::PI;
303    let n = PROFILE_POINTS;
304    let offsets: Vec<Vec<f64>> = (0..p.n_qubits)
305        .map(|q| crate::basis::linspace(p.delta[q] - 0.75 * p.sw[q], p.delta[q] + 0.75 * p.sw[q], n))
306        .collect();
307    let u = controls(p, w, &p.rabi_max);
308    let initial = &p.initial_states[i];
309    let finals = crate::parallel::map(n, |j| -> Result<Vec<[f64; 3]>> {
310        let at: Vec<f64> = offsets.iter().map(|o| o[j]).collect();
311        let h0 = p.model.drift(&at, p.coupling.as_ref())?;
312        let last = trajectory(p, &h0, &u, initial)?
313            .pop()
314            .unwrap_or_else(|| initial.clone());
315        Ok(p.observables
316            .iter()
317            .map(|ops| [0, 1, 2].map(|k| expectation(&ops[k], &last)))
318            .collect())
319    })
320    .into_iter()
321    .collect::<Result<Vec<_>>>()?;
322    let xyz = (0..p.n_qubits)
323        .map(|q| [0, 1, 2].map(|k| finals.iter().map(|f| f[q][k]).collect()))
324        .collect();
325    Ok(ExcitationProfile {
326        initial_state: i,
327        offsets_hz: offsets.iter().map(|o| o.iter().map(|v| v / two_pi).collect()).collect(),
328        xyz,
329    })
330}
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335    use crate::config::examples;
336    use crate::optim::Exit;
337
338    fn result_for(solution: Vec<f64>) -> RunResult {
339        RunResult {
340            seed: 3,
341            algorithm: "l-bfgs".into(),
342            solution,
343            fidelity: 0.0,
344            penalty: 0.0,
345            fidelity_history: vec![],
346            iterations: 0,
347            evaluations: 0,
348            exit: Exit::Converged,
349            elapsed_s: 0.0,
350            notices: vec![],
351            peak_amplitude: vec![],
352        }
353    }
354
355    fn single() -> Config {
356        let mut c = Config::from_json(examples()[0].1).unwrap();
357        c.optimization.h0_snapshots = 5;
358        c
359    }
360
361    #[test]
362    fn a_zero_pulse_leaves_populations_alone() {
363        let cfg = single();
364        let n = Problem::build_with_seed(&cfg, 3).unwrap().n_params();
365        let a = analyse(&cfg, &result_for(vec![0.0; n])).unwrap();
366        let d = &a.dynamics[0];
367        assert_eq!(d.labels, vec!["ψ1", "ψ2"]);
368        for t in 0..a.times_ns.len() {
369            let pop0 = d.mean[0][t][0].powi(2) + d.mean[0][t][1].powi(2);
370            assert!((pop0 - 1.0).abs() < 1e-12);
371            assert!((d.observables[0][2][t] - 1.0).abs() < 1e-12);
372        }
373        assert!(a.pulses[0].amp.iter().all(|&v| v == 0.0));
374    }
375
376    /// The mean trajectory's last point is the pulse applied to the initial state, as the objective sees it.
377    #[test]
378    fn the_last_state_matches_an_independent_propagation() {
379        let mut cfg = single();
380        cfg.parameters.coverage = vec![crate::config::Coverage::Single];
381        let problem = Problem::build_with_seed(&cfg, 3).unwrap();
382        let x: Vec<f64> = problem.x0.clone();
383        let target = problem.batch[0].target.clone();
384        let model = CostModel::new(problem);
385        let fid = model.value(&x).unwrap().fidelity;
386        let a = analyse(&cfg, &result_for(x)).unwrap();
387        let last: Vec<C<f64>> = a.dynamics[0]
388            .mean
389            .iter()
390            .map(|c| C::new(c.last().unwrap()[0], c.last().unwrap()[1]))
391            .collect();
392        let psi = CMat::column(last);
393        let overlap = target.inner(&psi).norm_sqr();
394        assert!((overlap - fid).abs() < 1e-12, "{overlap} vs {fid}");
395    }
396
397    /// States are plotted at the step boundaries, from the initial state at 0 to the final one at T.
398    #[test]
399    fn states_are_timed_at_the_step_boundaries() {
400        let cfg = single();
401        let p = Problem::build_with_seed(&cfg, 3).unwrap();
402        let (n, duration) = (p.n_pulse, p.duration);
403        let a = analyse(&cfg, &result_for(p.x0.clone())).unwrap();
404        assert_eq!(a.state_times_ns.len(), n + 1);
405        assert_eq!(a.state_times_ns[0], 0.0);
406        assert!((a.state_times_ns[n] - duration * 1e9).abs() < 1e-9);
407        let d = &a.dynamics[0];
408        assert!(
409            d.mean
410                .iter()
411                .chain(d.snapshots.iter().flatten())
412                .all(|c| c.len() == n + 1)
413        );
414        assert!(
415            d.observables
416                .iter()
417                .chain(&d.observables_min)
418                .all(|o| o.iter().all(|v| v.len() == n + 1))
419        );
420        // |0>: ψ1 = 1 before the pulse.
421        assert_eq!(d.mean[0][0], [1.0, 0.0]);
422    }
423
424    /// Leakage is the population outside the computational subspace: for one three-level transmon, `|ψ₃|²`.
425    #[test]
426    fn leakage_is_the_population_outside_the_computational_subspace() {
427        let cfg = crate::hamiltonian::default_config("duffing_transmon", 1).unwrap();
428        let p = Problem::build_with_seed(&cfg, 3).unwrap();
429        let a = analyse(&cfg, &result_for(p.x0.clone())).unwrap();
430        let d = &a.dynamics[0];
431        assert_eq!(d.leakage.len(), a.state_times_ns.len());
432        assert_eq!(d.leakage[0], 0.0, "the initial state is in the subspace");
433        for (t, &l) in d.leakage.iter().enumerate() {
434            let third = d.mean[2][t][0].powi(2) + d.mean[2][t][1].powi(2);
435            assert!((l - third).abs() < 1e-12, "t {t}: {l} vs {third}");
436            assert!((0.0..=1.0).contains(&l));
437            assert!(d.leakage_min[t] <= d.leakage_max[t] && d.leakage_min[t] >= 0.0);
438        }
439        assert!(d.leakage.iter().any(|&l| l > 1e-9), "a transmon drive leaks something");
440    }
441
442    /// Two-level models have nowhere to leak to.
443    #[test]
444    fn two_level_models_report_no_leakage() {
445        let cfg = single();
446        let n = Problem::build_with_seed(&cfg, 3).unwrap().n_params();
447        let a = analyse(&cfg, &result_for(vec![0.3; n])).unwrap();
448        let worst = a.dynamics[0].leakage.iter().fold(0.0f64, |m, l| m.max(l.abs()));
449        assert!(worst < 1e-12, "{worst}");
450    }
451
452    /// A gate run still plots the configured initial state, under every snapshot.
453    #[test]
454    fn gate_runs_plot_the_configured_initial_states() {
455        let mut cfg = Config::from_json(examples().iter().find(|e| e.0 == "two_qubit_parameters").unwrap().1).unwrap();
456        cfg.optimization.h0_snapshots = 3;
457        cfg.parameters.coverage = vec![crate::config::Coverage::Broadband; 2];
458        let n = Problem::build_with_seed(&cfg, 3).unwrap().n_params();
459        let a = analyse(&cfg, &result_for(vec![0.0; n])).unwrap();
460        let d = &a.dynamics[0];
461        assert_eq!((d.mean.len(), d.snapshots.len()), (4, 3));
462        // |Z, −Z> = |01>: ψ2 = 1 before the pulse, in every snapshot.
463        assert!(d.snapshots.iter().all(|s| s[1][0] == [1.0, 0.0]));
464    }
465
466    /// The dissipative dynamics plot ends where the objective measures its fidelity.
467    #[test]
468    fn the_last_dissipative_state_matches_the_objective() {
469        let mut cfg =
470            Config::from_json(examples().iter().find(|e| e.0 == "single_qubit_dissipative").unwrap().1).unwrap();
471        cfg.parameters.coverage = vec![crate::config::Coverage::Single];
472        let problem = Problem::build_with_seed(&cfg, 3).unwrap();
473        let x = problem.x0.clone();
474        let target = problem.batch[0].target.clone();
475        let model = CostModel::new(problem);
476        let fid = model.value(&x).unwrap().fidelity;
477        let a = analyse(&cfg, &result_for(x)).unwrap();
478        let d = &a.dynamics[0];
479        // Two levels, so the plot keeps the whole density matrix: ρ11, ρ12, ρ21, ρ22 in order.
480        let rho = CMat::from_fn(2, 2, |r, c| {
481            let last = d.mean[r * 2 + c].last().unwrap();
482            C::new(last[0], last[1])
483        });
484        let got = target.matmul(&rho).unwrap().trace().re;
485        assert!((got - fid).abs() < 1e-12, "{got} vs {fid}");
486    }
487
488    #[test]
489    fn the_profile_spans_one_and_a_half_sweep_widths() {
490        let cfg = single();
491        let n = Problem::build_with_seed(&cfg, 3).unwrap().n_params();
492        let a = analyse(&cfg, &result_for(vec![0.0; n])).unwrap();
493        let o = &a.profiles[0].offsets_hz[0];
494        assert_eq!(o.len(), PROFILE_POINTS);
495        assert!((o[0] - (10e6 - 3.75e6)).abs() < 1e-3 && (o[o.len() - 1] - (10e6 + 3.75e6)).abs() < 1e-3);
496        // No pulse: every offset leaves Z at +1.
497        assert!(a.profiles[0].xyz[0][2].iter().all(|&z| (z - 1.0).abs() < 1e-12));
498    }
499}