Skip to main content

lib_jsl_dsp/discrete/sources/
nco.rs

1//! A numerically controlled oscillator (NCO) and the machinery shared by every signal source.
2//!
3//! The oscillator is a fixed-point phase accumulator: the phase is a `u64` where `2^64` is one full
4//! cycle, advanced each sample by a frequency tuning word. Wrap-around is free, the phase never
5//! drifts, and frequency resolution is `sample_rate / 2^64`.
6//!
7//! A source is an [`NcoSource`], which pairs an [`Nco`] with a [`Waveform`] that maps phase to an
8//! amplitude, plus an output amplitude and offset. Sine, square, triangle, ramp, pulse-train and
9//! noise sources are all just different waveforms driven by the same oscillator, and they all
10//! implement [`StreamOperator`] through the one implementation here.
11//!
12//! All periodic waveforms share the sine's phase reference: at phase 0 they are at their
13//! rising zero crossing (or, for the 0/1 pulse train, at the start of the pulse).
14//!
15//! # Streaming
16//! A source implements `StreamOperator<(), Output>` (free-running: the length of the input slice is
17//! the number of samples to produce) and `StreamOperator<f64, Output>` (frequency modulation: each
18//! input value is an instantaneous frequency offset in Hz added to the oscillator frequency), where
19//! `Output` is `f64` for real sources and `Complex<f64>` for the quadrature source.
20//!
21//! See the book entry [Signal sources: oscillators, CORDIC and waveforms](https://jwkunz.github.io/lib_jsl/book/comms/sources.html#phase-accumulation).
22
23use crate::discrete::stream_operator::{StreamOperator, StreamOperatorManagement};
24use lib_jsl_core::ErrorsJSL;
25use num_complex::Complex;
26use std::fmt::Debug;
27
28/// `2^64` as a float: one full cycle of the phase accumulator.
29const CYCLE: f64 = 18_446_744_073_709_551_616.0;
30
31/// A point in the oscillator's cycle, as a fraction of a turn in `[0, 1)` scaled by `2^64`.
32#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Default)]
33pub struct Phase(pub u64);
34
35impl Phase {
36    /// Builds a phase from a (possibly negative or greater than one) number of turns.
37    pub fn from_turns(turns: f64) -> Phase {
38        Phase(tuning_word(turns))
39    }
40
41    /// The phase as a fraction of a turn in `[0, 1)`.
42    pub fn turns(self) -> f64 {
43        self.0 as f64 / CYCLE
44    }
45
46    /// The phase in radians in `[0, 2π)`.
47    pub fn radians(self) -> f64 {
48        self.turns() * std::f64::consts::TAU
49    }
50}
51
52/// Phase threshold (in `2^-64` turns, up to and including `2^64`) for a duty cycle in `[0, 1]`:
53/// a waveform is "high" while its phase is below the threshold.
54pub(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
61/// Exact threshold for a duty cycle of `numerator / denominator`, rounded up so that on an
62/// [`Nco::from_period`] oscillator exactly `numerator` of every `denominator` samples are high.
63pub(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
70/// Converts a number of turns (modulo 1) into a fixed-point tuning word.
71fn tuning_word(turns: f64) -> u64 {
72    let frac = turns.rem_euclid(1.0);
73    ((frac * CYCLE).round() as u128) as u64 // 2^64 wraps to 0
74}
75
76/// A numerically controlled oscillator.
77#[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    /// An oscillator at `frequency_hz` for the given sampling rate. The frequency may be negative
87    /// (the phase runs backwards) and must not exceed Nyquist, `sample_rate / 2`, in magnitude.
88    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    /// An oscillator that completes exactly one cycle every `period` samples (`period >= 2`).
98    ///
99    /// The tuning word is rounded *up*, so samples that fall exactly on a waveform edge (for
100    /// example the 4th sample of a 6-sample square wave) always land on the late side of it.
101    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    /// Sets the starting phase (and the phase that [`reset`](Self::reset) returns to), in turns.
110    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    /// Changes the frequency without disturbing the phase.
117    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    /// The frequency actually realised by the tuning word, in Hz (negative if running backwards).
126    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    /// The phase that the next call to [`next_phase`](Self::next_phase) will return.
135    pub fn phase(&self) -> Phase {
136        Phase(self.phase)
137    }
138
139    /// Jumps to the given phase (in turns).
140    pub fn set_phase_turns(&mut self, turns: f64) {
141        self.phase = tuning_word(turns);
142    }
143
144    /// Returns the current phase and then advances by one sample.
145    // ANCHOR: nco
146    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    // ANCHOR_END: nco
152
153    /// Like [`next_phase`](Self::next_phase), but this step advances at the oscillator frequency
154    /// plus `offset_hz` (frequency modulation). The configured frequency is unchanged.
155    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    /// Returns to the starting phase.
163    pub fn reset(&mut self) {
164        self.phase = self.initial_phase;
165    }
166}
167
168/// A type a source can emit: real (`f64`) or complex (`Complex<f64>`) samples.
169pub trait Sample: Copy + Debug {
170    /// The additive identity, used as the default offset.
171    fn zero() -> Self;
172    /// `amplitude * self + offset`.
173    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
194/// Maps oscillator phase to an output value.
195pub trait Waveform {
196    /// The type of sample produced: `f64` for real waveforms, `Complex<f64>` for quadrature.
197    type Output: Sample;
198
199    /// The waveform value at `phase`. Called once per output sample, in order, so stateful
200    /// waveforms (such as sample-and-hold noise) may keep history.
201    fn sample(&mut self, phase: Phase) -> Self::Output;
202
203    /// Returns any internal state to its starting condition.
204    fn reset(&mut self) {}
205}
206
207/// A signal source: an [`Nco`] driving a [`Waveform`], scaled by `amplitude` and shifted by `offset`.
208#[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    /// Builds a unit-amplitude, zero-offset source from an oscillator and a waveform.
218    pub fn from_parts(nco: Nco, waveform: W) -> Self {
219        NcoSource { nco, waveform, amplitude: 1.0, offset: W::Output::zero() }
220    }
221
222    /// Sets the output amplitude (a multiplier on the waveform).
223    pub fn with_amplitude(mut self, amplitude: f64) -> Self {
224        self.amplitude = amplitude;
225        self
226    }
227
228    /// Sets a constant added to every output sample (a complex constant for complex sources).
229    pub fn with_offset(mut self, offset: W::Output) -> Self {
230        self.offset = offset;
231        self
232    }
233
234    /// Sets the starting phase in turns (a quarter turn turns a sine into a cosine).
235    pub fn with_phase_turns(mut self, turns: f64) -> Self {
236        self.nco = self.nco.with_phase_turns(turns);
237        self
238    }
239
240    /// Access to the oscillator, e.g. to retune it.
241    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    /// Access to the waveform.
250    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    /// Produces the next output sample.
263    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    /// Produces the next output sample with the frequency offset by `offset_hz` for this step.
270    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    /// Produces the next `count` samples.
277    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
294/// Free-running operation: the number of input items is the number of samples produced.
295impl<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
308/// Frequency-modulated operation: each input is a frequency offset in Hz for that sample.
309impl<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        // Negative frequency runs the phase backwards.
344        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                    // Never negative-of-zero; the accumulated rounding is far below one sample.
370                    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        // A constant offset of +100 Hz equals running at the shifted frequency.
420        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            // Phases are cyclic, so compare on the circle (rounding can straddle a wrap point).
426            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}