Algorithm Search⌘K

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.

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
Properties
carrier phase invariantdeterministicgain invariantonline
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 nn it correlates the received block yn,…,yn+L−1y_n, \ldots, y_{n+L-1} with the preamble s0,…,sL−1s_0, \ldots, s_{L-1}, c(n)=∑isˉi yn+ic(n) = \sum_i \bar s_i\,y_{n+i}. It then normalizes the squared magnitude by the energies of the preamble and of the received block, ρ(n)=∣c(n)∣2/(EsE(n))\rho(n) = |c(n)|^2/(E_sE(n)), which is between 0 and 1. It declares a frame when ρ(n)\rho(n) passes a threshold λ\lambda, and then moves to the largest ρ\rho 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 λ\lambda and LL. The phase and gain of c(n)c(n) 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 y0,y1,…y_0, y_1, \ldots at one sample per symbol, after the matched filter and symbol timing, a known preamble s0,…,sL−1s_0, \ldots, s_{L-1} with energy Es=∑i∣si∣2E_s = \sum_i |s_i|^2, and a threshold λ∈(0,1)\lambda \in (0, 1). Where a preamble starts at n0n_0, yn0+i=h si+vn0+iy_{n_0+i} = h\,s_i + v_{n_0+i} for an unknown complex gain hh that includes the carrier phase, and vv is noise. Before and after the preamble the stream is noise or data. The output is the start n^0\hat n_0, or nothing if no preamble is present, together with the gain estimate c(n^0)/Esc(\hat n_0)/E_s. 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

  1. DETECT(y[0..N-1], s[0..L-1], lambda)
  2. 1E <- sum of |y[i]|^2 for i <- 0 to L - 1
  3. 2for n <- 0 to N - L do
  4. 3if n > 0 then E <- E + |y[n+L-1]|^2 - |y[n-1]|^2 ▷ running energy
  5. 4c[n] <- sum of conj(s[i]) * y[n+i] for i <- 0 to L - 1
  6. 5rho[n] <- |c[n]|^2 / (Es * E)
  7. 6for n <- 0 to N - L do
  8. 7if rho[n] >= lambda then
  9. 8b <- the k in [n, n + L - 1] with the largest rho[k]
  10. 9return (b, rho[b], c[b] / Es)
  11. 10return none

Lines L1 to L5 compute ρ(n)\rho(n) for all starts, with a running sum for the energy. Line L7 compares with the threshold. For a target false alarm probability PfaP_{fa} per start on noise, the threshold is λ=1−Pfa1/(L−1)\lambda = 1 - P_{fa}^{1/(L-1)}. Line L8 refines the start to the peak in the next LL starts, because ρ\rho can first pass λ\lambda 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, s=(1,1,1,1,1,−1,−1,1,1,−1,1,−1,1)s = (1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1, -1, 1), with Es=13E_s = 13. The stream is two noise samples, the preamble times the gain h=0.5ej0.7h = 0.5e^{j0.7}, and one more noise sample: y=(0.3−0.2j,−0.1+0.4j,hs0,…,hs12,0.2+0.1j)y = (0.3 - 0.2j, -0.1 + 0.4j, h s_0, \ldots, h s_{12}, 0.2 + 0.1j), so there are four starts.

nn c(n)c(n) ∣c(n)∣2\lvert c(n)\rvert^2 E(n)E(n) ρ(n)\rho(n)
0 0.5824+0.5221j0.5824 + 0.5221j 0.61180.6118 3.053.05 0.01540.0154
1 −0.1+0.4j-0.1 + 0.4j 0.170.17 3.173.17 0.00410.0041
2 4.9715+4.1874j4.9715 + 4.1874j 42.2542.25 3.253.25 1.01.0
3 0.2+0.1j0.2 + 0.1j 0.050.05 3.053.05 0.00130.0013

With Pfa=10−6P_{fa} = 10^{-6} the threshold is λ=0.6838\lambda = 0.6838. The scan stops at n=2n = 2, and the detector returns (2,1.0,0.3824+0.3221j)(2, 1.0, 0.3824 + 0.3221j), which is hh. At n=1n = 1 the preamble overlaps itself shifted by one, and the Barker sidelobe at that shift is 0, so only the noise sample remains in c(1)c(1). On noise alone, λ=0.25\lambda = 0.25 gave 151 false alarms in 5000 windows against the predicted 158, with a noise variance that changed from window to window (measurement). At Es/N0=10E_s/N_0 = 10 dB with a random carrier phase, all of 100 preambles were found at the correct start, with a mean peak ρ\rho of 0.9140.914 (measurement).

