Algorithmadvanced
Van de Beek estimator
Also called cyclic prefix ML synchronization.
The maximum likelihood estimate of OFDM symbol timing and carrier frequency offset from the correlation of the cyclic prefix with the end of the symbol. It needs no training symbol.
- Time
- O(P + T) worst
- Space
- O(T) extra
- Where
- N = the number of subcarriers; P = the prefix length N_cp; T = the number of candidate starts
- Model
- Real RAM
- Properties
- blinddeterministicmaximum likelihoodtiming and frequency
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jan Jaap van de Beek, Magnus Sandell, Per Ola Börjesson, 1997
The van de Beek estimator finds where an OFDM symbol starts and the carrier frequency offset of the receiver from the cyclic prefix alone, without a training symbol. In OFDM, the first samples of each symbol are a copy of its last samples, samples later. The estimator slides a window of samples along the input and, for each candidate start , correlates the window with the samples positions later, . It also computes the energy of the same samples. The timing estimate maximizes , with , and the offset estimate is in subcarrier spacings. Van de Beek, Sandell and Börjesson showed that this is the joint maximum likelihood estimate when the OFDM samples are modeled as Gaussian and the channel adds white noise only. It solves the problem of frequency offset estimation and symbol timing for continuous OFDM streams. The page uses for the imaginary unit and for the offset. The code calls the prefix length l.
In plain words
Every OFDM symbol starts with a copy of its own tail. So somewhere in the received signal, a short stretch of samples matches another short stretch exactly one symbol body later. The receiver does not know where, so it tries every start. At each start it multiplies the stretch by the later stretch and adds up the products. At the right start, all the products point the same way and the sum is as large as the energy of the stretch. At wrong starts, they point in random directions and partly cancel. The right start is where the sum comes closest to the energy. A frequency offset turns the later copy by a fixed angle, so the angle of the sum at that start tells the receiver its offset.
The problem
The input is a window of complex baseband samples with , the DFT size , the prefix length and the SNR per sample. The model is , where is a stream of OFDM symbols with prefixes, is the unknown offset with , and is white noise . Find the index of the first sample of a prefix inside the window, and an estimate of .
The algorithm
VAN-DE-BEEK(r, N, N_cp, SNR)- 1
for θ ← 0, 1, .., M - N - N_cp do ▷ γ(0), Φ(0) are direct sums over k = 0, .., N_cp-1 - 2
γ(θ) ← γ(θ-1) + r[θ-1+N_cp] conj(r[θ-1+N_cp+N]) - r[θ-1] conj(r[θ-1+N]) - 3
Φ(θ) ← Φ(θ-1) + ½(|r[θ-1+N_cp]|² + |r[θ-1+N_cp+N]|² - |r[θ-1]|² - |r[θ-1+N]|²) - 4
Λ(θ) ← |γ(θ)| - ρ Φ(θ) for every θ, with ρ = SNR / (SNR + 1) - 5
θ̂ ← argmax_θ Λ(θ) - 6
ε̂ ← -angle(γ(θ̂)) / (2π) ▷ wrapped to [-1/2, 1/2) - 7
return θ̂, ε̂
Lines L1 to L3 slide the window of pairs: each step adds the newest pair and drops the oldest, so each candidate costs . On the prefix, the pair , holds the same sent sample, and the offset turns the second one by , so apart from noise. Line L4 compares the size of the correlation with the energy. Without noise, everywhere, with equality at a prefix start. With noise, the factor comes from the likelihood: it weights the energy less when the noise makes the pairs less alike. Line L5 picks the start, and line L6 reads the offset from the angle at that start.
Example
Take , , a stream of three symbols whose time samples are independent (seed 3), , no noise, and a window of 20 samples that starts 3 samples into the stream. The prefix of the second symbol starts at sample 10 of the stream, which is in the window. There are 11 candidates.
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1.382 | 1.197 | 1.678 | 0.684 | 0.725 | 0.363 | 2.182 | 4.650 | 3.309 | 2.064 | 1.364 | |
| 2.779 | 2.631 | 1.751 | 0.931 | 1.104 | 0.741 | 2.512 | 4.650 | 3.796 | 2.372 | 1.956 | |
| , | -1.397 | -1.434 | -0.073 | -0.248 | -0.380 | -0.378 | -0.330 | 0 | -0.487 | -0.308 | -0.592 |
| 0.407 | -0.390 | -0.397 | -0.162 | -0.168 | 0.391 | 0.123 | 0.1 | 0.065 | -0.051 | -0.096 |
Every is negative except at , where and , with the angle . Line L5 returns and line L6 returns . With the SNR set to 10 dB, so , the result is the same. At wrong starts the angle is random, which is why line L6 must use the angle at only.
At 10 dB per sample with , and , the tests measure 150 windows at random positions; about 95 percent of the timing estimates are within 2 samples of the prefix start, and at least 90 percent must be.
Correctness
Claim. (a) Under the Gaussian model, the log-likelihood of is a constant plus a positive multiple of , so lines L4 to L6 give the joint maximum likelihood estimate. (b) Without noise, for every , with equality at a prefix start, where the angle of is ; so the algorithm is exact for unless a wrong start ties. Both are theorems in the model above.
Key invariant. On a prefix, without noise. The Gaussian model makes every other pair of samples uncorrelated, so the likelihood depends on only through the prefix pairs, and these enter through and alone.
Part (b) is the triangle inequality with . At a high SNR, the variance of at the true start is close to , a closed form for a linearized phase error. The full proof is below.
Proof: The van de Beek statistic is the log-likelihood ratio of the Gaussian model, and it finds the exact timing and offset without noisefull
Notation. is the DFT size, the prefix length, and the imaginary unit. The receiver observes a window with , and a prefix starts at the unknown index , so for the sent sample equals . The channel adds white noise only, and the carrier offset is subcarrier spacings:
Lines L1 to L3 compute, for each candidate ,
Lemma 1 (running sums). If and are the direct sums, the updates of lines L2 and L3 give the sums above for every .
Proof. Going from to , the sum loses the term and gains the term . Line L2 adds with and subtracts with ; line L3 does the same for the energies.
The model. As in the paper of van de Beek, Sandell and Börjesson, model the sent samples as independent zero-mean circular complex Gaussian with variance , apart from the prefix copies, and the noise as independent . Let and . For a random OFDM symbol with many subcarriers, the time samples are close to Gaussian; for subcarrier values and the unitary inverse DFT they are exactly independent .
Lemma 2 (the pairs). For , the pair , has and . Every other pair of samples in the window is uncorrelated.
Proof. , because and the noise terms are independent of each other and of the signal. Two samples that are not a prefix pair use independent sent samples and independent noise.
Theorem 1 (the log-likelihood). Under the model, the log-likelihood of is
with independent of and . Its maximum over is at modulo 1, where the bracket equals . So lines L4 to L6 return the joint maximum likelihood estimate.
Proof. By Lemma 2, the window splits into the correlated pairs and independent single samples, so
and the first product does not depend on , because every sample has the same marginal . For one pair, the covariance matrix is with , its inverse is , and the quadratic form is . With , the log of the ratio is
because . Summing over gives the stated form with and . Finally , which is largest, and equal to , when modulo . The factor in front of the bracket is positive, so maximizing the bracket over after the maximization over is maximizing .
Theorem 2 (exact without noise). Without noise, take . Let the window contain a full prefix start , so . Then for every , , and modulo 1. If , the wrap after line L6 returns exactly. If no other ties, line L5 returns .
Proof. For any , the triangle inequality and give
so . At , for , so and . Both inequalities are equalities, , and the angle of is modulo .
A tie needs for all pairs at some other , with a common phase difference. For samples with a continuous distribution this has probability zero. With constant-modulus time samples it can happen, so the tests build the symbols from 4-QAM subcarrier values through an inverse DFT, whose time samples do not have a constant modulus.
The variance of the offset estimate (a closed form at high SNR). Fix the sent symbol, let be the energy of the prefix, and take with noise . Then
where is the rotated noise of the second sample, again . The three sums are uncorrelated with zero mean and have variances , and . For a small , the angle error is , and has half the variance of , so
With the mean energy and this is , which is for at 10 dB. The tests measure the variance for a fixed symbol within 15 percent of the first form. The estimate uses only the prefix pairs, so its variance is times larger than that of an estimator that correlates two repeated symbols of samples.
Complexity
The direct sums for cost , and each of the candidates costs in lines L2 to L4, so the time is in the real RAM. The implementation stores and for all candidates, extra space. A streaming receiver keeps only the running sums, a delay line of samples and the best value so far, so it needs space.
Properties
- Blind. It uses only the structure of the prefix, so it costs no training symbols and works on every symbol of a stream.
- Range. The offset is found modulo 1, so . An offset of is read as , as the tests check. The integer part needs another method.
- Variance. Close to at a high SNR: for at 10 dB. It uses pairs instead of , so the variance is times that of the Moose estimator, which correlates two repeated symbols.
- Timing spread. The metric changes slowly near the peak, so with noise the timing estimate spreads over a few samples. Short prefixes make this worse.
- Model. The derivation assumes Gaussian samples and a channel with white noise only. OFDM samples are close to Gaussian for large , so the estimator works well for real signals, but in a dispersive channel the first prefix samples contain interference from the previous symbol and it is no longer the maximum likelihood estimate.
Variants and improvements
- Average over symbols. In a continuous stream, the timing and the offset do not change from symbol to symbol, so adding and over several symbols, at the same position in each, cuts the variance roughly by the number of symbols.
- Without the SNR. Setting in line L4 gives , which needs no SNR. It is still exact without noise, but it is no longer the maximum likelihood estimate at a finite SNR.
- Correlation only. Some receivers use the maximum of alone. Without the energy term, a strong sample in a wrong window can win, so the estimate is worse.
- Dispersive channels. Correlating only the last samples of the prefix, which are free of interference from the previous symbol, removes the bias at the cost of fewer pairs.
- With pilots. Systems such as DVB-T add continual pilots for a finer frequency estimate and an integer offset search after the DFT; the prefix estimate serves for the first coarse step.
When to use it
Use it for a continuous OFDM stream without a preamble, as in digital broadcasting, or to track timing and offset on every symbol after acquisition. Use Schmidl-Cox synchronization for bursts with a preamble, where a large offset must be found quickly and the training symbol gives a wider range. Use the Moose estimator when two repeated symbols are available and the timing is known, to get a smaller variance.
Pitfalls
- The wrong sign in line L6. The product has the angle , so line L6 must negate the angle. With the product in line L2, the sign in line L6 must change too.
- Reading the angle at another start. Line L6 must take the angle of at from line L5. At other starts the angle is random, as the example shows.
- Correlating over the wrong lag. Line L2 must pair samples exactly apart, the DFT size, not , the symbol length.
- A window that is too short. Line L1 must see a whole prefix and its copy, so the window needs at least samples to contain a full prefix pair for any position of the stream.
- Dropping the energy term. Line L4 must subtract . The maximum of alone favors windows with large samples, not windows on the prefix.
- Constant-modulus test signals. If the time samples all have the same modulus, other starts can also give without noise, and line L5 may pick one of them. Test with Gaussian samples or with OFDM symbols made by an inverse DFT.
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
# Shared helper of the communications pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Complex baseband tools for the communications pages.
Vectors are lists of complex numbers. Matrices are lists of rows. The
functions here are plain building blocks: small linear algebra, convolution,
the DFT as a direct sum, the Gaussian Q function, dB conversion, complex
Gaussian noise and the Wilson score interval. No page algorithm (equalizer,
estimator, synchronizer, detector, precoder, demapper or power allocation)
lives in this file.
Conventions (prompts of the communications area):
- dft is X[k] = sum_n x[n] e^(-j 2 pi k n / N) with no factor; idft has 1/N.
- udft and uidft are the unitary pair, with 1/sqrt(N) on both sides.
- qfunc(x) = 0.5 erfc(x / sqrt(2)); it never computes 1 - Phi(x).
- cn(rng, var) draws CN(0, var): real and imaginary parts are independent
with variance var / 2 each, so E|w|^2 = var.
"""
import cmath
import math
import random
# ---------------------------------------------------------------- vectors and matrices
def zeros(rows: int, cols: int | None = None) -> list:
"""A zero vector of length rows, or a rows by cols zero matrix."""
if cols is None:
return [0j] * rows
return [[0j] * cols for _ in range(rows)]
def eye(n: int) -> list[list[complex]]:
"""The n by n identity matrix."""
return [[1 + 0j if i == k else 0j for k in range(n)] for i in range(n)]
def add(a: list, b: list) -> list:
"""Elementwise a + b for two vectors or two matrices of the same shape."""
if len(a) != len(b):
raise ValueError("shapes differ")
if a and isinstance(a[0], list):
return [add(r, s) for r, s in zip(a, b)]
return [x + y for x, y in zip(a, b)]
def sub(a: list, b: list) -> list:
"""Elementwise a - b for two vectors or two matrices of the same shape."""
if len(a) != len(b):
raise ValueError("shapes differ")
if a and isinstance(a[0], list):
return [sub(r, s) for r, s in zip(a, b)]
return [x - y for x, y in zip(a, b)]
def scale(c: complex, a: list) -> list:
"""The scalar c times a vector or a matrix."""
if a and isinstance(a[0], list):
return [scale(c, r) for r in a]
return [c * x for x in a]
def matmul(a: list[list[complex]], b: list[list[complex]]) -> list[list[complex]]:
"""The matrix product a b."""
if not a or not b or len(a[0]) != len(b):
raise ValueError("inner dimensions differ")
cols = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in cols] for row in a]
def matvec(a: list[list[complex]], x: list[complex]) -> list[complex]:
"""The matrix times vector product a x."""
if a and len(a[0]) != len(x):
raise ValueError("inner dimensions differ")
return [sum(p * q for p, q in zip(row, x)) for row in a]
def herm(a: list) -> list:
"""The conjugate transpose of a matrix. A vector gives its conjugate."""
if a and isinstance(a[0], list):
return [[complex(a[i][k]).conjugate() for i in range(len(a))] for k in range(len(a[0]))]
return [complex(x).conjugate() for x in a]
def dot(x: list[complex], y: list[complex]) -> complex:
"""The inner product x^H y = sum of conj(x_i) y_i."""
if len(x) != len(y):
raise ValueError("lengths differ")
return sum(complex(p).conjugate() * q for p, q in zip(x, y))
def norm2(x: list) -> float:
"""The squared Euclidean norm sum |x_i|^2 (squared Frobenius norm for a matrix)."""
if x and isinstance(x[0], list):
return sum(norm2(r) for r in x)
return sum(abs(v) ** 2 for v in x)
# ---------------------------------------------------------------- linear systems
def _lu(a: list[list[complex]]) -> tuple[list[list[complex]], list[int], int]:
"""LU factorization with partial pivoting. Returns (lu, perm, sign)."""
n = len(a)
if any(len(r) != n for r in a):
raise ValueError("matrix is not square")
m = [[complex(v) for v in r] for r in a]
perm = list(range(n))
sign = 1
for k in range(n):
p = max(range(k, n), key=lambda i: abs(m[i][k]))
if abs(m[p][k]) == 0.0:
raise ValueError("matrix is singular")
if p != k:
m[k], m[p] = m[p], m[k]
perm[k], perm[p] = perm[p], perm[k]
sign = -sign
for i in range(k + 1, n):
f = m[i][k] / m[k][k]
m[i][k] = f
if f != 0:
rk, ri = m[k], m[i]
for c in range(k + 1, n):
ri[c] -= f * rk[c]
return m, perm, sign
def _lu_solve(lu: list[list[complex]], perm: list[int], b: list[complex]) -> list[complex]:
n = len(lu)
y = [complex(b[perm[i]]) for i in range(n)]
for i in range(n):
for c in range(i):
y[i] -= lu[i][c] * y[c]
for i in range(n - 1, -1, -1):
for c in range(i + 1, n):
y[i] -= lu[i][c] * y[c]
y[i] /= lu[i][i]
return y
def solve(a: list[list[complex]], b: list) -> list:
"""Solve a x = b by Gaussian elimination with partial pivoting.
b is a vector, or a matrix whose columns are right-hand sides.
Raises ValueError if a is singular.
"""
lu, perm, _ = _lu(a)
if b and isinstance(b[0], list):
cols = [list(c) for c in zip(*b)]
xs = [_lu_solve(lu, perm, c) for c in cols]
return [list(r) for r in zip(*xs)]
if len(b) != len(a):
raise ValueError("lengths differ")
return _lu_solve(lu, perm, b)
def inv(a: list[list[complex]]) -> list[list[complex]]:
"""The inverse of a square matrix."""
return solve(a, eye(len(a)))
def det(a: list[list[complex]]) -> complex:
"""The determinant of a square matrix (0 for a singular matrix)."""
try:
lu, _, sign = _lu(a)
except ValueError as e:
if "singular" in str(e):
return 0j
raise
d = complex(sign)
for i in range(len(lu)):
d *= lu[i][i]
return d
def cholesky(a: list[list[complex]]) -> list[list[complex]]:
"""The lower triangular L with a = L L^H, for a Hermitian positive definite a.
Raises ValueError if a is not positive definite (to rounding).
"""
n = len(a)
low = zeros(n, n)
for i in range(n):
for k in range(i + 1):
s = complex(a[i][k]) - sum(low[i][c] * low[k][c].conjugate() for c in range(k))
if i == k:
if s.real <= 0.0:
raise ValueError("matrix is not positive definite")
low[i][i] = complex(math.sqrt(s.real))
else:
low[i][k] = s / low[k][k].real
return low
# ---------------------------------------------------------------- convolution and the DFT
def conv(a: list[complex], b: list[complex]) -> list[complex]:
"""Linear convolution, of length len(a) + len(b) - 1."""
if not a or not b:
return []
out = [0j] * (len(a) + len(b) - 1)
for i, x in enumerate(a):
for k, y in enumerate(b):
out[i + k] += x * y
return out
def cconv(a: list[complex], b: list[complex], n: int | None = None) -> list[complex]:
"""Circular convolution of length n (default: the longer length).
Both inputs are padded with zeros to length n, or must not be longer than n.
"""
if n is None:
n = max(len(a), len(b))
if len(a) > n or len(b) > n:
raise ValueError("input longer than n")
out = [0j] * n
for i, x in enumerate(a):
for k, y in enumerate(b):
out[(i + k) % n] += x * y
return out
def _twiddles(n: int, sign: int) -> list[complex]:
return [cmath.exp(sign * 2j * math.pi * t / n) for t in range(n)]
def dft(x: list[complex]) -> list[complex]:
"""X[k] = sum over n of x[n] e^(-j 2 pi k n / N), as a direct O(N^2) sum."""
n = len(x)
w = _twiddles(n, -1)
return [sum(x[t] * w[(k * t) % n] for t in range(n)) for k in range(n)]
def idft(xf: list[complex]) -> list[complex]:
"""x[n] = (1/N) sum over k of X[k] e^(j 2 pi k n / N), the inverse of dft."""
n = len(xf)
w = _twiddles(n, 1)
return [sum(xf[k] * w[(k * t) % n] for k in range(n)) / n for t in range(n)]
def udft(x: list[complex]) -> list[complex]:
"""The unitary DFT: dft(x) / sqrt(N)."""
s = 1.0 / math.sqrt(len(x)) if x else 1.0
return [v * s for v in dft(x)]
def uidft(xf: list[complex]) -> list[complex]:
"""The unitary inverse DFT: sqrt(N) idft(X), the inverse of udft."""
s = math.sqrt(len(xf)) if xf else 1.0
return [v * s for v in idft(xf)]
# ---------------------------------------------------------------- Q function and dB
def qfunc(x: float) -> float:
"""Q(x) = P(Z > x) for a standard normal Z, computed as 0.5 erfc(x / sqrt(2))."""
return 0.5 * math.erfc(x / math.sqrt(2.0))
def qinv(p: float) -> float:
"""The x with Q(x) = p, for 0 < p < 1, by bisection on Q (which decreases)."""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
lo, hi = -40.0, 40.0
for _ in range(200):
mid = 0.5 * (lo + hi)
if qfunc(mid) > p:
lo = mid
else:
hi = mid
if hi - lo <= 1e-15 * max(1.0, abs(mid)):
break
return 0.5 * (lo + hi)
def db(x: float) -> float:
"""10 log10(x), for a ratio of powers or energies."""
return 10.0 * math.log10(x)
def undb(d: float) -> float:
"""10^(d / 10), the inverse of db."""
return 10.0 ** (d / 10.0)
# ---------------------------------------------------------------- noise and statistics
def cn(rng: random.Random, var: float) -> complex:
"""One sample of CN(0, var): independent real and imaginary parts of variance var / 2."""
s = math.sqrt(var / 2.0)
return complex(rng.gauss(0.0, s), rng.gauss(0.0, s))
def awgn(rng: random.Random, x: list[complex], n0: float) -> list[complex]:
"""x plus independent CN(0, n0) noise on each sample."""
return [v + cn(rng, n0) for v in x]
def wilson(k: int, n: int, z: float = 3.29) -> tuple[float, float]:
"""The Wilson score interval for k successes in n trials (z = 3.29 is about 0.999 two-sided)."""
if n <= 0 or not 0 <= k <= n:
raise ValueError("need 0 <= k <= n and n > 0")
p = k / n
z2 = z * z
den = 1.0 + z2 / n
mid = (p + z2 / (2 * n)) / den
half = z * math.sqrt(p * (1 - p) / n + z2 / (4 * n * n)) / den
return max(0.0, mid - half), min(1.0, mid + half)
van_de_beek_estimator.py 59 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/van-de-beek-estimator/. The authors are listed in prov/9K7QSC.jsonl.
"""The van de Beek, Sandell and Borjesson estimator of symbol timing and
carrier frequency offset from the cyclic prefix of an OFDM signal.
The prefix of L samples repeats the last L samples of the symbol, N samples
later. A carrier offset epsilon (in subcarrier spacings) multiplies sample k
by e^(j 2 pi epsilon k / N), so r(k) conj(r(k + N)) has the angle
-2 pi epsilon on the prefix. For each candidate start theta:
gamma(theta) = sum for k = theta .. theta + L - 1 of r(k) conj(r(k + N))
Phi(theta) = (1/2) sum for k = theta .. theta + L - 1 of |r(k)|^2 + |r(k + N)|^2
Lambda(theta) = |gamma(theta)| - rho Phi(theta), rho = SNR / (SNR + 1)
theta_hat maximizes Lambda and epsilon_hat = -angle(gamma(theta_hat)) / (2 pi).
This is the maximum likelihood estimate when the OFDM samples are modeled as
complex Gaussian, in a channel with additive white Gaussian noise only.
gamma and Phi are running sums, so each new theta costs O(1).
"""
import cmath
import math
def statistics(r: list[complex], n: int, l: int) -> tuple[list[complex], list[float]]:
"""gamma(theta) and Phi(theta) for theta = 0, ..., len(r) - n - l."""
count = len(r) - n - l + 1
if count < 1:
raise ValueError("need at least N + L samples")
g = sum(r[k] * r[k + n].conjugate() for k in range(l))
p = 0.5 * sum(abs(r[k]) ** 2 + abs(r[k + n]) ** 2 for k in range(l))
gs, phis = [], []
for t in range(count): # @line L1
if t > 0:
a, b = t - 1, t - 1 + l
g += r[b] * r[b + n].conjugate() - r[a] * r[a + n].conjugate() # @line L2
p += 0.5 * (abs(r[b]) ** 2 + abs(r[b + n]) ** 2 - abs(r[a]) ** 2 - abs(r[a + n]) ** 2) # @line L3
gs.append(g)
phis.append(p)
return gs, phis
def estimate(r: list[complex], n: int, l: int, snr: float) -> tuple[int, float]:
"""(theta_hat, epsilon_hat) from the samples r, for N subcarriers and a prefix of L samples.
snr is the ratio of signal power to noise power per sample (not in dB).
theta_hat is the index in r of the first prefix sample; epsilon_hat is in [-1/2, 1/2).
"""
if snr <= 0:
raise ValueError("snr must be positive")
rho = snr / (snr + 1.0)
gs, phis = statistics(r, n, l)
lam = [abs(g) - rho * p for g, p in zip(gs, phis)] # @line L4
theta = max(range(len(lam)), key=lam.__getitem__) # @line L5
eps = -cmath.phase(gs[theta]) / (2 * math.pi) # @line L6
if eps >= 0.5:
eps -= 1.0
return theta, eps # @line L7
test_van_de_beek_estimator.py 102 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/van-de-beek-estimator/. The authors are listed in prov/9K7QSC.jsonl.
import cmath
import math
import random
import cbb
from van_de_beek_estimator import estimate, statistics
def symbol(rng: random.Random, n: int, l: int, ofdm: bool = False) -> list[complex]:
"""One OFDM symbol with a prefix of l samples.
With CN(0, 1) subcarrier values and the unitary inverse DFT, the N time
samples are again independent CN(0, 1), so the default draws them directly.
ofdm=True builds the symbol from 4-QAM subcarrier values instead.
"""
if ofdm:
s = 1 / math.sqrt(2)
x = cbb.uidft([complex(rng.choice((s, -s)), rng.choice((s, -s))) for _ in range(n)])
else:
x = [cbb.cn(rng, 1.0) for _ in range(n)]
return x[n - l:] + x
def apply_cfo(r: list[complex], eps: float, n: int) -> list[complex]:
return [x * cmath.exp(2j * math.pi * eps * i / n) for i, x in enumerate(r)]
def wrap(d: int, period: int) -> int:
"""d modulo period, in [-period / 2, period / 2)."""
return (d + period // 2) % period - period // 2
def test_running_sums_match_the_direct_sums() -> None:
rng = random.Random(1)
n, l = 32, 8
r = [cbb.cn(rng, 1.0) for _ in range(120)]
gs, phis = statistics(r, n, l)
assert len(gs) == 120 - n - l + 1
for t in (0, 5, 33, 80):
g = sum(r[k] * r[k + n].conjugate() for k in range(t, t + l))
p = 0.5 * sum(abs(r[k]) ** 2 + abs(r[k + n]) ** 2 for k in range(t, t + l))
assert abs(gs[t] - g) < 1e-9
assert abs(phis[t] - p) < 1e-9
def test_exact_without_noise() -> None:
# No noise: Lambda(theta) = |gamma| - Phi is 0 at the prefix start and negative elsewhere.
rng = random.Random(2)
n, l = 64, 16
for eps in (0.0, 0.12, -0.31, 0.45, -0.5):
for off in (0, 17, 63, 79):
s = symbol(rng, n, l, True) + symbol(rng, n, l, True) + symbol(rng, n, l, True)
r = apply_cfo(s, eps, n)[off:off + 2 * (n + l)]
theta, e = estimate(r, n, l, 1e9)
assert wrap(theta - (n + l - off), n + l) == 0
assert abs(e - eps) < 1e-9
def test_offset_range_is_half_a_spacing() -> None:
# epsilon and epsilon - 1 give the same gamma, so 0.6 is read as -0.4.
rng = random.Random(3)
n, l = 64, 16
s = symbol(rng, n, l) + symbol(rng, n, l)
_, e = estimate(apply_cfo(s, 0.6, n), n, l, 1e9)
assert abs(e + 0.4) < 1e-9
def test_timing_at_10_db() -> None:
# N = 64, L = 16, SNR = 10 dB per sample, epsilon = 0.2, 150 windows of 2(N + L) samples, seed 4.
# Measurement: about 95 percent of the estimates are within 2 samples of the prefix start.
rng = random.Random(4)
n, l, n0, eps = 64, 16, 0.1, 0.2
near = 0
trials = 150
for _ in range(trials):
s = symbol(rng, n, l) + symbol(rng, n, l) + symbol(rng, n, l)
off = rng.randrange(n + l)
r = cbb.awgn(rng, apply_cfo(s, eps, n), n0)[off:off + 2 * (n + l)]
theta, _ = estimate(r, n, l, 1 / n0)
near += abs(wrap(theta - (n + l - off), n + l)) <= 2
assert near >= 0.9 * trials
def test_variance_at_the_true_start() -> None:
# For a fixed symbol with prefix energy E, var(epsilon_hat) is about
# (N0 / E) (1 + L N0 / (2 E)) / (4 pi^2). E = L gives (1 / (4 pi^2 L SNR)) (1 + 1 / (2 SNR)).
rng = random.Random(5)
n, l, n0, eps = 64, 16, 0.1, 0.2
x = apply_cfo(symbol(rng, n, l), eps, n)
e = sum(abs(v) ** 2 for v in x[:l])
expect = n0 / e * (1 + l * n0 / (2 * e)) / (4 * math.pi ** 2)
acc = 0.0
trials = 2000
for _ in range(trials):
r = cbb.awgn(rng, x, n0)
gs, _ = statistics(r, n, l)
acc += (-cmath.phase(gs[0]) / (2 * math.pi) - eps) ** 2
assert 0.85 < acc / trials / expect < 1.15
assert abs((1 + 1 / 20) / (4 * math.pi ** 2 * 16 * 10) - 1.6623e-4) < 1e-8
History
Jan-Jaap van de Beek, Magnus Sandell and Per Ola Börjesson, at Luleå University of Technology, published the joint maximum likelihood estimator in IEEE Transactions on Signal Processing in 1997. The same year, Schmidl and Cox published their method with a training symbol. The prefix estimator became the standard blind synchronizer for continuous OFDM systems, and its correlation of the prefix with the symbol end is used in broadcasting receivers and in many later estimators that add pilots or average over symbols.
References
- J.-J. van de Beek, M. Sandell and P. O. Börjesson, ML estimation of time and frequency offset in OFDM systems, IEEE Transactions on Signal Processing 45(7), 1997, pages 1800 to 1805 (the Gaussian model, the log-likelihood function with the correlation gamma and the energy term Phi, and the joint estimate of timing and offset)
- T. M. Schmidl and D. C. Cox, Robust frequency and timing synchronization for OFDM, IEEE Transactions on Communications 45(12), 1997, pages 1613 to 1621 (the training-symbol alternative, with a wider range of offsets)
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 9K7QSC Edit this page History Report an error Markdown