Algorithm Search⌘K

Algorithmintro

Phase-locked loop

Also called PLL, digital phase-locked loop.

A feedback loop that makes a local oscillator follow the phase of an input. With a phase detector, a PI loop filter and an NCO, it tracks phase and frequency steps with zero steady-state error.

Time
O(N) worst
Space
O(1) extra
Where
N = the number of samples
Properties
deterministicnot exactfeedbackonline
Origin
Henri de Bellescize, Andrew J. Viterbi, 1932

A phase-locked loop (PLL) makes a local oscillator follow the phase of an input signal. It measures the phase difference between the input and the oscillator with a phase detector, smooths it with a loop filter, and uses the result to advance the oscillator. This page is the digital loop at one complex sample per symbol, with a proportional-plus-integral filter and a numerically controlled oscillator (NCO). It is the basic tool of carrier recovery. The Costas loop, the squaring loop and decision-directed carrier recovery are this loop with a different phase detector, which removes the data modulation first. The feedforward Viterbi and Viterbi estimator solves the same problem without feedback, and a cycle slip is the main failure of a loop in noise. The second-order loop on this page has two integrators, so in its linear model it follows both a phase step and a frequency step with zero error in the steady state. Its phase error variance in white noise is BLT/SNRB_L T/\mathrm{SNR}, where BLTB_L T is the noise bandwidth of the loop.

In plain words

Think of a clock that must keep time with a reference clock it can only glance at. At each tick you compare the two hands and see how far yours is ahead or behind. You do not jump to the reference at once, because each glance is a little noisy. You move your hand by a small part of the difference. You also keep a running memory of the differences. If your clock is always behind, the memory grows and you start to run your clock faster, until it runs at the same speed as the reference. Small corrections give a steady clock that reacts slowly. Large corrections react fast but carry more of the noise into your clock.

The problem

The input is a sequence of complex samples rk=Aejθk+wkr_k = A e^{j\theta_k} + w_k, k=0,…,N−1k = 0, \ldots, N-1, with an unknown phase θk\theta_k that changes slowly, and noise wk∼CN(0,N0)w_k \sim \mathcal{CN}(0, N_0) that is white and circular, as on the AWGN channel. Here the data modulation is already removed, or the input is an unmodulated pilot tone, and A=1A = 1, so Es=1E_s = 1 and the signal-to-noise ratio is SNR=Es/N0=1/N0\mathrm{SNR} = E_s/N_0 = 1/N_0. The loop must output, for each kk, an estimate ϕk\phi_k of θk\theta_k that uses only r0,…,rk−1r_0, \ldots, r_{k-1}. Typical inputs are a phase offset θk=θ0\theta_k = \theta_0 and a frequency offset θk=θ0+ωk\theta_k = \theta_0 + \omega k, where ω\omega is in radians per symbol.

The algorithm

  1. PLL(r[0..N-1], Kp, Ki, phi0)
  2. 1phi <- phi0; s <- 0
  3. 2for k <- 0 to N - 1 do
  4. 3est[k] <- phi ▷ the estimate used on r[k]
  5. 4e <- Im(r[k] * exp(-j * phi)) ▷ phase detector: sin(theta - phi) + noise
  6. 5s <- s + Ki * e ▷ integral path of the loop filter
  7. 6phi <- phi + Kp * e + s ▷ NCO: add the filter output to the phase
  8. 7return est

Line L4 rotates the sample back by the current estimate. Without noise, the imaginary part of ej(θ−ϕ)e^{j(\theta - \phi)} is sin⁡(θ−ϕ)\sin(\theta - \phi), which is close to the phase error θ−ϕ\theta - \phi when the error is small, so the detector gain is Kd=1K_d = 1. Lines L5 and L6 together are the loop filter F(z)=Kp+Ki/(1−z−1)F(z) = K_p + K_i/(1 - z^{-1}) followed by the oscillator, an accumulator. The integrator ss of line L5 learns the frequency offset: when the loop is locked to a frequency ω\omega, s=ωs = \omega and e=0e = 0. The phase ϕ\phi is not reduced modulo 2π2\pi, so it follows a frequency offset without jumps.

The gains come from two design values, the noise bandwidth BLTB_L T (normalized to the symbol rate) and the damping ζ\zeta. The usual rule, taken from the analog loop and accurate for small BLTB_L T, is

