Algorithm Search⌘K

Algorithmcore

Parallel code phase search

Also called FFT-based code acquisition.

Correlates a received block with a spreading code at all code phases at once: an FFT, a product with the conjugate code FFT and an inverse FFT per carrier offset. Standard in software GNSS receivers.

Time
Θ(F N log N) worst
Space
Θ(N) extra
Where
F = the number of carrier offsets; N = the block length in samples, with bounded prime factors
Properties
circular correlationdeterministicexhaustiveneeds full code period
Origin
R. D. J. van Nee, A. J. R. M. Coenen, 1991

Parallel code phase search finds the code phase and the carrier offset of a spread-spectrum signal by computing the correlation of a received block with the local code at all code phases at once. For each candidate carrier offset, it removes the carrier, takes the FFT of the block, multiplies it by the conjugate FFT of the code, and takes the inverse FFT. The result is the circular cross-correlation at every code phase. The cell with the largest magnitude gives the code phase and the offset. A serial search needs one dwell per code phase. The parallel search needs one block and O(Nlog⁡N)O(N \log N) work per carrier offset. It is the usual acquisition in software receivers for GPS and Galileo, before a delay-locked loop takes over.

In plain words

You have a copy of a long beep pattern, and you have recorded a short piece of the signal. You want to know where the pattern starts in your recording.

The slow way is to slide your copy one step at a time and score each position. The fast way uses a trick: break the recording and your copy into pure tones, combine them tone by tone, and turn the result back. This gives the scores for every position at the same time, for much less work.

The transmitter may also be a little off in frequency, because it moves. So you repeat the trick for a few guesses of the frequency error. The best score over all guesses tells you both the start and the frequency error.

The problem

The received block has NN samples, one per chip here:

x[n]=A ej2πνn/N c[(n−τ) mod N]+w[n],n=0,…,N−1,x[n] = A\, e^{j 2\pi \nu n / N}\, c[(n - \tau) \bmod N] + w[n], \qquad n = 0, \ldots, N - 1,

with a known periodic code cc of unit energy, an unknown code phase τ\tau, an unknown carrier offset ν\nu in cycles per block, and noise w[n]∼CN(0,N0)w[n] \sim \mathcal{CN}(0, N_0). The task is to compute, for each candidate offset νi\nu_i and each phase tt,

Si[t]=∑nx[n] e−j2πνin/N c[(n−t) mod N]‾,S_i[t] = \sum_{n} x[n]\, e^{-j 2\pi \nu_i n / N}\, \overline{c[(n - t) \bmod N]},

and to find the cell with the largest ∣Si[t]∣2|S_i[t]|^2. The receiver then compares that peak with a threshold, as in any signal detection problem.

The algorithm

  1. PCPS(x, c, ν_1, …, ν_F)
  2. 1C ← conj(FFT(c)) ▷ once per code
  3. 2for i ← 1 to F do
  4. 3y[n] ← x[n] · e^{-j2π ν_i n / N} for all n ▷ carrier wipe-off
  5. 4R_i ← IFFT(FFT(y) · C) ▷ R_i[t] = Σ_n y[n] conj(c[(n - t) mod N])
  6. 5t_i ← argmax_t |R_i[t]|
  7. 6return the (i, t_i) with the largest |R_i[t_i]|², and the rows R_i

L4 uses the correlation theorem: the DFT of the circular cross-correlation ρ[t]=∑ny[n] c[n−t]‾\rho[t] = \sum_n y[n]\, \overline{c[n - t]} is Y[k] C[k]‾Y[k]\, \overline{C[k]}. The FFT of the code does not depend on the received data, so it is computed once and stored. A frequency error δ=ν−νi\delta = \nu - \nu_i lowers the peak by the factor DN(δ)=∣sin⁡(πδ)/(Nsin⁡(πδ/N))∣D_N(\delta) = |\sin(\pi\delta) / (N \sin(\pi\delta/N))|, close to ∣sinc⁡(δ)∣|\operatorname{sinc}(\delta)|. This loss sets the spacing of the carrier offsets.

Example

A small search. Take the m-sequence of length N=63N = 63 with unit energy, A=1A = 1, no noise, τ=40\tau = 40 and a carrier offset of ν=0.3\nu = 0.3 cycles per block. Search the offsets −0.5-0.5, 00 and 0.50.5.

