Algorithm Search⌘K

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
Properties
blinddeterministicmaximum likelihoodtiming and frequency
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 NcpN_{cp} samples of each symbol are a copy of its last NcpN_{cp} samples, NN samples later. The estimator slides a window of NcpN_{cp} samples along the input and, for each candidate start θ\theta, correlates the window with the samples NN positions later, γ(θ)=∑kr(k) r∗(k+N)\gamma(\theta) = \sum_k r(k)\, r^*(k + N). It also computes the energy Φ(θ)\Phi(\theta) of the same samples. The timing estimate maximizes ∣γ(θ)∣−ρ Φ(θ)|\gamma(\theta)| - \rho\, \Phi(\theta), with ρ=SNR/(SNR+1)\rho = \text{SNR}/(\text{SNR} + 1), and the offset estimate is −∠γ(θ^)/(2π)-\angle\gamma(\hat\theta) / (2\pi) 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 jj for the imaginary unit and ε=Δf N/fs\varepsilon = \Delta f\, N / f_s 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 r(0),…,r(M−1)r(0), \ldots, r(M - 1) with M≥2N+NcpM \ge 2N + N_{cp}, the DFT size NN, the prefix length NcpN_{cp} and the SNR per sample. The model is r(k)=s(k) ej2πεk/N+n(k)r(k) = s(k)\, e^{j 2\pi\varepsilon k / N} + n(k), where ss is a stream of OFDM symbols with prefixes, ε\varepsilon is the unknown offset with ∣ε∣<1/2|\varepsilon| < 1/2, and n(k)n(k) is white noise CN(0,N0)\mathcal{CN}(0, N_0). Find the index θ^\hat\theta of the first sample of a prefix inside the window, and an estimate ε^\hat\varepsilon of ε\varepsilon.

The algorithm

  1. VAN-DE-BEEK(r, N, N_cp, SNR)
  2. 1for θ ← 0, 1, .., M - N - N_cp do ▷ γ(0), Φ(0) are direct sums over k = 0, .., N_cp-1
  3. 2γ(θ) ← γ(θ-1) + r[θ-1+N_cp] conj(r[θ-1+N_cp+N]) - r[θ-1] conj(r[θ-1+N])
  4. 3Φ(θ) ← Φ(θ-1) + ½(|r[θ-1+N_cp]|² + |r[θ-1+N_cp+N]|² - |r[θ-1]|² - |r[θ-1+N]|²)
  5. 4Λ(θ) ← |γ(θ)| - ρ Φ(θ) for every θ, with ρ = SNR / (SNR + 1)
  6. 5θ̂ ← argmax_θ Λ(θ)
  7. 6ε̂ ← -angle(γ(θ̂)) / (2π) ▷ wrapped to [-1/2, 1/2)
  8. 7return θ̂, ε̂

Lines L1 to L3 slide the window of NcpN_{cp} pairs: each step adds the newest pair and drops the oldest, so each candidate costs O(1)O(1). On the prefix, the pair r(k)r(k), r(k+N)r(k + N) holds the same sent sample, and the offset turns the second one by ej2πεe^{j 2\pi\varepsilon}, so r(k) r∗(k+N)=e−j2πε∣s(k)∣2r(k)\, r^*(k + N) = e^{-j 2\pi\varepsilon} |s(k)|^2 apart from noise. Line L4 compares the size of the correlation with the energy. Without noise, ∣γ∣≤Φ|\gamma| \le \Phi everywhere, with equality at a prefix start. With noise, the factor ρ\rho 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 N=8N = 8, Ncp=2N_{cp} = 2, a stream of three symbols whose time samples are independent CN(0,1)\mathcal{CN}(0, 1) (seed 3), ε=0.1\varepsilon = 0.1, 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 θ=7\theta = 7 in the window. There are 11 candidates.

θ\theta 0 1 2 3 4 5 6 7 8 9 10
∣γ(θ)∣\lvert\gamma(\theta)\rvert 1.382 1.197 1.678 0.684 0.725 0.363 2.182 4.650 3.309 2.064 1.364
Φ(θ)\Phi(\theta) 2.779 2.631 1.751 0.931 1.104 0.741 2.512 4.650 3.796 2.372 1.956
Λ(θ)\Lambda(\theta), ρ=1\rho = 1 -1.397 -1.434 -0.073 -0.248 -0.380 -0.378 -0.330 0 -0.487 -0.308 -0.592
−∠γ/2π-\angle\gamma / 2\pi 0.407 -0.390 -0.397 -0.162 -0.168 0.391 0.123 0.1 0.065 -0.051 -0.096

