Algorithm Search⌘K

Algorithmcore

Gardner timing error detector

Also called Gardner TED, Gardner algorithm.

A timing error detector at two samples per symbol. It multiplies the midpoint sample by the difference of the two strobes around it, needs no decisions and does not depend on the carrier phase.

Time
O(N) worst
Space
O(1) extra
Where
N = the number of symbols
Properties
carrier phase invariantdeterministicnon data aidedonline
Origin
Floyd M. Gardner, 1986

The Gardner timing error detector is the most common non-data-aided detector for symbol timing recovery in digital modems. It takes two samples per symbol: the strobe yky_k, where the symbol should be read, and the midpoint yk−1/2y_{k-1/2} halfway between two strobes. Its output is ek=Re⁡{yk−1/2‾ (yk−1−yk)}e_k = \operatorname{Re}\{\overline{y_{k-1/2}}\,(y_{k-1} - y_k)\}. When the data change sign between two symbols, the midpoint lies on the zero crossing of the transition if the timing is right, and it moves away from zero, with a sign that shows the direction of the error, if the timing is wrong. The product with yk−1−yky_{k-1} - y_k removes the sign of the transition. The detector needs no decisions, and a carrier phase cancels in the product, so the loop can run before carrier recovery. For raised cosine pulses its mean output is Asin⁡(2πΔ)A\sin(2\pi\Delta) with A=4sin⁡(πβ/2)π(4−β2)A = \frac{4\sin(\pi\beta/2)}{\pi(4 - \beta^2)}. It drives the loop filter and accumulator of a phase-locked loop, with a Farrow interpolator when the sample clock is free-running. Against the early-late gate it needs one sample fewer per symbol and has less self-noise; against the Mueller and Muller detector it needs twice the samples but no decisions and no carrier phase.

In plain words

Picture the signal moving from one symbol value to the next. If the next symbol has the opposite sign, the signal crosses zero on the way, and with correct timing it crosses exactly halfway between the two reading points. The detector reads the signal at that halfway point too. If the halfway reading is not zero, the timing is off, and whether it lies above or below zero, compared with the direction of the change, tells whether the reading points are early or late. When two neighboring symbols are equal, the difference between them is near zero and the detector says almost nothing, which is correct because there is no crossing to measure. A turn of the whole signal by the carrier does not matter, since the detector compares the signal only with itself.

The problem

Times are in symbol periods, T=1T = 1. The receiver can sample the matched filter output

y(t)=ejθ∑mam g(t−m−τ)+v(t)y(t) = e^{j\theta}\sum_m a_m\,g(t - m - \tau) + v(t)

at times it chooses, with a controlled clock or with an interpolator on a fixed grid of at least two samples per symbol. The pulse gg is real and even (a raised cosine with roll-off β\beta in the analysis), the symbols ama_m are unknown, independent and zero-mean with E∣am∣2=1E|a_m|^2 = 1 (BPSK, QPSK or QAM), θ\theta is an unknown carrier phase, vv is filtered noise with SNR=Es/N0\mathrm{SNR} = E_s/N_0, and the delay τ\tau is unknown and may drift. The loop must give estimates τk\tau_k so that the strobes y(k+τk)y(k + \tau_k) fall on the symbol instants.

The algorithm

  1. GARDNER(y, N, Kp, Ki, tau0)
  2. 1tau <- tau0; s <- 0
  3. 2prev <- y(-1 + tau)
  4. 3for k <- 0 to N - 1 do
  5. 4mid <- y(k - 1/2 + tau) ▷ midpoint sample
  6. 5cur <- y(k + tau) ▷ strobe; est[k] <- tau
  7. 6e <- Re(conj(mid) * (prev - cur)) ▷ Gardner detector
  8. 7s <- s + Ki * e ▷ loop filter
  9. 8tau <- tau + Kp * e + s ▷ timing accumulator
  10. 9prev <- cur
  11. 10return est, strobes