ωnT=2BLTζ+1/(4ζ),KdKp=2ζ ωnT,KdKi=(ωnT)2.\omega_n T = \frac{2 B_L T}{\zeta + 1/(4\zeta)}, \qquad K_d K_p = 2\zeta\,\omega_n T, \qquad K_d K_i = (\omega_n T)^2.

For ζ=1/2\zeta = 1/\sqrt2 this is Kp=83BLTK_p = \frac83 B_L T and Ki=329(BLT)2K_i = \frac{32}{9} (B_L T)^2. The exact noise bandwidth of the digital loop is BLT=12∑khk2B_L T = \frac12 \sum_k h_k^2, with hh the impulse response of the closed loop, and the proof gives it in closed form.

Example

Take BLT=0.02B_L T = 0.02 and ζ=1/2\zeta = 1/\sqrt2. The rule gives Kp=0.053333K_p = 0.053333 and Ki=0.0014222K_i = 0.0014222, and the exact noise bandwidth of this digital loop is 0.0207380.020738. The input has the constant phase θ=0.7\theta = 0.7 rad, with no noise, and the loop starts at ϕ=0\phi = 0.

kk ϕ\phi (line L3) ee (line L4) ss (line L5) new ϕ\phi (line L6)
0 00 0.6442180.644218 0.0009160.000916 0.0352740.035274
1 0.0352740.035274 0.6168430.616843 0.0017940.001794 0.0699660.069966
2 0.0699660.069966 0.5891720.589172 0.0026310.002631 0.1040200.104020

The phase error θ−ϕk\theta - \phi_k then evolves as follows. It overshoots to −0.1470-0.1470 at k=58k = 58, as a loop with this damping does, and it stays below 10−310^{-3} from k=300k = 300 on.

kk 0 10 25 50 100 150 200 300
error (rad) 0.70.7 0.37890.3789 0.05600.0560 −0.1389-0.1389 −0.0634-0.0634 0.001460.00146 0.004270.00427 −0.00023-0.00023

With a frequency offset of 0.0020.002 cycles per symbol added, θk=0.7+0.012566 k\theta_k = 0.7 + 0.012566\,k, the errors at k=100k = 100, 200200, 300300 and 400400 are −0.0494-0.0494, 0.002620.00262, −9.5×10−5-9.5 \times 10^{-5} and −5.3×10−8-5.3 \times 10^{-8}, and the error at k=2999k = 2999 is 00 to double precision. The integrator ss has learned ω=0.012566\omega = 0.012566.

In noise, the linear model predicts the variance BLT/SNRB_L T/\mathrm{SNR}. For BLT=0.01B_L T = 0.01 (exact value 0.0101810.010181) and SNR=10\mathrm{SNR} = 10 (10 dB), that is 1.018×10−31.018 \times 10^{-3} rad2^2, a standard deviation of 1.83 degrees. A simulation of 60000 samples with seed 5, after 2000 samples of settling, measured 9.60×10−49.60 \times 10^{-4}, a ratio of 0.940.94.

Correctness

Claim. If 0<Kp<20 < K_p < 2, Ki>0K_i > 0 and 2Kp+Ki<42K_p + K_i < 4, then in the linear model the loop is stable, it follows θk=θ0+ωk\theta_k = \theta_0 + \omega k with an error that tends to zero, and in noise its phase error has variance N0BLT=BLT/SNRN_0 B_L T = B_L T/\mathrm{SNR} with BLT=12∑khk2B_L T = \frac12 \sum_k h_k^2.

Key steps. Line L4 outputs sin⁡(θk−ϕk)\sin(\theta_k - \phi_k) plus a noise term nkn_k of variance N0/2N_0/2, white, because a rotation does not change the law of circular Gaussian noise. With sin⁡x≈x\sin x \approx x, the closed loop from θ\theta to ϕ\phi is

H(z)=(Kp+Ki)z−Kpz2+(Kp+Ki−2)z+(1−Kp),H(z) = \frac{(K_p + K_i) z - K_p}{z^2 + (K_p + K_i - 2) z + (1 - K_p)},

and the Jury test on the denominator gives the three conditions. The error transfer 1−H(z)1 - H(z) has the factor (z−1)2(z - 1)^2, which cancels the double pole of a phase ramp, so the error tends to zero. The noise enters at the same point as θ\theta, so its contribution has variance N02∑hk2\frac{N_0}{2} \sum h_k^2. The full proof is in the proofs file, together with the closed form of ∑hk2\sum h_k^2.

