Algorithm Search⌘K

Algorithmadvanced

Massey optimum frame synchronization

Also called Massey sync rule.

The maximum likelihood rule to find a sync word among random binary data on the AWGN channel. It subtracts a sum of ln cosh terms from the plain correlation at each candidate position.

Time
O(N L) worst
Space
O(1) extra
Where
L = the length of the sync word; N = the number of candidate positions in the window
Properties
deterministicneeds snrsoft decision
Origin
James L. Massey, 1972

Massey optimum frame synchronization finds where a known sync word starts in a received stream of binary symbols when the symbols around it are random data. The obvious rule is to correlate the received values with the sync word and pick the largest correlation. James L. Massey showed in 1972 that this rule is not optimum. A position where the received values are large in magnitude, but are data, can give a large correlation by chance. The maximum likelihood rule subtracts a correction from the correlation at each candidate position μ\mu:

M(μ)=∑i=0L−1si yμ+i−N02Es∑i=0L−1ln⁡cosh⁡2Es yμ+iN0.M(\mu) = \sum_{i=0}^{L-1} s_i\,y_{\mu+i} - \frac{N_0}{2\sqrt{E_s}}\sum_{i=0}^{L-1}\ln\cosh\frac{2\sqrt{E_s}\,y_{\mu+i}}{N_0}.

Up to a scale and a constant, the second sum is the log-likelihood that the values are random data. The rule picks the μ\mu with the largest M(μ)M(\mu). It needs the signal-to-noise ratio, but it has a simple high-SNR form, ∑i(siyμ+i−∣yμ+i∣)\sum_i (s_i y_{\mu+i} - |y_{\mu+i}|), that does not. It is a rule for frame synchronization, the soft-decision counterpart of the correlation detector.

In plain words

A receiver looks for a known short pattern inside a long stream of signs. The simple method slides the pattern along the stream and counts how well it matches at each place. But strong random data can match by chance. Massey's rule also asks, at each place, how well the received values look like random data. It rewards places that look like the pattern and also look unlike random data. The rule needs to know how strong the noise is. When the noise is weak, it becomes simple: a place only scores well if every sign agrees with the pattern.

The problem

The input is a window of NN real received values y0,…,yN−1y_0, \ldots, y_{N-1}, read cyclically, and a sync word s0,…,sL−1∈{+1,−1}s_0, \ldots, s_{L-1} \in \{+1, -1\}. The window holds the sync word at an unknown start μ∈{0,…,N−1}\mu \in \{0, \ldots, N-1\}, all values equally likely. The other N−LN - L symbols are independent and equally likely to be +1+1 or −1-1. Each received value is yi=Es di+niy_i = \sqrt{E_s}\,d_i + n_i, where did_i is the sync or data symbol and the nin_i are independent Gaussian with variance N0/2N_0/2, the real AWGN channel after a matched filter and correct symbol timing. The output is an estimate μ^\hat\mu that minimizes the probability that μ^≠μ\hat\mu \ne \mu.

The algorithm

  1. MASSEY-SYNC(y[0..N-1], s[0..L-1], Es, N0)
  2. 1best <- -infinity; bestmu <- 0
  3. 2for mu <- 0 to N - 1 do
  4. 3for i <- 0 to L - 1 do
  5. 4corr <- corr + s[i] * y[(mu + i) mod N]
  6. 5lc <- lc + ln cosh(2 sqrt(Es) y[(mu + i) mod N] / N0)
  7. 6M <- corr - N0 / (2 sqrt(Es)) * lc ▷ corr and lc start at 0 for each mu
  8. 7if M > best then
  9. 8best <- M; bestmu <- mu
  10. 9return bestmu

Line L4 is the plain correlation and line L5 adds Massey's correction. The function ln⁡cosh⁡x\ln\cosh x is computed as ∣x∣+ln⁡(1+e−2∣x∣)−ln⁡2|x| + \ln(1 + e^{-2|x|}) - \ln 2, which does not overflow for large ∣x∣|x|. Line L6 combines the two sums with the weight N0/(2Es)N_0/(2\sqrt{E_s}). Lines L7 to L9 keep the best position.