νi\nu_i ∣Ri[40]∣2\lvert R_i[40]\rvert^2 largest ∣Ri[t]∣2\lvert R_i[t]\rvert^2, t≠40t \ne 40
−0.5-0.5 0.0547 0.0446
00 0.7369 0.0308
0.50.5 0.8752 0.0156

The search returns the offset 0.50.5 and the phase 4040. The peak 0.87520.8752 is D63(0.2)2D_{63}(0.2)^2, the loss for the remaining error of 0.20.2 cycles. In the row for −0.5-0.5, the error is 0.80.8 cycles, and the peak almost disappears into the side values.

GPS numbers. A 1 ms block searched with carrier bins 500 Hz apart has a worst error of 250 Hz, which is 0.250.25 cycles per block. The loss is 20log⁡10D(0.25)=−0.9120 \log_{10} D(0.25) = -0.91 dB. With bins 1 kHz apart it would be −3.92-3.92 dB.

Work. For F=41F = 41 offsets and N=1024N = 1024 samples, the direct sums need FN2=42,991,616F N^2 = 42{,}991{,}616 complex multiply-adds. With radix-2 FFTs of (N/2)log⁡2N=5120(N/2) \log_2 N = 5120 complex multiplications each, the search needs 41⋅(2⋅5120+1024)+5120=466,94441 \cdot (2 \cdot 5120 + 1024) + 5120 = 466{,}944, about 92 times fewer.

Correctness

By the correlation theorem, the inverse DFT of Y[k] C[k]‾Y[k]\, \overline{C[k]} is the circular cross-correlation of yy and cc, and yy is the block with the carrier for νi\nu_i removed. So L4 computes Ri[t]=Si[t]R_i[t] = S_i[t] for every phase tt in one pass. The mixed-radix FFT computes the DFT by splitting the index n=ps+rn = p s + r and using WNpsk=WmskW_N^{p s k} = W_m^{s k}, which proves it correct by induction on NN. L5 and L6 then take the largest value over all cells. The loss formula follows from summing the geometric series ∑nej2πδn/N\sum_n e^{j 2\pi \delta n / N} when all chips have the same magnitude. The full proof is in the proofs folder.

Proof: Parallel code phase search computes every cell of the search grid and returns the largestfull

The input is a block x∈CNx \in \mathbb{C}^N, a code c∈CNc \in \mathbb{C}^N and carrier offsets ν1,…,νF\nu_1, \ldots, \nu_F in cycles per block. For each cell (i,t)(i, t) of the grid, the target value is the correlation

Si[t]=∑n=0N−1x[n] e−j2πνin/N c[(n−t) mod N]‾.S_i[t] = \sum_{n=0}^{N-1} x[n]\, e^{-j 2\pi \nu_i n / N}\, \overline{c[(n - t) \bmod N]}.

Write WN=e−j2π/NW_N = e^{-j 2\pi / N}, F\mathcal{F} for the DFT, (Fu)[k]=∑nu[n]WNkn(\mathcal{F} u)[k] = \sum_n u[n] W_N^{kn}, and F−1\mathcal{F}^{-1} for its inverse, (F−1U)[n]=1N∑kU[k]WN−kn(\mathcal{F}^{-1} U)[n] = \frac{1}{N} \sum_k U[k] W_N^{-kn}. All indices are taken modulo NN.

Lemma 1 (the FFT computes the DFT). For every N≥1N \ge 1, fft returns Fx\mathcal{F} x, and ifft returns F−1X\mathcal{F}^{-1} X.

Proof. By strong induction on NN. For N=1N = 1 both sides are x[0]x[0]. If NN is prime, the routine evaluates the defining sum directly. Otherwise let pp be the smallest prime factor and N=pmN = p m with m<Nm < N. Split the index as n=ps+rn = p s + r with 0≤r<p0 \le r < p and 0≤s<m0 \le s < m. Then

(Fx)[k]=∑r=0p−1WNrk∑s=0m−1x[ps+r] WNpsk=∑r=0p−1WNrk Fr[k mod m],(\mathcal{F} x)[k] = \sum_{r=0}^{p-1} W_N^{r k} \sum_{s=0}^{m-1} x[p s + r]\, W_N^{p s k} = \sum_{r=0}^{p-1} W_N^{r k}\, F_r[k \bmod m],