Every Λ\Lambda is negative except at θ=7\theta = 7, where ∣γ∣=Φ=4.650|\gamma| = \Phi = 4.650 and γ=3.762−2.733j\gamma = 3.762 - 2.733j, with the angle −2π⋅0.1-2\pi \cdot 0.1. Line L5 returns θ^=7\hat\theta = 7 and line L6 returns ε^=0.1\hat\varepsilon = 0.1. With the SNR set to 10 dB, so ρ=0.909\rho = 0.909, the result is the same. At wrong starts the angle is random, which is why line L6 must use the angle at θ^\hat\theta only.

At 10 dB per sample with N=64N = 64, Ncp=16N_{cp} = 16 and ε=0.2\varepsilon = 0.2, 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 (θ,ε)(\theta, \varepsilon) is a constant plus a positive multiple of Re⁡(ej2πεγ(θ))−ρ Φ(θ)\operatorname{Re}(e^{j 2\pi\varepsilon} \gamma(\theta)) - \rho\, \Phi(\theta), so lines L4 to L6 give the joint maximum likelihood estimate. (b) Without noise, Λ(θ)≤0\Lambda(\theta) \le 0 for every θ\theta, with equality at a prefix start, where the angle of γ\gamma is −2πε-2\pi\varepsilon; so the algorithm is exact for ∣ε∣<1/2|\varepsilon| < 1/2 unless a wrong start ties. Both are theorems in the model above.

Key invariant. On a prefix, r(k+N)=ej2πεr(k)r(k + N) = e^{j 2\pi\varepsilon} r(k) without noise. The Gaussian model makes every other pair of samples uncorrelated, so the likelihood depends on (θ,ε)(\theta, \varepsilon) only through the NcpN_{cp} prefix pairs, and these enter through γ\gamma and Φ\Phi alone.

Part (b) is the triangle inequality with ∣a∣∣b∣≤12(∣a∣2+∣b∣2)|a||b| \le \frac12 (|a|^2 + |b|^2). At a high SNR, the variance of ε^\hat\varepsilon at the true start is close to 14π2Ncp SNR(1+12 SNR)\frac{1}{4\pi^2 N_{cp}\, \text{SNR}} (1 + \frac{1}{2\,\text{SNR}}), 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. NN is the DFT size, NcpN_{cp} the prefix length, and jj the imaginary unit. The receiver observes a window r(0),…,r(M−1)r(0), \ldots, r(M - 1) with M≥2N+NcpM \ge 2N + N_{cp}, and a prefix starts at the unknown index θ\theta, so for k∈I={θ,…,θ+Ncp−1}k \in I = \{\theta, \ldots, \theta + N_{cp} - 1\} the sent sample s(k+N)s(k + N) equals s(k)s(k). The channel adds white noise only, and the carrier offset is ε\varepsilon subcarrier spacings:

r(k)=s(k) ej2πεk/N+n(k).r(k) = s(k)\, e^{j 2\pi \varepsilon k / N} + n(k).

Lines L1 to L3 compute, for each candidate θ\theta,

γ(θ)=∑k=θθ+Ncp−1r(k) r∗(k+N),Φ(θ)=12∑k=θθ+Ncp−1(∣r(k)∣2+∣r(k+N)∣2).\gamma(\theta) = \sum_{k = \theta}^{\theta + N_{cp} - 1} r(k)\, r^*(k + N), \qquad \Phi(\theta) = \frac12 \sum_{k = \theta}^{\theta + N_{cp} - 1} \left( |r(k)|^2 + |r(k + N)|^2 \right).

Lemma 1 (running sums). If γ(0)\gamma(0) and Φ(0)\Phi(0) are the direct sums, the updates of lines L2 and L3 give the sums above for every θ≥1\theta \ge 1.