The linear model is a closed form under assumptions: small phase errors, white Gaussian noise and a constant input amplitude. For large errors, the sine of line L4 matters. Its slope is negative near ±π\pm\pi, so the error point π\pi is an unstable equilibrium, and in noise the loop can leave the stable point and slip by 2π2\pi; see cycle slip.

Proof: The second-order digital PLL follows phase and frequency steps with zero steady-state error, and its phase error variance is B_L T / SNR in the linear modelfull

The input is rk=ejθk+wkr_k = e^{j\theta_k} + w_k with wk∼CN(0,N0)w_k \sim \mathcal{CN}(0, N_0) independent, Es=1E_s = 1 and SNR=Es/N0=1/N0\mathrm{SNR} = E_s/N_0 = 1/N_0. Write ϕk\phi_k for the estimate recorded in line L3 at step kk, eke_k for the detector output of line L4 and sks_k for the integrator after line L5. Lines L5 and L6 give

sk=sk−1+Kiek,ϕk+1=ϕk+Kpek+sk,s−1=0, ϕ0=ϕstart.(1)s_k = s_{k-1} + K_i e_k, \qquad \phi_{k+1} = \phi_k + K_p e_k + s_k, \qquad s_{-1} = 0,\ \phi_0 = \phi_{\text{start}}. \tag{1}

We work in exact real arithmetic, as in the real RAM.

Lemma 1 (the phase detector). ek=sin⁡(θk−ϕk)+nke_k = \sin(\theta_k - \phi_k) + n_k, where nk=Im⁡(wke−jϕk)n_k = \operatorname{Im}(w_k e^{-j\phi_k}). Given the past, nkn_k is Gaussian with mean 00 and variance N0/2N_0/2, and the nkn_k are independent.

Proof. rke−jϕk=ej(θk−ϕk)+wke−jϕkr_k e^{-j\phi_k} = e^{j(\theta_k - \phi_k)} + w_k e^{-j\phi_k}, and the imaginary part of the first term is sin⁡(θk−ϕk)\sin(\theta_k - \phi_k). The phase ϕk\phi_k depends only on w0,…,wk−1w_0, \ldots, w_{k-1}. A circular Gaussian variable keeps its law under a rotation, so wke−jϕk∼CN(0,N0)w_k e^{-j\phi_k} \sim \mathcal{CN}(0, N_0) given the past, and its imaginary part has variance N0/2N_0/2. □\square

So the detector gain is Kd=1K_d = 1: near lock, ek≈(θk−ϕk)+nke_k \approx (\theta_k - \phi_k) + n_k. The linear model replaces sin⁡x\sin x by xx. It is exact in the limit of small errors, and the tests check it with a step of 10−410^{-4} rad.

Lemma 2 (the closed loop). In the linear model, with ZZ-transforms Θ(z)\Theta(z), Φ(z)\Phi(z) and N(z)N(z),

Φ(z)=H(z) (Θ(z)+N(z)),H(z)=(Kp+Ki)z−Kpz2+(Kp+Ki−2)z+(1−Kp).\Phi(z) = H(z)\,\bigl(\Theta(z) + N(z)\bigr), \qquad H(z) = \frac{(K_p + K_i) z - K_p}{z^2 + (K_p + K_i - 2) z + (1 - K_p)}.

Proof. With ek=θk+nk−ϕke_k = \theta_k + n_k - \phi_k, (1) gives the loop filter F(z)=Kp+Ki/(1−z−1)F(z) = K_p + K_i/(1 - z^{-1}) from ee to ϕk+1−ϕk\phi_{k+1} - \phi_k, so (z−1)Φ(z)=F(z)E(z)(z - 1)\Phi(z) = F(z) E(z). The open loop is G(z)=F(z)/(z−1)=((Kp+Ki)z−Kp)/(z−1)2G(z) = F(z)/(z - 1) = ((K_p + K_i) z - K_p)/(z - 1)^2, and Φ=G(Θ+N−Φ)\Phi = G(\Theta + N - \Phi) gives Φ=G1+G(Θ+N)\Phi = \frac{G}{1 + G}(\Theta + N). Multiply the numerator and the denominator by (z−1)2(z - 1)^2: (z−1)2+(Kp+Ki)z−Kp=z2+(Kp+Ki−2)z+1−Kp(z-1)^2 + (K_p + K_i) z - K_p = z^2 + (K_p + K_i - 2) z + 1 - K_p. □\square