Example

Take s=(+1,+1,−1)s = (+1, +1, -1), Es=N0=1E_s = N_0 = 1, so the weight in line L6 is 12\frac12, and the window y=(0.7,0.4,−0.6,2.4,1.8,0.3,0.9,1.2)y = (0.7, 0.4, -0.6, 2.4, 1.8, 0.3, 0.9, 1.2). The sync word was sent at μ=0\mu = 0, and the large values at positions 3 and 4 are data.

μ\mu correlation ∑ln⁡cosh⁡(2y)\sum\ln\cosh(2y) M(μ)M(\mu) ∑(siyi−∣yi∣)\sum(s_iy_i - \lvert y_i\rvert) sign disagreements
0 1.71.7 1.6501.650 0.8750.875 00 0
1 −2.6-2.6 4.9914.991 −5.096-5.096 −6.0-6.0 2
2 00 7.6087.608 −3.804-3.804 −4.8-4.8 2
3 3.93.9 7.1857.185 0.3080.308 −0.6-0.6 1
4 1.21.2 4.2124.212 −0.906-0.906 −1.8-1.8 1
5 00 3.0193.019 −1.509-1.509 −2.4-2.4 1
6 1.41.4 3.6153.615 −0.407-0.407 −1.4-1.4 1
7 1.51.5 2.7722.772 0.1140.114 −0.8-0.8 1

Correlation picks μ=3\mu = 3, because the data values 2.42.4 and 1.81.8 are large. Massey's rule picks μ=0\mu = 0: the large values at μ=3\mu = 3 also have a large ln⁡cosh⁡\ln\cosh sum, so they look like data. The high-SNR form and the count of sign disagreements also pick μ=0\mu = 0.

In 2000 random trials per row, the fraction of wrong positions was (measurement):

sync word, window, Es/N0E_s/N_0 Massey correlation high-SNR form hard decisions
Barker 7, N=32N = 32, 0 dB 0.1970.197 0.3580.358 0.2150.215 0.3330.333
Barker 13, N=64N = 64, 0 dB 0.0360.036 0.1590.159 0.0390.039 0.1370.137
Barker 13, N=64N = 64, 3 dB 0.0040.004 0.0600.060 0.0040.004 0.0250.025

Correctness

Claim. M(μ)M(\mu) is a positive multiple of the log-likelihood of μ\mu plus a constant that does not depend on μ\mu. So the rule is the maximum likelihood rule, and with equally likely positions it minimizes the probability of a wrong μ^\hat\mu among all rules that see yy. This is a theorem under the model of the problem.

Key steps. Given μ\mu, the values are independent. At a sync position the density of yy is ϕ(y)e2Essy/N0\phi(y)e^{2\sqrt{E_s}sy/N_0}, and at a data position it is ϕ(y)cosh⁡(2Esy/N0)\phi(y)\cosh(2\sqrt{E_s}y/N_0), the average over d=±1d = \pm1, where ϕ\phi does not depend on μ\mu. The product over all NN positions, divided by the product of the cosh⁡\cosh terms over all positions, leaves only the sync positions, and its logarithm is 2EsN0M(μ)\frac{2\sqrt{E_s}}{N_0}M(\mu) plus a constant. As N0→0N_0 \to 0, N02aln⁡cosh⁡2ayN0→∣y∣\frac{N_0}{2a}\ln\cosh\frac{2ay}{N_0} \to |y|, which gives the high-SNR form. The full proof is in the proofs file, and the tests compare MM with a direct sum of log densities.

Proof: Massey's metric is a scaled log-likelihood of the sync word position, so the rule is maximum likelihood and minimizes the probability of a sync error for a uniform positionfull