Line L6 is the detector. With this sign it is positive when the strobes are early (τk<τ\tau_k < \tau), so line L8 adds it. Gardner's paper writes the difference the other way and subtracts. Line L9 keeps the strobe for the next symbol, so each symbol costs two new samples. Lines L7 and L8 are the PLL loop with the delay in place of the phase. For a first-order loop with noise bandwidth BLTB_LT, Kp=4BLT/((1+2BLT)KD)K_p = 4B_LT/\bigl((1 + 2B_LT)K_D\bigr) with the detector slope KD=2πAK_D = 2\pi A at unit symbol energy, which is 1.5084941.508494 for β=0.5\beta = 0.5.

Example

Take QPSK data (seed 1), β=0.5\beta = 0.5, the true delay τ=0.3\tau = 0.3, no noise, BLT=0.01B_LT = 0.01 and Ki=0K_i = 0, so Kp=0.025997K_p = 0.025997. The loop starts at τ0=0\tau_0 = 0, and the samples are rounded to three decimals:

kk τk\tau_k prev mid (L4) cur (L5) eke_k (L6) τk+1\tau_{k+1} (L8)
0 00 0.104−0.080j0.104 - 0.080j −0.173+0.112j-0.173 + 0.112j −0.702+0.490j-0.702 + 0.490j −0.203510-0.203510 −0.005291-0.005291
1 −0.005291-0.005291 −0.702+0.490j-0.702 + 0.490j −0.487+0.826j-0.487 + 0.826j 0.463+0.935j0.463 + 0.935j 0.1989660.198966 −0.000118-0.000118
2 −0.000118-0.000118 0.463+0.935j0.463 + 0.935j 0.563+0.402j0.563 + 0.402j −0.389−0.520j-0.389 - 0.520j 1.0648071.064807 0.0275630.027563

The mean error at Δ=0.3\Delta = 0.3 is Asin⁡(0.6π)=0.2283A\sin(0.6\pi) = 0.2283, but the first output is negative: at k=0k = 0 the data pattern pulls the wrong way. The large output at k=2k = 2 comes from a full sign change in both the real and the imaginary parts, the case that carries the most timing information. The error τ−τk\tau - \tau_k is 0.2380.238 at k=10k = 10, 0.1770.177 at 2525, 0.0520.052 at 5050 and below 10−310^{-3} at 100100 and 200200. After that the loop jitters around the delay with an rms error of 0.0050.005 and peaks of 0.0110.011, without noise. With alternating data am=(−1)ma_m = (-1)^m, the output is sin⁡(2πΔ)\sin(2\pi\Delta) exactly and the loop stays at τ\tau.

In noise at Es/N0=10E_s/N_0 = 10 dB with BLT=0.01B_LT = 0.01, the loop form of the MCRB is 2.66×10−42.66 \times 10^{-4}. Three runs of 2400 symbols (seeds 7, 8 and 9) measured a variance of 1.361.36 to 2.082.08 times this bound (measurement).

Correctness

Claim. For raised cosine pulses, independent zero-mean data and stationary noise, the mean of eke_k with τk\tau_k held fixed is Asin⁡(2πΔ)A\sin(2\pi\Delta), Δ=τ−τk\Delta = \tau - \tau_k, for every carrier phase. So the loop has stable points at Δ∈Z\Delta \in \mathbb{Z} and behaves near lock as a PLL with detector gain 2πA2\pi A.

Key steps. A phase ejθe^{j\theta} cancels between yk−1/2‾\overline{y_{k-1/2}} and yk−1−yky_{k-1} - y_k. The cross terms between different symbols have mean zero, so the mean is a sum over all integer shifts of p(t)=g(t−12)(g(t−1)−g(t))p(t) = g(t - \frac12)\bigl(g(t - 1) - g(t)\bigr). By Poisson summation only the Fourier coefficients at 00 and ±1\pm1 remain. The one at 00 is zero, because both products have the same integral, the autocorrelation of gg at lag 12\frac12. The one at 11 is jA2\frac{jA}{2}, an integral over the roll-off band. The full proof is in the proofs file.

The S-curve is a closed form under assumptions: raised cosine pulses, independent data, stationary noise, and τk\tau_k constant while the mean is taken. The jitter and the noise ratios are measurements.

Proof: The Gardner detector has the S-curve A sin(2 pi Delta) with A = 4 sin(pi beta/2) / (pi (4 - beta^2)) for raised cosine pulses, and it does not depend on the carrier phasefull