Proof. Going from θ−1\theta - 1 to θ\theta, the sum loses the term k=θ−1k = \theta - 1 and gains the term k=θ−1+Ncpk = \theta - 1 + N_{cp}. Line L2 adds r(b) r∗(b+N)r(b)\, r^*(b + N) with b=θ−1+Ncpb = \theta - 1 + N_{cp} and subtracts r(a) r∗(a+N)r(a)\, r^*(a + N) with a=θ−1a = \theta - 1; line L3 does the same for the energies. □\square

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 σs2\sigma_s^2, apart from the prefix copies, and the noise as independent CN(0,σn2)\mathcal{CN}(0, \sigma_n^2). Let σ2=σs2+σn2\sigma^2 = \sigma_s^2 + \sigma_n^2 and ρ=σs2/σ2=SNR/(SNR+1)\rho = \sigma_s^2 / \sigma^2 = \text{SNR} / (\text{SNR} + 1). For a random OFDM symbol with many subcarriers, the time samples are close to Gaussian; for CN(0,1)\mathcal{CN}(0, 1) subcarrier values and the unitary inverse DFT they are exactly independent CN(0,1)\mathcal{CN}(0, 1).

Lemma 2 (the pairs). For k∈Ik \in I, the pair a=r(k)a = r(k), b=r(k+N)b = r(k + N) has E∣a∣2=E∣b∣2=σ2E|a|^2 = E|b|^2 = \sigma^2 and E[ab∗]=σ2ρ e−j2πεE[a b^*] = \sigma^2 \rho\, e^{-j 2\pi \varepsilon}. Every other pair of samples in the window is uncorrelated.

Proof. E[ab∗]=E[s(k)s∗(k+N)] ej2πεk/Ne−j2πε(k+N)/N=σs2e−j2πεE[a b^*] = E[s(k) s^*(k + N)]\, e^{j 2\pi \varepsilon k / N} e^{-j 2\pi \varepsilon (k + N) / N} = \sigma_s^2 e^{-j 2\pi\varepsilon}, because s(k+N)=s(k)s(k + N) = s(k) 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. □\square

Theorem 1 (the log-likelihood). Under the model, the log-likelihood of (θ,ε)(\theta, \varepsilon) is

log⁡f(r∣θ,ε)=C+2ρσ2(1−ρ2)[Re⁡(ej2πεγ(θ))−ρ Φ(θ)],\log f(r \mid \theta, \varepsilon) = C + \frac{2\rho}{\sigma^2 (1 - \rho^2)} \left[ \operatorname{Re}\left( e^{j 2\pi\varepsilon} \gamma(\theta) \right) - \rho\, \Phi(\theta) \right],

with CC independent of θ\theta and ε\varepsilon. Its maximum over ε\varepsilon is at ε=−∠γ(θ)/(2π)\varepsilon = -\angle\gamma(\theta) / (2\pi) modulo 1, where the bracket equals Λ(θ)=∣γ(θ)∣−ρ Φ(θ)\Lambda(\theta) = |\gamma(\theta)| - \rho\, \Phi(\theta). So lines L4 to L6 return the joint maximum likelihood estimate.

Proof. By Lemma 2, the window splits into the NcpN_{cp} correlated pairs and independent single samples, so

f(r∣θ,ε)=∏kf(r(k))∏k∈If(r(k),r(k+N))f(r(k)) f(r(k+N)),f(r \mid \theta, \varepsilon) = \prod_{k} f(r(k)) \prod_{k \in I} \frac{f(r(k), r(k + N))}{f(r(k))\, f(r(k + N))},

and the first product does not depend on (θ,ε)(\theta, \varepsilon), because every sample has the same marginal CN(0,σ2)\mathcal{CN}(0, \sigma^2). For one pair, the covariance matrix is σ2(1cc∗1)\sigma^2 \begin{pmatrix} 1 & c \\ c^* & 1 \end{pmatrix} with c=ρe−j2πεc = \rho e^{-j 2\pi\varepsilon}, its inverse is 1σ2(1−ρ2)(1−c−c∗1)\frac{1}{\sigma^2 (1 - \rho^2)} \begin{pmatrix} 1 & -c \\ -c^* & 1 \end{pmatrix}, and the quadratic form is ∣a∣2+∣b∣2−2Re⁡(c a∗b)σ2(1−ρ2)\frac{|a|^2 + |b|^2 - 2 \operatorname{Re}(c\, a^* b)}{\sigma^2 (1 - \rho^2)}. With Re⁡(c a∗b)=ρRe⁡(ej2πεab∗)\operatorname{Re}(c\, a^* b) = \rho \operatorname{Re}(e^{j 2\pi\varepsilon} a b^*), the log of the ratio is

