Algorithmcore
Serial search code acquisition
Also called serial search acquisition.
Finds the code phase of a spread-spectrum signal by testing candidate phases one at a time: correlate, compare with a threshold, verify a crossing. It gives the coarse alignment before tracking.
- Solves
- Signal detection
- Time
- Θ(N q (1 + K a) / p) expectedΘ(N) per_dwell
- Space
- Θ(1) extra
- Where
- K = the penalty of a false alarm in dwells; N = the number of chips per dwell; a = the false alarm probability per dwell; p = the detection probability per dwell; q = the number of cells
- Model
- Real RAM
- Properties
- deterministicneeds verificationone correlatorworst case unbounded
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Andreas Polydoros, Charles L. Weber, 1984
A direct-sequence receiver cannot despread a signal until it knows where the code starts. Serial search code acquisition finds this code phase by brute force, one candidate at a time. The receiver has cells, the candidate phases (and, in GPS, also candidate frequencies). It correlates the received chips with the local code at one cell, compares the energy with a threshold, and moves to the next cell if the energy is below it. A crossing is checked by a longer verification step, since noise alone can cross the threshold. When a crossing passes the check, the phase is known to within a fraction of a chip, and a delay-locked loop takes over to track it. The method needs only one correlator, but its time grows with the number of cells. Parallel code phase search tests all phases at once with FFTs.
In plain words
Picture a long pattern of beeps arriving from a transmitter, and you have a copy of the pattern. You do not know where in the pattern the transmitter is, so you cannot line up your copy.
So you try one alignment and listen for a short time. If your copy matches, you hear a strong echo of agreement. If it does not, you hear only a little.
If the agreement is weak, you slide your copy by one step and try again. If it is strong, you listen longer to be sure, because noise sometimes sounds like agreement. A false alarm costs time. A miss costs more, because you must go around all the other alignments before you come back to the right one.
You stop at the first alignment that passes the longer test.
The problem
The received chips in one dwell are for , with a known code of unit energy, an unknown phase and noise . The task is to find among cells with a short mean time. Each dwell uses a new block of chips. This is a signal detection problem repeated over the cells: at each cell the receiver decides between "signal at this phase" and "noise only".
The algorithm
SERIAL-SEARCH(dwell, q, γ, verify, K, start)- 1
k ← start mod q - 2
while the time budget is not used up do - 3
z ← dwell(k) ▷ correlate a new block with the code at phase k - 4
if |z|² > γ then ▷ threshold test on the energy - 5
if verify(k) then return k ▷ a rejected crossing costs K dwells - 6
k ← (k + 1) mod q
The dwell computes . By the autocorrelation of the code, is . For an m-sequence with unit energy, and elsewhere, so the right cell gives a large mean and the others a small one. The energy test is noncoherent, since the carrier phase is unknown. With ,
where is the Marcum Q function. This gives the detection probability at the right cell and the false alarm probability at the wrong cells. With no signal, , so sets the false alarm rate.
With perfect verification, a uniformly random start, and time counted in dwells, the mean acquisition time is
Example
A small trace. Take the m-sequence (), , no noise, the true phase , the start and . The dwells at cells give , below the threshold. The dwell at cell gives , the verification accepts it, and the search returns after dwells.
Mean time. For the 1023 code phases of the GPS C/A code with , and , dwells, or s with 1 ms dwells. A perfect detector would need dwells.
From the signal level. A 1 ms dwell on a signal at dB-Hz gives (15 dB). The threshold gives .
| (dB-Hz) | , 1023 cells | , 41943 cells | ||
|---|---|---|---|---|
| 45 | 31.62 | 0.99999974 | 563.1 dwells | 23.07 s |
| 40 | 10.00 | 0.9423 | 632.1 dwells | 25.90 s |
| 38 | 6.31 | 0.7493 | 939.7 dwells | 38.51 s |
| 35 | 3.16 | 0.3688 | 2489.1 dwells | 102.04 s |
The last column uses and the search grid of Borre and coauthors: 41 Doppler bins of 500 Hz times 1023 code phases, 41943 cells, with 1 ms dwells. A weak signal costs time in two ways: it is missed more often, and each miss costs a full pass over the other cells.
Correctness
The search returns only from L5, so with a perfect verification it returns only the true cell. Each visit to the true cell is a new dwell that crosses the threshold with probability , and L6 visits the true cell once in every dwells, so the search stops with probability 1 if . For the mean time, let be the number of misses at the true cell, a geometric variable with mean . A start at position before the true cell costs wrong dwells, and each miss costs one more dwell at the true cell and wrong dwells. A wrong dwell costs on average, and its false alarms are independent of . Averaging over a uniform gives the formula. The full proof, with the Marcum Q series, is in the proofs folder.
Proof: Serial search returns the true code phase, and its mean acquisition timefull
The model has cells, numbered , and one of them, , is the true code phase. Each dwell at a cell uses a fresh block of chips
with a code of unit energy, . The dwell computes (L3) and compares with a threshold (L4). A crossing goes to a verification (L5). We assume that the verification is perfect: it accepts the true cell and rejects every other cell, and a rejection costs further dwells. Time is counted in dwells. Write for the probability that a dwell at the true cell crosses the threshold and for the probability that a dwell at a wrong cell crosses it.
Lemma 1 (law of one dwell). , where is the periodic autocorrelation of the code. The outputs of different dwells are independent.
Proof. Substitute into . The signal part is ; the substitution turns it into . The noise part is a fixed linear combination of independent variables with squared coefficients summing to , so it is . Each dwell uses its own block, so the noise parts of different dwells are independent.
For an m-sequence with unit energy, and for . So all wrong cells have the same .
Lemma 2 (detection and false alarm probabilities). If , then
where is the Marcum Q function of order 1. So , and is the same with in place of .
Proof. Write with independent real Gaussians of variance 1 and means whose squares add to . Then has the noncentral chi-square law with 2 degrees of freedom and noncentrality . This law is a Poisson mixture: with , it is the law of a central chi-square variable with degrees of freedom, that is, twice a variable. For an integer , , the probability that a Poisson process of rate 1 has fewer than points in . The event is with , that is, . Averaging over gives the series.
Lemma 3 (the result is the true cell). If , the search stops with probability 1, and when it returns a cell, that cell is .
Proof. The search returns only from L5, and only when the verification accepts the cell, which by assumption happens only at . L6 moves the cell by one modulo , so the true cell is visited once in every consecutive dwells. Each visit is a fresh dwell (Lemma 1) that crosses the threshold with probability , independently of the earlier visits. The probability that the first visits all miss is .
Lemma 4 (mean time from a fixed start). Let be the position of in the visiting order from the start cell, so . Write . Then
Proof. Let be the number of visits to that miss before the first hit. By Lemma 3 and the independence of the dwells, , so . The search makes dwells at , each of cost 1, and dwells at wrong cells. A wrong dwell costs , where is the indicator of a false alarm, with . The variables at the wrong dwells are independent of the outcomes at , hence of and . By Wald's identity the expected total cost of the wrong dwells is . So
which is the stated formula after grouping the terms with .
Theorem (mean acquisition time). If the start cell is uniform and independent of , then
Proof. With a uniform start, is uniform on , so . Averaging Lemma 4 over ,
since . The last bracket is , which gives the formula.
Checks. With and , , the mean position of a uniform cell. With , , the mean of a geometric variable.
Cost. Each dwell computes one correlation of products, so the expected number of operations is times , with space beyond the block of chips.
Complexity
In the real RAM model, each dwell costs multiply-adds (L3). The expected number of dwells is , which is , so the expected cost is , with extra space. There is no worst-case bound, because noise can cause misses at the true cell any number of times; a real receiver stops after a time budget (L2).
Properties
- One correlator. The hardware is one correlator and one comparator, the reason serial search was used in early receivers.
- Linear in the number of cells. The mean time grows with . Doubling the cells to 2046 half-chip cells raises the mean time at 45 dB-Hz from 563.1 to 1125.8 dwells.
- Misses are expensive. A miss costs about dwells, a false alarm costs . So the threshold is usually set low enough to keep high.
- False alarm penalty. At 45 dB-Hz, gives 512.0 dwells and gives 1023.1 dwells, with the same .
- Independent dwells. The formula assumes a new block for each dwell. Reusing the same block in all cells makes the outcomes dependent.
Variants and improvements
- Multiple dwell. Use a short first dwell and a longer second dwell only on crossings. The verification in L5 is a simple form of this.
- Search strategies. Start at the most likely cell and expand to both sides (a Z search or expanding window), when prior information gives a likely phase.
- Several correlators. Test several adjacent cells per dwell to divide the time by the number of correlators.
- Matched filter acquisition. A matched filter tests one new phase per chip. Polydoros and Weber treat it in Part II of their paper.
- FFT search. Parallel code phase search computes all correlations of one block in operations.
- Sequential tests. Let the dwell time depend on the data, stopping early at cells where the energy is clearly low.
When to use it
Use serial search when the hardware can afford only one correlator, or when the number of cells is small. When a processor with an FFT is available, as in software GNSS receivers, the parallel search over all code phases is faster per block. Serial search also works for long codes whose period is too large for one FFT, where the receiver searches a window of phases around a prior estimate.
Pitfalls
- Cell spacing. The autocorrelation of a rectangular chip is a triangle of width two chips. With cells one chip apart, the true phase can be half a chip from the nearest cell, and the amplitude drops to , a loss of 6.02 dB. With half-chip cells the worst loss is 2.50 dB.
- Frequency offset. A residual carrier offset rotates the chips during the dwell and lowers the peak. Long dwells need fine frequency bins.
- Data bit changes. A data bit transition inside a dwell can cancel part of the correlation.
- Wrong noise level. The threshold needs the noise level. An error in changes exponentially, so receivers estimate it from cells with no signal.
- Formula without verification. The formula assumes a verification that never accepts a wrong cell. If it can, the search can lock on a wrong phase, and the tracking loop must detect this and restart the search.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the communications pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Complex baseband tools for the communications pages.
Vectors are lists of complex numbers. Matrices are lists of rows. The
functions here are plain building blocks: small linear algebra, convolution,
the DFT as a direct sum, the Gaussian Q function, dB conversion, complex
Gaussian noise and the Wilson score interval. No page algorithm (equalizer,
estimator, synchronizer, detector, precoder, demapper or power allocation)
lives in this file.
Conventions (prompts of the communications area):
- dft is X[k] = sum_n x[n] e^(-j 2 pi k n / N) with no factor; idft has 1/N.
- udft and uidft are the unitary pair, with 1/sqrt(N) on both sides.
- qfunc(x) = 0.5 erfc(x / sqrt(2)); it never computes 1 - Phi(x).
- cn(rng, var) draws CN(0, var): real and imaginary parts are independent
with variance var / 2 each, so E|w|^2 = var.
"""
import cmath
import math
import random
# ---------------------------------------------------------------- vectors and matrices
def zeros(rows: int, cols: int | None = None) -> list:
"""A zero vector of length rows, or a rows by cols zero matrix."""
if cols is None:
return [0j] * rows
return [[0j] * cols for _ in range(rows)]
def eye(n: int) -> list[list[complex]]:
"""The n by n identity matrix."""
return [[1 + 0j if i == k else 0j for k in range(n)] for i in range(n)]
def add(a: list, b: list) -> list:
"""Elementwise a + b for two vectors or two matrices of the same shape."""
if len(a) != len(b):
raise ValueError("shapes differ")
if a and isinstance(a[0], list):
return [add(r, s) for r, s in zip(a, b)]
return [x + y for x, y in zip(a, b)]
def sub(a: list, b: list) -> list:
"""Elementwise a - b for two vectors or two matrices of the same shape."""
if len(a) != len(b):
raise ValueError("shapes differ")
if a and isinstance(a[0], list):
return [sub(r, s) for r, s in zip(a, b)]
return [x - y for x, y in zip(a, b)]
def scale(c: complex, a: list) -> list:
"""The scalar c times a vector or a matrix."""
if a and isinstance(a[0], list):
return [scale(c, r) for r in a]
return [c * x for x in a]
def matmul(a: list[list[complex]], b: list[list[complex]]) -> list[list[complex]]:
"""The matrix product a b."""
if not a or not b or len(a[0]) != len(b):
raise ValueError("inner dimensions differ")
cols = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in cols] for row in a]
def matvec(a: list[list[complex]], x: list[complex]) -> list[complex]:
"""The matrix times vector product a x."""
if a and len(a[0]) != len(x):
raise ValueError("inner dimensions differ")
return [sum(p * q for p, q in zip(row, x)) for row in a]
def herm(a: list) -> list:
"""The conjugate transpose of a matrix. A vector gives its conjugate."""
if a and isinstance(a[0], list):
return [[complex(a[i][k]).conjugate() for i in range(len(a))] for k in range(len(a[0]))]
return [complex(x).conjugate() for x in a]
def dot(x: list[complex], y: list[complex]) -> complex:
"""The inner product x^H y = sum of conj(x_i) y_i."""
if len(x) != len(y):
raise ValueError("lengths differ")
return sum(complex(p).conjugate() * q for p, q in zip(x, y))
def norm2(x: list) -> float:
"""The squared Euclidean norm sum |x_i|^2 (squared Frobenius norm for a matrix)."""
if x and isinstance(x[0], list):
return sum(norm2(r) for r in x)
return sum(abs(v) ** 2 for v in x)
# ---------------------------------------------------------------- linear systems
def _lu(a: list[list[complex]]) -> tuple[list[list[complex]], list[int], int]:
"""LU factorization with partial pivoting. Returns (lu, perm, sign)."""
n = len(a)
if any(len(r) != n for r in a):
raise ValueError("matrix is not square")
m = [[complex(v) for v in r] for r in a]
perm = list(range(n))
sign = 1
for k in range(n):
p = max(range(k, n), key=lambda i: abs(m[i][k]))
if abs(m[p][k]) == 0.0:
raise ValueError("matrix is singular")
if p != k:
m[k], m[p] = m[p], m[k]
perm[k], perm[p] = perm[p], perm[k]
sign = -sign
for i in range(k + 1, n):
f = m[i][k] / m[k][k]
m[i][k] = f
if f != 0:
rk, ri = m[k], m[i]
for c in range(k + 1, n):
ri[c] -= f * rk[c]
return m, perm, sign
def _lu_solve(lu: list[list[complex]], perm: list[int], b: list[complex]) -> list[complex]:
n = len(lu)
y = [complex(b[perm[i]]) for i in range(n)]
for i in range(n):
for c in range(i):
y[i] -= lu[i][c] * y[c]
for i in range(n - 1, -1, -1):
for c in range(i + 1, n):
y[i] -= lu[i][c] * y[c]
y[i] /= lu[i][i]
return y
def solve(a: list[list[complex]], b: list) -> list:
"""Solve a x = b by Gaussian elimination with partial pivoting.
b is a vector, or a matrix whose columns are right-hand sides.
Raises ValueError if a is singular.
"""
lu, perm, _ = _lu(a)
if b and isinstance(b[0], list):
cols = [list(c) for c in zip(*b)]
xs = [_lu_solve(lu, perm, c) for c in cols]
return [list(r) for r in zip(*xs)]
if len(b) != len(a):
raise ValueError("lengths differ")
return _lu_solve(lu, perm, b)
def inv(a: list[list[complex]]) -> list[list[complex]]:
"""The inverse of a square matrix."""
return solve(a, eye(len(a)))
def det(a: list[list[complex]]) -> complex:
"""The determinant of a square matrix (0 for a singular matrix)."""
try:
lu, _, sign = _lu(a)
except ValueError as e:
if "singular" in str(e):
return 0j
raise
d = complex(sign)
for i in range(len(lu)):
d *= lu[i][i]
return d
def cholesky(a: list[list[complex]]) -> list[list[complex]]:
"""The lower triangular L with a = L L^H, for a Hermitian positive definite a.
Raises ValueError if a is not positive definite (to rounding).
"""
n = len(a)
low = zeros(n, n)
for i in range(n):
for k in range(i + 1):
s = complex(a[i][k]) - sum(low[i][c] * low[k][c].conjugate() for c in range(k))
if i == k:
if s.real <= 0.0:
raise ValueError("matrix is not positive definite")
low[i][i] = complex(math.sqrt(s.real))
else:
low[i][k] = s / low[k][k].real
return low
# ---------------------------------------------------------------- convolution and the DFT
def conv(a: list[complex], b: list[complex]) -> list[complex]:
"""Linear convolution, of length len(a) + len(b) - 1."""
if not a or not b:
return []
out = [0j] * (len(a) + len(b) - 1)
for i, x in enumerate(a):
for k, y in enumerate(b):
out[i + k] += x * y
return out
def cconv(a: list[complex], b: list[complex], n: int | None = None) -> list[complex]:
"""Circular convolution of length n (default: the longer length).
Both inputs are padded with zeros to length n, or must not be longer than n.
"""
if n is None:
n = max(len(a), len(b))
if len(a) > n or len(b) > n:
raise ValueError("input longer than n")
out = [0j] * n
for i, x in enumerate(a):
for k, y in enumerate(b):
out[(i + k) % n] += x * y
return out
def _twiddles(n: int, sign: int) -> list[complex]:
return [cmath.exp(sign * 2j * math.pi * t / n) for t in range(n)]
def dft(x: list[complex]) -> list[complex]:
"""X[k] = sum over n of x[n] e^(-j 2 pi k n / N), as a direct O(N^2) sum."""
n = len(x)
w = _twiddles(n, -1)
return [sum(x[t] * w[(k * t) % n] for t in range(n)) for k in range(n)]
def idft(xf: list[complex]) -> list[complex]:
"""x[n] = (1/N) sum over k of X[k] e^(j 2 pi k n / N), the inverse of dft."""
n = len(xf)
w = _twiddles(n, 1)
return [sum(xf[k] * w[(k * t) % n] for k in range(n)) / n for t in range(n)]
def udft(x: list[complex]) -> list[complex]:
"""The unitary DFT: dft(x) / sqrt(N)."""
s = 1.0 / math.sqrt(len(x)) if x else 1.0
return [v * s for v in dft(x)]
def uidft(xf: list[complex]) -> list[complex]:
"""The unitary inverse DFT: sqrt(N) idft(X), the inverse of udft."""
s = math.sqrt(len(xf)) if xf else 1.0
return [v * s for v in idft(xf)]
# ---------------------------------------------------------------- Q function and dB
def qfunc(x: float) -> float:
"""Q(x) = P(Z > x) for a standard normal Z, computed as 0.5 erfc(x / sqrt(2))."""
return 0.5 * math.erfc(x / math.sqrt(2.0))
def qinv(p: float) -> float:
"""The x with Q(x) = p, for 0 < p < 1, by bisection on Q (which decreases)."""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
lo, hi = -40.0, 40.0
for _ in range(200):
mid = 0.5 * (lo + hi)
if qfunc(mid) > p:
lo = mid
else:
hi = mid
if hi - lo <= 1e-15 * max(1.0, abs(mid)):
break
return 0.5 * (lo + hi)
def db(x: float) -> float:
"""10 log10(x), for a ratio of powers or energies."""
return 10.0 * math.log10(x)
def undb(d: float) -> float:
"""10^(d / 10), the inverse of db."""
return 10.0 ** (d / 10.0)
# ---------------------------------------------------------------- noise and statistics
def cn(rng: random.Random, var: float) -> complex:
"""One sample of CN(0, var): independent real and imaginary parts of variance var / 2."""
s = math.sqrt(var / 2.0)
return complex(rng.gauss(0.0, s), rng.gauss(0.0, s))
def awgn(rng: random.Random, x: list[complex], n0: float) -> list[complex]:
"""x plus independent CN(0, n0) noise on each sample."""
return [v + cn(rng, n0) for v in x]
def wilson(k: int, n: int, z: float = 3.29) -> tuple[float, float]:
"""The Wilson score interval for k successes in n trials (z = 3.29 is about 0.999 two-sided)."""
if n <= 0 or not 0 <= k <= n:
raise ValueError("need 0 <= k <= n and n > 0")
p = k / n
z2 = z * z
den = 1.0 + z2 / n
mid = (p + z2 / (2 * n)) / den
half = z * math.sqrt(p * (1 - p) / n + z2 / (4 * n * n)) / den
return max(0.0, mid - half), min(1.0, mid + half)
serial_search_code_acquisition.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/serial-search-code-acquisition/. The authors are listed in prov/3AJ158.jsonl.
"""Serial search for the code phase of a direct-sequence signal.
Model of one dwell: a fresh block of N chips
r[n] = sqrt(Es) c[(n - tau) mod N] + w[n], w[n] ~ CN(0, N0),
with sum |c[n]|^2 = 1. The dwell at the cell k computes
z = sum over n of conj(c[(n - k) mod N]) r[n]
and compares |z|^2 with a threshold gamma. A crossing is checked by a
verification that costs K dwells when it is a false alarm. The cells are
visited in the order start, start + 1, ... modulo q.
"""
import math
import random
from typing import Callable
from cbb import cn
def correlate(r: list[complex], c: list[complex], k: int) -> complex:
"""z = sum over n of conj(c[(n - k) mod N]) r[n]: the correlator output at the code phase k."""
n = len(c)
return sum(c[(i - k) % n].conjugate() * r[i] for i in range(n))
def received_block(rng: random.Random, c: list[complex], tau: int, es: float, n0: float) -> list[complex]:
"""One block of N chips with the code at phase tau and CN(0, N0) noise per chip."""
n = len(c)
a = math.sqrt(es)
if n0 == 0:
return [a * c[(i - tau) % n] for i in range(n)]
return [a * c[(i - tau) % n] + cn(rng, n0) for i in range(n)]
def serial_search(
dwell: Callable[[int], complex],
q: int,
gamma: float,
verify: Callable[[int], bool],
k_penalty: int,
start: int = 0,
max_dwells: int = 10**7,
) -> tuple[int | None, int]:
"""Search the cells start, start + 1, ... (mod q) until a crossing passes verification.
dwell(k) returns the correlator output for a fresh block at cell k.
Returns (cell, time), where time counts dwells, plus k_penalty dwells for
each crossing that fails verification. Returns (None, time) if the
time reaches max_dwells first.
"""
k = start % q # @line L1
time = 0
while time < max_dwells: # @line L2
z = dwell(k) # @line L3
time += 1
if abs(z) ** 2 > gamma: # @line L4
if verify(k): # @line L5
return k, time
time += k_penalty
k = (k + 1) % q # @line L6
return None, time
def marcum_q1(a: float, b: float, tol: float = 1e-16) -> float:
"""Q1(a, b) = P(|X| > b) for X complex Gaussian with |E X| = a and variance 1 per real part.
Series: Q1(a, b) = sum over j >= 0 of Poisson(j; a^2/2) * P(Gamma(j + 1) > b^2/2), with
P(Gamma(m) > x) = e^(-x) sum over i < m of x^i / i!.
"""
lam = a * a / 2.0
x = b * b / 2.0
pois = math.exp(-lam)
term = math.exp(-x)
tail = term
total = pois * tail
j = 0
while True:
j += 1
pois *= lam / j
term *= x / j
tail += term
total += pois * min(tail, 1.0)
if j > lam and pois < tol:
break
return min(total, 1.0)
def dwell_probabilities(es: float, n0: float, n: int, gamma: float, off_peak: float | None = None) -> tuple[float, float]:
"""(Pd, Pfa) for one dwell with threshold gamma on |z|^2.
Under H1, z ~ CN(sqrt(Es), N0). Under H0, z ~ CN(sqrt(Es) R, N0), where R is the
off-peak periodic autocorrelation of the code (-1/N for an m-sequence by default).
With z ~ CN(mu, N0), P(|z|^2 > gamma) = Q1(sqrt(2 |mu|^2 / N0), sqrt(2 gamma / N0)).
"""
if off_peak is None:
off_peak = -1.0 / n
b = math.sqrt(2.0 * gamma / n0)
pd = marcum_q1(math.sqrt(2.0 * es / n0), b)
pfa = marcum_q1(math.sqrt(2.0 * es * off_peak * off_peak / n0), b)
return pd, pfa
def mean_acquisition_time(q: int, pd: float, pfa: float, k_penalty: int, tau_d: float = 1.0) -> float:
"""E[T] = (2 + (2 - Pd)(q - 1)(1 + K Pfa)) / (2 Pd) * tau_d, for a uniformly random true cell."""
return (2.0 + (2.0 - pd) * (q - 1) * (1.0 + k_penalty * pfa)) / (2.0 * pd) * tau_d
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_serial_search_code_acquisition.py 111 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/serial-search-code-acquisition/. The authors are listed in prov/3AJ158.jsonl.
import math
import random
from cbb import cn, wilson
from serial_search_code_acquisition import (
correlate,
dwell_probabilities,
marcum_q1,
mean_acquisition_time,
mseq_code,
received_block,
serial_search,
)
C31 = mseq_code([5, 2, 0])
def bessel_i0(x: float) -> float:
total, term, k = 1.0, 1.0, 0
while term > 1e-17 * total:
k += 1
term *= (x / (2 * k)) ** 2
total += term
return total
def marcum_by_integration(a: float, b: float) -> float:
# Simpson's rule on the Rice density x exp(-(x^2 + a^2)/2) I0(a x) from b to b + 40.
steps = 4000
h = 40.0 / steps
f = [(b + i * h) * math.exp(-((b + i * h) ** 2 + a * a) / 2) * bessel_i0(a * (b + i * h)) for i in range(steps + 1)]
return h / 3 * (f[0] + f[-1] + 4 * sum(f[1:-1:2]) + 2 * sum(f[2:-1:2]))
def test_marcum_q_check_values() -> None:
for b in (0.0, 0.5, 1.0, 3.0):
assert abs(marcum_q1(0.0, b) - math.exp(-b * b / 2)) < 1e-14
for a in (0.5, 2.0, 5.0):
assert abs(marcum_q1(a, 0.0) - 1.0) < 1e-14
for a, b in ((1.0, 1.0), (2.0, 3.0), (4.0, 2.5), (6.0, 7.0)):
assert abs(marcum_q1(a, b) - marcum_by_integration(a, b)) < 1e-9
def test_correlator_peak() -> None:
r = received_block(random.Random(0), C31, 9, 4.0, 0.0)
for k in range(31):
expected = 2.0 if k == 9 else 2.0 * (-1 / 31)
assert abs(correlate(r, C31, k) - expected) < 1e-12
def test_noiseless_search_finds_the_phase() -> None:
rng = random.Random(1)
for tau in range(31):
start = rng.randrange(31)
r = received_block(rng, C31, tau, 1.0, 0.0)
cell, time = serial_search(lambda k: correlate(r, C31, k), 31, 0.5, lambda k: k == tau, 10, start)
assert cell == tau
assert time == (tau - start) % 31 + 1
def test_dwell_probabilities_by_simulation() -> None:
rng = random.Random(2)
es, n0, gamma = 4.0, 1.0, 3.0
pd, pfa = dwell_probabilities(es, n0, 31, gamma)
trials = 3000
hits = sum(abs(correlate(received_block(rng, C31, 5, es, n0), C31, 5)) ** 2 > gamma for _ in range(trials))
alarms = sum(abs(correlate(received_block(rng, C31, 5, es, n0), C31, 17)) ** 2 > gamma for _ in range(trials))
lo, hi = wilson(hits, trials)
assert lo <= pd <= hi
lo, hi = wilson(alarms, trials)
assert lo <= pfa <= hi
def test_mean_time_by_simulation() -> None:
rng = random.Random(3)
q, es, n0, gamma, k_pen = 63, 3.0, 1.0, 2.5, 6
pd, pfa = dwell_probabilities(es, n0, q, gamma)
a = math.sqrt(es)
def run() -> int:
tau = rng.randrange(q)
# The exact law of the correlator output: CN(sqrt(Es) R, N0), R = 1 at tau and -1/q elsewhere.
def dwell(k: int) -> complex:
mean = a if k == tau else -a / q
return mean + cn(rng, n0)
cell, time = serial_search(dwell, q, gamma, lambda k: k == tau, k_pen, 0)
assert cell == tau
return time
times = [run() for _ in range(3000)]
m = sum(times) / len(times)
sd = math.sqrt(sum((t - m) ** 2 for t in times) / (len(times) - 1))
expected = mean_acquisition_time(q, pd, pfa, k_pen)
assert abs(m - expected) < 4 * sd / math.sqrt(len(times))
def test_mean_time_formula_limits() -> None:
assert mean_acquisition_time(1, 1.0, 0.0, 10) == 1.0
for q in (2, 10, 1023):
assert abs(mean_acquisition_time(q, 1.0, 0.0, 10) - (q + 1) / 2) < 1e-9
# Each false alarm adds K dwells: with Pd = 1, E[T] = 1 + (q - 1)(1 + K Pfa) / 2.
assert abs(mean_acquisition_time(11, 1.0, 0.1, 10) - (1 + 10 * 2 / 2)) < 1e-12
def test_max_dwells_stops_a_search_that_cannot_succeed() -> None:
cell, time = serial_search(lambda k: 0j, 7, 1.0, lambda k: True, 3, 0, max_dwells=50)
assert cell is None and time == 50
History
Serial search is the simplest acquisition method for spread-spectrum receivers, because it needs only one correlator. J. K. Holmes and C. C. Chen analyzed its acquisition time in 1977. In 1984 Andreas Polydoros and Charles Weber gave a unified theory of serial search acquisition in two parts, the second for receivers with a matched filter. With fast processors, FFT-based searches replaced serial search in many software GNSS receivers.
References
- A. Polydoros and C. L. Weber, A unified approach to serial search spread-spectrum code acquisition, Part I, General theory, IEEE Transactions on Communications 32(5), 1984, pp. 542 to 549 (the general theory of serial search acquisition)
- J. K. Holmes and C. C. Chen, Acquisition time performance of PN spread-spectrum systems, IEEE Transactions on Communications, 1977, The analysis of the acquisition time of a serial search
- 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.2, p. 76 (serial search acquisition over 41 frequency bins and 1023 code phases)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 3AJ158 Edit this page History Report an error Markdown