The window holds NN real received symbols y0,…,yN−1y_0, \ldots, y_{N-1}, read cyclically. A sync word s0,…,sL−1∈{+1,−1}s_0, \ldots, s_{L-1} \in \{+1, -1\} starts at an unknown position μ∈{0,…,N−1}\mu \in \{0, \ldots, N - 1\}, uniform. The other N−LN - L positions carry independent data di∈{+1,−1}d_i \in \{+1, -1\}, each value with probability 12\frac12. The channel is yi=Es di+niy_i = \sqrt{E_s}\,d_i + n_i, where did_i is the sync or data symbol at position ii, and the nin_i are independent N(0,N0/2)\mathcal{N}(0, N_0/2). Write a=Esa = \sqrt{E_s}. Lines L3 to L6 compute

M(μ)=∑i=0L−1si yμ+i−N02a∑i=0L−1ln⁡cosh⁡2a yμ+iN0,M(\mu) = \sum_{i=0}^{L-1} s_i\,y_{\mu+i} - \frac{N_0}{2a}\sum_{i=0}^{L-1}\ln\cosh\frac{2a\,y_{\mu+i}}{N_0},

with indices mod NN, and lines L1, L2 and L7 to L9 return the μ\mu with the largest M(μ)M(\mu).

Lemma 1 (one position). For a position with a known symbol ss, the density of yy is ϕ(y) e2asy/N0\phi(y)\,e^{2asy/N_0}, and for a data position it is ϕ(y)cosh⁡(2ay/N0)\phi(y)\cosh(2ay/N_0), where ϕ(y)=(πN0)−1/2e−(y2+a2)/N0\phi(y) = (\pi N_0)^{-1/2}e^{-(y^2 + a^2)/N_0}.

Proof. The Gaussian density with mean asas and variance N0/2N_0/2 is (πN0)−1/2e−(y−as)2/N0(\pi N_0)^{-1/2}e^{-(y - as)^2/N_0}, and (y−as)2=y2+a2−2asy(y - as)^2 = y^2 + a^2 - 2asy since s2=1s^2 = 1. For a data position, average the two cases s=±1s = \pm1 with weight 12\frac12: 12(e2ay/N0+e−2ay/N0)=cosh⁡(2ay/N0)\frac12(e^{2ay/N_0} + e^{-2ay/N_0}) = \cosh(2ay/N_0). □\square

Theorem 1 (log-likelihood). For every μ\mu,

ln⁡p(y∣μ)=2aN0M(μ)+C(y),\ln p(y \mid \mu) = \frac{2a}{N_0}M(\mu) + C(y),

where C(y)C(y) does not depend on μ\mu.

Proof. Given μ\mu, the positions are independent. Let SμS_\mu be the set of the LL sync positions. By Lemma 1,

p(y∣μ)=∏i=0N−1ϕ(yi)⋅∏i∉Sμcosh⁡2ayiN0⋅∏i∈Sμe2asi−μyi/N0.p(y \mid \mu) = \prod_{i=0}^{N-1}\phi(y_i)\cdot\prod_{i \notin S_\mu}\cosh\frac{2ay_i}{N_0}\cdot\prod_{i \in S_\mu}e^{2as_{i-\mu}y_i/N_0}.

Multiply and divide by ∏i∈Sμcosh⁡(2ayi/N0)\prod_{i \in S_\mu}\cosh(2ay_i/N_0). Then the first two products become ∏iϕ(yi)cosh⁡(2ayi/N0)\prod_{i}\phi(y_i)\cosh(2ay_i/N_0) over all ii, which does not depend on μ\mu, and the rest is ∏i∈Sμe2asi−μyi/N0/cosh⁡(2ayi/N0)\prod_{i \in S_\mu}e^{2as_{i-\mu}y_i/N_0}/\cosh(2ay_i/N_0). Its logarithm is 2aN0∑isiyμ+i−∑iln⁡cosh⁡(2ayμ+i/N0)=2aN0M(μ)\frac{2a}{N_0}\sum_i s_i y_{\mu+i} - \sum_i\ln\cosh(2ay_{\mu+i}/N_0) = \frac{2a}{N_0}M(\mu). □\square

