Skip to main content

ctrl_freeq/basis/
mod.rs

1//! Basis functions for the pulse waveforms.
2//!
3//! Each qubit's waveform is a combination of a few smooth basis functions sampled on the pulse's time grid, mapped
4//! to `x ∈ [−1, 1]`.  The raw basis is multiplied by an amplitude envelope where the waveform mode calls for it and
5//! orthonormalised by a QR decomposition, as in the Python package's `mat_with_amplitude_and_qr`.
6//!
7//! A new basis is one type implementing [`Basis`] plus one entry in [`basis`] and [`basis_names`].
8
9mod 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
24/// A family of basis functions.
25pub trait Basis: Send + Sync {
26    /// The JSON name.
27    fn name(&self) -> &'static str;
28
29    /// The `x.len() × ncols` matrix whose column `i` is the `i`-th basis function at `x`.
30    fn matrix(&self, x: &[f64], ncols: usize, rng: &mut Rng) -> RMat<f64>;
31
32    /// Number of basis functions for `n_para` user coefficients in `mode`.
33    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    /// Number of optimiser parameters for `n_para` user coefficients in `mode` (the Python `update_n_para`).
41    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    /// Whether `n_para` is usable in `mode`; the message says why not.
49    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    /// The initial coefficients kept from `raw`, `n_para` uniform draws in `[−1, 1)`, before `polar_phase` appends
61    /// its extra entry.
62    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
70/// The basis with JSON name `name`.
71pub 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
90/// Every basis name, in the order the interface lists them.
91pub fn basis_names() -> &'static [&'static str] {
92    &["cheb", "leg", "fou", "poly", "hermite", "gegen", "chirp", "random"]
93}
94
95/// `n` points evenly spaced from `start` to `stop` inclusive, computed as numpy's `linspace` does.
96pub 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/// One qubit's waveform basis: the two matrices its parameters multiply.
110#[derive(Clone, Debug, PartialEq)]
111pub struct QubitBasis {
112    /// The waveform mode.
113    pub mode: WaveformMode,
114    /// `cart`: x and y quadratures; `polar`: amplitude and phase; `polar_phase`: the envelope (every column the
115    /// same) and the phase basis.
116    pub q: [RMat<f64>; 2],
117    /// The amplitude envelope as an `n_pulse × 1` column; `polar_phase` scales it by its first parameter.
118    pub envelope: RMat<f64>,
119    /// Number of optimiser parameters for this qubit.
120    pub n_params: usize,
121}
122
123/// Build one qubit's basis matrices: sample the basis on `n_pulse` points, apply the envelope and orthonormalise.
124pub 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
164/// The QR basis of `m`'s columns, refused unless they are linearly independent: for dependent columns QR fills the
165/// missing directions with arbitrary vectors, waveforms the basis never had.  The rank is numpy's `matrix_rank`: the
166/// singular values above `σ_max · max(rows, cols) · ε`.
167fn 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
181/// `n_para` raw coefficients drawn uniformly from `[−1, 1)`, as numpy's `uniform(-1, 1, n_para)` does.
182pub 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
186/// The initial optimiser parameters for one qubit from its raw coefficients.
187pub 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;