because WNpsk=WmskW_N^{p s k} = W_m^{s k}, which depends on kk only modulo mm. Here FrF_r is the DFT of length mm of the part x[r],x[r+p],…x[r], x[r + p], \ldots, which the recursive call computes correctly by the induction hypothesis. The routine evaluates exactly the right-hand side. For the inverse, FX‾‾[n]=∑kX[k]WN−kn\overline{\mathcal{F} \overline{X}}[n] = \sum_k X[k] W_N^{-kn}, and dividing by NN gives F−1X\mathcal{F}^{-1} X. □\square

Lemma 2 (correlation theorem). For y,c∈CNy, c \in \mathbb{C}^N, let ρ[t]=∑ny[n] c[n−t]‾\rho[t] = \sum_n y[n]\, \overline{c[n - t]}. Then Fρ=(Fy)⋅Fc‾\mathcal{F} \rho = (\mathcal{F} y) \cdot \overline{\mathcal{F} c}, so ρ=F−1((Fy)⋅Fc‾)\rho = \mathcal{F}^{-1}\big((\mathcal{F} y) \cdot \overline{\mathcal{F} c}\big).

Proof.

(Fρ)[k]=∑t∑ny[n] c[n−t]‾ WNkt=∑ny[n]WNkn∑tc[n−t] WNk(n−t)‾,(\mathcal{F} \rho)[k] = \sum_t \sum_n y[n]\, \overline{c[n - t]}\, W_N^{k t} = \sum_n y[n] W_N^{k n} \sum_t \overline{c[n - t]\, W_N^{k (n - t)}},

since WNa‾=WN−a\overline{W_N^{a}} = W_N^{-a} gives WNkt=WNkn WNk(n−t)‾W_N^{kt} = W_N^{kn}\, \overline{W_N^{k(n-t)}}. As tt runs over all residues, so does n−tn - t, so the inner sum is (Fc)[k]‾\overline{(\mathcal{F} c)[k]} for every nn. □\square

Lemma 3 (each row is a full correlation). For each ii, the row computed in L3 and L4 equals SiS_i.

Proof. L1 stores C=Fc‾C = \overline{\mathcal{F} c}, once. L3 forms y[n]=x[n]e−j2πνin/Ny[n] = x[n] e^{-j 2\pi \nu_i n / N}. L4 computes F−1((Fy)⋅C)\mathcal{F}^{-1}((\mathcal{F} y) \cdot C), which by Lemmas 1 and 2 is ρ[t]=∑ny[n] c[n−t]‾=Si[t]\rho[t] = \sum_n y[n]\, \overline{c[n - t]} = S_i[t]. □\square

Theorem. The search returns a cell (i,t)(i, t) with ∣Si[t]∣2=max⁡i′,t′∣Si′[t′]∣2|S_i[t]|^2 = \max_{i', t'} |S_{i'}[t']|^2, together with all the rows SiS_i.

Proof. By Lemma 3 the rows are the correct correlations. L5 picks in row ii a phase tit_i with the largest ∣Si[t]∣|S_i[t]|, and the running comparison keeps the row with the largest ∣Si[ti]∣2|S_i[t_i]|^2, with ties resolved by the first index. After the loop the kept cell has the largest value over all rows, and L6 returns it. □\square

Proposition (loss from a carrier error). Let x[n]=A ej2πνn/N c[(n−τ) mod N]x[n] = A\, e^{j 2\pi \nu n / N}\, c[(n - \tau) \bmod N] with ∣c[n]∣2=1/N|c[n]|^2 = 1/N for all nn, and let δ=ν−νi\delta = \nu - \nu_i. Then

∣Si[τ]∣=∣A∣ DN(δ),DN(δ)=∣sin⁡(πδ)Nsin⁡(πδ/N)∣,|S_i[\tau]| = |A|\, D_N(\delta), \qquad D_N(\delta) = \left|\frac{\sin(\pi \delta)}{N \sin(\pi \delta / N)}\right|,

with DN(0)=1D_N(0) = 1. As N→∞N \to \infty, DN(δ)→∣sin⁡(πδ)/(πδ)∣D_N(\delta) \to |\sin(\pi\delta)/(\pi\delta)|.