Times are in symbol periods, T=1T = 1. The matched filter output is y(t)=ejθ∑mamg(t−m−τ)+v(t)y(t) = e^{j\theta}\sum_m a_m g(t - m - \tau) + v(t), with a raised cosine pulse gg of roll-off 0<β<10 < \beta < 1, independent data with Eam=0E a_m = 0 and E∣am∣2=1E|a_m|^2 = 1, any carrier phase θ\theta, and noise vv independent of the data with zero mean. With τk\tau_k held fixed, line L2 or line L9 gives the previous strobe y(k−1+τk)y(k - 1 + \tau_k), line L4 gives the midpoint y(k−12+τk)y(k - \frac12 + \tau_k) and line L5 the current strobe y(k+τk)y(k + \tau_k). Line L6 forms

ek=Re⁡{y(k−12+τk)‾ (y(k−1+τk)−y(k+τk))}.e_k = \operatorname{Re}\bigl\{\overline{y(k - \tfrac12 + \tau_k)}\,\bigl(y(k - 1 + \tau_k) - y(k + \tau_k)\bigr)\bigr\}.

Write Δ=τ−τk\Delta = \tau - \tau_k. G(f)G(f) is the raised cosine spectrum, and on ∣u∣≤β2|u| \le \frac{\beta}{2} it satisfies G(12+u)=12(1−sin⁡πuβ)G(\frac12 + u) = \frac12(1 - \sin\frac{\pi u}{\beta}) and G(12−u)=12(1+sin⁡πuβ)G(\frac12 - u) = \frac12(1 + \sin\frac{\pi u}{\beta}).

Lemma 1 (phase invariance). eke_k does not change when yy is replaced by ejϕye^{j\phi}y for any real ϕ\phi.

Proof. ejϕy1‾ (ejϕy2−ejϕy3)=e−jϕejϕ y1‾(y2−y3)\overline{e^{j\phi}y_1}\,(e^{j\phi}y_2 - e^{j\phi}y_3) = e^{-j\phi}e^{j\phi}\,\overline{y_1}(y_2 - y_3). □\square

Lemma 2 (mean as a periodic sum). Without noise, E[ek]=∑mp(m−Δ)E[e_k] = \sum_m p(m - \Delta), where p(t)=g(t−12)(g(t−1)−g(t))p(t) = g(t - \frac12)\bigl(g(t - 1) - g(t)\bigr).

Proof. By Lemma 1 we can take θ=0\theta = 0. Each of the three samples is ∑mamg(⋅)\sum_m a_m g(\cdot), with the arguments k−m−12−Δk - m - \frac12 - \Delta, k−m−1−Δk - m - 1 - \Delta and k−m−Δk - m - \Delta. The cross terms with m≠m′m \ne m' have mean zero, and E∣am∣2=1E|a_m|^2 = 1, so E[ek]=∑mp(k−m−Δ)E[e_k] = \sum_m p(k - m - \Delta). As mm runs over all integers, so does n=k−mn = k - m, which gives ∑np(n−Δ)\sum_n p(n - \Delta). The result is real because gg is real. With noise, the extra term is E[v(t1)‾(v(t2)−v(t3))]E[\overline{v(t_1)}(v(t_2) - v(t_3))] with t2−t1=−12t_2 - t_1 = -\frac12 and t3−t1=12t_3 - t_1 = \frac12, which is zero for a stationary noise with an even real autocorrelation. □\square

Theorem 1 (S-curve). E[ek]=Asin⁡(2πΔ)E[e_k] = A\sin(2\pi\Delta) with

A=4sin⁡(πβ/2)π(4−β2).A = \frac{4\sin(\pi\beta/2)}{\pi(4 - \beta^2)}.

For β=0.5\beta = 0.5, A=0.2400843A = 0.2400843 and the slope at lock is KD=2πA=1.508494K_D = 2\pi A = 1.508494.

Proof. By Poisson summation, ∑mp(m−Δ)=∑nP(n)e−j2πnΔ\sum_m p(m - \Delta) = \sum_n P(n)e^{-j2\pi n\Delta}, where PP is the Fourier transform of pp. Each product of two shifted copies of gg has a transform supported on ∣f∣≤1+β<2|f| \le 1 + \beta < 2, so only n∈{−1,0,1}n \in \{-1, 0, 1\} remain.

