Skip to main content

lib_jsl_dsp/discrete/sources/
triangle.rs

1//! Triangle wave source.
2//!
3//! See the book entry [Signal sources: oscillators, CORDIC and waveforms](https://jwkunz.github.io/lib_jsl/book/comms/sources.html#waveforms-and-noise).
4
5use super::nco::{Nco, NcoSource, Phase, Waveform};
6use lib_jsl_core::ErrorsJSL;
7
8/// A symmetric triangle wave aligned with the sine: 0 at phase 0, `+1` at a quarter turn, 0 at
9/// half a turn, `-1` at three quarters.
10#[derive(Clone, Copy, Debug, Default)]
11pub struct TriangleWave;
12
13impl Waveform for TriangleWave {
14    type Output = f64;
15
16    fn sample(&mut self, phase: Phase) -> f64 {
17        let t = phase.turns();
18        if t < 0.25 {
19            4.0 * t
20        } else if t < 0.75 {
21            2.0 - 4.0 * t
22        } else {
23            4.0 * t - 4.0
24        }
25    }
26}
27
28impl NcoSource<TriangleWave> {
29    /// A triangle wave at `frequency_hz`.
30    pub fn triangle(frequency_hz: f64, sample_rate: f64) -> Result<Self, ErrorsJSL> {
31        Ok(NcoSource::from_parts(Nco::new(frequency_hz, sample_rate)?, TriangleWave))
32    }
33
34    /// A triangle wave with an integer `period` in samples (>= 2).
35    pub fn triangle_with_period(period: u64) -> Result<Self, ErrorsJSL> {
36        Ok(NcoSource::from_parts(Nco::from_period(period)?, TriangleWave))
37    }
38}
39
40/// Convenience: `length` samples of a unit triangle wave with an integer `period` (>= 2).
41pub fn triangle(period: usize, length: usize) -> Result<Vec<f64>, ErrorsJSL> {
42    Ok(NcoSource::triangle_with_period(period as u64)?.generate(length))
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn exact_shape() {
51        let x = triangle(8, 8).unwrap();
52        let want = [0.0, 0.5, 1.0, 0.5, 0.0, -0.5, -1.0, -0.5];
53        for (a, b) in x.iter().zip(want) {
54            assert!((a - b).abs() < 1e-12, "{x:?}");
55        }
56        let x = triangle(4, 4).unwrap();
57        assert!((x[0]).abs() < 1e-12 && (x[1] - 1.0).abs() < 1e-12 && x[2].abs() < 1e-12 && (x[3] + 1.0).abs() < 1e-12);
58        assert!(triangle(1, 4).is_err());
59    }
60
61    #[test]
62    fn periodic_continuous_and_bounded() {
63        let x = triangle(100, 1000).unwrap();
64        for i in 0..900 {
65            assert!((x[i] - x[i + 100]).abs() < 1e-9, "periodicity");
66        }
67        assert!(x.iter().all(|v| v.abs() <= 1.0 + 1e-12));
68        // The slope magnitude is constant (4 / period) away from the corners.
69        for w in x.windows(2) {
70            assert!(((w[1] - w[0]).abs() - 0.04).abs() < 1e-9);
71        }
72    }
73
74    #[test]
75    fn triangle_is_the_arcsine_of_the_sine() {
76        let mut tri = NcoSource::triangle(3.0, 100.0).unwrap();
77        let mut sin = NcoSource::sinusoid(3.0, 100.0).unwrap();
78        for _ in 0..200 {
79            let (t, s) = (tri.next_sample(), sin.next_sample());
80            assert!((t - 2.0 / std::f64::consts::PI * s.asin()).abs() < 1e-9);
81        }
82    }
83}