Proof. At t=τt = \tau, each term is A ej2πδn/N ∣c[(n−τ) mod N]∣2=(A/N) ej2πδn/NA\, e^{j 2\pi \delta n / N}\, |c[(n - \tau) \bmod N]|^2 = (A/N)\, e^{j 2\pi \delta n / N}. The sum of the geometric series is AN1−ej2πδ1−ej2πδ/N\frac{A}{N} \frac{1 - e^{j 2\pi \delta}}{1 - e^{j 2\pi \delta / N}} for δ/N∉Z\delta / N \notin \mathbb{Z}, and ∣1−ejθ∣=2∣sin⁡(θ/2)∣|1 - e^{j\theta}| = 2 |\sin(\theta/2)| gives the formula. For the limit, Nsin⁡(πδ/N)→πδN \sin(\pi\delta/N) \to \pi \delta. □\square

Cost. Let N=p1p2⋯pkN = p_1 p_2 \cdots p_k with primes p1≤⋯≤pkp_1 \le \cdots \le p_k. The FFT does O(Npj)O(N p_j) work at the level that splits off pjp_j, so its cost is O(N(p1+⋯+pk))O(N (p_1 + \cdots + p_k)), which is O(Nlog⁡N)O(N \log N) when the prime factors are bounded, for example when NN is a power of two. The search does one FFT of the code and, for each of the FF offsets, NN products in L3, two FFTs and NN products in L4, and NN comparisons in L5. With bounded prime factors the total is O(FNlog⁡N)O(F N \log N), against Θ(FN2)\Theta(F N^2) for the direct sums. It stores O(N)O(N) values per row, and O(N)O(N) in all if the rows are not kept.

Complexity

In the real RAM model, one FFT of length NN costs O(Nlog⁡N)O(N \log N) when the prime factors of NN are bounded, for example when NN is a power of two. Each offset costs two FFTs and O(N)O(N) other operations, so the search costs Θ(FNlog⁡N)\Theta(F N \log N), plus one FFT of the code. The direct correlations cost Θ(FN2)\Theta(F N^2). The extra space is Θ(N)\Theta(N) for one row; keeping all rows for a later threshold test takes Θ(FN)\Theta(F N).

Properties

  • Exhaustive. Every cell of the grid is computed, so the result does not depend on a search order, and the peak can be compared with all other cells, for example by the ratio of the highest to the second-highest peak.
  • Same statistics as a dwell. Each Si[t]S_i[t] is exactly the correlator output of a serial search at that cell, on the same block. Only the cost differs.
  • Circular. The FFT computes a circular correlation. It equals the true correlation only when the block holds whole periods of a periodic code.
  • Loss between bins. The peak loss is DN(δ)D_N(\delta) for a frequency error δ\delta, and the code phase is found to the nearest sample.

Variants and improvements

  • Parallel frequency search. Multiply the block by the code at one phase and take an FFT over the carrier; this searches all offsets at once for one phase. Borre and coauthors describe it next to the code phase search.
  • Longer integration. Add the powers ∣Ri[t]∣2|R_i[t]|^2 of several blocks (noncoherent) or the complex values (coherent) to detect weak signals. Coherent addition needs finer frequency bins.
  • Shifting in frequency. A cyclic shift of FFT(x)\mathrm{FFT}(x) by one bin is a carrier offset of one cycle per block, so integer offsets need no new FFT of the block.
  • Finer phase. Interpolate between samples around the peak, or use more samples per chip, before handing the phase to the tracking loop.

When to use it

Use the parallel code phase search when the receiver has a processor that can run FFTs and the code period fits in one block, as for the 1023-chip GPS C/A code with 1 ms blocks. It is the standard first step of software receivers. For very long codes, a serial search over a window of phases, or a hardware bank of correlators, may be cheaper. For a known preamble in a burst, the same correlation is preamble correlation detection.

Pitfalls

  • Zero padding breaks the circular model. Padding the block with zeros to reach a power of two changes the circular correlation of a periodic code into something else, and the peak shrinks. Resample to a convenient length, or use an FFT that handles the actual length.
  • Data bit changes. A data bit transition inside the block can cancel part of the peak. When a data bit lasts much longer than a block, a transition can affect at most one of two consecutive blocks, so searching both and keeping the better result avoids the loss.
  • Too coarse frequency bins. The loss grows fast with the frequency error: 0.910.91 dB at a quarter of a cycle per block, 3.923.92 dB at half a cycle.
  • Code Doppler over long integrations. Motion also stretches the code. Over long integrations the code phase drifts by more than a sample, and the peak spreads.
  • Peak at the edge. The phase is circular, so a peak at t=N−1t = N - 1 is next to the one at t=0t = 0. Interpolation and tracking must handle the wrap.

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)
parallel_code_phase_search.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parallel-code-phase-search/. The authors are listed in prov/NZHGJE.jsonl.