Corollary 1 (optimality). Because 2aN0>0\frac{2a}{N_0} > 0, the μ\mu that maximizes MM maximizes the likelihood. With a uniform prior on μ\mu, the maximum likelihood rule is the maximum a posteriori rule, which minimizes the probability of a wrong μ\mu among all rules that see yy (theorem: a MAP decision is optimal for the 0-1 loss).

Theorem 2 (limits). As N0→0N_0 \to 0 with EsE_s fixed, M(μ)=∑i(siyμ+i−∣yμ+i∣)+LN02aln⁡2+o(1)M(\mu) = \sum_i\bigl(s_i y_{\mu+i} - |y_{\mu+i}|\bigr) + \frac{LN_0}{2a}\ln 2 + o(1), uniformly for bounded yy. For small a ∣yi∣/N0a\,|y_i|/N_0, M(μ)=∑isiyμ+i−aN0∑iyμ+i2M(\mu) = \sum_i s_i y_{\mu+i} - \frac{a}{N_0}\sum_i y_{\mu+i}^2 plus terms of order a3yμ+i4/N03a^3 y_{\mu+i}^4/N_0^3.

Proof. ln⁡cosh⁡x=∣x∣−ln⁡2+ln⁡(1+e−2∣x∣)\ln\cosh x = |x| - \ln 2 + \ln(1 + e^{-2|x|}), and the last term goes to 00 as ∣x∣→∞|x| \to \infty. With x=2ay/N0x = 2ay/N_0, N02aln⁡cosh⁡x=∣y∣−N02aln⁡2+N02aln⁡(1+e−4a∣y∣/N0)\frac{N_0}{2a}\ln\cosh x = |y| - \frac{N_0}{2a}\ln 2 + \frac{N_0}{2a}\ln(1 + e^{-4a|y|/N_0}); the last term is at most N02aln⁡2\frac{N_0}{2a}\ln 2 and goes to zero, and the constant does not depend on μ\mu. For small xx, ln⁡cosh⁡x=x22−x412+…\ln\cosh x = \frac{x^2}{2} - \frac{x^4}{12} + \ldots, so N02aln⁡cosh⁡2ayN0=aN0y2+O(a3y4/N03)\frac{N_0}{2a}\ln\cosh\frac{2ay}{N_0} = \frac{a}{N_0}y^2 + O(a^3y^4/N_0^3). □\square

The correction term penalizes positions where the received values are large in magnitude whatever their sign. Plain correlation lacks it, so a stretch of large data values that happens to agree with ss in sign can win. At high SNR the term becomes ∑∣y∣\sum|y|, so a window scores ∑(siyi−∣yi∣)≤0\sum(s_iy_i - |y_i|) \le 0, with zero only when every sign agrees with ss. The tests check Theorem 1 against a direct sum of log densities to 10−910^{-9}, Theorem 2 at N0=10−4N_0 = 10^{-4}, and the gain over correlation by simulation.

Complexity

In the real RAM with ln⁡cosh⁡\ln\cosh as one operation, the direct rule does LL multiply-adds and LL evaluations of ln⁡cosh⁡\ln\cosh for each of the NN positions, so O(NL)O(NL) time and O(1)O(1) extra space. Since the correction at one position is a sum of a function of single values, ln⁡cosh⁡\ln\cosh can be computed once per sample and summed with a sliding window in O(N)O(N). The correlations can be computed for all positions with the FFT in O(Nlog⁡N)O(N\log N). The high-SNR form replaces ln⁡cosh⁡\ln\cosh with an absolute value, and the hard rule needs only sign comparisons.