Lemma 3 (stability). Both poles of HH lie inside the unit circle if and only if 0<Kp<20 < K_p < 2, Ki>0K_i > 0 and 2Kp+Ki<42K_p + K_i < 4.

Proof. By the Jury test, the roots of z2+a1z+a2z^2 + a_1 z + a_2 lie inside the unit circle if and only if ∣a2∣<1|a_2| < 1, 1+a1+a2>01 + a_1 + a_2 > 0 and 1−a1+a2>01 - a_1 + a_2 > 0. Here a2=1−Kpa_2 = 1 - K_p, 1+a1+a2=Ki1 + a_1 + a_2 = K_i and 1−a1+a2=4−2Kp−Ki1 - a_1 + a_2 = 4 - 2K_p - K_i. □\square

Theorem 1 (zero steady-state error). Assume the gains satisfy Lemma 3, there is no noise and the linear model holds. If the input phase is θk=θ0+ωk\theta_k = \theta_0 + \omega k for k≥0k \ge 0 (a phase step together with a frequency step), then θk−ϕk→0\theta_k - \phi_k \to 0.

Proof. The error is E(z)=(1−H(z))Θ(z)E(z) = (1 - H(z))\Theta(z) with 1−H(z)=(z−1)2/D(z)1 - H(z) = (z - 1)^2/D(z), where DD is the denominator of HH. The input transform is Θ(z)=θ0z/(z−1)+ωz/(z−1)2\Theta(z) = \theta_0 z/(z - 1) + \omega z/(z - 1)^2. So E(z)=(θ0z(z−1)+ωz)/D(z)E(z) = (\theta_0 z (z - 1) + \omega z)/D(z). All poles of EE are the roots of DD, inside the unit circle, so eke_k is a sum of terms c pkc\,p^k and c k pkc\,k\,p^k with ∣p∣<1|p| < 1, and it tends to 00. □\square

The loop has two integrators, the one of line L5 and the oscillator of line L6. A frequency ramp θk=αk2/2\theta_k = \alpha k^2/2 gives the error α/Ki\alpha/K_i in the steady state by the same argument.

Lemma 4 (the noise bandwidth). Let hkh_k be the impulse response of HH and BLT=12∑khk2B_L T = \frac12 \sum_k h_k^2. With b0=Kp+Kib_0 = K_p + K_i, b1=−Kpb_1 = -K_p, a1=Kp+Ki−2a_1 = K_p + K_i - 2 and a2=1−Kpa_2 = 1 - K_p,

2BLT=(b02+b12)(1+a2)−2b0b1a1(1−a2)((1+a2)2−a12).2 B_L T = \frac{(b_0^2 + b_1^2)(1 + a_2) - 2 b_0 b_1 a_1}{(1 - a_2)\bigl((1 + a_2)^2 - a_1^2\bigr)}.

Proof. Feed HH with white noise xkx_k of unit variance. The output yky_k is stationary, yk+a1yk−1+a2yk−2=b0xk−1+b1xk−2y_k + a_1 y_{k-1} + a_2 y_{k-2} = b_0 x_{k-1} + b_1 x_{k-2}, and r0=E[yk2]=∑hk2r_0 = E[y_k^2] = \sum h_k^2. Let rm=E[ykyk−m]r_m = E[y_k y_{k-m}]. Since E[ykxk−m]=hmE[y_k x_{k-m}] = h_m with h0=0h_0 = 0, h1=b0h_1 = b_0 and h2=b1−a1b0h_2 = b_1 - a_1 b_0, multiplying the recursion by yky_k, yk−1y_{k-1} and yk−2y_{k-2} and taking means gives

r0+a1r1+a2r2=b0h1+b1h2,a1r0+(1+a2)r1=b0b1,a2r0+a1r1+r2=0.r_0 + a_1 r_1 + a_2 r_2 = b_0 h_1 + b_1 h_2, \quad a_1 r_0 + (1 + a_2) r_1 = b_0 b_1, \quad a_2 r_0 + a_1 r_1 + r_2 = 0.

