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 in the model's space.  The identity for two-level models.
82    fn embed_density(&self, rho: &CMat<f64>) -> Result<CMat<f64>> {
83        Ok(rho.clone())
84    }
85
86    /// A computational-basis operator in the model's space: the operator on the computational subspace and the
87    /// identity elsewhere.  The identity map for two-level models.
88    fn embed_gate(&self, g: &CMat<f64>) -> Result<CMat<f64>> {
89        Ok(g.clone())
90    }
91}
92
93/// The model a configuration describes.  No `hamiltonian_type` means the Python package's original spin-chain
94/// path, whose default coupling is `Z` rather than the `spin_chain` model's `XY`.
95pub fn model_from_config(cfg: &Config) -> Result<Box<dyn HamiltonianModel>> {
96    let n = cfg.n_qubits();
97    let p = &cfg.parameters;
98    let two_pi = 2.0 * std::f64::consts::PI;
99    let scaled = |v: &Option<Vec<f64>>| v.as_ref().map(|v| v.iter().map(|x| two_pi * x).collect::<Vec<_>>());
100    Ok(match cfg.hamiltonian_type.as_deref() {
101        None => Box::new(SpinChain::new(
102            n,
103            Coupling::parse(p.coupling_type.as_deref().unwrap_or("Z"))?,
104        )),
105        Some("spin_chain") => Box::new(SpinChain::new(
106            n,
107            Coupling::parse(p.coupling_type.as_deref().unwrap_or("XY"))?,
108        )),
109        Some("superconducting") => {
110            let zz = match &p.zz_crosstalk {
111                Some(m) => Some(upper_coupling(m, n).map_err(Error::Config)?.map(|v| two_pi * v)),
112                None => None,
113            };
114            Box::new(Superconducting::new(
115                n,
116                p.coupling_type.clone().unwrap_or_else(|| "XY".into()),
117                scaled(&p.anharmonicities),
118                zz,
119                p.stark_shift_coeffs.clone(),
120            ))
121        }
122        Some("duffing_transmon") => {
123            let alpha = scaled(&p.anharmonicities)
124                .ok_or_else(|| Error::Config("the duffing_transmon model needs anharmonicities".into()))?;
125            Box::new(DuffingTransmon::new(n, alpha)?)
126        }
127        Some(other) => {
128            return Err(Error::Config(format!(
129                "unknown hamiltonian_type \"{other}\"; choose one of {}",
130                model_names().join(", ")
131            )));
132        }
133    })
134}
135
136/// Every model name, in the order the interface lists them.
137pub fn model_names() -> &'static [&'static str] {
138    &crate::config::HAMILTONIAN_TYPES
139}
140
141/// The couplings of `j` as an upper-triangular matrix.
142///
143/// Accepts an upper-triangular, lower-triangular or symmetric matrix, as the Python package does for spin chains.
144/// A pair given in both triangles with different values is an error.
145#[allow(clippy::needless_range_loop)] // `j[a][b]` and `j[b][a]` are read together
146pub fn upper_coupling(j: &[Vec<f64>], n: usize) -> std::result::Result<RMat<f64>, String> {
147    if j.len() != n || j.iter().any(|r| r.len() != n) {
148        return Err(format!("J must be a {n}x{n} matrix"));
149    }
150    let mut out = RMat::<f64>::zeros(n, n);
151    for a in 0..n {
152        for b in a + 1..n {
153            let (u, l) = (j[a][b], j[b][a]);
154            let close = (u - l).abs() <= 1e-8 * u.abs().max(l.abs());
155            let v = match (u != 0.0, l != 0.0) {
156                (true, true) if !close => {
157                    return Err(format!(
158                        "J is asymmetric: J[{a},{b}] = {u} but J[{b},{a}] = {l}; give a symmetric matrix or one triangle"
159                    ));
160                }
161                (true, _) => u,
162                (false, _) => l,
163            };
164            out.set(a, b, v);
165        }
166    }
167    Ok(out)
168}
169
170/// A complete, runnable configuration for `n_qubits` qubits of the model `name` - the Python `default_config`.
171pub fn default_config(name: &str, n_qubits: usize) -> Result<Config> {
172    if n_qubits == 0 {
173        return Err(Error::Config("at least one qubit is needed".into()));
174    }
175    let n = n_qubits;
176    let (offset_step, coupling, target_gate, first_states) = match name {
177        "spin_chain" => (10e6, 16.67e6, "CNOT", vec!["Z", "-Z"]),
178        "superconducting" | "duffing_transmon" => (10e6, 1.047e7, "iSWAP", vec!["-Z", "Z"]),
179        _ => {
180            return Err(Error::Config(format!(
181                "unknown hamiltonian_type \"{name}\"; choose one of {}",
182                model_names().join(", ")
183            )));
184        }
185    };
186    let mut j = vec![vec![0.0; n]; n];
187    for (i, row) in j.iter_mut().enumerate().take(n - 1) {
188        row[i + 1] = coupling;
189    }
190    let (initial_states, target_states) = if n == 1 {
191        (vec![vec!["Z".to_string()]], Targets::Axis(vec![vec!["-Z".to_string()]]))
192    } else {
193        let mut init: Vec<String> = first_states.iter().map(|s| s.to_string()).collect();
194        init.extend(std::iter::repeat_n("-Z".to_string(), n - 2));
195        (vec![init], Targets::Gate(vec![target_gate.to_string()]))
196    };
197    let per = |v: f64| vec![v; n];
198    Ok(Config {
199        hamiltonian_type: Some(name.to_string()),
200        qubits: (1..=n).map(|i| format!("q{i}")).collect(),
201        compute_resource: Some("cpu".into()),
202        cpu_cores: None,
203        seed: None,
204        parameters: Parameters {
205            delta: Some((1..=n).map(|i| i as f64 * offset_step).collect()),
206            sigma_delta: Some(per(0.0)),
207            omega_r_max: per(40e6),
208            sigma_omega_r_max: per(0.0),
209            pulse_duration: per(200e-9),
210            point_in_pulse: vec![100; n],
211            wf_type: vec!["cheb".into(); n],
212            wf_mode: vec![WaveformMode::Cart; n],
213            amplitude_envelope: vec!["gn".into(); n],
214            amplitude_order: vec![1; n],
215            coverage: vec![Coverage::Broadband; n],
216            sw: per(5e6),
217            pulse_offset: per(0.0),
218            pulse_bandwidth: per(5e5),
219            ratio_factor: per(0.5),
220            profile_order: vec![2; n],
221            n_para: vec![16; n],
222            j: Some(j),
223            coupling_type: Some("XY".into()),
224            sigma_j: Some(0.0),
225            t1: None,
226            t2: None,
227            anharmonicities: (name == "duffing_transmon").then(|| per(-330e6)),
228            zz_crosstalk: None,
229            stark_shift_coeffs: None,
230        },
231        initial_states,
232        target_states,
233        optimization: Optimization {
234            space: Space::Hilbert,
235            dissipation_mode: None,
236            h0_snapshots: 1,
237            omega_r_snapshots: 1,
238            algorithm: "l-bfgs".into(),
239            max_iter: 300,
240            targ_fid: 0.999,
241        },
242    })
243}
244
245/// `op` acting on site `site` of `n` sites of local dimension `op.rows`, identity elsewhere.
246pub(crate) fn embed_local(op: &CMat<f64>, site: usize, n: usize) -> CMat<f64> {
247    crate::setup::embed(op, site, n)
248}
249
250#[cfg(test)]
251mod tests;