Skip to main content

lib_jsl_dsp/discrete/synchronization/
phase_locked_loop.rs

1//! A digital phase-locked loop with a second-order (proportional-integral) loop filter.
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#the-loop).
4
5use lib_jsl_core::ErrorsJSL;
6use num_complex::Complex;
7use std::f64::consts::{PI, TAU};
8
9type C64 = Complex<f64>;
10
11/// Proportional-integral loop filter and NCO shared by the carrier-tracking loops.
12///
13/// Gains follow the standard design for a type-2 loop with unit detector and NCO gains (Rice,
14/// *Digital Communications*, appendix C): with `θ = B_n T / (ζ + 1/(4ζ))`,
15/// `K_p = 4ζθ / (1 + 2ζθ + θ²)` and `K_i = 4θ² / (1 + 2ζθ + θ²)`. Such a loop tracks a phase and a
16/// constant frequency offset with zero steady-state error.
17#[derive(Debug, Clone)]
18pub struct LoopFilter {
19    proportional: f64,
20    integral: f64,
21    /// NCO phase (radians).
22    phase: f64,
23    /// Integrator state: the frequency estimate (radians per sample).
24    frequency: f64,
25}
26
27impl LoopFilter {
28    /// `normalized_bandwidth` is the noise bandwidth times the sample period (`B_n T`, typically
29    /// 0.001 to 0.05); `damping` is the damping factor ζ (0.707 is the usual choice).
30    pub fn new(normalized_bandwidth: f64, damping: f64) -> Result<Self, ErrorsJSL> {
31        if !(normalized_bandwidth > 0.0 && normalized_bandwidth < 0.5) || !(damping > 0.0) {
32            return Err(ErrorsJSL::InvalidInputRange("Need 0 < BnT < 0.5 and a positive damping factor."));
33        }
34        // ANCHOR: loop_filter
35        let theta = normalized_bandwidth / (damping + 0.25 / damping);
36        let denominator = 1.0 + 2.0 * damping * theta + theta * theta;
37        Ok(LoopFilter { proportional: 4.0 * damping * theta / denominator, integral: 4.0 * theta * theta / denominator, phase: 0.0, frequency: 0.0 })
38    }
39
40    /// Advances the NCO with the detector error (radians).
41    pub fn update(&mut self, error: f64) {
42        self.frequency += self.integral * error;
43        self.phase = (self.phase + self.proportional * error + self.frequency + PI).rem_euclid(TAU) - PI;
44    }
45        // ANCHOR_END: loop_filter
46
47    pub fn phase(&self) -> f64 {
48        self.phase
49    }
50
51    pub fn frequency(&self) -> f64 {
52        self.frequency
53    }
54
55    /// Presets the frequency estimate (radians per sample), e.g. from a coarse estimator.
56    pub fn set_frequency(&mut self, frequency: f64) {
57        self.frequency = frequency;
58    }
59}
60
61/// A phase-locked loop that locks a numerically controlled oscillator to a complex tone. The
62/// phase detector is `arg(x e^{−jφ})`, exact for all phase errors, so the loop pulls in from any
63/// initial phase; frequency offsets well inside the loop bandwidth are acquired directly.
64#[derive(Debug, Clone)]
65pub struct PhaseLockedLoop {
66    filter: LoopFilter,
67}
68
69impl PhaseLockedLoop {
70    pub fn new(normalized_bandwidth: f64, damping: f64) -> Result<Self, ErrorsJSL> {
71        Ok(PhaseLockedLoop { filter: LoopFilter::new(normalized_bandwidth, damping)? })
72    }
73
74    /// Processes one sample: returns the input derotated by the NCO and the phase error.
75    pub fn step(&mut self, x: C64) -> (C64, f64) {
76        let y = x * C64::from_polar(1.0, -self.filter.phase);
77        let error = if y.norm() > 0.0 { y.arg() } else { 0.0 };
78        self.filter.update(error);
79        (y, error)
80    }
81
82    /// Derotates a block.
83    pub fn process(&mut self, x: &[C64]) -> Vec<C64> {
84        x.iter().map(|&v| self.step(v).0).collect()
85    }
86
87    pub fn phase(&self) -> f64 {
88        self.filter.phase()
89    }
90
91    /// The tracked frequency in radians per sample.
92    pub fn frequency(&self) -> f64 {
93        self.filter.frequency()
94    }
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100
101    #[test]
102    fn locks_to_phase_and_frequency_offsets() {
103        let (omega, phi0) = (0.03, 2.5);
104        let mut pll = PhaseLockedLoop::new(0.02, 0.707).unwrap();
105        let x: Vec<C64> = (0..3000).map(|n| C64::from_polar(1.0, omega * n as f64 + phi0)).collect();
106        let y = pll.process(&x);
107        assert!((pll.frequency() - omega).abs() < 1e-9, "{}", pll.frequency());
108        assert!(y[2900..].iter().all(|v| v.arg().abs() < 1e-6));
109    }
110
111    #[test]
112    fn noise_jitter_scales_with_bandwidth_and_validation() {
113        // Phase noise on the tone: the narrower loop leaves less jitter on its phase estimate.
114        let mut s: u64 = 7;
115        let mut uniform = || {
116            s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
117            (s >> 11) as f64 / (1u64 << 53) as f64 - 0.5
118        };
119        let x: Vec<C64> = (0..20_000).map(|n| C64::from_polar(1.0, 0.01 * n as f64 + 0.5 * uniform())).collect();
120        let jitter = |bandwidth: f64| {
121            let mut pll = PhaseLockedLoop::new(bandwidth, 0.707).unwrap();
122            pll.process(&x[..5000]);
123            let errors: Vec<f64> = (5000..20_000).map(|n| { pll.step(x[n]); ((pll.phase() - 0.01 * (n + 1) as f64 + PI).rem_euclid(TAU) - PI).powi(2) }).collect();
124            (errors.iter().sum::<f64>() / errors.len() as f64).sqrt()
125        };
126        let (wide, narrow) = (jitter(0.05), jitter(0.005));
127        assert!(narrow < 0.5 * wide, "{narrow} vs {wide}");
128        assert!(PhaseLockedLoop::new(0.0, 0.7).is_err() && PhaseLockedLoop::new(0.01, -1.0).is_err());
129    }
130}