Algorithm Search⌘K

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.

Time
O(N) worst
Space
O(1) extra
Where
N = the number of symbols
Properties
deterministicnon data aidedonline
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 II and a quadrature arm QQ. For BPSK, the product IQIQ is 12sin⁡2Δ\frac12 \sin 2\Delta for the phase error Δ\Delta 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 2\sqrt2 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 π\pi for BPSK and modulo π/2\pi/2 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 rk=akejθk+wkr_k = a_k e^{j\theta_k} + w_k, k=0,…,N−1k = 0, \ldots, N - 1, at one sample per symbol after matched filtering and correct symbol timing. The data aka_k are unknown, independent and uniform on BPSK {+1,−1}\{+1, -1\} or on QPSK {ej(π/4+mπ/2)}\{e^{j(\pi/4 + m\pi/2)}\}, so Es=1E_s = 1. The noise is wk∼CN(0,N0)w_k \sim \mathcal{CN}(0, N_0), white, and SNR=Es/N0\mathrm{SNR} = E_s/N_0. The carrier phase θk\theta_k is unknown and changes slowly, for example θk=θ0+ωk\theta_k = \theta_0 + \omega k. The loop must output a phase estimate ϕk\phi_k from r0,…,rk−1r_0, \ldots, r_{k-1}. Because of the symmetry of the constellation, the goal is ϕk→θk\phi_k \to \theta_k modulo π\pi (BPSK) or π/2\pi/2 (QPSK).

The algorithm

  1. COSTAS(r[0..N-1], Kp, Ki, mod, phi0)
  2. 1phi <- phi0; s <- 0
  3. 2for k <- 0 to N - 1 do
  4. 3est[k] <- phi
  5. 4z <- r[k] * exp(-j * phi); I <- Re z; Q <- Im z ▷ the two arms
  6. 5if mod = BPSK then e <- I * Q
  7. else e <- sgn(I) * Q - sgn(Q) * I ▷ QPSK
  8. 6s <- s + Ki * e ▷ loop filter
  9. 7phi <- phi + Kp * e + s ▷ oscillator
  10. 8return 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, IQ=12Im⁡(z2)IQ = \frac12 \operatorname{Im}(z^2), which shows how the data are removed: the square of ±1\pm1 is 11. For QPSK, each arm is hard-limited to its sign and multiplied by the other arm; this detector has gain Kd=2K_d = \sqrt2 near lock, against Kd=1K_d = 1 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 BLTB_L T and damping ζ\zeta, divided by KdK_d.

Example

Take BPSK, BLT=0.02B_L T = 0.02 and ζ=1/2\zeta = 1/\sqrt2, so Kp=0.053333K_p = 0.053333 and Ki=0.0014222K_i = 0.0014222. The carrier phase is θ=0.7\theta = 0.7 rad, there is no noise, and the data are random (seed 1). Since IQ=12sin⁡2ΔIQ = \frac12 \sin 2\Delta for both symbols, the first steps do not depend on the data:

kk ϕ\phi (line L3) ee (line L5) ss (line L6) new ϕ\phi (line L7)
0 00 0.4927250.492725 0.0007010.000701 0.0269790.026979
1 0.0269790.026979 0.4874240.487424 0.0013940.001394 0.0543690.054369
2 0.0543690.054369 0.4805920.480592 0.0020770.002077 0.0820780.082078

The phase error 0.7−ϕk0.7 - \phi_k is 0.422970.42297 at k=10k = 10, 0.088160.08816 at 2525, −0.13253-0.13253 at 5050 (the overshoot reaches −0.1461-0.1461), −0.06821-0.06821 at 100100, 0.004490.00449 at 200200 and −0.00023-0.00023 at 300300. From k=300k = 300 on it stays below 10−310^{-3} rad.