For n=0n = 0: P(0)=∫g(t−12)g(t−1) dt−∫g(t−12)g(t) dtP(0) = \int g(t - \frac12)g(t - 1)\,dt - \int g(t - \frac12)g(t)\,dt. Both integrals equal the autocorrelation of gg at lag 12\frac12, because gg is even. So P(0)=0P(0) = 0.

For n=1n = 1: let qs(t)=g(t−12)g(t−12+s)q_s(t) = g(t - \frac12)g(t - \frac12 + s), so p=q−1/2−q1/2p = q_{-1/2} - q_{1/2}. Its transform at 11 is Qs(1)=e−jπ∫G(f)G(1−f)ej2π(1−f)sdfQ_s(1) = e^{-j\pi}\int G(f)G(1 - f)e^{j2\pi(1 - f)s}df. The integrand is nonzero only for f=12+uf = \frac12 + u, ∣u∣≤β2|u| \le \frac{\beta}{2}, where G(f)G(1−f)=14cos⁡2πuβG(f)G(1 - f) = \frac14\cos^2\frac{\pi u}{\beta}. For s=−12s = -\frac12 the exponential is −jejπu-je^{j\pi u}, and for s=12s = \frac12 it is je−jπuje^{-j\pi u}. So

P(1)=Q−1/2(1)−Q1/2(1)=j2∫−β/2β/2cos⁡2πuβcos⁡(πu) du.P(1) = Q_{-1/2}(1) - Q_{1/2}(1) = \frac{j}{2}\int_{-\beta/2}^{\beta/2}\cos^2\frac{\pi u}{\beta}\cos(\pi u)\,du.

Write cos⁡2x=12(1+cos⁡2x)\cos^2 x = \frac12(1 + \cos 2x). The constant part gives 12∫−β/2β/2cos⁡(πu) du=1πsin⁡πβ2\frac12\int_{-\beta/2}^{\beta/2}\cos(\pi u)\,du = \frac{1}{\pi}\sin\frac{\pi\beta}{2}. For the other part, put α=2πβ\alpha = \frac{2\pi}{\beta}, so αβ2=π\frac{\alpha\beta}{2} = \pi. Then

∫−β/2β/2cos⁡(αu)cos⁡(πu) du=sin⁡(π−πβ2)α−π+sin⁡(π+πβ2)α+π=sin⁡πβ2(1α−π−1α+π)=2β2sin⁡(πβ/2)π(4−β2),\int_{-\beta/2}^{\beta/2}\cos(\alpha u)\cos(\pi u)\,du = \frac{\sin(\pi - \frac{\pi\beta}{2})}{\alpha - \pi} + \frac{\sin(\pi + \frac{\pi\beta}{2})}{\alpha + \pi} = \sin\frac{\pi\beta}{2}\Bigl(\frac{1}{\alpha - \pi} - \frac{1}{\alpha + \pi}\Bigr) = \frac{2\beta^2\sin(\pi\beta/2)}{\pi(4 - \beta^2)},

using α2−π2=π2(4−β2)/β2\alpha^2 - \pi^2 = \pi^2(4 - \beta^2)/\beta^2. Half of this is the second part. Together,

∫−β/2β/2cos⁡2πuβcos⁡(πu) du=sin⁡(πβ/2)π(1+β24−β2)=4sin⁡(πβ/2)π(4−β2)=A,\int_{-\beta/2}^{\beta/2}\cos^2\frac{\pi u}{\beta}\cos(\pi u)\,du = \frac{\sin(\pi\beta/2)}{\pi}\Bigl(1 + \frac{\beta^2}{4 - \beta^2}\Bigr) = \frac{4\sin(\pi\beta/2)}{\pi(4 - \beta^2)} = A,

so P(1)=jA2P(1) = \frac{jA}{2}. Since pp is real, P(−1)=P(1)‾=−jA2P(-1) = \overline{P(1)} = -\frac{jA}{2}. The sum is 2Re⁡{jA2e−j2πΔ}=Asin⁡(2πΔ)2\operatorname{Re}\{\frac{jA}{2}e^{-j2\pi\Delta}\} = A\sin(2\pi\Delta). □\square

