1mod 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum Source {
26 Cx,
28 Cy,
30 Power,
32}
33
34#[derive(Clone, Copy, Debug, PartialEq)]
36pub struct ControlChannel {
37 pub qubit: usize,
39 pub source: Source,
41 pub rabi_power: i32,
43 pub coeff: f64,
45}
46
47impl ControlChannel {
48 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
59pub trait HamiltonianModel: Send + Sync {
61 fn name(&self) -> &'static str;
63
64 fn dim(&self) -> usize;
66
67 fn drift(&self, offsets: &[f64], coupling: Option<&RMat<f64>>) -> Result<CMat<f64>>;
69
70 fn control_ops(&self) -> Vec<CMat<f64>>;
72
73 fn control_channels(&self) -> Vec<ControlChannel>;
75
76 fn embed_state(&self, psi: &CMat<f64>) -> Result<CMat<f64>> {
78 Ok(psi.clone())
79 }
80
81 fn embed_density(&self, rho: &CMat<f64>) -> Result<CMat<f64>> {
83 Ok(rho.clone())
84 }
85
86 fn embed_gate(&self, g: &CMat<f64>) -> Result<CMat<f64>> {
89 Ok(g.clone())
90 }
91}
92
93pub 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
136pub fn model_names() -> &'static [&'static str] {
138 &crate::config::HAMILTONIAN_TYPES
139}
140
141#[allow(clippy::needless_range_loop)] pub 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
170pub 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
245pub(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;