Skip to main content

lib_jsl_dsp/discrete/
waveforms.rs

1//! Test waveforms as functions of time, following `scipy.signal`: `sawtooth`, `square` (with a
2//! duty cycle), `gausspulse`, `chirp` (linear, quadratic, logarithmic, hyperbolic), `sweep_poly`
3//! and `unit_impulse`.
4//!
5//! See the book entry [Partial fractions, zoom FFT and waveforms](https://jwkunz.github.io/lib_jsl/book/spectral/partial-fractions-waveforms.html#waveforms).
6
7use lib_jsl_core::ErrorsJSL;
8use std::f64::consts::{PI, TAU};
9
10/// A sawtooth of period `2π` rising from −1 to 1 over the first `width · 2π` and falling back
11/// over the rest (SciPy's `sawtooth`); `width = 0.5` gives a triangle wave. `NaN` for a width
12/// outside `[0, 1]`.
13pub fn sawtooth(t: &[f64], width: f64) -> Vec<f64> {
14    t.iter()
15        .map(|&ti| {
16            if !(0.0..=1.0).contains(&width) {
17                return f64::NAN;
18            }
19            let m = ti.rem_euclid(TAU);
20            if m < width * TAU { m / (PI * width) - 1.0 } else { (PI * (width + 1.0) - m) / (PI * (1.0 - width)) }
21        })
22        .collect()
23}
24
25/// A square wave of period `2π`: +1 for the first `duty · 2π`, −1 after (SciPy's `square`).
26pub fn square_wave(t: &[f64], duty: f64) -> Vec<f64> {
27    t.iter()
28        .map(|&ti| {
29            if !(0.0..=1.0).contains(&duty) {
30                return f64::NAN;
31            }
32            if ti.rem_euclid(TAU) < duty * TAU { 1.0 } else { -1.0 }
33        })
34        .collect()
35}
36
37/// The in-phase part, quadrature part and envelope of a Gaussian-modulated sinusoid.
38#[derive(Clone, Debug, PartialEq)]
39pub struct GaussPulse {
40    pub in_phase: Vec<f64>,
41    pub quadrature: Vec<f64>,
42    pub envelope: Vec<f64>,
43}
44
45fn gauss_a(fc: f64, bw: f64, bwr: f64) -> Result<f64, ErrorsJSL> {
46    if fc < 0.0 || bw <= 0.0 || bwr >= 0.0 {
47        return Err(ErrorsJSL::InvalidInputRange("need fc ≥ 0, bw > 0 and bwr < 0 dB"));
48    }
49    let reference = 10f64.powf(bwr / 20.0);
50    Ok(-(PI * fc * bw).powi(2) / (4.0 * reference.ln()))
51}
52
53// ANCHOR: gausspulse
54/// `exp(−a t²) exp(2πi f_c t)` (SciPy's `gausspulse`), with `a` chosen so that the spectrum's
55/// width at `bwr` dB (−6 by default) is the fraction `bw` of `f_c`.
56pub fn gausspulse(t: &[f64], fc: f64, bw: f64, bwr: f64) -> Result<GaussPulse, ErrorsJSL> {
57    let a = gauss_a(fc, bw, bwr)?;
58    let envelope: Vec<f64> = t.iter().map(|&ti| (-a * ti * ti).exp()).collect();
59    Ok(GaussPulse {
60        in_phase: t.iter().zip(&envelope).map(|(&ti, e)| e * (TAU * fc * ti).cos()).collect(),
61        quadrature: t.iter().zip(&envelope).map(|(&ti, e)| e * (TAU * fc * ti).sin()).collect(),
62        envelope,
63    })
64}
65// ANCHOR_END: gausspulse
66
67/// The time after which the envelope of [`gausspulse`] stays below `tpr` dB (SciPy's
68/// `gausspulse('cutoff', …)`).
69pub fn gausspulse_cutoff(fc: f64, bw: f64, bwr: f64, tpr: f64) -> Result<f64, ErrorsJSL> {
70    if tpr >= 0.0 {
71        return Err(ErrorsJSL::InvalidInputRange("the cutoff level must be below 0 dB"));
72    }
73    let a = gauss_a(fc, bw, bwr)?;
74    Ok((-(10f64.powf(tpr / 20.0)).ln() / a).sqrt())
75}
76
77/// How the frequency of a [`chirp`] moves from `f0` at `t = 0` to `f1` at `t = t1`.
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79pub enum ChirpMethod {
80    Linear,
81    /// Quadratic, with the parabola's vertex at `t = 0` (`vertex_zero = true`) or at `t1`.
82    Quadratic { vertex_zero: bool },
83    /// Geometric: `f(t) = f0 (f1/f0)^{t/t1}`.
84    Logarithmic,
85    /// `f(t) = f0 f1 t1 / ((f0 − f1) t + f1 t1)`.
86    Hyperbolic,
87}
88
89// ANCHOR: chirp
90/// A swept-frequency cosine `cos(φ(t) + φ₀)` (SciPy's `chirp`, `phi` in degrees), where the phase
91/// `φ(t) = 2π ∫₀ᵗ f(τ) dτ` integrates the instantaneous frequency of the chosen sweep.
92pub fn chirp(t: &[f64], f0: f64, t1: f64, f1: f64, method: ChirpMethod, phi: f64) -> Result<Vec<f64>, ErrorsJSL> {
93    let phase = |ti: f64| -> Result<f64, ErrorsJSL> {
94        Ok(match method {
95            ChirpMethod::Linear => TAU * (f0 * ti + 0.5 * (f1 - f0) / t1 * ti * ti),
96            ChirpMethod::Quadratic { vertex_zero } => {
97                let beta = (f1 - f0) / (t1 * t1);
98                if vertex_zero { TAU * (f0 * ti + beta * ti.powi(3) / 3.0) } else { TAU * (f1 * ti + beta * ((t1 - ti).powi(3) - t1.powi(3)) / 3.0) }
99            }
100            ChirpMethod::Logarithmic => {
101                if f0 * f1 <= 0.0 {
102                    return Err(ErrorsJSL::InvalidInputRange("a logarithmic chirp needs f0 and f1 of the same sign"));
103                }
104                if f0 == f1 { TAU * f0 * ti } else { TAU * t1 / (f1 / f0).ln() * f0 * ((f1 / f0).powf(ti / t1) - 1.0) }
105            }
106            ChirpMethod::Hyperbolic => {
107                if f0 == 0.0 || f1 == 0.0 {
108                    return Err(ErrorsJSL::InvalidInputRange("a hyperbolic chirp needs non-zero f0 and f1"));
109                }
110                if f0 == f1 {
111                    TAU * f0 * ti
112                } else {
113                    let sing = -f1 * t1 / (f0 - f1);
114                    TAU * (-sing * f0) * (1.0 - ti / sing).abs().ln()
115                }
116            }
117        })
118    };
119    t.iter().map(|&ti| Ok((phase(ti)? + phi.to_radians()).cos())).collect()
120}
121// ANCHOR_END: chirp
122
123/// A cosine whose instantaneous frequency is the polynomial `poly(t)` (highest power first;
124/// SciPy's `sweep_poly`): `cos(2π ∫₀ᵗ poly + φ₀)`, `phi` in degrees.
125pub fn sweep_poly(t: &[f64], poly: &[f64], phi: f64) -> Vec<f64> {
126    let n = poly.len();
127    // The antiderivative, highest power first, with zero constant term.
128    let integral: Vec<f64> = poly.iter().enumerate().map(|(i, c)| c / (n - i) as f64).chain(std::iter::once(0.0)).collect();
129    t.iter().map(|&ti| (TAU * integral.iter().fold(0.0, |acc, &c| acc * ti + c) + phi.to_radians()).cos()).collect()
130}
131
132/// A unit impulse of length `n` at index `idx` (SciPy's `unit_impulse`).
133pub fn unit_impulse(n: usize, idx: usize) -> Vec<f64> {
134    let mut v = vec![0.0; n];
135    if idx < n {
136        v[idx] = 1.0;
137    }
138    v
139}
140
141#[cfg(test)]
142mod tests {
143    use super::*;
144
145    #[test]
146    fn shapes() {
147        let t: Vec<f64> = (0..8).map(|i| i as f64 * PI / 4.0).collect();
148        assert_eq!(sawtooth(&t, 1.0)[0], -1.0);
149        assert!((sawtooth(&t, 0.5)[2] - 0.0).abs() < 1e-15);
150        assert_eq!(square_wave(&t, 0.5), vec![1.0, 1.0, 1.0, 1.0, -1.0, -1.0, -1.0, -1.0]);
151        let g = gausspulse(&[0.0], 1000.0, 0.5, -6.0).unwrap();
152        assert_eq!((g.in_phase[0], g.envelope[0]), (1.0, 1.0));
153        // At the cutoff time the envelope is exactly tpr dB.
154        let tc = gausspulse_cutoff(1000.0, 0.5, -6.0, -60.0).unwrap();
155        let e = gausspulse(&[tc], 1000.0, 0.5, -6.0).unwrap().envelope[0];
156        assert!((20.0 * e.log10() + 60.0).abs() < 1e-10);
157    }
158
159    #[test]
160    fn a_linear_chirp_is_a_linear_sweep_poly() {
161        // f(t) = 10 + 15 t sweeps from 10 Hz to 40 Hz over 2 s.
162        let lin = chirp(&[0.3, 1.1], 10.0, 2.0, 40.0, ChirpMethod::Linear, 0.0).unwrap();
163        let poly = sweep_poly(&[0.3, 1.1], &[15.0, 10.0], 0.0);
164        assert!(lin.iter().zip(&poly).all(|(a, b)| (a - b).abs() < 1e-12));
165        for method in [ChirpMethod::Quadratic { vertex_zero: false }, ChirpMethod::Logarithmic, ChirpMethod::Hyperbolic] {
166            assert!(chirp(&[0.0, 0.7, 2.0], 10.0, 2.0, 40.0, method, 0.0).unwrap().iter().all(|v| v.abs() <= 1.0));
167        }
168    }
169}