lib_jsl_dsp/discrete/sources/
nco.rs1use crate::discrete::stream_operator::{StreamOperator, StreamOperatorManagement};
24use lib_jsl_core::ErrorsJSL;
25use num_complex::Complex;
26use std::fmt::Debug;
27
28const CYCLE: f64 = 18_446_744_073_709_551_616.0;
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Default)]
33pub struct Phase(pub u64);
34
35impl Phase {
36 pub fn from_turns(turns: f64) -> Phase {
38 Phase(tuning_word(turns))
39 }
40
41 pub fn turns(self) -> f64 {
43 self.0 as f64 / CYCLE
44 }
45
46 pub fn radians(self) -> f64 {
48 self.turns() * std::f64::consts::TAU
49 }
50}
51
52pub(crate) fn threshold_from_duty(duty: f64) -> Result<u128, ErrorsJSL> {
55 if !(0.0..=1.0).contains(&duty) {
56 return Err(ErrorsJSL::InvalidInputRange("Duty cycle must be between 0 and 1."));
57 }
58 Ok((duty * CYCLE).round() as u128)
59}
60
61pub(crate) fn threshold_from_ratio(numerator: u64, denominator: u64) -> Result<u128, ErrorsJSL> {
64 if denominator == 0 || numerator > denominator {
65 return Err(ErrorsJSL::InvalidInputRange("Duty ratio must satisfy 0 <= numerator <= denominator, denominator > 0."));
66 }
67 Ok(((numerator as u128) << 64).div_ceil(denominator as u128))
68}
69
70fn tuning_word(turns: f64) -> u64 {
72 let frac = turns.rem_euclid(1.0);
73 ((frac * CYCLE).round() as u128) as u64 }
75
76#[derive(Clone, Debug)]
78pub struct Nco {
79 phase: u64,
80 increment: u64,
81 initial_phase: u64,
82 sample_rate: f64,
83}
84
85impl Nco {
86 pub fn new(frequency_hz: f64, sample_rate: f64) -> Result<Nco, ErrorsJSL> {
89 if !(sample_rate.is_finite() && sample_rate > 0.0) {
90 return Err(ErrorsJSL::InvalidInputRange("NCO sample rate must be positive and finite."));
91 }
92 let mut nco = Nco { phase: 0, increment: 0, initial_phase: 0, sample_rate };
93 nco.set_frequency(frequency_hz)?;
94 Ok(nco)
95 }
96
97 pub fn from_period(period: u64) -> Result<Nco, ErrorsJSL> {
102 if period < 2 {
103 return Err(ErrorsJSL::InvalidInputRange("An NCO period must be at least 2 samples."));
104 }
105 let increment = (1u128 << 64).div_ceil(period as u128);
106 Ok(Nco { phase: 0, increment: increment as u64, initial_phase: 0, sample_rate: 1.0 })
107 }
108
109 pub fn with_phase_turns(mut self, turns: f64) -> Nco {
111 self.phase = tuning_word(turns);
112 self.initial_phase = self.phase;
113 self
114 }
115
116 pub fn set_frequency(&mut self, frequency_hz: f64) -> Result<(), ErrorsJSL> {
118 if !frequency_hz.is_finite() || frequency_hz.abs() > 0.5 * self.sample_rate {
119 return Err(ErrorsJSL::InvalidInputRange("NCO frequency must be finite and within Nyquist."));
120 }
121 self.increment = tuning_word(frequency_hz / self.sample_rate);
122 Ok(())
123 }
124
125 pub fn frequency(&self) -> f64 {
127 (self.increment as i64) as f64 / CYCLE * self.sample_rate
128 }
129
130 pub fn sample_rate(&self) -> f64 {
131 self.sample_rate
132 }
133
134 pub fn phase(&self) -> Phase {
136 Phase(self.phase)
137 }
138
139 pub fn set_phase_turns(&mut self, turns: f64) {
141 self.phase = tuning_word(turns);
142 }
143
144 pub fn next_phase(&mut self) -> Phase {
147 let current = Phase(self.phase);
148 self.phase = self.phase.wrapping_add(self.increment);
149 current
150 }
151 pub fn next_phase_modulated(&mut self, offset_hz: f64) -> Phase {
156 let current = Phase(self.phase);
157 let delta = tuning_word(offset_hz / self.sample_rate);
158 self.phase = self.phase.wrapping_add(self.increment).wrapping_add(delta);
159 current
160 }
161
162 pub fn reset(&mut self) {
164 self.phase = self.initial_phase;
165 }
166}
167
168pub trait Sample: Copy + Debug {
170 fn zero() -> Self;
172 fn scaled(self, amplitude: f64, offset: Self) -> Self;
174}
175
176impl Sample for f64 {
177 fn zero() -> f64 {
178 0.0
179 }
180 fn scaled(self, amplitude: f64, offset: f64) -> f64 {
181 amplitude * self + offset
182 }
183}
184
185impl Sample for Complex<f64> {
186 fn zero() -> Complex<f64> {
187 Complex::new(0.0, 0.0)
188 }
189 fn scaled(self, amplitude: f64, offset: Complex<f64>) -> Complex<f64> {
190 self * amplitude + offset
191 }
192}
193
194pub trait Waveform {
196 type Output: Sample;
198
199 fn sample(&mut self, phase: Phase) -> Self::Output;
202
203 fn reset(&mut self) {}
205}
206
207#[derive(Clone, Debug)]
209pub struct NcoSource<W: Waveform> {
210 nco: Nco,
211 waveform: W,
212 amplitude: f64,
213 offset: W::Output,
214}
215
216impl<W: Waveform> NcoSource<W> {
217 pub fn from_parts(nco: Nco, waveform: W) -> Self {
219 NcoSource { nco, waveform, amplitude: 1.0, offset: W::Output::zero() }
220 }
221
222 pub fn with_amplitude(mut self, amplitude: f64) -> Self {
224 self.amplitude = amplitude;
225 self
226 }
227
228 pub fn with_offset(mut self, offset: W::Output) -> Self {
230 self.offset = offset;
231 self
232 }
233
234 pub fn with_phase_turns(mut self, turns: f64) -> Self {
236 self.nco = self.nco.with_phase_turns(turns);
237 self
238 }
239
240 pub fn nco(&self) -> &Nco {
242 &self.nco
243 }
244
245 pub fn nco_mut(&mut self) -> &mut Nco {
246 &mut self.nco
247 }
248
249 pub fn waveform(&self) -> &W {
251 &self.waveform
252 }
253
254 pub fn waveform_mut(&mut self) -> &mut W {
255 &mut self.waveform
256 }
257
258 fn shape(&self, w: W::Output) -> W::Output {
259 w.scaled(self.amplitude, self.offset)
260 }
261
262 pub fn next_sample(&mut self) -> W::Output {
264 let phase = self.nco.next_phase();
265 let w = self.waveform.sample(phase);
266 self.shape(w)
267 }
268
269 pub fn next_sample_modulated(&mut self, offset_hz: f64) -> W::Output {
271 let phase = self.nco.next_phase_modulated(offset_hz);
272 let w = self.waveform.sample(phase);
273 self.shape(w)
274 }
275
276 pub fn generate(&mut self, count: usize) -> Vec<W::Output> {
278 (0..count).map(|_| self.next_sample()).collect()
279 }
280}
281
282impl<W: Waveform> StreamOperatorManagement for NcoSource<W> {
283 fn reset(&mut self) -> Result<(), ErrorsJSL> {
284 self.nco.reset();
285 self.waveform.reset();
286 Ok(())
287 }
288
289 fn finalize(&mut self) -> Result<(), ErrorsJSL> {
290 Ok(())
291 }
292}
293
294impl<W: Waveform> StreamOperator<(), W::Output> for NcoSource<W> {
296 fn process(&mut self, data_in: &[()]) -> Result<Option<Vec<W::Output>>, ErrorsJSL> {
297 if data_in.is_empty() {
298 return Ok(None);
299 }
300 Ok(Some(self.generate(data_in.len())))
301 }
302
303 fn flush(&mut self) -> Result<Option<Vec<W::Output>>, ErrorsJSL> {
304 Ok(None)
305 }
306}
307
308impl<W: Waveform> StreamOperator<f64, W::Output> for NcoSource<W> {
310 fn process(&mut self, data_in: &[f64]) -> Result<Option<Vec<W::Output>>, ErrorsJSL> {
311 if data_in.is_empty() {
312 return Ok(None);
313 }
314 Ok(Some(data_in.iter().map(|&df| self.next_sample_modulated(df)).collect()))
315 }
316
317 fn flush(&mut self) -> Result<Option<Vec<W::Output>>, ErrorsJSL> {
318 Ok(None)
319 }
320}
321
322#[cfg(test)]
323mod tests {
324 use super::*;
325
326 struct Identity;
327 impl Waveform for Identity {
328 type Output = f64;
329 fn sample(&mut self, phase: Phase) -> f64 {
330 phase.turns()
331 }
332 }
333
334 #[test]
335 fn frequency_round_trip_and_phase_ramp() {
336 let nco = Nco::new(1000.0, 8000.0).unwrap();
337 assert!((nco.frequency() - 1000.0).abs() < 1e-9);
338 let mut src = NcoSource::from_parts(nco, Identity);
339 let out = src.generate(10);
340 for (n, v) in out.iter().enumerate() {
341 assert!((v - (n as f64 / 8.0) % 1.0).abs() < 1e-12, "n = {n}");
342 }
343 let mut back = NcoSource::from_parts(Nco::new(-1000.0, 8000.0).unwrap(), Identity);
345 assert!((back.nco().frequency() + 1000.0).abs() < 1e-9);
346 let out = back.generate(3);
347 assert!((out[1] - 0.875).abs() < 1e-12 && (out[2] - 0.75).abs() < 1e-12);
348 }
349
350 #[test]
351 fn frequency_limits() {
352 assert!(Nco::new(5000.0, 8000.0).is_err());
353 assert!(Nco::new(f64::NAN, 8000.0).is_err());
354 assert!(Nco::new(100.0, 0.0).is_err());
355 assert!(Nco::new(4000.0, 8000.0).is_ok());
356 let mut nco = Nco::new(10.0, 100.0).unwrap();
357 assert!(nco.set_frequency(60.0).is_err());
358 assert!((nco.frequency() - 10.0).abs() < 1e-9, "failed retune leaves the frequency alone");
359 }
360
361 #[test]
362 fn exact_integer_periods() {
363 for period in [2u64, 3, 5, 6, 7, 10, 97, 1000, 4096] {
364 let mut nco = Nco::from_period(period).unwrap();
365 let cycles = 50;
366 for n in 0..period * cycles {
367 let p = nco.next_phase();
368 if n % period == 0 {
369 assert!(p.0 < period * cycles, "period {period}, n {n}: phase {}", p.0);
371 }
372 }
373 }
374 assert!(Nco::from_period(1).is_err());
375 assert!(Nco::from_period(0).is_err());
376 }
377
378 #[test]
379 fn reset_and_phase_control() {
380 let mut src = NcoSource::from_parts(Nco::new(1.0, 8.0).unwrap(), Identity).with_phase_turns(0.25);
381 let first = src.generate(4);
382 assert!((first[0] - 0.25).abs() < 1e-12);
383 StreamOperatorManagement::reset(&mut src).unwrap();
384 assert_eq!(src.generate(4), first, "reset returns to the configured starting phase");
385 src.nco_mut().set_phase_turns(0.5);
386 assert!((src.next_sample() - 0.5).abs() < 1e-12);
387 assert!((Phase::from_turns(-0.25).turns() - 0.75).abs() < 1e-12);
388 assert!((Phase::from_turns(1.5).turns() - 0.5).abs() < 1e-12);
389 assert!((Phase(1 << 62).radians() - std::f64::consts::FRAC_PI_2).abs() < 1e-12);
390 }
391
392 #[test]
393 fn amplitude_and_offset() {
394 let mut src = NcoSource::from_parts(Nco::new(1.0, 4.0).unwrap(), Identity).with_amplitude(4.0).with_offset(10.0);
395 let out = src.generate(4);
396 assert_eq!(out.iter().map(|v| v.round()).collect::<Vec<_>>(), vec![10.0, 11.0, 12.0, 13.0]);
397 }
398
399 #[test]
400 fn stream_operator_contract() {
401 let make = || NcoSource::from_parts(Nco::new(0.3, 8.0).unwrap(), Identity);
402 let mut a = make();
403 let whole = StreamOperator::<(), f64>::process(&mut a, &[(); 25]).unwrap().unwrap();
404 let mut b = make();
405 let mut chunked = Vec::new();
406 for n in [1usize, 7, 3, 14] {
407 chunked.extend(StreamOperator::<(), f64>::process(&mut b, &vec![(); n]).unwrap().unwrap());
408 }
409 assert_eq!(whole, chunked, "chunked processing is identical to one call");
410 assert!(StreamOperator::<(), f64>::process(&mut b, &[]).unwrap().is_none());
411 assert!(StreamOperator::<(), f64>::flush(&mut b).unwrap().is_none());
412 StreamOperatorManagement::reset(&mut b).unwrap();
413 assert_eq!(StreamOperator::<(), f64>::process(&mut b, &[(); 25]).unwrap().unwrap(), whole);
414 StreamOperatorManagement::finalize(&mut b).unwrap();
415 }
416
417 #[test]
418 fn frequency_modulation_input() {
419 let mut fm = NcoSource::from_parts(Nco::new(300.0, 8000.0).unwrap(), Identity);
421 let mut direct = NcoSource::from_parts(Nco::new(400.0, 8000.0).unwrap(), Identity);
422 let modulated = StreamOperator::<f64, f64>::process(&mut fm, &[100.0; 40]).unwrap().unwrap();
423 let reference = direct.generate(40);
424 for (m, r) in modulated.iter().zip(&reference) {
425 let d = (m - r).abs();
427 assert!(d.min(1.0 - d) < 1e-9, "{m} vs {r}");
428 }
429 assert!((fm.nco().frequency() - 300.0).abs() < 1e-9, "modulation does not retune the NCO");
430 assert!(StreamOperator::<f64, f64>::process(&mut fm, &[]).unwrap().is_none());
431 }
432}