The ambiguity is visible with θ=2.0\theta = 2.0. The initial error 2.02.0 is beyond π/2\pi/2, so the loop moves to the stable point π\pi away and settles at ϕ=2.0−π=−1.1416\phi = 2.0 - \pi = -1.1416. In this lock, every decision is inverted. For QPSK with θ=1.0\theta = 1.0, the loop settles at 1.0−π/2=−0.57081.0 - \pi/2 = -0.5708. A receiver resolves this with a known preamble or with differential encoding.

In noise at SNR=10\mathrm{SNR} = 10 (10 dB) and BLT=0.01B_L T = 0.01 (exact digital value 0.0101810.010181), the linear model gives 1.069×10−31.069 \times 10^{-3} rad2^2 for BPSK, which includes the squaring loss 1+1/(2⋅10)=1.051 + 1/(2 \cdot 10) = 1.05, and 1.018×10−31.018 \times 10^{-3} for QPSK. A simulation of 40000 symbols (seeds 3 and 4) measured 1.019×10−31.019 \times 10^{-3} and 9.74×10−49.74 \times 10^{-4}, ratios of 0.950.95 and 0.960.96.

Correctness

Claim. Without noise, the BPSK detector of line L5 outputs 12sin⁡2Δ\frac12 \sin 2\Delta and the QPSK detector outputs 2sin⁡Δ\sqrt2 \sin\Delta for ∣Δ∣<π/4|\Delta| < \pi/4, with period π/2\pi/2, for every data symbol. So the loop locks to θ\theta modulo π\pi (BPSK) or π/2\pi/2 (QPSK), with the steady-state behavior of the PLL. For BPSK in the linear model, the phase error variance is BLTSNR(1+12 SNR)\frac{B_L T}{\mathrm{SNR}}\bigl(1 + \frac{1}{2\,\mathrm{SNR}}\bigr).

Key steps. For BPSK, z=aejΔz = a e^{j\Delta} with a2=1a^2 = 1 gives IQ=12sin⁡2ΔIQ = \frac12 \sin 2\Delta, and with ψ=2ϕ\psi = 2\phi the loop is a PLL on r2r^2, which is the squaring loop. For QPSK, the detector does not change when zz is multiplied by jj, so one symbol suffices. Near lock, e=Δ+anQ+nInQe = \Delta + a n_Q + n_I n_Q for BPSK, and the term nInQn_I n_Q, noise times noise, adds the factor 1+N0/21 + N_0/2 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 rk=akejθ+wkr_k = a_k e^{j\theta} + w_k with data aka_k from BPSK (±1\pm1) or QPSK (ej(π/4+mπ/2)e^{j(\pi/4 + m\pi/2)}), Es=E∣ak∣2=1E_s = E|a_k|^2 = 1, and wk∼CN(0,N0)w_k \sim \mathcal{CN}(0, N_0) white, with SNR=1/N0\mathrm{SNR} = 1/N_0. Line L4 forms zk=rke−jϕkz_k = r_k e^{-j\phi_k}, with arms I=Re⁡zkI = \operatorname{Re} z_k and Q=Im⁡zkQ = \operatorname{Im} z_k. 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 BLT=12∑hk2B_L T = \frac12 \sum h_k^2. Write Δ=θ−ϕ\Delta = \theta - \phi for the phase error.

Lemma 1 (BPSK detector). Without noise, e=IQ=12sin⁡2Δe = IQ = \frac12 \sin 2\Delta for both values of aka_k. Also IQ=12Im⁡(z2)IQ = \frac12 \operatorname{Im}(z^2) for every zz.

Proof. z=aejΔz = a e^{j\Delta} with a=±1a = \pm1, so I=acos⁡ΔI = a\cos\Delta, Q=asin⁡ΔQ = a\sin\Delta and IQ=a2sin⁡Δcos⁡Δ=12sin⁡2ΔIQ = a^2 \sin\Delta\cos\Delta = \frac12 \sin 2\Delta. For any z=I+jQz = I + jQ, z2=I2−Q2+2jIQz^2 = I^2 - Q^2 + 2jIQ. □\square