"""Parallel code phase search: all code phases of one block at once with FFTs.

Model of the received block, one sample per chip:
    x[n] = A e^(j 2 pi nu n / N) c[(n - tau) mod N] + w[n],  n = 0, ..., N - 1,
where nu is the carrier offset in cycles per block. For each candidate offset
nu_i, the search removes the carrier and computes the circular cross-correlation
    R_i[t] = sum over n of y[n] conj(c[(n - t) mod N]),  y[n] = x[n] e^(-j 2 pi nu_i n / N),
for all t at once as IFFT(FFT(y) * conj(FFT(c))).
"""

import cmath
import math
import random

from cbb import cn


def _smallest_factor(n: int) -> int:
    p = 2
    while p * p <= n:
        if n % p == 0:
            return p
        p += 1
    return n


def fft(x: list[complex]) -> list[complex]:
    """X[k] = sum over n of x[n] e^(-j 2 pi k n / N), by a mixed-radix decimation in time.

    The length is split by its smallest prime factor p into p interleaved parts.
    A prime length uses the direct sum.
    """
    n = len(x)
    if n == 1:
        return [complex(x[0])]
    p = _smallest_factor(n)
    if p == n:
        w = [cmath.exp(-2j * math.pi * k / n) for k in range(n)]
        return [sum(x[m] * w[(k * m) % n] for m in range(n)) for k in range(n)]
    m = n // p
    parts = [fft(x[r::p]) for r in range(p)]
    w = [cmath.exp(-2j * math.pi * k / n) for k in range(n)]
    return [sum(w[(r * k) % n] * parts[r][k % m] for r in range(p)) for k in range(n)]


def ifft(xf: list[complex]) -> list[complex]:
    """x[n] = (1/N) sum over k of X[k] e^(j 2 pi k n / N), through fft of the conjugate."""
    n = len(xf)
    return [v.conjugate() / n for v in fft([v.conjugate() for v in xf])]


def pcps(x: list[complex], c: list[complex], nus: list[float]) -> tuple[int, int, float, list[list[complex]]]:
    """Search all code phases and the carrier offsets in nus.

    Returns (i, t, peak, rows): the index of the best offset, the best code phase,
    the peak power |R_i[t]|^2, and the correlations R_i for every offset.
    """
    n = len(x)
    cf = [v.conjugate() for v in fft(c)]  # @line L1
    best = (-1, -1, -1.0)
    rows = []
    for i, nu in enumerate(nus):  # @line L2
        y = [x[k] * cmath.exp(-2j * math.pi * nu * k / n) for k in range(n)]  # @line L3
        xf = fft(y)
        r = ifft([xf[k] * cf[k] for k in range(n)])  # @line L4
        rows.append(r)
        t = max(range(n), key=lambda s: abs(r[s]))  # @line L5
        if abs(r[t]) ** 2 > best[2]:
            best = (i, t, abs(r[t]) ** 2)
    return best[0], best[1], best[2], rows  # @line L6


def received_block(rng: random.Random, c: list[complex], tau: int, nu: float, amp: float, n0: float) -> list[complex]:
    """One block with the code at phase tau, a carrier offset of nu cycles per block, and CN(0, n0) noise."""
    n = len(c)
    out = [amp * cmath.exp(2j * math.pi * nu * k / n) * c[(k - tau) % n] for k in range(n)]
    if n0 > 0:
        out = [v + cn(rng, n0) for v in out]
    return out


def dirichlet(dnu: float, n: int) -> float:
    """|sum over k < n of e^(j 2 pi dnu k / n)| / n, the amplitude loss of a carrier error of dnu cycles per block."""
    if abs(math.sin(math.pi * dnu / n)) < 1e-15:
        return 1.0
    return abs(math.sin(math.pi * dnu) / (n * math.sin(math.pi * dnu / n)))


def mseq_code(exps: list[int]) -> list[complex]:
    """One period of an m-sequence as unit-energy chips: bit 0 -> +1/sqrt(N), bit 1 -> -1/sqrt(N)."""
    n = max(exps)
    s = [1] + [0] * (n - 1)
    taps = [i for i in exps if i < n]
    while len(s) < (1 << n) - 1:
        k = len(s) - n
        bit = 0
        for i in taps:
            bit ^= s[k + i]
        s.append(bit)
    scale = 1.0 / math.sqrt(len(s))
    return [complex((1 - 2 * v) * scale) for v in s]
