1mod dissipation;
8mod sampling;
9mod states;
10
11pub use dissipation::collapse_operators;
12pub use states::{embed, gate, gate_names, pauli_ops, paulis, product_density, product_state, rotation, spin_ops};
13
14use rand::SeedableRng;
15
16use crate::autodiff::{C, LindbladOps};
17use crate::basis::{QubitBasis, basis, envelope, initial_params, linspace, qubit_basis, raw_coefficients};
18use crate::config::{Config, Coverage, Space, Targets};
19use crate::error::{Error, Result};
20use crate::hamiltonian::{ControlChannel, HamiltonianModel, model_from_config, upper_coupling};
21use crate::linalg::{CMat, RMat};
22use sampling::{QubitOffsets, coupling_instances, excitation_profile, rabi_instances, sample_offsets};
23
24pub type Rng = rand_chacha::ChaCha8Rng;
27
28pub fn resolve_seed(cfg: &Config) -> u64 {
33 cfg.seed.unwrap_or_else(|| {
34 let now = crate::time::SystemTime::now()
35 .duration_since(crate::time::UNIX_EPOCH)
36 .map(|d| d.as_nanos())
37 .unwrap_or(0);
38 let mut z = (now as u64 ^ (now >> 64) as u64).wrapping_add(0x9E37_79B9_7F4A_7C15);
39 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
40 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
41 z ^ (z >> 31)
42 })
43}
44
45#[derive(Clone, Debug, PartialEq)]
47pub enum Evolution {
48 Hilbert,
50 Liouville,
52 Lindblad(LindbladOps),
54}
55
56#[derive(Clone, Debug, PartialEq)]
58pub struct BatchElement {
59 pub h0: CMat<f64>,
61 pub rabi: Vec<f64>,
63 pub initial: CMat<f64>,
65 pub target: CMat<f64>,
67 pub initial_index: usize,
69 pub snapshot: usize,
71 pub rabi_index: usize,
73}
74
75pub struct Problem {
77 pub n_qubits: usize,
79 pub dim: usize,
81 pub n_pulse: usize,
83 pub dt: f64,
85 pub duration: f64,
87 pub times: Vec<f64>,
89 pub qubits: Vec<QubitBasis>,
91 pub modulation: CMat<f64>,
93 pub control_ops: Vec<CMat<f64>>,
95 pub channels: Vec<ControlChannel>,
97 pub batch: Vec<BatchElement>,
99 pub evolution: Evolution,
101 pub space: Space,
103 pub x0: Vec<f64>,
105 pub seed: u64,
107 pub target_fidelity: f64,
109 pub max_iter: usize,
111 pub algorithm: String,
113 pub initial_states: Vec<CMat<f64>>,
115 pub observables: Vec<[CMat<f64>; 3]>,
117 pub model: Box<dyn HamiltonianModel>,
119 pub rabi_max: Vec<f64>,
121 pub delta: Vec<f64>,
123 pub sw: Vec<f64>,
125 pub coupling: Option<RMat<f64>>,
127 pub n_snapshots: usize,
129 pub n_rabi: usize,
131}
132
133impl Problem {
134 pub fn n_params(&self) -> usize {
136 self.qubits.iter().map(|q| q.n_params).sum()
137 }
138
139 pub fn build(cfg: &Config) -> Result<Problem> {
141 Problem::build_with_seed(cfg, resolve_seed(cfg))
142 }
143
144 pub fn build_with_seed(cfg: &Config, seed: u64) -> Result<Problem> {
146 cfg.check()?;
147 let mut rng = Rng::seed_from_u64(seed);
148 let n = cfg.n_qubits();
149 let p = &cfg.parameters;
150 let two_pi = 2.0 * std::f64::consts::PI;
151 let per_qubit = |v: &Option<Vec<f64>>| -> Vec<f64> {
152 v.as_ref()
153 .map_or(vec![0.0; n], |v| v.iter().map(|x| two_pi * x).collect())
154 };
155 let scaled = |v: &[f64]| -> Vec<f64> { v.iter().map(|x| two_pi * x).collect() };
156
157 let duration = p.pulse_duration[0];
159 let n_pulse = p.point_in_pulse[0];
160 let dt = duration / n_pulse as f64;
161 let times = linspace(f64::EPSILON, duration, n_pulse);
162
163 let bases = p.wf_type.iter().map(|name| basis(name)).collect::<Result<Vec<_>>>()?;
165 let raw: Vec<Vec<f64>> = p.n_para.iter().map(|&k| raw_coefficients(k, &mut rng)).collect();
166 let x_grid = linspace(-1.0, 1.0, n_pulse);
167 let mut qubits = Vec::with_capacity(n);
168 let mut x0 = Vec::new();
169 for q in 0..n {
170 let env = envelope(&p.amplitude_envelope[q], &x_grid, p.amplitude_order[q])?;
171 let qb = qubit_basis(bases[q].as_ref(), &env, p.n_para[q], p.wf_mode[q], n_pulse, &mut rng)?;
172 x0.extend(initial_params(bases[q].as_ref(), &raw[q], p.wf_mode[q]));
173 qubits.push(qb);
174 }
175
176 let rabi_max = scaled(&p.omega_r_max);
178 let rabi = rabi_instances(
179 &rabi_max,
180 &scaled(&p.sigma_omega_r_max),
181 cfg.optimization.omega_r_snapshots,
182 &mut rng,
183 );
184
185 let delta = per_qubit(&p.delta);
187 let sigma_delta = per_qubit(&p.sigma_delta);
188 let sw = scaled(&p.sw);
189 let specs: Vec<QubitOffsets> = (0..n)
190 .map(|q| QubitOffsets {
191 coverage: p.coverage[q],
192 delta: delta[q],
193 sigma: sigma_delta[q],
194 sw: sw[q],
195 bandwidth: two_pi * p.pulse_bandwidth[q],
196 ratio: p.ratio_factor[q],
197 profile_order: p.profile_order[q],
198 })
199 .collect();
200 let fixed = p.coverage.iter().all(|&c| c == Coverage::Single) && sigma_delta.iter().all(|&s| s == 0.0);
201 let per_qubit_offsets: Vec<Vec<f64>> = if fixed {
202 delta.iter().map(|&d| vec![d]).collect()
203 } else {
204 specs
205 .iter()
206 .map(|s| sample_offsets(s, cfg.optimization.h0_snapshots, &mut rng))
207 .collect()
208 };
209 let m = per_qubit_offsets[0].len();
210 let profiles: Vec<Vec<f64>> = specs
211 .iter()
212 .zip(&per_qubit_offsets)
213 .map(|(s, o)| excitation_profile(s, o))
214 .collect();
215
216 let coupling = match (&p.j, n > 1) {
218 (Some(j), true) => Some(upper_coupling(j, n).map_err(Error::Config)?.map(|v| two_pi * v)),
219 _ => None,
220 };
221 let sigma_j = two_pi * p.sigma_j.unwrap_or(0.0);
222 let couplings = coupling.as_ref().map(|j| coupling_instances(j, sigma_j, m, &mut rng));
223
224 let model = model_from_config(cfg)?;
226 let drifts = (0..m)
227 .map(|k| {
228 let offsets: Vec<f64> = per_qubit_offsets.iter().map(|o| o[k]).collect();
229 model.drift(&offsets, couplings.as_ref().map(|c| &c[k]))
230 })
231 .collect::<Result<Vec<_>>>()?;
232
233 let space = cfg.space();
235 let raw_state = |axes: &[String]| -> Result<CMat<f64>> {
236 match space {
237 Space::Hilbert => product_state(axes),
238 Space::Liouville => product_density(axes),
239 }
240 };
241 let embed = |s: &CMat<f64>| -> Result<CMat<f64>> {
242 match space {
243 Space::Hilbert => model.embed_state(s),
244 Space::Liouville => model.embed_density(s),
245 }
246 };
247 let apply = |u: &CMat<f64>, s: &CMat<f64>| -> Result<CMat<f64>> {
248 match space {
249 Space::Hilbert => u.matmul(s),
250 Space::Liouville => u.matmul(s)?.matmul(&u.adjoint()),
251 }
252 };
253 let raw_initials: Vec<CMat<f64>> = cfg.initial_states.iter().map(|a| raw_state(a)).collect::<Result<_>>()?;
254 let initial_states: Vec<CMat<f64>> = raw_initials.iter().map(&embed).collect::<Result<_>>()?;
255 let deg = std::f64::consts::PI / 180.0;
256 let mut targets: Vec<Vec<CMat<f64>>> = Vec::with_capacity(raw_initials.len());
258 for (pi, init) in raw_initials.iter().enumerate() {
259 let mut row = Vec::with_capacity(m);
260 for (k, &first) in profiles[0].iter().enumerate() {
261 let applies = first == 1.0;
262 let t = match &cfg.target_states {
263 Targets::Axis(axes) if applies => raw_state(&axes[pi])?,
264 Targets::Gate(names) if applies => apply(&gate(&names[pi], n)?, init)?,
265 Targets::PhiBeta { phi, beta } => {
266 let angles: Vec<f64> = (0..n).map(|q| beta[pi][q] * deg * profiles[q][k]).collect();
267 apply(&rotation(&phi[pi], &angles, n)?, init)?
268 }
269 _ => init.clone(),
270 };
271 row.push(embed(&t)?);
272 }
273 targets.push(row);
274 }
275 if space == Space::Liouville {
276 for t in targets.iter().flatten() {
277 let purity = t.matmul(t)?.trace().re;
278 if (purity - 1.0).abs() > 1e-9 {
279 return Err(Error::NotSupported(
280 "Liouville-space fidelity needs pure targets; this target is mixed".into(),
281 ));
282 }
283 }
284 }
285
286 let mut batch = Vec::with_capacity(initial_states.len() * m * rabi.len());
288 for (pi, init) in initial_states.iter().enumerate() {
289 for (k, h0) in drifts.iter().enumerate() {
290 for (r, rb) in rabi.iter().enumerate() {
291 batch.push(BatchElement {
292 h0: h0.clone(),
293 rabi: rb.clone(),
294 initial: init.clone(),
295 target: targets[pi][k].clone(),
296 initial_index: pi,
297 snapshot: k,
298 rabi_index: r,
299 });
300 }
301 }
302 }
303
304 let evolution = if cfg.is_dissipative() {
305 let (t1, t2) = (p.t1.as_deref().unwrap_or(&[]), p.t2.as_deref().unwrap_or(&[]));
306 Evolution::Lindblad(LindbladOps::new(&collapse_operators(t1, t2)?)?)
307 } else if space == Space::Liouville {
308 Evolution::Liouville
309 } else {
310 Evolution::Hilbert
311 };
312
313 let offsets = scaled(&p.pulse_offset);
314 let modulation = CMat::from_fn(n_pulse, n, |t, q| {
315 C::from_polar(1.0, offsets[q] * (times[t] - duration / 2.0))
316 });
317 let observables = pauli_ops(n)
318 .iter()
319 .map(|o| -> Result<[CMat<f64>; 3]> {
320 Ok([
321 model.embed_gate(&o[0])?,
322 model.embed_gate(&o[1])?,
323 model.embed_gate(&o[2])?,
324 ])
325 })
326 .collect::<Result<Vec<_>>>()?;
327
328 Ok(Problem {
329 n_qubits: n,
330 dim: model.dim(),
331 n_pulse,
332 dt,
333 duration,
334 times,
335 qubits,
336 modulation,
337 control_ops: model.control_ops(),
338 channels: model.control_channels(),
339 batch,
340 evolution,
341 space,
342 x0,
343 seed,
344 target_fidelity: cfg.optimization.targ_fid,
345 max_iter: cfg.optimization.max_iter,
346 algorithm: cfg.optimization.algorithm.clone(),
347 initial_states,
348 observables,
349 model,
350 rabi_max,
351 delta,
352 sw,
353 coupling,
354 n_snapshots: m,
355 n_rabi: rabi.len(),
356 })
357 }
358}
359
360#[cfg(test)]
361mod tests;