Eliminate r2r_2 with the third equation and r1r_1 with the second; the result is the formula. The tests compare it with 12∑hk2\frac12 \sum h_k^2 from 20000 terms of the impulse response. □\square

Theorem 2 (phase error variance in the linear model). With a constant θ\theta, stable gains and the linear model, the phase error θ−ϕk\theta - \phi_k has mean 00 and variance N02⋅2BLT=BLT/SNR\frac{N_0}{2} \cdot 2 B_L T = B_L T/\mathrm{SNR} in the steady state.

Proof. By Lemma 2, ϕk−θ\phi_k - \theta tends to the response of HH to nkn_k plus a transient that decays. By Lemma 1 the nkn_k are white with variance N0/2N_0/2, so the variance of the output is N02∑hk2=N0BLT\frac{N_0}{2} \sum h_k^2 = N_0 B_L T. □\square

The design rule of loop_gains is the analog formula ωnT=2BLT/(ζ+1/(4ζ))\omega_n T = 2 B_L T/(\zeta + 1/(4\zeta)), Kp=2ζωnTK_p = 2\zeta\omega_n T and Ki=(ωnT)2K_i = (\omega_n T)^2. It is not exact for the digital loop: for BLT=0.02B_L T = 0.02 and ζ=1/2\zeta = 1/\sqrt2, Lemma 4 gives 0.0207380.020738. The tests check the design within 5 percent for BLT≤0.02B_L T \le 0.02, and they check Theorem 2 by simulation at an SNR of 10 dB within a factor of 1.25.

Complexity

Each sample costs one complex exponential (a cosine and a sine, or a table lookup in an NCO), two real multiplications for the imaginary part of line L4, and three multiplications and four additions in lines L5 and L6. That is O(1)O(1) per sample and O(N)O(N) for NN samples in the real RAM, with O(1)O(1) extra space for ϕ\phi and ss. The loop is sequential: each step needs the phase from the step before, so it does not split over parallel hardware without a change of structure.

Properties

  • Steady-state errors. In the linear model, a phase step and a frequency step give zero error in the steady state (Theorem 1 of the proof). A frequency ramp θk=αk2/2\theta_k = \alpha k^2/2, such as the Doppler of an accelerating receiver, gives the constant error α/Ki\alpha/K_i.
  • Noise and speed are traded by one number. The variance BLT/SNRB_L T/\mathrm{SNR} grows with the bandwidth, and the settling time falls like 1/BLT1/B_L T. In the example, the error falls below 10−310^{-3} rad in about 6/BLT6/B_L T symbols.
  • Design rule against exact bandwidth. The analog formula is a rule for small BLTB_L T. For ζ=1/2\zeta = 1/\sqrt2 the exact values are 0.00504490.0050449, 0.0101810.010181, 0.0207380.020738, 0.0548930.054893 and 0.121760.12176 for the design values 0.0050.005, 0.010.01, 0.020.02, 0.050.05 and 0.10.1.
  • Lock-in range. The loop locks without a slip only if the initial frequency error is small. The usual rule, from Gardner (Chapter 8), puts the lock-in range at about 2ζωn2\zeta\omega_n radians per symbol. Beyond it, the loop pulls in slowly, with slips, or not at all.
  • Hang-up. If the initial error is near π\pi, the detector output is near zero and the restoring force is weak, so the loop can stay near the wrong point for a long time before it locks.
  • Dependence on amplitude. The detector gain is the amplitude AA of the input. If AA changes, the gains KdKpK_d K_p and KdKiK_d K_i change and the bandwidth and damping move. Real receivers put an automatic gain control before the loop or normalize the detector output.

Variants and improvements

  • First-order loop. Set Ki=0K_i = 0. The loop is simpler and always stable for 0<Kp<20 < K_p < 2, but a frequency offset ω\omega leaves the steady-state error arcsin⁡(ω/Kp)\arcsin(\omega/K_p), and the loop cannot lock if ∣ω∣>Kp|\omega| > K_p.
  • Third-order loop. Add a second integrator to the filter to follow a frequency ramp with zero error. It needs more care for stability.
  • Other phase detectors. For a modulated input, the detector must remove the data. The Costas loop multiplies the in-phase and quadrature arms, the squaring loop raises the sample to the power MM, and the decision-directed loop compares the sample with the decided symbol. Each gives a phase ambiguity of 2π/M2\pi/M.
  • Frequency-aided loops. A frequency-locked loop, or a coarse estimate from a frequency offset estimator, removes most of the frequency error before the PLL starts, which avoids slow pull-in.
  • Kalman form. For a phase that is a random walk with a random-walk frequency, the steady-state Kalman filter has the same structure as this second-order loop, with gains set by the noise variances.
  • Delay and timing loops. The same loop with a timing error detector tracks the symbol clock in symbol timing recovery, and with a code correlator it is the delay-locked loop.