Theorem 2 (lock points). In the mean, the loop of lines L7 and L8 with Kp>0K_p > 0 has stable points at Δ∈Z\Delta \in \mathbb{Z} and unstable points at Δ∈12+Z\Delta \in \frac12 + \mathbb{Z}. The linear model of the phase-locked loop with detector gain KD=2πAK_D = 2\pi A applies near lock, for every carrier phase.

Proof. As for any sine S-curve: A>0A > 0, the slope at 00 is 2πA>02\pi A > 0 and the slope at 12\frac12 is negative. Lemma 1 removes θ\theta. □\square

Theorem 3 (alternating data). If am=(−1)ma_m = (-1)^m and there is no noise, then ek=sin⁡(2πΔ)e_k = \sin(2\pi\Delta) exactly.

Proof. As in the early-late gate proof, y(t)=±ejθcos⁡(π(t−τ))y(t) = \pm e^{j\theta}\cos(\pi(t - \tau)). With c=π(k−Δ)c = \pi(k - \Delta), the samples are cos⁡(c−π)=−cos⁡c\cos(c - \pi) = -\cos c, cos⁡(c−π2)=sin⁡c\cos(c - \frac{\pi}{2}) = \sin c and cos⁡c\cos c, so ek=sin⁡c (−2cos⁡c)=−sin⁡(2c)=−sin⁡(2πk−2πΔ)=sin⁡(2πΔ)e_k = \sin c\,(-2\cos c) = -\sin(2c) = -\sin(2\pi k - 2\pi\Delta) = \sin(2\pi\Delta). □\square

The S-curve is a closed form under assumptions: raised cosine pulses, independent zero-mean data, stationary noise, and τk\tau_k constant while the mean is taken. The detector also has self-noise from the data pattern, which is zero for alternating data (Theorem 3) and not zero for random data. The tests check Theorem 1 on 1280 random QPSK symbols at three offsets, and Theorem 3 to 10−510^{-5}, the error of the truncated pulse sum in the test signal.

Complexity

Each symbol needs two new samples (lines L4 and L5), one complex subtraction, the real part of one complex product (two real multiplications and one addition), and the four operations of lines L7 and L8. With an interpolator of KK taps, a symbol costs 2K+O(1)2K + O(1) operations. The loop is O(1)O(1) per symbol and O(N)O(N) for NN symbols in the real RAM, with O(1)O(1) extra space besides the output.

Properties

  • Non-data-aided and phase-free. It needs no decisions and no carrier phase, so it works from the first symbol, before the carrier loop has locked. A residual frequency offset that turns the phase slowly does not disturb it.
  • Two samples per symbol. The strobe of one symbol is reused as the previous strobe of the next, so the sample rate is 2/T2/T, as in many modems that sample at twice the symbol rate anyway.
  • Needs excess bandwidth. A→0A \to 0 as β→0\beta \to 0: A=0.240A = 0.240 at β=0.5\beta = 0.5 and 0.0500.050 at β=0.1\beta = 0.1. With little excess bandwidth the S-curve is small and the self-noise dominates.
  • Self-noise and loop offset (measurement). Without noise the rms jitter was 0.00530.0053 at BLT=0.01B_LT = 0.01 and 0.00130.0013 at BLT=0.0025B_LT = 0.0025, and the mean of τk−τ\tau_k - \tau was about 0.32 BLT0.32\,B_LT, over three seeds each. The jitter is a third of that of the square-law early-late gate with the same bandwidth.
  • Gain depends on amplitude. KDK_D scales with the signal power, so an automatic gain control should come first.

Variants and improvements

  • Real-valued form. For BPSK, or for the real and imaginary parts of QPSK separately, e=yk−1/2I(yk−1I−ykI)+yk−1/2Q(yk−1Q−ykQ)e = y^I_{k-1/2}(y^I_{k-1} - y^I_k) + y^Q_{k-1/2}(y^Q_{k-1} - y^Q_k), which is the same value written without complex arithmetic.
  • Decision-directed form. Replacing yk−1−yky_{k-1} - y_k by a^k−1−a^k\hat a_{k-1} - \hat a_k removes much of the self-noise at high SNR, but it needs decisions and the carrier phase.
  • Feedforward use. The same products can be averaged over a block to estimate a fixed delay, but the Oerder and Meyr estimator is the usual feedforward choice.
  • Interpolated loop. In Gardner's 1993 structure, the sampler runs from a fixed clock, a numerically controlled oscillator gives the basepoint and the fractional interval, and a Farrow interpolator computes the samples of lines L4 and L5.