Correctness

Claim. 0≤ρ(n)≤10 \le \rho(n) \le 1, and ρ(n)=1\rho(n) = 1 exactly when the block is h sh\,s for some h≠0h \ne 0, in which case c(n)/Es=hc(n)/E_s = h. Scaling yy by any nonzero complex number changes no ρ(n)\rho(n). If the samples of a block are independent circular Gaussian with any variance, ρ(n)\rho(n) has the Beta(1,L−1)(1, L - 1) distribution, so P(ρ(n)≥λ)=(1−λ)L−1P(\rho(n) \ge \lambda) = (1 - \lambda)^{L-1}. Without noise, a preamble whose neighbours within L−1L - 1 starts have ρ<1\rho < 1 is found at its correct start, with the correct gain, if no earlier start passes λ\lambda. These are theorems.

Key steps. The bound and the equality case are the Cauchy-Schwarz inequality. The invariance holds because hh multiplies c(n)c(n) by hh and E(n)E(n) by ∣h∣2|h|^2. For the distribution, ρ\rho is the squared cosine of the angle between a fixed vector and an isotropic random vector in CL\mathbb{C}^L, which is Beta(1,L−1)(1, L - 1). 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 y0,y1,…y_0, y_1, \ldots and a known preamble s=(s0,…,sL−1)s = (s_0, \ldots, s_{L-1}) with Es=∑i∣si∣2>0E_s = \sum_i|s_i|^2 > 0 and L≥2L \ge 2. For a start nn, write yn=(yn,…,yn+L−1)\mathbf{y}_n = (y_n, \ldots, y_{n+L-1}). Line L4 computes c(n)=∑isi‾ yn+i=⟨s,yn⟩c(n) = \sum_i\overline{s_i}\,y_{n+i} = \langle s, \mathbf{y}_n\rangle, lines L1 and L3 keep E(n)=∥yn∥2E(n) = \|\mathbf{y}_n\|^2, and line L5 forms ρ(n)=∣c(n)∣2/(EsE(n))\rho(n) = |c(n)|^2/(E_s E(n)), or 00 when E(n)=0E(n) = 0. Lines L6 to L10 return the largest ρ\rho among the LL starts that begin at the first nn with ρ(n)≥λ\rho(n) \ge \lambda.

Lemma 1 (running energy). After line L3 at step nn, the variable holds E(n)E(n).

Proof. By induction on nn. Line L1 sets it to E(0)E(0). If it holds E(n−1)E(n - 1), line L3 adds ∣yn+L−1∣2|y_{n+L-1}|^2 and removes ∣yn−1∣2|y_{n-1}|^2, which turns the sum over n−1,…,n+L−2n - 1, \ldots, n + L - 2 into the sum over n,…,n+L−1n, \ldots, n + L - 1. □\square

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 10−910^{-9} over 300 symbols.

Theorem 1 (range and equality). 0≤ρ(n)≤10 \le \rho(n) \le 1, and ρ(n)=1\rho(n) = 1 if and only if yn=h s\mathbf{y}_n = h\,s for some complex h≠0h \ne 0. In that case c(n)/Es=hc(n)/E_s = h.

Proof. By the Cauchy-Schwarz inequality, ∣⟨s,yn⟩∣2≤∥s∥2∥yn∥2|\langle s, \mathbf{y}_n\rangle|^2 \le \|s\|^2\|\mathbf{y}_n\|^2, with equality if and only if the two vectors are linearly dependent. If yn=hs\mathbf{y}_n = hs, then c(n)=h∥s∥2=hEsc(n) = h\|s\|^2 = hE_s. □\square

Theorem 2 (invariance). For every complex h≠0h \ne 0, replacing yy by hyhy does not change any ρ(n)\rho(n).

Proof. ∣c(n)∣2|c(n)|^2 and E(n)E(n) are both multiplied by ∣h∣2|h|^2. □\square

So the detector needs no estimate of the gain, the carrier phase or the noise level, and its threshold λ\lambda is a fixed number.

Theorem 3 (false alarm probability). If the yiy_i in a window are independent CN(0,σ2)\mathcal{CN}(0, \sigma^2), then ρ(n)\rho(n) has the Beta(1,L−1)(1, L - 1) distribution for every σ2>0\sigma^2 > 0, and

P(ρ(n)≥λ)=(1−λ)L−1,0≤λ≤1.P(\rho(n) \ge \lambda) = (1 - \lambda)^{L-1}, \qquad 0 \le \lambda \le 1.