When to use it

Use a PLL to track a carrier phase that drifts during a long or continuous transmission, when the signal has a pilot tone or the data can be removed by a detector. A loop is cheap, works sample by sample and follows slow changes of frequency. For short bursts, a feedforward estimator such as Viterbi and Viterbi or a data-aided estimate over a preamble needs no acquisition time and has no cycle slips, so it is the better choice. At low SNR, a loop with a narrow bandwidth keeps the variance small but acquires slowly; use a frequency estimate first.

Pitfalls

  • Wrapping the phase. If line L6 reduces ϕ\phi modulo 2π2\pi and a later step compares phases, the jump at the wrap looks like a large error. Keep ϕ\phi unwrapped, or wrap only where the phase is used in line L4, where the exponential does not care.
  • The analog formula at large bandwidth. The rule gives BLT=0.12176B_L T = 0.12176 for a design value of 0.10.1. Check the exact bandwidth with the closed form when BLTB_L T is above about 0.020.02.
  • Delay in the loop. A hardware loop often has a pipeline delay between line L4 and the use of the new ϕ\phi. One extra symbol of delay changes the characteristic polynomial to third order and shrinks the stable region. Design with the delay in the model.
  • Unstable gains. Gains outside the Jury region do not make the phase grow without limit, because the sine of line L4 saturates. The loop swings instead: the tests show Kp=1.9K_p = 1.9 and Ki=0.5K_i = 0.5 held in an oscillation of about ±0.65\pm0.65 rad. This can look like a noisy lock.
  • Forgetting the detector gain. For a signal with amplitude A≠1A \ne 1, or for a Costas detector with Kd=2K_d = \sqrt2, the same KpK_p and KiK_i give a different loop. Divide the gains by KdK_d.
  • Sign of the detector. With e=Im⁡(r∗ejϕ)e = \operatorname{Im}(r^\ast e^{j\phi}), the sign of the error is reversed and the loop moves away from lock. The rotation of line L4 must be by −ϕ-\phi.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

phase_locked_loop.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/phase-locked-loop/. The authors are listed in prov/YWG207.jsonl.

"""A second-order digital phase-locked loop (PLL).

The input is one complex sample per symbol, r[k] = e^(j theta[k]) + w[k].
The loop has three parts:
  phase detector  e = Im(r[k] e^(-j phi)), which is sin(theta - phi) without noise
  loop filter     proportional gain kp plus an integrator with gain ki
  oscillator      phi <- phi + filter output (a numerically controlled oscillator)
The loop has two integrators (the filter and the oscillator), so it follows a
phase step and a frequency step with zero error in the steady state.

Linear model: closed-loop transfer from theta to phi
  H(z) = ((kp + ki) z - kp) / (z^2 + (kp + ki - 2) z + (1 - kp)).
The one-sided noise bandwidth is B_L T = (1/2) sum_n h[n]^2, and the phase error
variance in white noise is about B_L T / SNR for |r| = 1 and SNR = 1/N0.
"""

import cmath
import math
from typing import Sequence


def loop_gains(bl_t: float, zeta: float = 1.0 / math.sqrt(2.0), kd: float = 1.0) -> tuple[float, float]:
    """Gains (kp, ki) for a noise bandwidth B_L T and damping zeta.

    This is the usual design rule from the analog loop, accurate for small B_L T:
    omega_n T = 2 B_L T / (zeta + 1/(4 zeta)), kd kp = 2 zeta omega_n T, kd ki = (omega_n T)^2.
    noise_bandwidth() gives the exact B_L T of the digital loop.
    """
    wn_t = 2.0 * bl_t / (zeta + 1.0 / (4.0 * zeta))
    return 2.0 * zeta * wn_t / kd, wn_t * wn_t / kd