When to use it

Use the Gardner detector when the receiver has two samples per symbol, the modulation is BPSK, QPSK or a QAM with moderate roll-off, and the timing must lock before the carrier. It is the default choice in many software and hardware modems. With a small roll-off, or when decisions are reliable and the carrier phase is known, the Mueller and Muller detector or a data-aided detector gives less jitter. For short bursts, a feedforward estimate avoids the acquisition time of the loop.

Pitfalls

  • Wrong midpoint. The midpoint must be half a symbol before the current strobe, between the two strobes in the product. Taking it after the current strobe reverses the sign of the S-curve, and the loop locks half a symbol off.
  • Sign convention. Gardner's paper uses yk−yk−1y_k - y_{k-1} and subtracts the error from the timing. Mixing one convention for the detector with the other for the update makes the loop diverge from the right point.
  • Long runs of equal symbols. A run of equal symbols has no transitions and gives no timing information. Scrambling the data keeps transitions frequent.
  • Small roll-off. At β=0.1\beta = 0.1 the slope is a fifth of that at β=0.5\beta = 0.5. Use a narrow loop or another detector.
  • Offset QPSK. In OQPSK the quadrature data are delayed by half a symbol, so the detector must use the matching midpoint for each arm, or it sees no S-curve.

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.

gardner_timing_error_detector.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gardner-timing-error-detector/. The authors are listed in prov/9K1C0E.jsonl.

"""The Gardner timing error detector (F. M. Gardner, 1986) in a first- or second-order loop.

Times are in symbol periods T. The receiver has a sampler y(t) for the matched
filter output (an ADC with a controlled clock, or an interpolator). The loop
takes two samples per symbol: the strobe y(k + tau_k) and the midpoint
y(k - 1/2 + tau_k). The detector is

    e_k = Re{ conj(y(k - 1/2 + tau_k)) (y(k - 1 + tau_{k-1}) - y(k + tau_k)) },

which is positive when the receiver samples too early (tau_k < tau). It needs
no decisions and no carrier phase: a phase rotation of y cancels in the
product. For raised cosine pulses with roll-off beta and i.i.d. zero-mean data
with E|a|^2 = 1, the mean of e_k is A sin(2 pi delta) with
A = 4 sin(pi beta / 2) / (pi (4 - beta^2)) and delta = tau - tau_k.
(This sign convention makes tau grow when e > 0; Gardner's paper writes the
difference the other way and subtracts.)
"""

import math
from typing import Callable

Sampler = Callable[[float], complex]


def detector(prev: complex, mid: complex, cur: complex) -> float:
    """The Gardner error from the previous strobe, the midpoint and the current strobe."""
    return (mid.conjugate() * (prev - cur)).real  # @line L6


def s_curve_amplitude(beta: float) -> float:
    """A in E[e] = A sin(2 pi delta), for raised cosine pulses and i.i.d. data."""
    return 4.0 * math.sin(math.pi * beta / 2.0) / (math.pi * (4.0 - beta * beta))


def gain_for_bandwidth(bl_t: float, kd: float) -> float:
    """kp of a first-order loop with noise bandwidth B_L T for the detector slope kd."""
    return 4.0 * bl_t / ((1.0 + 2.0 * bl_t) * kd)


def gardner_loop(
    sample: Sampler,
    n: int,
    kp: float,
    ki: float = 0.0,
    tau0: float = 0.0,
) -> tuple[list[float], list[complex]]:
    """Run the loop over n symbols. Return the estimates tau_k and the strobes y(k + tau_k)."""
    tau, s = tau0, 0.0  # @line L1
    prev = sample(-1.0 + tau)  # @line L2
    taus: list[float] = []
    strobes: list[complex] = []
    for k in range(n):  # @line L3
        taus.append(tau)
        mid = sample(k - 0.5 + tau)  # @line L4
        cur = sample(k + tau)  # @line L5
        strobes.append(cur)
        e = detector(prev, mid, cur)  # @line L6
        s += ki * e  # @line L7
        tau += kp * e + s  # @line L8
        prev = cur  # @line L9
    return taus, strobes  # @line L10