Properties

  • Optimal for its model. No rule has a smaller error probability on the AWGN channel with random binary data and a uniform start.
  • Needs EsE_s and N0N_0. The weight and the argument of ln⁡cosh⁡\ln\cosh depend on both. A wrong estimate gives a rule between correlation and the high-SNR form.
  • High-SNR form. ∑i(siyμ+i−∣yμ+i∣)≤0\sum_i(s_iy_{\mu+i} - |y_{\mu+i}|) \le 0, with equality only when every sign agrees with ss. It needs no SNR and in the table it is close to the optimum.
  • Low-SNR form. For small Es∣y∣/N0\sqrt{E_s}|y|/N_0, M(μ)≈∑isiyμ+i−EsN0∑iyμ+i2M(\mu) \approx \sum_i s_iy_{\mu+i} - \frac{\sqrt{E_s}}{N_0}\sum_i y_{\mu+i}^2, a correlation minus an energy term.
  • Hard decisions. With only the signs of yy, a binary symmetric channel, the optimum rule counts the sign disagreements with ss and picks the fewest.

Variants and improvements

  • Periodic sync words. When the sync word repeats every frame, the metrics of several frames can be added before the decision, which lowers the error probability.
  • Sequential detection. Instead of a window with exactly one sync word, a receiver can test each position as it arrives against a threshold, as in preamble correlation detection, at the cost of false alarms.
  • Other channels and modulations. Lui and Tan derived the maximum likelihood rule and its approximations for Gaussian channels in more general settings. For M-ary signals the ln⁡cosh⁡\ln\cosh term becomes the log of the average likelihood over the data alphabet.
  • Unknown carrier phase. With noncoherent reception the correlation becomes a magnitude, and the correction changes with it.
  • Choice of the sync word. Words with low off-peak autocorrelation, such as Barker codes, reduce the chance that a shifted copy of the word partly overlapping itself wins.

When to use it

Use Massey's rule when the receiver must find a short sync word in soft-decision data at a low SNR and has an estimate of Es/N0E_s/N_0. Use the high-SNR form when the SNR is moderate or unknown, since it keeps almost all of the gain and needs only absolute values. Use plain correlation only when the sync word is long compared with the bias from the data, or when the data around the word are not random, as with a known preamble before the payload.

Pitfalls

  • Treating correlation as optimum. The example shows correlation choosing a data position. The gap grows at low SNR and for short sync words.
  • Wrong noise level. The rule is only optimum with the correct N0N_0 and EsE_s. Large errors in the estimate move it toward one of its limits.
  • Overflow in ln⁡cosh⁡\ln\cosh. cosh⁡x\cosh x overflows in double precision for ∣x∣|x| above about 710710. Use the stable form.
  • Model mismatch. The derivation needs exactly one sync word in the window and random binary data. Several sync words, coded data with structure, or a window at the edge of a burst break this.
  • Timing first. The rule works on symbol-spaced matched filter outputs, so symbol timing must be recovered before it is applied.

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)
massey_frame_synchronization.py 67 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/massey-frame-synchronization/. The authors are listed in prov/JTBTTM.jsonl.

"""Massey's optimum frame synchronization rule (1972) for binary data on the AWGN channel.

Model: a window of N received real symbols y[0..N-1], read cyclically, holds one
sync word s[0..L-1] (entries +1 or -1) that starts at an unknown position mu.
The other N - L symbols are independent, equally likely data in {+1, -1}. The
channel is y[i] = sqrt(Es) d[i] + n[i] with n[i] ~ N(0, N0/2), the real AWGN
channel with SNR Es/N0 per symbol. With mu equally likely, the maximum
likelihood (and MAP) rule picks the mu that maximizes

    M(mu) = sum_{i<L} s[i] y[mu+i] - (N0 / (2 sqrt(Es))) sum_{i<L} ln cosh(2 sqrt(Es) y[mu+i] / N0).

The first sum is the plain correlation; the second is Massey's correction.
"""

import math
from typing import Sequence


def ln_cosh(x: float) -> float:
    """ln cosh x without overflow: |x| + ln(1 + e^(-2|x|)) - ln 2."""
    ax = abs(x)
    return ax + math.log1p(math.exp(-2.0 * ax)) - math.log(2.0)


