Skip to main content

lib_jsl_dsp/discrete/sources/
ramp.rs

1//! Ramp (sawtooth) 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 rising sawtooth aligned with the sine: it crosses zero going up at phase 0, reaches `+1` just
9/// before half a turn, jumps to `-1`, and rises again.
10#[derive(Clone, Copy, Debug, Default)]
11pub struct RampWave;
12
13impl Waveform for RampWave {
14    type Output = f64;
15
16    fn sample(&mut self, phase: Phase) -> f64 {
17        // Shifting by half a turn is an exact wrapping add on the fixed-point phase.
18        let shifted = phase.0.wrapping_add(1 << 63);
19        shifted as f64 / 18_446_744_073_709_551_616.0 * 2.0 - 1.0
20    }
21}
22
23impl NcoSource<RampWave> {
24    /// A rising sawtooth at `frequency_hz`. A negative frequency gives a falling sawtooth.
25    pub fn ramp(frequency_hz: f64, sample_rate: f64) -> Result<Self, ErrorsJSL> {
26        Ok(NcoSource::from_parts(Nco::new(frequency_hz, sample_rate)?, RampWave))
27    }
28
29    /// A rising sawtooth with an integer `period` in samples (>= 2).
30    pub fn ramp_with_period(period: u64) -> Result<Self, ErrorsJSL> {
31        Ok(NcoSource::from_parts(Nco::from_period(period)?, RampWave))
32    }
33}
34
35/// Convenience: `length` samples of a unit sawtooth with an integer `period` (>= 2).
36pub fn ramp(period: usize, length: usize) -> Result<Vec<f64>, ErrorsJSL> {
37    Ok(NcoSource::ramp_with_period(period as u64)?.generate(length))
38}
39
40#[cfg(test)]
41mod tests {
42    use super::*;
43
44    #[test]
45    fn exact_shape() {
46        let x = ramp(8, 16).unwrap();
47        let want = [0.0, 0.25, 0.5, 0.75, -1.0, -0.75, -0.5, -0.25];
48        for (n, v) in x.iter().enumerate() {
49            assert!((v - want[n % 8]).abs() < 1e-12, "n = {n}: {v}");
50        }
51        assert!(ramp(1, 4).is_err());
52    }
53
54    #[test]
55    fn constant_slope_and_range() {
56        let x = ramp(50, 500).unwrap();
57        assert!(x.iter().all(|v| (-1.0..1.0).contains(v)));
58        let mut jumps = 0;
59        for w in x.windows(2) {
60            let d = w[1] - w[0];
61            if d < 0.0 {
62                jumps += 1;
63                assert!((d + 2.0 - 2.0 / 50.0).abs() < 1e-9);
64            } else {
65                assert!((d - 2.0 / 50.0).abs() < 1e-9);
66            }
67        }
68        assert_eq!(jumps, 10, "one wrap every 50 samples, first at n = 25");
69    }
70
71    #[test]
72    fn negative_frequency_falls() {
73        let mut r = NcoSource::ramp(-1.0, 8.0).unwrap();
74        let x = r.generate(4);
75        assert!((x[0]).abs() < 1e-12 && (x[1] + 0.25).abs() < 1e-12 && (x[2] + 0.5).abs() < 1e-12);
76    }
77
78    #[test]
79    fn zero_mean() {
80        let x = ramp(100, 10_000).unwrap();
81        assert!((x.iter().sum::<f64>() / x.len() as f64).abs() < 0.01);
82    }
83}