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.
- Solves
- Carrier recovery
- Time
- O(N) worst
- Space
- O(1) extra
- Where
- N = the number of samples
- Model
- Real RAM
- Properties
- deterministicnot exactfeedbackonline
- Evidence
- Proof sketchCode in 1 languages
- 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 , where 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 , , with an unknown phase that changes slowly, and noise 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 , so and the signal-to-noise ratio is . The loop must output, for each , an estimate of that uses only . Typical inputs are a phase offset and a frequency offset , where is in radians per symbol.
The algorithm
PLL(r[0..N-1], Kp, Ki, phi0)- 1
phi <- phi0; s <- 0 - 2
for k <- 0 to N - 1 do - 3
est[k] <- phi ▷ the estimate used on r[k] - 4
e <- Im(r[k] * exp(-j * phi)) ▷ phase detector: sin(theta - phi) + noise - 5
s <- s + Ki * e ▷ integral path of the loop filter - 6
phi <- phi + Kp * e + s ▷ NCO: add the filter output to the phase - 7
return est
Line L4 rotates the sample back by the current estimate. Without noise, the imaginary part of is , which is close to the phase error when the error is small, so the detector gain is . Lines L5 and L6 together are the loop filter followed by the oscillator, an accumulator. The integrator of line L5 learns the frequency offset: when the loop is locked to a frequency , and . The phase is not reduced modulo , so it follows a frequency offset without jumps.
The gains come from two design values, the noise bandwidth (normalized to the symbol rate) and the damping . The usual rule, taken from the analog loop and accurate for small , is
For this is and . The exact noise bandwidth of the digital loop is , with the impulse response of the closed loop, and the proof gives it in closed form.
Example
Take and . The rule gives and , and the exact noise bandwidth of this digital loop is . The input has the constant phase rad, with no noise, and the loop starts at .
| (line L3) | (line L4) | (line L5) | new (line L6) | |
|---|---|---|---|---|
| 0 | ||||
| 1 | ||||
| 2 |
The phase error then evolves as follows. It overshoots to at , as a loop with this damping does, and it stays below from on.
| 0 | 10 | 25 | 50 | 100 | 150 | 200 | 300 | |
|---|---|---|---|---|---|---|---|---|
| error (rad) |
With a frequency offset of cycles per symbol added, , the errors at , , and are , , and , and the error at is to double precision. The integrator has learned .
In noise, the linear model predicts the variance . For (exact value ) and (10 dB), that is rad, a standard deviation of 1.83 degrees. A simulation of 60000 samples with seed 5, after 2000 samples of settling, measured , a ratio of .
Correctness
Claim. If , and , then in the linear model the loop is stable, it follows with an error that tends to zero, and in noise its phase error has variance with .
Key steps. Line L4 outputs plus a noise term of variance , white, because a rotation does not change the law of circular Gaussian noise. With , the closed loop from to is
and the Jury test on the denominator gives the three conditions. The error transfer has the factor , which cancels the double pole of a phase ramp, so the error tends to zero. The noise enters at the same point as , so its contribution has variance . The full proof is in the proofs file, together with the closed form of .
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 , so the error point is an unstable equilibrium, and in noise the loop can leave the stable point and slip by ; 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 with independent, and . Write for the estimate recorded in line L3 at step , for the detector output of line L4 and for the integrator after line L5. Lines L5 and L6 give
We work in exact real arithmetic, as in the real RAM.
Lemma 1 (the phase detector). , where . Given the past, is Gaussian with mean and variance , and the are independent.
Proof. , and the imaginary part of the first term is . The phase depends only on . A circular Gaussian variable keeps its law under a rotation, so given the past, and its imaginary part has variance .
So the detector gain is : near lock, . The linear model replaces by . It is exact in the limit of small errors, and the tests check it with a step of rad.
Lemma 2 (the closed loop). In the linear model, with -transforms , and ,
Proof. With , (1) gives the loop filter from to , so . The open loop is , and gives . Multiply the numerator and the denominator by : .
Lemma 3 (stability). Both poles of lie inside the unit circle if and only if , and .
Proof. By the Jury test, the roots of lie inside the unit circle if and only if , and . Here , and .
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 for (a phase step together with a frequency step), then .
Proof. The error is with , where is the denominator of . The input transform is . So . All poles of are the roots of , inside the unit circle, so is a sum of terms and with , and it tends to .
The loop has two integrators, the one of line L5 and the oscillator of line L6. A frequency ramp gives the error in the steady state by the same argument.
Lemma 4 (the noise bandwidth). Let be the impulse response of and . With , , and ,
Proof. Feed with white noise of unit variance. The output is stationary, , and . Let . Since with , and , multiplying the recursion by , and and taking means gives
Eliminate with the third equation and with the second; the result is the formula. The tests compare it with from 20000 terms of the impulse response.
Theorem 2 (phase error variance in the linear model). With a constant , stable gains and the linear model, the phase error has mean and variance in the steady state.
Proof. By Lemma 2, tends to the response of to plus a transient that decays. By Lemma 1 the are white with variance , so the variance of the output is .
The design rule of loop_gains is the analog formula , and . It is not exact for the digital loop: for and , Lemma 4 gives . The tests check the design within 5 percent for , 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 per sample and for samples in the real RAM, with extra space for and . 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 , such as the Doppler of an accelerating receiver, gives the constant error .
- Noise and speed are traded by one number. The variance grows with the bandwidth, and the settling time falls like . In the example, the error falls below rad in about symbols.
- Design rule against exact bandwidth. The analog formula is a rule for small . For the exact values are , , , and for the design values , , , and .
- 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 radians per symbol. Beyond it, the loop pulls in slowly, with slips, or not at all.
- Hang-up. If the initial error is near , 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 of the input. If changes, the gains and 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 . The loop is simpler and always stable for , but a frequency offset leaves the steady-state error , and the loop cannot lock if .
- 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 , and the decision-directed loop compares the sample with the decided symbol. Each gives a phase ambiguity of .
- 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 modulo and a later step compares phases, the jump at the wrap looks like a large error. Keep 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 for a design value of . Check the exact bandwidth with the closed form when is above about .
- Delay in the loop. A hardware loop often has a pipeline delay between line L4 and the use of the new . 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 and held in an oscillation of about rad. This can look like a noisy lock.
- Forgetting the detector gain. For a signal with amplitude , or for a Costas detector with , the same and give a different loop. Divide the gains by .
- Sign of the detector. With , the sign of the error is reversed and the loop moves away from lock. The rotation of line L4 must be by .
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.
# 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
- 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)
- 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag YWG207 Edit this page History Report an error Markdown