Skip to main content

lib_jsl_dsp/discrete/synchronization/
costas_loop.rs

1//! Costas loops: carrier recovery for suppressed-carrier BPSK and QPSK.
2//!
3//! See the book entry [Synchronisation: phase-locked loops, Costas loops and timing recovery](https://jwkunz.github.io/lib_jsl/book/comms/synchronisation.html#costas-loops).
4
5use super::phase_locked_loop::LoopFilter;
6use lib_jsl_core::ErrorsJSL;
7use num_complex::Complex;
8
9type C64 = Complex<f64>;
10
11/// The modulation whose carrier the loop recovers.
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub enum CostasModulation {
14    /// Detector `sgn(I)·Q`: insensitive to the ±1 data, locks with a 180° ambiguity.
15    Bpsk,
16    /// Detector `sgn(I)·Q − sgn(Q)·I`: insensitive to the four symbols, locks with a 90°
17    /// ambiguity (resolve it with differential coding or a known preamble).
18    Qpsk,
19}
20
21/// A decision-directed Costas loop. Symbols (one complex sample per symbol, timing already
22/// recovered) are derotated by the NCO, and the data-stripping phase detector, applied to the
23/// unit-magnitude derotated sample (so the detector gain is one near lock), drives the same
24/// second-order loop filter as [`super::phase_locked_loop::PhaseLockedLoop`].
25#[derive(Debug, Clone)]
26pub struct CostasLoop {
27    filter: LoopFilter,
28    modulation: CostasModulation,
29}
30
31impl CostasLoop {
32    pub fn new(modulation: CostasModulation, normalized_bandwidth: f64, damping: f64) -> Result<Self, ErrorsJSL> {
33        Ok(CostasLoop { filter: LoopFilter::new(normalized_bandwidth, damping)?, modulation })
34    }
35
36    /// Processes one symbol: returns the derotated symbol and the detector error.
37    pub fn step(&mut self, x: C64) -> (C64, f64) {
38        let y = x * C64::from_polar(1.0, -self.filter.phase());
39        let magnitude = y.norm();
40        let error = if magnitude > 0.0 {
41            let u = y / magnitude;
42            match self.modulation {
43                CostasModulation::Bpsk => u.re.signum() * u.im,
44                CostasModulation::Qpsk => (u.re.signum() * u.im - u.im.signum() * u.re) / std::f64::consts::SQRT_2,
45            }
46        } else {
47            0.0
48        };
49        self.filter.update(error);
50        (y, error)
51    }
52
53    pub fn process(&mut self, x: &[C64]) -> Vec<C64> {
54        x.iter().map(|&v| self.step(v).0).collect()
55    }
56
57    pub fn phase(&self) -> f64 {
58        self.filter.phase()
59    }
60
61    pub fn frequency(&self) -> f64 {
62        self.filter.frequency()
63    }
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69    use std::f64::consts::FRAC_PI_4;
70
71    fn bits(n: usize, seed: u64) -> Vec<bool> {
72        let mut s = seed;
73        (0..n)
74            .map(|_| {
75                s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
76                s >> 63 == 1
77            })
78            .collect()
79    }
80
81    #[test]
82    fn recovers_bpsk_with_a_frequency_offset() {
83        let data = bits(6000, 1);
84        let (omega, phi0) = (0.004, 0.9);
85        let x: Vec<C64> = data.iter().enumerate().map(|(n, &b)| C64::from_polar(if b { 1.0 } else { -1.0 }, omega * n as f64 + phi0)).collect();
86        let mut costas = CostasLoop::new(CostasModulation::Bpsk, 0.01, 0.707).unwrap();
87        let y = costas.process(&x);
88        assert!((costas.frequency() - omega).abs() < 1e-6, "{}", costas.frequency());
89        // After lock the symbols lie on the real axis; the sign is ambiguous by 180°.
90        let tail = 5000..6000;
91        assert!(tail.clone().all(|n| y[n].im.abs() < 1e-4));
92        let agree = tail.clone().filter(|&n| (y[n].re > 0.0) == data[n]).count();
93        assert!(agree == 1000 || agree == 0, "{agree}");
94    }
95
96    #[test]
97    fn recovers_qpsk_up_to_a_quarter_turn_and_validates() {
98        let (a, b) = (bits(8000, 2), bits(8000, 3));
99        let symbols: Vec<C64> = a.iter().zip(&b).map(|(&i, &q)| C64::new(if i { 1.0 } else { -1.0 }, if q { 1.0 } else { -1.0 }) / 2f64.sqrt()).collect();
100        let x: Vec<C64> = symbols.iter().enumerate().map(|(n, s)| s * C64::from_polar(1.0, 0.002 * n as f64 - 0.4)).collect();
101        let mut costas = CostasLoop::new(CostasModulation::Qpsk, 0.005, 0.707).unwrap();
102        let y = costas.process(&x);
103        // Every recovered symbol sits on a diagonal, and one fixed rotation by kπ/2 maps them to
104        // the transmitted ones.
105        assert!(y[7000..].iter().all(|v| ((v.arg() - FRAC_PI_4).rem_euclid(std::f64::consts::FRAC_PI_2)).min(std::f64::consts::FRAC_PI_2 - (v.arg() - FRAC_PI_4).rem_euclid(std::f64::consts::FRAC_PI_2)) < 1e-3));
106        let rotation = (0..4).find(|&k| (7000..8000).all(|n| (y[n] * C64::from_polar(1.0, k as f64 * std::f64::consts::FRAC_PI_2) - symbols[n]).norm() < 1e-2));
107        assert!(rotation.is_some());
108        assert!(CostasLoop::new(CostasModulation::Bpsk, 0.6, 0.7).is_err());
109    }
110}