test_gardner_timing_error_detector.py 139 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gardner-timing-error-detector/. The authors are listed in prov/9K1C0E.jsonl.

import cmath
import math
import random

from gardner_timing_error_detector import detector, gain_for_bandwidth, gardner_loop, s_curve_amplitude

BETA = 0.5
TAU = 0.3
QPSK = [cmath.exp(1j * (math.pi / 4 + m * math.pi / 2)) for m in range(4)]


def rc(t, b):
    """The raised cosine pulse with roll-off b and T = 1."""
    if abs(t) < 1e-12:
        return 1.0
    if abs(abs(t) - 1 / (2 * b)) < 1e-9:
        return math.pi / 4 * math.sin(math.pi / (2 * b)) / (math.pi / (2 * b))
    return math.sin(math.pi * t) / (math.pi * t) * math.cos(math.pi * b * t) / (1 - (2 * b * t) ** 2)


def rrc(t, b):
    """The root raised cosine pulse with roll-off b and T = 1."""
    if abs(t) < 1e-12:
        return 1 - b + 4 * b / math.pi
    if abs(abs(t) - 1 / (4 * b)) < 1e-9:
        return b / math.sqrt(2) * ((1 + 2 / math.pi) * math.sin(math.pi / (4 * b)) + (1 - 2 / math.pi) * math.cos(math.pi / (4 * b)))
    return (math.sin(math.pi * (1 - b) * t) + 4 * b * t * math.cos(math.pi * (1 + b) * t)) / (math.pi * t * (1 - (4 * b * t) ** 2))


def make_sampler(a, tau, n0=0.0, seed=0, theta=0.0, span=4, reach=8):
    """Matched filter output y(t) = e^(j theta) sum a_k g(t - k - tau) + v(t), g raised cosine.

    The noise is v(t) = sum_n w_n rrc(t - n h) with h = 1/2 and w_n i.i.d.
    CN(0, h n0). Since rrc has bandwidth (1 + beta)/2 < 1/(2h), v is stationary
    with autocorrelation n0 g(t - s): the matched filter output of white noise
    of density n0 (up to the cut of rrc at span symbols).
    """
    rot = cmath.exp(1j * theta)
    h = 0.5
    n_lo = int(-6 / h)
    w = None
    if n0 > 0:
        rng = random.Random(seed)
        sd = math.sqrt(h * n0 / 2)
        w = [complex(rng.gauss(0, sd), rng.gauss(0, sd)) for _ in range(int((len(a) + 12) / h))]
    reach_w = int(span / h)

    def sample(t):
        k0 = int(round(t - tau))
        acc = 0j
        for k in range(max(0, k0 - reach), min(len(a), k0 + reach + 1)):
            acc += a[k] * rc(t - k - tau, BETA)
        acc *= rot
        if w is not None:
            c = int(round(t / h))
            for n in range(c - reach_w, c + reach_w + 1):
                acc += w[n - n_lo] * rrc(t - n * h, BETA)
        return acc

    return sample


def qpsk(n, seed):
    rng = random.Random(seed)
    return [rng.choice(QPSK) for _ in range(n)]


def test_amplitude_closed_form():
    assert abs(s_curve_amplitude(0.5) - 0.2400843) < 1e-6
    # For small roll-off the amplitude is about beta / 2.
    assert abs(s_curve_amplitude(0.01) / 0.005 - 1) < 1e-3


def test_noise_model_has_unit_variance_at_any_offset():
    sample = make_sampler([0j] * 600, TAU, n0=1.0, seed=11)
    for off in (0.0, 0.25, 0.5):
        vals = [sample(k + off) for k in range(5, 595)]
        var = sum(abs(v) ** 2 for v in vals) / len(vals)
        # 590 samples that are nearly independent: the standard error is about 0.04.
        assert abs(var - 1.0) < 0.2