def massey_metric(y: Sequence[float], s: Sequence[int], mu: int, es: float, n0: float) -> float:
    """M(mu): the correlation minus Massey's correction term, with cyclic indices."""
    n, a = len(y), math.sqrt(es)
    corr, corr_term = 0.0, 0.0
    for i, si in enumerate(s):  # @line L3
        v = y[(mu + i) % n]
        corr += si * v  # @line L4
        corr_term += ln_cosh(2.0 * a * v / n0)  # @line L5
    return corr - n0 / (2.0 * a) * corr_term  # @line L6


def massey_sync(y: Sequence[float], s: Sequence[int], es: float, n0: float) -> int:
    """The maximum likelihood start position of the sync word in the cyclic window y."""
    best, best_mu = -math.inf, 0  # @line L1
    for mu in range(len(y)):  # @line L2
        m = massey_metric(y, s, mu, es, n0)
        if m > best:  # @line L7
            best, best_mu = m, mu  # @line L8
    return best_mu  # @line L9


def correlation_sync(y: Sequence[float], s: Sequence[int]) -> int:
    """The plain correlation rule: argmax of sum s[i] y[mu + i]."""
    n = len(y)
    scores = [sum(si * y[(mu + i) % n] for i, si in enumerate(s)) for mu in range(n)]
    return max(range(n), key=lambda mu: scores[mu])


def high_snr_sync(y: Sequence[float], s: Sequence[int]) -> int:
    """The high-SNR form of Massey's rule: argmax of sum (s[i] y[mu + i] - |y[mu + i]|)."""
    n = len(y)
    scores = [sum(si * y[(mu + i) % n] - abs(y[(mu + i) % n]) for i, si in enumerate(s)) for mu in range(n)]
    return max(range(n), key=lambda mu: scores[mu])


def hard_sync(y: Sequence[float], s: Sequence[int]) -> int:
    """The rule for hard decisions: the fewest disagreements between sign(y) and s."""
    n = len(y)
    dist = [sum(1 for i, si in enumerate(s) if (1 if y[(mu + i) % n] >= 0 else -1) != si) for mu in range(n)]
    return min(range(n), key=lambda mu: dist[mu])
test_massey_frame_synchronization.py 101 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/massey-frame-synchronization/. The authors are listed in prov/JTBTTM.jsonl.

import math
import random

from cbb import wilson
from massey_frame_synchronization import (
    correlation_sync,
    hard_sync,
    high_snr_sync,
    ln_cosh,
    massey_metric,
    massey_sync,
)

BARKER7 = [1, 1, 1, -1, -1, 1, -1]
BARKER13 = [1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1, -1, 1]


def window(rng, s, n, es, n0):
    """A cyclic window of n symbols: random +-1 data with s at a random start mu."""
    mu = rng.randrange(n)
    d = [rng.choice((1, -1)) for _ in range(n)]
    for i, si in enumerate(s):
        d[(mu + i) % n] = si
    sd = math.sqrt(n0 / 2)
    return mu, [math.sqrt(es) * x + rng.gauss(0, sd) for x in d]


def log_likelihood(y, s, mu, es, n0):
    """ln p(y | mu) from the model, term by term: Gaussian densities at the sync
    positions, and the average of the two Gaussian densities at the data positions."""
    n, a = len(y), math.sqrt(es)
    sync = {(mu + i) % n: si for i, si in enumerate(s)}
    total = 0.0
    for i, v in enumerate(y):
        if i in sync:
            total += -((v - a * sync[i]) ** 2) / n0
        else:
            total += math.log(0.5 * math.exp(-((v - a) ** 2) / n0) + 0.5 * math.exp(-((v + a) ** 2) / n0))
    return total - n * 0.5 * math.log(math.pi * n0)


def test_ln_cosh():
    for x in (-30.0, -2.5, -0.1, 0.0, 0.3, 4.0, 700.0):
        if abs(x) < 300:
            assert abs(ln_cosh(x) - math.log(math.cosh(x))) < 1e-12
    assert abs(ln_cosh(1000.0) - (1000.0 - math.log(2.0))) < 1e-9


