Algorithmcore
Schmidl-Cox synchronization
Also called Schmidl-Cox algorithm.
Finds the start of an OFDM frame and its carrier frequency offset from a training symbol with two equal halves, and the even integer part of the offset from a second training symbol.
- Time
- O(D + N log N + G N) worst
- Space
- O(N) extra
- Where
- D = the number of candidate start positions; G = the number of integer offsets tried; N = the number of subcarriers
- Model
- Real RAM
- Properties
- data aideddeterministictiming and frequency
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Timothy M. Schmidl, Donald C. Cox, 1997
Schmidl-Cox synchronization finds where an OFDM burst starts and how far the receiver's carrier frequency is from the transmitter's, before the receiver can take any DFT. It needs a training symbol whose time samples are two equal halves, made by putting data only on the even subcarriers. The receiver correlates each half-length window of the input with the next one, , and normalizes it to with the energy of the second half. rises to a plateau when the window lies on the training symbol, which gives the timing. On the plateau the angle of is , which gives the offset modulo 2, in units of the subcarrier spacing. A second training symbol, with a known pattern relative to the first, removes the remaining ambiguity . It is a data-aided method for the problems of frame synchronization and frequency offset estimation in OFDM. The Moose estimator uses two whole repeated symbols and assumes the timing is known; the van de Beek estimator uses the cyclic prefix and needs no training symbol. The page uses for the imaginary unit, the unitary DFT pair of the OFDM page, and .
In plain words
A receiver that wakes up does not know where a burst begins, and its oscillator is slightly off, so every sample turns a little more than it should. The sender starts the burst with a block that repeats itself: the second half is a copy of the first half. The receiver slides a window along the signal and compares each half with the next half. When the window sits on the special block, the two halves match very well, apart from a fixed turn. The good match tells the receiver where the block is. The size of the turn between the halves tells it how far off its oscillator is. A turn can only be measured up to a full circle, so a second known block settles the rest.
The problem
The input is a stream of complex baseband samples , where holds a burst that starts with two training symbols, each with a cyclic prefix of samples, is a channel with taps, is the unknown offset in subcarrier spacings and . The SNR is the mean energy per sample divided by . The first training symbol is zero on the odd subcarriers; the second, , is known through the ratio on the even subcarriers. Find a DFT start inside the part of the first symbol that is free of interference from earlier samples, and an estimate of , with .
The algorithm
SCHMIDL-COX(r, N, N_cp, v, g_max)- 1
for d ← 0, 1, .. do ▷ P(0) and R(0) are direct sums over m = 0, .., N/2-1 - 2
P(d) ← P(d-1) + conj(r[d-1+N/2]) r[d-1+N] - conj(r[d-1]) r[d-1+N/2] - 3
R(d) ← R(d-1) + |r[d-1+N]|² - |r[d-1+N/2]|² - 4
M(d) ← |P(d)|² / R(d)² - 5
d̂ ← argmax_d M(d) ▷ or the middle of the starts with M ≥ 0.9 max M - 6
ε_f ← angle(P(d̂)) / π ▷ fractional part, in (-1, 1] - 7
z[i] ← r[i] e^(-j2π ε_f i / N) for all i ▷ remove the fractional part - 8
Y1 ← F z[d̂ .. d̂+N-1]; Y2 ← F z[d̂+N+N_cp .. d̂+2N+N_cp-1] - 9
ĝ ← argmax over |g| ≤ g_max of |Σ_{k even} conj(Y1[k+2g] v[k]) Y2[k+2g]|² / (2 (Σ_{k even} |Y2[k]|²)²) - 10
return d̂, ε_f + 2ĝ
Lines L1 to L4 slide the window. Each step adds the newest product and drops the oldest one, so and cost per start instead of . Line L4 normalizes by the energy, so the metric does not depend on the received power. Line L5 picks the timing. The paper of Schmidl and Cox averages the starts whose metric is within 90 percent of the maximum, because has a flat top over the excess prefix and its largest value is often at the edge; the implementation offers both rules. Line L6 reads the phase advance over half a symbol, , so the result is modulo 2. Line L7 removes this part. The rest of the offset is an even integer , which shifts the subcarriers by positions without leakage. Line L8 takes the DFT of both training symbols at the same position in each symbol. Line L9 tries each shift: at the true shift, the products of line L9 all have the same phase and add up coherently, because . Line L10 combines the two parts.
Example
Take , , a channel , six zero samples before the burst, , random QPSK training symbols (seed 11) and no noise. The first symbol occupies samples 6 to 25, its body starts at sample 10, and the starts free of interference are , that is starts.
| 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | |
|---|---|---|---|---|---|---|---|---|---|
| (line L4) | 0.645 | 0.972 | 0.980 | 1 | 1 | 1 | 1 | 0.975 | 0.829 |
| 0.328 | 0.323 | 0.323 | 0.3 | 0.3 | 0.3 | 0.3 | 0.296 | 0.306 |
Line L5 with the largest value finds , the first start of the plateau; the 90 percent rule takes the starts 5 to 11 and returns their middle, . Line L6 gives , which is modulo 2. After line L7 the remaining offset is , so . Line L9 gives these values of the normalized metric for : , , , , , , . The maximum is at , and line L10 returns .
At dB per sample with , and in white noise, the tests measure the following over 100 frames: the 90 percent rule puts the start inside the 9 starts free of interference in at least 90 frames, near the middle on average, and all 100 offset estimates are within of .
Correctness
Claim. Without noise and with : (a) and modulo for each of the starts whose two half windows lie in the part of the first symbol that is free of interference; (b) for such a , line L9 attains its largest possible value at the true . So the algorithm returns exactly when is on the plateau, and line L9 has no tie. This is a theorem in the model above.
Key invariant. On the plateau, the received samples are periodic with period apart from the offset factor: . This holds because the training symbol has period and the cyclic prefix keeps the channel output circular.
Part (b) follows from the Cauchy-Schwarz inequality: at the true shift, all products have the same phase. With noise, the fractional estimate has the variance at a high SNR, a closed form for a linearized phase error; the tests check it within 15 percent. The full proof is below.
Proof: The Schmidl-Cox metric is 1 on the ISI-free starts, its angle gives the fractional offset, and the second symbol gives the even integer partfull
Notation. is even, and the half length is . The unitary DFT pair is the one of the OFDM page, with , and is the imaginary unit. The channel has taps, the prefix has samples, and the carrier frequency offset is subcarrier spacings, so the receiver sees
with the sent samples and independent . The first training symbol is zero on the odd subcarriers, and the second, , is nonzero on the even ones; for even . Lines L1 to L4 compute
Lemma 1 (two equal halves). If for every odd , then for .
Proof. , and for every even , while the odd terms are zero.
Lemma 2 (the recursion). Lines L2 and L3 give the sums above for every if they start from the direct sums at .
Proof. Going from to , the sum for loses the term of , which is , and gains the term of , which is . The same holds for with and .
Lemma 3 (the plateau). Without noise, let the first training symbol start (with its prefix) at sample , so its body starts at . For every with , , so and modulo , if . There are such .
Proof. Let . For , the sample only uses sent samples of the first training symbol, and as in Lemma 1 of the OFDM page it equals the circular convolution of and at index modulo . A circular convolution with a sequence of period (Lemma 1) has period , so whenever both and are in this range. For in the stated range and , the indices and are both in it. Then , because the offset factor advances by . Substituting gives , and the same relation gives . The count is .
Remark (M can pass 1 elsewhere). By the Cauchy-Schwarz inequality, with , the energy of the first half. So , which is 1 on the plateau but can be larger than 1 next to it, where the two halves have different energies. The global maximum of is then not on the plateau. This is why the implementation offers the middle of the 90 percent plateau as the timing estimate.
Lemma 4 (the fractional part). If is on the plateau, line L6 returns , and for an integer .
Proof. By Lemma 3, for the integer that puts the angle in . Divide by .
Lemma 5 (the even integer part). After line L7 removes , the remaining offset is the even integer . Let and be the DFTs of line L8 taken at plateau starts, without noise. Define
with indices modulo , where the training symbols satisfy on the even subcarriers and . Then for every , and for the true .
Proof. An integer offset multiplies sample of each window by times a constant phase, so it shifts the DFT: , where is the channel gain with the phase ramp of the window start, the same for both symbols because both windows start at the same position in their symbols, and , are constants. Hence for the true ,
because . All terms have the same phase, so the numerator is , and the denominator is , because the even subcarriers are closed under a shift by and . So . For any , the Cauchy-Schwarz inequality bounds the numerator by . Here , and on the even (both are times or at the same position), so each factor equals after the shift. So .
Equality at a wrong needs to be proportional to on all even , which a random code avoids with high probability. Line L9 searches , so the true must be in that range.
Theorem (noise-free correctness). Without noise, with , a timing estimate on the plateau, and no tie in line L9, line L10 returns and exactly.
Proof. Lemmas 3 to 5.
Variance of the fractional estimate (a closed form at high SNR). At a plateau start, let be the noise-free samples of the first half, , and write the noise of the two halves as and , all independent . Then
The three noise sums are uncorrelated with zero mean. The first two have variance each and the third . For a small , , and has half the variance of , so
With the mean sample energy and per sample, , and
For at 10 dB this is , and the tests measure it within 15 percent. At a high SNR the leading term dominates; the factor comes from the noise-times-noise term.
Complexity
Lines L1 to L4 cost per start after an start-up, so candidate starts cost . Line L5 is a scan, . Line L7 rotates samples, line L8 is two FFTs, , and line L9 costs per candidate , so for candidates. The total is time in the real RAM. A receiver that runs lines L1 to L4 on a stream keeps samples in a delay line, so the extra space is .
Properties
- Range. The fractional estimate covers , twice the range of an estimator that compares two full symbols, because the halves are only samples apart. The integer search extends the range to .
- Robust to the channel. The halves pass through the same channel, so and the angle of do not depend on on the plateau. Only the plateau gets shorter, by starts.
- Variance. Near at a high SNR: for at 10 dB, a standard deviation of subcarrier spacings. This is 8 times the variance of the Moose estimator with two full symbols of samples, which correlates twice as many samples (a factor 2) spaced twice as far apart (a factor 4). The price of the Moose estimator is its range, .
- Timing is coarse. The plateau makes the timing estimate uncertain by a few samples, which is acceptable because any start on the plateau works and the residual delay becomes a phase ramp that the channel estimate absorbs.
- Blind to the data. The training symbol is known only through its structure for lines L1 to L6; the known values are used only in line L9.
Variants and improvements
- Normalize by both halves. Using keeps everywhere, by the Cauchy-Schwarz inequality and the inequality of the arithmetic and geometric means, so the maximum is on the plateau.
- Sharper timing. Training symbols with more than two parts, some of them negated, give a metric with a sharp peak instead of a plateau, at the cost of a smaller range.
- Fine timing after the coarse step. A cross-correlation with the known training symbol, as in preamble correlation detection, or the channel estimate itself, refines the start.
- Integer offset from a pilot pattern. Instead of a second training symbol, the receiver can correlate the DFT output with a known pilot pattern over the candidate shifts.
- Repeated short symbols. IEEE 802.11a starts its burst with ten repetitions of a short symbol; the same delay-and-correlate idea with a shorter lag gives detection and a coarse offset with a larger range.
When to use it
Use Schmidl-Cox when an OFDM receiver must find bursts and correct large offsets quickly from a preamble, as in wireless LAN and other packet systems, and when one or two symbols of training are affordable. Use the van de Beek estimator for a continuous OFDM stream without a preamble, as in broadcasting. Use the Moose estimator when the timing is already known and the offset is less than half a spacing, to get a smaller variance.
Pitfalls
- Taking the maximum of M as the timing. With the energy of the second half only, can be larger than 1 next to the plateau (the tests see ), so line L5 with the plain maximum can land just outside the starts free of interference. Use the middle of the 90 percent region in line L5, or normalize by both halves in line L3.
- A lag that is not N/2. Line L2 must compare samples apart, matching the period of the training symbol. A training symbol with data on the odd subcarriers too has no period , and never reaches its plateau.
- Reading the angle as epsilon. Line L6 must divide the angle by , not : the halves are half a symbol apart, so the phase advance is .
- Forgetting the wrap. The fractional estimate is only modulo 2. For line L6 gives , and without line L9 the receiver keeps an offset of two subcarriers, which renames every subcarrier and makes every decision wrong.
- Shifting the wrong way. In line L9, the indices are for both symbols; comparing with looks for a shift between the symbols, which does not exist.
- Both DFT windows at different positions. Line L8 must take the second window exactly samples after the first, so that the timing phase ramp is the same in both and cancels in line L9.
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)
schmidl_cox_synchronization.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/schmidl-cox-synchronization/. The authors are listed in prov/HGVMCQ.jsonl.
"""Schmidl-Cox timing and frequency synchronization for OFDM.
The first training symbol carries symbols only on the even subcarriers, so its
N time samples are two equal halves of length L = N / 2. A carrier frequency
offset epsilon (in subcarrier spacings) multiplies sample n by
e^(j 2 pi epsilon n / N), so the second half is the first half times
e^(j pi epsilon). The timing metric M(d) = |P(d)|^2 / R(d)^2 finds the symbol,
and the angle of P gives the fractional offset in (-1, 1]. A second training
symbol, with a known differential code v on the even subcarriers, gives the
even integer part 2g.
The DFT pair is the unitary one, as on the OFDM page.
"""
import cmath
import math
import random
import cbb
def training_symbols(n: int, rng: random.Random) -> tuple[list[complex], list[complex], list[complex]]:
"""The two training symbols (subcarrier values) and the code v on the even subcarriers.
The first symbol has sqrt(2) times a random 4-QAM value on each even
subcarrier and zero on the odd ones; the second has a random 4-QAM value on
every subcarrier. v[k] = X2[k] / X1[k] for even k (zero for odd k).
"""
if n % 2:
raise ValueError("N must be even")
s = 1 / math.sqrt(2)
def q() -> complex:
return complex(rng.choice((s, -s)), rng.choice((s, -s)))
x1 = [math.sqrt(2) * q() if k % 2 == 0 else 0j for k in range(n)]
x2 = [q() for _ in range(n)]
v = [x2[k] / x1[k] if k % 2 == 0 else 0j for k in range(n)]
return x1, x2, v
def timing_metric(r: list[complex], half: int) -> tuple[list[complex], list[float], list[float]]:
"""P(d), R(d) and M(d) = |P(d)|^2 / R(d)^2 for d = 0, ..., len(r) - 2 half.
P and R are updated in O(1) per step from the previous value.
"""
count = len(r) - 2 * half + 1
if count < 1:
raise ValueError("need at least N samples")
p = sum(r[m].conjugate() * r[m + half] for m in range(half))
e = sum(abs(r[m + half]) ** 2 for m in range(half))
ps, rs, ms = [], [], []
for d in range(count): # @line L1
if d > 0:
p += r[d - 1 + half].conjugate() * r[d - 1 + 2 * half] - r[d - 1].conjugate() * r[d - 1 + half] # @line L2
e += abs(r[d - 1 + 2 * half]) ** 2 - abs(r[d - 1 + half]) ** 2 # @line L3
ps.append(p)
rs.append(e)
ms.append(abs(p) ** 2 / (e * e) if e > 0 else 0.0) # @line L4
return ps, rs, ms
def timing_estimate(ms: list[float], method: str = "max") -> int:
"""The index of the largest M(d), or the middle of the 90 percent plateau around it."""
dmax = max(range(len(ms)), key=ms.__getitem__) # @line L5
if method == "max":
return dmax
if method != "plateau":
raise ValueError("method is max or plateau")
level = 0.9 * ms[dmax]
lo = dmax
while lo > 0 and ms[lo - 1] >= level:
lo -= 1
hi = dmax
while hi < len(ms) - 1 and ms[hi + 1] >= level:
hi += 1
return (lo + hi) // 2
def fractional_offset(p: complex) -> float:
"""epsilon_f = angle(P) / pi, in (-1, 1]."""
return cmath.phase(p) / math.pi # @line L6
def integer_offset(y1: list[complex], y2: list[complex], v: list[complex], gmax: int) -> int:
"""The g in [-gmax, gmax] that maximizes |sum over even k of conj(Y1[k+2g] v[k]) Y2[k+2g]|^2."""
n = len(y1)
norm = sum(abs(y2[k]) ** 2 for k in range(0, n, 2))
best, best_g = -1.0, 0
for g in range(-gmax, gmax + 1): # @line L9
acc = sum((y1[(k + 2 * g) % n] * v[k]).conjugate() * y2[(k + 2 * g) % n] for k in range(0, n, 2))
b = abs(acc) ** 2 / (2 * norm * norm) if norm > 0 else 0.0
if b > best:
best, best_g = b, g
return best_g
def synchronize(r: list[complex], n: int, ncp: int, v: list[complex], method: str = "max", gmax: int | None = None) -> tuple[int, float]:
"""Estimate the timing d and the offset epsilon from a stream that holds the two training symbols.
The first training symbol is followed directly by the second, each with a
prefix of ncp samples. The returned d is an FFT start in the first symbol.
"""
half = n // 2
if gmax is None:
gmax = n // 4
ps, _, ms = timing_metric(r[: len(r) - n - ncp], half)
d = timing_estimate(ms, method)
eps_f = fractional_offset(ps[d])
z = [r[i] * cmath.exp(-2j * math.pi * eps_f * i / n) for i in range(len(r))] # @line L7
y1 = cbb.udft(z[d:d + n]) # @line L8
y2 = cbb.udft(z[d + n + ncp:d + 2 * n + ncp])
g = integer_offset(y1, y2, v, gmax)
return d, eps_f + 2 * g # @line L10
def apply_cfo(r: list[complex], eps: float, n: int) -> list[complex]:
"""Multiply sample i by e^(j 2 pi eps i / N): a carrier offset of eps subcarrier spacings."""
return [x * cmath.exp(2j * math.pi * eps * i / n) for i, x in enumerate(r)]
test_schmidl_cox_synchronization.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/schmidl-cox-synchronization/. The authors are listed in prov/HGVMCQ.jsonl.
import cmath
import math
import random
import cbb
from schmidl_cox_synchronization import (
apply_cfo,
fractional_offset,
synchronize,
timing_estimate,
timing_metric,
training_symbols,
)
def with_prefix(xf: list[complex], ncp: int) -> list[complex]:
x = cbb.uidft(xf)
return x[len(x) - ncp:] + x
def frame(rng: random.Random, n: int, ncp: int, lead: int) -> tuple[list[complex], list[complex]]:
"""lead zero samples, the two training symbols with prefixes, one data symbol."""
x1, x2, v = training_symbols(n, rng)
data = [cbb.cn(rng, 1.0) for _ in range(n)]
s = [0j] * lead + with_prefix(x1, ncp) + with_prefix(x2, ncp) + with_prefix(data, ncp)
return s, v
def test_first_training_symbol_has_two_equal_halves() -> None:
rng = random.Random(1)
for n in (8, 64, 256):
x1, _, _ = training_symbols(n, rng)
x = cbb.uidft(x1)
assert max(abs(x[m] - x[m + n // 2]) for m in range(n // 2)) < 1e-12
assert abs(cbb.norm2(x) - n) < 1e-9
def test_recursive_metric_matches_the_direct_sums() -> None:
rng = random.Random(2)
r = [cbb.cn(rng, 1.0) for _ in range(100)]
half = 16
ps, rs, ms = timing_metric(r, half)
for d in (0, 7, 40, 68):
p = sum(r[d + m].conjugate() * r[d + m + half] for m in range(half))
e = sum(abs(r[d + m + half]) ** 2 for m in range(half))
assert abs(ps[d] - p) < 1e-9
assert abs(rs[d] - e) < 1e-9
assert abs(ms[d] - abs(p) ** 2 / e ** 2) < 1e-9
def test_plateau_without_noise() -> None:
# Channel of 3 taps, prefix 8: M(d) = 1 for the ncp - L + 2 = 7 starts d with an ISI-free window.
rng = random.Random(3)
n, ncp, lead = 64, 8, 20
s, _ = frame(rng, n, ncp, lead)
r = cbb.conv(s, [0.9, 0.4j, -0.2])
_, _, ms = timing_metric(r, n // 2)
ones = [d for d, m in enumerate(ms) if abs(m - 1) < 1e-9]
assert ones == list(range(lead + 2, lead + ncp + 1))
# R(d) is the energy of the second half only, so M(d) can pass 1 next to the plateau.
assert max(ms) > 1.01
assert lead + 2 <= timing_estimate(ms, "plateau") <= lead + ncp
def test_offsets_without_noise() -> None:
rng = random.Random(4)
n, ncp, lead = 64, 8, 20
for eps in (0.12, -0.45, 0.83, 4.3, -1.7, -6.25):
s, v = frame(rng, n, ncp, lead)
r = apply_cfo(cbb.conv(s, [0.9, 0.4j, -0.2]), eps, n)
d, e = synchronize(r, n, ncp, v, method="plateau")
assert lead + 2 <= d <= lead + ncp
assert abs(e - eps) < 1e-9
def test_fractional_part_wraps() -> None:
assert abs(fractional_offset(cmath.exp(1j * math.pi * 4.3)) - 0.3) < 1e-12
assert abs(fractional_offset(cmath.exp(-1j * math.pi * 1.7)) - 0.3) < 1e-12
def test_timing_and_offset_at_moderate_snr() -> None:
# AWGN, SNR = 10 dB per sample, N = 64, ncp = 8, epsilon = 2.12, 100 frames, seed 5.
# The ISI-free starts are lead, ..., lead + ncp, with the middle at lead + 4.
# The plateau estimate spreads by a few samples around the middle (a measurement).
rng = random.Random(5)
n, ncp, lead, n0, eps = 64, 8, 30, 0.1, 2.12
good_t = good_f = 0
total = 0
trials = 100
for _ in range(trials):
s, v = frame(rng, n, ncp, lead)
r = cbb.awgn(rng, apply_cfo(s, eps, n), n0)
d, e = synchronize(r, n, ncp, v, method="plateau", gmax=3)
good_t += lead <= d <= lead + ncp
good_f += abs(e - eps) < 0.05
total += d - lead
assert good_t >= 0.9 * trials
assert 3 <= total / trials <= 5
assert good_f == trials
def test_variance_of_the_fractional_estimate() -> None:
# At the true timing, var(eps_f) is about (1 / (pi^2 L SNR)) (1 + 1 / (2 SNR)), L = N / 2.
# N = 64, SNR = 10 dB: 3.3245e-4. 2000 trials, seed 6, ratio within 0.85 to 1.15.
rng = random.Random(6)
n, ncp, n0, eps = 64, 8, 0.1, 0.12
snr, half = 1 / n0, n // 2
expect = (1 + 1 / (2 * snr)) / (math.pi ** 2 * half * snr)
assert abs(expect - 3.3245e-4) < 1e-7
acc = 0.0
trials = 2000
x1, _, _ = training_symbols(n, rng)
x = apply_cfo(with_prefix(x1, ncp), eps, n)
for _ in range(trials):
r = cbb.awgn(rng, x, n0)
ps, _, _ = timing_metric(r[ncp:ncp + n], half)
acc += (fractional_offset(ps[0]) - eps) ** 2
ratio = acc / trials / expect
assert 0.85 < ratio < 1.15
History
Timothy Schmidl and Donald Cox at Stanford published the method in 1997, aiming at fast acquisition of bursts in wireless LANs. They built on the idea of Moose, who in 1994 had derived the maximum likelihood estimate of the offset from two repeated symbols, and moved the repetition inside a single symbol to widen the range and to get the timing from the same correlation. The same year, van de Beek, Sandell and Börjesson gave a blind method from the cyclic prefix. The delay-and-correlate structure of Schmidl-Cox is still the usual first step of OFDM packet receivers.
References
- 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 with two identical halves, the timing metric and its plateau, the fractional offset from the angle of P, and the second training symbol for the integer offset)
- P. H. Moose, A technique for orthogonal frequency division multiplexing frequency offset correction, IEEE Transactions on Communications 42(10), 1994, pages 2908 to 2914 (the maximum likelihood offset estimate from a repeated symbol, the basis of the fractional estimate)
- 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 blind alternative that uses the cyclic prefix instead of a training symbol)
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 HGVMCQ Edit this page History Report an error Markdown