def pll(r: Sequence[complex], kp: float, ki: float, phi0: float = 0.0) -> list[float]:
    """Run the loop on r. Element k of the result is the phase estimate used on r[k].

    The estimate is not reduced modulo 2 pi, so it follows a phase ramp without jumps.
    """
    phi = phi0  # @line L1
    s = 0.0  # @line L1
    est = []
    for x in r:  # @line L2
        est.append(phi)  # @line L3
        e = (x * cmath.exp(-1j * phi)).imag  # @line L4
        s += ki * e  # @line L5
        phi += kp * e + s  # @line L6
    return est  # @line L7


def closed_loop(kp: float, ki: float) -> tuple[tuple[float, float], tuple[float, float]]:
    """((b0, b1), (a1, a2)) of H(z) = (b0 z + b1) / (z^2 + a1 z + a2)."""
    return (kp + ki, -kp), (kp + ki - 2.0, 1.0 - kp)


def is_stable(kp: float, ki: float) -> bool:
    """Jury test of the linear loop: 0 < kp < 2, ki > 0 and 2 kp + ki < 4."""
    return 0.0 < kp < 2.0 and ki > 0.0 and 2.0 * kp + ki < 4.0


def noise_bandwidth(kp: float, ki: float) -> float:
    """B_L T = (1/2) sum_n h[n]^2 of the linear loop, in closed form.

    For H(z) = (b0 z + b1)/(z^2 + a1 z + a2) with both poles inside the unit circle,
    sum h^2 = ((b0^2 + b1^2)(1 + a2) - 2 b0 b1 a1) / ((1 - a2)((1 + a2)^2 - a1^2)).
    """
    if not is_stable(kp, ki):
        raise ValueError("the loop is not stable")
    (b0, b1), (a1, a2) = closed_loop(kp, ki)
    num = (b0 * b0 + b1 * b1) * (1.0 + a2) - 2.0 * b0 * b1 * a1
    den = (1.0 - a2) * ((1.0 + a2) ** 2 - a1 * a1)
    return 0.5 * num / den
test_phase_locked_loop.py 110 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/phase-locked-loop/. The authors are listed in prov/YWG207.jsonl.

import cmath
import math
import random

from phase_locked_loop import closed_loop, is_stable, loop_gains, noise_bandwidth, pll


def impulse_response(kp, ki, n):
    """h[0..n-1] of the linear loop, from the difference equation of H(z)."""
    (b0, b1), (a1, a2) = closed_loop(kp, ki)
    h = []
    for k in range(n):
        x1 = 1.0 if k == 1 else 0.0  # input delayed by one: z^-1 numerator term b0
        x2 = 1.0 if k == 2 else 0.0
        y = b0 * x1 + b1 * x2
        if k >= 1:
            y -= a1 * h[k - 1]
        if k >= 2:
            y -= a2 * h[k - 2]
        h.append(y)
    return h


def spectral_radius(kp, ki):
    _, (a1, a2) = closed_loop(kp, ki)
    d = cmath.sqrt(a1 * a1 - 4.0 * a2)
    return max(abs((-a1 + d) / 2.0), abs((-a1 - d) / 2.0))


def test_noise_bandwidth_closed_form_matches_impulse_response() -> None:
    for kp, ki in [(0.0266667, 0.000355556), (0.3, 0.05), (1.0, 0.5), (1.5, 0.8)]:
        h = impulse_response(kp, ki, 20000)
        assert abs(0.5 * sum(x * x for x in h) - noise_bandwidth(kp, ki)) < 1e-9


def test_design_rule_gives_the_bandwidth_for_small_values() -> None:
    for bl in (0.005, 0.01, 0.02):
        kp, ki = loop_gains(bl)
        assert abs(noise_bandwidth(kp, ki) / bl - 1.0) < 0.05
    kp, ki = loop_gains(0.02)
    assert abs(kp - 8 * 0.02 / 3) < 1e-15 and abs(ki - 32 * 0.02**2 / 9) < 1e-15
    assert abs(noise_bandwidth(kp, ki) - 0.020738169) < 1e-8


def test_jury_region_matches_the_poles() -> None:
    for i in range(-2, 43):
        for j in range(-2, 45):
            kp, ki = 0.05 * i + 0.013, 0.1 * j + 0.017
            assert is_stable(kp, ki) == (spectral_radius(kp, ki) < 1.0)


