Skip to main content

ctrl_freeq/hamiltonian/
mod.rs

1//! Hamiltonian models: the physical platforms.
2//!
3//! Every platform uses the bilinear control form `H(t) = H_drift + Σ_k u_k(t)·H_k`.  A model supplies the drift for
4//! given offsets and couplings, the fixed control operators `H_k`, and - as data - how each control amplitude
5//! `u_k(t)` is made from the waveform: see [`ControlChannel`].  Models never see the autodiff tape, so a new
6//! platform needs no gradient code.
7//!
8//! A new model is one type implementing [`HamiltonianModel`] plus entries in [`model_from_config`],
9//! [`model_names`](crate::config::HAMILTONIAN_TYPES) and [`default_config`].
10
11mod duffing;
12mod spin_chain;
13mod superconducting;
14
15pub use duffing::DuffingTransmon;
16pub use spin_chain::{Coupling, SpinChain};
17pub use superconducting::Superconducting;
18
19use crate::config::{Config, Coverage, Optimization, Parameters, Space, Targets, WaveformMode};
20use crate::error::{Error, Result};
21use crate::linalg::{CMat, RMat};
22
23/// Which part of a qubit's waveform drives a control channel.
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum Source {
26    /// The in-phase (x) quadrature.
27    Cx,
28    /// The quadrature (y) component.
29    Cy,
30    /// The instantaneous power `cx² + cy²`.
31    Power,
32}
33
34/// How one control amplitude is made: `u(t) = coeff · rabi[qubit]^rabi_power · source(t)`.
35#[derive(Clone, Copy, Debug, PartialEq)]
36pub struct ControlChannel {
37    /// The qubit whose waveform and Rabi frequency drive the channel.
38    pub qubit: usize,
39    /// Which part of the waveform.
40    pub source: Source,
41    /// Power of the Rabi frequency.
42    pub rabi_power: i32,
43    /// Constant factor.
44    pub coeff: f64,
45}
46
47impl ControlChannel {
48    /// `coeff · rabi · cx` or `· cy`, the usual I/Q drive.
49    pub fn drive(qubit: usize, source: Source) -> Self {
50        ControlChannel {
51            qubit,
52            source,
53            rabi_power: 1,
54            coeff: 1.0,
55        }
56    }
57}
58
59/// A physical platform.
60pub trait HamiltonianModel: Send + Sync {
61    /// The JSON name.
62    fn name(&self) -> &'static str;
63
64    /// Hilbert-space dimension.
65    fn dim(&self) -> usize;
66
67    /// The drift Hamiltonian for per-qubit `offsets` and an upper-triangular `coupling` matrix, both in rad/s.
68    fn drift(&self, offsets: &[f64], coupling: Option<&RMat<f64>>) -> Result<CMat<f64>>;
69
70    /// The fixed control operators `H_k`, one per channel.
71    fn control_ops(&self) -> Vec<CMat<f64>>;
72
73    /// How each control amplitude is made, one per operator.
74    fn control_channels(&self) -> Vec<ControlChannel>;
75
76    /// A computational-basis state vector in the model's space.  The identity for two-level models.
77    fn embed_state(&self, psi: &CMat<f64>) -> Result<CMat<f64>> {
78        Ok(psi.clone())
79    }
80
81    /// A computational-basis density matrix, or any operator, in the model's space and zero outside the
82    /// computational subspace: `P·ρ·P†`.  Also embeds Pauli operators and plot observables.  The identity for
83    /// two-level models.
84    fn embed_density(&self, rho: &CMat<f64>) -> Result<CMat<f64>> {
85        Ok(rho.clone())
86    }
87
88    /// A computational-basis operator in the model's space: the operator on the computational subspace and the
89    /// identity elsewhere.  The identity map for two-level models.
90    fn embed_gate(&self, g: &CMat<f64>) -> Result<CMat<f64>> {
91        Ok(g.clone())
92    }
93}
94
95/// The model a configuration describes.  No `hamiltonian_type` means the Python package's original spin-chain
96/// path, whose default coupling is `Z` rather than the `spin_chain` model's `XY`.
97pub fn model_from_config(cfg: &Config) -> Result<Box<dyn HamiltonianModel>> {
98    let n = cfg.n_qubits();
99    let p = &cfg.parameters;
100    let two_pi = 2.0 * std::f64::consts::PI;
101    let scaled = |v: &Option<Vec<f64>>| v.as_ref().map(|v| v.iter().map(|x| two_pi * x).collect::<Vec<_>>());
102    Ok(match cfg.hamiltonian_type.as_deref() {
103        None => Box::new(SpinChain::new(
104            n,
105            Coupling::parse(p.coupling_type.as_deref().unwrap_or("Z"))?,
106        )),
107        Some("spin_chain") => Box::new(SpinChain::new(
108            n,
109            Coupling::parse(p.coupling_type.as_deref().unwrap_or("XY"))?,
110        )),
111        Some("superconducting") => {
112            let zz = match &p.zz_crosstalk {
113                Some(m) => Some(upper_coupling(m, n).map_err(Error::Config)?.map(|v| two_pi * v)),
114                None => None,
115            };
116            Box::new(Superconducting::new(
117                n,
118                p.coupling_type.clone().unwrap_or_else(|| "XY".into()),
119                scaled(&p.anharmonicities),
120                zz,
121                p.stark_shift_coeffs.clone(),
122            ))
123        }
124        Some("duffing_transmon") => {
125            let alpha = scaled(&p.anharmonicities)
126                .ok_or_else(|| Error::Config("the duffing_transmon model needs anharmonicities".into()))?;
127            Box::new(DuffingTransmon::new(n, alpha)?)
128        }
129        Some(other) => {
130            return Err(Error::Config(format!(
131                "unknown hamiltonian_type \"{other}\"; choose one of {}",
132                model_names().join(", ")
133            )));
134        }
135    })
136}
137
138/// Every model name, in the order the interface lists them.
139pub fn model_names() -> &'static [&'static str] {
140    &crate::config::HAMILTONIAN_TYPES
141}
142
143/// The couplings of `j` as an upper-triangular matrix.
144///
145/// Accepts an upper-triangular, lower-triangular or symmetric matrix, as the Python package does for spin chains.
146/// A pair given in both triangles with different values is an error.
147#[allow(clippy::needless_range_loop)] // `j[a][b]` and `j[b][a]` are read together
148pub fn upper_coupling(j: &[Vec<f64>], n: usize) -> std::result::Result<RMat<f64>, String> {
149    if j.len() != n || j.iter().any(|r| r.len() != n) {
150        return Err(format!("J must be a {n}x{n} matrix"));
151    }
152    let mut out = RMat::<f64>::zeros(n, n);
153    for a in 0..n {
154        for b in a + 1..n {
155            let (u, l) = (j[a][b], j[b][a]);
156            let close = (u - l).abs() <= 1e-8 * u.abs().max(l.abs());
157            let v = match (u != 0.0, l != 0.0) {
158                (true, true) if !close => {
159                    return Err(format!(
160                        "J is asymmetric: J[{a},{b}] = {u} but J[{b},{a}] = {l}; give a symmetric matrix or one triangle"
161                    ));
162                }
163                (true, _) => u,
164                (false, _) => l,
165            };
166            out.set(a, b, v);
167        }
168    }
169    Ok(out)
170}
171
172/// A complete, runnable configuration for `n_qubits` qubits of the model `name` - the Python `default_config`.
173pub fn default_config(name: &str, n_qubits: usize) -> Result<Config> {
174    if n_qubits == 0 {
175        return Err(Error::Config("at least one qubit is needed".into()));
176    }
177    let n = n_qubits;
178    let (offset_step, coupling, target_gate, first_states) = match name {
179        "spin_chain" => (10e6, 16.67e6, "CNOT", vec!["Z", "-Z"]),
180        "superconducting" | "duffing_transmon" => (10e6, 1.047e7, "iSWAP", vec!["-Z", "Z"]),
181        _ => {
182            return Err(Error::Config(format!(
183                "unknown hamiltonian_type \"{name}\"; choose one of {}",
184                model_names().join(", ")
185            )));
186        }
187    };
188    let mut j = vec![vec![0.0; n]; n];
189    for (i, row) in j.iter_mut().enumerate().take(n - 1) {
190        row[i + 1] = coupling;
191    }
192    let (initial_states, target_states) = if n == 1 {
193        (vec![vec!["Z".to_string()]], Targets::Axis(vec![vec!["-Z".to_string()]]))
194    } else {
195        let mut init: Vec<String> = first_states.iter().map(|s| s.to_string()).collect();
196        init.extend(std::iter::repeat_n("-Z".to_string(), n - 2));
197        (vec![init], Targets::Gate(vec![target_gate.to_string()]))
198    };
199    let per = |v: f64| vec![v; n];
200    Ok(Config {
201        hamiltonian_type: Some(name.to_string()),
202        qubits: (1..=n).map(|i| format!("q{i}")).collect(),
203        compute_resource: Some("cpu".into()),
204        cpu_cores: None,
205        seed: None,
206        parameters: Parameters {
207            delta: Some((1..=n).map(|i| i as f64 * offset_step).collect()),
208            sigma_delta: Some(per(0.0)),
209            omega_r_max: per(40e6),
210            sigma_omega_r_max: per(0.0),
211            pulse_duration: per(200e-9),
212            point_in_pulse: vec![100; n],
213            wf_type: vec!["cheb".into(); n],
214            wf_mode: vec![WaveformMode::Cart; n],
215            amplitude_envelope: vec!["gn".into(); n],
216            amplitude_order: vec![1; n],
217            coverage: vec![Coverage::Broadband; n],
218            sw: per(5e6),
219            pulse_offset: per(0.0),
220            pulse_bandwidth: per(5e5),
221            ratio_factor: per(0.5),
222            profile_order: vec![2; n],
223            n_para: vec![16; n],
224            j: Some(j),
225            coupling_type: Some("XY".into()),
226            sigma_j: Some(0.0),
227            t1: None,
228            t2: None,
229            anharmonicities: (name == "duffing_transmon").then(|| per(-330e6)),
230            zz_crosstalk: None,
231            stark_shift_coeffs: None,
232        },
233        initial_states,
234        target_states,
235        optimization: Optimization {
236            space: Space::Hilbert,
237            dissipation_mode: None,
238            h0_snapshots: 1,
239            omega_r_snapshots: 1,
240            algorithm: "l-bfgs".into(),
241            max_iter: 300,
242            targ_fid: 0.999,
243        },
244    })
245}
246
247/// `op` acting on site `site` of `n` sites of local dimension `op.rows`, identity elsewhere.
248pub(crate) fn embed_local(op: &CMat<f64>, site: usize, n: usize) -> CMat<f64> {
249    crate::setup::embed(op, site, n)
250}
251
252#[cfg(test)]
253mod tests;