1mod envelope;
10mod fourier;
11mod polynomial;
12mod qr;
13
14pub use envelope::{envelope, envelope_names};
15pub use qr::qr_q;
16
17use rand::RngExt;
18
19use crate::config::WaveformMode;
20use crate::error::{Error, Result};
21use crate::linalg::RMat;
22use crate::setup::Rng;
23
24pub trait Basis: Send + Sync {
26 fn name(&self) -> &'static str;
28
29 fn matrix(&self, x: &[f64], ncols: usize, rng: &mut Rng) -> RMat<f64>;
31
32 fn columns(&self, n_para: usize, mode: WaveformMode) -> usize {
34 match mode {
35 WaveformMode::PolarPhase => n_para,
36 WaveformMode::Cart | WaveformMode::Polar => n_para / 2,
37 }
38 }
39
40 fn parameter_count(&self, n_para: usize, mode: WaveformMode) -> usize {
42 match mode {
43 WaveformMode::PolarPhase => n_para + 1,
44 WaveformMode::Cart | WaveformMode::Polar => n_para,
45 }
46 }
47
48 fn check_n_para(&self, n_para: usize, mode: WaveformMode) -> std::result::Result<(), String> {
50 match mode {
51 WaveformMode::PolarPhase if n_para == 0 => Err("n_para must be at least 1".into()),
52 WaveformMode::Cart | WaveformMode::Polar if n_para < 2 || n_para % 2 == 1 => Err(format!(
53 "n_para must be even and at least 2 in {} mode (got {n_para})",
54 mode.name()
55 )),
56 _ => Ok(()),
57 }
58 }
59
60 fn initial_coefficients(&self, raw: &[f64], mode: WaveformMode) -> Vec<f64> {
63 match mode {
64 WaveformMode::PolarPhase => raw.to_vec(),
65 WaveformMode::Cart | WaveformMode::Polar => raw[..2 * (raw.len() / 2)].to_vec(),
66 }
67 }
68}
69
70pub fn basis(name: &str) -> Result<Box<dyn Basis>> {
72 Ok(match name {
73 "cheb" => Box::new(polynomial::Chebyshev),
74 "leg" => Box::new(polynomial::Legendre),
75 "gegen" => Box::new(polynomial::Gegenbauer { lambda: 0.5 }),
76 "poly" => Box::new(polynomial::Monomial),
77 "hermite" => Box::new(polynomial::Hermite),
78 "chirp" => Box::new(polynomial::Chirp),
79 "random" => Box::new(polynomial::Random),
80 "fou" => Box::new(fourier::Fourier),
81 _ => {
82 return Err(Error::Config(format!(
83 "unknown basis \"{name}\"; choose one of {}",
84 basis_names().join(", ")
85 )));
86 }
87 })
88}
89
90pub fn basis_names() -> &'static [&'static str] {
92 &["cheb", "leg", "fou", "poly", "hermite", "gegen", "chirp", "random"]
93}
94
95pub fn linspace(start: f64, stop: f64, n: usize) -> Vec<f64> {
97 match n {
98 0 => Vec::new(),
99 1 => vec![start],
100 _ => {
101 let step = (stop - start) / (n - 1) as f64;
102 let mut v: Vec<f64> = (0..n).map(|i| i as f64 * step + start).collect();
103 v[n - 1] = stop;
104 v
105 }
106 }
107}
108
109#[derive(Clone, Debug, PartialEq)]
111pub struct QubitBasis {
112 pub mode: WaveformMode,
114 pub q: [RMat<f64>; 2],
117 pub envelope: RMat<f64>,
119 pub n_params: usize,
121}
122
123pub fn qubit_basis(
125 basis: &dyn Basis,
126 envelope: &[f64],
127 n_para: usize,
128 mode: WaveformMode,
129 n_pulse: usize,
130 rng: &mut Rng,
131) -> Result<QubitBasis> {
132 basis.check_n_para(n_para, mode).map_err(Error::Config)?;
133 let ncols = basis.columns(n_para, mode);
134 if ncols > n_pulse {
135 return Err(Error::Config(format!(
136 "{ncols} basis functions need at least {ncols} points in the pulse, not {n_pulse}"
137 )));
138 }
139 if envelope.len() != n_pulse {
140 return Err(Error::Dimension(
141 "envelope length differs from the number of pulse points".into(),
142 ));
143 }
144 let x = linspace(-1.0, 1.0, n_pulse);
145 let b = basis.matrix(&x, ncols, rng);
146 let enveloped = RMat::from_fn(n_pulse, ncols, |r, c| b.get(r, c) * envelope[r]);
147 let orthonormal = |m: &RMat<f64>| orthonormal(m, basis.name());
148 let q = match mode {
149 WaveformMode::PolarPhase => [RMat::from_fn(n_pulse, ncols, |r, _| envelope[r]), orthonormal(&b)?],
150 WaveformMode::Polar => [orthonormal(&enveloped)?, orthonormal(&b)?],
151 WaveformMode::Cart => {
152 let q = orthonormal(&enveloped)?;
153 [q.clone(), q]
154 }
155 };
156 Ok(QubitBasis {
157 mode,
158 q,
159 envelope: RMat::column(envelope.to_vec()),
160 n_params: basis.parameter_count(n_para, mode),
161 })
162}
163
164fn orthonormal(m: &RMat<f64>, name: &str) -> Result<RMat<f64>> {
168 let s = nalgebra::DMatrix::from_fn(m.rows, m.cols, |r, c| m.get(r, c)).singular_values();
169 let tol = s.max() * m.rows.max(m.cols) as f64 * f64::EPSILON;
170 let rank = s.iter().filter(|&&v| v > tol).count();
171 if rank < m.cols {
172 return Err(Error::Config(format!(
173 "the {name} basis has only {rank} independent functions of the {} requested on {} points; use fewer \
174 parameters or more points",
175 m.cols, m.rows
176 )));
177 }
178 Ok(qr_q(m))
179}
180
181pub fn raw_coefficients(n_para: usize, rng: &mut Rng) -> Vec<f64> {
183 (0..n_para).map(|_| -1.0 + 2.0 * rng.random::<f64>()).collect()
184}
185
186pub fn initial_params(basis: &dyn Basis, raw: &[f64], mode: WaveformMode) -> Vec<f64> {
188 let mut x = basis.initial_coefficients(raw, mode);
189 if mode == WaveformMode::PolarPhase {
190 if let Some(&last) = x.last() {
191 x.push(last);
192 }
193 }
194 x
195}
196
197#[cfg(test)]
198mod tests;