lib_jsl_dsp/discrete/synchronization/
phase_locked_loop.rs1use lib_jsl_core::ErrorsJSL;
6use num_complex::Complex;
7use std::f64::consts::{PI, TAU};
8
9type C64 = Complex<f64>;
10
11#[derive(Debug, Clone)]
18pub struct LoopFilter {
19 proportional: f64,
20 integral: f64,
21 phase: f64,
23 frequency: f64,
25}
26
27impl LoopFilter {
28 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 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 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 pub fn phase(&self) -> f64 {
48 self.phase
49 }
50
51 pub fn frequency(&self) -> f64 {
52 self.frequency
53 }
54
55 pub fn set_frequency(&mut self, frequency: f64) {
57 self.frequency = frequency;
58 }
59}
60
61#[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 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 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 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 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}