1mod dissipation;
9mod sampling;
10mod states;
11
12pub use dissipation::collapse_operators;
13pub use states::{
14 canonical_gate, embed, gate, gate_names, pauli_ops, paulis, product_density, product_state, rotation, spin_ops,
15};
16
17use rand::SeedableRng;
18
19use crate::autodiff::{C, LindbladOps};
20use crate::basis::{QubitBasis, basis, envelope, initial_params, linspace, qubit_basis, raw_coefficients};
21use crate::config::{Config, Coverage, Space, Targets};
22use crate::error::{Error, Result};
23use crate::hamiltonian::{ControlChannel, HamiltonianModel, model_from_config, upper_coupling};
24use crate::linalg::{CMat, RMat};
25use sampling::{QubitOffsets, coupling_instances, excitation_profile, rabi_instances, sample_offsets};
26
27pub type Rng = rand_chacha::ChaCha8Rng;
30
31pub fn resolve_seed(cfg: &Config) -> u64 {
36 cfg.seed.unwrap_or_else(|| {
37 let now = crate::time::SystemTime::now()
38 .duration_since(crate::time::UNIX_EPOCH)
39 .map(|d| d.as_nanos())
40 .unwrap_or(0);
41 let mut z = (now as u64 ^ (now >> 64) as u64).wrapping_add(0x9E37_79B9_7F4A_7C15);
42 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
43 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
44 z ^ (z >> 31)
45 })
46}
47
48#[derive(Clone, Debug, PartialEq)]
50pub enum Evolution {
51 Hilbert,
53 Liouville,
55 Lindblad(LindbladOps),
57}
58
59#[derive(Clone, Debug, PartialEq)]
66pub struct BatchElement {
67 pub h0: CMat<f64>,
69 pub rabi: Vec<f64>,
71 pub initial: CMat<f64>,
73 pub target: CMat<f64>,
75 pub initial_index: usize,
77 pub snapshot: usize,
79 pub rabi_index: usize,
81}
82
83pub struct Problem {
85 pub n_qubits: usize,
87 pub dim: usize,
89 pub n_pulse: usize,
91 pub dt: f64,
93 pub duration: f64,
95 pub times: Vec<f64>,
97 pub qubits: Vec<QubitBasis>,
99 pub modulation: CMat<f64>,
101 pub control_ops: Vec<CMat<f64>>,
103 pub channels: Vec<ControlChannel>,
105 pub batch: Vec<BatchElement>,
107 pub evolution: Evolution,
109 pub space: Space,
111 pub x0: Vec<f64>,
113 pub seed: u64,
115 pub target_fidelity: f64,
117 pub max_iter: usize,
119 pub algorithm: String,
121 pub initial_states: Vec<CMat<f64>>,
123 pub observables: Vec<[CMat<f64>; 3]>,
125 pub model: Box<dyn HamiltonianModel>,
127 pub rabi_max: Vec<f64>,
129 pub delta: Vec<f64>,
131 pub sw: Vec<f64>,
133 pub coupling: Option<RMat<f64>>,
135 pub n_snapshots: usize,
137 pub n_rabi: usize,
139}
140
141impl Problem {
142 pub fn n_params(&self) -> usize {
144 self.qubits.iter().map(|q| q.n_params).sum()
145 }
146
147 pub fn build(cfg: &Config) -> Result<Problem> {
149 Problem::build_with_seed(cfg, resolve_seed(cfg))
150 }
151
152 pub fn build_with_seed(cfg: &Config, seed: u64) -> Result<Problem> {
154 cfg.check()?;
155 let mut rng = Rng::seed_from_u64(seed);
156 let n = cfg.n_qubits();
157 let p = &cfg.parameters;
158 let two_pi = 2.0 * std::f64::consts::PI;
159 let per_qubit = |v: &Option<Vec<f64>>| -> Vec<f64> {
160 v.as_ref()
161 .map_or(vec![0.0; n], |v| v.iter().map(|x| two_pi * x).collect())
162 };
163 let scaled = |v: &[f64]| -> Vec<f64> { v.iter().map(|x| two_pi * x).collect() };
164
165 let duration = p.pulse_duration[0];
167 let n_pulse = p.point_in_pulse[0];
168 let dt = duration / n_pulse as f64;
169 let times: Vec<f64> = (0..n_pulse).map(|t| (t as f64 + 0.5) * dt).collect();
170
171 let bases = p.wf_type.iter().map(|name| basis(name)).collect::<Result<Vec<_>>>()?;
173 let raw: Vec<Vec<f64>> = p.n_para.iter().map(|&k| raw_coefficients(k, &mut rng)).collect();
174 let x_grid = linspace(-1.0, 1.0, n_pulse);
175 let mut qubits = Vec::with_capacity(n);
176 let mut x0 = Vec::new();
177 for q in 0..n {
178 let env = envelope(&p.amplitude_envelope[q], &x_grid, p.amplitude_order[q])?;
179 let qb = qubit_basis(bases[q].as_ref(), &env, p.n_para[q], p.wf_mode[q], n_pulse, &mut rng)?;
180 x0.extend(initial_params(bases[q].as_ref(), &raw[q], p.wf_mode[q]));
181 qubits.push(qb);
182 }
183
184 let rabi_max = scaled(&p.omega_r_max);
186 let rabi = rabi_instances(
187 &rabi_max,
188 &scaled(&p.sigma_omega_r_max),
189 cfg.optimization.omega_r_snapshots,
190 &mut rng,
191 );
192
193 let delta = per_qubit(&p.delta);
195 let sigma_delta = per_qubit(&p.sigma_delta);
196 let sw = scaled(&p.sw);
197 let specs: Vec<QubitOffsets> = (0..n)
198 .map(|q| QubitOffsets {
199 coverage: p.coverage[q],
200 delta: delta[q],
201 sigma: sigma_delta[q],
202 sw: sw[q],
203 bandwidth: two_pi * p.pulse_bandwidth[q],
204 ratio: p.ratio_factor[q],
205 profile_order: p.profile_order[q],
206 })
207 .collect();
208 let coupling = match (&p.j, n > 1) {
209 (Some(j), true) => Some(upper_coupling(j, n).map_err(Error::Config)?.map(|v| two_pi * v)),
210 _ => None,
211 };
212 let sigma_j = two_pi * p.sigma_j.unwrap_or(0.0);
213 let fixed = p.coverage.iter().all(|&c| c == Coverage::Single)
215 && sigma_delta.iter().all(|&s| s == 0.0)
216 && (coupling.is_none() || sigma_j == 0.0);
217 let per_qubit_offsets: Vec<Vec<f64>> = if fixed {
218 delta.iter().map(|&d| vec![d]).collect()
219 } else {
220 specs
221 .iter()
222 .map(|s| sample_offsets(s, cfg.optimization.h0_snapshots, &mut rng))
223 .collect()
224 };
225 let m = per_qubit_offsets[0].len();
226 let profiles: Vec<Vec<f64>> = specs
227 .iter()
228 .zip(&per_qubit_offsets)
229 .map(|(s, o)| excitation_profile(s, o))
230 .collect();
231
232 let couplings = coupling.as_ref().map(|j| coupling_instances(j, sigma_j, m, &mut rng));
234
235 let model = model_from_config(cfg)?;
237 let drifts = (0..m)
238 .map(|k| {
239 let offsets: Vec<f64> = per_qubit_offsets.iter().map(|o| o[k]).collect();
240 model.drift(&offsets, couplings.as_ref().map(|c| &c[k]))
241 })
242 .collect::<Result<Vec<_>>>()?;
243
244 let space = cfg.space();
246 let raw_state = |axes: &[String]| -> Result<CMat<f64>> {
247 match space {
248 Space::Hilbert => product_state(axes),
249 Space::Liouville => product_density(axes),
250 }
251 };
252 let embed = |s: &CMat<f64>| -> Result<CMat<f64>> {
253 match space {
254 Space::Hilbert => model.embed_state(s),
255 Space::Liouville => model.embed_density(s),
256 }
257 };
258 let apply = |u: &CMat<f64>, s: &CMat<f64>| -> Result<CMat<f64>> {
259 match space {
260 Space::Hilbert => u.matmul(s),
261 Space::Liouville => u.matmul(s)?.matmul(&u.adjoint()),
262 }
263 };
264 let raw_initials: Vec<CMat<f64>> = cfg.initial_states.iter().map(|a| raw_state(a)).collect::<Result<_>>()?;
265 let initial_states: Vec<CMat<f64>> = raw_initials.iter().map(&embed).collect::<Result<_>>()?;
266 let in_band = |q: usize, k: usize| profiles[q][k] == 1.0;
268 let everyone_in_band = |k: usize| (0..n).all(|q| in_band(q, k));
269
270 let rows: Vec<Row> = match cfg.target_states.single_gate() {
273 Some(name) => {
274 let v = gate(name, n)?;
275 let id = CMat::<f64>::identity(1 << n);
276 let gates: Vec<&CMat<f64>> = (0..m).map(|k| if everyone_in_band(k) { &v } else { &id }).collect();
277 gate_rows(&gates, space, model.as_ref())?
278 }
279 None => {
280 let deg = std::f64::consts::PI / 180.0;
281 let target = |pi: usize, init: &CMat<f64>, k: usize| -> Result<CMat<f64>> {
282 let t = match &cfg.target_states {
283 Targets::Axis(axes) => {
285 let per_qubit: Vec<String> = (0..n)
286 .map(|q| {
287 if in_band(q, k) {
288 &axes[pi][q]
289 } else {
290 &cfg.initial_states[pi][q]
291 }
292 })
293 .cloned()
294 .collect();
295 raw_state(&per_qubit)?
296 }
297 Targets::Gate(names) if everyone_in_band(k) => apply(&gate(&names[pi], n)?, init)?,
298 Targets::Gate(_) => init.clone(),
299 Targets::PhiBeta { phi, beta } => {
300 let angles: Vec<f64> = (0..n).map(|q| beta[pi][q] * deg * profiles[q][k]).collect();
301 apply(&rotation(&phi[pi], &angles, n)?, init)?
302 }
303 };
304 let t = embed(&t)?;
305 if space == Space::Liouville && (t.matmul(&t)?.trace().re - 1.0).abs() > 1e-9 {
306 return Err(Error::NotSupported(
307 "Liouville-space fidelity needs pure targets; this target is mixed".into(),
308 ));
309 }
310 Ok(t)
311 };
312 raw_initials
313 .iter()
314 .enumerate()
315 .map(|(pi, init)| {
316 Ok(Row {
317 evolved: embed(init)?,
318 targets: (0..m).map(|k| target(pi, init, k)).collect::<Result<_>>()?,
319 })
320 })
321 .collect::<Result<_>>()?
322 }
323 };
324
325 let mut batch = Vec::with_capacity(rows.len() * m * rabi.len());
327 for (pi, row) in rows.into_iter().enumerate() {
328 for (k, h0) in drifts.iter().enumerate() {
329 for (r, rb) in rabi.iter().enumerate() {
330 batch.push(BatchElement {
331 h0: h0.clone(),
332 rabi: rb.clone(),
333 initial: row.evolved.clone(),
334 target: row.targets[k].clone(),
335 initial_index: pi,
336 snapshot: k,
337 rabi_index: r,
338 });
339 }
340 }
341 }
342
343 let evolution = if cfg.is_dissipative() {
344 let (t1, t2) = (p.t1.as_deref().unwrap_or(&[]), p.t2.as_deref().unwrap_or(&[]));
345 Evolution::Lindblad(LindbladOps::new(&collapse_operators(t1, t2)?, dt)?)
346 } else if space == Space::Liouville {
347 Evolution::Liouville
348 } else {
349 Evolution::Hilbert
350 };
351
352 let offsets = scaled(&p.pulse_offset);
353 let modulation = CMat::from_fn(n_pulse, n, |t, q| {
354 C::from_polar(1.0, offsets[q] * (times[t] - duration / 2.0))
355 });
356 let observables = pauli_ops(n)
358 .iter()
359 .map(|o| -> Result<[CMat<f64>; 3]> {
360 Ok([
361 model.embed_density(&o[0])?,
362 model.embed_density(&o[1])?,
363 model.embed_density(&o[2])?,
364 ])
365 })
366 .collect::<Result<Vec<_>>>()?;
367
368 Ok(Problem {
369 n_qubits: n,
370 dim: model.dim(),
371 n_pulse,
372 dt,
373 duration,
374 times,
375 qubits,
376 modulation,
377 control_ops: model.control_ops(),
378 channels: model.control_channels(),
379 batch,
380 evolution,
381 space,
382 x0,
383 seed,
384 target_fidelity: cfg.optimization.targ_fid,
385 max_iter: cfg.optimization.max_iter,
386 algorithm: cfg.optimization.algorithm.clone(),
387 initial_states,
388 observables,
389 model,
390 rabi_max,
391 delta,
392 sw,
393 coupling,
394 n_snapshots: m,
395 n_rabi: rabi.len(),
396 })
397 }
398}
399
400struct Row {
402 evolved: CMat<f64>,
404 targets: Vec<CMat<f64>>,
406}
407
408fn gate_rows(gates: &[&CMat<f64>], space: Space, model: &dyn HamiltonianModel) -> Result<Vec<Row>> {
418 let d = gates.first().map_or(1, |g| g.rows);
419 match space {
420 Space::Hilbert => Ok(vec![Row {
421 evolved: model.embed_state(&CMat::identity(d))?,
422 targets: gates.iter().map(|w| model.embed_state(w)).collect::<Result<_>>()?,
423 }]),
424 Space::Liouville => pauli_strings(d.trailing_zeros() as usize)
425 .iter()
426 .enumerate()
427 .map(|(j, u)| {
428 let weight = if j == 0 { 1.0 } else { 1.0 / (d + 1) as f64 };
429 let targets = gates
430 .iter()
431 .map(|w| {
432 Ok(model
433 .embed_density(&w.matmul(u)?.matmul(&w.adjoint())?)?
434 .scale_re(weight))
435 })
436 .collect::<Result<_>>()?;
437 Ok(Row {
438 evolved: model.embed_density(u)?,
439 targets,
440 })
441 })
442 .collect(),
443 }
444}
445
446fn pauli_strings(n: usize) -> Vec<CMat<f64>> {
448 let [x, y, z] = paulis();
449 let single = [CMat::identity(2), x, y, z];
450 (0..1usize << (2 * n))
451 .map(|i| {
452 (0..n)
453 .rev()
454 .fold(CMat::identity(1), |acc, q| acc.kron(&single[(i >> (2 * q)) & 3]))
455 })
456 .collect()
457}
458
459#[cfg(test)]
460mod tests;