Algorithmcore
Costas loop
Also called Costas phase-locked loop.
A carrier loop for BPSK and QPSK. It splits each sample into in-phase and quadrature arms and drives a PLL with their product, so it locks modulo pi for BPSK and modulo pi/2 for QPSK.
- Solves
- Carrier recovery
- Time
- O(N) worst
- Space
- O(1) extra
- Where
- N = the number of symbols
- Model
- Real RAM
- Properties
- deterministicnon data aidedonline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- John P. Costas, 1956
The Costas loop recovers the carrier phase of a BPSK or QPSK signal, whose spectrum has no carrier tone. It rotates each sample by the current phase estimate and splits it into an in-phase arm and a quadrature arm . For BPSK, the product is for the phase error whatever the data symbol is, so it can drive the loop filter and the oscillator of a phase-locked loop. It is one of the classic solutions of carrier recovery. For BPSK it gives exactly the same phase as the squaring loop with the same gains, and for QPSK the hard-limited Costas detector is times the detector of decision-directed carrier recovery. The feedforward Viterbi and Viterbi estimator removes the data in the same way, but over a block and without feedback. Like every estimator that does not know the data, the loop locks only modulo for BPSK and modulo for QPSK, and in noise it can jump between these points; see cycle slip.
In plain words
A BPSK signal flips its sign with each data bit. An ordinary phase-locked loop sees the flips as phase jumps of half a turn and cannot follow them. The Costas loop looks at the signal along two directions at once, the direction it thinks is right and the one at a right angle to it. If its guess is a little off, part of the signal leaks into the second direction. The product of the two parts tells which way the guess is off, and the sign of the data cancels in the product. The loop corrects its guess with this product, as a normal loop does. It cannot tell the right phase from the opposite one, because a flipped signal with flipped data looks the same.
The problem
The input is , , at one sample per symbol after matched filtering and correct symbol timing. The data are unknown, independent and uniform on BPSK or on QPSK , so . The noise is , white, and . The carrier phase is unknown and changes slowly, for example . The loop must output a phase estimate from . Because of the symmetry of the constellation, the goal is modulo (BPSK) or (QPSK).
The algorithm
COSTAS(r[0..N-1], Kp, Ki, mod, phi0)- 1
phi <- phi0; s <- 0 - 2
for k <- 0 to N - 1 do - 3
est[k] <- phi - 4
z <- r[k] * exp(-j * phi); I <- Re z; Q <- Im z ▷ the two arms - 5
if mod = BPSK then e <- I * Q else e <- sgn(I) * Q - sgn(Q) * I ▷ QPSK- 6
s <- s + Ki * e ▷ loop filter - 7
phi <- phi + Kp * e + s ▷ oscillator - 8
return est
Line L4 is the derotation. In an analog receiver it is two mixers, one with the cosine and one with the sine of the oscillator, each followed by a low-pass filter; at one sample per symbol after the matched filter the two arms are the real and imaginary parts of one complex product. Line L5 is the Costas phase detector. For BPSK, , which shows how the data are removed: the square of is . For QPSK, each arm is hard-limited to its sign and multiplied by the other arm; this detector has gain near lock, against for BPSK. Lines L6 and L7 are the second-order loop of the PLL. The gains come from the PLL design rule for a noise bandwidth and damping , divided by .
Example
Take BPSK, and , so and . The carrier phase is rad, there is no noise, and the data are random (seed 1). Since for both symbols, the first steps do not depend on the data:
| (line L3) | (line L5) | (line L6) | new (line L7) | |
|---|---|---|---|---|
| 0 | ||||
| 1 | ||||
| 2 |
The phase error is at , at , at (the overshoot reaches ), at , at and at . From on it stays below rad.
The ambiguity is visible with . The initial error is beyond , so the loop moves to the stable point away and settles at . In this lock, every decision is inverted. For QPSK with , the loop settles at . A receiver resolves this with a known preamble or with differential encoding.
In noise at (10 dB) and (exact digital value ), the linear model gives rad for BPSK, which includes the squaring loss , and for QPSK. A simulation of 40000 symbols (seeds 3 and 4) measured and , ratios of and .
Correctness
Claim. Without noise, the BPSK detector of line L5 outputs and the QPSK detector outputs for , with period , for every data symbol. So the loop locks to modulo (BPSK) or (QPSK), with the steady-state behavior of the PLL. For BPSK in the linear model, the phase error variance is .
Key steps. For BPSK, with gives , and with the loop is a PLL on , which is the squaring loop. For QPSK, the detector does not change when is multiplied by , so one symbol suffices. Near lock, for BPSK, and the term , noise times noise, adds the factor to the variance. The full proof is in the proofs file.
The variance formula is a closed form under assumptions: the linear model, white Gaussian noise, correct timing and a constant amplitude. The equality between the BPSK Costas loop and the squaring loop is exact.
Proof: The Costas detector removes BPSK and QPSK data, the loop locks modulo pi or pi/2, and its BPSK variance has the squaring loss 1 + 1/(2 SNR)full
The input is with data from BPSK () or QPSK (), , and white, with . Line L4 forms , with arms and . Lines L6 and L7 are the loop filter and the oscillator of the phase-locked loop, whose proof gives the linear closed loop, the Jury conditions and the noise bandwidth . Write for the phase error.
Lemma 1 (BPSK detector). Without noise, for both values of . Also for every .
Proof. with , so , and . For any , .
Lemma 2 (QPSK detector). Let . Then , and without noise for , for each of the four symbols. So the S-curve has period .
Proof. , so , using for . The four symbols are , so it suffices to take . Then , and for both arms are positive: .
Lemma 3 (BPSK Costas loop is a PLL on the squared signal). Let and . Then and , with .
Proof. By Lemma 1, . Multiply lines L6 and L7 by 2.
So the BPSK Costas loop and the squaring loop with and the same gains give the same phase, exactly. The tests check this sample by sample.
Theorem 1 (lock points and ambiguity). Assume the gains satisfy the conditions of the PLL with and , where for BPSK and for QPSK. Without noise, the stable equilibria of the error are for BPSK and for QPSK. Near each of them the linear model of the PLL holds with the detector gain , and the loop follows a phase step and a frequency step with zero steady-state error modulo the ambiguity.
Proof. By Lemmas 1 and 2, the detector output without noise depends only on , not on the data. The zeros of are , and the slope is at and at the odd multiples of , which are unstable. For QPSK, the S-curve is on with slope at , and it jumps from to at , so it drives the error away from and toward the nearest multiple of . Near a stable point, the loop is the PLL with detector gain , and the PLL proof gives the rest.
The ambiguity cannot be removed by any detector that does not know the data. For BPSK, the received sequence for and for is the same, so no function of alone can tell from . For QPSK the same holds for .
Theorem 2 (BPSK variance with the squaring loss). For BPSK in the linear model, the phase error variance is
Proof. At lock, with , independent of the past by the rotation invariance used in the PLL proof. For small , and to first order, so
The mean slope is . The noise term has mean and variance , and the are uncorrelated. The PLL proof gives the variance . With this is the formula.
The factor is the squaring loss: the noise times noise term . For QPSK with correct signs of and , the same expansion gives with , so ; wrong signs add a small extra error at low SNR. The tests compare both values with a simulation at 10 dB within a factor of 1.25.
Complexity
Each symbol costs one complex rotation, one real multiplication (BPSK) or two multiplications and two sign tests (QPSK) for the detector, and the five operations of the loop filter and the oscillator. That is per symbol, for symbols in the real RAM, and extra space. The loop is sequential, like every feedback loop.
Properties
- Non-data-aided. The loop needs no known symbols and no decisions for BPSK. The QPSK detector uses the signs of the arms, which are hard decisions, so at low SNR it behaves like a decision-directed loop with wrong decisions; see data-aided synchronization.
- Squaring loss. For BPSK, the noise times noise term raises the variance by over that of a loop that knows the data: by 1.05 at 10 dB and by 1.5 at 0 dB.
- Phase ambiguity. The stable points are spaced by (BPSK) or (QPSK). Which point the loop picks depends on the start. Cycle slips move the loop between them.
- Detector gain depends on amplitude. The BPSK S-curve scales with , the square of the signal amplitude, and the QPSK detector scales with . An automatic gain control keeps the loop bandwidth fixed.
- Steady state. The second-order filter tracks a frequency offset with zero error, as in the PLL; the tests check this for cycles per symbol.
Variants and improvements
- Analog Costas loop. The original loop multiplies the received passband signal with the cosine and the sine of a voltage-controlled oscillator, filters both products and multiplies the two arms. The arm filters must pass the data, and they add delay to the loop.
- Soft QPSK detector. , which is , is the fourth-power detector of the squaring loop with . The hard-limited form of line L5 has less noise at moderate and high SNR.
- Decision-directed loop. Replacing and by the nearest constellation point extends the idea to QAM; see decision-directed carrier recovery.
- Hyperbolic tangent detector. For BPSK, the maximum likelihood detector averaged over the data uses . It becomes at low SNR, up to a constant, and at high SNR.
- Feedforward estimation. For short bursts, the Viterbi and Viterbi estimator uses the same power law on a block and has no acquisition time.
When to use it
Use a Costas loop for continuous BPSK or QPSK transmission when no pilot tone is sent and the SNR is moderate. It is simple, it needs no decisions for BPSK, and it was the standard carrier loop for suppressed-carrier links, including deep-space links. Use the decision-directed loop for QAM, a data-aided estimate when a preamble or pilots are present, and a feedforward block estimator for short bursts.
Pitfalls
- Gains not divided by the detector gain. The QPSK detector of line L5 has . Using the BPSK gains for QPSK makes the loop times wider than designed.
- Ignoring the ambiguity. A Costas loop can lock with an error of (BPSK) or a multiple of (QPSK), and nothing in the loop shows it. Every decision is then wrong or rotated. Use a unique word, a preamble or differential encoding.
- Too large a frequency offset. The S-curve of BPSK has period , half that of a PLL, and that of QPSK has period . A large initial frequency error makes the loop slip between ambiguity points instead of locking. Remove the coarse offset first.
- Wrong timing. The detector assumes samples at the symbol centers. With a timing error, intersymbol interference adds self noise to and , and the loop variance grows even without channel noise.
- Using BPSK on a QPSK signal. For QPSK, averages to zero over the data, so the BPSK detector gives no restoring force.
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/costas-loop/. The authors are listed in prov/J5XYD4.jsonl.
"""The Costas loop for BPSK and QPSK, in digital form at one sample per symbol.
Each sample is rotated by the current phase estimate, z = r e^(-j phi). The
in-phase arm is I = Re z and the quadrature arm is Q = Im z. The detector
removes the data:
BPSK: e = I Q, which is (1/2) sin(2 delta) without noise (gain 1)
QPSK: e = sgn(I) Q - sgn(Q) I, which is sqrt(2) sin(delta) for |delta| < pi/4
without noise (gain sqrt(2)); this is the hard-limited Costas detector.
Here delta = theta - phi is the phase error. The loop filter and the oscillator
are those of a second-order PLL: s <- s + ki e, phi <- phi + kp e + s.
The loop locks to theta modulo pi (BPSK) or modulo pi/2 (QPSK).
"""
import cmath
import math
from typing import Sequence
GAIN = {"bpsk": 1.0, "qpsk": math.sqrt(2.0)}
def loop_gains(bl_t: float, mod: str, zeta: float = 1.0 / math.sqrt(2.0)) -> tuple[float, float]:
"""(kp, ki) for the noise bandwidth B_L T and damping zeta, divided by the detector gain."""
wn_t = 2.0 * bl_t / (zeta + 1.0 / (4.0 * zeta))
kd = GAIN[mod]
return 2.0 * zeta * wn_t / kd, wn_t * wn_t / kd
def sgn(x: float) -> float:
return 1.0 if x >= 0.0 else -1.0
def detector(z: complex, mod: str) -> float:
"""The Costas error from the two arms I = Re z and Q = Im z."""
i, q = z.real, z.imag
if mod == "bpsk":
return i * q # @line L5
if mod == "qpsk":
return sgn(i) * q - sgn(q) * i # @line L5
raise ValueError("mod must be 'bpsk' or 'qpsk'")
def costas(r: Sequence[complex], kp: float, ki: float, mod: str = "bpsk", phi0: float = 0.0) -> list[float]:
"""Run the loop on r. Element k of the result is the phase estimate used on r[k]."""
phi = phi0 # @line L1
s = 0.0 # @line L1
est = []
for x in r: # @line L2
est.append(phi) # @line L3
z = x * cmath.exp(-1j * phi) # @line L4
e = detector(z, mod) # @line L5
s += ki * e # @line L6
phi += kp * e + s # @line L7
return est # @line L8
test_costas_loop.py 99 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/costas-loop/. The authors are listed in prov/J5XYD4.jsonl.
import cmath
import math
import random
from costas_loop import costas, detector, loop_gains
BPSK = [1 + 0j, -1 + 0j]
QPSK = [cmath.exp(1j * (math.pi / 4 + math.pi / 2 * m)) for m in range(4)]
def symbols(rng, mod, n):
return [rng.choice(BPSK if mod == "bpsk" else QPSK) for _ in range(n)]
def noise_bandwidth(kp, ki):
"""B_L T of the linear second-order loop with gains kd kp and kd ki (closed form)."""
b0, b1, a1, a2 = kp + ki, -kp, kp + ki - 2.0, 1.0 - kp
return 0.5 * ((b0 * b0 + b1 * b1) * (1 + a2) - 2 * b0 * b1 * a1) / ((1 - a2) * ((1 + a2) ** 2 - a1 * a1))
def test_s_curves_without_noise() -> None:
for i in range(-300, 301):
d = i * math.pi / 300
for a in BPSK:
assert abs(detector(a * cmath.exp(1j * d), "bpsk") - 0.5 * math.sin(2 * d)) < 1e-12
for a in QPSK:
e = detector(a * cmath.exp(1j * d), "qpsk")
# period pi/2: reduce d to [-pi/4, pi/4)
dr = (d + math.pi / 4) % (math.pi / 2) - math.pi / 4
if abs(abs(dr) - math.pi / 4) > 1e-9:
assert abs(e - math.sqrt(2) * math.sin(dr)) < 1e-12
def test_bpsk_loop_equals_a_pll_on_the_squared_signal() -> None:
# psi = 2 phi follows the PLL psi += kp E + S, S += ki E with E = Im(r^2 e^(-j psi)).
rng = random.Random(11)
sd = math.sqrt(0.05)
r = [a * cmath.exp(0.7j) + complex(rng.gauss(0, sd), rng.gauss(0, sd)) for a in symbols(rng, "bpsk", 3000)]
kp, ki = loop_gains(0.02, "bpsk")
est = costas(r, kp, ki, "bpsk")
psi, s = 0.0, 0.0
for k, x in enumerate(r):
assert abs(2 * est[k] - psi) < 1e-9
e = (x * x * cmath.exp(-1j * psi)).imag
s += ki * e
psi += kp * e + s
def test_lock_from_0_7_rad_without_noise() -> None:
rng = random.Random(1)
for mod in ("bpsk", "qpsk"):
kp, ki = loop_gains(0.02, mod)
r = [a * cmath.exp(0.7j) for a in symbols(rng, mod, 1500)]
est = costas(r, kp, ki, mod)
assert max(abs(0.7 - p) for p in est[300:]) < 1e-3
assert abs(0.7 - est[-1]) < 1e-9
def test_phase_ambiguity() -> None:
rng = random.Random(1)
# BPSK locks modulo pi, QPSK modulo pi/2, to the stable point nearest the start.
for mod, th, target in [("bpsk", 2.0, 2.0 - math.pi), ("qpsk", 1.0, 1.0 - math.pi / 2)]:
kp, ki = loop_gains(0.02, mod)
r = [a * cmath.exp(1j * th) for a in symbols(rng, mod, 1500)]
est = costas(r, kp, ki, mod)
assert abs(est[-1] - target) < 1e-6
def test_frequency_offset_is_tracked() -> None:
rng = random.Random(2)
w = 2 * math.pi * 0.001
for mod in ("bpsk", "qpsk"):
kp, ki = loop_gains(0.02, mod)
r = [a * cmath.exp(1j * (0.7 + w * k)) for k, a in enumerate(symbols(rng, mod, 2000))]
est = costas(r, kp, ki, mod)
assert max(abs(0.7 + w * k - est[k]) for k in range(600, 2000)) < 1e-4
def test_phase_error_variance_at_10_db() -> None:
# Linear model, B_L T = 0.01: BPSK var = (B_L T / SNR)(1 + 1/(2 SNR)) (squaring loss);
# QPSK with correct decisions var = B_L T / SNR. Accept a factor of 1.25 either way.
snr = 10.0
sd = math.sqrt(0.5 / snr)
for mod, seed in (("bpsk", 3), ("qpsk", 4)):
rng = random.Random(seed)
kp, ki = loop_gains(0.01, mod)
kd = 1.0 if mod == "bpsk" else math.sqrt(2.0)
r = [a * cmath.exp(0.7j) + complex(rng.gauss(0, sd), rng.gauss(0, sd)) for a in symbols(rng, mod, 40000)]
err = [0.7 - p for p in costas(r, kp, ki, mod)[2000:]]
m = sum(err) / len(err)
var = sum((e - m) ** 2 for e in err) / len(err)
pred = noise_bandwidth(kd * kp, kd * ki) / snr
if mod == "bpsk":
pred *= 1 + 1 / (2 * snr)
assert abs(m) < 0.01
assert 0.8 < var / pred < 1.25
History
John P. Costas, at General Electric, published the loop in 1956 in a paper that argued for double-sideband suppressed-carrier transmission instead of single-sideband. Such a signal has no carrier for an ordinary phase-locked loop, and his receiver recovered the carrier from the product of the in-phase and the quadrature channels. The loop became the standard carrier recovery circuit for BPSK and QPSK in satellite and deep-space links. In digital receivers it is a few lines of code, as above. The same J. P. Costas later described the Costas arrays used in radar, which are a different subject.
References
- J. P. Costas, Synchronous communications, Proceedings of the IRE 44(12), 1956, pages 1713 to 1718, the receiver with an in-phase and a quadrature arm whose product controls the local oscillator, for suppressed-carrier transmission
- John G. Proakis and Masoud Salehi, Digital Communications, fifth edition, McGraw-Hill, 2008, Section 5.2-5 (non-decision-directed loops: the squaring loop and the Costas loop)
- Umberto Mengali and Aldo N. D'Andrea, Synchronization Techniques for Digital Receivers, Plenum Press, 1997, Chapter 5 (carrier phase recovery with linear modulations, the feedback and non-data-aided schemes)
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 J5XYD4 Edit this page History Report an error Markdown