Skip to main content

ctrl_freeq/config/
mod.rs

1//! The optimisation problem as the Python package writes it: the same JSON schema, field for field.
2//!
3//! Frequencies are in Hz and times in seconds, exactly as in the Python configuration files; the setup converts
4//! them to angular frequencies.  Per-qubit settings are parallel arrays indexed by qubit.  One field is new: an
5//! optional top-level `"seed"`, which makes the random parts of a run - the initial coefficients and the sampled
6//! offsets - reproducible.  The Python package ignores it.
7
8mod examples;
9
10pub use examples::examples;
11
12use serde::de::{self, Deserializer};
13use serde::ser::{SerializeMap, Serializer};
14use serde::{Deserialize, Serialize};
15
16use crate::error::{Error, Result};
17
18/// A complete optimisation problem.
19#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
20pub struct Config {
21    /// The physical platform: `spin_chain`, `superconducting` or `duffing_transmon`.  Absent means the Python
22    /// package's original spin-chain path, whose default coupling is `Z`.
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub hamiltonian_type: Option<String>,
25    /// One name per qubit; the count sets the number of qubits.
26    pub qubits: Vec<String>,
27    /// `cpu` or `gpu`.  This version always computes on the CPU.
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub compute_resource: Option<String>,
30    /// Number of CPU threads to use natively.  Absent means all of them.
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    pub cpu_cores: Option<usize>,
33    /// Seed for every random choice in a run.  Absent means one is drawn from the clock.
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub seed: Option<u64>,
36    /// Physical and pulse parameters.
37    pub parameters: Parameters,
38    /// Initial states: for each, one axis (`Z`, `-Z`, `X`, `-X`, `Y`, `-Y`) per qubit.
39    pub initial_states: Vec<Vec<String>>,
40    /// What each initial state should become.
41    pub target_states: Targets,
42    /// Optimiser settings.
43    pub optimization: Optimization,
44}
45
46/// Physical and pulse parameters.  Arrays have one entry per qubit unless noted.
47#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
48pub struct Parameters {
49    /// Offset (chemical shift, detuning) per qubit in Hz.  Absent means zero.
50    #[serde(rename = "Delta", default, skip_serializing_if = "Option::is_none")]
51    pub delta: Option<Vec<f64>>,
52    /// Standard deviation of the offset in Hz.  Absent means zero.
53    #[serde(rename = "sigma_Delta", default, skip_serializing_if = "Option::is_none")]
54    pub sigma_delta: Option<Vec<f64>>,
55    /// Maximum Rabi frequency (drive amplitude) in Hz.
56    #[serde(rename = "Omega_R_max")]
57    pub omega_r_max: Vec<f64>,
58    /// Standard deviation of the Rabi frequency in Hz.
59    #[serde(rename = "sigma_Omega_R_max")]
60    pub sigma_omega_r_max: Vec<f64>,
61    /// Pulse duration in seconds.  Only the first entry is used, as in Python.
62    pub pulse_duration: Vec<f64>,
63    /// Number of time points in the pulse.  Only the first entry is used, as in Python.
64    pub point_in_pulse: Vec<usize>,
65    /// Basis per qubit: `cheb`, `leg`, `poly`, `fou`, `hermite`, `gegen`, `chirp` or `random`.
66    pub wf_type: Vec<String>,
67    /// Waveform parametrisation per qubit.
68    pub wf_mode: Vec<WaveformMode>,
69    /// Amplitude envelope per qubit: `gn`, `hs` or `quad`.
70    pub amplitude_envelope: Vec<String>,
71    /// Envelope order per qubit.
72    pub amplitude_order: Vec<u32>,
73    /// Offset coverage per qubit.
74    pub coverage: Vec<Coverage>,
75    /// Sweep width (offset range) in Hz.
76    pub sw: Vec<f64>,
77    /// Carrier offset of the pulse in Hz.
78    pub pulse_offset: Vec<f64>,
79    /// Excitation bandwidth in Hz, for the selective coverages: the width of the band for `selective`, and for
80    /// `band_selective` the full width at half maximum of the profile the target rotation angle is scaled by
81    /// (which is not the excitation the optimised pulse achieves).
82    pub pulse_bandwidth: Vec<f64>,
83    /// Fraction of offsets sampled outside the band, for the selective coverages.
84    pub ratio_factor: Vec<f64>,
85    /// Super-Gaussian order of the band-selective profile; at least 1.  Higher orders have flatter tops and
86    /// steeper edges, with the same width at half maximum.
87    pub profile_order: Vec<u32>,
88    /// Number of basis coefficients per qubit, as the user sets it.
89    pub n_para: Vec<usize>,
90    /// Coupling matrix in Hz, `n × n`; upper, lower or symmetric.  Absent means zero.
91    #[serde(rename = "J", default, skip_serializing_if = "Option::is_none")]
92    pub j: Option<Vec<Vec<f64>>>,
93    /// Coupling type: `Z`, `XY` or `XYZ` for spin chains; `XY`, `ZZ` or `XY+ZZ` for superconducting qubits.
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    pub coupling_type: Option<String>,
96    /// Standard deviation of the non-zero couplings in Hz.
97    #[serde(rename = "sigma_J", default, skip_serializing_if = "Option::is_none")]
98    pub sigma_j: Option<f64>,
99    /// Amplitude-damping time T1 in seconds, dissipative mode only.
100    #[serde(rename = "T1", default, skip_serializing_if = "Option::is_none")]
101    pub t1: Option<Vec<f64>>,
102    /// Coherence time T2 in seconds, dissipative mode only.
103    #[serde(rename = "T2", default, skip_serializing_if = "Option::is_none")]
104    pub t2: Option<Vec<f64>>,
105    /// Transmon anharmonicities in Hz (superconducting and Duffing models).
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub anharmonicities: Option<Vec<f64>>,
108    /// Calibrated static ZZ coupling matrix in Hz (superconducting model).
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub zz_crosstalk: Option<Vec<Vec<f64>>>,
111    /// AC Stark shift coefficients, dimensionless (superconducting model).
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub stark_shift_coeffs: Option<Vec<f64>>,
114}
115
116/// Optimiser settings.
117#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
118pub struct Optimization {
119    /// State space.
120    pub space: Space,
121    /// Whether T1/T2 relaxation is included.  Absent means non-dissipative.
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    pub dissipation_mode: Option<Dissipation>,
124    /// Number of sampled drift Hamiltonians (offsets and couplings).
125    #[serde(rename = "H0_snapshots")]
126    pub h0_snapshots: usize,
127    /// Number of sampled Rabi frequencies.
128    #[serde(rename = "Omega_R_snapshots")]
129    pub omega_r_snapshots: usize,
130    /// Optimiser name; see [`optimizer_names`](crate::optim::optimizer_names).
131    pub algorithm: String,
132    /// Iteration limit.  For derivative-free optimisers an iteration is one function evaluation.
133    pub max_iter: usize,
134    /// Target fidelity; the run stops once fidelity minus penalty reaches it.
135    pub targ_fid: f64,
136}
137
138/// State space.
139#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
140#[serde(rename_all = "lowercase")]
141pub enum Space {
142    /// State vectors.
143    Hilbert,
144    /// Density matrices.
145    Liouville,
146}
147
148/// Whether relaxation is modelled.
149#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
150pub enum Dissipation {
151    /// Unitary evolution only.
152    #[serde(rename = "non-dissipative")]
153    NonDissipative,
154    /// Lindblad evolution with T1/T2; forces Liouville space.
155    #[serde(rename = "dissipative")]
156    Dissipative,
157}
158
159/// How a qubit's waveform is parametrised.
160#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
161pub enum WaveformMode {
162    /// Two basis expansions for the x and y quadratures.
163    #[serde(rename = "cart")]
164    Cart,
165    /// Two basis expansions for amplitude and phase.
166    #[serde(rename = "polar")]
167    Polar,
168    /// A fixed envelope scaled by one amplitude parameter, and a basis expansion for the phase.
169    #[serde(rename = "polar_phase")]
170    PolarPhase,
171}
172
173impl WaveformMode {
174    /// Every mode, in the order the interface lists them.
175    pub const ALL: [WaveformMode; 3] = [WaveformMode::Cart, WaveformMode::Polar, WaveformMode::PolarPhase];
176
177    /// The JSON name.
178    pub fn name(self) -> &'static str {
179        match self {
180            WaveformMode::Cart => "cart",
181            WaveformMode::Polar => "polar",
182            WaveformMode::PolarPhase => "polar_phase",
183        }
184    }
185}
186
187/// How the offsets of a qubit are sampled.
188#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
189#[serde(rename_all = "snake_case")]
190pub enum Coverage {
191    /// Normally distributed about the offset.
192    Single,
193    /// Uniform across the sweep width.
194    Broadband,
195    /// Inside the band normally distributed, outside uniform; the target applies only inside the band.
196    Selective,
197    /// Inside and outside the band uniform; the target follows a super-Gaussian profile.
198    BandSelective,
199}
200
201impl Coverage {
202    /// Every coverage, in the order the interface lists them.
203    pub const ALL: [Coverage; 4] = [
204        Coverage::Single,
205        Coverage::Broadband,
206        Coverage::Selective,
207        Coverage::BandSelective,
208    ];
209
210    /// The JSON name.
211    pub fn name(self) -> &'static str {
212        match self {
213            Coverage::Single => "single",
214            Coverage::Broadband => "broadband",
215            Coverage::Selective => "selective",
216            Coverage::BandSelective => "band_selective",
217        }
218    }
219}
220
221/// What each initial state should become.
222#[derive(Clone, Debug, PartialEq)]
223pub enum Targets {
224    /// A product state, one axis per qubit, per initial state.
225    Axis(Vec<Vec<String>>),
226    /// A gate name per initial state; see [`Targets::single_gate`] for what one name for every state means.
227    Gate(Vec<String>),
228    /// A rotation about an axis per qubit (`x`, `-x`, `y`, `-y`, `z`, `-z`) by an angle in degrees, per initial state.
229    PhiBeta {
230        /// Rotation axes.
231        phi: Vec<Vec<String>>,
232        /// Rotation angles in degrees.
233        beta: Vec<Vec<f64>>,
234    },
235}
236
237impl Targets {
238    /// The JSON key naming the method: `Axis`, `Gate` or `Phi`.
239    pub fn method(&self) -> &'static str {
240        match self {
241            Targets::Axis(_) => "Axis",
242            Targets::Gate(_) => "Gate",
243            Targets::PhiBeta { .. } => "Phi",
244        }
245    }
246
247    /// Number of target entries.
248    pub fn len(&self) -> usize {
249        match self {
250            Targets::Axis(v) => v.len(),
251            Targets::Gate(v) => v.len(),
252            Targets::PhiBeta { phi, .. } => phi.len(),
253        }
254    }
255
256    /// Whether there are no target entries.
257    pub fn is_empty(&self) -> bool {
258        self.len() == 0
259    }
260
261    /// The gate every initial state names, when they all name the same one.  Such a target asks for the gate
262    /// itself, scored by its average gate fidelity over the computational basis; different gates for different
263    /// initial states ask for each state to reach its gate's image.
264    pub fn single_gate(&self) -> Option<&str> {
265        match self {
266            Targets::Gate(names) => {
267                // By canonical name, so that `CNOT` and `CX` are the one gate they describe.
268                let first = crate::setup::canonical_gate(names.first()?);
269                names
270                    .iter()
271                    .all(|n| crate::setup::canonical_gate(n) == first)
272                    .then_some(first)
273            }
274            _ => None,
275        }
276    }
277}
278
279impl Serialize for Targets {
280    fn serialize<S: Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
281        match self {
282            Targets::Axis(v) => {
283                let mut m = s.serialize_map(Some(1))?;
284                m.serialize_entry("Axis", v)?;
285                m.end()
286            }
287            Targets::Gate(v) => {
288                let mut m = s.serialize_map(Some(1))?;
289                m.serialize_entry("Gate", v)?;
290                m.end()
291            }
292            Targets::PhiBeta { phi, beta } => {
293                let mut m = s.serialize_map(Some(2))?;
294                m.serialize_entry("Phi", phi)?;
295                m.serialize_entry("Beta", beta)?;
296                m.end()
297            }
298        }
299    }
300}
301
302/// The raw target map.  The Python GUI can write every key, with nulls for the unused ones.
303#[derive(Deserialize)]
304struct RawTargets {
305    #[serde(rename = "Axis", default)]
306    axis: Option<Vec<Option<Vec<String>>>>,
307    #[serde(rename = "Gate", default)]
308    gate: Option<Vec<Option<String>>>,
309    #[serde(rename = "Phi", default)]
310    phi: Option<Vec<Option<Vec<String>>>>,
311    #[serde(rename = "Beta", default)]
312    beta: Option<Vec<Option<Vec<f64>>>>,
313}
314
315/// The entries of a list if it is present, non-empty and has no nulls.
316fn complete<T>(v: Option<Vec<Option<T>>>) -> Option<Vec<T>> {
317    let v = v?;
318    if v.is_empty() {
319        return None;
320    }
321    v.into_iter().collect()
322}
323
324impl<'de> Deserialize<'de> for Targets {
325    fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
326        let raw = RawTargets::deserialize(d)?;
327        if let Some(axis) = complete(raw.axis) {
328            return Ok(Targets::Axis(axis));
329        }
330        if let Some(gate) = complete(raw.gate) {
331            return Ok(Targets::Gate(gate));
332        }
333        if let (Some(phi), Some(beta)) = (complete(raw.phi), complete(raw.beta)) {
334            return Ok(Targets::PhiBeta { phi, beta });
335        }
336        Err(de::Error::custom(
337            "target_states needs a complete \"Axis\", \"Gate\", or \"Phi\" and \"Beta\" list",
338        ))
339    }
340}
341
342/// Axis names for states.
343pub const STATE_AXES: [&str; 6] = ["Z", "-Z", "X", "-X", "Y", "-Y"];
344/// Axis names for rotations.
345pub const ROTATION_AXES: [&str; 6] = ["x", "-x", "y", "-y", "z", "-z"];
346/// Hamiltonian model names.
347pub const HAMILTONIAN_TYPES: [&str; 3] = ["spin_chain", "superconducting", "duffing_transmon"];
348
349impl Config {
350    /// Parse a configuration.  Only the JSON syntax and field types are checked; see [`validate`](Self::validate).
351    pub fn from_json(json: &str) -> Result<Config> {
352        serde_json::from_str(json).map_err(|e| Error::Config(e.to_string()))
353    }
354
355    /// Serialise as pretty-printed JSON in the Python schema.
356    pub fn to_json(&self) -> String {
357        serde_json::to_string_pretty(self).expect("a Config always serialises")
358    }
359
360    /// Number of qubits.
361    pub fn n_qubits(&self) -> usize {
362        self.qubits.len()
363    }
364
365    /// Whether T1/T2 relaxation is on.
366    pub fn is_dissipative(&self) -> bool {
367        self.optimization.dissipation_mode == Some(Dissipation::Dissipative)
368    }
369
370    /// The effective state space: dissipative runs are always in Liouville space.
371    pub fn space(&self) -> Space {
372        if self.is_dissipative() {
373            Space::Liouville
374        } else {
375            self.optimization.space
376        }
377    }
378
379    /// Every problem with this configuration, as sentences naming the field.  Empty means it can run.
380    pub fn validate(&self) -> Vec<String> {
381        validate::validate(self)
382    }
383
384    /// [`validate`](Self::validate) as a `Result`.
385    pub fn check(&self) -> Result<()> {
386        let problems = self.validate();
387        if problems.is_empty() {
388            Ok(())
389        } else {
390            Err(Error::Config(problems.join("; ")))
391        }
392    }
393}
394
395mod validate;