test_parallel_code_phase_search.py 77 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parallel-code-phase-search/. The authors are listed in prov/NZHGJE.jsonl.

import cmath
import math
import random

from cbb import cn, dft
from parallel_code_phase_search import dirichlet, fft, ifft, mseq_code, pcps, received_block

C63 = mseq_code([6, 1, 0])


def brute_force(x: list[complex], c: list[complex], nu: float) -> list[complex]:
    n = len(x)
    y = [x[k] * cmath.exp(-2j * math.pi * nu * k / n) for k in range(n)]
    return [sum(y[k] * c[(k - t) % n].conjugate() for k in range(n)) for t in range(n)]


def test_fft_matches_the_direct_dft() -> None:
    rng = random.Random(0)
    for n in (1, 2, 3, 7, 8, 12, 30, 63, 64, 105):
        x = [cn(rng, 1.0) for _ in range(n)]
        xf = fft(x)
        ref = dft(x)
        assert max(abs(a - b) for a, b in zip(xf, ref)) < 1e-9 * n
        back = ifft(xf)
        assert max(abs(a - b) for a, b in zip(back, x)) < 1e-12 * n


def test_code_is_an_m_sequence() -> None:
    assert len(C63) == 63
    for s in range(1, 63):
        r = sum(C63[k].conjugate() * C63[(k - s) % 63] for k in range(63))
        assert abs(r + 1 / 63) < 1e-12


def test_matches_brute_force_at_every_cell() -> None:
    rng = random.Random(1)
    nus = [-1.0, -0.5, 0.0, 0.5, 1.0]
    x = received_block(rng, C63, 17, 0.4, 2.0, 1.0)
    _, _, _, rows = pcps(x, C63, nus)
    for nu, row in zip(nus, rows):
        ref = brute_force(x, C63, nu)
        assert max(abs(a - b) for a, b in zip(row, ref)) < 1e-9


def test_doppler_loss_is_the_dirichlet_kernel() -> None:
    rng = random.Random(2)
    for dnu in (0.0, 0.1, 0.25, 0.5, 0.9):
        x = received_block(rng, C63, 30, dnu, 1.0, 0.0)
        _, _, _, rows = pcps(x, C63, [0.0])
        assert abs(abs(rows[0][30]) - dirichlet(dnu, 63)) < 1e-12
    # Near the sinc limit for a long block.
    assert abs(dirichlet(0.25, 10**6) - math.sin(math.pi / 4) / (math.pi / 4)) < 1e-9


def test_finds_the_phase_and_the_offset_in_noise() -> None:
    rng = random.Random(3)
    nus = [k / 2 for k in range(-4, 5)]
    for _ in range(20):
        tau = rng.randrange(63)
        i_true = rng.randrange(len(nus))
        x = received_block(rng, C63, tau, nus[i_true] + rng.uniform(-0.1, 0.1), math.sqrt(30.0), 1.0)
        i, t, peak, _ = pcps(x, C63, nus)
        assert (i, t) == (i_true, tau)
        assert peak > 10.0


def test_noiseless_peak_values() -> None:
    x = received_block(random.Random(4), C63, 5, 0.0, 1.0, 0.0)
    i, t, peak, rows = pcps(x, C63, [0.0])
    assert (i, t) == (0, 5)
    assert abs(peak - 1.0) < 1e-12
    for s in range(63):
        if s != 5:
            assert abs(rows[0][s] + 1 / 63) < 1e-12

History

R. D. J. van Nee and A. J. R. M. Coenen proposed the FFT-based acquisition of the GPS C/A code in Electronics Letters in 1991. It replaced the code phase search of serial receivers with one circular correlation per frequency bin. With software receivers, which run all signal processing on a general processor, it became the standard acquisition method, as in the receiver of Borre and coauthors.

References

  1. R. D. J. van Nee and A. J. R. M. Coenen, New fast GPS code-acquisition technique using FFT, Electronics Letters 27(2), 1991, pp. 158 to 160
  2. Kai Borre, Dennis M. Akos, Nicolaj Bertelsen, Peter Rinder and Søren Holdt Jensen, A Software-Defined GPS and Galileo Receiver, Birkhäuser, 2007, Section 6.4, p. 81 (parallel code phase search acquisition); Section 6.3, p. 78 (the parallel search over frequency)

About this page

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

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