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>> {
85 Ok(rho.clone())
86 }
87
88 fn embed_gate(&self, g: &CMat<f64>) -> Result<CMat<f64>> {
91 Ok(g.clone())
92 }
93}
94
95pub 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
138pub fn model_names() -> &'static [&'static str] {
140 &crate::config::HAMILTONIAN_TYPES
141}
142
143#[allow(clippy::needless_range_loop)] pub 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
172pub 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
247pub(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;