Proof. Let UU be a unitary matrix whose first row is sH/∥s∥s^H/\|s\|. Then w=Uyn\mathbf{w} = U\mathbf{y}_n has independent CN(0,σ2)\mathcal{CN}(0, \sigma^2) entries, because the distribution of a white circular Gaussian vector does not change under a unitary map. Also c(n)=∥s∥ w1c(n) = \|s\|\,w_1 and E(n)=∥w∥2E(n) = \|\mathbf{w}\|^2, so ρ(n)=∣w1∣2/∑i∣wi∣2\rho(n) = |w_1|^2/\sum_i|w_i|^2. The values ∣wi∣2|w_i|^2 are independent and exponential with mean σ2\sigma^2, which is Gamma(1,σ2)(1, \sigma^2). For independent G1∼G_1 \sim Gamma(1)(1) and G2=∑i≥2∣wi∣2∼G_2 = \sum_{i \ge 2}|w_i|^2 \sim Gamma(L−1)(L - 1) with the same scale, G1/(G1+G2)G_1/(G_1 + G_2) is Beta(1,L−1)(1, L - 1), and the scale cancels. The tail of Beta(1,L−1)(1, L - 1) is ∫λ1(L−1)(1−r)L−2dr=(1−λ)L−1\int_\lambda^1 (L - 1)(1 - r)^{L-2}dr = (1 - \lambda)^{L-1}. □\square

Corollary 1 (threshold). For a target false alarm probability PfaP_{fa} per start, λ=1−Pfa1/(L−1)\lambda = 1 - P_{fa}^{1/(L-1)}. For a stream with KK starts of noise, the union bound gives at most KPfaK P_{fa} for the probability of any false alarm.

Theorem 4 (correct detection without noise). If yy holds hshs at start n0n_0 and no start n<n0n < n_0 has ρ(n)≥λ\rho(n) \ge \lambda, and every n≠n0n \ne n_0 in [n0−L+1,n0+L−1][n_0 - L + 1, n_0 + L - 1] has ρ(n)<1\rho(n) < 1, then the detector returns n0n_0, ρ=1\rho = 1 and the gain hh.

Proof. The scan of lines L6 and L7 stops at the first n1≤n0n_1 \le n_0 with ρ(n1)≥λ\rho(n_1) \ge \lambda, since ρ(n0)=1≥λ\rho(n_0) = 1 \ge \lambda by Theorem 1. Then n0∈[n1,n1+L−1]n_0 \in [n_1, n_1 + L - 1], and line L8 picks the maximum over that range, which is the unique start with ρ=1\rho = 1. Theorem 1 gives the gain. □\square

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 0.5ej0.70.5e^{j0.7}.

Complexity

In the real RAM, line L3 costs O(1)O(1) per start, line L4 costs LL complex multiply-adds, and line L5 costs O(1)O(1). So NN symbols cost O(NL)O(NL) operations, and the refinement adds O(L)O(L). With ±1\pm1 preambles the multiplications become additions and subtractions. With the FFT and overlap-save blocks the correlations cost O(Nlog⁡L)O(N\log L). A streaming detector keeps only the last LL symbols, so the extra space beyond the input buffer is O(1)O(1) for the energy and the correlation.

Properties

  • Constant false alarm rate on noise. The threshold sets PfaP_{fa} without knowledge of the noise level. A union bound gives at most KPfaKP_{fa} for any false alarm in KK 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, ρ\rho 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. ∣c(n)∣2|c(n)|^2 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 yn+iyˉn+i−1y_{n+i}\bar y_{n+i-1} with sisˉi−1s_i\bar s_{i-1} tolerates a frequency offset that would make c(n)c(n) 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 LL and λ\lambda 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 1/L1/L symbols, use a differential or autocorrelation detector.

Pitfalls

  • Frequency offset. For a preamble of constant amplitude, a phase that rotates by Δϕ\Delta\phi per symbol multiplies ∣c(n)∣|c(n)| at the true start by ∣sin⁡(LΔϕ/2)/(Lsin⁡(Δϕ/2))∣|\sin(L\Delta\phi/2)/(L\sin(\Delta\phi/2))|. When LΔϕL\Delta\phi approaches 2π2\pi, the peak vanishes.
  • Stopping at the first crossing. The first start with ρ≥λ\rho \ge \lambda can be a partial overlap. Refine to the peak, as line L8 does.
  • Zero energy. A block of exact zeros gives 0/00/0. The implementation returns ρ=0\rho = 0 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 λ\lambda 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.

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)
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

  1. 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
  2. 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
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.with_fft
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example