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.
6
7mod dissipation;
8mod sampling;
9mod states;
10
11pub use dissipation::collapse_operators;
12pub use states::{embed, gate, gate_names, pauli_ops, paulis, product_density, product_state, rotation, spin_ops};
13
14use rand::SeedableRng;
15
16use crate::autodiff::{C, LindbladOps};
17use crate::basis::{QubitBasis, basis, envelope, initial_params, linspace, qubit_basis, raw_coefficients};
18use crate::config::{Config, Coverage, Space, Targets};
19use crate::error::{Error, Result};
20use crate::hamiltonian::{ControlChannel, HamiltonianModel, model_from_config, upper_coupling};
21use crate::linalg::{CMat, RMat};
22use sampling::{QubitOffsets, coupling_instances, excitation_profile, rabi_instances, sample_offsets};
23
24/// The random number generator every random choice in a run is drawn from.  Seeded explicitly, so runs are
25/// reproducible and nothing needs an operating-system entropy source.
26pub type Rng = rand_chacha::ChaCha8Rng;
27
28/// The seed a run of `cfg` uses: the configured one, or one drawn from the clock.
29///
30/// The clock reading is mixed with SplitMix64, so seeds drawn a moment apart - or from a browser clock with
31/// millisecond resolution - still differ in every bit.
32pub fn resolve_seed(cfg: &Config) -> u64 {
33    cfg.seed.unwrap_or_else(|| {
34        let now = crate::time::SystemTime::now()
35            .duration_since(crate::time::UNIX_EPOCH)
36            .map(|d| d.as_nanos())
37            .unwrap_or(0);
38        let mut z = (now as u64 ^ (now >> 64) as u64).wrapping_add(0x9E37_79B9_7F4A_7C15);
39        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
40        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
41        z ^ (z >> 31)
42    })
43}
44
45/// How states evolve over one time step.
46#[derive(Clone, Debug, PartialEq)]
47pub enum Evolution {
48    /// `ψ ← U·ψ`.
49    Hilbert,
50    /// `ρ ← U·ρ·U†`.
51    Liouville,
52    /// `ρ ← U·ρ·U†`, then an explicit Euler step of the Lindblad dissipator.
53    Lindblad(LindbladOps),
54}
55
56/// One batch element.
57#[derive(Clone, Debug, PartialEq)]
58pub struct BatchElement {
59    /// Drift Hamiltonian in rad/s.
60    pub h0: CMat<f64>,
61    /// Rabi frequency per qubit in rad/s.
62    pub rabi: Vec<f64>,
63    /// Initial state: a column vector (Hilbert) or a density matrix (Liouville).
64    pub initial: CMat<f64>,
65    /// Target, of the same kind as `initial`.
66    pub target: CMat<f64>,
67    /// Which initial state.
68    pub initial_index: usize,
69    /// Which drift snapshot.
70    pub snapshot: usize,
71    /// Which Rabi snapshot.
72    pub rabi_index: usize,
73}
74
75/// Everything an evaluation of the objective needs, derived from a [`Config`].
76pub struct Problem {
77    /// Number of qubits.
78    pub n_qubits: usize,
79    /// Hilbert-space dimension of the model.
80    pub dim: usize,
81    /// Number of time steps.
82    pub n_pulse: usize,
83    /// Time step in seconds: duration / steps.
84    pub dt: f64,
85    /// Pulse duration in seconds.
86    pub duration: f64,
87    /// Time grid in seconds, `linspace(ε, T, n_pulse)` as in Python.
88    pub times: Vec<f64>,
89    /// Each qubit's basis matrices.
90    pub qubits: Vec<QubitBasis>,
91    /// `exp(i·offset_q·(t − T/2))`, `n_pulse × n_qubits`.
92    pub modulation: CMat<f64>,
93    /// Control operators `H_k`.
94    pub control_ops: Vec<CMat<f64>>,
95    /// How each control amplitude is made.
96    pub channels: Vec<ControlChannel>,
97    /// The batch, ordered by initial state, then drift snapshot, then Rabi snapshot.
98    pub batch: Vec<BatchElement>,
99    /// State evolution per step.
100    pub evolution: Evolution,
101    /// Effective state space.
102    pub space: Space,
103    /// Initial optimiser parameters.
104    pub x0: Vec<f64>,
105    /// The seed every random quantity was drawn from.
106    pub seed: u64,
107    /// Target fidelity.
108    pub target_fidelity: f64,
109    /// Iteration limit.
110    pub max_iter: usize,
111    /// Optimiser name.
112    pub algorithm: String,
113    /// Initial states in the model's space, one per configured initial state.
114    pub initial_states: Vec<CMat<f64>>,
115    /// Per qubit, the Pauli observables `[σx, σy, σz]` in the model's space.
116    pub observables: Vec<[CMat<f64>; 3]>,
117    /// The Hamiltonian model.
118    pub model: Box<dyn HamiltonianModel>,
119    /// Maximum Rabi frequency per qubit in rad/s.
120    pub rabi_max: Vec<f64>,
121    /// Offset per qubit in rad/s.
122    pub delta: Vec<f64>,
123    /// Sweep width per qubit in rad/s.
124    pub sw: Vec<f64>,
125    /// Configured coupling (upper-triangular, rad/s, without noise); `None` for one qubit.
126    pub coupling: Option<RMat<f64>>,
127    /// Number of drift snapshots.
128    pub n_snapshots: usize,
129    /// Number of Rabi snapshots.
130    pub n_rabi: usize,
131}
132
133impl Problem {
134    /// Number of optimiser parameters.
135    pub fn n_params(&self) -> usize {
136        self.qubits.iter().map(|q| q.n_params).sum()
137    }
138
139    /// Build the problem `cfg` describes, with its own seed or one from the clock.
140    pub fn build(cfg: &Config) -> Result<Problem> {
141        Problem::build_with_seed(cfg, resolve_seed(cfg))
142    }
143
144    /// Build the problem `cfg` describes, drawing every random quantity from `seed`.
145    pub fn build_with_seed(cfg: &Config, seed: u64) -> Result<Problem> {
146        cfg.check()?;
147        let mut rng = Rng::seed_from_u64(seed);
148        let n = cfg.n_qubits();
149        let p = &cfg.parameters;
150        let two_pi = 2.0 * std::f64::consts::PI;
151        let per_qubit = |v: &Option<Vec<f64>>| -> Vec<f64> {
152            v.as_ref()
153                .map_or(vec![0.0; n], |v| v.iter().map(|x| two_pi * x).collect())
154        };
155        let scaled = |v: &[f64]| -> Vec<f64> { v.iter().map(|x| two_pi * x).collect() };
156
157        // Time grid.
158        let duration = p.pulse_duration[0];
159        let n_pulse = p.point_in_pulse[0];
160        let dt = duration / n_pulse as f64;
161        let times = linspace(f64::EPSILON, duration, n_pulse);
162
163        // Initial coefficients (all qubits first, as Python draws them), then the bases.
164        let bases = p.wf_type.iter().map(|name| basis(name)).collect::<Result<Vec<_>>>()?;
165        let raw: Vec<Vec<f64>> = p.n_para.iter().map(|&k| raw_coefficients(k, &mut rng)).collect();
166        let x_grid = linspace(-1.0, 1.0, n_pulse);
167        let mut qubits = Vec::with_capacity(n);
168        let mut x0 = Vec::new();
169        for q in 0..n {
170            let env = envelope(&p.amplitude_envelope[q], &x_grid, p.amplitude_order[q])?;
171            let qb = qubit_basis(bases[q].as_ref(), &env, p.n_para[q], p.wf_mode[q], n_pulse, &mut rng)?;
172            x0.extend(initial_params(bases[q].as_ref(), &raw[q], p.wf_mode[q]));
173            qubits.push(qb);
174        }
175
176        // Rabi frequencies.
177        let rabi_max = scaled(&p.omega_r_max);
178        let rabi = rabi_instances(
179            &rabi_max,
180            &scaled(&p.sigma_omega_r_max),
181            cfg.optimization.omega_r_snapshots,
182            &mut rng,
183        );
184
185        // Offsets and excitation profiles.
186        let delta = per_qubit(&p.delta);
187        let sigma_delta = per_qubit(&p.sigma_delta);
188        let sw = scaled(&p.sw);
189        let specs: Vec<QubitOffsets> = (0..n)
190            .map(|q| QubitOffsets {
191                coverage: p.coverage[q],
192                delta: delta[q],
193                sigma: sigma_delta[q],
194                sw: sw[q],
195                bandwidth: two_pi * p.pulse_bandwidth[q],
196                ratio: p.ratio_factor[q],
197                profile_order: p.profile_order[q],
198            })
199            .collect();
200        let fixed = p.coverage.iter().all(|&c| c == Coverage::Single) && sigma_delta.iter().all(|&s| s == 0.0);
201        let per_qubit_offsets: Vec<Vec<f64>> = if fixed {
202            delta.iter().map(|&d| vec![d]).collect()
203        } else {
204            specs
205                .iter()
206                .map(|s| sample_offsets(s, cfg.optimization.h0_snapshots, &mut rng))
207                .collect()
208        };
209        let m = per_qubit_offsets[0].len();
210        let profiles: Vec<Vec<f64>> = specs
211            .iter()
212            .zip(&per_qubit_offsets)
213            .map(|(s, o)| excitation_profile(s, o))
214            .collect();
215
216        // Couplings.
217        let coupling = match (&p.j, n > 1) {
218            (Some(j), true) => Some(upper_coupling(j, n).map_err(Error::Config)?.map(|v| two_pi * v)),
219            _ => None,
220        };
221        let sigma_j = two_pi * p.sigma_j.unwrap_or(0.0);
222        let couplings = coupling.as_ref().map(|j| coupling_instances(j, sigma_j, m, &mut rng));
223
224        // The model and the drifts.
225        let model = model_from_config(cfg)?;
226        let drifts = (0..m)
227            .map(|k| {
228                let offsets: Vec<f64> = per_qubit_offsets.iter().map(|o| o[k]).collect();
229                model.drift(&offsets, couplings.as_ref().map(|c| &c[k]))
230            })
231            .collect::<Result<Vec<_>>>()?;
232
233        // States and targets, computed in the qubits' space and then embedded.
234        let space = cfg.space();
235        let raw_state = |axes: &[String]| -> Result<CMat<f64>> {
236            match space {
237                Space::Hilbert => product_state(axes),
238                Space::Liouville => product_density(axes),
239            }
240        };
241        let embed = |s: &CMat<f64>| -> Result<CMat<f64>> {
242            match space {
243                Space::Hilbert => model.embed_state(s),
244                Space::Liouville => model.embed_density(s),
245            }
246        };
247        let apply = |u: &CMat<f64>, s: &CMat<f64>| -> Result<CMat<f64>> {
248            match space {
249                Space::Hilbert => u.matmul(s),
250                Space::Liouville => u.matmul(s)?.matmul(&u.adjoint()),
251            }
252        };
253        let raw_initials: Vec<CMat<f64>> = cfg.initial_states.iter().map(|a| raw_state(a)).collect::<Result<_>>()?;
254        let initial_states: Vec<CMat<f64>> = raw_initials.iter().map(&embed).collect::<Result<_>>()?;
255        let deg = std::f64::consts::PI / 180.0;
256        // targets[p][k]: what initial state p should become at snapshot k.
257        let mut targets: Vec<Vec<CMat<f64>>> = Vec::with_capacity(raw_initials.len());
258        for (pi, init) in raw_initials.iter().enumerate() {
259            let mut row = Vec::with_capacity(m);
260            for (k, &first) in profiles[0].iter().enumerate() {
261                let applies = first == 1.0;
262                let t = match &cfg.target_states {
263                    Targets::Axis(axes) if applies => raw_state(&axes[pi])?,
264                    Targets::Gate(names) if applies => apply(&gate(&names[pi], n)?, init)?,
265                    Targets::PhiBeta { phi, beta } => {
266                        let angles: Vec<f64> = (0..n).map(|q| beta[pi][q] * deg * profiles[q][k]).collect();
267                        apply(&rotation(&phi[pi], &angles, n)?, init)?
268                    }
269                    _ => init.clone(),
270                };
271                row.push(embed(&t)?);
272            }
273            targets.push(row);
274        }
275        if space == Space::Liouville {
276            for t in targets.iter().flatten() {
277                let purity = t.matmul(t)?.trace().re;
278                if (purity - 1.0).abs() > 1e-9 {
279                    return Err(Error::NotSupported(
280                        "Liouville-space fidelity needs pure targets; this target is mixed".into(),
281                    ));
282                }
283            }
284        }
285
286        // The batch: initial state, then drift snapshot, then Rabi snapshot.
287        let mut batch = Vec::with_capacity(initial_states.len() * m * rabi.len());
288        for (pi, init) in initial_states.iter().enumerate() {
289            for (k, h0) in drifts.iter().enumerate() {
290                for (r, rb) in rabi.iter().enumerate() {
291                    batch.push(BatchElement {
292                        h0: h0.clone(),
293                        rabi: rb.clone(),
294                        initial: init.clone(),
295                        target: targets[pi][k].clone(),
296                        initial_index: pi,
297                        snapshot: k,
298                        rabi_index: r,
299                    });
300                }
301            }
302        }
303
304        let evolution = if cfg.is_dissipative() {
305            let (t1, t2) = (p.t1.as_deref().unwrap_or(&[]), p.t2.as_deref().unwrap_or(&[]));
306            Evolution::Lindblad(LindbladOps::new(&collapse_operators(t1, t2)?)?)
307        } else if space == Space::Liouville {
308            Evolution::Liouville
309        } else {
310            Evolution::Hilbert
311        };
312
313        let offsets = scaled(&p.pulse_offset);
314        let modulation = CMat::from_fn(n_pulse, n, |t, q| {
315            C::from_polar(1.0, offsets[q] * (times[t] - duration / 2.0))
316        });
317        let observables = pauli_ops(n)
318            .iter()
319            .map(|o| -> Result<[CMat<f64>; 3]> {
320                Ok([
321                    model.embed_gate(&o[0])?,
322                    model.embed_gate(&o[1])?,
323                    model.embed_gate(&o[2])?,
324                ])
325            })
326            .collect::<Result<Vec<_>>>()?;
327
328        Ok(Problem {
329            n_qubits: n,
330            dim: model.dim(),
331            n_pulse,
332            dt,
333            duration,
334            times,
335            qubits,
336            modulation,
337            control_ops: model.control_ops(),
338            channels: model.control_channels(),
339            batch,
340            evolution,
341            space,
342            x0,
343            seed,
344            target_fidelity: cfg.optimization.targ_fid,
345            max_iter: cfg.optimization.max_iter,
346            algorithm: cfg.optimization.algorithm.clone(),
347            initial_states,
348            observables,
349            model,
350            rabi_max,
351            delta,
352            sw,
353            coupling,
354            n_snapshots: m,
355            n_rabi: rabi.len(),
356        })
357    }
358}
359
360#[cfg(test)]
361mod tests;