def test_metric_is_scaled_log_likelihood():
    rng = random.Random(1)
    for _ in range(20):
        es, n0 = 1.0, rng.uniform(0.3, 3.0)
        s = BARKER7 if rng.random() < 0.5 else BARKER13
        _, y = window(rng, s, 24, es, n0)
        scale = 2 * math.sqrt(es) / n0
        ll = [log_likelihood(y, s, mu, es, n0) for mu in range(len(y))]
        m = [massey_metric(y, s, mu, es, n0) for mu in range(len(y))]
        for mu in range(1, len(y)):
            assert abs((ll[mu] - ll[0]) - scale * (m[mu] - m[0])) < 1e-9
        best = max(range(len(y)), key=lambda k: ll[k])
        assert massey_sync(y, s, es, n0) == best


def test_high_snr_limit():
    rng = random.Random(2)
    for _ in range(50):
        _, y = window(rng, BARKER13, 40, 1.0, 1.0)
        assert massey_sync(y, BARKER13, 1.0, 1e-4) == high_snr_sync(y, BARKER13)


def test_hard_rule_counts_disagreements():
    y = [0.9, -1.2, 0.1, 1.1, -0.3, -0.8, 0.7, 1.0]
    s = [1, -1, 1]
    # Start 0 gives signs (+, -, +): no disagreement.
    assert hard_sync(y, s) == 0
    # Without noise every rule finds a start whose window matches s.
    clean = [1.0, 1.0, -1.0, 1.0, 1.0, 1.0, -1.0, -1.0, 1.0, -1.0]
    w = [1, 1, -1, -1, 1]
    for rule in (hard_sync, high_snr_sync, correlation_sync):
        mu = rule(clean, w)
        assert [clean[(mu + i) % len(clean)] for i in range(len(w))] == [float(v) for v in w]


def test_massey_beats_correlation_at_zero_db():
    # Barker 7 in a window of 32 at Es/N0 = 0 dB. With 600 trials both rules make
    # more than 100 errors, so the 99.9 percent Wilson intervals are narrow.
    rng = random.Random(3)
    es, n0 = 1.0, 1.0
    trials = 600
    err_m = err_c = 0
    for _ in range(trials):
        mu, y = window(rng, BARKER7, 32, es, n0)
        err_m += massey_sync(y, BARKER7, es, n0) != mu
        err_c += correlation_sync(y, BARKER7) != mu
    assert err_m >= 100 and err_c >= 100
    lo_c, _ = wilson(err_c, trials)
    _, hi_m = wilson(err_m, trials)
    assert hi_m < lo_c

History

Before 1972, receivers found sync words by correlation, and the choice of good sync words, from the Barker codes of 1953 onward, was studied in that setting. James L. Massey published "Optimum frame synchronization" in the IEEE Transactions on Communications in 1972. He derived the maximum likelihood rule for a sync word in random binary data on the Gaussian channel, with its high-SNR form and a rule for hard decisions, and showed that correlation lacks a correction term. Robert A. Scholtz surveyed frame synchronization techniques in 1980, and G. L. Lui and H. H. Tan extended the analysis of the optimum rules for Gaussian channels in 1987.

References

  1. James L. Massey, Optimum frame synchronization, IEEE Transactions on Communications 20(2), 1972, pages 115 to 119, the maximum likelihood rule for a sync word in random binary data on the Gaussian channel, its high-SNR form and the rule for hard decisions
  2. Robert A. Scholtz, Frame synchronization techniques, IEEE Transactions on Communications 28(8), 1980, pages 1204 to 1213, the survey of frame sync rules, including Massey's rule and the choice of sync words
  3. G. L. Lui and H. H. Tan, Frame synchronization for Gaussian channels, IEEE Transactions on Communications 35(8), 1987, pages 818 to 829, the maximum likelihood frame sync rule and its approximations on Gaussian channels, and their error probabilities

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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