lib_jsl_dsp/discrete/sources/
sinusoid.rs1use super::cordic::{Cordic32, Cordic64};
6use super::nco::{Nco, NcoSource, Phase, Waveform};
7use lib_jsl_core::ErrorsJSL;
8
9#[derive(Clone, Debug)]
11pub enum SineKernel {
12 Direct,
14 Cordic(Cordic32),
17 Cordic64(Cordic64),
20}
21
22impl SineKernel {
23 pub fn sin_cos(&self, phase: Phase) -> (f64, f64) {
25 match self {
26 SineKernel::Direct => phase.radians().sin_cos(),
27 SineKernel::Cordic(c) => {
28 let angle = (phase.0.wrapping_add(1 << 31) >> 32) as u32;
30 let (s, co) = c.sin_cos_fixed(angle);
31 (s as f64 / Cordic32::ONE as f64, co as f64 / Cordic32::ONE as f64)
32 }
33 SineKernel::Cordic64(c) => {
34 let (s, co) = c.sin_cos_fixed(phase.0);
36 (s as f64 / Cordic64::ONE as f64, co as f64 / Cordic64::ONE as f64)
37 }
38 }
39 }
40}
41
42#[derive(Clone, Debug)]
44pub struct SineWave {
45 kernel: SineKernel,
46}
47
48impl SineWave {
49 pub fn new(kernel: SineKernel) -> SineWave {
50 SineWave { kernel }
51 }
52}
53
54impl Waveform for SineWave {
55 type Output = f64;
56
57 fn sample(&mut self, phase: Phase) -> f64 {
58 self.kernel.sin_cos(phase).0
59 }
60}
61
62impl NcoSource<SineWave> {
63 pub fn sinusoid(frequency_hz: f64, sample_rate: f64) -> Result<Self, ErrorsJSL> {
65 Ok(NcoSource::from_parts(Nco::new(frequency_hz, sample_rate)?, SineWave::new(SineKernel::Direct)))
66 }
67
68 pub fn sinusoid_cordic(frequency_hz: f64, sample_rate: f64, iterations: u32) -> Result<Self, ErrorsJSL> {
71 let kernel = SineKernel::Cordic(Cordic32::new(iterations)?);
72 Ok(NcoSource::from_parts(Nco::new(frequency_hz, sample_rate)?, SineWave::new(kernel)))
73 }
74
75 pub fn sinusoid_cordic64(frequency_hz: f64, sample_rate: f64, iterations: u32) -> Result<Self, ErrorsJSL> {
78 let kernel = SineKernel::Cordic64(Cordic64::new(iterations)?);
79 Ok(NcoSource::from_parts(Nco::new(frequency_hz, sample_rate)?, SineWave::new(kernel)))
80 }
81}
82
83pub fn sinusoid(frequency_hz: f64, sample_rate: f64, length: usize) -> Result<Vec<f64>, ErrorsJSL> {
85 Ok(NcoSource::sinusoid(frequency_hz, sample_rate)?.generate(length))
86}
87
88#[cfg(test)]
89mod tests {
90 use super::*;
91 use crate::discrete::stream_operator::StreamOperator;
92
93 #[test]
94 fn matches_the_analytic_sine() {
95 let x = sinusoid(440.0, 8000.0, 2000).unwrap();
96 for (n, v) in x.iter().enumerate() {
97 let want = (std::f64::consts::TAU * 440.0 * n as f64 / 8000.0).sin();
98 assert!((v - want).abs() < 1e-9, "n = {n}");
99 }
100 assert_eq!(x[0], 0.0);
101 }
102
103 #[test]
104 fn no_phase_drift_over_long_runs() {
105 let mut s = NcoSource::sinusoid(3.0, 1000.0).unwrap();
107 let _ = s.generate(10_000_000 - 1);
108 let last = s.next_sample();
109 let want = (std::f64::consts::TAU * 3.0 * 9_999_999.0 / 1000.0).sin();
110 assert!((last - want).abs() < 1e-6, "{last} vs {want}");
111 }
112
113 #[test]
114 fn cordic_kernel_agrees_with_direct() {
115 let mut direct = NcoSource::sinusoid(1234.5, 44_100.0).unwrap();
116 let mut cordic = NcoSource::sinusoid_cordic(1234.5, 44_100.0, 30).unwrap();
117 for _ in 0..3000 {
118 assert!((direct.next_sample() - cordic.next_sample()).abs() < 3e-8);
119 }
120 assert!(NcoSource::sinusoid_cordic(10.0, 100.0, 0).is_err());
121 assert!(NcoSource::sinusoid_cordic(10.0, 100.0, 31).is_err());
122 }
123
124 #[test]
125 fn cordic64_kernel_matches_double_precision_and_beats_the_32_bit_one() {
126 let mut direct = NcoSource::sinusoid(1234.5, 44_100.0).unwrap();
127 let mut wide = NcoSource::sinusoid_cordic64(1234.5, 44_100.0, 52).unwrap();
128 let mut narrow = NcoSource::sinusoid_cordic(1234.5, 44_100.0, 30).unwrap();
129 let (mut e_wide, mut e_narrow) = (0.0f64, 0.0f64);
130 for _ in 0..20_000 {
131 let d = direct.next_sample();
132 e_wide = e_wide.max((d - wide.next_sample()).abs());
133 e_narrow = e_narrow.max((d - narrow.next_sample()).abs());
134 }
135 assert!(e_wide < 3e-15, "64-bit kernel error {e_wide:e}");
136 assert!(e_narrow > 1e-10 && e_wide < e_narrow / 1000.0, "{e_wide:e} vs {e_narrow:e}");
137 assert!(NcoSource::sinusoid_cordic64(10.0, 100.0, 0).is_err());
138 assert!(NcoSource::sinusoid_cordic64(10.0, 100.0, 63).is_err());
139 }
140
141 #[test]
142 fn amplitude_offset_and_quadrature() {
143 let mut cosine = NcoSource::sinusoid(100.0, 1000.0).unwrap().with_phase_turns(0.25).with_amplitude(2.0).with_offset(1.0);
144 let x = cosine.generate(10);
145 for (n, v) in x.iter().enumerate() {
146 let want = 1.0 + 2.0 * (std::f64::consts::TAU * 0.1 * n as f64).cos();
147 assert!((v - want).abs() < 1e-12);
148 }
149 }
150
151 #[test]
152 fn works_through_the_stream_operator_trait() {
153 let mut s = NcoSource::sinusoid(50.0, 1000.0).unwrap();
154 let a = StreamOperator::<(), f64>::process(&mut s, &[(); 100]).unwrap().unwrap();
155 assert_eq!(a, sinusoid(50.0, 1000.0, 100).unwrap());
156 }
157
158 #[test]
159 fn tone_has_unit_power_at_the_right_frequency() {
160 let n = 4000;
161 let x = sinusoid(250.0, 4000.0, n).unwrap();
162 let (re, im) = x.iter().enumerate().fold((0.0, 0.0), |(r, i), (k, v)| {
163 let a = std::f64::consts::TAU * 250.0 * k as f64 / 4000.0;
164 (r + v * a.cos(), i - v * a.sin())
165 });
166 assert!(((re * re + im * im).sqrt() * 2.0 / n as f64 - 1.0).abs() < 1e-9);
167 assert!(sinusoid(5000.0, 4000.0, 10).is_err());
168 }
169}