Skip to main content

lib_jsl_dsp/discrete/sources/
quadrature.rs

1//! Quadrature (complex) source: cosine on the real axis, sine on the imaginary axis.
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 super::sinusoid::SineKernel;
7use super::cordic::{Cordic32, Cordic64};
8use lib_jsl_core::ErrorsJSL;
9use num_complex::Complex;
10
11/// The sense in which the quadrature output rotates, i.e. the sign of its imaginary (sine) part.
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub enum Polarity {
14    /// `cos θ + j sin θ = e^{+jθ}`: rotates counter-clockwise, so a positive oscillator frequency
15    /// appears at a positive frequency in the spectrum.
16    Positive,
17    /// `cos θ − j sin θ = e^{−jθ}`: the complex conjugate; rotates clockwise, which mirrors the
18    /// spectrum (the same as running the oscillator at the negative frequency).
19    Negative,
20}
21
22impl Polarity {
23    /// `+1.0` for [`Positive`](Polarity::Positive), `-1.0` for [`Negative`](Polarity::Negative).
24    pub fn sign(self) -> f64 {
25        match self {
26            Polarity::Positive => 1.0,
27            Polarity::Negative => -1.0,
28        }
29    }
30}
31
32/// The quadrature waveform: `cos(2π·phase) + j·polarity·sin(2π·phase)`, from one shared kernel
33/// evaluation (a single CORDIC pass yields both components).
34#[derive(Clone, Debug)]
35pub struct QuadratureWave {
36    kernel: SineKernel,
37    polarity: Polarity,
38}
39
40impl QuadratureWave {
41    pub fn new(kernel: SineKernel, polarity: Polarity) -> QuadratureWave {
42        QuadratureWave { kernel, polarity }
43    }
44
45    pub fn polarity(&self) -> Polarity {
46        self.polarity
47    }
48
49    /// Changes the polarity; takes effect from the next sample, with the phase unbroken.
50    pub fn set_polarity(&mut self, polarity: Polarity) {
51        self.polarity = polarity;
52    }
53}
54
55impl Waveform for QuadratureWave {
56    type Output = Complex<f64>;
57
58    fn sample(&mut self, phase: Phase) -> Complex<f64> {
59        let (s, c) = self.kernel.sin_cos(phase);
60        Complex::new(c, self.polarity.sign() * s)
61    }
62}
63
64impl NcoSource<QuadratureWave> {
65    /// A quadrature source at `frequency_hz` using floating-point `sin`/`cos`.
66    pub fn quadrature(frequency_hz: f64, sample_rate: f64, polarity: Polarity) -> Result<Self, ErrorsJSL> {
67        Ok(NcoSource::from_parts(Nco::new(frequency_hz, sample_rate)?, QuadratureWave::new(SineKernel::Direct, polarity)))
68    }
69
70    /// A quadrature source whose sine and cosine come from a single 32-bit integer CORDIC pass
71    /// with `iterations` (1 to 30) micro-rotations (accurate to about 1e-8).
72    pub fn quadrature_cordic(frequency_hz: f64, sample_rate: f64, polarity: Polarity, iterations: u32) -> Result<Self, ErrorsJSL> {
73        let kernel = SineKernel::Cordic(Cordic32::new(iterations)?);
74        Ok(NcoSource::from_parts(Nco::new(frequency_hz, sample_rate)?, QuadratureWave::new(kernel, polarity)))
75    }
76
77    /// Like [`quadrature_cordic`](Self::quadrature_cordic) but with the 64-bit CORDIC
78    /// (`iterations` 1 to 62; 52 or more reaches double-precision accuracy) driven by the
79    /// oscillator's full 64-bit phase.
80    pub fn quadrature_cordic64(frequency_hz: f64, sample_rate: f64, polarity: Polarity, iterations: u32) -> Result<Self, ErrorsJSL> {
81        let kernel = SineKernel::Cordic64(Cordic64::new(iterations)?);
82        Ok(NcoSource::from_parts(Nco::new(frequency_hz, sample_rate)?, QuadratureWave::new(kernel, polarity)))
83    }
84
85    /// The current polarity.
86    pub fn polarity(&self) -> Polarity {
87        self.waveform().polarity()
88    }
89
90    /// Changes the polarity; the phase continues without a jump.
91    pub fn set_polarity(&mut self, polarity: Polarity) {
92        self.waveform_mut().set_polarity(polarity);
93    }
94}
95
96/// Convenience: `length` samples of a unit complex tone at `frequency_hz`.
97pub fn quadrature(frequency_hz: f64, sample_rate: f64, length: usize, polarity: Polarity) -> Result<Vec<Complex<f64>>, ErrorsJSL> {
98    Ok(NcoSource::quadrature(frequency_hz, sample_rate, polarity)?.generate(length))
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104    use crate::discrete::stream_operator::{StreamOperator, StreamOperatorManagement};
105    use std::f64::consts::TAU;
106
107    /// Magnitude of the DFT of `x` at normalized frequency `f` (cycles per sample).
108    fn dft_at(x: &[Complex<f64>], f: f64) -> f64 {
109        let sum: Complex<f64> = x.iter().enumerate().map(|(n, v)| v * Complex::from_polar(1.0, -TAU * f * n as f64)).sum();
110        sum.norm() / x.len() as f64
111    }
112
113    #[test]
114    fn positive_polarity_is_the_complex_exponential() {
115        let x = quadrature(1000.0, 8000.0, 100, Polarity::Positive).unwrap();
116        for (n, v) in x.iter().enumerate() {
117            let want = Complex::from_polar(1.0, TAU * 0.125 * n as f64);
118            assert!((v - want).norm() < 1e-9, "n = {n}");
119        }
120        assert!((x[0] - Complex::new(1.0, 0.0)).norm() < 1e-12);
121        assert!((x[2] - Complex::new(0.0, 1.0)).norm() < 1e-9, "a quarter turn is +j");
122    }
123
124    #[test]
125    fn negative_polarity_is_the_conjugate() {
126        let pos = quadrature(1234.0, 10_000.0, 200, Polarity::Positive).unwrap();
127        let neg = quadrature(1234.0, 10_000.0, 200, Polarity::Negative).unwrap();
128        for (p, n) in pos.iter().zip(&neg) {
129            assert_eq!(p.re, n.re);
130            assert_eq!(p.im, -n.im);
131        }
132        assert_eq!(Polarity::Positive.sign(), 1.0);
133        assert_eq!(Polarity::Negative.sign(), -1.0);
134    }
135
136    #[test]
137    fn spectrum_is_single_sided_and_polarity_mirrors_it() {
138        let n = 800;
139        let f = 0.1;
140        let pos = quadrature(f * 8000.0, 8000.0, n, Polarity::Positive).unwrap();
141        let neg = quadrature(f * 8000.0, 8000.0, n, Polarity::Negative).unwrap();
142        assert!((dft_at(&pos, f) - 1.0).abs() < 1e-9, "all the energy at +f");
143        assert!(dft_at(&pos, -f) < 1e-9, "no image at -f");
144        assert!((dft_at(&neg, -f) - 1.0).abs() < 1e-9);
145        assert!(dft_at(&neg, f) < 1e-9);
146        // Negative polarity equals negative frequency.
147        let backwards = quadrature(-f * 8000.0, 8000.0, n, Polarity::Positive).unwrap();
148        for (a, b) in neg.iter().zip(&backwards) {
149            assert!((a - b).norm() < 1e-9);
150        }
151    }
152
153    #[test]
154    fn cordic_kernel_gives_both_components_with_unit_magnitude() {
155        let mut direct = NcoSource::quadrature(777.7, 48_000.0, Polarity::Positive).unwrap();
156        let mut cordic = NcoSource::quadrature_cordic(777.7, 48_000.0, Polarity::Positive, 30).unwrap();
157        for _ in 0..5000 {
158            let (d, c) = (direct.next_sample(), cordic.next_sample());
159            assert!((d - c).norm() < 5e-8);
160            assert!((c.norm() - 1.0).abs() < 2e-8);
161        }
162        // The single-sided spectrum survives the fixed-point arithmetic (image below ~ -150 dBc).
163        // (800 Hz at 8 kHz: 36-degree steps and exactly 80 cycles in 800 samples, so no leakage.)
164        let x = NcoSource::quadrature_cordic(800.0, 8000.0, Polarity::Positive, 30).unwrap().generate(800);
165        assert!(dft_at(&x, -0.1) < 5e-8 && (dft_at(&x, 0.1) - 1.0).abs() < 5e-8);
166        assert!(NcoSource::quadrature_cordic(1.0, 10.0, Polarity::Positive, 0).is_err());
167        // A coarse rotator is visibly worse.
168        let coarse = NcoSource::quadrature_cordic(800.0, 8000.0, Polarity::Positive, 8).unwrap().generate(800);
169        assert!(dft_at(&coarse, -0.1) > 1e-4, "image {}", dft_at(&coarse, -0.1));
170    }
171
172    #[test]
173    fn cordic64_quadrature_is_double_precision_clean() {
174        // 800 Hz at 8 kHz: exactly 80 cycles in 800 samples, so the image bin has no leakage.
175        let x = NcoSource::quadrature_cordic64(800.0, 8000.0, Polarity::Positive, 52).unwrap().generate(800);
176        assert!(dft_at(&x, -0.1) < 5e-15, "image {}", dft_at(&x, -0.1));
177        assert!((dft_at(&x, 0.1) - 1.0).abs() < 5e-15);
178        for v in &x {
179            assert!((v.norm() - 1.0).abs() < 3e-15);
180        }
181        let mut direct = NcoSource::quadrature(333.3, 8000.0, Polarity::Negative).unwrap();
182        let mut wide = NcoSource::quadrature_cordic64(333.3, 8000.0, Polarity::Negative, 52).unwrap();
183        for _ in 0..3000 {
184            assert!((direct.next_sample() - wide.next_sample()).norm() < 5e-15);
185        }
186        assert!(NcoSource::quadrature_cordic64(1.0, 10.0, Polarity::Positive, 63).is_err());
187    }
188
189    #[test]
190    fn polarity_can_be_switched_mid_stream_without_a_phase_jump() {
191        let mut s = NcoSource::quadrature(1000.0, 8000.0, Polarity::Positive).unwrap();
192        let before = s.generate(5);
193        s.set_polarity(Polarity::Negative);
194        assert_eq!(s.polarity(), Polarity::Negative);
195        let after = s.generate(5);
196        // Real part continues the cosine; the imaginary part flips sign relative to the sine.
197        for (k, v) in after.iter().enumerate() {
198            let n = (5 + k) as f64;
199            assert!((v.re - (TAU * 0.125 * n).cos()).abs() < 1e-9);
200            assert!((v.im + (TAU * 0.125 * n).sin()).abs() < 1e-9);
201        }
202        assert!((before[4].re - (TAU * 0.5).cos()).abs() < 1e-9);
203    }
204
205    #[test]
206    fn stream_operator_amplitude_offset_and_modulation() {
207        let mut s = NcoSource::quadrature(500.0, 8000.0, Polarity::Positive).unwrap();
208        let a = StreamOperator::<(), Complex<f64>>::process(&mut s, &[(); 64]).unwrap().unwrap();
209        assert_eq!(a, quadrature(500.0, 8000.0, 64, Polarity::Positive).unwrap());
210        StreamOperatorManagement::reset(&mut s).unwrap();
211        assert_eq!(StreamOperator::<(), Complex<f64>>::process(&mut s, &[(); 64]).unwrap().unwrap(), a);
212        assert!(StreamOperator::<(), Complex<f64>>::flush(&mut s).unwrap().is_none());
213        assert!(StreamOperator::<(), Complex<f64>>::process(&mut s, &[]).unwrap().is_none());
214
215        // Scaling and a complex DC offset.
216        let mut scaled = NcoSource::quadrature(1000.0, 8000.0, Polarity::Positive).unwrap().with_amplitude(2.0).with_offset(Complex::new(1.0, -3.0));
217        let v = scaled.generate(3);
218        assert!((v[0] - Complex::new(3.0, -3.0)).norm() < 1e-12);
219        assert!((v[2] - Complex::new(1.0, -1.0)).norm() < 1e-9);
220
221        // FM: +250 Hz of offset on a 750 Hz oscillator equals a 1 kHz tone.
222        let mut fm = NcoSource::quadrature(750.0, 8000.0, Polarity::Positive).unwrap();
223        let out = StreamOperator::<f64, Complex<f64>>::process(&mut fm, &[250.0; 32]).unwrap().unwrap();
224        let reference = quadrature(1000.0, 8000.0, 32, Polarity::Positive).unwrap();
225        for (a, b) in out.iter().zip(&reference) {
226            assert!((a - b).norm() < 1e-9);
227        }
228    }
229
230    #[test]
231    fn quarter_turn_start_swaps_the_components() {
232        // Starting a quarter turn ahead turns (cos, sin) into (-sin, cos): multiplication by +j.
233        let base = quadrature(900.0, 8000.0, 20, Polarity::Positive).unwrap();
234        let ahead = NcoSource::quadrature(900.0, 8000.0, Polarity::Positive).unwrap().with_phase_turns(0.25).generate(20);
235        for (b, a) in base.iter().zip(&ahead) {
236            assert!((a - b * Complex::new(0.0, 1.0)).norm() < 1e-9);
237        }
238    }
239}