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.
80    pub pulse_bandwidth: Vec<f64>,
81    /// Fraction of offsets sampled outside the band, for the selective coverages.
82    pub ratio_factor: Vec<f64>,
83    /// Super-Gaussian order of the band-selective profile.
84    pub profile_order: Vec<u32>,
85    /// Number of basis coefficients per qubit, as the user sets it.
86    pub n_para: Vec<usize>,
87    /// Coupling matrix in Hz, `n × n`; upper, lower or symmetric.  Absent means zero.
88    #[serde(rename = "J", default, skip_serializing_if = "Option::is_none")]
89    pub j: Option<Vec<Vec<f64>>>,
90    /// Coupling type: `Z`, `XY` or `XYZ` for spin chains; `XY`, `ZZ` or `XY+ZZ` for superconducting qubits.
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub coupling_type: Option<String>,
93    /// Standard deviation of the non-zero couplings in Hz.
94    #[serde(rename = "sigma_J", default, skip_serializing_if = "Option::is_none")]
95    pub sigma_j: Option<f64>,
96    /// Amplitude-damping time T1 in seconds, dissipative mode only.
97    #[serde(rename = "T1", default, skip_serializing_if = "Option::is_none")]
98    pub t1: Option<Vec<f64>>,
99    /// Coherence time T2 in seconds, dissipative mode only.
100    #[serde(rename = "T2", default, skip_serializing_if = "Option::is_none")]
101    pub t2: Option<Vec<f64>>,
102    /// Transmon anharmonicities in Hz (superconducting and Duffing models).
103    #[serde(default, skip_serializing_if = "Option::is_none")]
104    pub anharmonicities: Option<Vec<f64>>,
105    /// Calibrated static ZZ coupling matrix in Hz (superconducting model).
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub zz_crosstalk: Option<Vec<Vec<f64>>>,
108    /// AC Stark shift coefficients, dimensionless (superconducting model).
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub stark_shift_coeffs: Option<Vec<f64>>,
111}
112
113/// Optimiser settings.
114#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
115pub struct Optimization {
116    /// State space.
117    pub space: Space,
118    /// Whether T1/T2 relaxation is included.  Absent means non-dissipative.
119    #[serde(default, skip_serializing_if = "Option::is_none")]
120    pub dissipation_mode: Option<Dissipation>,
121    /// Number of sampled drift Hamiltonians (offsets and couplings).
122    #[serde(rename = "H0_snapshots")]
123    pub h0_snapshots: usize,
124    /// Number of sampled Rabi frequencies.
125    #[serde(rename = "Omega_R_snapshots")]
126    pub omega_r_snapshots: usize,
127    /// Optimiser name; see [`optimizer_names`](crate::optim::optimizer_names).
128    pub algorithm: String,
129    /// Iteration limit.  For derivative-free optimisers an iteration is one function evaluation.
130    pub max_iter: usize,
131    /// Target fidelity; the run stops once fidelity minus penalty reaches it.
132    pub targ_fid: f64,
133}
134
135/// State space.
136#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
137#[serde(rename_all = "lowercase")]
138pub enum Space {
139    /// State vectors.
140    Hilbert,
141    /// Density matrices.
142    Liouville,
143}
144
145/// Whether relaxation is modelled.
146#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
147pub enum Dissipation {
148    /// Unitary evolution only.
149    #[serde(rename = "non-dissipative")]
150    NonDissipative,
151    /// Lindblad evolution with T1/T2; forces Liouville space.
152    #[serde(rename = "dissipative")]
153    Dissipative,
154}
155
156/// How a qubit's waveform is parametrised.
157#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
158pub enum WaveformMode {
159    /// Two basis expansions for the x and y quadratures.
160    #[serde(rename = "cart")]
161    Cart,
162    /// Two basis expansions for amplitude and phase.
163    #[serde(rename = "polar")]
164    Polar,
165    /// A fixed envelope scaled by one amplitude parameter, and a basis expansion for the phase.
166    #[serde(rename = "polar_phase")]
167    PolarPhase,
168}
169
170impl WaveformMode {
171    /// Every mode, in the order the interface lists them.
172    pub const ALL: [WaveformMode; 3] = [WaveformMode::Cart, WaveformMode::Polar, WaveformMode::PolarPhase];
173
174    /// The JSON name.
175    pub fn name(self) -> &'static str {
176        match self {
177            WaveformMode::Cart => "cart",
178            WaveformMode::Polar => "polar",
179            WaveformMode::PolarPhase => "polar_phase",
180        }
181    }
182}
183
184/// How the offsets of a qubit are sampled.
185#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
186#[serde(rename_all = "snake_case")]
187pub enum Coverage {
188    /// Normally distributed about the offset.
189    Single,
190    /// Uniform across the sweep width.
191    Broadband,
192    /// Inside the band normally distributed, outside uniform; the target applies only inside the band.
193    Selective,
194    /// Inside and outside the band uniform; the target follows a super-Gaussian profile.
195    BandSelective,
196}
197
198impl Coverage {
199    /// Every coverage, in the order the interface lists them.
200    pub const ALL: [Coverage; 4] = [
201        Coverage::Single,
202        Coverage::Broadband,
203        Coverage::Selective,
204        Coverage::BandSelective,
205    ];
206
207    /// The JSON name.
208    pub fn name(self) -> &'static str {
209        match self {
210            Coverage::Single => "single",
211            Coverage::Broadband => "broadband",
212            Coverage::Selective => "selective",
213            Coverage::BandSelective => "band_selective",
214        }
215    }
216}
217
218/// What each initial state should become.
219#[derive(Clone, Debug, PartialEq)]
220pub enum Targets {
221    /// A product state, one axis per qubit, per initial state.
222    Axis(Vec<Vec<String>>),
223    /// A gate name per initial state.
224    Gate(Vec<String>),
225    /// A rotation about an axis per qubit (`x`, `-x`, `y`, `-y`, `z`, `-z`) by an angle in degrees, per initial state.
226    PhiBeta {
227        /// Rotation axes.
228        phi: Vec<Vec<String>>,
229        /// Rotation angles in degrees.
230        beta: Vec<Vec<f64>>,
231    },
232}
233
234impl Targets {
235    /// The JSON key naming the method: `Axis`, `Gate` or `Phi`.
236    pub fn method(&self) -> &'static str {
237        match self {
238            Targets::Axis(_) => "Axis",
239            Targets::Gate(_) => "Gate",
240            Targets::PhiBeta { .. } => "Phi",
241        }
242    }
243
244    /// Number of target entries.
245    pub fn len(&self) -> usize {
246        match self {
247            Targets::Axis(v) => v.len(),
248            Targets::Gate(v) => v.len(),
249            Targets::PhiBeta { phi, .. } => phi.len(),
250        }
251    }
252
253    /// Whether there are no target entries.
254    pub fn is_empty(&self) -> bool {
255        self.len() == 0
256    }
257}
258
259impl Serialize for Targets {
260    fn serialize<S: Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
261        match self {
262            Targets::Axis(v) => {
263                let mut m = s.serialize_map(Some(1))?;
264                m.serialize_entry("Axis", v)?;
265                m.end()
266            }
267            Targets::Gate(v) => {
268                let mut m = s.serialize_map(Some(1))?;
269                m.serialize_entry("Gate", v)?;
270                m.end()
271            }
272            Targets::PhiBeta { phi, beta } => {
273                let mut m = s.serialize_map(Some(2))?;
274                m.serialize_entry("Phi", phi)?;
275                m.serialize_entry("Beta", beta)?;
276                m.end()
277            }
278        }
279    }
280}
281
282/// The raw target map.  The Python GUI can write every key, with nulls for the unused ones.
283#[derive(Deserialize)]
284struct RawTargets {
285    #[serde(rename = "Axis", default)]
286    axis: Option<Vec<Option<Vec<String>>>>,
287    #[serde(rename = "Gate", default)]
288    gate: Option<Vec<Option<String>>>,
289    #[serde(rename = "Phi", default)]
290    phi: Option<Vec<Option<Vec<String>>>>,
291    #[serde(rename = "Beta", default)]
292    beta: Option<Vec<Option<Vec<f64>>>>,
293}
294
295/// The entries of a list if it is present, non-empty and has no nulls.
296fn complete<T>(v: Option<Vec<Option<T>>>) -> Option<Vec<T>> {
297    let v = v?;
298    if v.is_empty() {
299        return None;
300    }
301    v.into_iter().collect()
302}
303
304impl<'de> Deserialize<'de> for Targets {
305    fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
306        let raw = RawTargets::deserialize(d)?;
307        if let Some(axis) = complete(raw.axis) {
308            return Ok(Targets::Axis(axis));
309        }
310        if let Some(gate) = complete(raw.gate) {
311            return Ok(Targets::Gate(gate));
312        }
313        if let (Some(phi), Some(beta)) = (complete(raw.phi), complete(raw.beta)) {
314            return Ok(Targets::PhiBeta { phi, beta });
315        }
316        Err(de::Error::custom(
317            "target_states needs a complete \"Axis\", \"Gate\", or \"Phi\" and \"Beta\" list",
318        ))
319    }
320}
321
322/// Axis names for states.
323pub const STATE_AXES: [&str; 6] = ["Z", "-Z", "X", "-X", "Y", "-Y"];
324/// Axis names for rotations.
325pub const ROTATION_AXES: [&str; 6] = ["x", "-x", "y", "-y", "z", "-z"];
326/// Hamiltonian model names.
327pub const HAMILTONIAN_TYPES: [&str; 3] = ["spin_chain", "superconducting", "duffing_transmon"];
328
329impl Config {
330    /// Parse a configuration.  Only the JSON syntax and field types are checked; see [`validate`](Self::validate).
331    pub fn from_json(json: &str) -> Result<Config> {
332        serde_json::from_str(json).map_err(|e| Error::Config(e.to_string()))
333    }
334
335    /// Serialise as pretty-printed JSON in the Python schema.
336    pub fn to_json(&self) -> String {
337        serde_json::to_string_pretty(self).expect("a Config always serialises")
338    }
339
340    /// Number of qubits.
341    pub fn n_qubits(&self) -> usize {
342        self.qubits.len()
343    }
344
345    /// Whether T1/T2 relaxation is on.
346    pub fn is_dissipative(&self) -> bool {
347        self.optimization.dissipation_mode == Some(Dissipation::Dissipative)
348    }
349
350    /// The effective state space: dissipative runs are always in Liouville space.
351    pub fn space(&self) -> Space {
352        if self.is_dissipative() {
353            Space::Liouville
354        } else {
355            self.optimization.space
356        }
357    }
358
359    /// Every problem with this configuration, as sentences naming the field.  Empty means it can run.
360    pub fn validate(&self) -> Vec<String> {
361        validate::validate(self)
362    }
363
364    /// [`validate`](Self::validate) as a `Result`.
365    pub fn check(&self) -> Result<()> {
366        let problems = self.validate();
367        if problems.is_empty() {
368            Ok(())
369        } else {
370            Err(Error::Config(problems.join("; ")))
371        }
372    }
373}
374
375mod validate;