def test_exact_lock_on_alternating_data():
    # With a_k = (-1)^k the signal is cos(pi (t - tau)) and the error is
    # sin(2 pi (tau - tau_k)) exactly, so the loop has no self-noise.
    a = [(-1) ** k + 0j for k in range(400)]
    taus, _ = gardner_loop(make_sampler(a, TAU, reach=24), 360, kp=0.1)
    # What is left comes from cutting the pulse at 24 symbols.
    for t in taus[300:]:
        assert abs(t - TAU) < 1e-5


def test_detector_mean_matches_s_curve():
    a = qpsk(1300, 2)
    sample = make_sampler(a, TAU)
    amp = s_curve_amplitude(BETA)
    for delta in (-0.3, 0.1, 0.2):
        es = []
        for k in range(10, 1290):
            t = k + TAU - delta
            es.append(detector(sample(t - 1), sample(t - 0.5), sample(t)))
        mean = sum(es) / len(es)
        # The standard error of the mean is about 0.02 here.
        assert abs(mean - amp * math.sin(2 * math.pi * delta)) < 0.06


def test_carrier_phase_does_not_change_the_loop():
    a = qpsk(300, 4)
    t1, _ = gardner_loop(make_sampler(a, TAU), 250, kp=0.05)
    t2, _ = gardner_loop(make_sampler(a, TAU, theta=2.3), 250, kp=0.05)
    assert max(abs(x - y) for x, y in zip(t1, t2)) < 1e-9


def test_random_data_noiseless_settles_near_true_delay():
    a = qpsk(1700, 5)
    kd = 2 * math.pi * s_curve_amplitude(BETA)
    taus, _ = gardner_loop(make_sampler(a, TAU), 1650, kp=gain_for_bandwidth(0.0025, kd))
    tail = taus[800:]
    mean = sum(tail) / len(tail)
    assert abs(mean - TAU) < 0.003
    assert max(abs(t - TAU) for t in tail) < 0.006


def test_noise_variance_against_mcrb():
    snr = 10.0
    bl_t = 0.01
    xi = 1.0 / 12.0 + BETA ** 2 * (0.25 - 2.0 / math.pi ** 2)
    mcrb = bl_t / (4 * math.pi ** 2 * xi * snr)
    a = qpsk(2400, 6)
    sample = make_sampler(a, TAU, n0=1.0 / snr, seed=7)
    kd = 2 * math.pi * s_curve_amplitude(BETA)
    taus, _ = gardner_loop(sample, 2350, kp=gain_for_bandwidth(bl_t, kd))
    tail = taus[400:]
    mean = sum(tail) / len(tail)
    var = sum((t - mean) ** 2 for t in tail) / len(tail)
    assert 1.0 <= var / mcrb <= 4.0

History

Floyd M. Gardner published the detector in the IEEE Transactions on Communications in 1986, for receivers that sample at two samples per symbol with a clock that is not tied to the symbol rate. Its independence of the carrier phase allowed timing recovery to come first in a digital receiver. In 1993 Gardner, with Lars Erup and Robert A. Harris, described how such a loop drives an interpolator from a free-running sample clock, and the pair of the Gardner detector and a Farrow interpolator became a standard structure in digital modems.

References

  1. F. M. Gardner, A BPSK/QPSK timing-error detector for sampled receivers, IEEE Transactions on Communications 34(5), 1986, pages 423 to 429, the detector from the midpoint sample and the two strobes, its S-curve, and its independence of the carrier phase
  2. F. M. Gardner, Interpolation in digital modems, Part I: Fundamentals, IEEE Transactions on Communications 41(3), 1993, pages 501 to 507, timing loops with a free-running sampler, an interpolator and a numerically controlled oscillator
  3. Umberto Mengali and Aldo N. D'Andrea, Synchronization Techniques for Digital Receivers, Plenum Press, 1997, Chapter 7 (timing recovery in baseband transmission) and Chapter 8 (timing recovery with linear modulations: the non-data-aided detectors)
  4. Heinrich Meyr, Marc Moeneclaey and Stefan A. Fechtel, Digital Communication Receivers, Wiley, 1998, Chapter 9 (interpolation and the digital timing loop)

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