−log⁡(1−ρ2)+2ρRe⁡(ej2πεab∗)−ρ2(∣a∣2+∣b∣2)σ2(1−ρ2),-\log(1 - \rho^2) + \frac{2\rho \operatorname{Re}\left(e^{j 2\pi\varepsilon} a b^*\right) - \rho^2 \left(|a|^2 + |b|^2\right)}{\sigma^2 (1 - \rho^2)},

because −∣a∣2+∣b∣2σ2(1−ρ2)+∣a∣2+∣b∣2σ2=−ρ2(∣a∣2+∣b∣2)σ2(1−ρ2)-\frac{|a|^2 + |b|^2}{\sigma^2 (1 - \rho^2)} + \frac{|a|^2 + |b|^2}{\sigma^2} = -\frac{\rho^2 (|a|^2 + |b|^2)}{\sigma^2 (1 - \rho^2)}. Summing over k∈Ik \in I gives the stated form with ∑ab∗=γ(θ)\sum a b^* = \gamma(\theta) and ∑(∣a∣2+∣b∣2)=2Φ(θ)\sum (|a|^2 + |b|^2) = 2\Phi(\theta). Finally Re⁡(ej2πεγ)=∣γ∣cos⁡(2πε+∠γ)\operatorname{Re}(e^{j 2\pi\varepsilon} \gamma) = |\gamma| \cos(2\pi\varepsilon + \angle\gamma), which is largest, and equal to ∣γ∣|\gamma|, when 2πε=−∠γ2\pi\varepsilon = -\angle\gamma modulo 2π2\pi. The factor in front of the bracket is positive, so maximizing the bracket over θ\theta after the maximization over ε\varepsilon is maximizing Λ\Lambda. □\square

Theorem 2 (exact without noise). Without noise, take ρ=1\rho = 1. Let the window contain a full prefix start θ0\theta_0, so θ0+Ncp−1+N≤M−1\theta_0 + N_{cp} - 1 + N \le M - 1. Then Λ(θ)≤0\Lambda(\theta) \le 0 for every θ\theta, Λ(θ0)=0\Lambda(\theta_0) = 0, and −∠γ(θ0)/(2π)=ε-\angle\gamma(\theta_0) / (2\pi) = \varepsilon modulo 1. If ∣ε∣<1/2|\varepsilon| < 1/2, the wrap after line L6 returns ε\varepsilon exactly. If no other θ\theta ties, line L5 returns θ0\theta_0.

Proof. For any θ\theta, the triangle inequality and xy≤12(x2+y2)xy \le \frac12 (x^2 + y^2) give

∣γ(θ)∣≤∑k∣r(k)∣ ∣r(k+N)∣≤12∑k(∣r(k)∣2+∣r(k+N)∣2)=Φ(θ),|\gamma(\theta)| \le \sum_k |r(k)|\, |r(k + N)| \le \frac12 \sum_k \left( |r(k)|^2 + |r(k + N)|^2 \right) = \Phi(\theta),

so Λ(θ)≤0\Lambda(\theta) \le 0. At θ0\theta_0, r(k+N)=ej2πεr(k)r(k + N) = e^{j 2\pi\varepsilon} r(k) for k∈Ik \in I, so γ(θ0)=e−j2πε∑k∣r(k)∣2\gamma(\theta_0) = e^{-j 2\pi\varepsilon} \sum_k |r(k)|^2 and Φ(θ0)=∑k∣r(k)∣2\Phi(\theta_0) = \sum_k |r(k)|^2. Both inequalities are equalities, Λ(θ0)=0\Lambda(\theta_0) = 0, and the angle of γ(θ0)\gamma(\theta_0) is −2πε-2\pi\varepsilon modulo 2π2\pi. □\square

A tie needs ∣r(k)∣=∣r(k+N)∣|r(k)| = |r(k + N)| for all NcpN_{cp} pairs at some other θ\theta, 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 E=∑k∈I∣s(k)∣2E = \sum_{k \in I} |s(k)|^2 be the energy of the prefix, and take θ=θ0\theta = \theta_0 with noise CN(0,N0)\mathcal{CN}(0, N_0). Then

