Skip to main content

ctrl_freeq/setup/
mod.rs

1//! From a [`Config`] to the numbers the optimiser works with - the Python `Initialise`.
2//!
3//! [`Problem::build`] validates the configuration, draws every random quantity from one seeded generator, and
4//! assembles the batch: one element per (initial state, drift snapshot, Rabi snapshot), each with its drift
5//! Hamiltonian, Rabi frequencies, initial state and target.  One gate for every initial state is scored as a gate
6//! instead; [`BatchElement`] says how.
7
8mod dissipation;
9mod sampling;
10mod states;
11
12pub use dissipation::collapse_operators;
13pub use states::{
14    canonical_gate, embed, gate, gate_names, pauli_ops, paulis, product_density, product_state, rotation, spin_ops,
15};
16
17use rand::SeedableRng;
18
19use crate::autodiff::{C, LindbladOps};
20use crate::basis::{QubitBasis, basis, envelope, initial_params, linspace, qubit_basis, raw_coefficients};
21use crate::config::{Config, Coverage, Space, Targets};
22use crate::error::{Error, Result};
23use crate::hamiltonian::{ControlChannel, HamiltonianModel, model_from_config, upper_coupling};
24use crate::linalg::{CMat, RMat};
25use sampling::{QubitOffsets, coupling_instances, excitation_profile, rabi_instances, sample_offsets};
26
27/// The random number generator every random choice in a run is drawn from.  Seeded explicitly, so runs are
28/// reproducible and nothing needs an operating-system entropy source.
29pub type Rng = rand_chacha::ChaCha8Rng;
30
31/// The seed a run of `cfg` uses: the configured one, or one drawn from the clock.
32///
33/// The clock reading is mixed with SplitMix64, so seeds drawn a moment apart - or from a browser clock with
34/// millisecond resolution - still differ in every bit.
35pub fn resolve_seed(cfg: &Config) -> u64 {
36    cfg.seed.unwrap_or_else(|| {
37        let now = crate::time::SystemTime::now()
38            .duration_since(crate::time::UNIX_EPOCH)
39            .map(|d| d.as_nanos())
40            .unwrap_or(0);
41        let mut z = (now as u64 ^ (now >> 64) as u64).wrapping_add(0x9E37_79B9_7F4A_7C15);
42        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
43        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
44        z ^ (z >> 31)
45    })
46}
47
48/// How states evolve over one time step.
49#[derive(Clone, Debug, PartialEq)]
50pub enum Evolution {
51    /// `ψ ← U·ψ`.
52    Hilbert,
53    /// `ρ ← U·ρ·U†`.
54    Liouville,
55    /// `ρ ← U·ρ·U†`, then the Lindblad dissipator's exact channel over the step.
56    Lindblad(LindbladOps),
57}
58
59/// One batch element.
60///
61/// For state targets it evolves one initial state and scores it against its target.  For one gate
62/// ([`Targets::single_gate`]) it scores the average gate fidelity instead: in Hilbert space one element evolves the
63/// whole computational basis as the columns of `initial`; in Liouville space the elements evolve the Pauli operators,
64/// each scored against the gate's image of it, weighted so the batch mean is Nielsen's average gate fidelity.
65#[derive(Clone, Debug, PartialEq)]
66pub struct BatchElement {
67    /// Drift Hamiltonian in rad/s.
68    pub h0: CMat<f64>,
69    /// Rabi frequency per qubit in rad/s.
70    pub rabi: Vec<f64>,
71    /// What is evolved: state vectors as columns (Hilbert) or a density matrix or Pauli operator (Liouville).
72    pub initial: CMat<f64>,
73    /// What `initial` is scored against after the pulse, of the same shape.
74    pub target: CMat<f64>,
75    /// Which initial state, or which Pauli operator for a gate in Liouville space (0 in Hilbert space).
76    pub initial_index: usize,
77    /// Which drift snapshot.
78    pub snapshot: usize,
79    /// Which Rabi snapshot.
80    pub rabi_index: usize,
81}
82
83/// Everything an evaluation of the objective needs, derived from a [`Config`].
84pub struct Problem {
85    /// Number of qubits.
86    pub n_qubits: usize,
87    /// Hilbert-space dimension of the model.
88    pub dim: usize,
89    /// Number of time steps.
90    pub n_pulse: usize,
91    /// Time step in seconds: duration / steps.
92    pub dt: f64,
93    /// Pulse duration in seconds.
94    pub duration: f64,
95    /// Waveform sample times in seconds: the middle of each step, `(t + ½)·dt`.
96    pub times: Vec<f64>,
97    /// Each qubit's basis matrices.
98    pub qubits: Vec<QubitBasis>,
99    /// `exp(i·offset_q·(t − T/2))`, `n_pulse × n_qubits`.
100    pub modulation: CMat<f64>,
101    /// Control operators `H_k`.
102    pub control_ops: Vec<CMat<f64>>,
103    /// How each control amplitude is made.
104    pub channels: Vec<ControlChannel>,
105    /// The batch, ordered by initial state (or Pauli operator), then drift snapshot, then Rabi snapshot.
106    pub batch: Vec<BatchElement>,
107    /// State evolution per step.
108    pub evolution: Evolution,
109    /// Effective state space.
110    pub space: Space,
111    /// Initial optimiser parameters.
112    pub x0: Vec<f64>,
113    /// The seed every random quantity was drawn from.
114    pub seed: u64,
115    /// Target fidelity.
116    pub target_fidelity: f64,
117    /// Iteration limit.
118    pub max_iter: usize,
119    /// Optimiser name.
120    pub algorithm: String,
121    /// Initial states in the model's space, one per configured initial state; the plots start from these.
122    pub initial_states: Vec<CMat<f64>>,
123    /// Per qubit, the Pauli observables `[σx, σy, σz]` in the model's space, zero outside the computational subspace.
124    pub observables: Vec<[CMat<f64>; 3]>,
125    /// The Hamiltonian model.
126    pub model: Box<dyn HamiltonianModel>,
127    /// Maximum Rabi frequency per qubit in rad/s.
128    pub rabi_max: Vec<f64>,
129    /// Offset per qubit in rad/s.
130    pub delta: Vec<f64>,
131    /// Sweep width per qubit in rad/s.
132    pub sw: Vec<f64>,
133    /// Configured coupling (upper-triangular, rad/s, without noise); `None` for one qubit.
134    pub coupling: Option<RMat<f64>>,
135    /// Number of drift snapshots.
136    pub n_snapshots: usize,
137    /// Number of Rabi snapshots.
138    pub n_rabi: usize,
139}
140
141impl Problem {
142    /// Number of optimiser parameters.
143    pub fn n_params(&self) -> usize {
144        self.qubits.iter().map(|q| q.n_params).sum()
145    }
146
147    /// Build the problem `cfg` describes, with its own seed or one from the clock.
148    pub fn build(cfg: &Config) -> Result<Problem> {
149        Problem::build_with_seed(cfg, resolve_seed(cfg))
150    }
151
152    /// Build the problem `cfg` describes, drawing every random quantity from `seed`.
153    pub fn build_with_seed(cfg: &Config, seed: u64) -> Result<Problem> {
154        cfg.check()?;
155        let mut rng = Rng::seed_from_u64(seed);
156        let n = cfg.n_qubits();
157        let p = &cfg.parameters;
158        let two_pi = 2.0 * std::f64::consts::PI;
159        let per_qubit = |v: &Option<Vec<f64>>| -> Vec<f64> {
160            v.as_ref()
161                .map_or(vec![0.0; n], |v| v.iter().map(|x| two_pi * x).collect())
162        };
163        let scaled = |v: &[f64]| -> Vec<f64> { v.iter().map(|x| two_pi * x).collect() };
164
165        // Time grid.
166        let duration = p.pulse_duration[0];
167        let n_pulse = p.point_in_pulse[0];
168        let dt = duration / n_pulse as f64;
169        let times: Vec<f64> = (0..n_pulse).map(|t| (t as f64 + 0.5) * dt).collect();
170
171        // Initial coefficients (all qubits first, as Python draws them), then the bases.
172        let bases = p.wf_type.iter().map(|name| basis(name)).collect::<Result<Vec<_>>>()?;
173        let raw: Vec<Vec<f64>> = p.n_para.iter().map(|&k| raw_coefficients(k, &mut rng)).collect();
174        let x_grid = linspace(-1.0, 1.0, n_pulse);
175        let mut qubits = Vec::with_capacity(n);
176        let mut x0 = Vec::new();
177        for q in 0..n {
178            let env = envelope(&p.amplitude_envelope[q], &x_grid, p.amplitude_order[q])?;
179            let qb = qubit_basis(bases[q].as_ref(), &env, p.n_para[q], p.wf_mode[q], n_pulse, &mut rng)?;
180            x0.extend(initial_params(bases[q].as_ref(), &raw[q], p.wf_mode[q]));
181            qubits.push(qb);
182        }
183
184        // Rabi frequencies.
185        let rabi_max = scaled(&p.omega_r_max);
186        let rabi = rabi_instances(
187            &rabi_max,
188            &scaled(&p.sigma_omega_r_max),
189            cfg.optimization.omega_r_snapshots,
190            &mut rng,
191        );
192
193        // Offsets and excitation profiles.
194        let delta = per_qubit(&p.delta);
195        let sigma_delta = per_qubit(&p.sigma_delta);
196        let sw = scaled(&p.sw);
197        let specs: Vec<QubitOffsets> = (0..n)
198            .map(|q| QubitOffsets {
199                coverage: p.coverage[q],
200                delta: delta[q],
201                sigma: sigma_delta[q],
202                sw: sw[q],
203                bandwidth: two_pi * p.pulse_bandwidth[q],
204                ratio: p.ratio_factor[q],
205                profile_order: p.profile_order[q],
206            })
207            .collect();
208        let coupling = match (&p.j, n > 1) {
209            (Some(j), true) => Some(upper_coupling(j, n).map_err(Error::Config)?.map(|v| two_pi * v)),
210            _ => None,
211        };
212        let sigma_j = two_pi * p.sigma_j.unwrap_or(0.0);
213        // One snapshot suffices only when nothing in the drift is uncertain.
214        let fixed = p.coverage.iter().all(|&c| c == Coverage::Single)
215            && sigma_delta.iter().all(|&s| s == 0.0)
216            && (coupling.is_none() || sigma_j == 0.0);
217        let per_qubit_offsets: Vec<Vec<f64>> = if fixed {
218            delta.iter().map(|&d| vec![d]).collect()
219        } else {
220            specs
221                .iter()
222                .map(|s| sample_offsets(s, cfg.optimization.h0_snapshots, &mut rng))
223                .collect()
224        };
225        let m = per_qubit_offsets[0].len();
226        let profiles: Vec<Vec<f64>> = specs
227            .iter()
228            .zip(&per_qubit_offsets)
229            .map(|(s, o)| excitation_profile(s, o))
230            .collect();
231
232        // Couplings.
233        let couplings = coupling.as_ref().map(|j| coupling_instances(j, sigma_j, m, &mut rng));
234
235        // The model and the drifts.
236        let model = model_from_config(cfg)?;
237        let drifts = (0..m)
238            .map(|k| {
239                let offsets: Vec<f64> = per_qubit_offsets.iter().map(|o| o[k]).collect();
240                model.drift(&offsets, couplings.as_ref().map(|c| &c[k]))
241            })
242            .collect::<Result<Vec<_>>>()?;
243
244        // States and targets, computed in the qubits' space and then embedded.
245        let space = cfg.space();
246        let raw_state = |axes: &[String]| -> Result<CMat<f64>> {
247            match space {
248                Space::Hilbert => product_state(axes),
249                Space::Liouville => product_density(axes),
250            }
251        };
252        let embed = |s: &CMat<f64>| -> Result<CMat<f64>> {
253            match space {
254                Space::Hilbert => model.embed_state(s),
255                Space::Liouville => model.embed_density(s),
256            }
257        };
258        let apply = |u: &CMat<f64>, s: &CMat<f64>| -> Result<CMat<f64>> {
259            match space {
260                Space::Hilbert => u.matmul(s),
261                Space::Liouville => u.matmul(s)?.matmul(&u.adjoint()),
262            }
263        };
264        let raw_initials: Vec<CMat<f64>> = cfg.initial_states.iter().map(|a| raw_state(a)).collect::<Result<_>>()?;
265        let initial_states: Vec<CMat<f64>> = raw_initials.iter().map(&embed).collect::<Result<_>>()?;
266        // Where a target applies: a qubit is in its band where its excitation profile is 1.
267        let in_band = |q: usize, k: usize| profiles[q][k] == 1.0;
268        let everyone_in_band = |k: usize| (0..n).all(|q| in_band(q, k));
269
270        // Per initial state, what it is scored against at each snapshot: its target state, or for one gate the
271        // gate's action on the whole computational basis (see `gate_rows`).
272        let rows: Vec<Row> = match cfg.target_states.single_gate() {
273            Some(name) => {
274                let v = gate(name, n)?;
275                let id = CMat::<f64>::identity(1 << n);
276                let gates: Vec<&CMat<f64>> = (0..m).map(|k| if everyone_in_band(k) { &v } else { &id }).collect();
277                gate_rows(&gates, space, model.as_ref())?
278            }
279            None => {
280                let deg = std::f64::consts::PI / 180.0;
281                let target = |pi: usize, init: &CMat<f64>, k: usize| -> Result<CMat<f64>> {
282                    let t = match &cfg.target_states {
283                        // A product state: each qubit's target axis in its band, its initial axis elsewhere.
284                        Targets::Axis(axes) => {
285                            let per_qubit: Vec<String> = (0..n)
286                                .map(|q| {
287                                    if in_band(q, k) {
288                                        &axes[pi][q]
289                                    } else {
290                                        &cfg.initial_states[pi][q]
291                                    }
292                                })
293                                .cloned()
294                                .collect();
295                            raw_state(&per_qubit)?
296                        }
297                        Targets::Gate(names) if everyone_in_band(k) => apply(&gate(&names[pi], n)?, init)?,
298                        Targets::Gate(_) => init.clone(),
299                        Targets::PhiBeta { phi, beta } => {
300                            let angles: Vec<f64> = (0..n).map(|q| beta[pi][q] * deg * profiles[q][k]).collect();
301                            apply(&rotation(&phi[pi], &angles, n)?, init)?
302                        }
303                    };
304                    let t = embed(&t)?;
305                    if space == Space::Liouville && (t.matmul(&t)?.trace().re - 1.0).abs() > 1e-9 {
306                        return Err(Error::NotSupported(
307                            "Liouville-space fidelity needs pure targets; this target is mixed".into(),
308                        ));
309                    }
310                    Ok(t)
311                };
312                raw_initials
313                    .iter()
314                    .enumerate()
315                    .map(|(pi, init)| {
316                        Ok(Row {
317                            evolved: embed(init)?,
318                            targets: (0..m).map(|k| target(pi, init, k)).collect::<Result<_>>()?,
319                        })
320                    })
321                    .collect::<Result<_>>()?
322            }
323        };
324
325        // The batch: initial state (or Pauli operator), then drift snapshot, then Rabi snapshot.
326        let mut batch = Vec::with_capacity(rows.len() * m * rabi.len());
327        for (pi, row) in rows.into_iter().enumerate() {
328            for (k, h0) in drifts.iter().enumerate() {
329                for (r, rb) in rabi.iter().enumerate() {
330                    batch.push(BatchElement {
331                        h0: h0.clone(),
332                        rabi: rb.clone(),
333                        initial: row.evolved.clone(),
334                        target: row.targets[k].clone(),
335                        initial_index: pi,
336                        snapshot: k,
337                        rabi_index: r,
338                    });
339                }
340            }
341        }
342
343        let evolution = if cfg.is_dissipative() {
344            let (t1, t2) = (p.t1.as_deref().unwrap_or(&[]), p.t2.as_deref().unwrap_or(&[]));
345            Evolution::Lindblad(LindbladOps::new(&collapse_operators(t1, t2)?, dt)?)
346        } else if space == Space::Liouville {
347            Evolution::Liouville
348        } else {
349            Evolution::Hilbert
350        };
351
352        let offsets = scaled(&p.pulse_offset);
353        let modulation = CMat::from_fn(n_pulse, n, |t, q| {
354            C::from_polar(1.0, offsets[q] * (times[t] - duration / 2.0))
355        });
356        // Projected, zero outside the computational subspace, so leaked population reads as zero on every axis.
357        let observables = pauli_ops(n)
358            .iter()
359            .map(|o| -> Result<[CMat<f64>; 3]> {
360                Ok([
361                    model.embed_density(&o[0])?,
362                    model.embed_density(&o[1])?,
363                    model.embed_density(&o[2])?,
364                ])
365            })
366            .collect::<Result<Vec<_>>>()?;
367
368        Ok(Problem {
369            n_qubits: n,
370            dim: model.dim(),
371            n_pulse,
372            dt,
373            duration,
374            times,
375            qubits,
376            modulation,
377            control_ops: model.control_ops(),
378            channels: model.control_channels(),
379            batch,
380            evolution,
381            space,
382            x0,
383            seed,
384            target_fidelity: cfg.optimization.targ_fid,
385            max_iter: cfg.optimization.max_iter,
386            algorithm: cfg.optimization.algorithm.clone(),
387            initial_states,
388            observables,
389            model,
390            rabi_max,
391            delta,
392            sw,
393            coupling,
394            n_snapshots: m,
395            n_rabi: rabi.len(),
396        })
397    }
398}
399
400/// One row of the batch before the drift and Rabi snapshots multiply it.
401struct Row {
402    /// What is evolved.
403    evolved: CMat<f64>,
404    /// Per drift snapshot, what it is scored against.
405    targets: Vec<CMat<f64>>,
406}
407
408/// The rows that score the average gate fidelity to `gates[k]` at drift snapshot `k`.
409///
410/// Hilbert space: one row evolving the embedded computational basis `P`, scored against `P·W` by
411/// `(‖M‖² + |Tr M|²)/(d(d+1))` with `M = (P·W)†·U·P`, which counts leakage (Pedersen et al. 2007).
412///
413/// Liouville space: a row per Pauli string `P_j` (the identity first), scored by `Re Tr(σ_j·Λ(P_j))` against the
414/// scaled image `σ_j = c_j·W·P_j·W†`.  Nielsen's formula, generalised to maps that lose population,
415/// `F = (d·x₀ + Σ_j x_j)/(d²·(d + 1))` with `x_j = Re Tr(W·P_j·W†·Λ(P_j))`, is then the mean over the `d²` rows with
416/// `c₀ = 1` and `c_j = 1/(d + 1)` otherwise.
417fn gate_rows(gates: &[&CMat<f64>], space: Space, model: &dyn HamiltonianModel) -> Result<Vec<Row>> {
418    let d = gates.first().map_or(1, |g| g.rows);
419    match space {
420        Space::Hilbert => Ok(vec![Row {
421            evolved: model.embed_state(&CMat::identity(d))?,
422            targets: gates.iter().map(|w| model.embed_state(w)).collect::<Result<_>>()?,
423        }]),
424        Space::Liouville => pauli_strings(d.trailing_zeros() as usize)
425            .iter()
426            .enumerate()
427            .map(|(j, u)| {
428                let weight = if j == 0 { 1.0 } else { 1.0 / (d + 1) as f64 };
429                let targets = gates
430                    .iter()
431                    .map(|w| {
432                        Ok(model
433                            .embed_density(&w.matmul(u)?.matmul(&w.adjoint())?)?
434                            .scale_re(weight))
435                    })
436                    .collect::<Result<_>>()?;
437                Ok(Row {
438                    evolved: model.embed_density(u)?,
439                    targets,
440                })
441            })
442            .collect(),
443    }
444}
445
446/// The `4ⁿ` Pauli strings on `n` qubits, the identity first: an orthogonal basis, `Tr(P_i·P_j) = 2ⁿ·δ_ij`.
447fn pauli_strings(n: usize) -> Vec<CMat<f64>> {
448    let [x, y, z] = paulis();
449    let single = [CMat::identity(2), x, y, z];
450    (0..1usize << (2 * n))
451        .map(|i| {
452            (0..n)
453                .rev()
454                .fold(CMat::identity(1), |acc, q| acc.kron(&single[(i >> (2 * q)) & 3]))
455        })
456        .collect()
457}
458
459#[cfg(test)]
460mod tests;