def test_linear_model_for_a_small_step() -> None:
    # A step of 1e-4 rad keeps sin(x) = x to about 2e-13, so the loop follows H(z)
    # to about 1e-6 of the step size.
    kp, ki = loop_gains(0.02)
    th = 1e-4
    est = pll([cmath.exp(1j * th)] * 300, kp, ki)
    h = impulse_response(kp, ki, 300)
    step = 0.0
    for k in range(300):
        step += h[k]
        assert abs(est[k] - th * step) < 1e-10


def test_phase_step_of_0_7_rad() -> None:
    kp, ki = loop_gains(0.02)
    est = pll([cmath.exp(0.7j)] * 1000, kp, ki)
    err = [0.7 - p for p in est]
    assert err[0] == 0.7
    assert max(abs(e) for e in err[300:]) < 1e-3
    assert abs(min(err) + 0.147) < 0.001  # the overshoot of a damping of 1/sqrt(2)
    assert err.index(min(err)) == 58


def test_frequency_step_gives_zero_steady_state_error() -> None:
    kp, ki = loop_gains(0.02)
    w = 2 * math.pi * 0.002
    r = [cmath.exp(1j * (w * k + 0.7)) for k in range(2000)]
    est = pll(r, kp, ki)
    err = [w * k + 0.7 - est[k] for k in range(2000)]
    assert max(abs(e) for e in err[400:]) < 1e-5
    assert max(abs(e) for e in err[600:]) < 1e-6
    assert abs(err[-1]) < 1e-12


def test_unstable_gains_do_not_lock() -> None:
    # 2 kp + ki = 4.3 > 4: a pole lies outside the unit circle. A tiny error grows
    # until the sine of the detector limits it, and the loop keeps swinging.
    kp, ki = 1.9, 0.5
    assert not is_stable(kp, ki)
    est = pll([cmath.exp(1e-6j)] * 200, kp, ki)
    assert min(abs(1e-6 - p) for p in est[-20:]) > 0.5


def test_phase_error_variance_in_noise() -> None:
    # SNR = 10 (10 dB), B_L T = 0.01: the linear model gives var = B_L T / SNR.
    snr = 10.0
    sd = math.sqrt(0.5 / snr)
    kp, ki = loop_gains(0.01)
    rng = random.Random(5)
    r = [cmath.exp(0.7j) + complex(rng.gauss(0, sd), rng.gauss(0, sd)) for _ in range(60000)]
    err = [0.7 - p for p in pll(r, kp, ki)[2000:]]
    m = sum(err) / len(err)
    var = sum((e - m) ** 2 for e in err) / len(err)
    ratio = var / (noise_bandwidth(kp, ki) / snr)
    assert abs(m) < 0.005
    assert 0.8 < ratio < 1.25

History

Henri de Bellescize described synchronous reception of radio signals with a phase-locked local oscillator in 1932. In the 1940s, phase-locked circuits kept the horizontal scan of television receivers in step with the transmitter. In the 1950s, the space program used loops to track the weak carriers of satellites, and Jaffe and Rechtin gave a design of loop filters for such signals in 1955. Andrew Viterbi analyzed the nonlinear loop in noise in 1963 with Fokker-Planck methods, and found the distribution of the phase error and the rate of loss of lock. Floyd Gardner's book Phaselock Techniques (first edition 1966) made the loop a standard tool of engineers. With digital receivers, the loop became an all-digital recursion such as the one on this page.

References

  1. Floyd M. Gardner, Phaselock Techniques, third edition, Wiley, 2005, Chapters 2 and 4 (transfer functions of analog and digital loops), Chapter 6 (effects of additive noise, the noise bandwidth), Chapter 8 (acquisition) and Chapter 13 (digital sampled loops)
  2. A. J. Viterbi, Phase-locked loop dynamics in the presence of noise by Fokker-Planck techniques, Proceedings of the IEEE 51(12), 1963, pages 1737 to 1753, the nonlinear model of the loop in noise, the stationary distribution of the phase error and the time to loss of lock
  3. John G. Proakis and Masoud Salehi, Digital Communications, fifth edition, McGraw-Hill, 2008, Section 5.2-2 (the phase-locked loop) and Section 5.2-3 (effect of additive noise on the phase estimate)
  4. Heinrich Meyr, Marc Moeneclaey and Stefan A. Fechtel, Digital Communication Receivers, Wiley, 1998, Chapter 6 (performance analysis of synchronizers, the tracking performance of feedback loops)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example