Algorithmcore
Preamble correlation detection
Also called sync word correlation, correlation frame synchronizer.
Slides a known preamble over the received symbols, normalizes the correlation by the energy of both, and declares a frame start where it passes a threshold set for a false alarm rate.
- Solves
- Frame synchronization
- Time
- O(N L) worstO(N log L) with_fft
- Space
- O(1) extra
- Where
- L = the length of the preamble; N = the number of received symbols
- Model
- Real RAM
- Properties
- carrier phase invariantdeterministicgain invariantonline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- R. H. Barker, 1953
Preamble correlation detection finds the start of a frame or burst by searching the received symbols for a known preamble or sync word. At each start it correlates the received block with the preamble , . It then normalizes the squared magnitude by the energies of the preamble and of the received block, , which is between 0 and 1. It declares a frame when passes a threshold , and then moves to the largest near that point. The magnitude removes the carrier phase, and the normalization removes the unknown gain and noise level, so on Gaussian noise the false alarm rate depends only on and . The phase and gain of give a first estimate of the channel. It is the usual rule for burst receivers, and the threshold version of cross-correlation with a matched filter for the preamble. For a sync word in random data with a known noise level, Massey's rule is the optimum.
In plain words
The sender puts a known pattern in front of each message. The receiver slides a copy of the pattern along what it receives and, at each place, measures how well the received part looks like the pattern, on a scale from 0 to 1. The scale does not depend on how loud the signal is or on its phase. When the measure is higher than a set level, the receiver says that a message starts there. It then checks a few nearby places and takes the best one. A higher set level gives fewer false starts on noise but can miss weak messages.
The problem
The input is a stream of complex symbols at one sample per symbol, after the matched filter and symbol timing, a known preamble with energy , and a threshold . Where a preamble starts at , for an unknown complex gain that includes the carrier phase, and is noise. Before and after the preamble the stream is noise or data. The output is the start , or nothing if no preamble is present, together with the gain estimate . The aims are a small probability of false alarm on noise or data and a small probability of a miss or a wrong start.
The algorithm
DETECT(y[0..N-1], s[0..L-1], lambda)- 1
E <- sum of |y[i]|^2 for i <- 0 to L - 1 - 2
for n <- 0 to N - L do - 3
if n > 0 then E <- E + |y[n+L-1]|^2 - |y[n-1]|^2 ▷ running energy - 4
c[n] <- sum of conj(s[i]) * y[n+i] for i <- 0 to L - 1 - 5
rho[n] <- |c[n]|^2 / (Es * E) - 6
for n <- 0 to N - L do - 7
if rho[n] >= lambda then - 8
b <- the k in [n, n + L - 1] with the largest rho[k] - 9
return (b, rho[b], c[b] / Es) - 10
return none
Lines L1 to L5 compute for all starts, with a running sum for the energy. Line L7 compares with the threshold. For a target false alarm probability per start on noise, the threshold is . Line L8 refines the start to the peak in the next starts, because can first pass on a sidelobe or on a partial overlap. Line L9 returns the start, the peak value and the complex gain estimate.
Example
Take the Barker code of length 13, , with . The stream is two noise samples, the preamble times the gain , and one more noise sample: , so there are four starts.
| 0 | ||||
| 1 | ||||
| 2 | ||||
| 3 |
With the threshold is . The scan stops at , and the detector returns , which is . At the preamble overlaps itself shifted by one, and the Barker sidelobe at that shift is 0, so only the noise sample remains in . On noise alone, gave 151 false alarms in 5000 windows against the predicted 158, with a noise variance that changed from window to window (measurement). At dB with a random carrier phase, all of 100 preambles were found at the correct start, with a mean peak of (measurement).
Correctness
Claim. , and exactly when the block is for some , in which case . Scaling by any nonzero complex number changes no . If the samples of a block are independent circular Gaussian with any variance, has the Beta distribution, so . Without noise, a preamble whose neighbours within starts have is found at its correct start, with the correct gain, if no earlier start passes . These are theorems.
Key steps. The bound and the equality case are the Cauchy-Schwarz inequality. The invariance holds because multiplies by and by . For the distribution, is the squared cosine of the angle between a fixed vector and an isotropic random vector in , which is Beta. The full proof is in the proofs file. The tests check the running energy against direct sums, the invariance and the false alarm rate.
Proof: The normalized correlation lies in [0, 1], equals 1 exactly on a scaled copy of the preamble, and has the false alarm probability (1 - lambda)^(L - 1) on white Gaussian noisefull
The input is a sequence of complex symbols and a known preamble with and . For a start , write . Line L4 computes , lines L1 and L3 keep , and line L5 forms , or when . Lines L6 to L10 return the largest among the starts that begin at the first with .
Lemma 1 (running energy). After line L3 at step , the variable holds .
Proof. By induction on . Line L1 sets it to . If it holds , line L3 adds and removes , which turns the sum over into the sum over .
In floating point the running sum gathers rounding error over a long stream; the implementation offers a direct recomputation to reset it, and the tests compare both to over 300 symbols.
Theorem 1 (range and equality). , and if and only if for some complex . In that case .
Proof. By the Cauchy-Schwarz inequality, , with equality if and only if the two vectors are linearly dependent. If , then .
Theorem 2 (invariance). For every complex , replacing by does not change any .
Proof. and are both multiplied by .
So the detector needs no estimate of the gain, the carrier phase or the noise level, and its threshold is a fixed number.
Theorem 3 (false alarm probability). If the in a window are independent , then has the Beta distribution for every , and
Proof. Let be a unitary matrix whose first row is . Then has independent entries, because the distribution of a white circular Gaussian vector does not change under a unitary map. Also and , so . The values are independent and exponential with mean , which is Gamma. For independent Gamma and Gamma with the same scale, is Beta, and the scale cancels. The tail of Beta is .
Corollary 1 (threshold). For a target false alarm probability per start, . For a stream with starts of noise, the union bound gives at most for the probability of any false alarm.
Theorem 4 (correct detection without noise). If holds at start and no start has , and every in has , then the detector returns , and the gain .
Proof. The scan of lines L6 and L7 stops at the first with , since by Theorem 1. Then , and line L8 picks the maximum over that range, which is the unique start with . Theorem 1 gives the gain.
The false alarm formula is a theorem for white circular Gaussian noise. On data symbols instead of noise it does not hold, because data symbols can match part of the preamble; that rate depends on the data and the preamble. The tests check Theorem 3 with 5000 windows of noise whose variance changes from window to window, and Theorem 4 with a gain of .
Complexity
In the real RAM, line L3 costs per start, line L4 costs complex multiply-adds, and line L5 costs . So symbols cost operations, and the refinement adds . With preambles the multiplications become additions and subtractions. With the FFT and overlap-save blocks the correlations cost . A streaming detector keeps only the last symbols, so the extra space beyond the input buffer is for the energy and the correlation.
Properties
- Constant false alarm rate on noise. The threshold sets without knowledge of the noise level. A union bound gives at most for any false alarm in starts.
- Phase and gain free. The detection needs no carrier recovery, and the result gives a gain and phase estimate for it.
- Data can cause false alarms. On random data symbols the Beta law does not hold, because data can match part of the preamble. The rate depends on the data alphabet and the preamble.
- Sidelobes matter. Near the true start, follows the aperiodic autocorrelation of the preamble. Sequences with low sidelobes, such as Barker codes, give a sharp peak.
- Not optimum for an embedded sync word. For a sync word in random binary data and a known SNR, Massey's rule has a lower error probability.
Variants and improvements
- Unnormalized correlation. against a threshold that scales with an estimate of the noise level, as in CFAR detection. This is cheaper but needs the noise estimate.
- Differential correlation. Correlating with tolerates a frequency offset that would make cancel over the preamble.
- Autocorrelation of a repeated preamble. Schmidl and Cox send a preamble with two equal halves and correlate the received signal with itself, which works for any frequency offset but has a flat peak.
- Other preambles. Zadoff-Chu sequences have constant amplitude and zero periodic autocorrelation sidelobes, and m-sequences have two-valued periodic autocorrelation. Both give longer preambles than the Barker codes allow.
- Fractional timing. Running the detector at several samples per symbol and interpolating the peak also gives the symbol timing.
When to use it
Use preamble correlation detection in burst receivers, packet radios and any link where frames start with a known preamble and the carrier phase, gain and noise level are unknown. Choose and from the needed false alarm and miss rates. When the preamble is short and embedded in random data at a low SNR, use Massey's rule. When the frequency offset is large compared with symbols, use a differential or autocorrelation detector.
Pitfalls
- Frequency offset. For a preamble of constant amplitude, a phase that rotates by per symbol multiplies at the true start by . When approaches , the peak vanishes.
- Stopping at the first crossing. The first start with can be a partial overlap. Refine to the peak, as line L8 does.
- Zero energy. A block of exact zeros gives . The implementation returns there.
- Drift of the running sum. In floating point, the running energy can drift over long streams. Recompute it from time to time, or use exact arithmetic on integer samples.
- Threshold from the wrong model. The formula for is for white Gaussian noise. On data or on interference, measure the false alarm rate.
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)
preamble_correlation_detection.py 72 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/preamble-correlation-detection/. The authors are listed in prov/31P2YC.jsonl.
"""Preamble correlation detection with a threshold on the normalized correlation.
The input is a stream of complex symbols y[0..] at one sample per symbol and a
known preamble s[0..L-1]. For each start n the detector forms
c(n) = sum_i conj(s[i]) y[n + i], E(n) = sum_i |y[n + i]|^2,
rho(n) = |c(n)|^2 / (E_s E(n)), E_s = sum_i |s[i]|^2.
By the Cauchy-Schwarz inequality 0 <= rho(n) <= 1, with rho(n) = 1 exactly when
y[n..n+L-1] is a complex multiple of s. rho does not change when y is scaled by
any nonzero complex number, so it needs neither the carrier phase nor the gain
nor the noise level. The detector declares the first n with rho(n) >= lambda,
then moves to the largest rho in the next L - 1 starts.
On noise alone, y i.i.d. CN(0, sigma^2), P(rho(n) >= lambda) = (1 - lambda)^(L - 1)
for each n, for every sigma.
"""
import cmath
import math
from typing import Optional, Sequence
def threshold_for_pfa(pfa: float, length: int) -> float:
"""lambda with (1 - lambda)^(L - 1) = pfa, the false alarm rate per start on noise alone."""
return 1.0 - pfa ** (1.0 / (length - 1))
def normalized_correlation(y: Sequence[complex], s: Sequence[complex]) -> list[float]:
"""rho(n) for n = 0, ..., len(y) - L, with a running sum for E(n)."""
length = len(s)
es = sum(abs(v) ** 2 for v in s)
energy = sum(abs(v) ** 2 for v in y[:length]) # @line L1
out: list[float] = []
for n in range(len(y) - length + 1): # @line L2
if n > 0:
energy += abs(y[n + length - 1]) ** 2 - abs(y[n - 1]) ** 2 # @line L3
c = sum(s[i].conjugate() * y[n + i] for i in range(length)) # @line L4
out.append(abs(c) ** 2 / (es * energy) if energy > 0 else 0.0) # @line L5
return out
def detect(
y: Sequence[complex], s: Sequence[complex], lam: float
) -> Optional[tuple[int, float, complex]]:
"""The first preamble start whose rho passes lam, refined to the peak.
Return (n, rho(n), gain) with the complex gain estimate c(n) / E_s, or None.
"""
rho = normalized_correlation(y, s)
length = len(s)
for n, r in enumerate(rho): # @line L6
if r >= lam: # @line L7
window = range(n, min(n + length, len(rho)))
best = max(window, key=lambda k: rho[k]) # @line L8
es = sum(abs(v) ** 2 for v in s)
c = sum(s[i].conjugate() * y[best + i] for i in range(length))
return best, rho[best], c / es # @line L9
return None # @line L10
def phase_of(gain: complex) -> float:
"""The carrier phase estimate arg(c(n)), in (-pi, pi]."""
return cmath.phase(gain)
def recompute_energy(y: Sequence[complex], n: int, length: int) -> float:
"""E(n) by a direct sum, to check or to reset the running sum."""
return math.fsum(abs(v) ** 2 for v in y[n:n + length])
test_preamble_correlation_detection.py 98 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/preamble-correlation-detection/. The authors are listed in prov/31P2YC.jsonl.
import cmath
import math
import random
from cbb import cn, wilson
from preamble_correlation_detection import (
detect,
normalized_correlation,
phase_of,
recompute_energy,
threshold_for_pfa,
)
BARKER13 = [complex(v) for v in (1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1, -1, 1)]
def rho_direct(y, s, n):
"""|sum conj(s) y|^2 / (E_s E(n)) with every sum taken afresh."""
c = sum(si.conjugate() * y[n + i] for i, si in enumerate(s))
es = sum(abs(v) ** 2 for v in s)
return abs(c) ** 2 / (es * recompute_energy(y, n, len(s)))
def test_threshold_formula():
lam = threshold_for_pfa(1e-6, 13)
assert abs(lam - (1 - 10 ** -0.5)) < 1e-12
assert abs((1 - lam) ** 12 - 1e-6) < 1e-18
def test_finds_clean_preamble_with_unknown_gain():
rng = random.Random(1)
gain = 0.5 * cmath.exp(0.7j)
y = [cn(rng, 1.0) for _ in range(37)] + [gain * v for v in BARKER13] + [cn(rng, 1.0) for _ in range(30)]
found = detect(y, BARKER13, threshold_for_pfa(1e-6, 13))
assert found is not None
n, r, g = found
assert n == 37
assert abs(r - 1.0) < 1e-12
assert abs(g - gain) < 1e-12
assert abs(phase_of(g) - 0.7) < 1e-12
def test_running_energy_matches_direct_sums():
rng = random.Random(2)
y = [cn(rng, 2.0) for _ in range(300)]
rho = normalized_correlation(y, BARKER13)
assert len(rho) == 300 - 13 + 1
for n, r in enumerate(rho):
assert abs(r - rho_direct(y, BARKER13, n)) < 1e-9
assert 0.0 <= r <= 1.0 + 1e-12
def test_scale_invariance():
rng = random.Random(3)
y = [cn(rng, 1.0) for _ in range(100)]
c = 3.0 * cmath.exp(1.3j)
r1 = normalized_correlation(y, BARKER13)
r2 = normalized_correlation([c * v for v in y], BARKER13)
assert max(abs(a - b) for a, b in zip(r1, r2)) < 1e-12
def test_false_alarm_rate_on_noise():
# P(rho >= lambda) = (1 - lambda)^(L - 1) for any noise level. lambda = 0.25
# and L = 13 give 0.0317, so 5000 trials expect 158 false alarms.
rng = random.Random(4)
lam, trials, hits = 0.25, 5000, 0
for _ in range(trials):
var = rng.uniform(0.01, 100.0)
y = [cn(rng, var) for _ in range(13)]
hits += normalized_correlation(y, BARKER13)[0] >= lam
p = (1 - lam) ** 12
assert trials * p >= 100
lo, hi = wilson(hits, trials)
assert lo <= p <= hi
def test_no_detection_on_noise_with_low_false_alarm_rate():
rng = random.Random(5)
y = [cn(rng, 1.0) for _ in range(1000)]
assert detect(y, BARKER13, threshold_for_pfa(1e-6, 13)) is None
def test_detects_noisy_preamble():
# Es/N0 = 10 dB per symbol and a random carrier phase. At the true start rho is
# about SNR / (1 + SNR) = 0.91, well above lambda = 0.684.
rng = random.Random(6)
lam = threshold_for_pfa(1e-6, 13)
good = 0
for _ in range(100):
start = rng.randrange(20, 60)
g = cmath.exp(1j * rng.uniform(-math.pi, math.pi))
y = [cn(rng, 0.1) for _ in range(start)] + [g * v + cn(rng, 0.1) for v in BARKER13] + [cn(rng, 0.1) for _ in range(20)]
found = detect(y, BARKER13, lam)
good += found is not None and found[0] == start
assert good >= 95
History
R. H. Barker described in 1953 how a receiver can find a synchronizing group in a binary stream by comparing it with the known pattern, and gave the binary sequences, now called Barker codes, whose off-peak agreement is at most one. Correlation with a sync word then became the usual method for frame synchronization in telemetry and data links. James L. Massey showed in 1972 that correlation is not the optimum rule for a sync word in random data, and Robert A. Scholtz surveyed the correlation detector, its error probabilities and the design of sync words in 1980. Burst and packet receivers use the energy-normalized form, which Schmidl and Cox also used for their timing metric in 1997.
References
- R. H. Barker, Group synchronizing of binary digital systems, in Communication Theory, Butterworths, 1953, the detection of a synchronizing group by agreement with a known pattern and the binary sequences with small off-peak agreement
- Robert A. Scholtz, Frame synchronization techniques, IEEE Transactions on Communications 28(8), 1980, pages 1204 to 1213, the correlation detector with a threshold, its false alarm and miss probabilities, and the choice of sync words
- James L. Massey, Optimum frame synchronization, IEEE Transactions on Communications 20(2), 1972, pages 115 to 119, the comparison of correlation with the optimum rule for a sync word in random data
- Timothy M. Schmidl and Donald C. Cox, Robust frequency and timing synchronization for OFDM, IEEE Transactions on Communications 45(12), 1997, pages 1613 to 1621, a timing metric normalized by the received energy, used to detect a preamble in bursts
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 31P2YC Edit this page History Report an error Markdown