Skip to main content

lib_jsl_dsp/discrete/sources/
noise.rs

1//! Noise 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;
7use lib_jsl_random::distributions::gaussian_distribution_box_muller;
8use lib_jsl_random::uniform_generator::UniformGenerator;
9use lib_jsl_random::xoshiro256plusplus::Xoshiro256PlusPlus;
10
11/// The amplitude distribution of the noise before amplitude/offset scaling.
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub enum NoiseKind {
14    /// Uniform on `[-1, 1)`: mean 0, variance 1/3.
15    Uniform,
16    /// Gaussian with mean 0 and variance 1.
17    Gaussian,
18}
19
20/// A pseudo-random noise waveform.
21///
22/// In *white* mode a fresh value is drawn for every sample. In *sample-and-hold* mode a new value
23/// is drawn each time the oscillator phase wraps and held in between, giving noise that changes at
24/// the oscillator frequency (this requires a positive oscillator frequency). The generator is
25/// seeded, so output is reproducible and [`reset`](Waveform::reset) replays the same sequence.
26#[derive(Clone, Debug)]
27pub struct NoiseWave {
28    kind: NoiseKind,
29    seed: u64,
30    rng: Xoshiro256PlusPlus,
31    hold: bool,
32    last_phase: u64,
33    held: f64,
34    started: bool,
35    spare: Option<f64>,
36}
37
38impl NoiseWave {
39    fn new(kind: NoiseKind, seed: u64, hold: bool) -> NoiseWave {
40        NoiseWave { kind, seed, rng: Xoshiro256PlusPlus::from_seed(seed), hold, last_phase: 0, held: 0.0, started: false, spare: None }
41    }
42
43    fn draw(&mut self) -> f64 {
44        match self.kind {
45            NoiseKind::Uniform => 2.0 * self.rng.next_f64() - 1.0,
46            NoiseKind::Gaussian => {
47                if let Some(v) = self.spare.take() {
48                    return v;
49                }
50                loop {
51                    let (a, b) = gaussian_distribution_box_muller(&mut self.rng, 0.0, 1.0);
52                    if a.is_finite() && b.is_finite() {
53                        self.spare = Some(b);
54                        return a;
55                    }
56                }
57            }
58        }
59    }
60}
61
62impl Waveform for NoiseWave {
63    type Output = f64;
64
65    fn sample(&mut self, phase: Phase) -> f64 {
66        if !self.hold {
67            return self.draw();
68        }
69        if !self.started || phase.0 < self.last_phase {
70            self.held = self.draw();
71            self.started = true;
72        }
73        self.last_phase = phase.0;
74        self.held
75    }
76
77    fn reset(&mut self) {
78        self.rng = Xoshiro256PlusPlus::from_seed(self.seed);
79        self.last_phase = 0;
80        self.held = 0.0;
81        self.started = false;
82        self.spare = None;
83    }
84}
85
86impl NcoSource<NoiseWave> {
87    /// White noise: an independent value every sample.
88    pub fn white_noise(kind: NoiseKind, seed: u64) -> Self {
89        let nco = Nco::new(0.25, 1.0).expect("valid placeholder oscillator");
90        NcoSource::from_parts(nco, NoiseWave::new(kind, seed, false))
91    }
92
93    /// Sample-and-hold noise that draws a new value `rate_hz` times per second.
94    pub fn sample_and_hold_noise(kind: NoiseKind, seed: u64, rate_hz: f64, sample_rate: f64) -> Result<Self, ErrorsJSL> {
95        if rate_hz <= 0.0 {
96            return Err(ErrorsJSL::InvalidInputRange("Sample-and-hold noise needs a positive update rate."));
97        }
98        Ok(NcoSource::from_parts(Nco::new(rate_hz, sample_rate)?, NoiseWave::new(kind, seed, true)))
99    }
100}
101
102/// Convenience: `length` samples of unit-variance white Gaussian noise from the given `seed`.
103pub fn noise(length: usize, seed: u64) -> Vec<f64> {
104    NcoSource::white_noise(NoiseKind::Gaussian, seed).generate(length)
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110    use crate::discrete::stream_operator::{StreamOperator, StreamOperatorManagement};
111
112    fn mean_var(x: &[f64]) -> (f64, f64) {
113        let m = x.iter().sum::<f64>() / x.len() as f64;
114        (m, x.iter().map(|v| (v - m).powi(2)).sum::<f64>() / x.len() as f64)
115    }
116
117    #[test]
118    fn gaussian_statistics() {
119        let x = noise(200_000, 1);
120        let (m, v) = mean_var(&x);
121        assert!(m.abs() < 0.01 && (v - 1.0).abs() < 0.02, "mean {m} var {v}");
122        // About 68% within one standard deviation.
123        let within = x.iter().filter(|v| v.abs() < 1.0).count() as f64 / x.len() as f64;
124        assert!((within - 0.6827).abs() < 0.01);
125    }
126
127    #[test]
128    fn uniform_statistics_and_bounds() {
129        let x = NcoSource::white_noise(NoiseKind::Uniform, 2).generate(200_000);
130        assert!(x.iter().all(|v| (-1.0..1.0).contains(v)));
131        let (m, v) = mean_var(&x);
132        assert!(m.abs() < 0.01 && (v - 1.0 / 3.0).abs() < 0.01, "mean {m} var {v}");
133    }
134
135    #[test]
136    fn white_noise_is_uncorrelated() {
137        let x = noise(100_000, 3);
138        for lag in 1..5 {
139            let c: f64 = x.iter().zip(&x[lag..]).map(|(a, b)| a * b).sum::<f64>() / x.len() as f64;
140            assert!(c.abs() < 0.02, "lag {lag}: {c}");
141        }
142    }
143
144    #[test]
145    fn seeded_and_resettable() {
146        assert_eq!(noise(100, 5), noise(100, 5));
147        assert_ne!(noise(100, 5), noise(100, 6));
148        let mut s = NcoSource::white_noise(NoiseKind::Gaussian, 9);
149        let first = s.generate(51); // odd count exercises the cached second Box-Muller value
150        StreamOperatorManagement::reset(&mut s).unwrap();
151        assert_eq!(s.generate(51), first);
152    }
153
154    #[test]
155    fn amplitude_and_offset_scale_the_noise() {
156        let mut s = NcoSource::white_noise(NoiseKind::Gaussian, 4).with_amplitude(3.0).with_offset(5.0);
157        let (m, v) = mean_var(&s.generate(100_000));
158        assert!((m - 5.0).abs() < 0.05 && (v - 9.0).abs() < 0.2, "mean {m} var {v}");
159    }
160
161    #[test]
162    fn sample_and_hold_updates_at_the_oscillator_rate() {
163        // 25 Hz at 100 Hz sampling: a new value every 4 samples.
164        let mut s = NcoSource::sample_and_hold_noise(NoiseKind::Uniform, 7, 25.0, 100.0).unwrap();
165        let x = s.generate(40);
166        for block in x.chunks(4) {
167            assert!(block.iter().all(|&v| v == block[0]), "{block:?}");
168        }
169        let distinct: std::collections::BTreeSet<u64> = x.iter().map(|v| v.to_bits()).collect();
170        assert_eq!(distinct.len(), 10);
171        assert!(NcoSource::sample_and_hold_noise(NoiseKind::Uniform, 1, 0.0, 100.0).is_err());
172        assert!(NcoSource::sample_and_hold_noise(NoiseKind::Uniform, 1, 80.0, 100.0).is_err());
173    }
174
175    #[test]
176    fn stream_operator_interface() {
177        let mut s = NcoSource::white_noise(NoiseKind::Gaussian, 11);
178        let a = StreamOperator::<(), f64>::process(&mut s, &[(); 30]).unwrap().unwrap();
179        assert_eq!(a, noise(30, 11));
180    }
181}