ej2πεγ(θ0)=E+Z,Z=∑ks(k) n′∗(k)+∑kn(k) s∗(k)+∑kn(k) n′∗(k),e^{j 2\pi\varepsilon} \gamma(\theta_0) = E + Z, \qquad Z = \sum_k s(k)\, n'^*(k) + \sum_k n(k)\, s^*(k) + \sum_k n(k)\, n'^*(k),

where n′n' is the rotated noise of the second sample, again CN(0,N0)\mathcal{CN}(0, N_0). The three sums are uncorrelated with zero mean and have variances EN0E N_0, EN0E N_0 and NcpN02N_{cp} N_0^2. For a small ZZ, the angle error is Im⁡(Z)/E\operatorname{Im}(Z) / E, and Im⁡(Z)\operatorname{Im}(Z) has half the variance of ZZ, so

var⁡(ε^)≈14π2⋅2EN0+NcpN022E2=14π2⋅N0E(1+NcpN02E).\operatorname{var}(\hat\varepsilon) \approx \frac{1}{4\pi^2} \cdot \frac{2 E N_0 + N_{cp} N_0^2}{2 E^2} = \frac{1}{4\pi^2} \cdot \frac{N_0}{E} \left( 1 + \frac{N_{cp} N_0}{2E} \right).

With the mean energy E=NcpEsE = N_{cp} E_s and SNR=Es/N0\text{SNR} = E_s / N_0 this is 14π2Ncp SNR(1+12 SNR)\frac{1}{4\pi^2 N_{cp}\, \text{SNR}} \left( 1 + \frac{1}{2\,\text{SNR}} \right), which is 1.6623×10−41.6623 \times 10^{-4} for Ncp=16N_{cp} = 16 at 10 dB. The tests measure the variance for a fixed symbol within 15 percent of the first form. The estimate uses only the NcpN_{cp} prefix pairs, so its variance is N/NcpN / N_{cp} times larger than that of an estimator that correlates two repeated symbols of NN samples.

Complexity

The direct sums for θ=0\theta = 0 cost O(Ncp)O(N_{cp}), and each of the T=M−N−Ncp+1T = M - N - N_{cp} + 1 candidates costs O(1)O(1) in lines L2 to L4, so the time is O(Ncp+T)O(N_{cp} + T) in the real RAM. The implementation stores γ\gamma and Φ\Phi for all candidates, O(T)O(T) extra space. A streaming receiver keeps only the running sums, a delay line of N+NcpN + N_{cp} samples and the best value so far, so it needs O(N)O(N) 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 ∣ε∣<1/2|\varepsilon| < 1/2. An offset of 0.60.6 is read as −0.4-0.4, as the tests check. The integer part needs another method.
  • Variance. Close to 14π2Ncp SNR(1+12 SNR)\frac{1}{4\pi^2 N_{cp}\,\text{SNR}} (1 + \frac{1}{2\,\text{SNR}}) at a high SNR: 1.66×10−41.66 \times 10^{-4} for Ncp=16N_{cp} = 16 at 10 dB. It uses NcpN_{cp} pairs instead of NN, so the variance is N/NcpN / N_{cp} 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 NN, so the estimator works well for real signals, but in a dispersive channel the first L−1L - 1 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 Λ\Lambda and γ\gamma over several symbols, at the same position in each, cuts the variance roughly by the number of symbols.
  • Without the SNR. Setting ρ=1\rho = 1 in line L4 gives ∣γ∣−Φ|\gamma| - \Phi, 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 ∣γ(θ)∣|\gamma(\theta)| 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 Ncp−L+1N_{cp} - L + 1 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 r(k) r∗(k+N)r(k)\, r^*(k + N) has the angle −2πε-2\pi\varepsilon, so line L6 must negate the angle. With the product r∗(k) r(k+N)r^*(k)\, r(k + N) in line L2, the sign in line L6 must change too.
  • Reading the angle at another start. Line L6 must take the angle of γ\gamma at θ^\hat\theta 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 NN apart, the DFT size, not N+NcpN + N_{cp}, 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 2N+Ncp2N + N_{cp} samples to contain a full prefix pair for any position of the stream.
  • Dropping the energy term. Line L4 must subtract ρ Φ(θ)\rho\, \Phi(\theta). The maximum of ∣γ∣|\gamma| 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 Λ=0\Lambda = 0 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.

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

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

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
  • at least three sources
  • a scene preset for the example