Lemma 2 (QPSK detector). Let e(z)=sgn⁡(I) Q−sgn⁡(Q) Ie(z) = \operatorname{sgn}(I)\,Q - \operatorname{sgn}(Q)\,I. Then e(jz)=e(z)e(jz) = e(z), and without noise e=2sin⁡Δe = \sqrt2 \sin\Delta for ∣Δ∣<π/4|\Delta| < \pi/4, for each of the four symbols. So the S-curve has period π/2\pi/2.

Proof. jz=−Q+jIjz = -Q + jI, so e(jz)=sgn⁡(−Q) I−sgn⁡(I)(−Q)=e(z)e(jz) = \operatorname{sgn}(-Q)\,I - \operatorname{sgn}(I)(-Q) = e(z), using sgn⁡(−x)=−sgn⁡(x)\operatorname{sgn}(-x) = -\operatorname{sgn}(x) for x≠0x \ne 0. The four symbols are jmejπ/4j^m e^{j\pi/4}, so it suffices to take a=ejπ/4a = e^{j\pi/4}. Then z=ej(π/4+Δ)z = e^{j(\pi/4 + \Delta)}, and for ∣Δ∣<π/4|\Delta| < \pi/4 both arms are positive: e=sin⁡(π/4+Δ)−cos⁡(π/4+Δ)=2sin⁡Δe = \sin(\pi/4 + \Delta) - \cos(\pi/4 + \Delta) = \sqrt2 \sin\Delta. □\square

Lemma 3 (BPSK Costas loop is a PLL on the squared signal). Let ψk=2ϕk\psi_k = 2\phi_k and Sk=2skS_k = 2 s_k. Then ψk+1=ψk+KpEk+Sk\psi_{k+1} = \psi_k + K_p E_k + S_k and Sk=Sk−1+KiEkS_k = S_{k-1} + K_i E_k, with Ek=Im⁡(rk2e−jψk)E_k = \operatorname{Im}(r_k^2 e^{-j\psi_k}).

Proof. By Lemma 1, 2ek=Im⁡(zk2)=Im⁡(rk2e−j2ϕk)=Ek2e_k = \operatorname{Im}(z_k^2) = \operatorname{Im}(r_k^2 e^{-j2\phi_k}) = E_k. Multiply lines L6 and L7 by 2. □\square

So the BPSK Costas loop and the squaring loop with M=2M = 2 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 KdKpK_d K_p and KdKiK_d K_i, where Kd=1K_d = 1 for BPSK and Kd=2K_d = \sqrt2 for QPSK. Without noise, the stable equilibria of the error are Δ∈πZ\Delta \in \pi\mathbb{Z} for BPSK and Δ∈π2Z\Delta \in \frac{\pi}{2}\mathbb{Z} for QPSK. Near each of them the linear model of the PLL holds with the detector gain KdK_d, 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 Δ\Delta, not on the data. The zeros of 12sin⁡2Δ\frac12 \sin 2\Delta are Δ∈π2Z\Delta \in \frac{\pi}{2}\mathbb{Z}, and the slope cos⁡2Δ\cos 2\Delta is +1+1 at Δ∈πZ\Delta \in \pi\mathbb{Z} and −1-1 at the odd multiples of π/2\pi/2, which are unstable. For QPSK, the S-curve is 2sin⁡Δ\sqrt2\sin\Delta on (−π/4,π/4)(-\pi/4, \pi/4) with slope 2\sqrt2 at 00, and it jumps from +1+1 to −1-1 at Δ=π/4\Delta = \pi/4, so it drives the error away from ±π/4\pm\pi/4 and toward the nearest multiple of π/2\pi/2. Near a stable point, the loop is the PLL with detector gain KdK_d, and the PLL proof gives the rest. □\square

The ambiguity cannot be removed by any detector that does not know the data. For BPSK, the received sequence for (θ,a)(\theta, a) and for (θ+π,−a)(\theta + \pi, -a) is the same, so no function of rr alone can tell θ\theta from θ+π\theta + \pi. For QPSK the same holds for (θ+π/2,−ja)(\theta + \pi/2, -ja).

Theorem 2 (BPSK variance with the squaring loss). For BPSK in the linear model, the phase error variance is

σϕ2=BLTSNR(1+12 SNR).\sigma_\phi^2 = \frac{B_L T}{\mathrm{SNR}}\left(1 + \frac{1}{2\,\mathrm{SNR}}\right).

Proof. At lock, zk=akejΔ+nkz_k = a_k e^{j\Delta} + n_k with nk=nI+jnQ∼CN(0,N0)n_k = n_I + j n_Q \sim \mathcal{CN}(0, N_0), independent of the past by the rotation invariance used in the PLL proof. For small Δ\Delta, I=ak+nII = a_k + n_I and Q=akΔ+nQQ = a_k \Delta + n_Q to first order, so

ek=Δ(1+aknI)+aknQ+nInQ.e_k = \Delta(1 + a_k n_I) + a_k n_Q + n_I n_Q.

The mean slope is 11. The noise term vk=aknQ+nInQv_k = a_k n_Q + n_I n_Q has mean 00 and variance E[nQ2]+E[nI2]E[nQ2]=N02+N024E[n_Q^2] + E[n_I^2] E[n_Q^2] = \frac{N_0}{2} + \frac{N_0^2}{4}, and the vkv_k are uncorrelated. The PLL proof gives the variance σv2⋅2BLT=N0BLT(1+N0/2)\sigma_v^2 \cdot 2 B_L T = N_0 B_L T (1 + N_0/2). With N0=1/SNRN_0 = 1/\mathrm{SNR} this is the formula. □\square

The factor 1+1/(2 SNR)1 + 1/(2\,\mathrm{SNR}) is the squaring loss: the noise times noise term nInQn_I n_Q. For QPSK with correct signs of II and QQ, the same expansion gives ek=2Δ+vke_k = \sqrt2\Delta + v_k with Var⁡vk=N0\operatorname{Var} v_k = N_0, so σϕ2=N0⋅2BLT/2=BLT/SNR\sigma_\phi^2 = N_0 \cdot 2B_L T/2 = B_L T/\mathrm{SNR}; 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 O(1)O(1) per symbol, O(N)O(N) for NN symbols in the real RAM, and O(1)O(1) 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 1+1/(2 SNR)1 + 1/(2\,\mathrm{SNR}) 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 π\pi (BPSK) or π/2\pi/2 (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 A2A^2, the square of the signal amplitude, and the QPSK detector scales with AA. 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 0.0010.001 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. e=IQ(I2−Q2)e = IQ(I^2 - Q^2), which is 14Im⁡(z4)\frac14 \operatorname{Im}(z^4), is the fourth-power detector of the squaring loop with M=4M = 4. The hard-limited form of line L5 has less noise at moderate and high SNR.
  • Decision-directed loop. Replacing sgn⁡(I)\operatorname{sgn}(I) and sgn⁡(Q)\operatorname{sgn}(Q) 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 tanh⁡(2I/N0) Q\tanh(2I/N_0)\, Q. It becomes IQIQ at low SNR, up to a constant, and sgn⁡(I) Q\operatorname{sgn}(I)\, Q 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 Kd=2K_d = \sqrt2. Using the BPSK gains for QPSK makes the loop 2\sqrt2 times wider than designed.
  • Ignoring the ambiguity. A Costas loop can lock with an error of π\pi (BPSK) or a multiple of π/2\pi/2 (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 π\pi, half that of a PLL, and that of QPSK has period π/2\pi/2. 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 II and QQ, and the loop variance grows even without channel noise.
  • Using BPSK on a QPSK signal. For QPSK, IQIQ 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.

costas_loop.pyI0RawGitHub
# 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

  1. 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
  2. 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)
  3. 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.

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